momentic 1.0.91 → 1.0.92

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,7 +1,7 @@
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]="2d9a3251-b2b9-56ca-9199-8e81915b4aed")}catch(e){}}();
4
- var $S=Object.create;var wp=Object.defineProperty;var HS=Object.getOwnPropertyDescriptor;var WS=Object.getOwnPropertyNames;var GS=Object.getPrototypeOf,VS=Object.prototype.hasOwnProperty;var vp=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var qS=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of WS(e))!VS.call(n,o)&&o!==t&&wp(n,o,{get:()=>e[o],enumerable:!(r=HS(e,o))||r.enumerable});return n};var KS=(n,e,t)=>(t=n!=null?$S(GS(n)):{},qS(e||!n||!n.__esModule?wp(t,"default",{value:n,enumerable:!0}):t,n));var gy=vp((T7,hy)=>{"use strict";hy.exports=uy;function uy(n,e,t){n instanceof RegExp&&(n=py(n,t)),e instanceof RegExp&&(e=py(e,t));var r=my(n,e,t);return r&&{start:r[0],end:r[1],pre:t.slice(0,r[0]),body:t.slice(r[0]+n.length,r[1]),post:t.slice(r[1]+e.length)}}function py(n,e){var t=e.match(n);return t?t[0]:null}uy.range=my;function my(n,e,t){var r,o,i,s,a,l=t.indexOf(n),c=t.indexOf(e,l+1),d=l;if(l>=0&&c>0){if(n===e)return[l,c];for(r=[],i=t.length;d>=0&&!a;)d==l?(r.push(d),l=t.indexOf(n,d+1)):r.length==1?a=[r.pop(),c]:(o=r.pop(),o<i&&(i=o,s=c),c=t.indexOf(e,d+1)),d=l<c&&l>=0?l:c;r.length&&(a=[i,s])}return a}});var Ty=vp((C7,xy)=>{"use strict";var fy=gy();xy.exports=TR;var yy="\0SLASH"+Math.random()+"\0",by="\0OPEN"+Math.random()+"\0",yd="\0CLOSE"+Math.random()+"\0",Sy="\0COMMA"+Math.random()+"\0",wy="\0PERIOD"+Math.random()+"\0";function fd(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function vR(n){return n.split("\\\\").join(yy).split("\\{").join(by).split("\\}").join(yd).split("\\,").join(Sy).split("\\.").join(wy)}function xR(n){return n.split(yy).join("\\").split(by).join("{").split(yd).join("}").split(Sy).join(",").split(wy).join(".")}function vy(n){if(!n)return[""];var e=[],t=fy("{","}",n);if(!t)return n.split(",");var r=t.pre,o=t.body,i=t.post,s=r.split(",");s[s.length-1]+="{"+o+"}";var a=vy(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function TR(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),Oi(vR(n),!0).map(xR)):[]}function CR(n){return"{"+n+"}"}function ER(n){return/^-?0\d/.test(n)}function AR(n,e){return n<=e}function RR(n,e){return n>=e}function Oi(n,e){var t=[],r=fy("{","}",n);if(!r)return[n];var o=r.pre,i=r.post.length?Oi(r.post,!1):[""];if(/\$$/.test(r.pre))for(var s=0;s<i.length;s++){var a=o+"{"+r.body+"}"+i[s];t.push(a)}else{var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),d=l||c,p=r.body.indexOf(",")>=0;if(!d&&!p)return r.post.match(/,.*\}/)?(n=r.pre+"{"+r.body+yd+r.post,Oi(n)):[n];var u;if(d)u=r.body.split(/\.\./);else if(u=vy(r.body),u.length===1&&(u=Oi(u[0],!1).map(CR),u.length===1))return i.map(function(U){return r.pre+u[0]+U});var m;if(d){var h=fd(u[0]),g=fd(u[1]),f=Math.max(u[0].length,u[1].length),y=u.length==3?Math.abs(fd(u[2])):1,v=AR,b=g<h;b&&(y*=-1,v=RR);var E=u.some(ER);m=[];for(var x=h;v(x,g);x+=y){var C;if(c)C=String.fromCharCode(x),C==="\\"&&(C="");else if(C=String(x),E){var L=f-C.length;if(L>0){var N=new Array(L+1).join("0");x<0?C="-"+N+C.slice(1):C=N+C}}m.push(C)}}else{m=[];for(var P=0;P<u.length;P++)m.push.apply(m,Oi(u[P],!1))}for(var P=0;P<m.length;P++)for(var s=0;s<i.length;s++){var a=o+m[P]+i[s];(!e||d||a)&&t.push(a)}}return t}});var ml=(n,e)=>{},jo=()=>{},hl=!1;try{let n=await import("@sentry/node"),{nodeProfilingIntegration:e}=await import("@sentry/profiling-node");ml=n.captureException,jo=n.profiler.stopProfiler,n.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",integrations:[e()],environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:1}),n.profiler.startProfiler(),hl=!0}catch{}import{Command as DL,Option as Kt}from"@commander-js/extra-typings";import{execSync as UL}from"child_process";import Nb from"body-parser";import EP from"cors";import AP from"dedent";import RP from"events";import _b,{Router as IP}from"express";import PP from"http";import{z as xp}from"zod";var ZL=xp.object({input:xp.string()});import{z as ze}from"zod";var tO=ze.object({srcs:ze.array(ze.string()),urls:ze.array(ze.string()),desiredSrc:ze.string().optional(),desiredUrl:ze.string().optional()}),Tp=ze.object({srcRegex:ze.string().optional(),urlRegex:ze.string().optional()}),Cp=ze.object({x:ze.number(),y:ze.number(),correlation:ze.number()}),nO=ze.object({searchImageBase64String:ze.string(),pageImageBase64String:ze.string(),id:ze.string().uuid(),timeoutMs:ze.number().max(1e4).min(0).optional()});import{z as M}from"zod";import{v4 as Oe}from"uuid";import*as w from"zod";function he(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(o){return new this.constructor({...this._def,openapi:o})};let e=n.ZodObject.prototype.extend;n.ZodObject.prototype.extend=function(...o){let i=e.apply(this,o);return i._def.extendMetadata={extends:this},delete i._def.openapi,i};let t=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...o){let i=t.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i};let r=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...o){let i=r.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i}}import{z as ce}from"zod";he(ce);var Ep=ce.object({plan:ce.string().optional(),evidence:ce.string().optional(),thoughts:ce.string(),result:ce.boolean(),relevantElements:ce.array(ce.number()).optional()}),$o=(r=>(r.CONTAINS="CONTAINS",r.STARTS_WITH="STARTS_WITH",r.EQUALS="EQUALS",r))($o||{});var YS=ce.object({type:ce.literal("ELEMENT_CONTENT"),negated:ce.boolean().optional(),operation:ce.nativeEnum($o),value:ce.string()}).openapi({ref:"ElementContentAssertion"}),XS=ce.object({type:ce.literal("ELEMENT_ATTRIBUTE"),negated:ce.boolean().optional(),operation:ce.nativeEnum($o),attr:ce.string(),value:ce.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Ho=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(Ho||{}),JS=ce.object({type:ce.literal("ELEMENT_EXISTENCE"),negated:ce.boolean().optional(),condition:ce.nativeEnum(Ho)}).openapi({ref:"ElementExistenceAssertion"}),Ap=ce.discriminatedUnion("type",[YS,XS,JS]).openapi({ref:"ManualElementAssertion"});var ZS=ce.object({type:ce.literal("CONTENT"),negated:ce.boolean().optional(),value:ce.string()}).openapi({ref:"PageContentAssertion"}),Rp=ce.discriminatedUnion("type",[ZS]).openapi({ref:"ManualPageAssertion"});import*as V from"zod";he(V);var er=(a=>(a.AI="AI",a.AI_HEALED="AI_HEALED",a.CLICK_TO_FIND="CLICK_TO_FIND",a.XY_PERCENT="XY_PERCENT",a.RECORDING="RECORDING",a.USER_CSS_SELECTOR="USER_CSS_SELECTOR",a.HEURISTIC_HEALED="HEURISTIC_HEALED",a))(er||{}),QS=V.object({mPathSelectorTokens:V.string().array(),frameSrcRegex:V.string().optional(),frameUrlRegex:V.string().optional(),indices:V.number().array()}),tr=V.object({id:V.number().int(),dataMomenticId:V.number().int().optional(),selector:V.string().optional(),generatedSelectors:V.string().array().optional(),role:V.string().optional(),name:V.string().optional(),numChildren:V.number().optional(),content:V.string().optional(),pathFromRoot:V.string().optional(),serializedForm:V.string().optional(),nodeOnlySerializedForm:V.string().optional(),serializedHtml:V.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:V.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:V.string().url().optional(),boundingBox:V.object({x:V.number().optional(),y:V.number().optional(),width:V.number(),height:V.number()}).describe("css pixel bounding box").optional(),frameCache:QS.optional(),inputDescription:V.string().optional().describe("the description that generated this cache"),targetSource:V.nativeEnum(er).optional(),targetUpdateTime:V.string().optional()}).openapi({ref:"A11yTargetWithCache"});function Ip(n){return!!(n.name||n.role||n.content||n.serializedForm||n.serializedHtml||n.screenshotUrl)}var ew=V.object({type:V.literal("description"),elementDescriptor:V.string(),a11yData:tr.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),tw=V.object({x:V.number(),y:V.number()}),nw=V.object({type:V.literal("coordinates"),pixels:tw}).openapi({ref:"CoordinatesTarget"});function kn(n){return n.type==="description"}function cn(n){return n.type==="coordinates"}var at=V.discriminatedUnion("type",[ew,nw]).openapi({ref:"ElementTarget"});function gl(n){if(!n)return!1;switch(n.type){case"description":return!!n.elementDescriptor}return!0}function lt(n){if(!n)return"";switch(n.type){case"description":return n.elementDescriptor;case"coordinates":return`x: ${n.pixels.x}, y: ${n.pixels.y}`}}import{z as te}from"zod";var Qi=te.object({url:te.string(),method:te.union([te.literal("GET"),te.literal("POST"),te.literal("PUT"),te.literal("DELETE"),te.literal("PATCH")]),headers:te.record(te.string(),te.string()).optional(),params:te.record(te.string(),te.string()).optional(),body:te.string().optional(),timeout:te.number().int().optional().describe("Max seconds to wait for the request to complete")}),Pp=te.object({url:te.string(),headers:te.record(te.string(),te.string()).optional(),query:te.string(),variables:te.record(te.string(),te.string()).optional(),timeout:te.number().int().optional().describe("Max seconds to wait for the request to complete")}),es=te.object({code:te.string(),fragment:te.boolean().optional(),environment:te.union([te.literal("NODE"),te.literal("BROWSER")]).optional().describe("default NODE"),timeout:te.number().int().max(60).optional().describe("Max seconds for the code to complete")});var He=(D=>(D.AI_EXTRACT="AI_EXTRACT",D.AI_ASSERTION="AI_ASSERTION",D.AI_WAIT="AI_WAIT",D.AUTH_LOAD="AUTH_LOAD",D.AUTH_SAVE="AUTH_SAVE",D.BLUR="BLUR",D.CAPTCHA="CAPTCHA",D.CLICK="CLICK",D.COOKIE="COOKIE",D.COPY="COPY",D.DIALOG="DIALOG",D.DRAG="DRAG",D.ELEMENT_CHECK="ELEMENT_CHECK",D.FILE_UPLOAD="FILE_UPLOAD",D.FOCUS="FOCUS",D.GO_BACK="GO_BACK",D.GO_FORWARD="GO_FORWARD",D.HOVER="HOVER",D.JAVASCRIPT="JAVASCRIPT",D.LOCAL_STORAGE="LOCAL_STORAGE",D.MOUSE_DRAG="MOUSE_DRAG",D.NAVIGATE="NAVIGATE",D.NEW_TAB="NEW_TAB",D.PAGE_CHECK="PAGE_CHECK",D.PASTE="PASTE",D.PRESS="PRESS",D.REFRESH="REFRESH",D.REQUEST="REQUEST",D.GRAPHQL_REQUEST="GRAPHQL_REQUEST",D.SCROLL_DOWN="SCROLL_DOWN",D.SCROLL_UP="SCROLL_UP",D.SCROLL_LEFT="SCROLL_LEFT",D.SCROLL_RIGHT="SCROLL_RIGHT",D.SELECT_OPTION="SELECT_OPTION",D.TAB="TAB",D.TYPE="TYPE",D.VISUAL_DIFF="VISUAL_DIFF",D.WAIT="WAIT",D.WAIT_FOR_URL="WAIT_FOR_URL",D.SUCCESS="SUCCESS",D))(He||{});he(w);var Y=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),_t=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),dn=w.object({target:tr}).optional().openapi({ref:"SingleTargetCache"}),ts=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),rw=Y.merge(ts).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),ns=_t.merge(w.object({cache:dn})),Br=Y.merge(ns.merge(w.object({target:at.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),jr=Y.merge(ns.merge(w.object({target:at.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),$r=Y.merge(ns.merge(w.object({target:at.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Hr=Y.merge(ns.merge(w.object({target:at.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),SO=w.discriminatedUnion("type",[Br,jr,$r,Hr]).openapi({ref:"AllScrollCommands"}),ow=Y.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),iw=Y.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),sw=w.discriminatedUnion("type",[w.object({type:w.literal("SUBSTRING"),url:w.string()}),w.object({type:w.literal("GLOB"),glob:w.string()}),w.object({type:w.literal("REGEX"),regex:w.string()})]),aw=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")}),lw=Y.extend({type:w.literal("WAIT_FOR_URL"),url:w.string().optional().describe("Deprecated: url or glob to wait for. New commands should use the discriminated matcher field."),matcher:sw.optional()}).merge(aw).openapi({ref:"WaitUrlCommand"}),cw=Y.merge(ts).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),dw=Y.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),pw=Y.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),uw=Y.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),mw=Y.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"}),bl=Y.merge(_t).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),hw=Y.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),gw=Y.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),fw=Y.merge(es).extend({type:w.literal("JAVASCRIPT"),envKey:w.string().optional()}).openapi({ref:"JavaScriptCommand"}),Wo=Y.merge(_t).merge(w.object({type:w.literal("CLICK"),target:at,doubleClick:w.boolean().optional(),rightClick:w.boolean().optional(),waitForUrl:w.string().optional().describe("Deprecated: wait for the click to trigger a page load or new tab that matches the provided URL or URL glob (e.g. https://google.com/**/*)."),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(),cache:dn})).openapi({ref:"ClickCommand"}),Go=Y.merge(_t).merge(w.object({type:w.literal("DRAG"),fromTarget:at,toTarget:at,hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:w.object({fromTarget:tr.optional(),toTarget:tr.optional()}).optional()})).openapi({ref:"DragCommand"}),Vo=Y.merge(_t).merge(w.object({type:w.literal("MOUSE_DRAG"),target:at.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:dn})).openapi({ref:"MouseDragCommand"}),qo=Y.merge(_t).merge(w.object({type:w.literal("HOVER"),target:at,cache:dn})).openapi({ref:"HoverCommand"}),Ko=Y.merge(_t).merge(w.object({type:w.literal("FOCUS"),target:at,cache:dn})).openapi({ref:"FocusCommand"}),Yo=Y.merge(_t).extend({type:w.literal("BLUR"),target:at.optional(),cache:dn}).openapi({ref:"BlurCommand"}),yw=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),bw=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Sw=Y.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[yw,bw]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),ww=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.number().int()})]),Xo=Y.merge(_t).extend({type:w.literal("SELECT_OPTION"),target:at,cache:dn,option:w.string().describe("option value, deprecated old field").optional(),choice:ww.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Sl=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),wl=Y.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:Sl.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),vw=wl.extend({type:w.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),xn=5,vl=600,Jo=Y.merge(_t).extend({type:w.literal("ELEMENT_CHECK"),target:at,assertion:Ap,cache:dn,timeout:w.number().int().min(0).max(vl).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),xw=Y.extend({type:w.literal("PAGE_CHECK"),assertion:Rp,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(vl).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Tw=Y.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"}),Cw=w.object({clearContent:w.boolean().optional(),forceClearContent:w.boolean().optional(),pressKeysSequentially:w.boolean().optional().describe("Deprecated: this is now the default. Please set delay to zero if you wish to achieve instant typing behavior."),delay:w.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:w.boolean().optional(),pressEnter:w.boolean().optional()}),Zo=Y.merge(_t).merge(Cw).extend({type:w.literal("TYPE"),target:at.optional(),value:w.string(),cache:dn}).openapi({ref:"TypeCommand"}),Ew=Y.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"}),Aw=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),Rw=w.object({type:w.literal("REGEX"),pattern:w.string()}),Iw=w.object({type:w.literal("INDEX"),index:w.number()}),Pw=w.discriminatedUnion("type",[Aw,Rw,Iw]),Lw=Y.merge(ts).merge(w.object({type:w.literal("TAB"),url:w.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:Pw.optional()})).openapi({ref:"TabCommand"}),Ow=Y.merge(ts).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),kw=Y.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),Mw=Y.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),Nw=Y.extend({type:w.literal("REQUEST")}).merge(Qi).openapi({ref:"RequestCommand"}),_w=Y.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(Pp).openapi({ref:"GraphQLRequestCommand"}),Fw=Y.merge(w.object({type:w.literal("SUCCESS"),condition:wl.optional()})).openapi({ref:"SuccessCommand"}),Dw=Y.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Uw=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),Qo=Y.merge(_t).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:at.optional(),screenshot:Uw.optional(),cache:dn})).openapi({ref:"VisualDiffCommand"}),Lp=w.discriminatedUnion("type",[Wo,Zo,Ew,Xo,rw,jr,Br,wl,qo,iw,Fw]),zw=w.discriminatedUnion("type",[vw,Tw,mw,uw,bl,kw,hw,ow,Go,Jo,Sw,dw,pw,fw,Mw,Vo,Ow,xw,gw,cw,Nw,_w,$r,Hr,Lw,Qo,Ko,Yo,lw]),rs=w.discriminatedUnion("type",[...Lp.options,...zw.options]).openapi({ref:"Command"}),os=w.discriminatedUnion("type",[...Lp.options,Dw]);function Mn(n){let e;switch(n){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:Oe(),type:n};break;case"AUTH_LOAD":{e={id:Oe(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:Oe(),type:n,goal:""};break;case"DIALOG":e={id:Oe(),type:n,action:"DISMISS"};break;case"DRAG":e={id:Oe(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Oe(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Oe(),type:n,url:""};break;case"WAIT":e={id:Oe(),type:n,delay:1};break;case"BLUR":e={id:Oe(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Oe(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Oe(),type:n,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Oe(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Oe(),type:n,url:""};break;case"REQUEST":e={id:Oe(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Oe(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Oe(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:Oe(),type:n,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Oe(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:Oe(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Oe(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Oe(),type:n,assertion:{type:"CONTENT",value:""}};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}import{z as Bw}from"zod";var CO=Bw.discriminatedUnion("type",[Yo,bl,Wo,Go,Ko,qo,Vo,Br,jr,$r,Hr,Xo,Zo,Qo,Jo]);function Op(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as jw}from"zod";var bt={type:!0,cache:!0},nr=jw.discriminatedUnion("type",[Yo.pick(bt),Wo.pick(bt),Go.pick(bt),Jo.pick(bt),Ko.pick(bt),qo.pick(bt),Vo.pick(bt),Br.pick(bt),jr.pick(bt),$r.pick(bt),Hr.pick(bt),Xo.pick(bt),Zo.pick(bt),Qo.pick(bt)]),xl=Object.values(He).filter(n=>nr.options.some(e=>e.shape.type.safeParse(n).success));rs.options.forEach(n=>{if("target"in n.shape&&!xl.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as Cl}from"zod";import{z as Tl}from"zod";import{z as Wr}from"zod";var St=Wr.object({index:Wr.number().optional().describe("global index within a test (in-order traversal)"),id:Wr.string(),skipped:Wr.boolean().optional(),envKey:Wr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Wr.boolean().optional()});he(Tl);var wt=St.extend({type:Tl.literal("PRESET_ACTION"),command:rs,skipped:Tl.boolean().optional()}).openapi({ref:"PresetAction"});he(Cl);var rr=St.extend({type:Cl.literal("AI_ACTION"),text:Cl.string(),steps:wt.array().optional()}).openapi({ref:"AIAction"});import{z as re}from"zod";var $w=re.object({cacheKey:re.string(),cacheExpiryMs:re.number()}),El=St.extend({id:re.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:re.record(re.string()).optional(),cacheConfig:$w.optional()}),Tn=El.extend({type:re.literal("MODULE"),moduleId:re.string().uuid()}),Hw=re.union([Tn.pick({type:!0,moduleId:!0}),re.record(re.unknown())]),Ww=re.object({type:re.literal("URL_REGEX"),regex:re.string()}),Gw=re.object({type:re.literal("PAGE_CHECK"),substring:re.string()}),Al=re.object({cacheInvalidation:re.discriminatedUnion("type",[Gw,Ww]).optional()}),vt=re.object({moduleId:re.string().uuid(),name:re.string(),description:re.string().nullish(),enabled:re.boolean().nullish(),parameters:re.string().array().nullish(),defaultParameters:re.record(re.string(),re.string()).nullish(),defaultCacheKey:re.string().nullish(),defaultCacheTtl:re.number().nullish(),defaultCacheAllInvocations:re.boolean().nullish(),autoAuth:re.boolean().nullish(),advanced:Al.nullish()});import{z as tt}from"zod";import{z as Rl}from"zod";he(Rl);var Gr=St.extend({type:Rl.literal("AI_ACTION_DYNAMIC"),text:Rl.string()}).openapi({ref:"AIActionDynamic"});import{z as kp}from"zod";var Il=St.extend({type:kp.literal("CONDITIONAL"),skipped:kp.boolean().optional()});import{z as is}from"zod";var Vw=is.object({type:is.literal("url"),url:is.string()}),ei=St.extend({type:is.literal("IFRAME"),identifier:Vw});import{z as Ft}from"zod";var Pl=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(Pl||{});var qw=Ft.discriminatedUnion("type",[Ft.object({type:Ft.literal("NAVIGATE_URL"),url:Ft.string().url()}),Ft.object({type:Ft.literal("GO_TO_SECTION_START")})]),Kw=Ft.object({trigger:Ft.nativeEnum(Pl).optional(),attempts:Ft.number().int().optional(),restartBehavior:qw}),ti=St.extend({type:Ft.literal("SECTION"),description:Ft.string().describe("user provided goal of what the section should accomplish"),plan:Ft.string().array().optional(),autohealingConfig:Kw.optional()});var Mp=vt.merge(El).extend({type:tt.literal("RESOLVED_MODULE"),steps:tt.lazy(()=>Ae.array())}),Ll=vt.extend({steps:tt.lazy(()=>Ae.array())}),Ol=ei.extend({steps:tt.lazy(()=>We.array())}),Yw=ei.extend({steps:tt.lazy(()=>Ae.array())}),kl=ti.extend({steps:tt.lazy(()=>We.array())}),Xw=ti.extend({steps:tt.lazy(()=>Ae.array())}),or=Il.extend({blocks:tt.object({assertion:tt.lazy(()=>wt),steps:tt.lazy(()=>We.array())}).array(),elseSteps:tt.lazy(()=>We.array().optional())}),Jw=Il.extend({blocks:tt.object({assertion:tt.lazy(()=>wt),steps:tt.lazy(()=>Ae.array())}).array(),elseSteps:tt.lazy(()=>Ae.array().optional())}),We=tt.discriminatedUnion("type",[wt,rr,Gr,Tn,or,Ol,kl]),Ae=tt.discriminatedUnion("type",[wt,rr,Gr,Mp,Jw,Yw,Xw]);import{z as Dt}from"zod";var Zw=Dt.object({steps:We.array(),beforeSteps:We.array().nullish(),afterSteps:We.array().nullish()}),Vr=Dt.object({steps:Ae.array(),beforeSteps:Ae.array().nullish(),afterSteps:Ae.array().nullish()}),ir=Dt.object({steps:Dt.record(Dt.string(),Dt.unknown()).array(),beforeSteps:Dt.record(Dt.string(),Dt.unknown()).array().nullish(),afterSteps:Dt.record(Dt.string(),Dt.unknown()).array().nullish()});var mt="1.0.19";import{z as sr}from"zod";var Ml=sr.object({key:sr.string(),testId:sr.string().optional(),moduleId:sr.string().optional(),organizationId:sr.string(),value:nr}),Np=sr.record(sr.string(),Ml);var _p=M.object({phrase:M.string()}),Nl=M.object({thoughts:M.string().optional(),result:M.union([M.literal("NOT_FOUND"),M.string(),M.number(),M.array(M.unknown()),M.record(M.unknown(),M.unknown()),M.unknown()])}),TM=M.object({text:M.string()}),Fp=M.object({thoughts:M.string(),id:M.number().int()}),Qw=M.discriminatedUnion("op",[M.object({op:M.literal("replace"),path:M.string(),value:M.string()}),M.object({op:M.literal("add"),path:M.string(),value:M.string()}),M.object({op:M.literal("remove"),path:M.string()})]),CM=M.object({thoughts:M.string(),patches:Qw.array()}),Dp=[M.literal("add"),M.literal("replace"),M.literal("remove")],ev=M.object({op:M.union(Dp),path:M.string(),value:Ae.optional()}),Up=M.object({patches:ev.array(),thoughts:M.string()});var tv=M.object({thoughts:M.string(),op:M.union(Dp),value:M.union([M.null(),Ae])}),zp=M.object({reasoning:M.string(),scenario:M.string(),patch:tv.or(M.null())}),EM=M.object({thoughts:M.string(),evaluation:M.number().min(1).max(10)}),AM=M.object({observations:M.string(),reasoning:M.string(),command:os});var _l=M.object({summary:M.string(),reasoning:M.string(),evaluation:M.discriminatedUnion("type",[M.object({type:M.literal("DONE")}),M.object({type:M.literal("RIGHT_TRACK")}),M.object({type:M.literal("WRONG_TRACK"),feedback:M.string()}),M.object({type:M.literal("IMPOSSIBLE")})])});import{z as F}from"zod";import{z as ai}from"zod";import{z as Tx}from"zod";import*as q from"zod";import{cloneDeep as oi}from"lodash-es";var nv=n=>{let e=Bp(n,0);if(e===void 0||!ov(n[e]))return;let t=Bp(n,e+1);if(t!==void 0)return iv(n,e,t)},jp=nv,Bp=(n,e)=>{for(let t=e;t<n.length;t+=1){let r=n[t];if(!rv(r))return t}},rv=n=>n===" "||n===" "||n===`
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]="516fb9a5-624b-5744-9389-945ddcf0c140")}catch(e){}}();
4
+ var $S=Object.create;var wp=Object.defineProperty;var HS=Object.getOwnPropertyDescriptor;var WS=Object.getOwnPropertyNames;var GS=Object.getPrototypeOf,VS=Object.prototype.hasOwnProperty;var vp=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var qS=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of WS(e))!VS.call(n,o)&&o!==t&&wp(n,o,{get:()=>e[o],enumerable:!(r=HS(e,o))||r.enumerable});return n};var KS=(n,e,t)=>(t=n!=null?$S(GS(n)):{},qS(e||!n||!n.__esModule?wp(t,"default",{value:n,enumerable:!0}):t,n));var gy=vp((v7,hy)=>{"use strict";hy.exports=uy;function uy(n,e,t){n instanceof RegExp&&(n=py(n,t)),e instanceof RegExp&&(e=py(e,t));var r=my(n,e,t);return r&&{start:r[0],end:r[1],pre:t.slice(0,r[0]),body:t.slice(r[0]+n.length,r[1]),post:t.slice(r[1]+e.length)}}function py(n,e){var t=e.match(n);return t?t[0]:null}uy.range=my;function my(n,e,t){var r,o,i,s,a,l=t.indexOf(n),c=t.indexOf(e,l+1),d=l;if(l>=0&&c>0){if(n===e)return[l,c];for(r=[],i=t.length;d>=0&&!a;)d==l?(r.push(d),l=t.indexOf(n,d+1)):r.length==1?a=[r.pop(),c]:(o=r.pop(),o<i&&(i=o,s=c),c=t.indexOf(e,d+1)),d=l<c&&l>=0?l:c;r.length&&(a=[i,s])}return a}});var Ty=vp((x7,xy)=>{"use strict";var fy=gy();xy.exports=TR;var yy="\0SLASH"+Math.random()+"\0",by="\0OPEN"+Math.random()+"\0",yd="\0CLOSE"+Math.random()+"\0",Sy="\0COMMA"+Math.random()+"\0",wy="\0PERIOD"+Math.random()+"\0";function fd(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function vR(n){return n.split("\\\\").join(yy).split("\\{").join(by).split("\\}").join(yd).split("\\,").join(Sy).split("\\.").join(wy)}function xR(n){return n.split(yy).join("\\").split(by).join("{").split(yd).join("}").split(Sy).join(",").split(wy).join(".")}function vy(n){if(!n)return[""];var e=[],t=fy("{","}",n);if(!t)return n.split(",");var r=t.pre,o=t.body,i=t.post,s=r.split(",");s[s.length-1]+="{"+o+"}";var a=vy(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function TR(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),Oi(vR(n),!0).map(xR)):[]}function CR(n){return"{"+n+"}"}function ER(n){return/^-?0\d/.test(n)}function AR(n,e){return n<=e}function RR(n,e){return n>=e}function Oi(n,e){var t=[],r=fy("{","}",n);if(!r)return[n];var o=r.pre,i=r.post.length?Oi(r.post,!1):[""];if(/\$$/.test(r.pre))for(var s=0;s<i.length;s++){var a=o+"{"+r.body+"}"+i[s];t.push(a)}else{var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),d=l||c,p=r.body.indexOf(",")>=0;if(!d&&!p)return r.post.match(/,.*\}/)?(n=r.pre+"{"+r.body+yd+r.post,Oi(n)):[n];var u;if(d)u=r.body.split(/\.\./);else if(u=vy(r.body),u.length===1&&(u=Oi(u[0],!1).map(CR),u.length===1))return i.map(function(U){return r.pre+u[0]+U});var m;if(d){var h=fd(u[0]),g=fd(u[1]),f=Math.max(u[0].length,u[1].length),y=u.length==3?Math.abs(fd(u[2])):1,v=AR,b=g<h;b&&(y*=-1,v=RR);var E=u.some(ER);m=[];for(var x=h;v(x,g);x+=y){var C;if(c)C=String.fromCharCode(x),C==="\\"&&(C="");else if(C=String(x),E){var L=f-C.length;if(L>0){var N=new Array(L+1).join("0");x<0?C="-"+N+C.slice(1):C=N+C}}m.push(C)}}else{m=[];for(var P=0;P<u.length;P++)m.push.apply(m,Oi(u[P],!1))}for(var P=0;P<m.length;P++)for(var s=0;s<i.length;s++){var a=o+m[P]+i[s];(!e||d||a)&&t.push(a)}}return t}});var ml=(n,e)=>{},jo=()=>{},hl=!1;try{let n=await import("@sentry/node"),{nodeProfilingIntegration:e}=await import("@sentry/profiling-node");ml=n.captureException,jo=n.profiler.stopProfiler,n.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",integrations:[e()],environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:1}),n.profiler.startProfiler(),hl=!0}catch{}import{Command as DL,Option as Kt}from"@commander-js/extra-typings";import{execSync as UL}from"child_process";import Nb from"body-parser";import EP from"cors";import AP from"dedent";import RP from"events";import _b,{Router as IP}from"express";import PP from"http";import{z as xp}from"zod";var ZL=xp.object({input:xp.string()});import{z as ze}from"zod";var tO=ze.object({srcs:ze.array(ze.string()),urls:ze.array(ze.string()),desiredSrc:ze.string().optional(),desiredUrl:ze.string().optional()}),Tp=ze.object({srcRegex:ze.string().optional(),urlRegex:ze.string().optional()}),Cp=ze.object({x:ze.number(),y:ze.number(),correlation:ze.number()}),nO=ze.object({searchImageBase64String:ze.string(),pageImageBase64String:ze.string(),id:ze.string().uuid(),timeoutMs:ze.number().max(1e4).min(0).optional()});import{z as M}from"zod";import{v4 as Oe}from"uuid";import*as w from"zod";function he(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(o){return new this.constructor({...this._def,openapi:o})};let e=n.ZodObject.prototype.extend;n.ZodObject.prototype.extend=function(...o){let i=e.apply(this,o);return i._def.extendMetadata={extends:this},delete i._def.openapi,i};let t=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...o){let i=t.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i};let r=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...o){let i=r.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i}}import{z as ce}from"zod";he(ce);var Ep=ce.object({plan:ce.string().optional(),evidence:ce.string().optional(),thoughts:ce.string(),result:ce.boolean(),relevantElements:ce.array(ce.number()).optional()}),$o=(r=>(r.CONTAINS="CONTAINS",r.STARTS_WITH="STARTS_WITH",r.EQUALS="EQUALS",r))($o||{});var YS=ce.object({type:ce.literal("ELEMENT_CONTENT"),negated:ce.boolean().optional(),operation:ce.nativeEnum($o),value:ce.string()}).openapi({ref:"ElementContentAssertion"}),XS=ce.object({type:ce.literal("ELEMENT_ATTRIBUTE"),negated:ce.boolean().optional(),operation:ce.nativeEnum($o),attr:ce.string(),value:ce.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Ho=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(Ho||{}),JS=ce.object({type:ce.literal("ELEMENT_EXISTENCE"),negated:ce.boolean().optional(),condition:ce.nativeEnum(Ho)}).openapi({ref:"ElementExistenceAssertion"}),Ap=ce.discriminatedUnion("type",[YS,XS,JS]).openapi({ref:"ManualElementAssertion"});var ZS=ce.object({type:ce.literal("CONTENT"),negated:ce.boolean().optional(),value:ce.string()}).openapi({ref:"PageContentAssertion"}),Rp=ce.discriminatedUnion("type",[ZS]).openapi({ref:"ManualPageAssertion"});import*as V from"zod";he(V);var er=(a=>(a.AI="AI",a.AI_HEALED="AI_HEALED",a.CLICK_TO_FIND="CLICK_TO_FIND",a.XY_PERCENT="XY_PERCENT",a.RECORDING="RECORDING",a.USER_CSS_SELECTOR="USER_CSS_SELECTOR",a.HEURISTIC_HEALED="HEURISTIC_HEALED",a))(er||{}),QS=V.object({mPathSelectorTokens:V.string().array(),frameSrcRegex:V.string().optional(),frameUrlRegex:V.string().optional(),indices:V.number().array()}),tr=V.object({id:V.number().int(),dataMomenticId:V.number().int().optional(),selector:V.string().optional(),generatedSelectors:V.string().array().optional(),role:V.string().optional(),name:V.string().optional(),numChildren:V.number().optional(),content:V.string().optional(),pathFromRoot:V.string().optional(),serializedForm:V.string().optional(),nodeOnlySerializedForm:V.string().optional(),serializedHtml:V.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:V.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:V.string().url().optional(),boundingBox:V.object({x:V.number().optional(),y:V.number().optional(),width:V.number(),height:V.number()}).describe("css pixel bounding box").optional(),frameCache:QS.optional(),inputDescription:V.string().optional().describe("the description that generated this cache"),targetSource:V.nativeEnum(er).optional(),targetUpdateTime:V.string().optional()}).openapi({ref:"A11yTargetWithCache"});function Ip(n){return!!(n.name||n.role||n.content||n.serializedForm||n.serializedHtml||n.screenshotUrl)}var ew=V.object({type:V.literal("description"),elementDescriptor:V.string(),a11yData:tr.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),tw=V.object({x:V.number(),y:V.number()}),nw=V.object({type:V.literal("coordinates"),pixels:tw}).openapi({ref:"CoordinatesTarget"});function kn(n){return n.type==="description"}function cn(n){return n.type==="coordinates"}var at=V.discriminatedUnion("type",[ew,nw]).openapi({ref:"ElementTarget"});function gl(n){if(!n)return!1;switch(n.type){case"description":return!!n.elementDescriptor}return!0}function lt(n){if(!n)return"";switch(n.type){case"description":return n.elementDescriptor;case"coordinates":return`x: ${n.pixels.x}, y: ${n.pixels.y}`}}import{z as te}from"zod";var Qi=te.object({url:te.string(),method:te.union([te.literal("GET"),te.literal("POST"),te.literal("PUT"),te.literal("DELETE"),te.literal("PATCH")]),headers:te.record(te.string(),te.string()).optional(),params:te.record(te.string(),te.string()).optional(),body:te.string().optional(),timeout:te.number().int().optional().describe("Max seconds to wait for the request to complete")}),Pp=te.object({url:te.string(),headers:te.record(te.string(),te.string()).optional(),query:te.string(),variables:te.record(te.string(),te.string()).optional(),timeout:te.number().int().optional().describe("Max seconds to wait for the request to complete")}),es=te.object({code:te.string(),fragment:te.boolean().optional(),environment:te.union([te.literal("NODE"),te.literal("BROWSER")]).optional().describe("default NODE"),timeout:te.number().int().max(60).optional().describe("Max seconds for the code to complete")});var He=(D=>(D.AI_EXTRACT="AI_EXTRACT",D.AI_ASSERTION="AI_ASSERTION",D.AI_WAIT="AI_WAIT",D.AUTH_LOAD="AUTH_LOAD",D.AUTH_SAVE="AUTH_SAVE",D.BLUR="BLUR",D.CAPTCHA="CAPTCHA",D.CLICK="CLICK",D.COOKIE="COOKIE",D.COPY="COPY",D.DIALOG="DIALOG",D.DRAG="DRAG",D.ELEMENT_CHECK="ELEMENT_CHECK",D.FILE_UPLOAD="FILE_UPLOAD",D.FOCUS="FOCUS",D.GO_BACK="GO_BACK",D.GO_FORWARD="GO_FORWARD",D.HOVER="HOVER",D.JAVASCRIPT="JAVASCRIPT",D.LOCAL_STORAGE="LOCAL_STORAGE",D.MOUSE_DRAG="MOUSE_DRAG",D.NAVIGATE="NAVIGATE",D.NEW_TAB="NEW_TAB",D.PAGE_CHECK="PAGE_CHECK",D.PASTE="PASTE",D.PRESS="PRESS",D.REFRESH="REFRESH",D.REQUEST="REQUEST",D.GRAPHQL_REQUEST="GRAPHQL_REQUEST",D.SCROLL_DOWN="SCROLL_DOWN",D.SCROLL_UP="SCROLL_UP",D.SCROLL_LEFT="SCROLL_LEFT",D.SCROLL_RIGHT="SCROLL_RIGHT",D.SELECT_OPTION="SELECT_OPTION",D.TAB="TAB",D.TYPE="TYPE",D.VISUAL_DIFF="VISUAL_DIFF",D.WAIT="WAIT",D.WAIT_FOR_URL="WAIT_FOR_URL",D.SUCCESS="SUCCESS",D))(He||{});he(w);var Y=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),_t=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),dn=w.object({target:tr}).optional().openapi({ref:"SingleTargetCache"}),ts=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),rw=Y.merge(ts).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),ns=_t.merge(w.object({cache:dn})),Br=Y.merge(ns.merge(w.object({target:at.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),jr=Y.merge(ns.merge(w.object({target:at.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),$r=Y.merge(ns.merge(w.object({target:at.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Hr=Y.merge(ns.merge(w.object({target:at.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),SO=w.discriminatedUnion("type",[Br,jr,$r,Hr]).openapi({ref:"AllScrollCommands"}),ow=Y.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),iw=Y.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),sw=w.discriminatedUnion("type",[w.object({type:w.literal("SUBSTRING"),url:w.string()}),w.object({type:w.literal("GLOB"),glob:w.string()}),w.object({type:w.literal("REGEX"),regex:w.string()})]),aw=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")}),lw=Y.extend({type:w.literal("WAIT_FOR_URL"),url:w.string().optional().describe("Deprecated: url or glob to wait for. New commands should use the discriminated matcher field."),matcher:sw.optional()}).merge(aw).openapi({ref:"WaitUrlCommand"}),cw=Y.merge(ts).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),dw=Y.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),pw=Y.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),uw=Y.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),mw=Y.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"}),bl=Y.merge(_t).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),hw=Y.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),gw=Y.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),fw=Y.merge(es).extend({type:w.literal("JAVASCRIPT"),envKey:w.string().optional()}).openapi({ref:"JavaScriptCommand"}),Wo=Y.merge(_t).merge(w.object({type:w.literal("CLICK"),target:at,doubleClick:w.boolean().optional(),rightClick:w.boolean().optional(),waitForUrl:w.string().optional().describe("Deprecated: wait for the click to trigger a page load or new tab that matches the provided URL or URL glob (e.g. https://google.com/**/*)."),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(),cache:dn})).openapi({ref:"ClickCommand"}),Go=Y.merge(_t).merge(w.object({type:w.literal("DRAG"),fromTarget:at,toTarget:at,hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:w.object({fromTarget:tr.optional(),toTarget:tr.optional()}).optional()})).openapi({ref:"DragCommand"}),Vo=Y.merge(_t).merge(w.object({type:w.literal("MOUSE_DRAG"),target:at.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:dn})).openapi({ref:"MouseDragCommand"}),qo=Y.merge(_t).merge(w.object({type:w.literal("HOVER"),target:at,cache:dn})).openapi({ref:"HoverCommand"}),Ko=Y.merge(_t).merge(w.object({type:w.literal("FOCUS"),target:at,cache:dn})).openapi({ref:"FocusCommand"}),Yo=Y.merge(_t).extend({type:w.literal("BLUR"),target:at.optional(),cache:dn}).openapi({ref:"BlurCommand"}),yw=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),bw=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Sw=Y.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[yw,bw]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),ww=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.number().int()})]),Xo=Y.merge(_t).extend({type:w.literal("SELECT_OPTION"),target:at,cache:dn,option:w.string().describe("option value, deprecated old field").optional(),choice:ww.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Sl=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),wl=Y.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:Sl.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),vw=wl.extend({type:w.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),xn=5,vl=600,Jo=Y.merge(_t).extend({type:w.literal("ELEMENT_CHECK"),target:at,assertion:Ap,cache:dn,timeout:w.number().int().min(0).max(vl).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),xw=Y.extend({type:w.literal("PAGE_CHECK"),assertion:Rp,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(vl).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Tw=Y.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"}),Cw=w.object({clearContent:w.boolean().optional(),forceClearContent:w.boolean().optional(),pressKeysSequentially:w.boolean().optional().describe("Deprecated: this is now the default. Please set delay to zero if you wish to achieve instant typing behavior."),delay:w.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:w.boolean().optional(),pressEnter:w.boolean().optional()}),Zo=Y.merge(_t).merge(Cw).extend({type:w.literal("TYPE"),target:at.optional(),value:w.string(),cache:dn}).openapi({ref:"TypeCommand"}),Ew=Y.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"}),Aw=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),Rw=w.object({type:w.literal("REGEX"),pattern:w.string()}),Iw=w.object({type:w.literal("INDEX"),index:w.number()}),Pw=w.discriminatedUnion("type",[Aw,Rw,Iw]),Lw=Y.merge(ts).merge(w.object({type:w.literal("TAB"),url:w.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:Pw.optional()})).openapi({ref:"TabCommand"}),Ow=Y.merge(ts).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),kw=Y.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),Mw=Y.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),Nw=Y.extend({type:w.literal("REQUEST")}).merge(Qi).openapi({ref:"RequestCommand"}),_w=Y.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(Pp).openapi({ref:"GraphQLRequestCommand"}),Fw=Y.merge(w.object({type:w.literal("SUCCESS"),condition:wl.optional()})).openapi({ref:"SuccessCommand"}),Dw=Y.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Uw=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),Qo=Y.merge(_t).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:at.optional(),screenshot:Uw.optional(),cache:dn})).openapi({ref:"VisualDiffCommand"}),Lp=w.discriminatedUnion("type",[Wo,Zo,Ew,Xo,rw,jr,Br,wl,qo,iw,Fw]),zw=w.discriminatedUnion("type",[vw,Tw,mw,uw,bl,kw,hw,ow,Go,Jo,Sw,dw,pw,fw,Mw,Vo,Ow,xw,gw,cw,Nw,_w,$r,Hr,Lw,Qo,Ko,Yo,lw]),rs=w.discriminatedUnion("type",[...Lp.options,...zw.options]).openapi({ref:"Command"}),os=w.discriminatedUnion("type",[...Lp.options,Dw]);function Mn(n){let e;switch(n){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:Oe(),type:n};break;case"AUTH_LOAD":{e={id:Oe(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:Oe(),type:n,goal:""};break;case"DIALOG":e={id:Oe(),type:n,action:"DISMISS"};break;case"DRAG":e={id:Oe(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Oe(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Oe(),type:n,url:""};break;case"WAIT":e={id:Oe(),type:n,delay:1};break;case"BLUR":e={id:Oe(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Oe(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Oe(),type:n,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Oe(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Oe(),type:n,url:""};break;case"REQUEST":e={id:Oe(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Oe(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Oe(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:Oe(),type:n,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Oe(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:Oe(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Oe(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Oe(),type:n,assertion:{type:"CONTENT",value:""}};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}import{z as Bw}from"zod";var CO=Bw.discriminatedUnion("type",[Yo,bl,Wo,Go,Ko,qo,Vo,Br,jr,$r,Hr,Xo,Zo,Qo,Jo]);function Op(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as jw}from"zod";var bt={type:!0,cache:!0},nr=jw.discriminatedUnion("type",[Yo.pick(bt),Wo.pick(bt),Go.pick(bt),Jo.pick(bt),Ko.pick(bt),qo.pick(bt),Vo.pick(bt),Br.pick(bt),jr.pick(bt),$r.pick(bt),Hr.pick(bt),Xo.pick(bt),Zo.pick(bt),Qo.pick(bt)]),xl=Object.values(He).filter(n=>nr.options.some(e=>e.shape.type.safeParse(n).success));rs.options.forEach(n=>{if("target"in n.shape&&!xl.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as Cl}from"zod";import{z as Tl}from"zod";import{z as Wr}from"zod";var St=Wr.object({index:Wr.number().optional().describe("global index within a test (in-order traversal)"),id:Wr.string(),skipped:Wr.boolean().optional(),envKey:Wr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Wr.boolean().optional()});he(Tl);var wt=St.extend({type:Tl.literal("PRESET_ACTION"),command:rs,skipped:Tl.boolean().optional()}).openapi({ref:"PresetAction"});he(Cl);var rr=St.extend({type:Cl.literal("AI_ACTION"),text:Cl.string(),steps:wt.array().optional()}).openapi({ref:"AIAction"});import{z as re}from"zod";var $w=re.object({cacheKey:re.string(),cacheExpiryMs:re.number()}),El=St.extend({id:re.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:re.record(re.string()).optional(),cacheConfig:$w.optional()}),Tn=El.extend({type:re.literal("MODULE"),moduleId:re.string().uuid()}),Hw=re.union([Tn.pick({type:!0,moduleId:!0}),re.record(re.unknown())]),Ww=re.object({type:re.literal("URL_REGEX"),regex:re.string()}),Gw=re.object({type:re.literal("PAGE_CHECK"),substring:re.string()}),Al=re.object({cacheInvalidation:re.discriminatedUnion("type",[Gw,Ww]).optional()}),vt=re.object({moduleId:re.string().uuid(),name:re.string(),description:re.string().nullish(),enabled:re.boolean().nullish(),parameters:re.string().array().nullish(),defaultParameters:re.record(re.string(),re.string()).nullish(),defaultCacheKey:re.string().nullish(),defaultCacheTtl:re.number().nullish(),defaultCacheAllInvocations:re.boolean().nullish(),autoAuth:re.boolean().nullish(),advanced:Al.nullish()});import{z as tt}from"zod";import{z as Rl}from"zod";he(Rl);var Gr=St.extend({type:Rl.literal("AI_ACTION_DYNAMIC"),text:Rl.string()}).openapi({ref:"AIActionDynamic"});import{z as kp}from"zod";var Il=St.extend({type:kp.literal("CONDITIONAL"),skipped:kp.boolean().optional()});import{z as is}from"zod";var Vw=is.object({type:is.literal("url"),url:is.string()}),ei=St.extend({type:is.literal("IFRAME"),identifier:Vw});import{z as Ft}from"zod";var Pl=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(Pl||{});var qw=Ft.discriminatedUnion("type",[Ft.object({type:Ft.literal("NAVIGATE_URL"),url:Ft.string().url()}),Ft.object({type:Ft.literal("GO_TO_SECTION_START")})]),Kw=Ft.object({trigger:Ft.nativeEnum(Pl).optional(),attempts:Ft.number().int().optional(),restartBehavior:qw}),ti=St.extend({type:Ft.literal("SECTION"),description:Ft.string().describe("user provided goal of what the section should accomplish"),plan:Ft.string().array().optional(),autohealingConfig:Kw.optional()});var Mp=vt.merge(El).extend({type:tt.literal("RESOLVED_MODULE"),steps:tt.lazy(()=>Ae.array())}),Ll=vt.extend({steps:tt.lazy(()=>Ae.array())}),Ol=ei.extend({steps:tt.lazy(()=>We.array())}),Yw=ei.extend({steps:tt.lazy(()=>Ae.array())}),kl=ti.extend({steps:tt.lazy(()=>We.array())}),Xw=ti.extend({steps:tt.lazy(()=>Ae.array())}),or=Il.extend({blocks:tt.object({assertion:tt.lazy(()=>wt),steps:tt.lazy(()=>We.array())}).array(),elseSteps:tt.lazy(()=>We.array().optional())}),Jw=Il.extend({blocks:tt.object({assertion:tt.lazy(()=>wt),steps:tt.lazy(()=>Ae.array())}).array(),elseSteps:tt.lazy(()=>Ae.array().optional())}),We=tt.discriminatedUnion("type",[wt,rr,Gr,Tn,or,Ol,kl]),Ae=tt.discriminatedUnion("type",[wt,rr,Gr,Mp,Jw,Yw,Xw]);import{z as Dt}from"zod";var Zw=Dt.object({steps:We.array(),beforeSteps:We.array().nullish(),afterSteps:We.array().nullish()}),Vr=Dt.object({steps:Ae.array(),beforeSteps:Ae.array().nullish(),afterSteps:Ae.array().nullish()}),ir=Dt.object({steps:Dt.record(Dt.string(),Dt.unknown()).array(),beforeSteps:Dt.record(Dt.string(),Dt.unknown()).array().nullish(),afterSteps:Dt.record(Dt.string(),Dt.unknown()).array().nullish()});var mt="1.0.19";import{z as sr}from"zod";var Ml=sr.object({key:sr.string(),testId:sr.string().optional(),moduleId:sr.string().optional(),organizationId:sr.string(),value:nr}),Np=sr.record(sr.string(),Ml);var _p=M.object({phrase:M.string()}),Nl=M.object({thoughts:M.string().optional(),result:M.union([M.literal("NOT_FOUND"),M.string(),M.number(),M.array(M.unknown()),M.record(M.unknown(),M.unknown()),M.unknown()])}),TM=M.object({text:M.string()}),Fp=M.object({thoughts:M.string(),id:M.number().int()}),Qw=M.discriminatedUnion("op",[M.object({op:M.literal("replace"),path:M.string(),value:M.string()}),M.object({op:M.literal("add"),path:M.string(),value:M.string()}),M.object({op:M.literal("remove"),path:M.string()})]),CM=M.object({thoughts:M.string(),patches:Qw.array()}),Dp=[M.literal("add"),M.literal("replace"),M.literal("remove")],ev=M.object({op:M.union(Dp),path:M.string(),value:Ae.optional()}),Up=M.object({patches:ev.array(),thoughts:M.string()});var tv=M.object({thoughts:M.string(),op:M.union(Dp),value:M.union([M.null(),Ae])}),zp=M.object({reasoning:M.string(),scenario:M.string(),patch:tv.or(M.null())}),EM=M.object({thoughts:M.string(),evaluation:M.number().min(1).max(10)}),AM=M.object({observations:M.string(),reasoning:M.string(),command:os});var _l=M.object({summary:M.string(),reasoning:M.string(),evaluation:M.discriminatedUnion("type",[M.object({type:M.literal("DONE")}),M.object({type:M.literal("RIGHT_TRACK")}),M.object({type:M.literal("WRONG_TRACK"),feedback:M.string()}),M.object({type:M.literal("IMPOSSIBLE")})])});import{z as F}from"zod";import{z as ai}from"zod";import{z as Tx}from"zod";import*as q from"zod";import{cloneDeep as oi}from"lodash-es";var nv=n=>{let e=Bp(n,0);if(e===void 0||!ov(n[e]))return;let t=Bp(n,e+1);if(t!==void 0)return iv(n,e,t)},jp=nv,Bp=(n,e)=>{for(let t=e;t<n.length;t+=1){let r=n[t];if(!rv(r))return t}},rv=n=>n===" "||n===" "||n===`
5
5
  `||n==="\r",ov=n=>n==="{"||n==="[",iv=(n,e,t)=>{let r;for(let o=t-1;o>e;o-=1){let i=n[o];if(i==="\r")return;if(i===`
6
6
  `)return sv(r);if(r===void 0)r=i;else if(r[0]===i)r+=i;else return}},sv=n=>n===void 0?0:n[0]===" "?n.length:n;var $p=(n,e)=>{let t=Fl(n,"toPrecision",e,e);return t===void 0?Fl(n,"toExponential",e,e):t},Fl=(n,e,t,r)=>{let i=n[e](r).replace(av,"$1").replace(lv,"$1");return i.length<=t?i:r===1?void 0:Fl(n,e,t,r-1)},av=/(e)\+/iu,lv=/\.?0*($|e)/iu;var Wp=(n,e)=>{if(typeof n!="string")throw new TypeError(`Input must be a JSON string: ${n}`);cv(e)},cv=n=>{if(dv(n),n<0)throw new TypeError(`"maxSize" argument must be positive: ${n}`);if(n<Hp)throw new TypeError(`"maxSize" argument must be at least ${Hp}: ${n}`)},dv=n=>{if(n===void 0)throw new TypeError('"maxSize" argument must be defined');if(!Number.isInteger(n))throw new TypeError(`"maxSize" argument must be an integer: ${n}`)},Hp=7;var ss=(n,e,t)=>{let r=Vp(e,t);return Gp(n,e,r)},Gp=(n,e,t)=>{if(t>=e)return t;let r=n[t];return r>=Sv&&r<=wv?Gp(n,e,t+1):t},as=(n,e,t)=>{if(t===void 0)return t;let r=Vp(e,t);return pv(n,r)},pv=(n,e)=>uv(n,e)?e-3:mv(n,e)?e-2:hv(n,e)?e-1:e,uv=(n,e)=>e>=3&&n[e-3]>=gv&&n[e-3]<=fv,mv=(n,e)=>e>=2&&n[e-2]>=yv,hv=(n,e)=>e>=1&&n[e-1]>=bv,Vp=(n,e)=>e<0||Object.is(e,-0)?Math.max(n+e,0):e,gv=240,fv=244,yv=224,bv=194,Sv=128,wv=191;var qp=(n,e,t)=>{let r=globalThis.Buffer.from(n),o=ss(r,r.length,e),i=as(r,r.length,t);return o===0&&i>=r.length?r.toString():r.toString("utf8",o,i)};var Kp=/[\uD800-\uDFFF]/gu,Yp="\uFFFD";var ls=n=>vv(n)?n.replace(Kp,Yp):n,vv=n=>{for(let e=0;e<n.length;e+=1){let t=n.codePointAt(e);if(t>=55296&&t<=57343)return!0}return!1};var zl=({input:n,targetByteCount:e,firstStartSurrogate:t,lastStartSurrogate:r,firstEndSurrogate:o,lastEndSurrogate:i,increment:s,canBacktrack:a,shift:l,charIndexInit:c})=>{let d=c,p=d,u=0;for(;u<e;d+=s){p=d;let h=n.charCodeAt(d);if(Number.isNaN(h))break;if(h<=127){u+=1;continue}if(h<=2047){u+=2;continue}if(u+=3,h<t||h>r)continue;let g=n.charCodeAt(d+s);Number.isNaN(g)||g<o||g>i||(u+=1,d+=s)}return(a&&u>e?p:d)+l};var Bl=(n,e,t)=>e<0||Object.is(e,-0)?Rv(n,e,t):Av(n,e,t),Av=(n,e,t)=>zl({input:n,targetByteCount:e,firstStartSurrogate:55296,lastStartSurrogate:56319,firstEndSurrogate:56320,lastEndSurrogate:57343,increment:1,canBacktrack:t,shift:0,charIndexInit:0}),Rv=(n,e,t)=>zl({input:n,targetByteCount:-e,firstStartSurrogate:56320,lastStartSurrogate:57343,firstEndSurrogate:55296,lastEndSurrogate:56319,increment:-1,canBacktrack:!t,shift:1,charIndexInit:n.length-1});var cs=(n,e,t)=>{let r=Bl(n,e,!1),o=Iv(n,t),i=r===0&&o===void 0?n:n.slice(r,o);return ls(i)},Iv=(n,e)=>{if(e===void 0)return e;let t=Bl(n,e,!0);return t===n.length?void 0:t};var Jp=(n,e,t)=>{let{textEncoder:r,textDecoder:o}=Pv(),i=Lv(n),{written:s}=r.encodeInto(n,i),a=ss(i,s,e),l=as(i,s,t),c=l===void 0?s:Math.min(l,s),d=i.subarray(a,c);return o.decode(d)},Pv=()=>(jl===void 0&&(jl=new globalThis.TextEncoder,Xp=new globalThis.TextDecoder("utf8",{fatal:!1})),{textEncoder:jl,textDecoder:Xp}),jl,Xp,Lv=n=>{let e=n.length*3;return e>Ov?new Uint8Array(e):((ds===void 0||ds.length<e)&&(ds=new Uint8Array(e)),ds)},Ov=1e5,ds;var Zp=(n,e)=>{if(e===void 0)return e;let t=$l(n,e);return t>=n.length*Qp?void 0:t},$l=(n,e)=>e<=n.length*-Qp?0:e,Qp=4;var eu=(n,e,t)=>{if(typeof n!="string")throw new TypeError(`First argument must be a string: ${n}`);kv(e),Mv(t)},kv=n=>{if(n===void 0)throw new TypeError("Second argument is required.");tu("Second",n)},Mv=n=>{n!==void 0&&tu("Third",n)},tu=(n,e)=>{if(!Number.isInteger(e))throw new TypeError(`${n} argument must be an integer: ${e}`)};var nu=n=>{let e=!0,t=0;for(let r=0;r<Hl;r+=1){let o=Nv(n,r);o<=127||(e&&(e=!1),o>2047&&(t+=1))}return{asciiOnly:e,longCharsPercentage:t/Hl}},Nv=(n,e)=>{let t=Hl-1,r=1-(t-e)/t,o=Math.round(r*(n.length-1));return n.charCodeAt(o)},Hl=50;var _v=(n,e,t)=>{if(eu(n,e,t),n==="")return n;let r=$l(n,e),o=Zp(n,t);return o===void 0&&Object.is(r,0)?ls(n):Fv(n,r,o)},ru=_v,Fv=(n,e,t)=>{if(n.length<=Dv)return cs(n,e,t);let{asciiOnly:r,longCharsPercentage:o}=nu(n);return r?zv(n,e,t):o>=Uv?cs(n,e,t):ou(n,e,t)},Dv=200,Uv=.4,zv=(n,e,t)=>"Buffer"in globalThis&&"from"in globalThis.Buffer?qp(n,e,t):ou(n,e,t),ou=(n,e,t)=>"TextEncoder"in globalThis?Jp(n,e,t):cs(n,e,t);var su=(n,e)=>{let t=JSON.stringify(n),r=$v(t),o=ru(r,0,e-iu.length-ni.length*2),s=`${Bv(o)}${iu}`;return Hv(s)},Bv=n=>n.replace(jv,""),jv=/(\\|\\u[0-9a-fA-F]{0,3})$/u,$v=n=>n.slice(ni.length,-ni.length),Hv=n=>`${ni}${n}${ni}`,ni='"',iu="...";var au=n=>globalThis.Buffer.byteLength(n);var Wl=n=>{let e=n.length,t=e;for(let r=0;r<e;r+=1){let o=n.charCodeAt(r);if(o<=Wv)continue;if(o<=Gv){t+=1;continue}if(t+=2,o<Vv||o>qv)continue;let i=n.charCodeAt(r+1);i<Kv||i>Yv||(r+=1)}return t},Wv=127,Gv=2047,Vv=55296,qv=56319,Kv=56320,Yv=57343;var lu=()=>Xv.bind(void 0,new TextEncoder),Xv=(n,e)=>{let t=Jv(e);return n.encodeInto(e,t).written},Jv=n=>{let e=n.length*3;return e>Zv?new Uint8Array(e):((ps===void 0||ps.length<e)&&(ps=new Uint8Array(e)),ps)},Zv=1e5,ps;var ex=()=>"Buffer"in globalThis&&"byteLength"in globalThis.Buffer?au:"TextEncoder"in globalThis?tx.bind(void 0,lu()):Wl,tx=(n,e)=>e.length<100?Wl(e):n(e),cu=ex();var du=n=>{if(n===null)return nx;if(n===!0)return rx;if(n===!1)return ox;let e=typeof n;return e==="object"?ix:e==="number"?JSON.stringify(n).length:Gl(n)},nx=4,rx=4,ox=5,ix=2,Gl=n=>cu(JSON.stringify(n));var us=({size:n,increment:e,maxSize:t,truncatedProps:r,path:o,value:i})=>{let s=n+e,a=s>t;return a?{size:n,stop:a,truncatedProps:[...r,{path:o,value:i}]}:{size:s,stop:a,truncatedProps:r}},uu=n=>du(n),mu=(n,e,t)=>{let r=gu({empty:n,indent:e,depth:t,keySpaceSize:0}),o=fu(n);return r+o},hu=({key:n,empty:e,indent:t,depth:r})=>{let o=gu({empty:e,indent:t,depth:r,keySpaceSize:1}),i=Gl(n),s=fu(e);return o+i+sx+s},sx=1,gu=({empty:n,indent:e,depth:t,keySpaceSize:r})=>{if(e===void 0)return 0;let o=pu+e*(t+1),i=n?pu+e*t:0;return r+o+i},pu=1,fu=n=>n?0:ax,ax=1;var ms=({parent:n,truncatedProps:e,path:t,increment:r,maxSize:o,key:i,empty:s,size:a,truncateValue:l,indent:c,depth:d})=>{let p=n[i],u=[...t,i],{size:m,stop:h,truncatedProps:g}=us({size:a,increment:r,maxSize:o,truncatedProps:e,path:u,value:p});return h?{empty:s,size:m,truncatedProps:g}:lx({value:p,truncatedProps:e,path:u,maxSize:o,empty:s,size:a,newSize:m,truncateValue:l,indent:c,depth:d})},lx=({value:n,truncatedProps:e,path:t,maxSize:r,empty:o,size:i,newSize:s,truncateValue:a,indent:l,depth:c})=>{let{value:d,size:p,truncatedProps:u}=a({value:n,truncatedProps:e,path:t,size:s,maxSize:r,indent:l,depth:c+1});return d===void 0?{empty:o,size:i,truncatedProps:u}:{empty:!1,size:p,value:d,truncatedProps:u}};var yu=({array:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:i,indent:s,depth:a})=>{let l=[],c={empty:!0,size:r,truncatedProps:e};for(let d=0;d<n.length;d+=1){let p=mu(c.empty,s,a);c=ms({parent:n,truncatedProps:c.truncatedProps,path:t,increment:p,maxSize:o,key:d,empty:c.empty,size:c.size,truncateValue:i,indent:s,depth:a}),c.value!==void 0&&l.push(c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var bu=({object:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:i,indent:s,depth:a})=>{let l={},c={empty:!0,size:r,truncatedProps:e};for(let d in n){let p=hu({key:d,empty:c.empty,indent:s,depth:a});c=ms({parent:n,truncatedProps:c.truncatedProps,path:t,increment:p,maxSize:o,key:d,empty:c.empty,size:c.size,truncateValue:i,indent:s,depth:a}),c.value!==void 0&&(l[d]=c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var hs=({value:n,truncatedProps:e,path:t,size:r,maxSize:o,indent:i,depth:s})=>{let a=uu(n),{size:l,stop:c,truncatedProps:d}=us({size:r,increment:a,maxSize:o,truncatedProps:e,path:t,value:n});return c?{value:void 0,size:l,truncatedProps:d}:cx({value:n,truncatedProps:d,path:t,size:l,maxSize:o,indent:i,depth:s})},cx=({value:n,truncatedProps:e,path:t,size:r,maxSize:o,indent:i,depth:s})=>typeof n!="object"||n===null?{value:n,size:r,truncatedProps:e}:Array.isArray(n)?yu({array:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:hs,indent:i,depth:s}):bu({object:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:hs,indent:i,depth:s});var dx=(n,e)=>{Wp(n,e);let t=px(n),r=ux(n),{value:o,truncatedProps:i}=hs({value:r,truncatedProps:[],path:[],size:0,maxSize:e,indent:t,depth:0});return{jsonString:mx({newValue:o,value:r,maxSize:e,indent:t}),truncatedProps:i}},ri=dx,px=n=>{let e=jp(n);return typeof e=="string"?e.length:e},ux=n=>{try{return JSON.parse(n)}catch(e){throw new TypeError(`Invalid JSON string: "${n}"
7
7
  ${e.message}`)}},mx=({newValue:n,value:e,maxSize:t,indent:r})=>n!==void 0?JSON.stringify(n,void 0,r):typeof e=="number"?$p(e,t):su(e,t);import*as ar from"zod";import{z as xt}from"zod";var ve="BASE_URL",gs="CURRENT_URL",qr="ENV_NAME",NN={[ve]:"https://www.google.com"},Su=xt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),fs=xt.object({name:xt.string(),variables:xt.record(xt.string().describe("variable name"),xt.string().describe("variable value"))}),ys=xt.object({localChromeExtensionPaths:xt.string().array().optional(),disableGpu:xt.boolean().optional()}),bs=xt.object({name:xt.string(),variables:xt.record(xt.string().describe("variable name"),xt.unknown().describe("variable value")),browser:ys.optional()});he(ar);var ii=ar.object({env:ar.record(ar.unknown())}).openapi({ref:"TestContextSnapshot"}),hx="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",gx=[ve,qr],wu=[gs,ve,qr],Tt=class n{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t={}){return new n({baseUrl:"about:blank",currentUrl:"about:blank",envName:e,variablesFromEnvironment:t})}static fromSnapshot({snapshot:e,environmentVariables:t}){let r=e.env[ve]??"about:blank",o=e.env[gs]??"about:blank",i=e.env[qr],s={};for(let[l,c]of Object.entries(e.env))wu.includes(l)||(t??{})[l]===void 0&&(s[l]=c);return new n({baseUrl:r,currentUrl:o,dynamicVariables:s,envName:i,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=oi(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){gx.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[qr]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return oi(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>wu.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,hx]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:i}=ri(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(i)}catch{e.env[r]=void 0}}let{jsonString:t}=ri(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[gs]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=oi(e.variablesFromEnvironment),this.setMomenticSystemVariable(ve,e.baseUrl),e.envName&&this.setMomenticSystemVariable(qr,e.envName)}getDynamicVariablesCopy(){return oi(this.env)}getVariablesFromEnvironmentCopy(){return oi(this.varsFromMomenticEnvironment)}};import{z as lr}from"zod";he(lr);var oe=(c=>(c.AI_PROVIDER="AIProviderError",c.USER_INFRA="UserInfrastructureError",c.ACTION_FAILURE="ActionFailureError",c.ASSERTION_FAILURE="AssertionFailureError",c.CONFIG_ERROR="UserConfigurationError",c.WEB_AGENT_PLATFORM="InternalWebAgentError",c.UNKNOWN_PLATFORM="InternalPlatformError",c.JOB_TIMEOUT="JobTimeoutError",c.UNKNOWN="UnknownError",c))(oe||{});var vu=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],xu={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"},Tu={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 assertion or check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},Vl=lr.object({reason:lr.nativeEnum(oe),summary:lr.string()}).openapi({ref:"TestResultClassification"}),Ss=lr.object({errorMessage:lr.string(),errorStack:lr.string().optional(),classification:Vl.optional()}).openapi({ref:"TestFailureDetails"});he(q);var Ge=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ge||{}),ql=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))(ql||{}),Kl=q.object({beforeUrl:q.string().optional(),afterUrl:q.string().optional(),message:q.string().optional(),beforeScreenshot:q.string().optional(),afterScreenshot:q.string().optional(),beforeSnapshot:q.string().optional(),afterSnapshot:q.string().optional(),startedAt:q.coerce.date(),finishedAt:q.coerce.date()}),fx=Kl.extend({viewport:q.object({height:q.number(),width:q.number()}),status:q.nativeEnum(ql),message:q.string().optional(),elementInteracted:q.string().optional()}),Nn=Kl.extend({status:q.nativeEnum(Ge),message:q.string().optional(),data:q.unknown().optional(),beforeTestContext:ii.optional(),afterTestContext:ii.optional(),failureReason:q.nativeEnum(oe).optional(),details:q.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"}),ws=Nn.merge(wt).extend({results:fx.array(),proposedStep:wt.optional()}),yx=Nn.merge(rr).extend({results:q.lazy(()=>ws.array())}),bx=Nn.merge(Gr).extend({results:q.lazy(()=>ws.array())}),Sx=Nn.merge(Tn).extend({moduleName:q.string().optional(),results:q.lazy(()=>Ut.array())}),wx=Nn.merge(or).extend({assertion:ws.optional(),results:q.lazy(()=>Ut.array()).describe("results for the block actually executed")}),vx=Nn.merge(ei).extend({results:q.lazy(()=>Ut.array())}),xx=Nn.merge(ti).extend({results:q.lazy(()=>Ut.array()),healingAttempts:q.lazy(()=>Ut.array().array()).optional()}),Ut=q.discriminatedUnion("type",[yx,bx,ws,Sx,wx,vx,xx]),_n=Nn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Cu=Kl.extend({index:q.number().optional(),description:q.string(),pageState:q.string().optional()});var Yl=Tx.object({results:Ut.array().describe("main results"),beforeResults:Ut.array().optional(),afterResults:Ut.array().optional()}),vs=Yl.partial();import{z as G}from"zod";import{z as ge}from"zod";var Cx=ge.object({type:ge.literal("FAILURE_RECOVERY"),thoughts:ge.string()}),Ex=ge.object({type:ge.literal("DESCRIPTION_UPDATE"),thoughts:ge.string()}),xs=ge.discriminatedUnion("type",[Ex,Cx]),Ts=(e=>(e.AUTO_HEALING="AUTO_HEALING",e))(Ts||{}),Ax=ge.object({testId:ge.string(),name:ge.string(),orgId:ge.string(),runId:ge.string(),purpose:ge.nativeEnum(Ts).catch("AUTO_HEALING"),steps:Ae.array(),details:xs.or(xs.array()).optional()}),a_=Ax.pick({name:!0,orgId:!0}),Xl=ge.object({id:ge.string(),name:ge.string().nullish(),createdAt:ge.string().pipe(ge.coerce.date()).or(ge.date()),organizationId:ge.string(),schemaVersion:ge.string(),purpose:ge.nativeEnum(Ts).catch("AUTO_HEALING"),runId:ge.string().nullish(),details:xs.or(xs.array()).nullish(),applied:ge.boolean().nullish(),appliedAt:ge.coerce.date().nullish()}),Eu=Xl.extend({steps:Ae.array()});import{isValidCron as Rx}from"cron-validator";import{z as J}from"zod";import{z as Jl}from"zod";var Cs=Jl.object({width:Jl.number().min(200).max(1e4),height:Jl.number().min(200).max(1e4)}),Au={"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}},d_=Object.keys(Au);var Xt=Au["Desktop Large"];var Ru=1e4,Iu=6e4,cr=(t=>(t.CHROMIUM="Chromium",t.GOOGLE_CHROME="Google Chrome",t))(cr||{}),Es=J.object({browserType:J.nativeEnum(cr).optional(),pageLoadTimeoutMs:J.number().optional().refine(n=>n===void 0||n<=Iu&&n>=-1,{message:`Page load timeout must be between 0 and ${Iu/1e3} seconds`}),smartWaitingTimeoutMs:J.number().optional().refine(n=>n===void 0||n<=Ru&&n>=-1,{message:`Smart waiting timeout must be between 0 and ${Ru/1e3} seconds`}),extraHeaders:J.record(J.string(),J.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:J.string().optional(),basicAuthorization:J.object({username:J.string().optional(),password:J.string().optional()}).optional(),disableJavaScript:J.boolean().optional(),disableGpu:J.boolean().optional(),localChromeExtensionPaths:J.string().array().optional()}),Pu=["extraHeaders","basicAuthorization","localChromeExtensionPaths"];var Ix=J.object({disableAICaching:J.boolean().default(!1),failureRecovery:J.boolean().optional().describe("undefined means inherit org settings")});var Px=J.object({viewport:Cs.optional()}),Kr=Px.merge(Ix).merge(Es),Yr=J.object({cron:J.string().refine(n=>Rx(n),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:J.boolean().default(!1),env:J.string().optional(),timeZone:J.string().default("America/Los_Angeles"),jobKey:J.string().optional()}),Xr=J.object({onSuccess:J.boolean().default(!1),failureMessage:J.string().optional(),onFailure:J.boolean().default(!0),successMessage:J.string().optional()}),Lx=J.object({name:J.string(),required:J.boolean().optional(),defaultValue:J.string().describe("this is not optional because we need a value when the editor is first loaded")}),As=Lx.array(),Ox=J.object({name:J.string(),value:J.string()}),Lu=Ox.array(),Rs=J.object({name:J.string(),default:J.boolean().optional(),fixtures:Su.array().optional()});he(G);var zt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},pe=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(pe||{}),Is=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Is||{});var Re=G.string().pipe(G.coerce.date()).or(G.date()),si=G.object({id:G.string(),runKey:G.string(),organizationId:G.string(),createdAt:Re,createdBy:G.string(),flake:G.boolean().nullish(),scheduledAt:Re.or(G.null()),startedAt:Re.or(G.null()),updatedAt:Re.nullish(),finishedAt:Re.or(G.null()),resolvedBaseUrl:G.string().nullish(),environmentName:G.string().nullish(),section:G.nativeEnum(Is).nullish(),status:G.nativeEnum(pe),trigger:G.nativeEnum(zt),attempts:G.number(),runAttempts:G.array(G.object({id:G.string(),status:G.nativeEnum(pe),startedAt:Re.or(G.null()),finishedAt:Re.or(G.null())})).optional(),videos:G.array(G.string()).optional(),failureReason:G.nativeEnum(oe).nullish(),failureDetails:Ss.nullish(),testFragments:G.array(Xl).nullish(),localTestId:G.string().nullish(),testId:G.string().nullish(),testName:G.string().nullish(),test:G.object({name:G.string(),id:G.string()}).nullish().default(null),suiteId:G.string().nullish()}).openapi({ref:"RunMetadata"}),kx={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Ps=si.pick({...kx,test:!0}),Ou=si.omit({failureReason:!0,failureDetails:!0,test:!0}),Zl=si.extend({stepsSnapshot:G.array(G.record(G.unknown())).nullish(),resolvedInputs:G.record(G.string(),G.string()).nullish(),test:G.object({name:G.string(),id:G.string(),baseUrl:G.string().nullish(),advanced:Kr.nullish()}).nullish()}).merge(Yl),ku=n=>n.includes("PASSED")&&n.includes("FAILED");var Mx=ai.object({id:ai.string().uuid(),startedAt:Re.or(ai.null()),finishedAt:Re.or(ai.null()),status:ai.nativeEnum(pe)}).merge(vs),P_=Mx.array();var Ls=(t=>(t.JUNIT="junit",t.ALLURE="allure",t))(Ls||{});import{z as Ve}from"zod";var Nx=Ve.object({id:Ve.string(),status:Ve.nativeEnum(pe),trigger:Ve.nativeEnum(zt),createdAt:Re,startedAt:Re.nullish(),finishedAt:Re.nullish(),gitCommitSha:Ve.string().nullish(),gitCommitShaShort:Ve.string().nullish(),gitCommitTimestamp:Re.nullish(),gitBranchName:Ve.string().nullish(),gitOriginUrl:Ve.string().nullish(),gitCommitMessage:Ve.string().nullish(),gitCommitAuthorName:Ve.string().nullish(),githubRepository:Ve.string().nullish(),gitlabProjectPath:Ve.string().nullish(),pipelineId:Ve.string().nullish(),suite:Ve.object({id:Ve.string(),name:Ve.string()}).nullish(),runs:Ve.object({status:Ve.nativeEnum(pe)}).array()}).openapi({ref:"RunGroup"}),Mu=Nx.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Ps.array()});import{z as qe}from"zod";import*as ne from"zod";var z_=ne.object({thoughts:ne.string().optional().describe("only provided if a description was provided"),target:tr.optional().describe("only provided if a description was provided"),pageState:ne.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ne.object({label:ne.string(),value:ne.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ne.object({data:ne.string(),height:ne.number().int(),width:ne.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Nu="<select> element",_u="text input or contenteditable element",_x="text input element",Ql=[Nu,_u,_x];function Fu(n,e){if(n===e)return!0;for(let t of Ql){if(!n.startsWith(t))continue;let r=n.slice(t.length+2);if(Ql.some(o=>e.startsWith(o)&&e.slice(o.length+2)===r)||r===e)return!0}return!!Ql.some(t=>e.startsWith(t)&&e.slice(t.length+2)===n)}function Os(n,e){if(!e||"useSelector"in n&&n.useSelector)return e;switch(n.type){case"SELECT_OPTION":return`${Nu}: ${e}`;case"TYPE":return`${_u}: ${e}`;default:return e}return e}var Jr=ne.object({matched:ne.boolean(),reason:ne.string().optional().describe("Human understandable description"),logs:ne.string().array().optional().describe("Logs for debugging")}),Fx=Jr.extend({type:ne.literal("A11Y_ID")}),Dx=Jr.extend({type:ne.literal("USER_SELECTOR")}),Ux=Jr.extend({type:ne.literal("CSS_SELECTOR"),selectors:ne.string().array()}),zx=Jr.extend({type:ne.literal("HTML_DISTANCE"),distance:ne.number().optional(),closestElement:ne.string().optional(),savedElement:ne.string().optional()}),Bx=Jr.extend({type:ne.literal("TEMPLATE_MATCHING"),elementImageUrl:ne.string().url()}),jx=Jr.extend({type:ne.literal("AUTO_FRAME"),logs:ne.string().array().optional()}),Du=ne.discriminatedUnion("type",[Fx,Dx,Ux,zx,Bx,jx]);var $x=qe.object({type:qe.literal("TARGETING"),name:qe.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Du.array(),pageState:qe.string().optional(),targetSource:qe.nativeEnum(er).optional(),targetUpdateTime:qe.string().optional()}),Hx=qe.object({type:qe.literal("AI_LOCATION"),matched:qe.boolean(),pageState:qe.string().optional(),ragUsed:qe.boolean().optional(),thoughts:qe.string().optional()}),Wx=qe.object({type:qe.literal("ASSERTION"),relevantElementsSerialized:qe.string().array().optional(),pageState:qe.string().optional(),ragUsed:qe.boolean().optional()}),Uu=qe.discriminatedUnion("type",[$x,Hx,Wx]);function ks(){return{details:[]}}import{z as ke}from"zod";var Gx=ke.object({id:ke.string(),name:ke.string()}),K_=Gx.merge(ke.object({createdAt:Re,createdBy:ke.string(),schedule:Yr,notification:Xr,environment:ke.object({name:ke.string()}).nullish(),beforeTests:ke.object({id:ke.string()}).array().nullish(),afterTests:ke.object({id:ke.string()}).array().nullish()})),zu=ke.object({id:ke.string().uuid(),orgId:ke.string(),createdAt:Re,startedAt:Re.or(ke.null()),finishedAt:Re.or(ke.null()),status:ke.nativeEnum(pe),trigger:ke.nativeEnum(zt),suite:ke.object({id:ke.string(),name:ke.string()}).nullish(),runs:si.array()}),Y_=zu.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Bu=zu.extend({runs:Ps.array()});var Jt=F.object({disableCache:F.boolean().optional(),loggerTags:F.record(F.string(),F.string()).optional(),langfuseSessionId:F.string().optional()}),Vx=F.object({screenshotBase64AfterCommand:F.string(),urlAfterCommand:F.string(),serializedCommand:F.string(),elementInteracted:F.string().optional(),thoughts:F.string().optional()}),pF=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string(),feedback:F.string().optional()}),uF=F.object({goal:F.string(),browserState:F.string()}),ju=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string().optional(),returnSchema:F.string().optional()}),$u=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string(),url:F.string(),contextChoice:Sl.optional()}),ec=F.object({goal:F.string(),browserState:F.string(),startingScreenshot:F.string().optional(),screenshot:F.string(),url:F.string(),history:Vx.array(),actionHint:F.string().optional(),lastError:F.string().optional()}),Hu=F.object({results:Ut.array(),errorMessage:F.string(),errorStack:F.string().optional()}),Wu=F.object({results:F.array(Ut),goal:F.string(),errorMessage:F.string()}),Gu=F.object({failedResults:Cu.array(),nextStepsSerialized:F.string().array(),currentUrl:F.string(),currentPageState:F.string(),currentScreenshot:F.string()}),mF=F.object({description:F.string(),type:F.union([F.literal("locator"),F.literal("assertion"),F.literal("ai-action")]),excerpt:F.string()});import{z as li}from"zod";var fF=li.object({goal:li.string()}),Vu=li.object({keywords:li.array(li.string())});import{z as ht}from"zod";var tc=ht.object({content:ht.string(),ids:ht.string().array(),tokenLength:ht.number()}),qx=ht.object({chunks:tc.array()}),SF=ht.object({ids:ht.string().array(),score:ht.number(),tokenLength:ht.number()}),wF=qx.extend({description:ht.string().describe("Input to pass to RAG engine"),tokenLimit:ht.number()}),qu=ht.object({ids:ht.number().array()}),Ku=ht.object({indices:ht.number().array()});var Yu=n=>!(!n.org_id||!n.user_id||!n.platform);import{z as dr}from"zod";var Xu=dr.object({id:dr.string().uuid(),skipped:dr.boolean().optional(),envKey:dr.string().optional().describe("key in the environment to save the result of this step to")}),nc=Xu.merge(Qi).extend({type:dr.literal("REQUEST")}),rc=Xu.merge(es).extend({type:dr.literal("JAVASCRIPT")}),oc=dr.discriminatedUnion("type",[rc,nc]);import{z as Bt}from"zod";import{z as pr}from"zod";var Kx=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Me=n=>{let e=n.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var Ms=pr.string().min(1).max(255).superRefine((n,e)=>{try{ci(n)}catch(t){return e.addIssue({code:pr.ZodIssueCode.custom,message:t.message,fatal:!0}),pr.NEVER}});function ci(n){if(n=n.toLowerCase().trim(),n.length===0||n.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(n))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(n.endsWith("-")||n.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(n.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(n))throw new Error(`"${n}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(n)||/^\s|\s$/.test(n))throw new Error("Name cannot start or end with a space or dot.");if(n.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(n==="none")throw new Error("Name cannot be 'none'.");if(n.match(Kx))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ns=pr.preprocess(n=>n===null?"":n,pr.union([pr.string().url(),pr.literal("")])).optional();var Ju=Bt.object({id:Bt.string(),name:Ms,description:Bt.string().optional().nullish(),baseUrl:Ns.nullish(),schemaVersion:Bt.string(),advanced:Bt.unknown().optional(),retries:Bt.number(),envs:Bt.array(Rs).nullish(),parameters:As.nullish()}),Yx=Bt.object({createdAt:Bt.coerce.date(),updatedAt:Bt.coerce.date(),schedule:Yr.nullish(),notification:Xr.nullish(),createdBy:Bt.string(),organizationId:Bt.string()}),Xx=Ju.merge(Yx),BF=Xx.extend({steps:oc.array()}),jF=Ju.extend({steps:oc.array()});import{z as Ct}from"zod";var Zu=Ct.object({startedAt:Ct.coerce.date(),finishedAt:Ct.coerce.date(),status:Ct.nativeEnum(Ge),message:Ct.string().optional(),data:Ct.unknown().optional()}),Zx=Zu.merge(rc).extend({type:Ct.literal("JAVASCRIPT")}),Qx=Zu.merge(nc).extend({type:Ct.literal("REQUEST")}),eT=Ct.discriminatedUnion("type",[Zx,Qx]),Qu=Ct.object({startedAt:Ct.coerce.date(),finishedAt:Ct.coerce.date().nullish(),status:Ct.nativeEnum(pe),results:eT.array(),failureReason:Ct.string().nullish(),failureDetails:Ss.nullish()});import{z as Et}from"zod";var tT=Et.object({id:Et.string(),organizationId:Et.string(),createdAt:Et.coerce.date(),updatedAt:Et.coerce.date(),createdBy:Et.string(),scheduledAt:Et.coerce.date().nullish(),startedAt:Et.coerce.date().nullish(),finishedAt:Et.coerce.date().nullish(),status:Et.nativeEnum(pe),trigger:Et.nativeEnum(zt),results:Qu.array().nullish(),apiTestName:Et.string().nullish(),apiTestPath:Et.string().nullish(),apiTestId:Et.string().nullish()}),XF=tT.pick({status:!0,startedAt:!0,finishedAt:!0});var di=(t=>(t.TestRun="test-run",t.CreditsUsed="credits-used",t))(di||{}),em=3;function nT(n){return n==="MODULE"||n==="IFRAME"||n==="CONDITIONAL"||n==="SECTION"||n==="RESOLVED_MODULE"}function ic(n){if(!nT(n))switch(n){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function sc(n){switch(n.type){case"AI_EXTRACT":return 3;case"AI_ASSERTION":return em;case"AI_WAIT":return 3;case"CAPTCHA":return 3;case"VISUAL_DIFF":return 3;case"CLICK":return n.useSelector?0:1;case"TYPE":return n.useSelector||!n.target||n.target.type!=="description"?0:1;case"SELECT_OPTION":return n.useSelector?0:1;case"HOVER":return n.useSelector?0:1;case"DRAG":return n.useSelector?0:1;case"ELEMENT_CHECK":return n.useSelector?0:1;case"MOUSE_DRAG":return n.useSelector?0:1;case"FOCUS":return n.useSelector?0:1;case"BLUR":return n.useSelector?0:1;case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":return n.target?.type==="description"?1:0;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"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}var _s=class{async reportBillableEvent(e,t,r){}async reportCreditsUsed(e,t,r,o){}};function ac(n,e){return{...n,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as rT,splitCookiesString as oT}from"set-cookie-parser";import{z as ie}from"zod";var lc=ie.object({name:ie.string(),value:ie.string(),url:ie.string().optional(),domain:ie.string().optional(),path:ie.string().optional(),expires:ie.number().default(Date.now()/1e3+60*60*24*365),httpOnly:ie.boolean().optional(),secure:ie.boolean().default(!0),sameSite:ie.union([ie.literal("Strict"),ie.literal("Lax"),ie.literal("None")]).default("None")});function Fs(n,e){let t=[],r=oT(n);for(let o of r){let i=rT(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let s;if(i.sameSite){let d=i.sameSite.trim().toLowerCase();if(d==="strict")s="Strict";else if(d==="lax")s="Lax";else if(d==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let a=lc.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:s});t.push(a);let l=[a.name,...Object.keys(a)].map(d=>d.toLowerCase()),c=o.match(/\b(\S+)=([^;]*)/g);if(c)for(let d of c){let[p,u]=d.split("=");if(!p||!u)throw new Error(`Invalid key-value pair in cookie: ${d}`);l.includes(p.toLowerCase())||t.push({...a,name:p,value:u})}}return t}var iT=ie.object({origin:ie.string(),localStorage:ie.array(ie.object({name:ie.string(),value:ie.string()}))}),sT=ie.object({entries:ie.record(ie.string(),ie.array(ie.tuple([ie.unknown(),ie.unknown()]))),version:ie.number().optional()}),Ds=ie.object({cookies:lc.array().optional(),origins:iT.array().optional(),idb:ie.record(ie.string(),sT).optional().describe("key is db name")});function Us(n,e){let t=[];return n.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=lc.safeParse({name:r.key,...r});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}var bD=new Set(Object.values(He));var aT={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_WAIT:"AI wait",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",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:"Local storage",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",SUCCESS:"Done"},SD={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_WAIT:[],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"],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:[],SUCCESS:[]},wD={AI_ACTION:"Ask AI achieve a specific goal. Caches the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page, retrying until a configurable timeout.",AI_WAIT:"Wait until AI considers a condition to be true.",CLICK:"Click on an element on the page based on a description.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page based on a description.",HOVER:"Hover over an element on the page based on a description.",FILE_UPLOAD:"Automatically upload a file when the next file chooser is activated.",FOCUS:"Focus an element on the page based on a description.",BLUR:"Remove focus from an element on the page based on a description.",SELECT_OPTION:"Select an option from an HTML Select <select> element based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using 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 local storage 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.",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 JSON snapshot including cookies, local storage, and IndexDB entries.",AUTH_SAVE:"Save auth state (cookies, local storage) into a JavaScript object format usable by 'Load auth state'.",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 state using pre-built conditions, including URL and content checks.",WAIT_FOR_URL:"Wait for the active page's URL to match a specific URL or glob pattern. If a new tab is opened, this command will wait for the new tab's URL to match instead.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the clipboard contents.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import{z as j}from"zod";var ED=j.object({body:j.string(),to:j.string(),from:j.string()}),AD=j.object({from:j.string().optional(),to:j.string(),timeout:j.number().optional(),beforeDate:j.string().pipe(j.coerce.date()).or(j.date()).optional(),afterDate:j.string().pipe(j.coerce.date()).or(j.date()).optional()}),RD=j.object({to:j.string(),from:j.string(),subject:j.string(),body:j.string()}),ID=j.object({inbox:j.string(),afterDate:j.string().pipe(j.coerce.date()).or(j.date()).optional(),timeout:j.number().optional(),trimWhitespace:j.boolean().optional()}),PD=j.object({inbox:j.string(),limit:j.number().optional(),afterDate:j.string().pipe(j.coerce.date()).or(j.date()).optional(),trimWhitespace:j.boolean().optional()});var tm=j.object({result:j.unknown(),variableUpdates:j.record(j.string(),j.unknown()).optional(),persistentVariableUpdates:j.record(j.string(),j.unknown()).optional(),error:j.string().optional(),success:j.boolean()}),LD=j.object({id:j.string().optional(),orgId:j.string(),momenticLambdaAuthHash:j.string(),code:j.string(),fragment:j.boolean(),state:ii,timeoutMs:j.number().optional()}),Zr=15e3;import*as ct from"zod";he(ct);var lT=ct.object({url:ct.string(),lineNumber:ct.number(),columnNumber:ct.number()}).openapi({ref:"CodeLocation"}),zs=ct.object({timestamp:ct.number(),text:ct.string(),type:ct.string(),tabIndex:ct.number(),args:ct.unknown().array().optional(),url:ct.string().optional(),location:lT.optional()}).openapi({ref:"ConsoleLog"}),nm=zs.array(),cT=nm.array();import*as dc from"zod";import{z as R}from"zod";var dT=R.object({name:R.string(),version:R.string(),comment:R.string().optional()}),pT=R.object({name:R.string(),version:R.string(),comment:R.string().optional()}),uT=R.object({onContentLoad:R.number().optional(),onLoad:R.number().optional(),comment:R.string().optional()}),om=R.object({startedDateTime:R.string(),id:R.string(),title:R.string().optional(),pageTimings:uT,comment:R.string().optional()}),mT=R.array(om),hT=R.object({name:R.string(),value:R.string(),path:R.string().optional(),domain:R.string().optional(),expires:R.string().optional(),httpOnly:R.boolean().optional(),secure:R.boolean().optional(),comment:R.string().optional()}),im=R.array(hT),gT=R.object({name:R.string(),value:R.string(),comment:R.string().optional()}),sm=R.array(gT),fT=R.object({name:R.string(),value:R.string(),comment:R.string().optional()}),yT=R.array(fT),bT=R.object({name:R.string(),value:R.string().optional(),fileName:R.string().optional(),contentType:R.string().optional(),comment:R.string().optional()}),ST=R.array(bT),wT=R.object({mimeType:R.string(),params:ST,text:R.string(),comment:R.string().optional()}),vT=R.object({method:R.string(),url:R.string(),httpVersion:R.string().optional(),cookies:im,headers:sm,queryString:yT,postData:wT.optional(),headersSize:R.number().optional(),bodySize:R.number().optional(),comment:R.string().optional()}),xT=R.object({size:R.number().optional(),compression:R.number().optional(),mimeType:R.string().optional(),text:R.string().optional(),encoding:R.string().optional(),comment:R.string().optional()}),TT=R.object({status:R.number(),statusText:R.string(),httpVersion:R.string().optional(),cookies:im,headers:sm,content:xT,redirectURL:R.string().optional(),headersSize:R.number().optional(),bodySize:R.number().optional(),comment:R.string().optional()}),rm=R.object({expires:R.string().optional(),lastAccess:R.string(),eTag:R.string(),hitCount:R.number(),comment:R.string().optional()}),CT=R.object({beforeRequest:rm.optional(),afterRequest:rm.optional(),comment:R.string().optional()}),ET=R.object({blocked:R.number().optional(),dns:R.number().optional(),connect:R.number().optional(),send:R.number(),wait:R.number(),receive:R.number(),ssl:R.number().optional(),comment:R.string().optional()}),am=R.object({pageref:R.string().optional(),startedDateTime:R.string(),time:R.number().optional(),request:vT,response:TT.optional(),cache:CT.optional(),timings:ET,serverIPAddress:R.string().optional(),connection:R.string().optional(),comment:R.string().optional(),_resourceType:R.string().optional()}),AT=R.array(am),RT=R.object({version:R.string().default("1.1"),creator:dT.optional(),browser:pT.optional(),pages:mT.optional(),entries:AT,comment:R.string().optional()}),IT=R.object({log:RT}),lm=R.record(R.string(),om),cm=R.record(R.string(),am);function cc(n,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(n).sort((t,r)=>new Date(t.startedDateTime).getTime()-new Date(r.startedDateTime).getTime()),entries:Object.values(e).sort((t,r)=>new Date(t.startedDateTime).getTime()-new Date(r.startedDateTime).getTime())}}}he(dc);var PT=dc.object({logsPerPage:zs.array().array(),harPages:lm.optional(),harEntries:cm.optional()}).openapi({ref:"DebugData"});var Bs=class extends Error{constructor(e,t,r,o={}){super(`The ${r} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function dm(n){for(let e of Object.values(oe))if(n.includes(e))return e}var A=class extends Error{reason;constructor(e,t,r){let o=!1;for(let s of Object.values(oe))if(t.startsWith(s)){o=!0,e=s;break}let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,r?.errOptions),this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e,Object.defineProperty(this,"lastScreenshotBuffer",{value:r?.lastScreenshotBuffer,enumerable:!1})}getLastScreenshotBuffer(){return"lastScreenshotBuffer"in this?this.lastScreenshotBuffer:void 0}toString(){return this.message}toJSON(){return{message:this.message}}},Fn=class extends Error{decisions;constructor(e,t,r={}){super(e,r),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
@@ -11,8 +11,8 @@ ${this.decisions.map(e=>e.toString()).join(`
11
11
  `).map((d,p)=>p>0?` ${d}`:d).join(`
12
12
  `)),console.log(t(` ${a}:`,c))}}else if(o)for(let s of o){let a=s;typeof s=="object"&&(a=JSON.stringify(s,void 0,2),a=a.split(`
13
13
  `).map((l,c)=>c>0?` ${l}`:l).join(`
14
- `)),console.log(" ",t(a))}}setMinLevel(e){this.minLogLevel=e}log(...e){this.logWithLevel(1,un.reset,...e)}info(...e){this.logWithLevel(1,un.blue,...e)}debug(...e){this.logWithLevel(0,un.dim,...e)}warn(...e){this.logWithLevel(2,un.yellow,...e)}error(...e){this.logWithLevel(3,un.red,...e)}success(...e){this.logWithLevel(4,un.green,...e)}dimmed(...e){this.logWithLevel(1,un.dim,...e)}underline(...e){this.logWithLevel(2,un.underline,...e)}bold(...e){this.logWithLevel(2,un.bold,...e)}grey(...e){this.logWithLevel(0,un.grey,...e)}child(e){return new n(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},S=new mc(1,{}),mr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>mr,flush:()=>{},bindings:()=>({})},js={},hr=({logger:n,logKey:e,maxCount:t,intervalMs:r},o,i,...s)=>{let a=js[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},js[e]=a),a.totalCount++,a.count<t&&(a.count++,n.debug(o,i,...s)),a.timer=setTimeout(()=>{let l=js[e];l?.totalCount!==l?.count&&n.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete js[e]},r)};import{z as Ke}from"zod";var xm=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"),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:Al.nullish()}),sU=xm.extend({steps:Ke.lazy(()=>We.array())}),Tm=5*60*1e3,hc=vt.merge(xm.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as cU}from"date-fns-tz";import{z as gr}from"zod";var gc=gr.object({failureRecovery:gr.boolean().optional(),aiAction:gr.boolean().optional()}),uU=gr.object({ai:gc.optional(),githubAppInstallationId:gr.number().nullish(),gitlabAppAccessToken:gr.string().nullish().optional(),gitlabAppBaseUrl:gr.string().nullish().optional()});import*as T from"zod";var AU=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),RU=Jt.merge(ec),Cm=os,IU=Jt.merge(ec);var PU=Jt.merge($u).extend({useConsensus:T.boolean().optional()}),fc=Ep,LU=Jt.extend({browserState:T.string(),goal:T.string(),screenshot:T.string()}),Em=Fp,OU=Jt.extend({goal:T.string(),browserState:T.string()}),Am=_p,kU=Jt.merge(ju);var MU=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()}),Rm=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()}),Im=mi,Pm=T.string().array(),NU=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")})]),Lm=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"))}),_T=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),_U=_T.array(),FU=T.object({testId:T.string(),schemaVersion:T.string()}).merge(ir),DU=T.object({entries:T.array(Ml),testId:T.string()}),UU=T.object({steps:T.array(T.record(T.unknown())),testId:T.string(),schemaVersion:T.string(),organizationId:T.string()}),Om=Np,zU=T.object({trigger:T.nativeEnum(zt),status:T.nativeEnum(pe),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()}),km=T.object({id:T.string()}),BU=T.object({status:T.nativeEnum(pe),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),jU=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(),trigger:T.nativeEnum(zt),schemaVersion:T.string().optional(),section:T.nativeEnum(Is).optional()}),Mm=T.object({id:T.string()}),FT=Zl.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Nm=FT.array(),$U=Zl.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),_m=T.object({id:T.string()}),HU=T.object({status:T.nativeEnum(pe),finishedAt:Re.optional()}).merge(vs),WU=T.object({screenshot:T.string()}),Fm=T.object({key:T.string()}),Dm=T.object({orgId:T.string(),userId:T.string()}),Um=T.array(fs),zm=T.record(T.string(),T.union([T.string(),T.boolean()])),GU=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),Bm=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),VU=T.object({suiteRunIds:T.string().array()}),jm=Bu.array(),qU=T.object({runGroupIds:T.string().array()}),gi=T.object({uploadUrl:T.string()}),KU=Jt.merge(Hu),YU=Jt.merge(Gu),XU=Jt.merge(Wu),DT=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()}),JU=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(di),properties:DT}).array(),$m=Eu.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),ZU=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),Hm=Ou.array(),QU=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),e1=Jt.extend({chunks:tc.array(),description:T.string().describe("Input to pass to AI"),type:T.union([T.literal("locator"),T.literal("assertion"),T.literal("ai-action")]),softTokenLimit:T.number(),hardTokenLimit:T.number()});import{z as ye}from"zod";var Wm=ye.object({orgId:ye.string(),cacheKeys:ye.string().array()}),r1=ye.object({keyParams:Wm,clientMetadata:ye.string(),lockAcquisitionTimeoutMs:ye.number().optional()}),Gm=ye.object({acquired:ye.boolean(),acquiredByMetadata:ye.string(),keyPrefix:ye.string()}),o1=ye.object({keyPrefix:ye.string(),result:ye.string(),ttlMs:ye.number()}),i1=ye.union([ye.object({keyPrefix:ye.string()}),Wm]),UT=ye.object({remainingTtlMs:ye.number(),value:ye.string().nullish()}),s1=ye.object({results:ye.record(ye.string(),UT),activeLocks:ye.string().array()}),Vm=0,qm=5*60*1e3;import{z as Zt}from"zod";var Km="test",Ym="module",Cn=(t=>(t.TEST=`${Km}.yaml`,t.MODULE=`${Ym}.yaml`,t))(Cn||{}),be=(o=>(o.TEST=`momentic/${Km}`,o.MODULE=`momentic/${Ym}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(be||{}),h1=jt.merge(ir),yc=vt.extend({steps:Zt.array(Zt.record(Zt.string(),Zt.unknown())),schemaVersion:Zt.string()}),g1=yc.extend({fileType:Zt.literal(be.MODULE)}),f1=Zt.object({test:Zt.string().describe("YAML for the test, including metadata and steps"),modules:Zt.record(Zt.string(),Zt.string()).describe("Map of module name to YAML for the module")});import{validator as x1}from"@exodus/schemasafe";import{z as C1}from"zod";var Xm=n=>{n.extraHeaders&&(n.extraHeaders=Object.fromEntries(Object.entries(n.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as F1}from"zod";import{z as $s}from"zod";var z1=$s.object({repositoriesIndexed:$s.boolean(),indexingInProgress:$s.boolean(),indexesOutdated:$s.boolean()});import{z as xe}from"zod";var bc=xe.object({assertion:xe.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),zT=xe.object({instruction:xe.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:bc.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.")}),Jm=zT.extend({subSteps:xe.lazy(()=>Jm.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Zm=xe.object({name:xe.string().describe("Short name describing the test plan"),description:xe.string().nullish().transform(n=>n??void 0).describe("Longer form description of the high level goal of the test plan")}),Qm=Zm.extend({id:xe.string(),createdAt:xe.coerce.date(),updatedAt:xe.coerce.date(),updatedBy:xe.string(),createdBy:xe.string(),test:xe.object({id:xe.string(),name:xe.string()}).nullish().transform(n=>n??void 0)}),H1=Qm.extend({testGenRuns:xe.tuple([]).or(xe.tuple([xe.object({id:xe.string(),startedAt:xe.coerce.date(),status:xe.nativeEnum(pe)})]))}),eh=xe.object({preConditions:bc.array(),postConditions:bc.array(),steps:Jm.array()}),W1=Qm.extend({plan:eh.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),BT=Zm.extend({plan:eh.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),G1=BT.array();var _="v1";var Qt=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function jT(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Sc=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){return{"Content-Type":"application/json"}}async sendRequest(e,t,r=3,o=3e4){let i=new AbortController,s=setTimeout(()=>i.abort(),o),a=()=>i.abort();t.signal&&t.signal.addEventListener("abort",a);try{return await this.sendRequestHelper(e,t,Math.max(1,r),i.signal)}finally{clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",a)}}async sendRequestHelper(e,t,r,o){let i=r,s,a={path:e,baseUrl:this.baseUrl,method:t.method};for(;r>0;)try{r--;let l=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:this.getHeaders(),signal:o});if(!l.ok){let d=await jT(l);throw new Qt(l.status,d,`Request to ${e} failed with status ${l.status}: ${d}`)}let c;return l.status===204?c=await l.text():c=await l.json(),this.logger&&!t.noLog&&c&&this.logger.debug({result:c,status:l.status,...a},"Got response from Momentic server"),c}catch(l){if(s=l,this.logger&&this.logger.warn({...a,err:l},`Got error response from Momentic server${r>0?", retrying":""}`),l instanceof Qt&&l.status>=400&&l.status<500||r===0)throw l;let c=1500,d=i-r,p=Math.min(c*Math.pow(2,d-1),3e4);await new Promise(u=>setTimeout(u,p))}throw s}},At=class extends Sc{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var dt=class extends At{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${_}/auth/check`,{method:"GET",noLog:!0},10,3e3),{orgId:t,userId:r}=Dm.parse(e);return{orgId:t,userId:r}}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${_}/runs/status`,{method:"POST",body:e,noLog:!0});return Nm.parse(t)}async createRunGroup(e){let t=await this.sendRequest(`/${_}/run-groups`,{method:"POST",body:e,noLog:!0},10);return km.parse(t)}async updateRunGroup(e,t){await this.sendRequest(`/${_}/run-groups/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRun(e){let t=await this.sendRequest(`/${_}/runs`,{method:"POST",body:e,noLog:!0},10);return Mm.parse(t)}async updateRun(e,t){await this.sendRequest(`/${_}/runs/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRunAttempt(e){let t=await this.sendRequest(`/${_}/runs/${e}/attempts`,{method:"POST",noLog:!0},10);return _m.parse(t)}async updateRunAttempt(e,t,r){await this.sendRequest(`/${_}/runs/${e}/attempts/${t}`,{method:"PATCH",body:r,noLog:!0},5)}async getTest(e){let t=await this.sendRequest(`/${_}/tests/${e}`,{method:"GET"});return Im.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${_}/tests`,{method:"GET"});return Pm.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${_}/tests/export`,{method:"POST",body:e});return Lm.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${_}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${_}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${_}/cache`,{method:"POST",body:e},10);return Om.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${_}/tests/queue`,{method:"POST",body:e});return Rm.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${_}/screenshots`,{method:"POST",body:e,noLog:!0},3,5e3);return Fm.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${_}/environments`,{method:"GET"});return Um.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${_}/environments/${e}`,{method:"GET"});return fs.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${_}/auth/flags`,{method:"GET",noLog:!0},10);return zm.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${_}/result-cache/lock`,{method:"POST",body:e,signal:t});return Gm.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${_}/result-cache/lock`,{method:"DELETE",body:{key:e}})}async deleteCacheResult(e){await this.sendRequest(`/${_}/result-cache/entry`,{method:"DELETE",body:e})}async setCacheResult(e){await this.sendRequest(`/${_}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${_}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${_}/suites/queue`,{method:"POST",body:e});return Bm.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},r=await this.sendRequest(`/${_}/suites/status`,{method:"POST",body:t,noLog:!0});return jm.parse(r)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${_}/run-groups/status`,{method:"POST",body:t,noLog:!0});return Mu.array().parse(r)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${_}/cache/lastUsedAt`,{method:"PATCH",body:e,noLog:!0})}catch(r){t.error({err:r},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${_}/test-fragments/`,{method:"POST",body:e})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async uploadRunNetworkLogs(e,t,r){try{await this.sendRequest(`/${_}/runs/${t}/network-logs`,{method:"POST",body:r,noLog:!0})}catch(o){e.error({err:o},"Failed to upload network logs")}}async uploadRunConsoleLogs(e,t,r){try{await this.sendRequest(`/${_}/runs/${t}/console-logs`,{method:"POST",body:r,noLog:!0})}catch(o){e.error({err:o},"Failed to upload console logs")}}async generateConsoleLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${_}/runs/${t}/attempts/${r}/console-logs`,{method:"POST",noLog:!0});return gi.parse(o)}async generateNetworkLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${_}/runs/${t}/attempts/${r}/network-logs`,{method:"POST",noLog:!0});return gi.parse(o)}async generateHtmlSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${_}/snapshots/${t}/html`,{method:"POST",noLog:!0});return gi.parse(r)}async generateA11yTreeSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${_}/snapshots/${t}/a11y`,{method:"POST",noLog:!0});return gi.parse(r)}async reportBillableEvents(e,t){try{await this.sendRequest(`/${_}/billing/events`,{method:"POST",body:t,noLog:!0},10,5e3)}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${_}/test-fragments/${e}`,{method:"GET",noLog:!0});return $m.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${_}/test-fragments/${e}`,{method:"PATCH",body:t})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${_}/results/tests/${e}`,{method:"POST",body:t});return Hm.parse(r)}};import{randomUUID as th}from"crypto";var Hs=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??th(),properties:ac({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??th(),properties:ac({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var Qr=class{constructor(e,t){this.client=e;this.orgId=t}async storeConsoleLogsForRun(e,t,r,o){return this.client.uploadRunConsoleLogs(e,r,o)}async storeNetworkLogsForRun(e,t,r,o){return this.client.uploadRunNetworkLogs(e,r,o)}async storeConsoleLogsForRunAttempt(e,t,r,o,i){try{let s=JSON.stringify(i),{uploadUrl:a}=await this.client.generateConsoleLogsForRunAttemptUploadUrl(e,r,o),l=await fetch(a,{method:"PUT",body:s,headers:{"Content-Type":"application/json"}});if(!l.ok)throw new Error(`Failed to upload network logs: ${l.statusText}`)}catch(s){e.error({err:s},"Failed to upload console logs")}}async storeNetworkLogsForRunAttempt(e,t,r,o,i){let s=JSON.stringify(i);try{let{uploadUrl:a}=await this.client.generateNetworkLogsForRunAttemptUploadUrl(e,r,o),l=await fetch(a,{method:"PUT",body:s,headers:{"Content-Type":"application/json"}});if(!l.ok)throw new Error(`Failed to upload network logs: ${l.statusText}`)}catch(a){e.error({err:a},"Failed to upload network logs")}}async storeHtmlSnapshot(e,t,r,o){try{let{uploadUrl:i}=await this.client.generateHtmlSnapshotUploadUrl(e,r),s=await fetch(i,{method:"PUT",body:o,headers:{"Content-Type":"text/html"}});if(!s.ok)throw new Error(`Failed to upload network logs: ${s.statusText}`)}catch(i){e.error({err:i},"Failed to upload html snapshot")}}async storeA11yTreeSnapshot(e,t,r,o){return Promise.resolve()}};function wc(n){let e={parentChain:[]};return Ws(n,e),e}function Ws(n,e){let{onPresetAction:t,onSimpleStepContainer:r,onConditional:o,earlyStop:i}=n;for(let s of n.steps)switch(s.type){case"PRESET_ACTION":if(t(s,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(s,e)&&i)return!0;e.parentChain.push(s);for(let l of s.blocks)if(t(l.assertion,e)&&i||Ws({...n,steps:l.steps},e)&&i)return!0;if(Ws({...n,steps:s.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":if(r?.(s,e)&&i)return!0;if(s.steps){if(e.parentChain.push(s),Ws({...n,steps:s.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(s,e)&&i)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(s)}}function fi(n,e){let t,r=[];return wc({steps:n,earlyStop:!0,onPresetAction:(o,i)=>o.id===e?(t=o,r=i.parentChain,!0):!1,onConditional:(o,i)=>o.id===e?(t=o,r=i.parentChain,!0):!1,onSimpleStepContainer:(o,i)=>o.id===e?(t=o,r=i.parentChain,!0):!1}),{result:t,parentChain:r}}function nh(n,e){e(n);for(let t in n){let r=n[t];r&&(Array.isArray(r)?Gs(r,e):typeof r=="object"&&nh(r,e))}}function Gs(n,e){for(let t of n)t&&(Array.isArray(t)?Gs(t,e):typeof t=="object"&&nh(t,e))}function eo({steps:n,topLevel:e=!0,...t}){let{stepCacheEntries:r,logger:o,keyPrefix:i}=t,s=[],a=[],l=0,c=(p,u)=>{try{let m=nr.parse(u.value);if(m.type!==p.type){o.warn({parsedCacheEntry:m,command:p},"Not using step cache due to type mismatch"),a.push(u.key);return}p.cache=m.cache,s.push(u.key)}catch(m){a.push(u.key),o.error({err:m,cacheEntry:u},"Not using step cache due to parsing error")}},d=(p,u)=>{let m=$T(p.id,u),h=m.find(g=>!!r[g]);h?c(p,r[h]):a.push(m[0])};for(let p of n)switch(p.type){case"RESOLVED_MODULE":{l+=p.steps.length;let{hits:m,misses:h}=eo({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=p.steps?.length??0,!p.steps?.length)break;let{hits:m,misses:h}=eo({...t,steps:p.steps,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!xl.includes(p.command.type)||p.command.type==="TYPE"&&!p.command.target||p.command.type==="MOUSE_DRAG"&&!p.command.target||"cache"in p.command&&p.command.cache)continue;l++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){l++,d(m.assertion.command,i),l+=m.steps.length;let{hits:h,misses:g}=eo({...t,steps:m.steps,topLevel:!1});s=s.concat(h),a=a.concat(g);break}if(p.elseSteps){l+=p.elseSteps.length;let{hits:m,misses:h}=eo({...t,steps:p.elseSteps,topLevel:!1});s=s.concat(m),a=a.concat(h)}break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(p)}return e&&l&&a.length>0&&o.debug({totalSteps:l,cacheMisses:a,cacheHits:s,cacheEntries:r.length},"Step cache did not fully resolve"),{hits:s,misses:a}}function rh(n,e){return e?`${e}:${n}`:n}function $T(n,e){let t=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let i=[...r.slice(o),n];t.push(i.join(":"))}return t.reverse(),t}function oh(n){let{moduleStepParents:e=[],moduleIdParents:t=[]}=n;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
15
- ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length;o>0;o--){let i=t[o-1],s=e.slice(o,e.length).join(":");r.push({key:rh(n.id,s),moduleId:i,organizationId:n.orgId,value:n.value})}return r.push({key:rh(n.id,e.join(":")),organizationId:n.orgId,value:n.value,testId:n.testId}),r}function ih(n){switch(n.type){case"DRAG":{if(n.fromTarget.type==="coordinates"||n.toTarget.type==="coordinates"||!n.fromTarget?.a11yData||!n.toTarget?.a11yData)return;n.cache={fromTarget:n.fromTarget.a11yData,toTarget:n.toTarget.a11yData},delete n.fromTarget.a11yData,delete n.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"ELEMENT_CHECK":case"BLUR":{if(n.target?.type==="coordinates"||!n.target?.a11yData)return;n.cache={target:n.target.a11yData},delete n.target.a11yData;return}default:return}}function sh(n){let e=new Set;return Gs(n,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let r=t.moduleId;typeof r=="string"&&!e.has(r)&&e.add(r)}}),e}function ah(n,e,t){e.length&&(n.type==="DRAG"?e.length!==2||!e.every(r=>r.cache)?t.warn({newTargets:e,cmd:n},"New targets for step are incorrect"):n.fromTarget.type==="description"&&n.toTarget.type==="description"&&(n.cache={fromTarget:e[0].cache,toTarget:e[1].cache}):e.length!==1||!e[0]?.cache?t.warn({newTargets:e,cmd:n},"New targets for step are incorrect"):"target"in n&&n.target&&n.target.type==="description"&&(n.cache={target:e[0].cache}))}function Ne(n,e,t=!1){return n.length<e?n:n.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var fr={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with"},yr={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with"},vc={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},xc={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function HT(n){switch(n.type){case"ELEMENT_CONTENT":return`${n.negated?yr[n.operation]:fr[n.operation]} '${n.value}'`;case"ELEMENT_ATTRIBUTE":{let t=n.negated?yr[n.operation]:fr[n.operation];return`attribute '${n.attr}' ${t} '${n.value}'`}case"ELEMENT_EXISTENCE":return n.negated?xc[n.condition]:vc[n.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}var wj={CONTENT:"The page"};function WT(n){switch(n.type){case"VALUE":return`the option with value ${n.value}`;case"LABEL":return`the option with label ${n.label}`;case"INDEX":return`the option at index ${n.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function Tc(n){switch(n.type){case"SUBSTRING":return`match substring '${n.url}'`;case"REGEX":return`match regex '${n.regex}'`;case"GLOB":return`match glob '${n.glob}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function GT(n){switch(n.type){case"CONTENT":return`${n.negated?yr.CONTAINS:fr.CONTAINS} '${n.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function br(n){switch(n.type){case"SUCCESS":return n.condition?.assertion?`Check success condition: ${n.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${n.goal}`;case"NAVIGATE":return`Go to URL: ${Ne(n.url,30)}`;case"DIALOG":return`Automatically ${n.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 ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${lt(n.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${lt(n.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${lt(n.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${lt(n.target)}`:""}`;case"WAIT":return`Wait for ${n.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(n.target?.type==="coordinates")return`Click at coordinates: ${lt(n.target)}`;let t="";return n.target?.elementDescriptor.length?t=` on element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` on element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Click${t}`}case"FOCUS":return`Focus ${lt(n.target)}`;case"BLUR":return`Focus ${lt(n.target)}`;case"DRAG":return`Drag ${lt(n.fromTarget)} onto ${lt(n.toTarget)}`;case"MOUSE_DRAG":return n.target?.type==="description"&&n.target.elementDescriptor?`Click and drag ${lt(n.target)} by ${n.deltaX}px horizontally, ${n.deltaY}px vertically`:`Click and drag mouse by ${n.deltaX}px horizontally, ${n.deltaY}px vertically`;case"TYPE":{let t="";return n.target?.type==="coordinates"?t=` in element at coordinates: ${lt(n.target)}`:n.target?.elementDescriptor.length?t=` in element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` in element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Type '${n.value}'${t||""}`}case"HOVER":{let t="";return n.target.type==="coordinates"?t=` over coordinates: ${lt(n.target)}`:n.target.elementDescriptor.length>0?t=` over element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` over element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Hover${t}`}case"PRESS":return`Press ${n.value}`;case"SELECT_OPTION":{let t="",r=n.option??WT(n.choice);return n.target.type==="coordinates"?t=` from element at coordinates: ${lt(n.target)}`:n.target.elementDescriptor.length>0?t=` from: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` from: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${r}'${t}`}case"TAB":if(n.url)return`Switch to tab with substring: ${n.url}`;if(n.action)switch(n.action.type){case"SUBSTRING":return`Switch to tab with substring: ${n.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${n.action.pattern}`;case"INDEX":return`Switch to tab at index: ${n.action.index}`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${n.url}`;case"REQUEST":return`Send ${n.method} request to ${n.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${n.url}`;case"COOKIE":return`Set cookie: ${n.value}`;case"LOCAL_STORAGE":return`Set local storage: ${n.key}: ${n.value}`;case"JAVASCRIPT":return`Run JavaScript: ${Ne(n.code,30)}`;case"AI_ASSERTION":return`Assertion: '${n.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${n.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${n.target?`for element: ${lt(n.target)}`:"for entire page"}`;case"FILE_UPLOAD":return n.fileSource.type==="URL"?`Upload file: ${n.fileSource.url}`:`Upload file: ${n.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${lt(n.target)} ${HT(n.assertion)}`;case"PAGE_CHECK":return`Assert the page ${GT(n.assertion)}`;case"WAIT_FOR_URL":return n.url?`Wait for page URL to match: ${n.url}`:n.matcher?`Wait for page URL to ${Tc(n.matcher)}`:"Wait for page URL to match";case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function lh(n){let e=[];for(let t of n){t.sort((s,a)=>s.timestamp-a.timestamp);let r=[],o,i=1;for(let s of t)o&&o.text===s.text&&o.type===s.type&&JSON.stringify(o.args??null)===JSON.stringify(s.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:r.push(o)),o=s,i=1);o&&r.push(o),e.push(r)}return e}import{cloneDeep as Cj,unset as Ej}from"lodash-es";function En(n){switch(n.type){case"AI_ACTION":return`AI action: ${Ne(n.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Ne(n.text,100)}`;case"PRESET_ACTION":return br(n.command);case"MODULE":return`Module: ${n.id}`;case"RESOLVED_MODULE":return`Module: ${n.name}`;case"CONDITIONAL":return"Conditional step";case"IFRAME":return"Frame step";case"SECTION":return`Section${n.description?`with goal: ${Ne(n.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(n)}}var VT="[FAILED]";async function dh(n,{numScreenshots:e=1,addIndices:t=!0,includeBeforeScreenshots:r=!1,includeDomState:o=!1,recursive:i=!0}){let s=[],a;for(let l=0;l<n.length;l++){let c=n[l],d=i?Sr(c):En(c),p={description:`Step ${l}: ${d}`,startedAt:c.startedAt,finishedAt:c.finishedAt,beforeUrl:c.beforeUrl,afterUrl:c.afterUrl,message:c.message!=="Successfully executed preset action."?c.message:void 0,index:t?l:void 0};if(c.status==="FAILED"){p.description=`${VT} ${p.description}`,t&&(a=l);try{let m=Uu.array().parse(c.details);for(let h of m)"pageState"in h&&o&&(p.pageState=h.pageState)}catch{}}e>0&&l>=n.length-e&&(p.afterScreenshot=c.afterScreenshot,r&&(p.beforeScreenshot=c.beforeScreenshot));let u=["beforeScreenshot","afterScreenshot"];for(let m of u){let h=p[m];if(h?.startsWith("http")){let f=await(await fetch(h)).arrayBuffer();p[m]=`data:image/jpeg;base64,${Buffer.from(f).toString("base64")}`}else h&&(p[m]=h.startsWith("data:")?h:`data:image/jpeg;base64,${h}`)}s.push(p)}return{results:s,failureIndex:a}}function Sr(n){let e=En(n);switch(n.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":e+=`
14
+ `)),console.log(" ",t(a))}}setMinLevel(e){this.minLogLevel=e}log(...e){this.logWithLevel(1,un.reset,...e)}info(...e){this.logWithLevel(1,un.blue,...e)}debug(...e){this.logWithLevel(0,un.dim,...e)}warn(...e){this.logWithLevel(2,un.yellow,...e)}error(...e){this.logWithLevel(3,un.red,...e)}success(...e){this.logWithLevel(4,un.green,...e)}dimmed(...e){this.logWithLevel(1,un.dim,...e)}underline(...e){this.logWithLevel(2,un.underline,...e)}bold(...e){this.logWithLevel(2,un.bold,...e)}grey(...e){this.logWithLevel(0,un.grey,...e)}child(e){return new n(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},S=new mc(1,{}),mr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>mr,flush:()=>{},bindings:()=>({})},js={},hr=({logger:n,logKey:e,maxCount:t,intervalMs:r},o,i,...s)=>{let a=js[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},js[e]=a),a.totalCount++,a.count<t&&(a.count++,n.debug(o,i,...s)),a.timer=setTimeout(()=>{let l=js[e];l?.totalCount!==l?.count&&n.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete js[e]},r)};import{z as Ke}from"zod";var xm=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"),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:Al.nullish()}),sU=xm.extend({steps:Ke.lazy(()=>We.array())}),Tm=5*60*1e3,hc=vt.merge(xm.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as cU}from"date-fns-tz";import{z as gr}from"zod";var gc=gr.object({failureRecovery:gr.boolean().optional(),aiAction:gr.boolean().optional()}),uU=gr.object({ai:gc.optional(),githubAppInstallationId:gr.number().nullish(),gitlabAppAccessToken:gr.string().nullish().optional(),gitlabAppBaseUrl:gr.string().nullish().optional()});import*as T from"zod";var AU=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),RU=Jt.merge(ec),Cm=os,IU=Jt.merge(ec);var PU=Jt.merge($u).extend({useConsensus:T.boolean().optional()}),fc=Ep,LU=Jt.extend({browserState:T.string(),goal:T.string(),screenshot:T.string()}),Em=Fp,OU=Jt.extend({goal:T.string(),browserState:T.string()}),Am=_p,kU=Jt.merge(ju);var MU=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()}),Rm=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()}),Im=mi,Pm=T.string().array(),NU=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")})]),Lm=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"))}),_T=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),_U=_T.array(),FU=T.object({testId:T.string(),schemaVersion:T.string()}).merge(ir),DU=T.object({entries:T.array(Ml),testId:T.string()}),UU=T.object({steps:T.array(T.record(T.unknown())),testId:T.string(),schemaVersion:T.string(),organizationId:T.string()}),Om=Np,zU=T.object({trigger:T.nativeEnum(zt),status:T.nativeEnum(pe),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()}),km=T.object({id:T.string()}),BU=T.object({status:T.nativeEnum(pe),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),jU=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(),trigger:T.nativeEnum(zt),schemaVersion:T.string().optional(),section:T.nativeEnum(Is).optional()}),Mm=T.object({id:T.string()}),FT=Zl.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Nm=FT.array(),$U=Zl.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),_m=T.object({id:T.string()}),HU=T.object({status:T.nativeEnum(pe),finishedAt:Re.optional()}).merge(vs),WU=T.object({screenshot:T.string()}),Fm=T.object({key:T.string()}),Dm=T.object({orgId:T.string(),userId:T.string()}),Um=T.array(fs),zm=T.record(T.string(),T.union([T.string(),T.boolean()])),GU=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),Bm=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),VU=T.object({suiteRunIds:T.string().array()}),jm=Bu.array(),qU=T.object({runGroupIds:T.string().array()}),gi=T.object({uploadUrl:T.string()}),KU=Jt.merge(Hu),YU=Jt.merge(Gu),XU=Jt.merge(Wu),DT=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()}),JU=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(di),properties:DT}).array(),$m=Eu.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),ZU=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),Hm=Ou.array(),QU=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),e1=Jt.extend({chunks:tc.array(),description:T.string().describe("Input to pass to AI"),type:T.union([T.literal("locator"),T.literal("assertion"),T.literal("ai-action")]),softTokenLimit:T.number(),hardTokenLimit:T.number()});import{z as ye}from"zod";var Wm=ye.object({orgId:ye.string(),cacheKeys:ye.string().array()}),r1=ye.object({keyParams:Wm,clientMetadata:ye.string(),lockAcquisitionTimeoutMs:ye.number().optional()}),Gm=ye.object({acquired:ye.boolean(),acquiredByMetadata:ye.string(),keyPrefix:ye.string()}),o1=ye.object({keyPrefix:ye.string(),result:ye.string(),ttlMs:ye.number()}),i1=ye.union([ye.object({keyPrefix:ye.string()}),Wm]),UT=ye.object({remainingTtlMs:ye.number(),value:ye.string().nullish()}),s1=ye.object({results:ye.record(ye.string(),UT),activeLocks:ye.string().array()}),Vm=0,qm=5*60*1e3;import{z as Zt}from"zod";var Km="test",Ym="module",Cn=(t=>(t.TEST=`${Km}.yaml`,t.MODULE=`${Ym}.yaml`,t))(Cn||{}),be=(o=>(o.TEST=`momentic/${Km}`,o.MODULE=`momentic/${Ym}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(be||{}),h1=jt.merge(ir),yc=vt.extend({steps:Zt.array(Zt.record(Zt.string(),Zt.unknown())),schemaVersion:Zt.string()}),g1=yc.extend({fileType:Zt.literal(be.MODULE)}),f1=Zt.object({test:Zt.string().describe("YAML for the test, including metadata and steps"),modules:Zt.record(Zt.string(),Zt.string()).describe("Map of module name to YAML for the module")});import{validator as x1}from"@exodus/schemasafe";var Xm=n=>{n.extraHeaders&&(n.extraHeaders=Object.fromEntries(Object.entries(n.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as N1}from"zod";import{z as $s}from"zod";var D1=$s.object({repositoriesIndexed:$s.boolean(),indexingInProgress:$s.boolean(),indexesOutdated:$s.boolean()});import{z as xe}from"zod";var bc=xe.object({assertion:xe.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),zT=xe.object({instruction:xe.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:bc.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.")}),Jm=zT.extend({subSteps:xe.lazy(()=>Jm.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Zm=xe.object({name:xe.string().describe("Short name describing the test plan"),description:xe.string().nullish().transform(n=>n??void 0).describe("Longer form description of the high level goal of the test plan")}),Qm=Zm.extend({id:xe.string(),createdAt:xe.coerce.date(),updatedAt:xe.coerce.date(),updatedBy:xe.string(),createdBy:xe.string(),test:xe.object({id:xe.string(),name:xe.string()}).nullish().transform(n=>n??void 0)}),j1=Qm.extend({testGenRuns:xe.tuple([]).or(xe.tuple([xe.object({id:xe.string(),startedAt:xe.coerce.date(),status:xe.nativeEnum(pe)})]))}),eh=xe.object({preConditions:bc.array(),postConditions:bc.array(),steps:Jm.array()}),$1=Qm.extend({plan:eh.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),BT=Zm.extend({plan:eh.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),H1=BT.array();var _="v1";var Qt=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function jT(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Sc=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){return{"Content-Type":"application/json"}}async sendRequest(e,t,r=3,o=3e4){let i=new AbortController,s=setTimeout(()=>i.abort(),o),a=()=>i.abort();t.signal&&t.signal.addEventListener("abort",a);try{return await this.sendRequestHelper(e,t,Math.max(1,r),i.signal)}finally{clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",a)}}async sendRequestHelper(e,t,r,o){let i=r,s,a={path:e,baseUrl:this.baseUrl,method:t.method};for(;r>0;)try{r--;let l=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:this.getHeaders(),signal:o});if(!l.ok){let d=await jT(l);throw new Qt(l.status,d,`Request to ${e} failed with status ${l.status}: ${d}`)}let c;return l.status===204?c=await l.text():c=await l.json(),this.logger&&!t.noLog&&c&&this.logger.debug({result:c,status:l.status,...a},"Got response from Momentic server"),c}catch(l){if(s=l,this.logger&&this.logger.warn({...a,err:l},`Got error response from Momentic server${r>0?", retrying":""}`),l instanceof Qt&&l.status>=400&&l.status<500||r===0)throw l;let c=1500,d=i-r,p=Math.min(c*Math.pow(2,d-1),3e4);await new Promise(u=>setTimeout(u,p))}throw s}},At=class extends Sc{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var dt=class extends At{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${_}/auth/check`,{method:"GET",noLog:!0},10,3e3),{orgId:t,userId:r}=Dm.parse(e);return{orgId:t,userId:r}}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${_}/runs/status`,{method:"POST",body:e,noLog:!0});return Nm.parse(t)}async createRunGroup(e){let t=await this.sendRequest(`/${_}/run-groups`,{method:"POST",body:e,noLog:!0},10);return km.parse(t)}async updateRunGroup(e,t){await this.sendRequest(`/${_}/run-groups/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRun(e){let t=await this.sendRequest(`/${_}/runs`,{method:"POST",body:e,noLog:!0},10);return Mm.parse(t)}async updateRun(e,t){await this.sendRequest(`/${_}/runs/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRunAttempt(e){let t=await this.sendRequest(`/${_}/runs/${e}/attempts`,{method:"POST",noLog:!0},10);return _m.parse(t)}async updateRunAttempt(e,t,r){await this.sendRequest(`/${_}/runs/${e}/attempts/${t}`,{method:"PATCH",body:r,noLog:!0},5)}async getTest(e){let t=await this.sendRequest(`/${_}/tests/${e}`,{method:"GET"});return Im.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${_}/tests`,{method:"GET"});return Pm.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${_}/tests/export`,{method:"POST",body:e});return Lm.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${_}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${_}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${_}/cache`,{method:"POST",body:e},10);return Om.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${_}/tests/queue`,{method:"POST",body:e});return Rm.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${_}/screenshots`,{method:"POST",body:e,noLog:!0},3,5e3);return Fm.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${_}/environments`,{method:"GET"});return Um.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${_}/environments/${e}`,{method:"GET"});return fs.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${_}/auth/flags`,{method:"GET",noLog:!0},10);return zm.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${_}/result-cache/lock`,{method:"POST",body:e,signal:t});return Gm.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${_}/result-cache/lock`,{method:"DELETE",body:{key:e}})}async deleteCacheResult(e){await this.sendRequest(`/${_}/result-cache/entry`,{method:"DELETE",body:e})}async setCacheResult(e){await this.sendRequest(`/${_}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${_}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${_}/suites/queue`,{method:"POST",body:e});return Bm.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},r=await this.sendRequest(`/${_}/suites/status`,{method:"POST",body:t,noLog:!0});return jm.parse(r)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${_}/run-groups/status`,{method:"POST",body:t,noLog:!0});return Mu.array().parse(r)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${_}/cache/lastUsedAt`,{method:"PATCH",body:e,noLog:!0})}catch(r){t.error({err:r},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${_}/test-fragments/`,{method:"POST",body:e})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async uploadRunNetworkLogs(e,t,r){try{await this.sendRequest(`/${_}/runs/${t}/network-logs`,{method:"POST",body:r,noLog:!0})}catch(o){e.error({err:o},"Failed to upload network logs")}}async uploadRunConsoleLogs(e,t,r){try{await this.sendRequest(`/${_}/runs/${t}/console-logs`,{method:"POST",body:r,noLog:!0})}catch(o){e.error({err:o},"Failed to upload console logs")}}async generateConsoleLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${_}/runs/${t}/attempts/${r}/console-logs`,{method:"POST",noLog:!0});return gi.parse(o)}async generateNetworkLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${_}/runs/${t}/attempts/${r}/network-logs`,{method:"POST",noLog:!0});return gi.parse(o)}async generateHtmlSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${_}/snapshots/${t}/html`,{method:"POST",noLog:!0});return gi.parse(r)}async generateA11yTreeSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${_}/snapshots/${t}/a11y`,{method:"POST",noLog:!0});return gi.parse(r)}async reportBillableEvents(e,t){try{await this.sendRequest(`/${_}/billing/events`,{method:"POST",body:t,noLog:!0},10,5e3)}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${_}/test-fragments/${e}`,{method:"GET",noLog:!0});return $m.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${_}/test-fragments/${e}`,{method:"PATCH",body:t})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${_}/results/tests/${e}`,{method:"POST",body:t});return Hm.parse(r)}};import{randomUUID as th}from"crypto";var Hs=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??th(),properties:ac({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??th(),properties:ac({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var Qr=class{constructor(e,t){this.client=e;this.orgId=t}async storeConsoleLogsForRun(e,t,r,o){return this.client.uploadRunConsoleLogs(e,r,o)}async storeNetworkLogsForRun(e,t,r,o){return this.client.uploadRunNetworkLogs(e,r,o)}async storeConsoleLogsForRunAttempt(e,t,r,o,i){try{let s=JSON.stringify(i),{uploadUrl:a}=await this.client.generateConsoleLogsForRunAttemptUploadUrl(e,r,o),l=await fetch(a,{method:"PUT",body:s,headers:{"Content-Type":"application/json"}});if(!l.ok)throw new Error(`Failed to upload network logs: ${l.statusText}`)}catch(s){e.error({err:s},"Failed to upload console logs")}}async storeNetworkLogsForRunAttempt(e,t,r,o,i){let s=JSON.stringify(i);try{let{uploadUrl:a}=await this.client.generateNetworkLogsForRunAttemptUploadUrl(e,r,o),l=await fetch(a,{method:"PUT",body:s,headers:{"Content-Type":"application/json"}});if(!l.ok)throw new Error(`Failed to upload network logs: ${l.statusText}`)}catch(a){e.error({err:a},"Failed to upload network logs")}}async storeHtmlSnapshot(e,t,r,o){try{let{uploadUrl:i}=await this.client.generateHtmlSnapshotUploadUrl(e,r),s=await fetch(i,{method:"PUT",body:o,headers:{"Content-Type":"text/html"}});if(!s.ok)throw new Error(`Failed to upload network logs: ${s.statusText}`)}catch(i){e.error({err:i},"Failed to upload html snapshot")}}async storeA11yTreeSnapshot(e,t,r,o){return Promise.resolve()}};function wc(n){let e={parentChain:[]};return Ws(n,e),e}function Ws(n,e){let{onPresetAction:t,onSimpleStepContainer:r,onConditional:o,earlyStop:i}=n;for(let s of n.steps)switch(s.type){case"PRESET_ACTION":if(t(s,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(s,e)&&i)return!0;e.parentChain.push(s);for(let l of s.blocks)if(t(l.assertion,e)&&i||Ws({...n,steps:l.steps},e)&&i)return!0;if(Ws({...n,steps:s.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":if(r?.(s,e)&&i)return!0;if(s.steps){if(e.parentChain.push(s),Ws({...n,steps:s.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(s,e)&&i)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(s)}}function fi(n,e){let t,r=[];return wc({steps:n,earlyStop:!0,onPresetAction:(o,i)=>o.id===e?(t=o,r=i.parentChain,!0):!1,onConditional:(o,i)=>o.id===e?(t=o,r=i.parentChain,!0):!1,onSimpleStepContainer:(o,i)=>o.id===e?(t=o,r=i.parentChain,!0):!1}),{result:t,parentChain:r}}function nh(n,e){e(n);for(let t in n){let r=n[t];r&&(Array.isArray(r)?Gs(r,e):typeof r=="object"&&nh(r,e))}}function Gs(n,e){for(let t of n)t&&(Array.isArray(t)?Gs(t,e):typeof t=="object"&&nh(t,e))}function eo({steps:n,topLevel:e=!0,...t}){let{stepCacheEntries:r,logger:o,keyPrefix:i}=t,s=[],a=[],l=0,c=(p,u)=>{try{let m=nr.parse(u.value);if(m.type!==p.type){o.warn({parsedCacheEntry:m,command:p},"Not using step cache due to type mismatch"),a.push(u.key);return}p.cache=m.cache,s.push(u.key)}catch(m){a.push(u.key),o.error({err:m,cacheEntry:u},"Not using step cache due to parsing error")}},d=(p,u)=>{let m=$T(p.id,u),h=m.find(g=>!!r[g]);h?c(p,r[h]):a.push(m[0])};for(let p of n)switch(p.type){case"RESOLVED_MODULE":{l+=p.steps.length;let{hits:m,misses:h}=eo({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=p.steps?.length??0,!p.steps?.length)break;let{hits:m,misses:h}=eo({...t,steps:p.steps,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!xl.includes(p.command.type)||p.command.type==="TYPE"&&!p.command.target||p.command.type==="MOUSE_DRAG"&&!p.command.target||"cache"in p.command&&p.command.cache)continue;l++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){l++,d(m.assertion.command,i),l+=m.steps.length;let{hits:h,misses:g}=eo({...t,steps:m.steps,topLevel:!1});s=s.concat(h),a=a.concat(g);break}if(p.elseSteps){l+=p.elseSteps.length;let{hits:m,misses:h}=eo({...t,steps:p.elseSteps,topLevel:!1});s=s.concat(m),a=a.concat(h)}break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(p)}return e&&l&&a.length>0&&o.debug({totalSteps:l,cacheMisses:a,cacheHits:s,cacheEntries:r.length},"Step cache did not fully resolve"),{hits:s,misses:a}}function rh(n,e){return e?`${e}:${n}`:n}function $T(n,e){let t=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let i=[...r.slice(o),n];t.push(i.join(":"))}return t.reverse(),t}function oh(n){let{moduleStepParents:e=[],moduleIdParents:t=[]}=n;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
15
+ ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length;o>0;o--){let i=t[o-1],s=e.slice(o,e.length).join(":");r.push({key:rh(n.id,s),moduleId:i,organizationId:n.orgId,value:n.value})}return r.push({key:rh(n.id,e.join(":")),organizationId:n.orgId,value:n.value,testId:n.testId}),r}function ih(n){switch(n.type){case"DRAG":{if(n.fromTarget.type==="coordinates"||n.toTarget.type==="coordinates"||!n.fromTarget?.a11yData||!n.toTarget?.a11yData)return;n.cache={fromTarget:n.fromTarget.a11yData,toTarget:n.toTarget.a11yData},delete n.fromTarget.a11yData,delete n.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"ELEMENT_CHECK":case"BLUR":{if(n.target?.type==="coordinates"||!n.target?.a11yData)return;n.cache={target:n.target.a11yData},delete n.target.a11yData;return}default:return}}function sh(n){let e=new Set;return Gs(n,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let r=t.moduleId;typeof r=="string"&&!e.has(r)&&e.add(r)}}),e}function ah(n,e,t){e.length&&(n.type==="DRAG"?e.length!==2||!e.every(r=>r.cache)?t.warn({newTargets:e,cmd:n},"New targets for step are incorrect"):n.fromTarget.type==="description"&&n.toTarget.type==="description"&&(n.cache={fromTarget:e[0].cache,toTarget:e[1].cache}):e.length!==1||!e[0]?.cache?t.warn({newTargets:e,cmd:n},"New targets for step are incorrect"):"target"in n&&n.target&&n.target.type==="description"&&(n.cache={target:e[0].cache}))}function Ne(n,e,t=!1){return n.length<e?n:n.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var fr={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with"},yr={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with"},vc={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},xc={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function HT(n){switch(n.type){case"ELEMENT_CONTENT":return`${n.negated?yr[n.operation]:fr[n.operation]} '${n.value}'`;case"ELEMENT_ATTRIBUTE":{let t=n.negated?yr[n.operation]:fr[n.operation];return`attribute '${n.attr}' ${t} '${n.value}'`}case"ELEMENT_EXISTENCE":return n.negated?xc[n.condition]:vc[n.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}var bj={CONTENT:"The page"};function WT(n){switch(n.type){case"VALUE":return`the option with value ${n.value}`;case"LABEL":return`the option with label ${n.label}`;case"INDEX":return`the option at index ${n.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function Tc(n){switch(n.type){case"SUBSTRING":return`match substring '${n.url}'`;case"REGEX":return`match regex '${n.regex}'`;case"GLOB":return`match glob '${n.glob}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function GT(n){switch(n.type){case"CONTENT":return`${n.negated?yr.CONTAINS:fr.CONTAINS} '${n.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function br(n){switch(n.type){case"SUCCESS":return n.condition?.assertion?`Check success condition: ${n.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${n.goal}`;case"NAVIGATE":return`Go to URL: ${Ne(n.url,30)}`;case"DIALOG":return`Automatically ${n.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 ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${lt(n.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${lt(n.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${lt(n.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${lt(n.target)}`:""}`;case"WAIT":return`Wait for ${n.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(n.target?.type==="coordinates")return`Click at coordinates: ${lt(n.target)}`;let t="";return n.target?.elementDescriptor.length?t=` on element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` on element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Click${t}`}case"FOCUS":return`Focus ${lt(n.target)}`;case"BLUR":return`Focus ${lt(n.target)}`;case"DRAG":return`Drag ${lt(n.fromTarget)} onto ${lt(n.toTarget)}`;case"MOUSE_DRAG":return n.target?.type==="description"&&n.target.elementDescriptor?`Click and drag ${lt(n.target)} by ${n.deltaX}px horizontally, ${n.deltaY}px vertically`:`Click and drag mouse by ${n.deltaX}px horizontally, ${n.deltaY}px vertically`;case"TYPE":{let t="";return n.target?.type==="coordinates"?t=` in element at coordinates: ${lt(n.target)}`:n.target?.elementDescriptor.length?t=` in element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` in element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Type '${n.value}'${t||""}`}case"HOVER":{let t="";return n.target.type==="coordinates"?t=` over coordinates: ${lt(n.target)}`:n.target.elementDescriptor.length>0?t=` over element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` over element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Hover${t}`}case"PRESS":return`Press ${n.value}`;case"SELECT_OPTION":{let t="",r=n.option??WT(n.choice);return n.target.type==="coordinates"?t=` from element at coordinates: ${lt(n.target)}`:n.target.elementDescriptor.length>0?t=` from: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` from: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${r}'${t}`}case"TAB":if(n.url)return`Switch to tab with substring: ${n.url}`;if(n.action)switch(n.action.type){case"SUBSTRING":return`Switch to tab with substring: ${n.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${n.action.pattern}`;case"INDEX":return`Switch to tab at index: ${n.action.index}`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${n.url}`;case"REQUEST":return`Send ${n.method} request to ${n.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${n.url}`;case"COOKIE":return`Set cookie: ${n.value}`;case"LOCAL_STORAGE":return`Set local storage: ${n.key}: ${n.value}`;case"JAVASCRIPT":return`Run JavaScript: ${Ne(n.code,30)}`;case"AI_ASSERTION":return`Assertion: '${n.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${n.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${n.target?`for element: ${lt(n.target)}`:"for entire page"}`;case"FILE_UPLOAD":return n.fileSource.type==="URL"?`Upload file: ${n.fileSource.url}`:`Upload file: ${n.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${lt(n.target)} ${HT(n.assertion)}`;case"PAGE_CHECK":return`Assert the page ${GT(n.assertion)}`;case"WAIT_FOR_URL":return n.url?`Wait for page URL to match: ${n.url}`:n.matcher?`Wait for page URL to ${Tc(n.matcher)}`:"Wait for page URL to match";case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function lh(n){let e=[];for(let t of n){t.sort((s,a)=>s.timestamp-a.timestamp);let r=[],o,i=1;for(let s of t)o&&o.text===s.text&&o.type===s.type&&JSON.stringify(o.args??null)===JSON.stringify(s.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:r.push(o)),o=s,i=1);o&&r.push(o),e.push(r)}return e}import{cloneDeep as xj,unset as Tj}from"lodash-es";function En(n){switch(n.type){case"AI_ACTION":return`AI action: ${Ne(n.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Ne(n.text,100)}`;case"PRESET_ACTION":return br(n.command);case"MODULE":return`Module: ${n.id}`;case"RESOLVED_MODULE":return`Module: ${n.name}`;case"CONDITIONAL":return"Conditional step";case"IFRAME":return"Frame step";case"SECTION":return`Section${n.description?`with goal: ${Ne(n.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(n)}}var VT="[FAILED]";async function dh(n,{numScreenshots:e=1,addIndices:t=!0,includeBeforeScreenshots:r=!1,includeDomState:o=!1,recursive:i=!0}){let s=[],a;for(let l=0;l<n.length;l++){let c=n[l],d=i?Sr(c):En(c),p={description:`Step ${l}: ${d}`,startedAt:c.startedAt,finishedAt:c.finishedAt,beforeUrl:c.beforeUrl,afterUrl:c.afterUrl,message:c.message!=="Successfully executed preset action."?c.message:void 0,index:t?l:void 0};if(c.status==="FAILED"){p.description=`${VT} ${p.description}`,t&&(a=l);try{let m=Uu.array().parse(c.details);for(let h of m)"pageState"in h&&o&&(p.pageState=h.pageState)}catch{}}e>0&&l>=n.length-e&&(p.afterScreenshot=c.afterScreenshot,r&&(p.beforeScreenshot=c.beforeScreenshot));let u=["beforeScreenshot","afterScreenshot"];for(let m of u){let h=p[m];if(h?.startsWith("http")){let f=await(await fetch(h)).arrayBuffer();p[m]=`data:image/jpeg;base64,${Buffer.from(f).toString("base64")}`}else h&&(p[m]=h.startsWith("data:")?h:`data:image/jpeg;base64,${h}`)}s.push(p)}return{results:s,failureIndex:a}}function Sr(n){let e=En(n);switch(n.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":e+=`
16
16
  `;for(let t=0;t<n.results.length;t++)e+=je(`Sub-step ${t} in AI action:
17
17
  `,2),e+=`${je(Sr(n.results[t]),2)}
18
18
  `,e+=je(`${"=".repeat(10)}
@@ -38,7 +38,7 @@ ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length
38
38
  `,e+=je(`${"=".repeat(10)}
39
39
  `,2);return e}default:return(r=>{throw new Error("You missed a case in the switch above")})(n)}}function je(n,e){return n.split(`
40
40
  `).map(t=>" ".repeat(e)+t).join(`
41
- `)}function ph(n){return n&&Ne(JSON.stringify(n),5e3)}function Vs(n,e){for(let t=0;t<n.length;t++){let r=n[t];try{if(r.data){let{jsonString:o}=ri(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":ch(r);break;case"CONDITIONAL":r.assertion&&ch(r.assertion),Vs(r.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"IFRAME":case"MODULE":case"SECTION":{Vs(r.results,e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}}function ch(n){let e=n.command;"cache"in e&&e.cache&&(e.cache=void 0)}import{cloneDeep as $j}from"lodash-es";function uh(n,e){if(!(!n.envs||!n.envs.length)){for(let t of n.envs){let r=t;e in t&&(r[e]&&(t.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}n.envs.some(t=>t.default)||(n.envs[0].default=!0)}}import JT from"diff-lines";import Ks,{gte as ZT}from"semver";var mh={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>(n=n.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),n=n.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),n)};var hh={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,r=t[t.length-1];return r&&r.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var qT=["target","fromTarget","toTarget"];function gh(n){for(let e of qT){if(n[e]===void 0)continue;let t=n[e];t.elementDescriptor!==void 0?t.type="description":n[e]={type:"description",elementDescriptor:""}}}var fh={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":return gh(e.command),e;case"AI_ACTION":{let t=e.commands;for(let r of t??[])gh(r);return e}default:return e}})};import{v4 as KT}from"uuid";var yh={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=KT()),e;default:return e}})};import{v4 as bh}from"uuid";var Sh={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??bh(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??bh()}})),delete e.commands),e;default:return e}})};var wh={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as YT}from"uuid";var vh={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>("id"in e&&typeof e.id=="string"||(e.id=YT()),e))};import{v4 as xh}from"uuid";var Th={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=xh())}return e.id=xh(),e})};var Ch={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as XT}from"uuid";var Eh={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=XT()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Ah={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var Rh={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&Ih(t),e})};function Ih(n){n&&Object.keys(n).forEach(e=>{if(typeof n[e]=="object"&&n[e]){Ih(n[e]);return}if(typeof n[e]!="string")return;let t=n[e];e==="code"?n[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(n[e]=t.replace(/inputs\./g,"env."))})}var Ph={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var Lh={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var Oh={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var kh={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async n=>n.map(e=>{if(e.type!=="AI_ASSERTION")return e;let r={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...r};return delete o.text,o}),stopOnFailure:!0};var qs=new Set(["CLICK","TYPE","SELECT_OPTION"]),Mh={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type,o=t?.elementDescriptor;return(o!==void 0||qs.has(r))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let a=s?.elementDescriptor,l=s?.type;(a!==void 0||qs.has(l))&&(s.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let a=s.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||qs.has(c))&&(a.target={elementDescriptor:l??""}),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(p=>{let u=p?.elementDescriptor,m=p?.type;(u!==void 0||qs.has(m))&&(p.target={elementDescriptor:u??""})})}),e}),stopOnFailure:!0};var Nh={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var _h={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type;return r?.startsWith("PRESET_")&&(t.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let s=i.type;s?.startsWith("PRESET_")&&(i.type=s.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let s=i.command,a=s?.type;a?.startsWith("PRESET_")&&(s.type=a.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(c=>{let d=c.type;d?.startsWith("PRESET_")&&(c.type=d.slice(7))})}),e}),stopOnFailure:!0};var wr=[kh,Nh,_h,Mh,mh,hh,fh,yh,Sh,wh,vh,Th,Ch,Eh,Ah,Rh,Ph,Lh,Oh];if(mt!==wr[wr.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");wr.forEach((n,e)=>{if(!Ks.valid(n.toVersion)||!Ks.valid(n.fromVersion))throw new Error(`Migration '${n.name}' has invalid version`);if(!Ks.gt(n.toVersion,n.fromVersion))throw new Error(`Migration '${n.name}' has toVersion <= fromVersion`);if(e===0)return;if(wr[e-1].toVersion!==n.fromVersion)throw new Error(`Migration '${n.name}' at index ${e} is not contiguous with previous migration`)});function QT(n){return n.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var yi=async({metadata:n,steps:e,logger:t,toVersion:r})=>{let o=e,{schemaVersion:i,id:s}=n,a=wr.findIndex(d=>Ks.gt(d.toVersion,i));if(a===-1)return{steps:o,newVersion:i};let l=i;for(let d=a;d<wr.length;d++){if(r&&ZT(l,r)){t.debug("Stopping migration early because toVersion was reached");break}let p=wr[d],u={id:s,migration:p.name,toVersion:p.toVersion};try{o=await Fh(o,p),l=p.toVersion}catch(m){throw t.error({err:m,...u},"Migration failed"),new Error(`Step migration ${p.name} failed: ${m}`)}}let c=JT(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:s},"Migration diffs"),{newVersion:l,steps:o}};async function Fh(n,e){let t=await e.execute(n);for(let r of t)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let i=r[o];!i||!Array.isArray(i)||QT(i)&&(r[o]=await Fh(i,e))}return t}async function Dh({rawSteps:n,metadata:e,logger:t,callbacks:r}){uh(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:s}=await Ys({rawSteps:n.steps,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o}),a={...e,steps:i,schemaVersion:s};for(let l of["beforeSteps","afterSteps"]){let c=n[l];if(!c)continue;let{resolvedSteps:d}=await Ys({rawSteps:c,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o});a[l]=d}return{resolvedTest:a,moduleIds:Array.from(Object.keys(o))}}async function Ys({rawSteps:n,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:i,steps:s}=await yi({metadata:e,steps:n,logger:t}),a;try{a=We.array().parse(s)}catch(c){throw t.error({type:"zod",err:c,newVersion:i,id:e.id,steps:s},"Failed to parse test steps while migrating test"),new Bs(`Failed to parse test steps while migrating test: ${c}`,e.id,"entity",{cause:c})}let l=[];for(let c of a)l.push(await bi({step:c,callbacks:r,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:i}}async function bi({step:n,callbacks:e,logger:t,resolvedModuleCache:r}){switch(n.type){case"AI_ACTION":return n;case"AI_ACTION_DYNAMIC":return n;case"PRESET_ACTION":return n;case"MODULE":{let l=n.moduleId,c=r[l];if(c)return{...c,...n,type:"RESOLVED_MODULE"};let d=await e.onFetchModule({id:l,logger:t});if(!d)throw new Error(`Could not find module with id ${l}`);let{newVersion:p,steps:u}=await yi({metadata:{id:l,schemaVersion:d.schemaVersion},steps:d.steps,logger:t}),m;try{m=We.array().parse(u)}catch(f){throw t.error({type:"zod",err:f,steps:u,newVersion:p,id:l},"Module failed to parse"),f}let h;try{h=await Promise.all(m.map(f=>bi({step:f,callbacks:e,logger:t,resolvedModuleCache:r})))}catch(f){throw t.error({err:f,...n},`Failed to recursively resolve module '${d.name}': ${f}`),f}let g={...d,steps:h};return r[l]=g,{...g,...n,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of n.blocks){let c=[];for(let d of l.steps)c.push(await bi({step:d,callbacks:e,logger:t,resolvedModuleCache:r}));o.push({...l,steps:c})}let i;if(n.elseSteps){i=[];for(let l of n.elseSteps)i.push(await bi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}))}return{...n,blocks:o,elseSteps:i};case"SECTION":case"IFRAME":let s=[];for(let l of n.steps)s.push(await bi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}));return{...n,steps:s};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}import{cloneDeep as Uh}from"lodash-es";import{v4 as Cc}from"uuid";async function Lt(n){let e=new Map,t=new Set,r=Uh(n.stepLists.steps),o=await vr({...n,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let a=Uh(n.stepLists[s]);if(!a)continue;let l=await vr({...n,steps:a,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...l.cachesToSave),i.moduleUpdates.push(...l.moduleUpdates),i.stepsToSave[s]=l.stepsToSave}return i}async function vr({steps:n,...e}){let{seenModules:t,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:s,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of n)switch(delete c.index,delete c.aiSuggested,c.id=e.createNewStepIds?Cc():c.id,c.type){case"PRESET_ACTION":{let p=c.command;p.id=r?.createNewCacheIds?Cc():p.id,ih(p),"cache"in p&&p.cache&&(r&&(l.cachesToSave=l.cachesToSave.concat(oh({id:p.id,orgId:r.orgId,testId:r.testId,value:nr.parse(p),moduleIdParents:o,moduleStepParents:i,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete p.cache),p.thoughts&&delete p.thoughts,l.stepsToSave.push({...c,command:p});break}case"RESOLVED_MODULE":{let p=r?.createNewCacheIds?Cc():c.id,u=c.moduleId;s.has(u)?u=s.get(u):a!==void 0&&(u=await a(c),s.set(c.moduleId,u));let{cachesToSave:m,stepsToSave:h,moduleUpdates:g}=await vr({...e,steps:c.steps,cacheCreationParams:r?{...r,createNewCacheIds:!1}:void 0,moduleStepParents:[...i,p],moduleIdParents:[...o,u],skipCacheIntermediateEntries:r?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(g),l.cachesToSave=l.cachesToSave.concat(m),t.has(u)||(t.add(u),l.moduleUpdates.push({...vt.parse(c),steps:We.array().parse(h),moduleId:u}));let f={type:"MODULE",moduleId:u,inputs:c.inputs,id:p,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:p,cachesToSave:u}=await vr({...e,steps:c.steps});try{c.steps=wt.array().parse(p)}catch(m){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${m}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(u);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(c);break}case"CONDITIONAL":{let p=[];for(let m of c.blocks){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await vr({...e,steps:m.steps});p.push({...m,steps:h}),l.cachesToSave=l.cachesToSave.concat(g),l.moduleUpdates=l.moduleUpdates.concat(f)}let u={...c,elseSteps:void 0,blocks:p};if(c.elseSteps){let{stepsToSave:m,cachesToSave:h,moduleUpdates:g}=await vr({...e,steps:c.elseSteps});u.elseSteps=m,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(g)}l.stepsToSave.push(u);break}case"IFRAME":case"SECTION":{let{stepsToSave:p,cachesToSave:u,moduleUpdates:m}=await vr({...e,steps:c.steps}),h={...c,steps:p};l.moduleUpdates=l.moduleUpdates.concat(m),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(u);break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as eC}from"lodash-es";import{stringify as zh}from"yaml";async function Bh(n,e=new Set){let t={id:n.id,name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:n.schemaVersion,advanced:n.advanced,retries:n.retries,envs:n.envs,disabled:n.disabled,labels:n.labels},r={},o=await tC({originalStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},modules:r,processedModuleNames:e}),i={fileType:be.TEST,...t,beforeSteps:o.beforeSteps&&o.beforeSteps.length>0?o.beforeSteps:void 0,steps:o.steps,afterSteps:o.afterSteps&&o.afterSteps.length>0?o.afterSteps:void 0};return{test:zh(i),modules:r}}async function tC({originalStepLists:n,modules:e,processedModuleNames:t}){let r=eC(n);Object.values(r).forEach(s=>{nC(s??[])});let{stepsToSave:o,moduleUpdates:i}=await Lt({stepLists:r});for(let s of i)t.has(s.name)||(e[s.name]=rC(s),t.add(s.name));return o}function nC(n){wc({steps:n,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function rC(n){let e=vt.parse(n),t={fileType:be.MODULE,...e,schemaVersion:mt,steps:n.steps};return zh(t)}async function Q(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},n);function i(){clearTimeout(o),e?.removeEventListener("abort",i),r(e?.reason)}})}async function Si({promiseGenerator:n,signal:e,codePath:t,logger:r}){let i=Date.now(),s=setInterval(()=>{if(e?.aborted){clearInterval(s);return}r?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((a,l)=>{function c(){clearInterval(s),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(s);return}e?.addEventListener("abort",c),(async()=>{try{a(await n())}catch(d){l(d)}finally{clearInterval(s),e?.removeEventListener("abort",c)}})()})}async function xr({promiseGenerator:n,timeoutMs:e,codePath:t,logger:r,signal:o}){let i=!1,s=new AbortController,a=()=>{s.abort()},l=setTimeout(()=>{i||s.abort()},e);o?.addEventListener("abort",a);try{return await Si({promiseGenerator:n,signal:s.signal,codePath:t,logger:r})}finally{i=!0,o?.removeEventListener("abort",a),clearTimeout(l)}}function Xs(n){let e=[];for(let t of n)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let r={...t,type:"MODULE"};e.push(Tn.parse(r));break}case"IFRAME":case"SECTION":{let r={...t,steps:Xs(t.steps)};e.push(We.parse(r));break}case"CONDITIONAL":{let r={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:Xs(o.steps)})),elseSteps:t.elseSteps?Xs(t.elseSteps):void 0};e.push(or.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Js(n){return Xs([n])[0]}import oC from"picomatch";var Ec=(n,e,t)=>{t?.caseInsensitive&&(n=n.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;r=n.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;r=n===e.glob||oC(o)(n);break}case"REGEX":{r=new RegExp(e.regex).test(n);break}}return t?.negated?!r:r};var to=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,r){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:r}=eo({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(r,e.logger)}};var no="v1",Un=class{httpClient;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}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${no}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof Qt?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${no}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${no}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${no}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${no}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${no}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as iC}from"zod";var ro=class extends At{constructor(e){super(e)}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Ku.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${_}/web-agent/recommend-chunks`,{method:"POST",body:e,signal:t.abortSignal});return qu.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${_}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return iC.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Em.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return fc.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return fc.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${_}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Cm.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${_}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${_}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return _l.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${_}/web-agent/reverse-mapped-description`,{method:"POST",body:{goal:e.goal,browserState:e.browserState,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Am.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return Nl.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${_}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Vl.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${_}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Vu.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${_}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Up.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${_}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return zp.parse(r)}};var Tr=class extends At{async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${_}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Cp.parse(r)}async constructIframeRegex(e,t={}){let r=await this.sendRequest(`/${_}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t?.signal});return Tp.parse(r)}};import{Server as gR}from"socket.io";var sC={showOverlay:!1},Ac=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:r,clientIp:o,sessionId:i,browserbaseSessionId:s}){return this.sessions.set(i,{controller:e,context:t,cleanup:r,clientIp:o,browserbaseSessionId:s,browserBehavior:sC}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(s){t.error({err:s},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(s){t.error({err:s},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}},K=new Ac;var aC=parseInt(process.env.MOMENTIC_SCREENSHOT_INTERVAL||"150");function jh(n,e,t){let r=Date.now(),o=-1,i,s=0,a=!1,l=Date.now(),c,d,p,u,m=!1,h=async(v,b)=>{if(!v.closed){{if(v.isInPageLoad)return;if(a)return}if(s>0&&Math.random()>=1/Math.max(s,8)){s===3&&t.warn("Screenshots are being dropped due to previous failures");return}try{a=!0;let E=p;p=void 0;let x=await v.screenshot({retries:0,timeout:750,scale:"device",quality:75});i&&x.equals(i)?x=void 0:i=x;let C=v.url(),L=b.toEditorDisplayCopy();x===void 0&&JSON.stringify(L)===JSON.stringify(c)&&C===u&&r>l||(n.emit("browserState",{logsPerPage:E?.logsPerPage,harPages:E?.harPages,harEntries:E?.harEntries,viewport:v.getViewport(),buffer:x,url:C,iframeSrcUrls:d??[],context:L,isInPageLoad:v.isInPageLoad}),r=Date.now()),u=C,c=L,s=0}catch(E){if(!n.connected)return;let x=E instanceof Error?E.message:`${E}`;if(x.includes("Frame was detached")||x.includes("Not attached to an active page")||x.includes("browser has been closed")||x.includes("UserInfrastructureError"))return;s++,t.error({err:E,sessionId:e},"Error taking screenshot")}finally{a=!1,n.connected&&s>10&&Date.now()-o>6e4&&(t.error({sessionId:e},"Screenshots to client are stale"),o=Date.now())}}},g=setInterval(()=>{let v=K.getSession(e),b=v?.controller?.browser;if(!b||b.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(g);return}h(b,v.context)},aC),f=(v,b)=>!!(JSON.stringify(v)!==JSON.stringify(d)||b.logsPerPage.some(E=>E.length>0)||b.harPages&&Object.keys(b.harPages).length>0||b.harEntries&&Object.keys(b.harEntries).length>0),y=setInterval(async()=>{let b=K.getSession(e)?.controller?.browser;if(!b||b.closed){clearInterval(y);return}else if(m)return;m=!0;try{let E=await b.getAllFrameUrls(),x=b.retrieveAndClearDebugData();f(E,x)&&(d=E,p=x,l=Date.now())}catch(E){t.warn({err:E},"Failed to fetch extended details")}finally{m=!1}},2500);return{timers:[g,y]}}var zn={};var lC=n=>()=>{let{sessionId:e}=n.metadata;zn[e]?.abort?.abort()},$h={event:"cancelApiTest",createHandler:lC};import{CookieJar as TC}from"tough-cookie";import{randomUUID as fC}from"crypto";import{faker as cC}from"@faker-js/faker";import dC from"assert";import pC from"axios";import uC from"moment";import*as mC from"otpauth";import hC from"pg";var oo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Hh=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};async function B(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a;return new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&c(Hh(p)),a=()=>{c(Hh(p))},p.addEventListener("abort",a)}if(t===Number.POSITIVE_INFINITY){n.then(l,c);return}let d=new oo;s=i.setTimeout.call(void 0,()=>{if(r){try{l(r())}catch(p){c(p)}return}"cancel"in n&&typeof n.cancel=="function"&&n.cancel(),o instanceof Error?c(o):(d.message=o??`Promise timed out after ${t} milliseconds`,c(d))},t),(async()=>{try{l(await n)}catch(p){c(p)}})()}).finally(()=>{s!==void 0&&i.clearTimeout.call(void 0,s),a!==void 0&&e.signal&&e.signal.removeEventListener("abort",a)})}async function Wh(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Fs(r,e);t.push(...o)}),t}var gC=Object.getPrototypeOf(async function(){}).constructor;async function Gh(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,s={},a=(f,y)=>{o[f]=y,s[f]=y},l={},c=(f,y)=>{o[f]=y,l[f]=y},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let p;r.includes("createAppAuth")&&(p=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new gC("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(pC,uC,cC,dC,hC,d,p,mC,Wh,o,a,c,y=>i.sms.send(y),y=>i.sms.fetchLatest(y),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await B(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error(`[${n}] Error executing code: ${f}`),m=!1,f instanceof oo?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:s,persistentVariableUpdates:l,success:m,error:g}}async function Vh({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:s=Zr}){let a=fC(),l=await Gh(a,{code:n,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:r,signal:i},o);return S.debug(`[${a}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as yC,randomUUID as bC}from"crypto";var qh=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Kh=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Yh({orgId:n,code:e,fragment:t,context:r,logger:o,timeoutMs:i=Zr,retries:s=1,signal:a}){if(!qh)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Kh)throw new Error("Missing lambda auth secret.");let p=yC("sha256",Kh).update(n).digest("hex");for(;d<=s;){d++,a?.throwIfAborted();let m={id:bC(),orgId:n,momenticLambdaAuthHash:p,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:i};try{if(l=await B(fetch(qh,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:i,message:`Timeout of ${i}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=tm.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function An(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Yh(n);else if(n.localTools)e=await Vh({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation error: ${e.error}`);if(e.variableUpdates)for(let[t,r]of Object.entries(e.variableUpdates))n.context.setVariable(t,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await n.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,r]of Object.entries(e.persistentVariableUpdates))n.context.setVariable(t,r)}return e.result}async function Ot(n){let{orgId:e,s:t,context:r,logger:o,timeoutMs:i=Zr,retries:s=1,signal:a,allowUndefined:l=!1}=n,c=/{{(.*?)}}/g,d=t.matchAll(c),p=t;for(let u of d){if(u.length<2)continue;let m=u[1].trim(),h;try{h=await An({orgId:e,code:m,fragment:!0,context:r,timeoutMs:i,logger:o,retries:s,localTools:n.localTools,signal:a})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(h===void 0&&!l)throw new A("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let g=typeof h=="string"?h:`${h}`;g=g.replaceAll(/\$/g,"$$$$"),p=p.replace(u[0],g)}return p}async function io(n){return Xh(n)}async function Xh({obj:n,bannedKeys:e,allowList:t,context:r,prefixPath:o="",replacements:i={},...s}){for(let a in n){if(e.includes(a))continue;let l=!1;if(t)if(t.includes(a))l=!0;else continue;let c=n[a],d=o?`${o}.${a}`:a;if(typeof c=="string"&&c.includes("{{")){let p=await Ot({s:c,context:r,...s});if(c===p)continue;i[d]=c,n[a]=p}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await Xh({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:i,allowList:l?void 0:t,...s})}return i}import wC from"fetch-cookie";import{cloneDeep as vC}from"lodash-es";var Zs=(n,e)=>{try{let{hostname:t,pathname:r}=new URL(n),{hostname:o,pathname:i}=new URL(e);return t!==o||r!==i}catch{return!1}},so=n=>{try{return new URL(n),!0}catch{return!1}},Jh=n=>!n.toLowerCase().startsWith("http"),ao=(n,e)=>{try{return new URL(n,e),!0}catch{return!1}};function Bn(n,e){try{return!!new URL(n).origin.trim()}catch(t){return e?.error({url:n,err:t},"Invalid URL in check"),!1}}var SC=3e4;async function Qs({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??SC/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([m,h])=>m&&h)),s=new URLSearchParams;Object.entries(n.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{s.append(m,h)});let a=s.toString(),l;if(so(n.url)&&(l=n.url),t&&ao(n.url,t)&&(l=new URL(n.url,t).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${n.url}`);let d=await B((async()=>{let m=a?`${l}?${a}`:l;try{return await r(m,{headers:i,method:n.method,body:n.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok)throw new A("ActionFailureError",`Fetch request failed with status ${d.status}`);let p={};d.headers.forEach((m,h)=>{p[h]=m});let u={status:d.status,headers:p};return d.headers.get("content-type")?.includes("json")?u.json=await d.json():d.headers.get("content-type")?.includes("text")&&(u.text=await d.text()),u}async function Zh(n){let{fixtures:e,inputs:t}=n,{context:r}=e,{orgId:o,step:i}=t,s=vC(i);await io({obj:s,orgId:o,bannedKeys:["code"],...e});let a=await xC(n);return s.envKey&&a.data&&r.setVariable(s.envKey,a.data),a}async function xC(n){let{fixtures:e,inputs:t}=n,{step:r,orgId:o,baseUrl:i}=t,{cookieJar:s}=e,a=new Date;switch(r.type){case"JAVASCRIPT":{let c=await An({code:r.code,orgId:o,fragment:!!r.fragment,timeoutMs:r.timeout?r.timeout*1e3:void 0,...e});try{JSON.stringify(c)}catch(d){return{...r,startedAt:a,finishedAt:new Date,status:"FAILED",message:`JavaScript return value is not serializable: ${d instanceof Error?d.message:`${d}`}`}}return{...r,startedAt:a,finishedAt:new Date,message:"JavaScript code executed successfully",status:"SUCCESS",data:c}}case"REQUEST":{let c=wC(fetch,s),d=await Qs({command:r,logger:e.logger,baseUrl:i,fetchImplementation:c});return{...r,startedAt:a,finishedAt:new Date,status:"SUCCESS",message:"Request executed successfully",data:d}}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}async function Qh(n){let{inputs:e,fixtures:t,callbacks:r}=n,{signal:o}=t,{steps:i,orgId:s,baseUrl:a}=e,{test:l,step:c}=r,d={startedAt:new Date,status:"RUNNING",results:[]},p=d.results,u=new TC,m={cookieJar:u,...t};for(let h of i){let g=new Date;c.onStarted?.(h.id);let f;try{o?.throwIfAborted(),f=await Zh({inputs:{step:h,baseUrl:a,orgId:s},fixtures:m})}catch(y){o?.aborted?f={...h,startedAt:g,finishedAt:new Date,status:"CANCELLED",message:"Step cancelled by user."}:f={...h,startedAt:g,finishedAt:new Date,status:"FAILED",message:`Step failed: ${y instanceof Error?y.message:`${y}`}`}}if(p.push(f),c.onFinished?.({result:f,cookies:Us(u,new URL(a).hostname)}),l.updateAttemptProgress?.({results:p}),f.status!=="SUCCESS"){d.status=f.status==="CANCELLED"?"CANCELLED":"FAILED";break}}return d.status==="RUNNING"&&(d.status="PASSED"),d.finishedAt=new Date,l.onFinished?.(),d}async function eg(n){let{socket:e,storage:t}=n,r=n.socket.id,{testId:o}=e.handshake.query;if(typeof o!="string")throw new Error(`Received invalid test ID that does not parse as a string: ${o}`);let i=await t.getOrgId({type:"api-test",testId:o}),{baseUrl:s,envName:a,environmentVariables:l}=await Rc({testId:o,orgId:i,logger:n.logger,storage:t,authorization:n.authorization}),c={type:"api-test",orgId:await n.storage.getOrgId({type:"api-test",testId:o}),testId:o,sessionId:r,latestContext:new Tt({baseUrl:s||"",currentUrl:s||"",variablesFromEnvironment:l,envName:a})};return zn[r]=c,c}async function Rc({testId:n,orgId:e,logger:t,storage:r,authorization:o}){let i=await r.fetchApiTestMetadata(n,e,t);if(!i)throw new Error(`Failed to fetch API test metadata for test ID: ${n}`);let s;o?.type==="API_KEY"&&(s=new Un({httpClient:new At(o)}));let a=i.envs?.find(p=>p.default),l;a&&(l=await r.fetchEnvironment(e,a.name,t));let c=i.baseUrl||l?.variables?.[ve];if(!c)throw new Error("Base URL is empty in both API test options and the configured environment");let d={...l?.variables};return{baseUrl:c,envName:l?.name,environmentVariables:d,localCodeEvalTools:s}}var CC=n=>async(e,t)=>{let{steps:r}=e,{authorization:o,metadata:i,socket:s,storage:a,logger:l}=n,{orgId:c,testId:d,sessionId:p}=i,u=l.child({testId:d,orgId:c,sessionId:p}),m=zn[p];if(!m)throw new Error(`No api testing session with id ${p} could be found. Please reconnect and try again.`);let h=new AbortController;m.abort=h;let g=m.latestContext,{localCodeEvalTools:f,baseUrl:y}=await Rc({testId:d,orgId:c,logger:u,storage:a,authorization:o}),v={context:g,logger:u,localTools:f,signal:h.signal},x=await Qh({inputs:{steps:r,orgId:c,baseUrl:y},fixtures:v,callbacks:{test:{onFinished:()=>{s.emit("apiTestFinished")}},step:{onStarted:C=>{s.emit("apiStepStarted",C)},onFinished:C=>{s.emit("apiStepFinished",C)}}}});t({result:x})},tg={event:"executeApiTest",createHandler:CC};var EC=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{e.info({sessionId:t},"Cancel event received");let r=K.getSession(t);if(!r)throw new Error("No active session found");try{r.controller.setClosed()}catch{}}},ng={event:"cancel",createHandler:EC};var AC=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=K.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.getBrowserState({skipWait:!0});o({a11yTree:a.serialize()})}catch(a){e.error({err:a},"Error fetching a11y tree from the browser"),o({err:a.message})}}},rg={event:"fetchA11yTree",createHandler:AC};var RC=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=K.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.html();o({html:a})}catch(a){e.error({err:a},"Error fetching DOM from the browser"),a.name==="TimeoutError"?o({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):o({err:a.message})}}},og={event:"fetchDom",createHandler:RC};var IC=({metadata:n,logger:e})=>{let{sessionId:t,type:r}=n;return o=>{e.info({sessionId:t,reason:o},`Disconnect event received (${o})`),r==="e2e"?K.removeSession(t,e):r==="api-test"&&delete zn[t]}},ig={event:"disconnect",createHandler:IC};import{diff as ZA}from"deep-object-diff";function $t(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=PC(t);LC(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await OC(i,e,r,o)}catch(s){n.logger.error({result:n.result,err:s},"Error hoisting scalar result metadata")}})())}function PC(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function LC(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function OC(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeScreenshot=t.beforeScreenshot),r&&(e.afterScreenshot=r.afterScreenshot)}import wi from"os";import kC from"v8";var sg,mn,Ic=wi.platform(),MC=wi.cpus().map(n=>({model:n.model,speed:n.speed}));function ag(n){n.debug({platform:Ic,cpuMetadata:MC},"Platform and CPU clock speed metadata");let e=()=>{try{let t=!1,r=NC(),o=_C();r.freeMemory<1e6&&(t=!0);let i=kC.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(t=!0),t?n.warn({platform:Ic,memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({platform:Ic,memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),setInterval(e,1e4)}function NC(){let n=wi.totalmem(),e=wi.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function _C(){let n=wi.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!mn)return mn=t,null;let r={user:t.user-mn.user,nice:t.nice-mn.nice,sys:t.sys-mn.sys,idle:t.idle-mn.idle,irq:t.irq-mn.irq,total:t.total-mn.total};return sg={measurementTime:e,intervalMs:e-mn.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},mn=t,sg}async function lo(n,e,t,r,o,i){try{let[s,a]=await Promise.all([t?o(t):void 0,r?o(r):void 0]);s&&(n&&(n.beforeScreenshot=s),e.beforeScreenshot=s),a&&(n&&(n.afterScreenshot=a),e.afterScreenshot=a)}catch(s){i.debug({err:s},"Error saving screenshot to S3")}}import{hostname as BC}from"os";async function dg(n){let{command:e,timeoutMs:t,targetingWrapper:r,disableCache:o,fixtures:i}=n,{logger:s,abortSignal:a}=i;if(e.target&&!kn(e.target))throw new Error("Element assertion with x/y is not supported yet");let l=Date.now(),c=0,d,p=500;for(;c<2||Date.now()-l<t;){c++,c>1&&await Q(p,a),a?.throwIfAborted(),s.debug({currentSleepDuration:p,attempts:c},"Attempting manual element assertion");try{let{newTarget:u,elementInteractedDisplayString:m,result:h}=await r({ctx:i.ctx,command:e,target:e.target,cache:e.cache?.target,action:async g=>FC(g.locator,n),options:{disableCache:o,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl,disableGlobalLocatorRedirect:!0}});if(d={success:h.success,data:h.data,err:h.err,newTarget:u,elementInteractedDisplayString:m},!h.success){d=h,p=Math.min(p*2,1e4);continue}return d}catch(u){if(a?.throwIfAborted(),s.warn({err:u},"Element assertion ended in error, retrying..."),e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated)return{success:!0,thoughts:`The element described does not exist on the page: ${u.message}`};if(!(u instanceof A)||u.reason!="ActionFailureError")throw u;d={success:!1,err:u}}}if(!d)throw new Error(`Failed to evaluate manual element assertion in ${t}ms.`);return d}async function FC(n,{command:e,fixtures:t}){let r=e.assertion;await t.browser.highlight(n);let o=!0,i,s;switch(r.type){case"ELEMENT_CONTENT":{let a=await n.textContent()??"";if(s={elementTextContent:Ne(a,500,!0)},!cg(a,r.value,r.operation,!!r.negated)){let l=r.negated?fr[r.operation]:yr[r.operation];o=!1,i=new A("AssertionFailureError",`The content ${l} '${r.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{s={elementOuterHtml:Ne(await n.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await n.getAttribute(r.attr,{timeout:3e3})??""}catch(l){i=new A("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${l}`),o=!1;break}if(!cg(a,r.value,r.operation,!!r.negated)){let l=r.negated?fr[r.operation]:yr[r.operation];o=!1,i=new A("AssertionFailureError",`The attribute ${r.attr} ${l} '${r.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await n.isVisible({timeout:xn*1e3});break}case"EDITABLE":{o=await n.isEditable({timeout:xn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await n.isEnabled({timeout:xn*1e3});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 a=r.negated?vc[r.condition]:xc[r.condition];i=new A("AssertionFailureError",`The element ${a}`)}break}}return{success:o,data:s,err:i}}var DC=5e3;async function ea({timeout:n=xn,...e}){let t=Date.now(),r=n*1e3,o=r+1e4,i,s=0,a=500,l=0;for(;s-t<r;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted(),l++,(l<5||l%10===0)&&e.logger.debug({currentSleepDuration:a,attempts:l},"Attempting page assertion");let c=Date.now();i=await lg({...e,returnHtml:!1}),s=Date.now();let d=s-c;if(d>1e3&&e.logger.warn({pageAssertDuration:d},"Page assertion took longer than expected"),!i.success)await Q(a,e.signal),a=Math.min(Math.floor(a*1.5),DC);else return i}return i=await lg({...e,returnHtml:!0}),i}async function lg({assertion:n,browser:e,returnHtml:t}){switch(n.type){case"CONTENT":{let o,i=!0,s;try{let{evaluation:a,pageHtml:l}=await e.evaluateFunctionInPage({...n,returnHtml:t},c=>{let d=document.documentElement.outerHTML,p=d.includes(c.value)===!c.negated;return{evaluation:p,pageHtml:!p&&c.returnHtml?d:void 0}});if(a)i=!0;else{i=!1;let c=n.negated?fr.CONTAINS:yr.CONTAINS;s=new A("AssertionFailureError",`The page ${c} '${n.value}'.`),o=l}}catch(a){s=new A("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:i,err:s,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function cg(n,e,t,r){let o;switch(t){case"CONTAINS":{o=n.includes(e);break}case"EQUALS":{o=n.trim()===e.trim();break}case"STARTS_WITH":{o=n.trim().startsWith(e);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return r?!o:o}import{Jimp as UC}from"jimp";async function vi(n,e){let t=await n.screenshot(e),r=await UC.fromBuffer(t);return{buffer:t,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as pg}from"jimp";import Pc from"jpeg-js";import zC from"pixelmatch";async function ug({ctx:n,command:e,disableCache:t,browser:r,targetingWrapper:o,logger:i,screenshotStorage:s}){if(e.target&&!kn(e.target))throw new Error("Visual Diff with x/y is not supported yet");await r.waitForDOMStability({logger:i});let a={clearHighlights:!0,hideCaret:!0},l;e.target?.elementDescriptor?l=(await o({ctx:n,command:e,target:e.target,cache:e.cache?.target??e.target?.a11yData,action:async U=>vi(r,{locator:U.locator,...a}),options:{disableCache:!!t,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl,disableGlobalLocatorRedirect:!0}})).result:l=await vi(r,a);let c=await s.prepareGoldenScreenshotForComparison(i,e,l);if((l.height!==c.height||l.width!==c.width)&&i.debug({currHeight:l.height,currWidth:l.width,savedHeight:c.height,savedWidth:c.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-c.height)>10||Math.abs(l.width-c.width)>10){let P=`${l.width}x${l.height}`,U=`${c.width}x${c.height}`;return{fail:!0,thoughts:`Current screenshot (${P}) does not match saved screenshot dimensions (${U}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:r.url()}}let d=await pg.fromBuffer(l.buffer),p={width:l.width,height:l.height},u=await pg.fromBuffer(c.buffer),m={width:c.width,height:c.height},h,g=p.width*p.height,f=m.width*m.height,y=Math.abs(p.height-m.height),v=Math.abs(p.width-m.width);if(g>f){let P=d.cover({w:m.width,h:m.height});l.buffer=await P.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(f>g){let P=u.cover({w:p.width,h:p.height});c.buffer=await P.getBuffer("image/jpeg"),h="saved"}let b={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},E=e.threshold??.1,C=zC(Pc.decode(c.buffer).data,Pc.decode(l.buffer).data,b.data,l.width,l.height,{threshold:E,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,L=C>E*100,N=`Visual diff of ${C.toFixed(2)}% detected, which is ${L?"over":"under"} the threshold of ${E*100}%.`;return h&&(N+=` The ${h} screenshot was cropped since it was taller by ${y} pixels and wider by ${v} pixels.`),{fail:L,thoughts:N,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Pc.encode(b,75).data,succeedImmediately:!1,urlAfterCommand:r.url()}}var Lc=async n=>{let{step:e,resolvedInputs:t}=n.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:s,controller:a}=n.fixtures,l=a.browser,{orgId:c,runId:d}=n.inputs,p=a.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),r.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",y=await Ot({orgId:c,s:f,context:o,logger:r,localTools:s,signal:p});g={orgId:c,cacheKeys:[y,...Object.entries(t).map(([b,E])=>`${b}:${E}`)]},r.debug({original:f,keyParams:g},"Module cache key params");let v=Date.now();for(;Date.now()-v<Tm;){p?.throwIfAborted();let b=await i.getCacheResult(g);if(b){r.debug({cacheResult:b},"Got result from module execution cache"),u=ta(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(b),m=!0;break}else r.debug({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let E=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${BC()};runId:${d}`},p);if(E.acquired){h=E.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await Q(2500+Math.random()*1e4,p)}}try{if(!u)u=await jC(n);else if(e.autoAuth){let f=Ds.safeParse(u.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,v=e.advanced?.cacheInvalidation;if(v&&v.type==="PAGE_CHECK"){let b={type:"CONTENT",value:v.substring},E=await ea({timeout:xn,assertion:b,browser:l,logger:r,signal:p});E.success?r.debug({invalResult:E},"Cached result still valid after page check, continuing..."):(r.info({invalResult:E},"Invalidating cached result due to page check failure"),y=!0)}if(g&&y)return await i.deleteCacheResult(g),Lc(n)}}finally{try{h!==void 0&&!m&&u?.status==="SUCCESS"&&await $C({step:e,result:u,browser:a.browser,cacheKeyPrefix:h,logger:r,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return u},jC=async n=>{let{step:e}=n.moduleParams,t=ta(e,n.moduleParams.resolvedInputs,"SUCCESS"),{status:r,results:o}=await jn(n.work,()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:`module ('${e.name}')`}}));return t.results=o,t.status=r,t.finishedAt=new Date,$t({asyncTasks:n.work.asyncTasks,nestedResults:o,result:t,logger:n.fixtures.logger}),t};function ta(n,e,t){let r={};return Object.entries(e).forEach(([i,s])=>{r[i]=JSON.stringify(s)}),{type:"MODULE",id:n.id,moduleId:n.moduleId,moduleName:n.name,startedAt:new Date,cacheConfig:n.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:t}}async function na({orgId:n,step:e,context:t,logger:r,codeEvalTools:o,signal:i}){let s={};try{for(let a of e.parameters??[]){let l=e.inputs?.[a]??e.defaultParameters?.[a];if(!l){r.warn(`No value or default found for parameter '${a}' that is required by module '${e.name}'`);continue}s[a]=await An({orgId:n,code:l,fragment:!0,context:t,logger:r,localTools:o,signal:i})}return s}catch(a){throw i?.throwIfAborted(),new A("UserConfigurationError",`Failed to evaluate module inputs: ${a}`)}}async function $C({step:n,result:e,browser:t,cacheKeyPrefix:r,logger:o,storage:i}){let s=n.cacheConfig?.cacheExpiryMs;(!s||s===Vm)&&(s=n.defaultCacheTtl??qm);let a;n.autoAuth?a=JSON.stringify(await t.saveAuthState()):e.data!==void 0?a=JSON.stringify(e.data):a='""',o.debug({cacheKeyPrefix:r,ttlMs:s,truncatedCacheResultJson:ph(a)},"Setting module cache result"),await i.setCacheResult({result:a,keyPrefix:r,ttlMs:s})}async function $n(n,e,t){let r=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,s="FAILED",a;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(a="Step aborted by user.",s="CANCELLED"):o instanceof A?a=`${o}`:a=`An unexpected error occurred: ${o.message}`,n.type==="RESOLVED_MODULE"){let l=ta(n,{},"FAILED");return l.message=a,l.startedAt=r,l.finishedAt=i,l}return{...Js(n),startedAt:r,finishedAt:i,status:s,data:null,message:a,results:[]}}}async function jn(n,e){let t=!1;try{return n&&!n.state.failureRecoveryDisabled&&(n.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{n&&t&&(n.state.failureRecoveryDisabled=void 0)}}import{randomUUID as mg}from"crypto";import{cloneDeep as WC}from"lodash-es";function ra(n,e){n.state.healingDetails?n.state.healingDetails.push(e):n.state.healingDetails=[e]}var oa=async n=>{let e=n.presetParams.step,{logger:t,controller:r,context:o,billingReporter:i}=n.fixtures,{collectDebugData:s}=n.options,{orgId:a,testMetadata:l,suiteMetadata:c}=n.inputs,d=e.command.type,p=t.child({commandType:d,stepId:e.id,commandId:e.command.id}),u=sc(e.command);n.work.asyncTasks.push(i.reportCreditsUsed(p,d,u,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let m=n.callbacks.test,h=r.browser.url(),g=new Date,f,y;if(s)try{f=await r.browser.screenshot({retries:1,clearHighlights:!0}),y=mg();let C=await r.browser.getRawCondensedHtml();n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(p,a,y,C))}catch(C){p.debug({err:C},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let v,b,E,x=ks();try{let C=await r.executePresetCommand(x,e.command,o,l?.advanced.disableAICaching??!1);C.beforeScreenshotOverride&&(f=C.beforeScreenshotOverride),E=C.afterScreenshotOverride;let{proposedStep:L}=GC({work:n.work,step:e,newTargets:C.newTargets,logger:p}),N=new Date,P=r.browser.url();b={beforeUrl:h,afterUrl:P,startedAt:g,finishedAt:N,viewport:r.browser.getViewport(),status:C.fail?"FAILED":"SUCCESS",elementInteracted:C.elementInteracted},v={...e,message:C.thoughts??VC(C.newTargets)??"Successfully executed preset action.",beforeUrl:h,afterUrl:P,finishedAt:N,startedAt:g,status:C.fail?"FAILED":"SUCCESS",data:C.data,results:[b],details:x.details,proposedStep:L},"assertion"in e.command&&(v.message=C.thoughts||"Assertion passed.")}catch(C){p.error({message:C.message,stack:C.stack},`Failed executing preset step ${br(e.command)}`);let L=r.browser.url(),N=new Date,P=C instanceof Error?C.message:`${C}`;C instanceof A&&C.getLastScreenshotBuffer()&&(E=C.getLastScreenshotBuffer()),b={beforeUrl:h,afterUrl:L,startedAt:g,finishedAt:N,viewport:r.browser.getViewport(),status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:P},v={...e,startedAt:g,finishedAt:N,beforeUrl:h,afterUrl:L,status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:P,failureReason:C instanceof A?C.reason:void 0,results:[b],details:x.details}}if(s)try{E||(E=await r.browser.screenshot({retries:1}));let C=mg(),L=await r.browser.getRawCondensedHtml();b.beforeSnapshot=y,v.beforeSnapshot=y,b.afterSnapshot=C,v.afterSnapshot=C,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(p,a,C,L))}catch(C){p.debug({err:C},"Failed to take screenshot after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return n.work.asyncTasks.push(lo(b,v,f,E,m.onSaveScreenshot,p)),v};function GC({work:n,step:e,newTargets:t,logger:r}){if(!t?.length)return{proposedStep:void 0};let o=e.command;ah(o,t,r);let i=t[0]?.description;if(i&&"target"in o&&o.target&&o.target.type==="description"){let s={...o,target:{...o.target,elementDescriptor:i}},a={...WC(e),command:s};return ra(n,{type:"DESCRIPTION_UPDATE",thoughts:`Updated element description after the original element could not be found on the page. New element location reasoning: ${t[0]?.thoughts}`}),{proposedStep:a}}return{proposedStep:void 0}}function VC(n){if(n?.length){if(n.length===1&&n[0]?.thoughts)return n[0].thoughts;if(n.length===2&&n.every(e=>e.thoughts))return`Located first element: ${n[0]?.thoughts}
41
+ `)}function ph(n){return n&&Ne(JSON.stringify(n),5e3)}function Vs(n,e){for(let t=0;t<n.length;t++){let r=n[t];try{if(r.data){let{jsonString:o}=ri(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":ch(r);break;case"CONDITIONAL":r.assertion&&ch(r.assertion),Vs(r.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"IFRAME":case"MODULE":case"SECTION":{Vs(r.results,e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}}function ch(n){let e=n.command;"cache"in e&&e.cache&&(e.cache=void 0)}import{cloneDeep as Bj}from"lodash-es";function uh(n,e){if(!(!n.envs||!n.envs.length)){for(let t of n.envs){let r=t;e in t&&(r[e]&&(t.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}n.envs.some(t=>t.default)||(n.envs[0].default=!0)}}import JT from"diff-lines";import Ks,{gte as ZT}from"semver";var mh={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>(n=n.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),n=n.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),n)};var hh={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,r=t[t.length-1];return r&&r.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var qT=["target","fromTarget","toTarget"];function gh(n){for(let e of qT){if(n[e]===void 0)continue;let t=n[e];t.elementDescriptor!==void 0?t.type="description":n[e]={type:"description",elementDescriptor:""}}}var fh={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":return gh(e.command),e;case"AI_ACTION":{let t=e.commands;for(let r of t??[])gh(r);return e}default:return e}})};import{v4 as KT}from"uuid";var yh={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=KT()),e;default:return e}})};import{v4 as bh}from"uuid";var Sh={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??bh(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??bh()}})),delete e.commands),e;default:return e}})};var wh={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as YT}from"uuid";var vh={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>("id"in e&&typeof e.id=="string"||(e.id=YT()),e))};import{v4 as xh}from"uuid";var Th={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=xh())}return e.id=xh(),e})};var Ch={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as XT}from"uuid";var Eh={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=XT()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Ah={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var Rh={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&Ih(t),e})};function Ih(n){n&&Object.keys(n).forEach(e=>{if(typeof n[e]=="object"&&n[e]){Ih(n[e]);return}if(typeof n[e]!="string")return;let t=n[e];e==="code"?n[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(n[e]=t.replace(/inputs\./g,"env."))})}var Ph={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var Lh={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var Oh={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var kh={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async n=>n.map(e=>{if(e.type!=="AI_ASSERTION")return e;let r={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...r};return delete o.text,o}),stopOnFailure:!0};var qs=new Set(["CLICK","TYPE","SELECT_OPTION"]),Mh={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type,o=t?.elementDescriptor;return(o!==void 0||qs.has(r))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let a=s?.elementDescriptor,l=s?.type;(a!==void 0||qs.has(l))&&(s.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let a=s.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||qs.has(c))&&(a.target={elementDescriptor:l??""}),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(p=>{let u=p?.elementDescriptor,m=p?.type;(u!==void 0||qs.has(m))&&(p.target={elementDescriptor:u??""})})}),e}),stopOnFailure:!0};var Nh={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var _h={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type;return r?.startsWith("PRESET_")&&(t.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let s=i.type;s?.startsWith("PRESET_")&&(i.type=s.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let s=i.command,a=s?.type;a?.startsWith("PRESET_")&&(s.type=a.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(c=>{let d=c.type;d?.startsWith("PRESET_")&&(c.type=d.slice(7))})}),e}),stopOnFailure:!0};var wr=[kh,Nh,_h,Mh,mh,hh,fh,yh,Sh,wh,vh,Th,Ch,Eh,Ah,Rh,Ph,Lh,Oh];if(mt!==wr[wr.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");wr.forEach((n,e)=>{if(!Ks.valid(n.toVersion)||!Ks.valid(n.fromVersion))throw new Error(`Migration '${n.name}' has invalid version`);if(!Ks.gt(n.toVersion,n.fromVersion))throw new Error(`Migration '${n.name}' has toVersion <= fromVersion`);if(e===0)return;if(wr[e-1].toVersion!==n.fromVersion)throw new Error(`Migration '${n.name}' at index ${e} is not contiguous with previous migration`)});function QT(n){return n.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var yi=async({metadata:n,steps:e,logger:t,toVersion:r})=>{let o=e,{schemaVersion:i,id:s}=n,a=wr.findIndex(d=>Ks.gt(d.toVersion,i));if(a===-1)return{steps:o,newVersion:i};let l=i;for(let d=a;d<wr.length;d++){if(r&&ZT(l,r)){t.debug("Stopping migration early because toVersion was reached");break}let p=wr[d],u={id:s,migration:p.name,toVersion:p.toVersion};try{o=await Fh(o,p),l=p.toVersion}catch(m){throw t.error({err:m,...u},"Migration failed"),new Error(`Step migration ${p.name} failed: ${m}`)}}let c=JT(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:s},"Migration diffs"),{newVersion:l,steps:o}};async function Fh(n,e){let t=await e.execute(n);for(let r of t)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let i=r[o];!i||!Array.isArray(i)||QT(i)&&(r[o]=await Fh(i,e))}return t}async function Dh({rawSteps:n,metadata:e,logger:t,callbacks:r}){uh(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:s}=await Ys({rawSteps:n.steps,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o}),a={...e,steps:i,schemaVersion:s};for(let l of["beforeSteps","afterSteps"]){let c=n[l];if(!c)continue;let{resolvedSteps:d}=await Ys({rawSteps:c,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o});a[l]=d}return{resolvedTest:a,moduleIds:Array.from(Object.keys(o))}}async function Ys({rawSteps:n,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:i,steps:s}=await yi({metadata:e,steps:n,logger:t}),a;try{a=We.array().parse(s)}catch(c){throw t.error({type:"zod",err:c,newVersion:i,id:e.id,steps:s},"Failed to parse test steps while migrating test"),new Bs(`Failed to parse test steps while migrating test: ${c}`,e.id,"entity",{cause:c})}let l=[];for(let c of a)l.push(await bi({step:c,callbacks:r,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:i}}async function bi({step:n,callbacks:e,logger:t,resolvedModuleCache:r}){switch(n.type){case"AI_ACTION":return n;case"AI_ACTION_DYNAMIC":return n;case"PRESET_ACTION":return n;case"MODULE":{let l=n.moduleId,c=r[l];if(c)return{...c,...n,type:"RESOLVED_MODULE"};let d=await e.onFetchModule({id:l,logger:t});if(!d)throw new Error(`Could not find module with id ${l}`);let{newVersion:p,steps:u}=await yi({metadata:{id:l,schemaVersion:d.schemaVersion},steps:d.steps,logger:t}),m;try{m=We.array().parse(u)}catch(f){throw t.error({type:"zod",err:f,steps:u,newVersion:p,id:l},"Module failed to parse"),f}let h;try{h=await Promise.all(m.map(f=>bi({step:f,callbacks:e,logger:t,resolvedModuleCache:r})))}catch(f){throw t.error({err:f,...n},`Failed to recursively resolve module '${d.name}': ${f}`),f}let g={...d,steps:h};return r[l]=g,{...g,...n,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of n.blocks){let c=[];for(let d of l.steps)c.push(await bi({step:d,callbacks:e,logger:t,resolvedModuleCache:r}));o.push({...l,steps:c})}let i;if(n.elseSteps){i=[];for(let l of n.elseSteps)i.push(await bi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}))}return{...n,blocks:o,elseSteps:i};case"SECTION":case"IFRAME":let s=[];for(let l of n.steps)s.push(await bi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}));return{...n,steps:s};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}import{cloneDeep as Uh}from"lodash-es";import{v4 as Cc}from"uuid";async function Lt(n){let e=new Map,t=new Set,r=Uh(n.stepLists.steps),o=await vr({...n,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let a=Uh(n.stepLists[s]);if(!a)continue;let l=await vr({...n,steps:a,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...l.cachesToSave),i.moduleUpdates.push(...l.moduleUpdates),i.stepsToSave[s]=l.stepsToSave}return i}async function vr({steps:n,...e}){let{seenModules:t,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:s,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of n)switch(delete c.index,delete c.aiSuggested,c.id=e.createNewStepIds?Cc():c.id,c.type){case"PRESET_ACTION":{let p=c.command;p.id=r?.createNewCacheIds?Cc():p.id,ih(p),"cache"in p&&p.cache&&(r&&(l.cachesToSave=l.cachesToSave.concat(oh({id:p.id,orgId:r.orgId,testId:r.testId,value:nr.parse(p),moduleIdParents:o,moduleStepParents:i,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete p.cache),p.thoughts&&delete p.thoughts,l.stepsToSave.push({...c,command:p});break}case"RESOLVED_MODULE":{let p=r?.createNewCacheIds?Cc():c.id,u=c.moduleId;s.has(u)?u=s.get(u):a!==void 0&&(u=await a(c),s.set(c.moduleId,u));let{cachesToSave:m,stepsToSave:h,moduleUpdates:g}=await vr({...e,steps:c.steps,cacheCreationParams:r?{...r,createNewCacheIds:!1}:void 0,moduleStepParents:[...i,p],moduleIdParents:[...o,u],skipCacheIntermediateEntries:r?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(g),l.cachesToSave=l.cachesToSave.concat(m),t.has(u)||(t.add(u),l.moduleUpdates.push({...vt.parse(c),steps:We.array().parse(h),moduleId:u}));let f={type:"MODULE",moduleId:u,inputs:c.inputs,id:p,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:p,cachesToSave:u}=await vr({...e,steps:c.steps});try{c.steps=wt.array().parse(p)}catch(m){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${m}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(u);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(c);break}case"CONDITIONAL":{let p=[];for(let m of c.blocks){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await vr({...e,steps:m.steps});p.push({...m,steps:h}),l.cachesToSave=l.cachesToSave.concat(g),l.moduleUpdates=l.moduleUpdates.concat(f)}let u={...c,elseSteps:void 0,blocks:p};if(c.elseSteps){let{stepsToSave:m,cachesToSave:h,moduleUpdates:g}=await vr({...e,steps:c.elseSteps});u.elseSteps=m,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(g)}l.stepsToSave.push(u);break}case"IFRAME":case"SECTION":{let{stepsToSave:p,cachesToSave:u,moduleUpdates:m}=await vr({...e,steps:c.steps}),h={...c,steps:p};l.moduleUpdates=l.moduleUpdates.concat(m),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(u);break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as eC}from"lodash-es";import{stringify as zh}from"yaml";async function Bh(n,e=new Set){let t={id:n.id,name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:n.schemaVersion,advanced:n.advanced,retries:n.retries,envs:n.envs,disabled:n.disabled,labels:n.labels},r={},o=await tC({originalStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},modules:r,processedModuleNames:e}),i={fileType:be.TEST,...t,beforeSteps:o.beforeSteps&&o.beforeSteps.length>0?o.beforeSteps:void 0,steps:o.steps,afterSteps:o.afterSteps&&o.afterSteps.length>0?o.afterSteps:void 0};return{test:zh(i),modules:r}}async function tC({originalStepLists:n,modules:e,processedModuleNames:t}){let r=eC(n);Object.values(r).forEach(s=>{nC(s??[])});let{stepsToSave:o,moduleUpdates:i}=await Lt({stepLists:r});for(let s of i)t.has(s.name)||(e[s.name]=rC(s),t.add(s.name));return o}function nC(n){wc({steps:n,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function rC(n){let e=vt.parse(n),t={fileType:be.MODULE,...e,schemaVersion:mt,steps:n.steps};return zh(t)}async function Q(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},n);function i(){clearTimeout(o),e?.removeEventListener("abort",i),r(e?.reason)}})}async function Si({promiseGenerator:n,signal:e,codePath:t,logger:r}){let i=Date.now(),s=setInterval(()=>{if(e?.aborted){clearInterval(s);return}r?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((a,l)=>{function c(){clearInterval(s),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(s);return}e?.addEventListener("abort",c),(async()=>{try{a(await n())}catch(d){l(d)}finally{clearInterval(s),e?.removeEventListener("abort",c)}})()})}async function xr({promiseGenerator:n,timeoutMs:e,codePath:t,logger:r,signal:o}){let i=!1,s=new AbortController,a=()=>{s.abort()},l=setTimeout(()=>{i||s.abort()},e);o?.addEventListener("abort",a);try{return await Si({promiseGenerator:n,signal:s.signal,codePath:t,logger:r})}finally{i=!0,o?.removeEventListener("abort",a),clearTimeout(l)}}function Xs(n){let e=[];for(let t of n)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let r={...t,type:"MODULE"};e.push(Tn.parse(r));break}case"IFRAME":case"SECTION":{let r={...t,steps:Xs(t.steps)};e.push(We.parse(r));break}case"CONDITIONAL":{let r={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:Xs(o.steps)})),elseSteps:t.elseSteps?Xs(t.elseSteps):void 0};e.push(or.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Js(n){return Xs([n])[0]}import oC from"picomatch";var Ec=(n,e,t)=>{t?.caseInsensitive&&(n=n.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;r=n.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;r=n===e.glob||oC(o)(n);break}case"REGEX":{r=new RegExp(e.regex).test(n);break}}return t?.negated?!r:r};var to=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,r){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:r}=eo({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(r,e.logger)}};var no="v1",Un=class{httpClient;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}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${no}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof Qt?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${no}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${no}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${no}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${no}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${no}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Qt?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as iC}from"zod";var ro=class extends At{constructor(e){super(e)}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Ku.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${_}/web-agent/recommend-chunks`,{method:"POST",body:e,signal:t.abortSignal});return qu.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${_}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return iC.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Em.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return fc.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return fc.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${_}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Cm.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${_}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${_}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return _l.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${_}/web-agent/reverse-mapped-description`,{method:"POST",body:{goal:e.goal,browserState:e.browserState,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Am.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return Nl.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${_}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Vl.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${_}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Vu.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${_}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Up.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${_}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return zp.parse(r)}};var Tr=class extends At{async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${_}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Cp.parse(r)}async constructIframeRegex(e,t={}){let r=await this.sendRequest(`/${_}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t?.signal});return Tp.parse(r)}};import{Server as gR}from"socket.io";var sC={showOverlay:!1},Ac=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:r,clientIp:o,sessionId:i,browserbaseSessionId:s}){return this.sessions.set(i,{controller:e,context:t,cleanup:r,clientIp:o,browserbaseSessionId:s,browserBehavior:sC}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(s){t.error({err:s},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(s){t.error({err:s},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}},K=new Ac;var aC=parseInt(process.env.MOMENTIC_SCREENSHOT_INTERVAL||"150");function jh(n,e,t){let r=Date.now(),o=-1,i,s=0,a=!1,l=Date.now(),c,d,p,u,m=!1,h=async(v,b)=>{if(!v.closed){{if(v.isInPageLoad)return;if(a)return}if(s>0&&Math.random()>=1/Math.max(s,8)){s===3&&t.warn("Screenshots are being dropped due to previous failures");return}try{a=!0;let E=p;p=void 0;let x=await v.screenshot({retries:0,timeout:750,scale:"device",quality:75});i&&x.equals(i)?x=void 0:i=x;let C=v.url(),L=b.toEditorDisplayCopy();x===void 0&&JSON.stringify(L)===JSON.stringify(c)&&C===u&&r>l||(n.emit("browserState",{logsPerPage:E?.logsPerPage,harPages:E?.harPages,harEntries:E?.harEntries,viewport:v.getViewport(),buffer:x,url:C,iframeSrcUrls:d??[],context:L,isInPageLoad:v.isInPageLoad}),r=Date.now()),u=C,c=L,s=0}catch(E){if(!n.connected)return;let x=E instanceof Error?E.message:`${E}`;if(x.includes("Frame was detached")||x.includes("Not attached to an active page")||x.includes("browser has been closed")||x.includes("UserInfrastructureError"))return;s++,t.error({err:E,sessionId:e},"Error taking screenshot")}finally{a=!1,n.connected&&s>10&&Date.now()-o>6e4&&(t.error({sessionId:e},"Screenshots to client are stale"),o=Date.now())}}},g=setInterval(()=>{let v=K.getSession(e),b=v?.controller?.browser;if(!b||b.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(g);return}h(b,v.context)},aC),f=(v,b)=>!!(JSON.stringify(v)!==JSON.stringify(d)||b.logsPerPage.some(E=>E.length>0)||b.harPages&&Object.keys(b.harPages).length>0||b.harEntries&&Object.keys(b.harEntries).length>0),y=setInterval(async()=>{let b=K.getSession(e)?.controller?.browser;if(!b||b.closed){clearInterval(y);return}else if(m)return;m=!0;try{let E=await b.getAllFrameUrls(),x=b.retrieveAndClearDebugData();f(E,x)&&(d=E,p=x,l=Date.now())}catch(E){t.warn({err:E},"Failed to fetch extended details")}finally{m=!1}},2500);return{timers:[g,y]}}var zn={};var lC=n=>()=>{let{sessionId:e}=n.metadata;zn[e]?.abort?.abort()},$h={event:"cancelApiTest",createHandler:lC};import{CookieJar as TC}from"tough-cookie";import{randomUUID as fC}from"crypto";import{faker as cC}from"@faker-js/faker";import dC from"assert";import pC from"axios";import uC from"moment";import*as mC from"otpauth";import hC from"pg";var oo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Hh=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};async function B(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a;return new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&c(Hh(p)),a=()=>{c(Hh(p))},p.addEventListener("abort",a)}if(t===Number.POSITIVE_INFINITY){n.then(l,c);return}let d=new oo;s=i.setTimeout.call(void 0,()=>{if(r){try{l(r())}catch(p){c(p)}return}"cancel"in n&&typeof n.cancel=="function"&&n.cancel(),o instanceof Error?c(o):(d.message=o??`Promise timed out after ${t} milliseconds`,c(d))},t),(async()=>{try{l(await n)}catch(p){c(p)}})()}).finally(()=>{s!==void 0&&i.clearTimeout.call(void 0,s),a!==void 0&&e.signal&&e.signal.removeEventListener("abort",a)})}async function Wh(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Fs(r,e);t.push(...o)}),t}var gC=Object.getPrototypeOf(async function(){}).constructor;async function Gh(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,s={},a=(f,y)=>{o[f]=y,s[f]=y},l={},c=(f,y)=>{o[f]=y,l[f]=y},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let p;r.includes("createAppAuth")&&(p=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new gC("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(pC,uC,cC,dC,hC,d,p,mC,Wh,o,a,c,y=>i.sms.send(y),y=>i.sms.fetchLatest(y),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await B(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error(`[${n}] Error executing code: ${f}`),m=!1,f instanceof oo?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:s,persistentVariableUpdates:l,success:m,error:g}}async function Vh({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:s=Zr}){let a=fC(),l=await Gh(a,{code:n,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:r,signal:i},o);return S.debug(`[${a}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as yC,randomUUID as bC}from"crypto";var qh=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Kh=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Yh({orgId:n,code:e,fragment:t,context:r,logger:o,timeoutMs:i=Zr,retries:s=1,signal:a}){if(!qh)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Kh)throw new Error("Missing lambda auth secret.");let p=yC("sha256",Kh).update(n).digest("hex");for(;d<=s;){d++,a?.throwIfAborted();let m={id:bC(),orgId:n,momenticLambdaAuthHash:p,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:i};try{if(l=await B(fetch(qh,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:i,message:`Timeout of ${i}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=tm.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function An(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Yh(n);else if(n.localTools)e=await Vh({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation error: ${e.error}`);if(e.variableUpdates)for(let[t,r]of Object.entries(e.variableUpdates))n.context.setVariable(t,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await n.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,r]of Object.entries(e.persistentVariableUpdates))n.context.setVariable(t,r)}return e.result}async function Ot(n){let{orgId:e,s:t,context:r,logger:o,timeoutMs:i=Zr,retries:s=1,signal:a,allowUndefined:l=!1}=n,c=/{{(.*?)}}/g,d=t.matchAll(c),p=t;for(let u of d){if(u.length<2)continue;let m=u[1].trim(),h;try{h=await An({orgId:e,code:m,fragment:!0,context:r,timeoutMs:i,logger:o,retries:s,localTools:n.localTools,signal:a})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(h===void 0&&!l)throw new A("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let g=typeof h=="string"?h:`${h}`;g=g.replaceAll(/\$/g,"$$$$"),p=p.replace(u[0],g)}return p}async function io(n){return Xh(n)}async function Xh({obj:n,bannedKeys:e,allowList:t,context:r,prefixPath:o="",replacements:i={},...s}){for(let a in n){if(e.includes(a))continue;let l=!1;if(t)if(t.includes(a))l=!0;else continue;let c=n[a],d=o?`${o}.${a}`:a;if(typeof c=="string"&&c.includes("{{")){let p=await Ot({s:c,context:r,...s});if(c===p)continue;i[d]=c,n[a]=p}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await Xh({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:i,allowList:l?void 0:t,...s})}return i}import wC from"fetch-cookie";import{cloneDeep as vC}from"lodash-es";var Zs=(n,e)=>{try{let{hostname:t,pathname:r}=new URL(n),{hostname:o,pathname:i}=new URL(e);return t!==o||r!==i}catch{return!1}},so=n=>{try{return new URL(n),!0}catch{return!1}},Jh=n=>!n.toLowerCase().startsWith("http"),ao=(n,e)=>{try{return new URL(n,e),!0}catch{return!1}};function Bn(n,e){try{return!!new URL(n).origin.trim()}catch(t){return e?.error({url:n,err:t},"Invalid URL in check"),!1}}var SC=3e4;async function Qs({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??SC/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([m,h])=>m&&h)),s=new URLSearchParams;Object.entries(n.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{s.append(m,h)});let a=s.toString(),l;if(so(n.url)&&(l=n.url),t&&ao(n.url,t)&&(l=new URL(n.url,t).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${n.url}`);let d=await B((async()=>{let m=a?`${l}?${a}`:l;try{return await r(m,{headers:i,method:n.method,body:n.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok)throw new A("ActionFailureError",`Fetch request failed with status ${d.status}`);let p={};d.headers.forEach((m,h)=>{p[h]=m});let u={status:d.status,headers:p};return d.headers.get("content-type")?.includes("json")?u.json=await d.json():d.headers.get("content-type")?.includes("text")&&(u.text=await d.text()),u}async function Zh(n){let{fixtures:e,inputs:t}=n,{context:r}=e,{orgId:o,step:i}=t,s=vC(i);await io({obj:s,orgId:o,bannedKeys:["code"],...e});let a=await xC(n);return s.envKey&&a.data&&r.setVariable(s.envKey,a.data),a}async function xC(n){let{fixtures:e,inputs:t}=n,{step:r,orgId:o,baseUrl:i}=t,{cookieJar:s}=e,a=new Date;switch(r.type){case"JAVASCRIPT":{let c=await An({code:r.code,orgId:o,fragment:!!r.fragment,timeoutMs:r.timeout?r.timeout*1e3:void 0,...e});try{JSON.stringify(c)}catch(d){return{...r,startedAt:a,finishedAt:new Date,status:"FAILED",message:`JavaScript return value is not serializable: ${d instanceof Error?d.message:`${d}`}`}}return{...r,startedAt:a,finishedAt:new Date,message:"JavaScript code executed successfully",status:"SUCCESS",data:c}}case"REQUEST":{let c=wC(fetch,s),d=await Qs({command:r,logger:e.logger,baseUrl:i,fetchImplementation:c});return{...r,startedAt:a,finishedAt:new Date,status:"SUCCESS",message:"Request executed successfully",data:d}}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}async function Qh(n){let{inputs:e,fixtures:t,callbacks:r}=n,{signal:o}=t,{steps:i,orgId:s,baseUrl:a}=e,{test:l,step:c}=r,d={startedAt:new Date,status:"RUNNING",results:[]},p=d.results,u=new TC,m={cookieJar:u,...t};for(let h of i){let g=new Date;c.onStarted?.(h.id);let f;try{o?.throwIfAborted(),f=await Zh({inputs:{step:h,baseUrl:a,orgId:s},fixtures:m})}catch(y){o?.aborted?f={...h,startedAt:g,finishedAt:new Date,status:"CANCELLED",message:"Step cancelled by user."}:f={...h,startedAt:g,finishedAt:new Date,status:"FAILED",message:`Step failed: ${y instanceof Error?y.message:`${y}`}`}}if(p.push(f),c.onFinished?.({result:f,cookies:Us(u,new URL(a).hostname)}),l.updateAttemptProgress?.({results:p}),f.status!=="SUCCESS"){d.status=f.status==="CANCELLED"?"CANCELLED":"FAILED";break}}return d.status==="RUNNING"&&(d.status="PASSED"),d.finishedAt=new Date,l.onFinished?.(),d}async function eg(n){let{socket:e,storage:t}=n,r=n.socket.id,{testId:o}=e.handshake.query;if(typeof o!="string")throw new Error(`Received invalid test ID that does not parse as a string: ${o}`);let i=await t.getOrgId({type:"api-test",testId:o}),{baseUrl:s,envName:a,environmentVariables:l}=await Rc({testId:o,orgId:i,logger:n.logger,storage:t,authorization:n.authorization}),c={type:"api-test",orgId:await n.storage.getOrgId({type:"api-test",testId:o}),testId:o,sessionId:r,latestContext:new Tt({baseUrl:s||"",currentUrl:s||"",variablesFromEnvironment:l,envName:a})};return zn[r]=c,c}async function Rc({testId:n,orgId:e,logger:t,storage:r,authorization:o}){let i=await r.fetchApiTestMetadata(n,e,t);if(!i)throw new Error(`Failed to fetch API test metadata for test ID: ${n}`);let s;o?.type==="API_KEY"&&(s=new Un({httpClient:new At(o)}));let a=i.envs?.find(p=>p.default),l;a&&(l=await r.fetchEnvironment(e,a.name,t));let c=i.baseUrl||l?.variables?.[ve];if(!c)throw new Error("Base URL is empty in both API test options and the configured environment");let d={...l?.variables};return{baseUrl:c,envName:l?.name,environmentVariables:d,localCodeEvalTools:s}}var CC=n=>async(e,t)=>{let{steps:r}=e,{authorization:o,metadata:i,socket:s,storage:a,logger:l}=n,{orgId:c,testId:d,sessionId:p}=i,u=l.child({testId:d,orgId:c,sessionId:p}),m=zn[p];if(!m)throw new Error(`No api testing session with id ${p} could be found. Please reconnect and try again.`);let h=new AbortController;m.abort=h;let g=m.latestContext,{localCodeEvalTools:f,baseUrl:y}=await Rc({testId:d,orgId:c,logger:u,storage:a,authorization:o}),v={context:g,logger:u,localTools:f,signal:h.signal},x=await Qh({inputs:{steps:r,orgId:c,baseUrl:y},fixtures:v,callbacks:{test:{onFinished:()=>{s.emit("apiTestFinished")}},step:{onStarted:C=>{s.emit("apiStepStarted",C)},onFinished:C=>{s.emit("apiStepFinished",C)}}}});t({result:x})},tg={event:"executeApiTest",createHandler:CC};var EC=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{e.info({sessionId:t},"Cancel event received");let r=K.getSession(t);if(!r)throw new Error("No active session found");try{r.controller.setClosed()}catch{}}},ng={event:"cancel",createHandler:EC};var AC=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=K.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.getBrowserState({skipWait:!0});o({a11yTree:a.serialize()})}catch(a){e.error({err:a},"Error fetching a11y tree from the browser"),o({err:a.message})}}},rg={event:"fetchA11yTree",createHandler:AC};var RC=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=K.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.html();o({html:a})}catch(a){e.error({err:a},"Error fetching DOM from the browser"),a.name==="TimeoutError"?o({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):o({err:a.message})}}},og={event:"fetchDom",createHandler:RC};var IC=({metadata:n,logger:e})=>{let{sessionId:t,type:r}=n;return o=>{e.info({sessionId:t,reason:o},`Disconnect event received (${o})`),r==="e2e"?K.removeSession(t,e):r==="api-test"&&delete zn[t]}},ig={event:"disconnect",createHandler:IC};import{diff as ZA}from"deep-object-diff";function $t(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=PC(t);LC(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await OC(i,e,r,o)}catch(s){n.logger.error({result:n.result,err:s},"Error hoisting scalar result metadata")}})())}function PC(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function LC(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function OC(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeScreenshot=t.beforeScreenshot),r&&(e.afterScreenshot=r.afterScreenshot)}import wi from"os";import kC from"v8";var sg,mn,Ic=wi.platform(),MC=wi.cpus().map(n=>({model:n.model,speed:n.speed}));function ag(n){n.debug({platform:Ic,cpuMetadata:MC},"Platform and CPU clock speed metadata");let e=()=>{try{let t=!1,r=NC(),o=_C();r.freeMemory<1e6&&(t=!0);let i=kC.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(t=!0),t?n.warn({platform:Ic,memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({platform:Ic,memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),setInterval(e,1e4)}function NC(){let n=wi.totalmem(),e=wi.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function _C(){let n=wi.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!mn)return mn=t,null;let r={user:t.user-mn.user,nice:t.nice-mn.nice,sys:t.sys-mn.sys,idle:t.idle-mn.idle,irq:t.irq-mn.irq,total:t.total-mn.total};return sg={measurementTime:e,intervalMs:e-mn.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},mn=t,sg}async function lo(n,e,t,r,o,i){try{let[s,a]=await Promise.all([t?o(t):void 0,r?o(r):void 0]);s&&(n&&(n.beforeScreenshot=s),e.beforeScreenshot=s),a&&(n&&(n.afterScreenshot=a),e.afterScreenshot=a)}catch(s){i.debug({err:s},"Error saving screenshot to S3")}}import{hostname as BC}from"os";async function dg(n){let{command:e,timeoutMs:t,targetingWrapper:r,disableCache:o,fixtures:i}=n,{logger:s,abortSignal:a}=i;if(e.target&&!kn(e.target))throw new Error("Element assertion with x/y is not supported yet");let l=Date.now(),c=0,d,p=500;for(;c<2||Date.now()-l<t;){c++,c>1&&await Q(p,a),a?.throwIfAborted(),s.debug({currentSleepDuration:p,attempts:c},"Attempting manual element assertion");try{let{newTarget:u,elementInteractedDisplayString:m,result:h}=await r({ctx:i.ctx,command:e,target:e.target,cache:e.cache?.target,action:async g=>FC(g.locator,n),options:{disableCache:o,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl,disableGlobalLocatorRedirect:!0}});if(d={success:h.success,data:h.data,err:h.err,newTarget:u,elementInteractedDisplayString:m},!h.success){d=h,p=Math.min(p*2,1e4);continue}return d}catch(u){if(a?.throwIfAborted(),s.warn({err:u},"Element assertion ended in error, retrying..."),e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated)return{success:!0,thoughts:`The element described does not exist on the page: ${u.message}`};if(!(u instanceof A)||u.reason!="ActionFailureError")throw u;d={success:!1,err:u}}}if(!d)throw new Error(`Failed to evaluate manual element assertion in ${t}ms.`);return d}async function FC(n,{command:e,fixtures:t}){let r=e.assertion;await t.browser.highlight(n);let o=!0,i,s;switch(r.type){case"ELEMENT_CONTENT":{let a=await n.textContent()??"";if(s={elementTextContent:Ne(a,500,!0)},!cg(a,r.value,r.operation,!!r.negated)){let l=r.negated?fr[r.operation]:yr[r.operation];o=!1,i=new A("AssertionFailureError",`The content ${l} '${r.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{s={elementOuterHtml:Ne(await n.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await n.getAttribute(r.attr,{timeout:3e3})??""}catch(l){i=new A("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${l}`),o=!1;break}if(!cg(a,r.value,r.operation,!!r.negated)){let l=r.negated?fr[r.operation]:yr[r.operation];o=!1,i=new A("AssertionFailureError",`The attribute ${r.attr} ${l} '${r.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await n.isVisible({timeout:xn*1e3});break}case"EDITABLE":{o=await n.isEditable({timeout:xn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await n.isEnabled({timeout:xn*1e3});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 a=r.negated?vc[r.condition]:xc[r.condition];i=new A("AssertionFailureError",`The element ${a}`)}break}}return{success:o,data:s,err:i}}var DC=5e3;async function ea({timeout:n=xn,...e}){let t=Date.now(),r=n*1e3,o=r+1e4,i,s=0,a=500,l=0;for(;s-t<r;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted(),l++,(l<5||l%10===0)&&e.logger.debug({currentSleepDuration:a,attempts:l},"Attempting page assertion");let c=Date.now();i=await lg({...e,returnHtml:!1}),s=Date.now();let d=s-c;if(d>1e3&&e.logger.warn({pageAssertDuration:d},"Page assertion took longer than expected"),!i.success)await Q(a,e.signal),a=Math.min(Math.floor(a*1.5),DC);else return i}return i=await lg({...e,returnHtml:!0}),i}async function lg({assertion:n,browser:e,returnHtml:t}){switch(n.type){case"CONTENT":{let o,i=!0,s;try{let{evaluation:a,pageHtml:l}=await e.evaluateFunctionInPage({...n,returnHtml:t},c=>{let d=document.documentElement.outerHTML,p=d.includes(c.value)===!c.negated;return{evaluation:p,pageHtml:!p&&c.returnHtml?d:void 0}});if(a)i=!0;else{i=!1;let c=n.negated?fr.CONTAINS:yr.CONTAINS;s=new A("AssertionFailureError",`The page ${c} '${n.value}'.`),o=l}}catch(a){s=new A("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:i,err:s,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function cg(n,e,t,r){let o;switch(t){case"CONTAINS":{o=n.includes(e);break}case"EQUALS":{o=n.trim()===e.trim();break}case"STARTS_WITH":{o=n.trim().startsWith(e);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return r?!o:o}import{Jimp as UC}from"jimp";async function vi(n,e){let t=await n.screenshot(e),r=await UC.fromBuffer(t);return{buffer:t,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as pg}from"jimp";import Pc from"jpeg-js";import zC from"pixelmatch";async function ug({ctx:n,command:e,disableCache:t,browser:r,targetingWrapper:o,logger:i,screenshotStorage:s}){if(e.target&&!kn(e.target))throw new Error("Visual Diff with x/y is not supported yet");await r.waitForDOMStability({logger:i});let a={clearHighlights:!0,hideCaret:!0},l;e.target?.elementDescriptor?l=(await o({ctx:n,command:e,target:e.target,cache:e.cache?.target??e.target?.a11yData,action:async U=>vi(r,{locator:U.locator,...a}),options:{disableCache:!!t,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl,disableGlobalLocatorRedirect:!0}})).result:l=await vi(r,a);let c=await s.prepareGoldenScreenshotForComparison(i,e,l);if((l.height!==c.height||l.width!==c.width)&&i.debug({currHeight:l.height,currWidth:l.width,savedHeight:c.height,savedWidth:c.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-c.height)>10||Math.abs(l.width-c.width)>10){let P=`${l.width}x${l.height}`,U=`${c.width}x${c.height}`;return{fail:!0,thoughts:`Current screenshot (${P}) does not match saved screenshot dimensions (${U}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:r.url()}}let d=await pg.fromBuffer(l.buffer),p={width:l.width,height:l.height},u=await pg.fromBuffer(c.buffer),m={width:c.width,height:c.height},h,g=p.width*p.height,f=m.width*m.height,y=Math.abs(p.height-m.height),v=Math.abs(p.width-m.width);if(g>f){let P=d.cover({w:m.width,h:m.height});l.buffer=await P.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(f>g){let P=u.cover({w:p.width,h:p.height});c.buffer=await P.getBuffer("image/jpeg"),h="saved"}let b={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},E=e.threshold??.1,C=zC(Pc.decode(c.buffer).data,Pc.decode(l.buffer).data,b.data,l.width,l.height,{threshold:E,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,L=C>E*100,N=`Visual diff of ${C.toFixed(2)}% detected, which is ${L?"over":"under"} the threshold of ${E*100}%.`;return h&&(N+=` The ${h} screenshot was cropped since it was taller by ${y} pixels and wider by ${v} pixels.`),{fail:L,thoughts:N,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Pc.encode(b,75).data,succeedImmediately:!1,urlAfterCommand:r.url()}}var Lc=async n=>{let{step:e,resolvedInputs:t}=n.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:s,controller:a}=n.fixtures,l=a.browser,{orgId:c,runId:d}=n.inputs,p=a.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),r.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",y=await Ot({orgId:c,s:f,context:o,logger:r,localTools:s,signal:p});g={orgId:c,cacheKeys:[y,...Object.entries(t).map(([b,E])=>`${b}:${E}`)]},r.debug({original:f,keyParams:g},"Module cache key params");let v=Date.now();for(;Date.now()-v<Tm;){p?.throwIfAborted();let b=await i.getCacheResult(g);if(b){r.debug({cacheResult:b},"Got result from module execution cache"),u=ta(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(b),m=!0;break}else r.debug({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let E=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${BC()};runId:${d}`},p);if(E.acquired){h=E.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await Q(2500+Math.random()*1e4,p)}}try{if(!u)u=await jC(n);else if(e.autoAuth){let f=Ds.safeParse(u.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,v=e.advanced?.cacheInvalidation;if(v&&v.type==="PAGE_CHECK"){let b={type:"CONTENT",value:v.substring},E=await ea({timeout:xn,assertion:b,browser:l,logger:r,signal:p});E.success?r.debug({invalResult:E},"Cached result still valid after page check, continuing..."):(r.info({invalResult:E},"Invalidating cached result due to page check failure"),y=!0)}if(g&&y)return await i.deleteCacheResult(g),Lc(n)}}finally{try{h!==void 0&&!m&&u?.status==="SUCCESS"&&await $C({step:e,result:u,browser:a.browser,cacheKeyPrefix:h,logger:r,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return u},jC=async n=>{let{step:e}=n.moduleParams,t=ta(e,n.moduleParams.resolvedInputs,"SUCCESS"),{status:r,results:o}=await jn(n.work,()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:`module ('${e.name}')`}}));return t.results=o,t.status=r,t.finishedAt=new Date,$t({asyncTasks:n.work.asyncTasks,nestedResults:o,result:t,logger:n.fixtures.logger}),t};function ta(n,e,t){let r={};return Object.entries(e).forEach(([i,s])=>{r[i]=JSON.stringify(s)}),{type:"MODULE",id:n.id,moduleId:n.moduleId,moduleName:n.name,startedAt:new Date,cacheConfig:n.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:t}}async function na({orgId:n,step:e,context:t,logger:r,codeEvalTools:o,signal:i}){let s={};try{for(let a of e.parameters??[]){let l=e.inputs?.[a]??e.defaultParameters?.[a];if(!l){r.warn(`No value or default found for parameter '${a}' that is required by module '${e.name}'`);continue}s[a]=await An({orgId:n,code:l,fragment:!0,context:t,logger:r,localTools:o,signal:i})}return s}catch(a){throw i?.throwIfAborted(),new A("UserConfigurationError",`Failed to evaluate module inputs: ${a}`)}}async function $C({step:n,result:e,browser:t,cacheKeyPrefix:r,logger:o,storage:i}){let s=n.cacheConfig?.cacheExpiryMs;(!s||s===Vm)&&(s=n.defaultCacheTtl??qm);let a;n.autoAuth?a=JSON.stringify(await t.saveAuthState()):e.data!==void 0?a=JSON.stringify(e.data):a='""',o.debug({cacheKeyPrefix:r,ttlMs:s,truncatedCacheResultJson:ph(a)},"Setting module cache result"),await i.setCacheResult({result:a,keyPrefix:r,ttlMs:s})}async function $n(n,e,t){let r=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,s="FAILED",a;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(a="Step aborted by user.",s="CANCELLED"):o instanceof A?a=`${o}`:a=`An unexpected error occurred: ${o.message}`,n.type==="RESOLVED_MODULE"){let l=ta(n,{},"FAILED");return l.message=a,l.startedAt=r,l.finishedAt=i,l}return{...Js(n),startedAt:r,finishedAt:i,status:s,data:null,message:a,results:[]}}}async function jn(n,e){let t=!1;try{return n&&!n.state.failureRecoveryDisabled&&(n.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{n&&t&&(n.state.failureRecoveryDisabled=void 0)}}import{randomUUID as mg}from"crypto";import{cloneDeep as WC}from"lodash-es";function ra(n,e){n.state.healingDetails?n.state.healingDetails.push(e):n.state.healingDetails=[e]}var oa=async n=>{let e=n.presetParams.step,{logger:t,controller:r,context:o,billingReporter:i}=n.fixtures,{collectDebugData:s}=n.options,{orgId:a,testMetadata:l,suiteMetadata:c}=n.inputs,d=e.command.type,p=t.child({commandType:d,stepId:e.id,commandId:e.command.id}),u=sc(e.command);n.work.asyncTasks.push(i.reportCreditsUsed(p,d,u,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let m=n.callbacks.test,h=r.browser.url(),g=new Date,f,y;if(s)try{f=await r.browser.screenshot({retries:1,clearHighlights:!0}),y=mg();let C=await r.browser.getRawCondensedHtml();n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(p,a,y,C))}catch(C){p.debug({err:C},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let v,b,E,x=ks();try{let C=await r.executePresetCommand(x,e.command,o,l?.advanced.disableAICaching??!1);C.beforeScreenshotOverride&&(f=C.beforeScreenshotOverride),E=C.afterScreenshotOverride;let{proposedStep:L}=GC({work:n.work,step:e,newTargets:C.newTargets,logger:p}),N=new Date,P=r.browser.url();b={beforeUrl:h,afterUrl:P,startedAt:g,finishedAt:N,viewport:r.browser.getViewport(),status:C.fail?"FAILED":"SUCCESS",elementInteracted:C.elementInteracted},v={...e,message:C.thoughts??VC(C.newTargets)??"Successfully executed preset action.",beforeUrl:h,afterUrl:P,finishedAt:N,startedAt:g,status:C.fail?"FAILED":"SUCCESS",data:C.data,results:[b],details:x.details,proposedStep:L},"assertion"in e.command&&(v.message=C.thoughts||"Assertion passed.")}catch(C){p.error({message:C.message,stack:C.stack},`Failed executing preset step ${br(e.command)}`);let L=r.browser.url(),N=new Date,P=C instanceof Error?C.message:`${C}`;C instanceof A&&C.getLastScreenshotBuffer()&&(E=C.getLastScreenshotBuffer()),b={beforeUrl:h,afterUrl:L,startedAt:g,finishedAt:N,viewport:r.browser.getViewport(),status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:P},v={...e,startedAt:g,finishedAt:N,beforeUrl:h,afterUrl:L,status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:P,failureReason:C instanceof A?C.reason:void 0,results:[b],details:x.details}}if(s)try{E||(E=await r.browser.screenshot({retries:1}));let C=mg(),L=await r.browser.getRawCondensedHtml();b.beforeSnapshot=y,v.beforeSnapshot=y,b.afterSnapshot=C,v.afterSnapshot=C,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(p,a,C,L))}catch(C){p.debug({err:C},"Failed to take screenshot after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return n.work.asyncTasks.push(lo(b,v,f,E,m.onSaveScreenshot,p)),v};function GC({work:n,step:e,newTargets:t,logger:r}){if(!t?.length)return{proposedStep:void 0};let o=e.command;ah(o,t,r);let i=t[0]?.description;if(i&&"target"in o&&o.target&&o.target.type==="description"){let s={...o,target:{...o.target,elementDescriptor:i}},a={...WC(e),command:s};return ra(n,{type:"DESCRIPTION_UPDATE",thoughts:`Updated element description after the original element could not be found on the page. New element location reasoning: ${t[0]?.thoughts}`}),{proposedStep:a}}return{proposedStep:void 0}}function VC(n){if(n?.length){if(n.length===1&&n[0]?.thoughts)return n[0].thoughts;if(n.length===2&&n.every(e=>e.thoughts))return`Located first element: ${n[0]?.thoughts}
42
42
  Located second element: ${n[1]?.thoughts}`}}var Oc=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];function hg(n){return new Array(n).fill(0).map(()=>Oc[Math.floor(Math.random()*Oc.length)]).join("-")}async function gg({codePath:n,screenshotBuff:e,storage:t,logger:r}){if(e)try{let o=await t.uploadScreenshot(e);return r.debug({screenshotUrl:o,codePath:n},"Saved screenshot for debugging"),o}catch(o){r.error({err:o,codePath:n},"Failed to save screenshot for debugging")}}async function hn({frameConfig:n,action:e,browser:t}){let r=t.getActiveFrameConfig();try{return n?t.setActiveFrameConfig(n):r?.type==="auto"&&t.setActiveFrameConfig(void 0),await e()}finally{t.setActiveFrameConfig(r)}}var fg="MOMENTIC_RUN_ID",yg="FINAL_SCREENSHOT_URL";import{cloneDeep as tE}from"lodash-es";async function bg(n){let{step:e}=n.conditionalParams,{logger:t,controller:r}=n.fixtures,o=new Date,i=Js(e),s=e.elseSteps,a=!0,l=[],c,d=ks();for(let h=0;h<e.blocks.length;h++){t.info(`Evaluating condition ${h} in conditional step`);let g=e.blocks[h];try{let f=await oa({...n,presetParams:{step:g.assertion}});l.push(f),t.info(`Condition ${h} resolved to true, executing the corresponding ${g.steps.length} steps`),a=!1,s=g.steps,c=f}catch(f){t.info({err:f},`Condition ${h} resolved to false`)}finally{r.throwIfClosed()}}if(s)a&&t.info("No conditions resolved to true, executing the else block steps");else return t.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...i,status:"SUCCESS",startedAt:o,data:l[l.length-1]?.data,message:l[l.length-1]?.message,results:[],finishedAt:new Date,details:d.details};t.info(`Executing ${s.length} steps in the selected conditional block`);let p=await n.executeStepList({...n,listParams:{steps:s,containerName:"conditional block"}}),m={...i,assertion:c,...p,startedAt:o,finishedAt:new Date};return $t({asyncTasks:n.work.asyncTasks,nestedResults:[...l,...p.results],result:m,logger:t}),m}var Sg=async n=>{let{controller:e}=n.fixtures;await e.browser.waitForDOMStability();let t=await e.browser.screenshot({}),r=await qC(n);r.finishedAt=new Date,$t({asyncTasks:n.work.asyncTasks,result:r,nestedResults:r.results,logger:n.fixtures.logger});let o=await e.browser.screenshot({});return n.work.asyncTasks.push(lo(void 0,r,t,o,n.callbacks.test.onSaveScreenshot,n.fixtures.logger)),r},qC=async n=>{let e=n.aiStepParams.step,{controller:t,context:r,logger:o}=n.fixtures,i={...e,startedAt:new Date,beforeTestContext:r.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{status:a}=await n.executeStepList({...n,listParams:{steps:e.steps,containerName:"AI action",results:i.results}});return i.finishedAt=new Date,i.status=a,i}catch(a){o.warn({err:a},"Failed executing saved deprecated AI action steps");let l=t.executeAbortController.signal.aborted;i.message=a instanceof Error?a.message:`${a}`,i.status=l?"CANCELLED":"FAILED"}return i};import{randomUUID as KC}from"crypto";var wg=15,vg=async n=>{let{controller:e}=n.fixtures;await e.browser.waitForDOMStability();let t=await e.browser.screenshot({}),r=await YC(n);r.finishedAt=new Date,$t({asyncTasks:n.work.asyncTasks,result:r,nestedResults:r.results,logger:n.fixtures.logger});let o=await e.browser.screenshot({});return n.work.asyncTasks.push(lo(void 0,r,t,o,n.callbacks.test.onSaveScreenshot,n.fixtures.logger)),r},YC=async n=>{let e=n.aiStepParams.step,{testMetadata:t,orgId:r}=n.inputs,{controller:o,context:i,logger:s,codeEvalTools:a}=n.fixtures,{test:l,step:c}=n.callbacks,d=`${e.id}-${Date.now()}`,p=s.child({stepId:e.id,langfuseSessionId:d}),u={...e,startedAt:new Date,beforeTestContext:i.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await Ot({orgId:r,s:e.text,context:i,logger:p,localTools:a});await o.browser.waitForDOMStability({logger:p});let g=`data:image/jpeg;base64,${(await o.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],y=0,v=0,b,E;for(;;){if(y>wg)return u.message=`Exceeded the maximum number of commands allowed per AI step (${wg})`,u.status="FAILED",u;if(o.executeAbortController.signal.aborted)return u.message="Test execution was cancelled",u.status="CANCELLED",u;c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let x=await o.evaluateAiAction({goal:m,startingScreenshot:y===0?void 0:g,history:f,logger:p,langfuseSessionId:d,lastError:E}),{evaluation:C,reasoning:L,summary:N}=x;p.info(x,"Got AI evaluation");let P=u.results[y-1]?.id;switch(C.type){case"DONE":return u.message=`Our AI evaluator confirmed all tasks are complete: ${L}`,u.status="SUCCESS",P&&c.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:`${N}
43
43
  ${L}`}),u;case"RIGHT_TRACK":{b=void 0,y===0?c.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:L}):P&&c.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:L});break}case"WRONG_TRACK":{if(b=`${L}
44
44
  ${C.feedback}`,v++,v>=3)return u.message=`Our AI agent requires additional information to achieve this goal:
@@ -2966,14 +2966,14 @@ ${o.logs.join(`
2966
2966
  Current tab: ${c}
2967
2967
  All tabs: ${l.join(`
2968
2968
  `)}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(d){this.logger.warn({err:d},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,r={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:1e3});if(!o)throw new A("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,s=o.y+o.height/2;await this.page.mouse.move(i,s,{steps:3});let a=0;for(;a<3;){a++;try{o=await t.boundingBox({timeout:1e3})}catch{}if(!o)break;let l=o.x+o.width/2,c=o.y+o.height/2;if(l===i&&c===s)break;this.logger.debug({newX:l,newY:c,targetX:i,targetY:s},"Drag target moved, re-adjusting mouse location"),i=l,s=c,await this.page.mouse.move(i,s,{steps:3})}await Q(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,r,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(Yc);i||(this.logger.debug("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:r}),await Q(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Rr({func:async t=>{await t.locator.scrollIntoViewIfNeeded({timeout:1e3});let r=await t.locator.boundingBox({timeout:1e3});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 Rr({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await De({fn:()=>{let r=document.activeElement;r&&r.nodeType===1&&r.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurCommand"});return}await this.highlight(e.locator),await Rr({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,r=!1){await this.highlight(e.locator),await Rr({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?t.index:void 0},{force:r,timeout:3e3})},targetingResult:e})}async press(e,t){let r=t.repeat??1;t.convertMeta&&(process.platform==="darwin"?e=e.replaceAll("Control","Meta"):e=e.replaceAll("Meta","Control"));for(let o=0;o<r;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let r=0,o=2;for(;r<o;){r++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:r},`Failed to reload page${r<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"})}async getBrowserState(e){let{logger:t=this.logger,maxAttempts:r=2,skipWaitForPageLoad:o}=e,i=e.abortSignal??this.abortSignal;if(o||await this.waitForPageLoad(),!e.skipWait){let l=Date.now();await this.waitForDOMStability({logger:t,signal:i}),t.debug({duration:Date.now()-l},"Waited for DOM stability before getting browser state")}let s=0,a;for(;s<r;){s++;try{return await B(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:i,logger:t,filterByViewport:e.filterByViewport}),{milliseconds:this.pageLoadTimeout*s,signal:i,message:"Getting browser state took too long"})}catch(l){if(i?.throwIfAborted(),a=l instanceof Error?l.message:`${l}`,s>=r)throw l;t.debug({err:l,url:this.url()},"Error getting a11y tree, retrying...")}}throw new A("ActionFailureError",`Getting page content failed after ${r} attempts. Error: ${a}`)}async getViewportOffsetDetails(e){let[t,r,o,i,s]=await De({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getViewportOffsetDetails"});return{upperBound:t,lowerBound:t+i,leftBound:r,rightBound:r+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??s}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:r=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},s=u=>{i.value=Date.now()},a=()=>s("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",a);let l=()=>s("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>l);let c=()=>s("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",c);let d=()=>s("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",d);let p=()=>s("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",p);try{await this.waitForDOMStabilityHelper(i,t,r,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",a),this.cdpClient.removeListener("Page.frameDetached",l),this.cdpClient.removeListener("Page.frameStartedLoading",c),this.cdpClient.removeListener("Page.navigatedWithinDocument",d),this.cdpClient.removeListener("Page.frameRequestedNavigation",p)}}async waitForDOMStabilityHelper(e,t,r,o){let i=!1,s=Date.now(),a,l={quality:25,retries:0,hideCaret:!0,disableAnimations:!0},c=!1,d=0;for(;Date.now()-s<r;){if(o?.throwIfAborted(),await Q(500,this.abortSignal),a)try{let u=await this.screenshot(l);if(!u.equals(a)){a=u,c=!1;continue}c=!0}catch(u){d++,d%3===0&&t.warn({err:u,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{a=await this.screenshot(l)}catch(u){d++,d%3===0&&t.warn({err:u,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<750)){i=!0;break}}let p={duration:Date.now()-s,a11yStableReceived:i,lastTreeUpdateMillisecondsAgo:Date.now()-e.value,screenshotStable:c};i||t.warn(p,"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:r,y:o}=e,i=this.url(),s=(await mo(this.context)).map(a=>a.url);this.logger.debug({x:r,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(r,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1}),t.waitForUrl&&await this.waitForUrl({beforeUrl:i,beforePages:s,matcher:{type:"GLOB",glob:t.waitForUrl}})}async dragAndDropUsingVisualCoordinates(e,t,r){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await Q(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,t,r,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(Yc);i||(this.logger.debug("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:r}),await Q(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),r=await B(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&r===1&&(r=2);let o=t.documents[0],i=o.layout,s=o.nodes,a=s.nodeName||[],l=s.backendNodeId||[],c=i.nodeIndex,d=i.bounds,p=-1;for(let v=0;v<a.length;v++)if(l[v]===e){p=c.indexOf(v);break}if(p===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[u=0,m=0,h=0,g=0]=d[p];u/=r,m/=r,h/=r,g/=r;let f=u+h/2,y=m+g/2;return{centerX:f,centerY:y}}async scrollVertical(e){return Qc({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()})}async scrollHorizontal(e){return Qc({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()})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout})}async createRawCDPSession(e){let t=await B(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.debug(`Created new CDP session for ${this.page.url()}`),t}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e)}async changeActivePage(e,t){this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let r=await this.context.newPage();await this.changeActivePage(r,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let r=!0,o,i=Date.now();for(;r||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){r=!1;try{await this.switchToPageHelper(e,t);return}catch(s){this.logger.warn({err:s},"Error switching to page, retrying..."),o=s,await Q(500)}}throw o}async switchToPageHelper(e,t){let r=this.context.pages().map((i,s)=>({page:i,url:i.url(),index:s})),o;if(e.type==="INDEX"){if(e.index<0||e.index>=r.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(r.map(i=>i.url))}`);o=r[e.index]}else{let i=r.filter(s=>e.type==="SUBSTRING"?s.url.includes(e.substring):s.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(s=>s.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
2969
- Available pages:${JSON.stringify(r.map(i=>i.url))}`);if(!Bn(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.debug(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Fs(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let r=await this.getActivePageOrFrame();await B(r.evaluate(([o,i])=>{o&&localStorage.setItem(o,i||"")},[e,t]),{milliseconds:2e3})}async solveCaptcha(){await this.getBrowserState({});let e;for(let a of Object.values(this.stateManager.a11yIdToNodeMap))if(a.role==="image"&&a.name.toLowerCase().includes("captcha")){if(!a.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,a.backendNodeId);break}if(!e){let a=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!a.captchas||!a.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),r=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:ba,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!r.ok){let a=`Captcha solver API returned error response: ${r.statusText}`;throw this.logger.error({text:await r.text()},a),new Error(a)}let{taskId:o}=await r.json(),i=Date.now(),s="";for(;Date.now()-i<6e4;){await Q(2500);let a=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:ba,taskId:o})});if(!a.ok){let c=`Captcha solution API returned error response: ${a.statusText}`;throw this.logger.error({text:await a.text()},c),new Error(c)}let l=await a.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"){s=l.solution.text;break}}if(!s)throw new Error("Captcha solution timed out");return s}getActiveFrameConfig(){return this.stateManager.frameConfig}async captureTargetFromClick(){let e=new AbortController;await this.startTreeRefreshCronForRecording(e.signal);let t;try{if(t=await(await this.getActivePageOrFrame()).evaluate(async()=>{let r=window;if(!r.resolveRecordingTarget){console.error("[MOMENTIC] Missing Momentic recording library functions");return}let o=null;r.targetCaptureClickListener=async s=>(console.info("[MOMENTIC] Target capture listener fired"),s.preventDefault(),s.stopImmediatePropagation(),o=s.target,!1),document.addEventListener("mousedown",r.targetCaptureClickListener,{capture:!0,once:!0});let i=Date.now();for(;!o&&Date.now()-i<1e4;)await new Promise(s=>setTimeout(s,250));if(!o)throw new Error("Timed out waiting for user to click on an element");return r.resolveRecordingTarget(o)}),t?.error)throw new Error(t.error);if(t?.target)t.warnings.length&&this.logger.warn({result:t},"Got warnings while capturing target from click");else throw new Error("No target captured from click")}catch(r){throw this.logger.error({err:r},"Error recording target click"),new Error(`Error recording click: ${r.message}`)}finally{e.abort()}if(!t)throw new Error("Got no target from recorded click - please make sure you clicked on an interactive element");return this.getTargetFromRecordedClick(t.target).target}getTargetFromRecordedClick(e){this.logger.debug(e,"Got HTML target attributes from click recording");let{htmlAttributes:t,dataMomenticId:r,mPathSelector:o}=e,i;if(o)i=this.stateManager.selectorToNodeMap[o];else if(r)i=this.stateManager.dataMomenticIdToNodeMap[r];else throw new Error("No data-momentic-id or momentic path selector found in click recording target");let s={id:i?.id??-1,dataMomenticId:r,targetSource:"CLICK_TO_FIND",targetUpdateTime:new Date().toUTCString(),...t};return i?this.saveA11yDetailsToCache(i,s):this.logger.warn({htmlAttributes:t},"Could not find corresponding accessibility node for click. Continuing with HTML attributes only"),{target:s,a11yNode:i}}async exposeRecordingBindings(){let e=({frame:t},r)=>{if(!this.transformer)return;let{type:o,target:i,error:s,warnings:a,selectedValue:l}=r,c=t.url();if(this.logger.debug({url:c,...r},`${o} event captured on element`),s){this.logger.error({error:s,warnings:a},"Error while capturing passive element interaction");return}else if(i)a.length&&this.logger.warn({warnings:a},`Warnings while capturing passive element interaction of type ${o}`);else{this.logger.error({event:r},"No target found in passive element interaction event");return}let{dataMomenticId:d,htmlAttributes:p,mPathSelector:u}=i,m;u?m=this.stateManager.selectorToNodeMap[u]:d?m=this.stateManager.dataMomenticIdToNodeMap[d]:this.logger.warn({target:i},"No data-momentic-id or momentic path selector found in passive element interaction target, skipping...");let h={id:m?.id??-1,dataMomenticId:d,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),...p};m?this.saveA11yDetailsToCache(m,h):this.logger.debug({url:c,htmlAttributes:p},"Could not find corresponding accessibility node for click, continuing with HTML attributes only"),(async()=>{if(!this.transformer){this.logger.warn("No natural language translation since transformer is not initialized anymore");return}this.logger.debug({target:i,url:c},`Generating description for ${o.toLowerCase()}ed target`);let g=this.stateManager.a11yTreeRoot?.serialize();m&&g&&g.length>5e3&&(g=Qg(m.id,g),this.logger.debug({serializedTree:g},"Trimmed a11y tree for description transformation"));try{await this.transformer.recordElementAction({type:o,target:h,browserState:g,url:c,selectedValue:l})}catch(f){this.logger.error({err:f},`Failed to record ${o} action`)}})()};await this.context.exposeBinding("isRecordingActive",()=>!!this.transformer),await this.context.exposeBinding("captureElementEvent",({frame:t},r)=>{try{e({frame:t},r)}catch(o){this.logger.error({err:o},"Failed to capture element interaction")}},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(t,r)=>{this.transformer&&this.transformer.recordKeystroke(r)}),await this.context.exposeBinding("isSelectorInA11yTree",(t,r)=>!!this.stateManager.selectorToNodeMap[r])}async startTreeRefreshCronForRecording(e){if(await this.stateManager.fetchA11yTreeForRecording(this.devicePixelRatio,e),e.aborted)return;let t,r=!1,o=0,i=0,s=async()=>{if(!(Date.now()-i<=1e3)&&!r){r=!0;try{await this.stateManager.fetchA11yTreeForRecording(this.devicePixelRatio,e),o=0}catch(a){if(i=Date.now(),o++,o>=8||a.message.includes("crashed")){clearInterval(t),this.logger.error({err:a},"Fatal errors while refreshing a11y tree during recording, exiting...");return}}finally{r=!1}}};t=setInterval(()=>{!this.transformer||e.aborted||s()},Bg),e.addEventListener("abort",()=>{clearInterval(t),t=void 0})}async startTabSwitchingCronForRecording(e){if(e.aborted)return;let t,r=(await this.getOpenPages()).map(a=>a.url),o=0,i=!1,s=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let a;try{a=(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=a.length-1;c>=r.length;c--){let d=a[c];Bn(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:r,currentUrl:l,newOpenPages:a},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:c});break}r=a};t=setInterval(async()=>{if(!i){i=!0;try{await s()}catch(a){this.logger.error({err:a},"Error while checking pages during recording")}finally{i=!1}}},250),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t){this.logger.debug("Starting passive recording mode in Chrome browser"),await this.startTreeRefreshCronForRecording(e),await this.startTabSwitchingCronForRecording(e),this.transformer=t,e.addEventListener("abort",async()=>{this.transformer=void 0})}async getSelectOptions(e){return await e.evaluate(r=>Array.from(r.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:r}){let o=this.pageLoadTimeout,i=e.url();if(i.includes("chrome-error://")){this.logger.warn({url:i,codePath:r},"Skipping load for chrome-error:// URL");return}try{await xr({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(s){throw s.name==="AbortError"?new Error(`The page with URL ${Ne(i,50)} did not load within the configured timeout (${o}ms): ${s}`):s}try{await xr({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(s){this.logger.warn({err:s,codePath:r},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return xA.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1,wrap_line_length:100})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:r}=await De({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getCondensedHtmlTree"});if(r)throw new Error(`Failed to process page HTML: ${r}`);if(!t)throw new A("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}async registerDialogHandler(e){let t=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",t)}async evaluateFunctionInPage(e,t){let r=await this.getActivePageOrFrame();return B(r.evaluate(t,e),{milliseconds:2e3})}async evaluateCodeInPage({code:e,fragment:t,context:r,timeoutMs:o=1e3}){let i=gf(),s={code:e,fragment:t,context:r},{result:a}=await B(this.page.evaluate(i,s),{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 a}async getDomNodeFromPixelPosition(e,t){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:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return r}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:r}){if(t<0||t>1||r<0||r>1)throw new A("InternalWebAgentError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:s,leftBound:a}=await this.getViewportOffsetDetails(e),l=Math.round(s),c=Math.round(a),d=Math.ceil(o*t),p=Math.ceil(i*r),u=d+c,m=p+l;return this.getDomNodeFromPixelPosition(u,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),r;try{r=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return r?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:Hg,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 getTargetFromPixelPosition(e,t=!0){let r=await this.getActivePageOrFrame(),o=await this.getDomNodeFromPixelPosition(e.x,e.y);return this.getTargetFromBackendNodeId(r,o.backendNodeId,t)}async getTargetFromPositionPercentages(e,t=!0){let r=await this.getActivePageOrFrame(),o=await this.getDomNodeFromPositionPercentages(r,e);return this.getTargetFromBackendNodeId(r,o.backendNodeId,t)}async getTargetFromBackendNodeId(e,t,r){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[gt],s=parseInt(i??"");if(!i||isNaN(s))throw new Error("No data-momentic-id was found on the DOM node");let a=e.locator(`[${gt}="${i}"]`);if(r){for(let p of Object.values(this.stateManager.a11yIdToNodeMap)){if(p.backendNodeId!==t)continue;let u={id:p.id,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache({node:p,target:u,dataMomenticId:parseInt(i),locator:a}),this.logger.debug({target:u},"Tied backend id to existing a11y node"),{target:u,locator:a}}let d=ca(`${i}`,this.stateManager.domGraph,this.logger);for(let p of d){let u=parseInt(p.attributes?.[gt]??"");if(isNaN(u))continue;let m=e.locator(`[${gt}="${u}"]`),h=this.stateManager.dataMomenticIdToNodeMap[u],g=h?.id;if(!g)continue;let f={id:g,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache({node:h,target:f,dataMomenticId:parseInt(i),locator:m}),this.logger.debug({target:f},"Tied backend id on non-accessible element to nearest a11y node"),{target:f,locator:m}}}let l=await this.fetchHtmlAttributes(a,this.logger),c={id:-1,dataMomenticId:s,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:c},"Tied backend id to html node"),{target:c,locator:a}}async performTargetRedirection(e,t,r){try{return await e.scrollIntoViewIfNeeded({timeout:3e3}),await B(this.performTargetRedirectionHelper(e,t,r),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,r){let o=Date.now(),i=await en(e,t);if(r===void 0&&(r=await e.boundingBox({timeout:1e3})),!r){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:s,y:a,width:l,height:c}=r,d=this.getViewport();if(s<0||a<0||s+l>d.width||a+c>d.height){t.debug("Skipping locator redirection because the element is outside the viewport");return}let p=await this.getActivePageOrFrame(),{dataMomenticId:u,mPathSelector:m,error:h,serializedElement:g,point:f,force:y,logs:v}=await e.evaluate(E=>{let x=window;if(!x.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return x.performTargetRedirection(E)},void 0,{timeout:1e3}),b=Date.now()-o;if(h){t.warn({error:h,serializedElement:g,duration:b,force:y,logs:v},"Got error from target redirection with bounding box");return}else{if(u)return t.debug({newDataMomenticId:u,serializedElement:g,duration:b,force:y,logs:v},"Redirected target to new element with bounding box with data-momentic-id"),{locator:p.locator(`[data-momentic-id="${u}"]`),hints:{clickableXY:f,force:y}};if(m)return t.debug({newMPathSelector:m,serializedElement:g,duration:b,force:y,logs:v},"Redirected target to new element with bounding box with mPath"),{locator:p.locator(m),hints:{clickableXY:f,force:y}};if(f)return t.debug({point:f,serializedElement:g,duration:b,force:y,logs:v},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:y}};if(y)return t.debug({serializedElement:g,duration:b,force:y,logs:v},"Forcing click on original element"),{locator:e,hints:{force:y}}}}async fetchHtmlAttributes(e,t=this.logger){let r=await e.evaluate(o=>{let i=window;return i.generateHtmlCacheAttributes?i.generateHtmlCacheAttributes(o):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},void 0,{timeout:1e3});if("error"in r)throw new Error(r.error);if(r.attributes)r.warnings.length&&t.warn(r,"Got warnings while generating HTML attributes for target");else return t.warn(r,"Got no generated HTML attributes for target"),{};return t.debug(r.attributes,"Generated HTML attributes for target"),r.attributes}async moveMouseFromPositionPercentages(e,t){let r;try{r=await this.getViewportOffsetDetails(this.page)}catch{return}let{width:o,height:i}=r,s=Math.ceil(o*e),a=Math.ceil(i*t);await this.page.mouse.move(s,a,{steps:3})}async clickMouseFromPositionPercentages(e,t){let r=await this.getActivePageOrFrame(),o=await this.getViewportOffsetDetails(r),{width:i,height:s}=o,a=Math.ceil(i*e),l=Math.ceil(s*t);await this.page.mouse.click(a,l,{button:"left"})}async scrollFromPositionPercentages(e,t){let r=await this.getActivePageOrFrame(),o;try{o=await this.getViewportOffsetDetails(r)}catch{return}let{width:i,height:s}=o,a=Math.ceil(i*e),l=Math.ceil(s*t);return await this.page.mouse.wheel(a,l),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!ba}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,r,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Kc(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${r}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!ya(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=t?.trim()||CA(e),o=SA(e),i=EA(e),s=uc[i];this.page.once("filechooser",async l=>{this.logger.info({filePath:e,fileName:r},"File chooser triggered");try{if(!ya(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:Dg.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 a=o.toString("base64");await(await this.getActivePageOrFrame()).evaluate(({fileName:l,base64Data:c,mimeType:d})=>{let p=window;p.momenticFileName=l,p.momenticFileBase64=c;let u=atob(c),m=new Array(u.length);for(let g=0;g<u.length;g++)m[g]=u.charCodeAt(g);let h=new Uint8Array(m);p.MomenticFile=class extends Blob{kind="file";name=p.momenticFileName;constructor(){super([h],{type:d})}isSameEntry(g){return g.name===this.name}queryPermission(g){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(g){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let g=new Blob([h]);return new File([g],p.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")}},p.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new p.MomenticFile])},{fileName:r,base64Data:a,mimeType:s})}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){let e={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},e}async copy(e){try{await this.evaluateFunctionInPage(e,t=>navigator.clipboard.writeText(t))}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(void 0,()=>{document.activeElement||document.body.focus()}),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(e,r=>navigator.clipboard.writeText(r));return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import qA from"fetch-cookie";import{cloneDeep as KA}from"lodash-es";import{CookieJar as YA}from"tough-cookie";import{randomUUID as Pn}from"crypto";var kA=["Shift","CapsLock","Dead","Meta","AudioVolumeUp","AudioVolumeDown"],Sa=class{recordedSteps=new Map;onStepRecorded;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,onStepRecord:t,generator:r,testId:o,orgId:i,logger:s}){this.signal=e,this.logger=s,this.testId=o,this.orgId=i,this.onStepRecorded=(a,l,c)=>{this.recordedSteps.set(l,{step:a,url:c}),t(a,l)},this.generator=r}reserveIndexForCommand(e,t){let r=this.nextStepOffset;return this.recordedSteps.set(r,{step:{id:Pn(),type:"PRESET_ACTION",command:Mn(e)},url:t}),this.nextStepOffset++,r}async recordElementAction(e){if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let{type:t,target:r,browserState:o,url:i}=e,{offset:s}=e,a,l,c=r.nodeOnlySerializedHtml?.trim()??r.nodeOnlySerializedForm??"Unknown element - please provide a description manually";switch(t){case"CLICK":a="CLICK";let m=Mn(a);l={id:Pn(),type:"PRESET_ACTION",command:{...m,target:{type:"description",elementDescriptor:c},cache:{target:r}}};break;case"SELECT":a="SELECT_OPTION";let h=Mn(a);l={id:Pn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",target:{type:"description",elementDescriptor:c},cache:{target:r},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break;default:throw new Error(`Unknown action type: ${t}`)}if(s===void 0&&(s=this.nextStepOffset,this.nextStepOffset++),this.onStepRecorded(l,s,i),r.id<=0){this.logger.debug("Skipping reverse mapping for non-accessible element");return}else if(!o){this.logger.debug("Skipping reverse mapping since the browser a11y state is not available");return}let d;try{d=(await this.generator.getReverseMappedDescription({goal:`${r.id}`,browserState:o},{disableCache:!1,orgId:this.orgId,loggerTags:{testId:this.testId,...nt(this.logger)}})).phrase}catch(m){this.logger.error({err:m},"Error generating reverse mapping description"),d=c}let p=this.recordedSteps.get(s)?.step,u=p?.command;u&&"target"in u&&u.target?(u.target={type:"description",elementDescriptor:d},this.onStepRecorded({...p,command:u},s,i)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,url:r,dataMomenticId:o}=e;if(kA.includes(t)||this.signal.aborted)return;let i="normal";t.length>1&&(i="special");let s;if(i==="normal"){let m=Mn("TYPE");s={id:Pn(),type:"PRESET_ACTION",command:{...m,target:void 0,value:t,clearContent:!1}}}else{let m=Mn("PRESS");s={id:Pn(),type:"PRESET_ACTION",command:{...m,value:t,convertMeta:!0}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),d=c?.step,p=d?.command,u=c?.url;if(r===u){if(p?.type===s.command.type){let m=p.value,h=s.command.value;s={id:Pn(),type:"PRESET_ACTION",command:{...p,value:s.command.type==="PRESS"?`${m}+${h}`:`${m}${h}`}},a=l}else if(p?.type==="CLICK"&&s.command.type==="TYPE")(!o||p.cache?.target.dataMomenticId===parseInt(o))&&(d.command={...s.command,target:p.target,cache:p.cache},s=c.step,a=l);else if(p?.type==="TYPE"&&s.command.type==="PRESS"&&s.command.value==="Backspace"){let m=p.value;s={id:Pn(),type:"PRESET_ACTION",command:{...p,value:m.slice(0,m.length-1)}},a=l}}a||(a=this.nextStepOffset,this.nextStepOffset++),this.onStepRecorded(s,a,r)}recordScroll(e){if(this.signal.aborted)return;let{url:t}=e,r=()=>{let{deltaY:s}=e;if(!s)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(s+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(s-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let d=s>0?"SCROLL_DOWN":"SCROLL_UP",p=Mn(d);p.deltaY=Math.abs(s);let u={id:Pn(),type:"PRESET_ACTION",command:p};this.onStepRecorded(u,c,t)},o=()=>{let{deltaX:s}=e;if(!s)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(s+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(s-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let d=s>0?"SCROLL_RIGHT":"SCROLL_LEFT",p=Mn(d);p.deltaX=Math.abs(s);let u={id:Pn(),type:"PRESET_ACTION",command:p};this.onStepRecorded(u,c,t)},i=this.recordedSteps.get(this.nextStepOffset-1);i?.step.command.type==="SCROLL_LEFT"||i?.step.command.type==="SCROLL_RIGHT"?(o(),e.deltaY>=20&&r()):(r(),e.deltaX>=20&&o())}};import{z as nn}from"zod";var i6=nn.object({doubleClick:nn.boolean().optional(),rightClick:nn.boolean().optional(),force:nn.boolean().optional(),waitForDownload:nn.boolean().optional(),waitForUrl:nn.string().optional(),delayMs:nn.number().optional()}),s6=nn.object({repeat:nn.number().optional(),convertMeta:nn.boolean().optional(),delayMs:nn.number().optional()});var rd=(n,e,t)=>{let[r,...o]=e.split("."),i=r;return o.length>=1?rd(n[i],o.join("."),t):n[i]=t,n};async function Gn(n,e={}){let t=await n.getBrowserState(e),r=t.serialize();return e.logger?.debug({tree:r.length>4e5?"REDACTED_DUE_TO_LENGTH":r,activeFrame:n.getActiveFrameConfig()},"Got a11y tree"),{serializedTree:r,tree:t}}var ho=3.1783027;function MA(n){let e=0;for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);!(r>=48&&r<=57)&&!(r>=65&&r<=90)&&!(r>=97&&r<=122)&&e++}return e}function Ri(n){return Math.ceil(od(n)/ho)}function od(n){let e=0;if(typeof n=="string"){let t=n;t=t.replaceAll(`
2969
+ Available pages:${JSON.stringify(r.map(i=>i.url))}`);if(!Bn(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.debug(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Fs(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let r=await this.getActivePageOrFrame();await B(r.evaluate(([o,i])=>{o&&localStorage.setItem(o,i||"")},[e,t]),{milliseconds:2e3})}async solveCaptcha(){await this.getBrowserState({});let e;for(let a of Object.values(this.stateManager.a11yIdToNodeMap))if(a.role==="image"&&a.name.toLowerCase().includes("captcha")){if(!a.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,a.backendNodeId);break}if(!e){let a=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!a.captchas||!a.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),r=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:ba,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!r.ok){let a=`Captcha solver API returned error response: ${r.statusText}`;throw this.logger.error({text:await r.text()},a),new Error(a)}let{taskId:o}=await r.json(),i=Date.now(),s="";for(;Date.now()-i<6e4;){await Q(2500);let a=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:ba,taskId:o})});if(!a.ok){let c=`Captcha solution API returned error response: ${a.statusText}`;throw this.logger.error({text:await a.text()},c),new Error(c)}let l=await a.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"){s=l.solution.text;break}}if(!s)throw new Error("Captcha solution timed out");return s}getActiveFrameConfig(){return this.stateManager.frameConfig}async captureTargetFromClick(){let e=new AbortController;await this.startTreeRefreshCronForRecording(e.signal);let t;try{if(t=await(await this.getActivePageOrFrame()).evaluate(async()=>{let r=window;if(!r.resolveRecordingTarget){console.error("[MOMENTIC] Missing Momentic recording library functions");return}let o=null;r.targetCaptureClickListener=async s=>(console.info("[MOMENTIC] Target capture listener fired"),s.preventDefault(),s.stopImmediatePropagation(),o=s.target,!1),document.addEventListener("mousedown",r.targetCaptureClickListener,{capture:!0,once:!0});let i=Date.now();for(;!o&&Date.now()-i<1e4;)await new Promise(s=>setTimeout(s,250));if(!o)throw new Error("Timed out waiting for user to click on an element");return r.resolveRecordingTarget(o)}),t?.error)throw new Error(t.error);if(t?.target)t.warnings.length&&this.logger.warn({result:t},"Got warnings while capturing target from click");else throw new Error("No target captured from click")}catch(r){throw this.logger.error({err:r},"Error recording target click"),new Error(`Error recording click: ${r.message}`)}finally{e.abort()}if(!t)throw new Error("Got no target from recorded click - please make sure you clicked on an interactive element");return this.getTargetFromRecordedClick(t.target).target}getTargetFromRecordedClick(e){this.logger.debug(e,"Got HTML target attributes from click recording");let{htmlAttributes:t,dataMomenticId:r,mPathSelector:o}=e,i;if(o)i=this.stateManager.selectorToNodeMap[o];else if(r)i=this.stateManager.dataMomenticIdToNodeMap[r];else throw new Error("No data-momentic-id or momentic path selector found in click recording target");let s={id:i?.id??-1,dataMomenticId:r,targetSource:"CLICK_TO_FIND",targetUpdateTime:new Date().toUTCString(),...t};return i?this.saveA11yDetailsToCache(i,s):this.logger.warn({htmlAttributes:t},"Could not find corresponding accessibility node for click. Continuing with HTML attributes only"),{target:s,a11yNode:i}}async exposeRecordingBindings(){let e=({frame:t},r)=>{if(!this.transformer)return;let{type:o,target:i,error:s,warnings:a,selectedValue:l}=r,c=t.url();if(this.logger.debug({url:c,...r},`${o} event captured on element`),s){this.logger.error({error:s,warnings:a},"Error while capturing passive element interaction");return}else if(i)a.length&&this.logger.warn({warnings:a},`Warnings while capturing passive element interaction of type ${o}`);else{this.logger.error({event:r},"No target found in passive element interaction event");return}let{dataMomenticId:d,htmlAttributes:p,mPathSelector:u}=i,m;u?m=this.stateManager.selectorToNodeMap[u]:d?m=this.stateManager.dataMomenticIdToNodeMap[d]:this.logger.warn({target:i},"No data-momentic-id or momentic path selector found in passive element interaction target, skipping...");let h={id:m?.id??-1,dataMomenticId:d,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),...p};m?this.saveA11yDetailsToCache(m,h):this.logger.debug({url:c,htmlAttributes:p},"Could not find corresponding accessibility node for click, continuing with HTML attributes only"),(async()=>{if(!this.transformer){this.logger.warn("No natural language translation since transformer is not initialized anymore");return}this.logger.debug({target:i,url:c},`Generating description for ${o.toLowerCase()}ed target`);let g=this.stateManager.a11yTreeRoot?.serialize();m&&g&&g.length>5e3&&(g=Qg(m.id,g),this.logger.debug({serializedTree:g},"Trimmed a11y tree for description transformation"));try{await this.transformer.recordElementAction({type:o,target:h,browserState:g,url:c,selectedValue:l})}catch(f){this.logger.error({err:f},`Failed to record ${o} action`)}})()};await this.context.exposeBinding("isRecordingActive",()=>!!this.transformer),await this.context.exposeBinding("captureElementEvent",({frame:t},r)=>{try{e({frame:t},r)}catch(o){this.logger.error({err:o},"Failed to capture element interaction")}},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(t,r)=>{this.transformer&&this.transformer.recordKeystroke(r)}),await this.context.exposeBinding("isSelectorInA11yTree",(t,r)=>!!this.stateManager.selectorToNodeMap[r])}async startTreeRefreshCronForRecording(e){if(await this.stateManager.fetchA11yTreeForRecording(this.devicePixelRatio,e),e.aborted)return;let t,r=!1,o=0,i=0,s=async()=>{if(!(Date.now()-i<=1e3)&&!r){r=!0;try{await this.stateManager.fetchA11yTreeForRecording(this.devicePixelRatio,e),o=0}catch(a){if(i=Date.now(),o++,o>=8||a.message.includes("crashed")){clearInterval(t),this.logger.error({err:a},"Fatal errors while refreshing a11y tree during recording, exiting...");return}}finally{r=!1}}};t=setInterval(()=>{!this.transformer||e.aborted||s()},Bg),e.addEventListener("abort",()=>{clearInterval(t),t=void 0})}async startTabSwitchingCronForRecording(e){if(e.aborted)return;let t,r=(await this.getOpenPages()).map(a=>a.url),o=0,i=!1,s=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let a;try{a=(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=a.length-1;c>=r.length;c--){let d=a[c];Bn(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:r,currentUrl:l,newOpenPages:a},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:c});break}r=a};t=setInterval(async()=>{if(!i){i=!0;try{await s()}catch(a){this.logger.error({err:a},"Error while checking pages during recording")}finally{i=!1}}},250),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t){this.logger.debug("Starting passive recording mode in Chrome browser"),await this.startTreeRefreshCronForRecording(e),await this.startTabSwitchingCronForRecording(e),this.transformer=t,e.addEventListener("abort",async()=>{this.transformer=void 0})}async getSelectOptions(e){return await e.evaluate(r=>Array.from(r.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:r}){let o=this.pageLoadTimeout,i=e.url();if(i.includes("chrome-error://")){this.logger.warn({url:i,codePath:r},"Skipping load for chrome-error:// URL");return}try{await xr({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(s){throw s.name==="AbortError"?new Error(`The page with URL ${Ne(i,50)} did not load within the configured timeout (${o}ms): ${s}`):s}try{await xr({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(s){this.logger.warn({err:s,codePath:r},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return xA.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1,wrap_line_length:100})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:r}=await De({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getCondensedHtmlTree"});if(r)throw new Error(`Failed to process page HTML: ${r}`);if(!t)throw new A("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}async registerDialogHandler(e){let t=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",t)}async evaluateFunctionInPage(e,t){let r=await this.getActivePageOrFrame();return B(r.evaluate(t,e),{milliseconds:2e3})}async evaluateCodeInPage({code:e,fragment:t,context:r,timeoutMs:o=1e3}){let i=gf(),s={code:e,fragment:t,context:r},{result:a}=await B(this.page.evaluate(i,s),{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 a}async getDomNodeFromPixelPosition(e,t){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:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return r}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:r}){if(t<0||t>1||r<0||r>1)throw new A("InternalWebAgentError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:s,leftBound:a}=await this.getViewportOffsetDetails(e),l=Math.round(s),c=Math.round(a),d=Math.ceil(o*t),p=Math.ceil(i*r),u=d+c,m=p+l;return this.getDomNodeFromPixelPosition(u,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),r;try{r=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return r?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:Hg,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 getTargetFromPixelPosition(e,t=!0){let r=await this.getActivePageOrFrame(),o=await this.getDomNodeFromPixelPosition(e.x,e.y);return this.getTargetFromBackendNodeId(r,o.backendNodeId,t)}async getTargetFromPositionPercentages(e,t=!0){let r=await this.getActivePageOrFrame(),o=await this.getDomNodeFromPositionPercentages(r,e);return this.getTargetFromBackendNodeId(r,o.backendNodeId,t)}async getTargetFromBackendNodeId(e,t,r){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[gt],s=parseInt(i??"");if(!i||isNaN(s))throw new Error("No data-momentic-id was found on the DOM node");let a=e.locator(`[${gt}="${i}"]`);if(r){for(let p of Object.values(this.stateManager.a11yIdToNodeMap)){if(p.backendNodeId!==t)continue;let u={id:p.id,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache({node:p,target:u,dataMomenticId:parseInt(i),locator:a}),this.logger.debug({target:u},"Tied backend id to existing a11y node"),{target:u,locator:a}}let d=ca(`${i}`,this.stateManager.domGraph,this.logger);for(let p of d){let u=parseInt(p.attributes?.[gt]??"");if(isNaN(u))continue;let m=e.locator(`[${gt}="${u}"]`),h=this.stateManager.dataMomenticIdToNodeMap[u],g=h?.id;if(!g)continue;let f={id:g,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache({node:h,target:f,dataMomenticId:parseInt(i),locator:m}),this.logger.debug({target:f},"Tied backend id on non-accessible element to nearest a11y node"),{target:f,locator:m}}}let l=await this.fetchHtmlAttributes(a,this.logger),c={id:-1,dataMomenticId:s,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:c},"Tied backend id to html node"),{target:c,locator:a}}async performTargetRedirection(e,t,r){try{return await e.scrollIntoViewIfNeeded({timeout:3e3}),await B(this.performTargetRedirectionHelper(e,t,r),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,r){let o=Date.now(),i=await en(e,t);if(r===void 0&&(r=await e.boundingBox({timeout:1e3})),!r){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:s,y:a,width:l,height:c}=r,d=this.getViewport();if(s<0||a<0||s+l>d.width||a+c>d.height){t.debug("Skipping locator redirection because the element is outside the viewport");return}let p=await this.getActivePageOrFrame(),{dataMomenticId:u,mPathSelector:m,error:h,serializedElement:g,point:f,force:y,logs:v}=await e.evaluate(E=>{let x=window;if(!x.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return x.performTargetRedirection(E)},void 0,{timeout:1e3}),b=Date.now()-o;if(h){t.warn({error:h,serializedElement:g,duration:b,force:y,logs:v},"Got error from target redirection with bounding box");return}else{if(u)return t.debug({newDataMomenticId:u,serializedElement:g,duration:b,force:y,logs:v},"Redirected target to new element with bounding box with data-momentic-id"),{locator:p.locator(`[data-momentic-id="${u}"]`),hints:{clickableXY:f,force:y}};if(m)return t.debug({newMPathSelector:m,serializedElement:g,duration:b,force:y,logs:v},"Redirected target to new element with bounding box with mPath"),{locator:p.locator(m),hints:{clickableXY:f,force:y}};if(f)return t.debug({point:f,serializedElement:g,duration:b,force:y,logs:v},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:y}};if(y)return t.debug({serializedElement:g,duration:b,force:y,logs:v},"Forcing click on original element"),{locator:e,hints:{force:y}}}}async fetchHtmlAttributes(e,t=this.logger){let r=await e.evaluate(o=>{let i=window;return i.generateHtmlCacheAttributes?i.generateHtmlCacheAttributes(o):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},void 0,{timeout:1e3});if("error"in r)throw new Error(r.error);if(r.attributes)r.warnings.length&&t.warn(r,"Got warnings while generating HTML attributes for target");else return t.warn(r,"Got no generated HTML attributes for target"),{};return t.debug(r.attributes,"Generated HTML attributes for target"),r.attributes}async moveMouseFromPositionPercentages(e,t){let r;try{r=await this.getViewportOffsetDetails(this.page)}catch{return}let{width:o,height:i}=r,s=Math.ceil(o*e),a=Math.ceil(i*t);await this.page.mouse.move(s,a,{steps:3})}async clickMouseFromPositionPercentages(e,t){let r=await this.getActivePageOrFrame(),o=await this.getViewportOffsetDetails(r),{width:i,height:s}=o,a=Math.ceil(i*e),l=Math.ceil(s*t);await this.page.mouse.click(a,l,{button:"left"})}async scrollFromPositionPercentages(e,t){let r=await this.getActivePageOrFrame(),o;try{o=await this.getViewportOffsetDetails(r)}catch{return}let{width:i,height:s}=o,a=Math.ceil(i*e),l=Math.ceil(s*t);return await this.page.mouse.wheel(a,l),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!ba}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,r,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Kc(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${r}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!ya(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=t?.trim()||CA(e),o=SA(e),i=EA(e),s=uc[i];this.page.once("filechooser",async l=>{this.logger.info({filePath:e,fileName:r},"File chooser triggered");try{if(!ya(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:Dg.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 a=o.toString("base64");await(await this.getActivePageOrFrame()).evaluate(({fileName:l,base64Data:c,mimeType:d})=>{let p=window;p.momenticFileName=l,p.momenticFileBase64=c;let u=atob(c),m=new Array(u.length);for(let g=0;g<u.length;g++)m[g]=u.charCodeAt(g);let h=new Uint8Array(m);p.MomenticFile=class extends Blob{kind="file";name=p.momenticFileName;constructor(){super([h],{type:d})}isSameEntry(g){return g.name===this.name}queryPermission(g){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(g){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let g=new Blob([h]);return new File([g],p.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")}},p.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new p.MomenticFile])},{fileName:r,base64Data:a,mimeType:s})}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){let e={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},e}async copy(e){try{await this.evaluateFunctionInPage(e,t=>navigator.clipboard.writeText(t))}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(void 0,()=>{document.activeElement||document.body.focus()}),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(e,r=>navigator.clipboard.writeText(r));return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import qA from"fetch-cookie";import{cloneDeep as KA}from"lodash-es";import{CookieJar as YA}from"tough-cookie";import{randomUUID as Pn}from"crypto";var kA=["Shift","CapsLock","Dead","Meta","AudioVolumeUp","AudioVolumeDown"],Sa=class{recordedSteps=new Map;onStepRecorded;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,onStepRecord:t,generator:r,testId:o,orgId:i,logger:s}){this.signal=e,this.logger=s,this.testId=o,this.orgId=i,this.onStepRecorded=(a,l,c)=>{this.recordedSteps.set(l,{step:a,url:c}),t(a,l)},this.generator=r}reserveIndexForCommand(e,t){let r=this.nextStepOffset;return this.recordedSteps.set(r,{step:{id:Pn(),type:"PRESET_ACTION",command:Mn(e)},url:t}),this.nextStepOffset++,r}async recordElementAction(e){if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let{type:t,target:r,browserState:o,url:i}=e,{offset:s}=e,a,l,c=r.nodeOnlySerializedHtml?.trim()??r.nodeOnlySerializedForm??"Unknown element - please provide a description manually";switch(t){case"CLICK":a="CLICK";let m=Mn(a);l={id:Pn(),type:"PRESET_ACTION",command:{...m,target:{type:"description",elementDescriptor:c},cache:{target:r}}};break;case"SELECT":a="SELECT_OPTION";let h=Mn(a);l={id:Pn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",target:{type:"description",elementDescriptor:c},cache:{target:r},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break;default:throw new Error(`Unknown action type: ${t}`)}if(s===void 0&&(s=this.nextStepOffset,this.nextStepOffset++),this.onStepRecorded(l,s,i),r.id<=0){this.logger.debug("Skipping reverse mapping for non-accessible element");return}else if(!o){this.logger.debug("Skipping reverse mapping since the browser a11y state is not available");return}let d;try{d=(await this.generator.getReverseMappedDescription({goal:`${r.id}`,browserState:o},{disableCache:!1,orgId:this.orgId,loggerTags:{testId:this.testId,...nt(this.logger)}})).phrase}catch(m){this.logger.error({err:m},"Error generating reverse mapping description"),d=c}let p=this.recordedSteps.get(s)?.step,u=p?.command;u&&"target"in u&&u.target?(u.target={type:"description",elementDescriptor:d},this.onStepRecorded({...p,command:u},s,i)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,url:r,dataMomenticId:o}=e;if(kA.includes(t)||this.signal.aborted)return;let i="normal";t.length>1&&(i="special");let s;if(i==="normal"){let m=Mn("TYPE");s={id:Pn(),type:"PRESET_ACTION",command:{...m,target:void 0,value:t,clearContent:!1}}}else{let m=Mn("PRESS");s={id:Pn(),type:"PRESET_ACTION",command:{...m,value:t,convertMeta:!0}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),d=c?.step,p=d?.command,u=c?.url;if(r===u){if(p?.type===s.command.type){let m=p.value,h=s.command.value;s={id:Pn(),type:"PRESET_ACTION",command:{...p,value:s.command.type==="PRESS"?`${m}+${h}`:`${m}${h}`}},a=l}else if(p?.type==="CLICK"&&s.command.type==="TYPE")(!o||p.cache?.target.dataMomenticId===parseInt(o))&&(d.command={...s.command,target:p.target,cache:p.cache},s=c.step,a=l);else if(p?.type==="TYPE"&&s.command.type==="PRESS"&&s.command.value==="Backspace"){let m=p.value;s={id:Pn(),type:"PRESET_ACTION",command:{...p,value:m.slice(0,m.length-1)}},a=l}}a||(a=this.nextStepOffset,this.nextStepOffset++),this.onStepRecorded(s,a,r)}recordScroll(e){if(this.signal.aborted)return;let{url:t}=e,r=()=>{let{deltaY:s}=e;if(!s)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(s+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(s-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let d=s>0?"SCROLL_DOWN":"SCROLL_UP",p=Mn(d);p.deltaY=Math.abs(s);let u={id:Pn(),type:"PRESET_ACTION",command:p};this.onStepRecorded(u,c,t)},o=()=>{let{deltaX:s}=e;if(!s)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(s+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(s-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let d=s>0?"SCROLL_RIGHT":"SCROLL_LEFT",p=Mn(d);p.deltaX=Math.abs(s);let u={id:Pn(),type:"PRESET_ACTION",command:p};this.onStepRecorded(u,c,t)},i=this.recordedSteps.get(this.nextStepOffset-1);i?.step.command.type==="SCROLL_LEFT"||i?.step.command.type==="SCROLL_RIGHT"?(o(),e.deltaY>=20&&r()):(r(),e.deltaX>=20&&o())}};import{z as nn}from"zod";var r6=nn.object({doubleClick:nn.boolean().optional(),rightClick:nn.boolean().optional(),force:nn.boolean().optional(),waitForDownload:nn.boolean().optional(),waitForUrl:nn.string().optional(),delayMs:nn.number().optional()}),o6=nn.object({repeat:nn.number().optional(),convertMeta:nn.boolean().optional(),delayMs:nn.number().optional()});var rd=(n,e,t)=>{let[r,...o]=e.split("."),i=r;return o.length>=1?rd(n[i],o.join("."),t):n[i]=t,n};async function Gn(n,e={}){let t=await n.getBrowserState(e),r=t.serialize();return e.logger?.debug({tree:r.length>4e5?"REDACTED_DUE_TO_LENGTH":r,activeFrame:n.getActiveFrameConfig()},"Got a11y tree"),{serializedTree:r,tree:t}}var ho=3.1783027;function MA(n){let e=0;for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);!(r>=48&&r<=57)&&!(r>=65&&r<=90)&&!(r>=97&&r<=122)&&e++}return e}function Ri(n){return Math.ceil(od(n)/ho)}function od(n){let e=0;if(typeof n=="string"){let t=n;t=t.replaceAll(`
2970
2970
  `,""),t=t.replaceAll(" ","");let r=MA(t);return t.length-r+ho*r}if(typeof n>"u")return 0;if(typeof n=="number")return String(n).length;if(Array.isArray(n))return n.forEach(t=>{e+=od(t)}),e;if(typeof n=="object"){let t=n;return Object.keys(t).forEach(r=>{e+=String(r).length,r==="image_url"?(t[r]??{}).detail==="high"?e+=1105*ho:e+=85*ho:e+=od(t[r])}),e}if(typeof n=="boolean")return n?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof n}': ${n}`)}var _f=1e6,Df={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Uf={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:15e3,maxLineLength:500},Ff=/<(\S+) id="(\d+)".*?>/g,NA=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,zf=["h1","h2","section","footer","nav","aside","form","label","dialog"],_A=[...zf,"span","div","h3"],FA=["table","select","form","ul","ol","menu","pre","code","dialog"],DA=["table","form","dialog","nav","section","ul","select"];function id(n){return n.serializedTree.length>_f&&(n.logger.warn({serializedTreeLength:n.serializedTree.length},"Serialized condensed tree is too long to chunk, truncating before chunking"),n.serializedTree=n.serializedTree.slice(0,_f)),UA(n)}function UA({serializedTree:n,options:e,logger:t}){let{minChunkTokenCount:r,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:s}=e,a=[],l=n.split(`
2971
2971
  `),c=0,d=[],p=0,u=[],m=[],h=!1;for(;c<l.length;){h&&(a.push({ids:u,content:d.join(`
2972
2972
  `),tokenLength:p}),d=[],p=0,u=m.length?[m[m.length-1].id]:[],h=!1);let g=l[c],f=Ri(g);p+=f,g.length>s&&(g=g.slice(0,s));let b=Array.from(g.matchAll(Ff)).map(I=>I&&I.length>=3?{tagName:I[1],id:I[2]}:void 0).filter(I=>!!I),x=Array.from(g.matchAll(NA)).map(I=>I&&(I[2]||I[4])).filter(I=>!!I);x.reverse();let C=g.replace(/ id="[0-9]+"/g,"");d.push(C);for(let I of b)u.push(I.id),m.push(I);for(let I of x){let ae=m[m.length-1];ae&&ae.tagName===I&&m.pop()}let L=m.some(I=>FA.includes(I.tagName)),N=l[c+1]??"",P=Ri(N),$=Array.from(N.matchAll(Ff)).map(I=>I&&I.length>2?I[1]:void 0).filter(I=>!!I),ee=$.some(I=>zf.includes(I)),k=$.some(I=>_A.includes(I));p+P>=i&&(h=!0),p>=r&&(ee&&!L||x.some(I=>DA.includes(I)))&&(h=!0),p>=o&&k&&!L&&(h=!0),c++}return d.length&&a.push({ids:u,content:d.join(`
2973
2973
  `),tokenLength:p}),a.forEach((g,f)=>{t.debug({chunk:g},`Chunk for page filtering (index ${f+1}/${a.length})`)}),{chunks:a}}var sd=4e4,ad=8e4;async function Ir(n){let{serializedTree:e,logger:t,flagStore:r,softTokenLimit:o=sd}=n;if(Ri(e)<o)return e;let s=id({serializedTree:e,options:Uf,logger:t});try{return r.isBooleanFlagEnabled("rag_v2")?await B(zA({...n,chunks:s.chunks}),{milliseconds:15e3}):await B(jA(n),{milliseconds:1e4})}catch(a){t.warn({err:a},"Error executing page filtering, attempting AI keyword fallback");try{return await BA({...n,chunks:s.chunks})}catch(l){return t.warn({err:l},"Error executing page filtering using keyword matching, using naive truncation"),e.slice(0,ad*ho)}}}async function zA({chunks:n,generator:e,description:t,type:r,logger:o,signal:i,orgId:s,tree:a,softTokenLimit:l=sd,hardTokenLimit:c=ad}){let d=await e.rankChunksWithAi({chunks:n,description:t,type:r,softTokenLimit:l,hardTokenLimit:c},{abortSignal:i,orgId:s,logger:o,loggerTags:nt(o)}),p=[];n.forEach((m,h)=>{d.indices.includes(h)&&(p=p.concat(m.ids))});let u=a.pruneUsingRelevantIds(new Set(p)).serialize();return o.debug({description:t,type:r,selectedChunks:d,tree:u},"Pruned a11y tree with AI page filtering"),u}async function BA(n){let{type:e,description:t,generator:r,orgId:o,tree:i,logger:s,hardTokenLimit:a=ad}=n;if(!t.trim())throw new Error("Empty description passed to page filtering");let l=await r.getExtractedKeywords({goal:t},{orgId:o,logger:n.logger,loggerTags:nt(n.logger)});for(let c of l.keywords){let d=n.chunks.filter(h=>h.content.includes(c));if(!d.length||d.reduce((h,g)=>h+g.tokenLength,0)>a&&d.length>1)continue;let u=d.flatMap(h=>h.ids),m=i.pruneUsingRelevantIds(new Set(u)).serialize();return s.debug({description:t,type:e,selectedChunks:d,tree:m},"Pruned a11y tree with keyword page filtering"),m}throw new Error("No keywords were unique enough for page filtering")}async function jA(n){let{description:e,generator:t,orgId:r,tree:o,logger:i,signal:s,softTokenLimit:a=sd}=n,l=id({serializedTree:o.serialize(),options:Df,logger:i}),c=await t.rankChunksWithRag({description:e,chunks:l.chunks,tokenLimit:a},{abortSignal:s,orgId:r,logger:i,loggerTags:nt(i)});if(c.ids.length===0)throw new Error("RAG returned no important ids");{let d=o.pruneUsingRelevantIds(new Set(c.ids.map(p=>`${p}`))).serialize();return i.debug({browserState:d},"Pruned a11y tree with RAG"),d}}async function ld(n,e){if(!n.description)throw new A("ActionFailureError","Cannot locate element with empty description");return hn({action:()=>$A(n,e),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:e.browser,logger:e.logger})}async function $A(n,e){let{disableCache:t,testContext:r,filterByViewport:o,skipWait:i}=n,{ctx:s,orgId:a,logger:l,browser:c,localCodeEvalTools:d,generator:p,abortSignal:u}=e,m=n.description;r&&(m=await Ot({orgId:a,s:m,context:r,logger:e.logger,localTools:d,signal:e.abortSignal}));let{serializedTree:h,tree:g}=await Gn(c,{filterByViewport:o,abortSignal:u,skipWait:i,logger:l}),f,y=Date.now(),v;for(;!f&&Date.now()-y<3e3;){u.throwIfAborted();try{f=await c.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(ee){v=ee}}if(!f)throw new A("InternalWebAgentError",`Failed to take screenshot of page to locate element: ${v?.message}`);let b=h,E=!1;b=await Ir({type:"locator",description:m,serializedTree:h,flagStore:e.flagStore,tree:g,logger:l,generator:p,orgId:a}),b!==h&&(E=!0);let x=f.toString("base64"),C=await p.getElementLocation({browserState:b,goal:m,screenshot:x,feedback:void 0},{disableCache:t,orgId:a,abortSignal:u,loggerTags:nt(l)});l.debug({usedRag:E,result:C},"Got locator result");let L=C.id>0;if(s?.details?.push({type:"AI_LOCATION",matched:L,pageState:b,ragUsed:E,thoughts:C.thoughts}),!L)throw new A("ActionFailureError",`Could not find any relevant element: ${C.thoughts}`);let{resolution:N,target:P,frameConfig:U,frameConfigSource:$}=await c.createTargetFromA11yId({id:C.id,description:m,targetSource:"AI",logger:l});if(U&&l.debug({frameConfigSource:$,frameConfig:Af(U)},"A11y node was resolved to a target within an iframe"),N.a11yNode?.properties?.hidden&&N.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: ${N.displayString}`);return{thoughts:C.thoughts,target:P,resolution:N,frameConfig:U}}var HA=15;async function cd({command:n,fixtures:e}){if(!n.assertion.trim())throw new A("ActionFailureError","Assertion command is missing the assertion content");let{browser:t,logger:r}=e,o=n.timeout?n.timeout*1e3:t.smartWaitingTimeout,i=WA(o),s=0,a=Date.now(),l,c,d;try{await hn({action:()=>t.clearHighlights(),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:t,logger:r})}catch(u){r.warn({err:u},"Failed to clear highlights before AI assertion, continuing...")}let p;for(;s<HA&&(!p||p-a<o);){e.abortSignal.throwIfAborted(),s!==0&&(r.info(`Waiting ${i}ms before retrying AI assertion`),await Q(i,e.abortSignal)),p=Date.now();try{let u=await hn({action:async()=>{let m=await Bf(t,r,e.abortSignal);return c&&c.serializedTree===m.serializedTree&&c.screenshotBuff.equals(m.screenshotBuff)?(r.debug("A11y tree and page screenshot did not change, skipping assertion attempt"),!1):(c=m,jf({command:n,state:m,fixtures:e,useConsensus:!1,highlightElementsOnFailure:!1}))},frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,logger:r,browser:t});if(!u)continue;l=u;break}catch(u){e.abortSignal.throwIfAborted(),d=u instanceof Error?u:new Error(`${u}`),r.info({err:u},`AI_WAIT assert attempt ${s} failed, retrying...`)}finally{s++}}if(!l){r.info("Executing one final AI assertion attempt");try{l=await hn({action:async()=>jf({command:n,state:await Bf(t,r,e.abortSignal),fixtures:e,useConsensus:!0,highlightElementsOnFailure:!0}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,logger:r,browser:t})}catch(u){e.abortSignal.throwIfAborted(),d=u instanceof Error?u:new Error(`${u}`)}finally{s++}}if(!l){let u=`AI assertion still failing after ${s} attempts.`;throw d&&(u+=` Latest result: ${d.message}`),new A("AssertionFailureError",u,{lastScreenshotBuffer:c?.screenshotBuff})}return l}async function Bf(n,e,t){let[r,o]=await Promise.all([Gn(n,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),n.screenshot({retries:1,respectActiveFrame:!0})]);return{...r,screenshotBuff:o}}async function jf({command:n,state:e,fixtures:t,useConsensus:r,highlightElementsOnFailure:o}){let{browser:i,logger:s,generator:a,orgId:l,abortSignal:c}=t,d={type:"ASSERTION"},{serializedTree:p,tree:u}=e,m=e.screenshotBuff,h=i.url(),g=p;g=await Ir({type:"assertion",serializedTree:p,description:n.assertion,flagStore:t.flagStore,tree:u,generator:a,orgId:l,logger:s,signal:c}),g!==p&&(d.ragUsed=!0),d.pageState=g;let f={goal:n.assertion,url:h,browserState:g,screenshot:m.toString("base64"),contextChoice:n.contextChoice},v=await(n.contextChoice==="VISION_ONLY"?(b,E)=>a.getVisualAssertionResult(b,E):(b,E)=>a.getAssertionResult(b,E))(f,{useConsensus:r,disableCache:!!n.disableCache,logger:s,orgId:l,abortSignal:c,loggerTags:nt(s)});if(s.debug({usedRag:d.ragUsed,result:v},"Got assertion attempt result"),(v.result||o)&&v.relevantElements&&(d.relevantElementsSerialized=v.relevantElements.map(b=>i.getSerializedFormFromA11yId(b)).filter(b=>!!b),await GA(v.relevantElements,i,s)),!v.result)throw new A("AssertionFailureError",v.thoughts);return{succeedImmediately:!1,thoughts:v.thoughts,urlAfterCommand:h,afterScreenshotOverride:m}}function WA(n){let e;return n>10*60*1e3?e=2*60*1e3:n>60*1e3?e=20*1e3:n>10*1e3?e=2*1e3:e=1e3,e}async function GA(n,e,t){let r=Date.now();for(let o of n){if(Date.now()-r>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await B(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var VA=3e4;async function $f({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??VA/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(n.headers||{}).filter(([p,u])=>p&&u)),a;if(so(n.url)&&(a=n.url),t&&ao(n.url,t)&&(a=new URL(n.url,t).toString()),!a)throw new A("ActionFailureError",`Invalid URL: ${n.url}`);let c=await B((async()=>{try{return await r(a,{headers:s,method:"POST",body:JSON.stringify({query:n.query,variables:n.variables}),signal:i.signal})}catch(p){e.error({err:p},"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 p;try{p=await c.json()}catch{throw new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${await c.text()}`)}throw p?.errors?.length&&p?.errors[0]?.message?new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p.errors[0].message}`):new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${await c.text()}`)}let d={};return c.headers.forEach((p,u)=>{d[u]=p}),{status:c.status,headers:d,json:await c.json()}}var go=class{flagStore;orgId;scratchPadId;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;analytics;recordAbortController=null;constructor({browser:e,generator:t,logger:r,analytics:o,flagStore:i,storage:s,orgId:a,localCodeEvalTools:l,uploadedFileStorage:c,visualDiffScreenshotStorage:d,scratchPadId:p}){this.orgId=a,this.scratchPadId=p,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=s,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=d,this.localCodeEvalTools=l,this.generator=t,this.logger=r,this.analytics=o,this.flagStore=i}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}setLogger(e){this.logger=e}async evaluateAiAction({goal:e,startingScreenshot:t,history:r,disableCache:o,langfuseSessionId:i,lastError:s,logger:a=this.logger}){let[l,c]=await Promise.all([Gn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=await Ir({type:"ai-action",description:e,serializedTree:l.serializedTree,tree:l.tree,logger:a,generator:this.generator,flagStore:this.flagStore,orgId:this.orgId,softTokenLimit:25e3,hardTokenLimit:5e4}),p=`data:image/jpeg;base64,${c.toString("base64")}`,u={url:this.browser.url(),browserState:d,startingScreenshot:t,history:r,goal:e,screenshot:p,lastError:s};return await this.generator.getMultiturnAiActionEvaluation(u,{disableCache:o,orgId:this.orgId,abortSignal:this.executeAbortController.signal,loggerTags:{...nt(a)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:r,actionHint:o,disableCache:i,logger:s=this.logger,langfuseSessionId:a}){let l=this.browser.url(),[c,d]=await Promise.all([Gn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),p=`data:image/jpeg;base64,${d.toString("base64")}`,u=await Ir({type:"ai-action",description:e,serializedTree:c.serializedTree,tree:c.tree,logger:s,generator:this.generator,flagStore:this.flagStore,orgId:this.orgId,softTokenLimit:25e3,hardTokenLimit:5e4}),m={url:l,browserState:u,startingScreenshot:t,history:r,goal:e,actionHint:o,screenshot:p};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,orgId:this.orgId,abortSignal:this.executeAbortController.signal,loggerTags:{...nt(s)},langfuseSessionId:a})}catch(h){throw new A("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(e){return Gn(this.browser,e)}async locateElement(e){return ld(e,this.getControllerFixtures())}async locateElementWithSelector(e,t){return hn({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:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}async wrapMultiElementTargetingCommand({ctx:e,command:t,targetNames:r,descriptions:o,caches:i,action:s,options:a,retriesWithAI:l=1}){let c=[];for(let d=0;d<o.length;d++){let p=o[d],u=await this.wrapElementTargetingCommand({ctx:e,command:t,target:p,cache:i[d],action:async m=>m,options:{...a,skipFetchTree:d!==0,targetName:r[d]}});c.push(u)}try{return{result:await s(...c.map(p=>p.result)),elementInteractedDisplayStrings:c.map(p=>p.elementInteractedDisplayString),newTargets:c.map(p=>p.newTarget)}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.debug({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,command:t,targetNames:r,descriptions:o,caches:o.map(()=>{}),action:s,options:a,retriesWithAI:l-1});throw new A("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){return hn({action:()=>this.wrapElementTargetingCommandHelper(e),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper({ctx:e,target:t,cache:r,action:o,options:i,command:s}){let{disableCache:a,useSelector:l,targetName:c="target",targetHealingInProgress:d}=i,p=i.retriesWithAI??1,u=!1,m=this.logger.child({commandId:s.id});if((!r||a)&&!gl(t))throw new A("ActionFailureError","Cannot target element with no cached data or element descriptor");if(l){if(t.type!=="description")throw new A("ActionFailureError","Cannot use selector with non-description target");let g=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:c,logger:m});return{result:await o({locator:g.locator}),elementInteractedDisplayString:g.displayString,newTarget:{cache:{id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()}}}}a&&(this.logger.debug("Cache explicitly disabled for this step"),u=!0,r=void 0),r?.inputDescription&&!Fu(t.elementDescriptor,r.inputDescription)&&(this.logger.debug({old:r.inputDescription,new:t.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),u=!0,r=void 0);let h=!!r&&Ip(r);if(!r){let g=new Date;this.logger.debug({targetHealingInProgress:d},"Prompting AI for an updated element location"),u&&await Q(this.browser.smartWaitingTimeout,this.executeAbortController.signal),p--;let f=await ld({description:Os(s,t.elementDescriptor),disableCache:a,iframeUrl:i.iframeUrl},this.getControllerFixtures(e));f.frameConfig&&this.browser.setActiveFrameConfig(f.frameConfig);let y=i.disableGlobalLocatorRedirect?{locator:f.resolution.locator}:await this.attemptLocatorRedirect(f.resolution.locator,m),v=await o(y),b;if(d){this.analytics.track({type:"execution:step_heal",heal_type:"AI",step_type:"PRESET_ACTION",command_type:s.type,duration_ms:Date.now()-g.getTime()}),f.target={...f.target,targetSource:"AI_HEALED",targetUpdateTime:new Date().toUTCString()};let E=f.resolution.pageState;if(E)try{b=await this.getReverseMappedTarget(E,f.target.id,!0)}catch(x){m.warn({err:x},"Failed to reverse map element auto-healed by AI, continuing...")}}return{result:v,elementInteractedDisplayString:f.resolution.displayString,newTarget:{cache:f.target,thoughts:f.thoughts,description:b}}}try{let g=new Date;if(r.frameCache&&this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")){let b=await this.browser.resolveAutoFrameCache(r.frameCache);this.browser.setActiveFrameConfig(b)}let f=await this.browser.resolveTarget(e,r,{targetName:c,logger:m}),y=i.disableGlobalLocatorRedirect?{locator:f.locator}:await this.attemptLocatorRedirect(f.locator,m),v=await o(y);if(h){let b=f.decisions.filter(E=>E.matched);if(b.length!==1)m.warn({decisions:f.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let E=b[0].type;this.analytics.track({type:"execution:step_heal",heal_type:E,step_type:"PRESET_ACTION",command_type:s.type,duration_ms:Date.now()-g.getTime()})}m.debug({cache:r},"Successfully used cached target to perform action")}else m.debug({cache:r},"Successfully generated and used new target data");return{result:v,elementInteractedDisplayString:f.displayString,newTarget:{cache:r}}}catch(g){if(this.throwIfClosed(),g instanceof A)throw g;if(p>0&&t)return m.debug({err:g,cache:r},"Failed to execute action with cached target, retrying with AI"),this.wrapElementTargetingCommand({ctx:e,command:s,target:t,cache:void 0,action:o,options:{...i,retriesWithAI:p,targetHealingInProgress:!0}});throw new A("ActionFailureError",g.message,{errOptions:{cause:g}})}}async attemptLocatorRedirect(e,t){return this.flagStore.isBooleanFlagEnabled("global_locator_redirect")?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return vi(this.browser,e)}async executePresetCommand(e,t,r,o){let i;try{i=await this.resolveCommandTemplateStrings(t,r)}catch(s){throw this.throwIfClosed(),new A("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=(await this.browser.getOpenPages()).map(u=>u.url),a=this.browser.url(),l=await this.executePresetCommandHelper(e,t,r,o),c=!0;(t.type==="NAVIGATE"||t.type==="NEW_TAB"||t.type==="TAB"||t.type==="REFRESH"||t.type==="WAIT_FOR_URL")&&(c=!1);let d=(await this.browser.getOpenPages()).map(u=>u.url),p=this.browser.url();if(c&&d.length!==s.length)for(let u=d.length-1;u>=s.length;u--){let m=d[u];if(Bn(m,this.logger)&&m!==a&&m!==p){this.logger.info({beforePages:s,afterPages:d,beforeUrl:a},"Auto-following new tab"),await this.browser.switchToPage({type:"INDEX",index:u});break}}return l}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{this.restoreCommandTemplateReplacements(t,i)}}restoreCommandTemplateReplacements(e,t={}){for(let[r,o]of Object.entries(t))rd(e,r,o)}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Vc(e)}}async resolveCommandTemplateStrings(e,t){return io({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,r,o){switch(o=o||"disableCache"in t&&!!t.disableCache,t.type){case"SUCCESS":let i=t.condition;return i?.assertion.trim()?cd({command:i,fixtures:this.getControllerFixtures(e)}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_WAIT":case"AI_ASSERTION":{if(!t.assertion.trim())throw new A("ActionFailureError","Missing assertion");if(t.timeout&&t.timeout>1800)throw new A("AssertionFailureError",`AI assertion timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);return cd({command:{...t,type:"AI_ASSERTION"},fixtures:this.getControllerFixtures(e)})}case"AI_EXTRACT":{if(!t.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");let u=await this.browser.getCondensedHtml(),m=await this.browser.screenshot({retries:2});try{let h=await this.generator.getTextExtraction({goal:t.goal,browserState:u,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${m.toString("base64")}`},{disableCache:o,orgId:this.orgId,abortSignal:this.executeAbortController.signal,loggerTags:nt(this.logger)});if(h.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");if(h.thoughts?.includes("MaxGenerationLengthExceededError"))throw new A("UserConfigurationError",h.thoughts);return{thoughts:h.thoughts||void 0,data:h.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(h){let g=h.message;throw g.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."):g.includes("AIProviderError")&&g.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:h}}):h}}case"NAVIGATE":if(!so(t.url)&&!ao(t.url,this.browser.baseUrl))throw new A("ActionFailureError",`Invalid URL provided to navigate command: ${t.url}`);await this.browser.navigate({url:t.url,loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(t.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let s=await this.browser.solveCaptcha();s&&(await this.wrapElementTargetingCommand({ctx:e,command:t,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:u=>this.browser.click(u,this.createCallbacksForBrowser(this.orgId),{}),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}}),await this.browser.type(s,{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 u,m=[];if(t.target&&cn(t.target))await this.browser.hoverUsingVisualCoordinates(t.target.pixels);else if(t.target&&t.target.elementDescriptor.trim()){let{newTarget:h,elementInteractedDisplayString:g}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:t.target,cache:t.cache?.target,action:f=>this.browser.hover(f),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});u=g,m.push(h)}switch(t.type){case"SCROLL_UP":await this.browser.scrollVertical(-(t.deltaY??0));break;case"SCROLL_DOWN":await this.browser.scrollVertical(t.deltaY);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(t.deltaX??0));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(t.deltaX);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:u,newTargets:m}}case"WAIT_FOR_URL":{if(t.timeout&&t.timeout>1800)throw new A("UserConfigurationError",`Wait for URL timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);let u=t.matcher;if(!u&&t.url&&(u={type:"GLOB",glob:t.url}),!u)throw new A("UserConfigurationError","No URL matcher provided for wait for URL command");await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:u},{timeout:t.timeout?t.timeout*1e3:void 0,negated:t.negated,caseInsensitive:t.caseInsensitive});break}case"WAIT":if(t.delay>1800)throw new A("UserConfigurationError",`Wait timeout of ${t.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=t.delay*1e3;await Q(a,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"CLICK":{if(cn(t.target)){await this.browser.clickUsingVisualCoordinates(t.target.pixels,t);break}let u=this.browser.url(),m={disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl},{elementInteractedDisplayString:h,newTarget:g,result:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,command:t,cache:t.cache?.target,action:v=>this.browser.click(v,this.createCallbacksForBrowser(this.orgId),t),options:m});g.cache&&(t.cache={target:g.cache});let y={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,newTargets:[g],data:f};return Zs(u,y.urlAfterCommand)&&(y.succeedImmediately=!0,y.succeedImmediatelyReason="URL changed"),y}case"COPY":return await this.browser.copy(t.value),{succeedImmediately:!1,data:t.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(cn(t.fromTarget)&&cn(t.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(t.fromTarget.pixels,t.toTarget.pixels,{hoverSeconds:t.hoverSeconds});break}if(cn(t.fromTarget)||cn(t.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{newTargets:u,elementInteractedDisplayStrings:m}=await this.wrapMultiElementTargetingCommand({ctx:e,command:t,targetNames:["from target","to target"],descriptions:[t.fromTarget,t.toTarget],caches:[t.cache?.fromTarget,t.cache?.toTarget],action:(h,g)=>this.browser.dragAndDrop(h.locator,g.locator,{hoverSeconds:t.hoverSeconds}),options:{useSelector:!!t.useSelector,disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m[0],newTargets:u}}case"MOUSE_DRAG":{let u=parseInt(t.deltaX),m=parseInt(t.deltaY),h=t.steps??5;if(isNaN(u)||isNaN(m))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);if(t.target&&cn(t.target)){await this.browser.mouseDragUsingVisualCoordinates(u,m,h,t.target.pixels,{force:t.force});break}let g,f,y=[];if(t.target?.elementDescriptor){let{newTarget:v,elementInteractedDisplayString:b,result:E}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:t.target,cache:t.cache?.target,action:async x=>x.locator,options:{useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableCache:o}});g=E,f=b,y.push(v)}return await this.browser.mouseDrag(u,m,h,g,{force:t.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,newTargets:y}}case"SELECT_OPTION":{if(!kn(t.target))throw new Error("Select with x/y is not supported yet");let u=t.target.elementDescriptor,m=t.choice??{type:"VALUE",value:t.option},{newTarget:h,elementInteractedDisplayString:g}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:{type:"description",elementDescriptor:u},cache:t.cache?.target,action:f=>this.browser.selectOption(f,m,t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,newTargets:[h]}}case"TAB":{let u={loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0,retry:!0};if(t.url)await this.browser.switchToPage({type:"SUBSTRING",substring:t.url},u);else if(t.action)await this.browser.switchToPage(t.action,u);else throw new A("UserConfigurationError","No method definition was specified for the tab switch command");break}case"NEW_TAB":await this.browser.createNewTab(t.url,{loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"COOKIE":if(!t.value)break;let l=await this.browser.setCookie(t.value);this.logger.debug({results:l},"Set cookies");break;case"LOCAL_STORAGE":if(!t.value||!t.key)break;await this.browser.setLocalStorage(t.key,t.value);break;case"JAVASCRIPT":{let u;try{t.environment==="BROWSER"?(u=await this.browser.evaluateCodeInPage({code:t.code,fragment:t.fragment??!1,context:r.toObjectCopy(),timeoutMs:t.timeout?t.timeout*1e3:void 0}),this.logger.debug({result:u},"Executed JavaScript in browser")):u=await An({orgId:this.orgId,code:t.code,fragment:!!t.fragment,context:r,timeoutMs:t.timeout?t.timeout*1e3:void 0,logger:this.logger,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async m=>{if(!this.scratchPadId){this.logger.warn({updates:m},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.scratchPadId,orgId:this.orgId,updates:m,logger:this.logger})}}})}catch(m){throw this.throwIfClosed(),new A("ActionFailureError",m instanceof Error?m.message:`${m}`,{errOptions:{cause:m}})}try{JSON.stringify(u)}catch(m){throw new A("ActionFailureError",`Return value is not serializable: ${m instanceof Error?m.message:`${m}`}`,{errOptions:{cause:m}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:u}}case"TYPE":{if(t.target&&cn(t.target)){await this.browser.clickUsingVisualCoordinates(t.target.pixels,t),await this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter},!0);break}let u=this.browser.url(),m,h=[],g=KA(t.target);if(g){let{elementInteractedDisplayString:y,newTarget:v}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:g,cache:t.cache?.target,action:b=>this.browser.typeIntoTarget(t.value,b,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter}),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableGlobalLocatorRedirect:!0}});h.push(v),m=y}else await this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter},!0);let f={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:m,newTargets:h};return Zs(u,f.urlAfterCommand)&&(f.succeedImmediately=!0,f.succeedImmediatelyReason="URL changed"),f}case"HOVER":{if(cn(t.target)){await this.browser.hoverUsingVisualCoordinates(t.target.pixels);break}let{newTarget:u,elementInteractedDisplayString:m}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:t.target,cache:t.cache?.target,action:h=>this.browser.hover(h),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,newTargets:[u]}}case"FOCUS":{if(!kn(t.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:u,newTarget:m}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:t.target,cache:t.cache?.target,action:h=>this.browser.focus(h),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:u,newTargets:[m]}}case"BLUR":{if(t.target&&!kn(t.target))throw new Error("Blur with x/y is not supported yet");if(!t.target||!t.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{newTarget:u,elementInteractedDisplayString:m}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,command:t,cache:t.cache?.target,action:h=>this.browser.blur(h),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,newTargets:[u]}}case"PRESS":let c=this.browser.url();await this.browser.press(t.value,{repeat:t.repeat,convertMeta:t.convertMeta,delayMs:t.delayMs});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Zs(c,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;case"REQUEST":{let u=new YA,m=qA(fetch,u),h;try{h=new URL(t.url).hostname}catch{}return{data:{...await Qs({command:t,baseUrl:this.browser.baseUrl,logger:this.logger,fetchImplementation:m}),cookies:Us(u,h)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await $f({command:t,baseUrl:this.browser.baseUrl,logger:this.logger}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return ug({ctx:e,command:t,disableCache:o,browser:this.browser,logger:this.logger,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:u=>this.wrapElementTargetingCommand(u)});case"FILE_UPLOAD":{let u,m;if(t.fileSource.type==="URL"?(m=t.fileSource.url,u=await nf({uri:t.fileSource.url,logger:this.logger,orgId:this.orgId})):t.fileSource.type==="USER_FILE"&&(m=t.fileSource.name,u=await this.uploadedFileStorage?.getFileForUpload(t.fileSource.name,this.orgId)),!u)throw new A("UserConfigurationError",`Attempted to use non-existent file for upload step: ${m}`);await this.browser.setFileChooserHandler({...u,filename:t.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let u;if(!t.storageState.trim())u=void 0;else if(u=await An({orgId:this.orgId,code:t.storageState,fragment:!1,context:r,logger:this.logger,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof u!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof u} instead)`);let m;try{m=Ds.optional().parse(u)}catch(h){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${h}`)}await this.browser.loadAuthState(m);break}case"ELEMENT_CHECK":{let u=(t.timeout??xn)*1e3,m=await dg({command:t,timeoutMs:u,targetingWrapper:h=>this.wrapElementTargetingCommand(h),fixtures:this.getControllerFixtures(e),disableCache:o});return{fail:!m.success,data:m.data,elementInteracted:m.elementInteractedDisplayString,newTargets:m.newTarget?[m.newTarget]:[],thoughts:m.err?.message??m.thoughts??`Element assertion ${m.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let u=await hn({action:async()=>ea({assertion:t.assertion,browser:this.browser,logger:this.logger,timeout:t.timeout,signal:this.executeAbortController.signal}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:this.browser,logger:this.logger});return{fail:!u.success,data:u.data,thoughts:u.success?"Page assertion passed.":u.err?.message??`Page assertion still failing after ${t.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}default:return(u=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedTarget(e,t,r){return(await this.generator.getReverseMappedDescription({browserState:e,goal:`element with ID ${t}`},{disableCache:r,orgId:this.orgId,abortSignal:this.executeAbortController.signal,loggerTags:nt(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode(e){this.recordAbortController=new AbortController;let t=new Sa({signal:this.recordAbortController.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,t),t}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,orgId:this.orgId,abortSignal:this.executeAbortController.signal,loggerTags:nt(this.logger)})}async runFailureRecovery(e){return this.generator.getFailureRecoveryProposal(e,{disableCache:!0,orgId:this.orgId,abortSignal:this.executeAbortController.signal,loggerTags:nt(this.logger)})}};var XA=4;async function Hf({socket:n,logger:e,analytics:t,storage:r,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:s,devicePixelRatio:a,generatorFactory:l,enricherFactory:c,browserbase:d,authorization:p}){let u=n.id,m=n.handshake.query.testId;if(!m)throw new Error("Socket connection request is missing testId");let h=await r.getOrgId({type:"e2e",testId:m});e=e.child({testId:m,orgId:h,sessionId:u});let g=await l(h,e),f=await c(h,e),{testMetadata:y,baseUrl:v,envName:b,localBrowserConfigFromEnv:E,environmentVariables:x,localCodeEvalTools:C}=await Pr({testId:m,orgId:h,logger:e,storage:r,authorization:p});if(K.getSession(u))return e.info("Associating connection with existing session (likely reconnect)"),{type:"e2e",sessionId:u,orgId:h,testId:m};let N=n.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:N,event:"connect",args:n.handshake.query},"Websocket event (connect)"),N&&K.getCurrentConnectionsByIp(N)>=XA)throw e.error({clientIp:N,sessions:K.getCurrentSessionsByIp(),...n.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.");K.reserveCapacityByIp(N);try{await JA({socket:n,baseUrl:v,envName:b,testMetadata:y,orgId:h,sessionId:u,logger:e,analytics:t,environmentVariables:x,clientIp:N,devicePixelRatio:a,storage:r,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:s,localCodeEvalTools:C,generator:g,enricher:f,browserbase:d,localBrowserConfigFromEnv:E})}catch(P){throw e.warn({err:P},"Error setting up socket session, possibly due to client closing the connection"),K.releaseCapacityByIp(N),P}return{type:"e2e",sessionId:u,testId:m,orgId:h}}async function JA({socket:n,baseUrl:e,envName:t,devicePixelRatio:r,testMetadata:o,orgId:i,sessionId:s,logger:a,analytics:l,storage:c,uploadedFileStorage:d,visualDiffScreenshotStorage:p,serviceMocker:u,localCodeEvalTools:m,generator:h,environmentVariables:g,localBrowserConfigFromEnv:f,clientIp:y,enricher:v,authorization:b}){let E={};E.viewport=o.advanced?.viewport,r&&(E.deviceScaleFactor=r);let x=o.id,C=await u?.initializeServicesForTest(i,x),L=await aa({advanced:{...f,...o.advanced},orgId:i,baseUrl:e,envName:t,localTools:m,envVariables:g,logger:a,customHeaders:void 0});a=a.child({orgId:i,sessionId:s,testId:x});let N=await co.init(i),P=await tn.init({baseUrl:e,userBrowserSettings:L,enricher:v,storage:c,flagStore:N,mockedServices:C,logger:a,contextArgs:E,onTabsChange:(I,ae)=>{n.emit("tabs",{tabs:I,activeTab:ae})}});await P.navigate({url:e,initialNavigation:!0});let U=new go({browser:P,generator:h,logger:a,analytics:l,flagStore:N,orgId:i,scratchPadId:void 0,storage:c,localCodeEvalTools:m,uploadedFileStorage:d,visualDiffScreenshotStorage:p}),$=jh(n,s,a),ee=async()=>{$.timers.forEach(I=>clearInterval(I))},k=new Tt({baseUrl:e,currentUrl:U.browser.url(),variablesFromEnvironment:g,envName:t});if(!n.connected)throw await P.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");n.emit("session",{url:e,userAgent:tn.USER_AGENT,viewport:U.browser.getViewport(),sessionId:s}),K.registerSession({controller:U,context:k,sessionId:s,cleanup:ee,clientIp:y})}async function Pr({testId:n,orgId:e,logger:t,storage:r,authorization:o}){let i=await r.fetchTestMetadata(n,e,t);if(!i)throw new Error(`Test metadata could not found for test ${n}`);let s;o?.type==="API_KEY"&&(s=new Un({httpClient:new At(o)}));let a=i.envs?.find(u=>u.default),l;a&&(l=await r.fetchEnvironment(e,a.name,t));let c=l&&"browser"in l?l.browser:void 0,d=i.baseUrl||l?.variables?.[ve];if(!d)throw new Error("Base URL is empty in both test options and the configured environment");let p={...l?.variables};return await Promise.all((i.parameters??[]).map(async u=>{let m=await Ot({orgId:e,s:u.defaultValue,context:Tt.dummyContext(l?.name,p),logger:t,localTools:s});p[u.name]=m})),{localCodeEvalTools:s,baseUrl:d,envName:l?.name,localBrowserConfigFromEnv:c,environmentVariables:p,testMetadata:i}}var dd={currentlyExecutingRequests:{}},eR=n=>async(e,t)=>{let r,{testId:o,orgId:i}=n.metadata,s=await Pr({testId:o,orgId:i,logger:n.logger,storage:n.storage,authorization:n.authorization}),a=`${o}|${s.baseUrl}`;try{let l=dd.currentlyExecutingRequests[a]??0;dd.currentlyExecutingRequests[a]=l+1,r=await tR({...n,...e,...s,done:t})}finally{n.logger.info({result:r,sessionId:n.metadata.sessionId},"Test execution complete"),dd.currentlyExecutingRequests[a]--}},tR=async({socket:n,steps:e,baseUrl:t,testMetadata:r,reInitialize:o,toStepId:i,fromStepId:s,storage:a,debugDataStorage:l,metadata:c,logger:d,analytics:p,envName:u,environmentVariables:m,localCodeEvalTools:h,done:g})=>{let{testId:f,sessionId:y,orgId:v}=c,b=y,E=K.getSession(y);if(!E)throw new Error("No active session found");let{controller:x,context:C}=E;x.setOpen(),d=d.child({testId:f,orgId:v,baseUrl:t,sessionId:y,runId:b}),d.info({steps:e.map(O=>`${O.type}${"command"in O?` - ${O.command.type}`:""}`),toStepId:i,fromStepId:s,reInitialize:o,envName:u,baseUrl:t,context:C,flags:x.flagStore.getAllFlags()},"Socket execution parameters");let L=m??{},N=async()=>{o&&(await x.browser.reset({newUrl:t}),C.reset({baseUrl:t,currentUrl:x.browser.url(),variablesFromEnvironment:L,envName:u}))},P=async()=>{try{await a.resolveStepCacheEntries({schemaVersion:r.schemaVersion,organizationId:v,testId:f,steps:e,logger:d})}catch(O){d.error({err:O},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Si({promiseGenerator:async()=>Promise.all([N(),P()]),signal:x.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),x.setOpen()}catch(O){if(n.emit("finished"),O.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${O}`)}let U=QA(e),$={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},ee={orgId:v,runId:b,testMetadata:r,steps:e,fromStepId:s,toStepId:i},k={controller:x,context:C,storage:a,debugDataStorage:l,codeEvalTools:h,billingReporter:new _s,logger:d,analytics:p},ae=await sa({fixtures:k,options:$,callbacks:{test:{onTestComplete:async()=>{n.emit("finished")},onSaveScreenshot:nR,onTestSuccess:async O=>{let Qe=O.steps,Z=ZA(U,Qe);if(Object.keys(Z).length>0){d.debug({changes:Z},"Updating steps post-run success");let{cachesToSave:Ce}=await Lt({stepLists:{steps:Qe},cacheCreationParams:{testId:f,orgId:v}});try{await a.saveStepCacheEntries(Ce,r.id,d)}catch(Le){d.warn({err:Le},"Failed to save step cache entries after execution success")}}else d.debug("No changes detected in steps post-run success")}},step:{onStarted:O=>n.emit("started",{stepId:O}),onSuccess:O=>{n.emit("success",O)},onFailure:O=>{n.emit("failure",O)},onCancelled:O=>{n.emit("cancelled",O)},onCommandGenerated:O=>{n.emit("commandGenerated",O)},onCommandExecuted:O=>{n.emit("commandExecuted",O)},onDynamicAIActionStatusUpdateEvent:O=>{n.emit("dynamicCommandStatusUpdate",O)},onDynamicAIActionEvaluatingEvent:O=>{n.emit("dynamicCommandEvaluating",O)},onDynamicCommandGenerated:O=>{n.emit("dynamicCommandGenerated",O)},onDynamicCommandExecuted:O=>{n.emit("dynamicCommandExecuted",O)}}},inputs:ee});return g?.(ae),ae.status},nR=async n=>n.toString("base64");var Wf={event:"execute",createHandler:eR};var rR=({metadata:n,logger:e,storage:t})=>{let{sessionId:r}=n;return async(o,i)=>{let{command:s,testMetadata:a,returnScreenshot:l}=o,c=Os(s,o.description);e.info({params:o},`Locate handler called - ${c}`);let d=K.getSession(r);if(!d)throw new Error("No active session found");let{controller:p,context:u}=d;p.setOpen();let m=Kr.parse(a.advanced??{}),h={},g;if(c){if("useSelector"in s&&s.useSelector)try{let f=await p.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);g=f.resolution.locator,h={target:f.target,thoughts:f.thoughts}}catch(f){e.warn({err:f},"Failed resolving target with selector"),i({err:`Failed locating element: ${f.message}`,decisions:f instanceof Fn?f.decisions:void 0});return}else try{let f=await p.locateElement({description:c,disableCache:m.disableAICaching,iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,skipWait:!0,testContext:u});h={target:f.target,thoughts:f.thoughts},g=f.resolution.locator}catch(f){(async()=>{try{let y=await p.browser.getCondensedHtml({skipWait:!0});e.warn({err:f,html:y.slice(0,1e5)},"Failed locating element with AI")}catch(y){e.warn({err:y},"Failed grabbing HTML after trying to locate element with AI")}})(),i({err:`Failed locating element with AI: ${f.message}`});return}if(s.type==="SELECT_OPTION"&&g)try{h.options=await p.browser.getSelectOptions(g)}catch(f){e.warn({err:f},"Failed getting select options"),i({err:`Failed getting select options: ${f.message}`});return}e.info({result:h},"Locate handler result")}if(l)try{let{buffer:f,width:y,height:v}=await p.screenshotWithDimensions({clearHighlights:!0,locator:g,hideCaret:!0}),b=await t.uploadScreenshot(f);h.screenshot={data:b,width:y,height:v}}catch(f){e.error({err:f},"Error capturing screenshot during locate"),i({err:`Error taking screenshot: ${f.message}`});return}if(i({result:h}),g)try{await Promise.all([p.browser.scrollIntoView(g),p.browser.highlight(g)])}catch(f){e.warn({err:f},"Error highlighting element, continuing...")}}},Gf={event:"locate",createHandler:rR};var oR=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async({percentX:r,percentY:o},i)=>{let s=K.getSession(t);if(!s)throw new Error("No active session found");let a=s.controller.browser;try{await a.clickMouseFromPositionPercentages(r,o)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode"),i({err:l.message})}}},Vf={event:"cloudClick",createHandler:oR};var iR=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=K.getSession(t);if(!i)throw new Error("No active session found");let{controller:s}=i;s.setOpen(),i.browserBehavior.showOverlay=!0;try{let a=await s.browser.captureTargetFromClick();o({result:a})}catch(a){e.error({err:a},"Record click failed"),o({err:a instanceof Error?a.message:`${a}`})}finally{i.browserBehavior.showOverlay=!1}}},qf={event:"recordTargetClick",createHandler:iR};var sR=({metadata:n,logger:e})=>{let{sessionId:t}=n,r,o=0,i=(a,l)=>{let c=async()=>{r=void 0;try{await a.highlightFromPositionPercentages(l),o=0}catch(d){e.error({err:d},"Error highlighting element on mouse move"),o++}};clearTimeout(r),r=setTimeout(c,50*(o+1))},s=0;return async a=>{let l=K.getSession(t);if(!l)throw new Error("No active session found");let{controller:c,browserBehavior:d}=l,p=c.browser;if(!p.closed){if(p.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}d.showOverlay&&(console.error("[MOMENTIC][DEBUG] CDP highlight occurred"),i(p,a));try{await p.moveMouseFromPositionPercentages(a.percentX,a.percentY),s=0}catch(u){s++,s%5===0&&e.warn({err:u,mouseErrors:s},"Error in socket mouse move handler")}}}},Kf={event:"cloudMouseMove",createHandler:sR};var aR=({metadata:n})=>{let{sessionId:e}=n;return async({percentDeltaX:t,percentDeltaY:r})=>{let o=K.getSession(e);if(!o)throw new Error("No active session found");let i=o.controller.browser;if(i.closed)return;let s=await i.scrollFromPositionPercentages(t,r);if(!s)return;let a=o.browserBehavior.recordingState?.transformer;a&&a.recordScroll({...s,url:i.url()})}},Yf={event:"cloudScroll",createHandler:aR};var lR=({metadata:n,generatorFactory:e,socket:t,logger:r})=>{let{sessionId:o,orgId:i,testId:s}=n;return async({stepId:a})=>{let l=K.getSession(o);if(!l)throw new Error("No active session found");let{controller:c,browserBehavior:d}=l,p=await e(i,r);r.info("Starting cloud recording");let u=await c.startRecordMode({generator:p,logger:r,testId:s,orgId:i,onStepRecord:(m,h)=>{t.emit("stepRecorded",{stepId:a,step:m,offset:h})}});d.recordingState={transformer:u},d.showOverlay=!0}},Xf={event:"cloudStartRecording",createHandler:lR};var cR=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{let r=K.getSession(t);if(!r)throw new Error("No active session found");e.info("Stopping cloud recording"),await r.controller.stopRecordMode(),r.browserBehavior.recordingState=void 0,r.browserBehavior.showOverlay=!1}},Jf={event:"cloudStopRecording",createHandler:cR};var dR=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],pR=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async({key:r})=>{let o=K.getSession(t);if(!o)throw new Error("No active session found");if(dR.includes(r))return;let{controller:i}=o;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:t},"Browser is closed, ignoring typing action");return}try{r.length>1?await i.browser.press(r,{}):await i.browser.type(r,{clearContent:!1,pressKeysSequentially:!0})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:t,err:s},"Browser is closed, ignoring typing action error");return}throw s}}},Zf={event:"cloudType",createHandler:pR};var uR=({socket:n,metadata:e,logger:t,storage:r,authorization:o})=>async(i,s)=>{let{testId:a,sessionId:l,orgId:c}=e;t.info({testId:a,sessionId:l},"Refresh event received");let{baseUrl:d}=await Pr({testId:a,orgId:c,logger:t,storage:r,authorization:o}),p=K.getSession(l);if(!p){n.emit("error",{message:"No session to refresh"});return}let{controller:u}=p;u.setOpen(),await u.browser.refresh();let m=u.browser.getViewport();t.info({baseUrl:d,viewport:m},`Session refreshed for test ${a} at ${d}`),s()},Qf={event:"refresh",createHandler:uR};var mR=({socket:n,metadata:e,logger:t,storage:r,authorization:o})=>async()=>{let{testId:i,sessionId:s,orgId:a}=e;t.info({testId:i,sessionId:s},"Reset event received");let{baseUrl:l,envName:c,environmentVariables:d}=await Pr({testId:i,orgId:a,logger:t,storage:r,authorization:o}),p=K.getSession(s);if(!p){n.emit("error",{message:"No session to reset"});return}let{controller:u,context:m}=p;await u.browser.reset({newUrl:l});let h=u.browser.baseUrl;m.reset({baseUrl:h,currentUrl:u.browser.url(),variablesFromEnvironment:d,envName:c});let g=u.browser.getViewport(),f=tn.USER_AGENT;t.info({baseUrl:l,viewport:g},`Session reset for test ${i} at ${h}`),n.emit("session",{url:h,userAgent:f,viewport:g,sessionId:s})},ey={event:"reset",createHandler:mR};var hR=({metadata:n})=>{let{sessionId:e}=n;return async({url:t})=>{let r=K.getSession(e);if(!r)throw new Error("No active session found");await r.controller.browser.switchToPage({type:"SUBSTRING",substring:t})}},ty={event:"switchTab",createHandler:hR};async function ny(n){let{socket:e}=n;return e.handshake.query.type==="api-test"?eg(n):Hf(n)}var ry=[ig,Wf,Gf,ey,Qf,ng,ty,qf,Xf,Jf,Kf,Vf,Zf,Yf,tg,$h,og,rg];var oy=n=>{let{logger:e}=n,t=new gR(n.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7});return t.on("connection",async r=>{let o;try{e.info({event:"connection",transport:r.conn.transport.name},"Websocket connection established"),o=await ny({...n,socket:r,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),r.emit("error",{message:i instanceof Error?i.message:`${i}`}),r.disconnect(!0);return}ry.forEach(i=>fR(i,{socket:r,metadata:o,...n,logger:e}))}),t},fR=(n,e)=>{let t=n.createHandler(e),r=(...o)=>{["cloudMouseMove","cloudScroll","cloudType","cloudClick"].includes(n.event)||e.logger.debug({...e.metadata,event:n.event,args:o},`Websocket event (${n.event})`);let i=s=>{e.logger.error({event:n.event,type:"websocket",args:o,err:s instanceof Error?s:new Error(`${s}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:s instanceof Error?s.message:`${s}`})};try{let s=t.apply(void 0,o);s&&typeof s.catch=="function"&&s.catch(i)}catch(s){i(s)}};e.socket.on(n.event,r)};import{Router as yP}from"express";import Wt from"fs";import yn from"path";import Lr from"yaml";import wa from"fs";import yR from"path";import{v4 as bR}from"uuid";import va from"yaml";function pd(n,e,t){let r=t.modules[n.moduleId]?.fullFilePath;if(!r)throw new Error(`Tried to update module ${n.moduleId} that could not be found on disk`);let o={...n,schemaVersion:e},i={fileType:be.MODULE,...hc.parse(o),steps:n.steps},s=va.stringify(i);wa.writeFileSync(r,s,"utf-8")}function iy(n,e,t,r){let o=t.modules[n]?.fullFilePath;if(!o)throw new Error(`Tried to update module ${n} that could not be found on disk`);let i=Ii(o,r),s={...i,...e},a={fileType:be.MODULE,...hc.parse(s),steps:i.steps},l=va.stringify(a);wa.writeFileSync(o,l,"utf-8")}async function sy({name:n,description:e,enabled:t,steps:r,folder:o}){let i=Me(n),s=yR.join(o,`${i}.module.yaml`),a=bR(),{stepsToSave:l}=await Lt({stepLists:{steps:r}}),c={fileType:be.MODULE,schemaVersion:mt,moduleId:a,name:n,description:e,enabled:t,steps:l.steps},d=va.stringify(c);return wa.writeFileSync(s,d,"utf-8"),{moduleId:a,name:n,description:e,enabled:t,steps:r}}function Ii(n,e){let t=wa.readFileSync(n,"utf-8"),r=va.parse(t);try{return yc.parse(r)}catch(o){throw e.error({err:o,moduleFilePath:n,moduleContents:t},`${n} does not parse as a valid Momentic module`),o}}async function ud(n,e,t,r){let o=Ii(n.fullFilePath,t),{resolvedSteps:i}=await Ys({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:r,logger:t,callbacks:{onFetchModule:async({id:a})=>{let l=e.modules[a]?.fullFilePath;if(l)return Ii(l,t)}}}),s={...o,steps:i};return r&&(r[n.id]=s),s}async function xa(n,e){let t={};return await Promise.all(Object.values(n.modules).map(async r=>{await ud(r,n,e,t)})),Array.from(Object.values(t))}async function ay({test:n,name:e,folder:t}){let r=await Bh(n);if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${Me(e)}.${Cn.TEST}`,s=yn.join(t,i);return Wt.writeFileSync(s,r.test,"utf-8"),s}function md(n,e,t){let r=yn.join(t.rootDir,n);if(!Wt.existsSync(r))throw new Error(`Test not found at path '${n}' in project '${t.rootDir}'`);let o=Wt.readFileSync(r,"utf-8"),i=Lr.parse(o),s={...i,...e},a=pn.parse(s),l={fileType:be.TEST,...pn.parse(a),steps:i.steps},c=Lr.stringify(l);Wt.writeFileSync(r,c,"utf-8")}function Pi(n,e,t,r){let o=yn.join(r.rootDir,n);if(!Wt.existsSync(o))throw new Error(`Test not found at path '${n}' in project '${r.rootDir}'`);let i=Wt.readFileSync(o,"utf-8"),s=Lr.parse(i),a=pn.parse({...s,schemaVersion:t}),l={fileType:be.TEST,...a,beforeSteps:e.beforeSteps??void 0,steps:e.steps,afterSteps:e.afterSteps??void 0},c=Lr.stringify(l);Wt.writeFileSync(o,c,"utf-8")}function hd(n,e,t=n){let r=n.split(yn.sep).pop()??"";if(hi.includes(r))return e.warn(`Skipping directory '${n}' because it is likely an artifact folder.`),[];let o=Wt.readdirSync(n),i=[];return o.forEach(s=>{let a=yn.join(n,s),l;try{l=Wt.statSync(a)}catch(c){e.warn({err:c},`Skipping path '${a}' because it could not be read.`);return}if(l.isDirectory())i=i.concat(hd(a,e,t));else if(s.endsWith(".yaml")){let c=Wt.readFileSync(a,"utf-8"),d=yn.relative(yn.resolve(t),yn.resolve(a));try{let p=Lr.parse(c),u=jt.parse(p);i.push({id:u.id,name:u.name,fullPathSegments:a.split(yn.sep),testPath:d,fileName:s,lastModified:l.mtime,createdAt:l.ctime})}catch{e.warn(`Skipping file '${a}' because it does not parse as a valid Momentic test.`)}}}),i}function Ta(n,e){let t=yn.join(e.rootDir,n);if(!t)throw new Error(`Could not find test with path ${n} in Momentic project (${e.rootDir})`);let r;try{r=Wt.readFileSync(t,"utf8"),r=r.replace(/\r\n|\r/g,`
2974
2974
  `)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=Lr.parse(r)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return jt.parse(o)}function gd(n,e,t){let r=t.project.rootDir,o;try{o=Wt.readFileSync(n,"utf-8")}catch(s){throw e.error({err:s,projectRoot:r},s.message),new Error(s.message)}let i=Lr.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${n} is missing steps`);return i}async function Ca(n,e,t){let r=gd(n,e,t),o;try{o=pn.parse(r)}catch(s){throw new Error(`Test ${n} is missing metadata or has invalid metadata: ${s}`)}let{resolvedTest:i}=await Dh({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:s,logger:a})=>{let l=t.modules[s]?.fullFilePath;if(l)return Ii(l,a)}}});return i}import SR from"@dotenvx/dotenvx";import wR from"fs";import ly from"path";function dy(n,e){return(n.config.environments??[]).map(t=>Li(t.name,n,e))}function cy(n){return n.includes("${")?n.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[r,o]=t.split(/:-|-/,2),i=process.env[r];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):n}function Li(n,e,t){let r=(e.config.environments??[]).find(s=>s.name===n);if(!r)throw new Error(`Environment ${n} not found in local project configuration file`);let o={[ve]:cy(r.baseUrl)};if(r.envVariables){let s={};for(let[a,l]of Object.entries(r.envVariables))if(typeof l=="string"){let c=cy(l);c&&(s[a]=c)}else{let c=l.fromFile,d;try{d=wR.readFileSync(ly.resolve(e.rootDir,c),"utf-8")}catch(p){throw new Error(`Failed to read environment variable '${a}' from file '${c}': ${p}`)}if(l.json)try{s[a]=JSON.parse(d)}catch(p){throw new Error(`Failed to parse environment variable '${a}' from file '${c}' as JSON: ${p}`)}else s[a]=d}Object.keys(s).length>0&&S.debug(s,"Set environment variables with interpolation from project configuration"),Object.assign(o,s)}if(r.envFile){let s={},a=SR.config({path:ly.resolve(e.rootDir,r.envFile),processEnv:s,logLevel:"error",quiet:!0});if(a.error)throw new Error(`Failed to load .env file: ${a.error.message}`);t.debug(s,"Set environment variables from .env file"),Object.assign(o,s)}return r.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:n,variables:o,browser:r.browser}}import{existsSync as JI,readFileSync as ZI,readdirSync as QI,writeFileSync as eP}from"fs";var Oy=KS(Ty(),1);var ki=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var IR={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Mi=n=>n.replace(/[[\]\\-]/g,"\\$&"),PR=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Cy=n=>n.join(""),Ey=(n,e)=>{let t=e;if(n.charAt(t)!=="[")throw new Error("not in a brace expression");let r=[],o=[],i=t+1,s=!1,a=!1,l=!1,c=!1,d=t,p="";e:for(;i<n.length;){let g=n.charAt(i);if((g==="!"||g==="^")&&i===t+1){c=!0,i++;continue}if(g==="]"&&s&&!l){d=i+1;break}if(s=!0,g==="\\"&&!l){l=!0,i++;continue}if(g==="["&&!l){for(let[f,[y,v,b]]of Object.entries(IR))if(n.startsWith(f,i)){if(p)return["$.",!1,n.length-t,!0];i+=f.length,b?o.push(y):r.push(y),a=a||v;continue e}}if(l=!1,p){g>p?r.push(Mi(p)+"-"+Mi(g)):g===p&&r.push(Mi(g)),p="",i++;continue}if(n.startsWith("-]",i+1)){r.push(Mi(g+"-")),i+=2;continue}if(n.startsWith("-",i+1)){p=g,i+=2;continue}r.push(Mi(g)),i++}if(d<i)return["",!1,0,!1];if(!r.length&&!o.length)return["$.",!1,n.length-t,!0];if(o.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!c){let g=r[0].length===2?r[0].slice(-1):r[0];return[PR(g),!1,d-t,!1]}let u="["+(c?"^":"")+Cy(r)+"]",m="["+(c?"":"^")+Cy(o)+"]";return[r.length&&o.length?"("+u+"|"+m+")":r.length?u:m,a,d-t,!0]};var rn=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var LR=new Set(["!","?","+","*","@"]),Ay=n=>LR.has(n),OR="(?!(?:^|/)\\.\\.?(?:$|/))",Ea="(?!\\.)",kR=new Set(["[","."]),MR=new Set(["..","."]),NR=new Set("().*{}+?[]^$\\!"),_R=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),bd="[^/]",Ry=bd+"*?",Iy=bd+"+?",fo=class n{type;#e;#t;#i=!1;#r=[];#s;#w;#c;#p=!1;#a;#l;#o=!1;constructor(e,t,r={}){this.type=e,e&&(this.#t=!0),this.#s=t,this.#e=this.#s?this.#s.#e:this,this.#a=this.#e===this?r:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#p&&this.#c.push(this),this.#w=this.#s?this.#s.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#r.map(e=>String(e)).join("|")+")":this.#l=this.#r.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#p)return this;this.toString(),this.#p=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,r=t.#s;for(;r;){for(let o=t.#w+1;!r.type&&o<r.#r.length;o++)for(let i of e.#r){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(r.#r[o])}t=r,r=t.#s}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof n&&t.#s===this))throw new Error("invalid part: "+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#r.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#p&&this.#s?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#s?.isStart())return!1;if(this.#w===0)return!0;let e=this.#s;for(let t=0;t<this.#w;t++){let r=e.#r[t];if(!(r instanceof n&&r.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#s?.type==="!")return!0;if(!this.#s?.isEnd())return!1;if(!this.type)return this.#s?.isEnd();let e=this.#s?this.#s.#r.length:0;return this.#w===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new n(this.type,e);for(let r of this.#r)t.copyIn(r);return t}static#y(e,t,r,o){let i=!1,s=!1,a=-1,l=!1;if(t.type===null){let m=r,h="";for(;m<e.length;){let g=e.charAt(m++);if(i||g==="\\"){i=!i,h+=g;continue}if(s){m===a+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(m===a+2&&l)&&(s=!1),h+=g;continue}else if(g==="["){s=!0,a=m,l=!1,h+=g;continue}if(!o.noext&&Ay(g)&&e.charAt(m)==="("){t.push(h),h="";let f=new n(g,t);m=n.#y(e,f,m,o),t.push(f);continue}h+=g}return t.push(h),m}let c=r+1,d=new n(null,t),p=[],u="";for(;c<e.length;){let m=e.charAt(c++);if(i||m==="\\"){i=!i,u+=m;continue}if(s){c===a+1?(m==="^"||m==="!")&&(l=!0):m==="]"&&!(c===a+2&&l)&&(s=!1),u+=m;continue}else if(m==="["){s=!0,a=c,l=!1,u+=m;continue}if(Ay(m)&&e.charAt(c)==="("){d.push(u),u="";let h=new n(m,d);d.push(h),c=n.#y(e,h,c,o);continue}if(m==="|"){d.push(u),u="",p.push(d),d=new n(null,t);continue}if(m===")")return u===""&&t.#r.length===0&&(t.#o=!0),d.push(u),u="",t.push(...p,d),c;u+=m}return t.type=null,t.#t=void 0,t.#r=[e.substring(r-1)],c}static fromGlob(e,t={}){let r=new n(null,void 0,t);return n.#y(e,r,0,t),r}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,r,o,i]=this.toRegExpSource();if(!(o||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let a=(this.#a.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#a}toRegExpSource(e){let t=e??!!this.#a.dot;if(this.#e===this&&this.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#r.map(m=>{let[h,g,f,y]=typeof m=="string"?n.#u(m,this.#t,l):m.toRegExpSource(e);return this.#t=this.#t||f,this.#i=this.#i||y,h}).join(""),d="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&MR.has(this.#r[0]))){let h=kR,g=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),f=!t&&!e&&h.has(c.charAt(0));d=g?OR:f?Ea:""}let p="";return this.isEnd()&&this.#e.#p&&this.#s?.type==="!"&&(p="(?:$|\\/)"),[d+c+p,rn(c),this.#t=!!this.#t,this.#i]}let r=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#m(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString();return this.#r=[l],this.type=null,this.#t=void 0,[l,rn(this.toString()),!1,!1]}let s=!r||e||t||!Ea?"":this.#m(!0);s===i&&(s=""),s&&(i=`(?:${i})(?:${s})*?`);let a="";if(this.type==="!"&&this.#o)a=(this.isStart()&&!t?Ea:"")+Iy;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?Ea:"")+Ry+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=o+i+l}return[a,rn(i),this.#t=!!this.#t,this.#i]}#m(e){return this.#r.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[r,o,i,s]=t.toRegExpSource(e);return this.#i=this.#i||s,r}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#u(e,t,r=!1){let o=!1,i="",s=!1;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(o){o=!1,i+=(NR.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?i+="\\\\":o=!0;continue}if(l==="["){let[c,d,p,u]=Ey(e,a);if(p){i+=c,s=s||d,a+=p-1,t=t||u;continue}}if(l==="*"){r&&e==="*"?i+=Iy:i+=Ry,t=!0;continue}if(l==="?"){i+=bd,t=!0;continue}i+=_R(l)}return[i,rn(e),!!t,s]}};var yo=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var ft=(n,e,t={})=>(ki(e),!t.nocomment&&e.charAt(0)==="#"?!1:new kt(e,t).match(n)),FR=/^\*+([^+@!?\*\[\(]*)$/,DR=n=>e=>!e.startsWith(".")&&e.endsWith(n),UR=n=>e=>e.endsWith(n),zR=n=>(n=n.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(n)),BR=n=>(n=n.toLowerCase(),e=>e.toLowerCase().endsWith(n)),jR=/^\*+\.\*+$/,$R=n=>!n.startsWith(".")&&n.includes("."),HR=n=>n!=="."&&n!==".."&&n.includes("."),WR=/^\.\*+$/,GR=n=>n!=="."&&n!==".."&&n.startsWith("."),VR=/^\*+$/,qR=n=>n.length!==0&&!n.startsWith("."),KR=n=>n.length!==0&&n!=="."&&n!=="..",YR=/^\?+([^+@!?\*\[\(]*)?$/,XR=([n,e=""])=>{let t=ky([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},JR=([n,e=""])=>{let t=My([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},ZR=([n,e=""])=>{let t=My([n]);return e?r=>t(r)&&r.endsWith(e):t},QR=([n,e=""])=>{let t=ky([n]);return e?r=>t(r)&&r.endsWith(e):t},ky=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},My=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},Ny=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Py={win32:{sep:"\\"},posix:{sep:"/"}},eI=Ny==="win32"?Py.win32.sep:Py.posix.sep;ft.sep=eI;var ot=Symbol("globstar **");ft.GLOBSTAR=ot;var tI="[^/]",nI=tI+"*?",rI="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",oI="(?:(?!(?:\\/|^)\\.).)*?",iI=(n,e={})=>t=>ft(t,n,e);ft.filter=iI;var Gt=(n,e={})=>Object.assign({},n,e),sI=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return ft;let e=ft;return Object.assign((r,o,i={})=>e(r,o,Gt(n,i)),{Minimatch:class extends e.Minimatch{constructor(o,i={}){super(o,Gt(n,i))}static defaults(o){return e.defaults(Gt(n,o)).Minimatch}},AST:class extends e.AST{constructor(o,i,s={}){super(o,i,Gt(n,s))}static fromGlob(o,i={}){return e.AST.fromGlob(o,Gt(n,i))}},unescape:(r,o={})=>e.unescape(r,Gt(n,o)),escape:(r,o={})=>e.escape(r,Gt(n,o)),filter:(r,o={})=>e.filter(r,Gt(n,o)),defaults:r=>e.defaults(Gt(n,r)),makeRe:(r,o={})=>e.makeRe(r,Gt(n,o)),braceExpand:(r,o={})=>e.braceExpand(r,Gt(n,o)),match:(r,o,i={})=>e.match(r,o,Gt(n,i)),sep:e.sep,GLOBSTAR:ot})};ft.defaults=sI;var _y=(n,e={})=>(ki(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,Oy.default)(n));ft.braceExpand=_y;var aI=(n,e={})=>new kt(n,e).makeRe();ft.makeRe=aI;var lI=(n,e,t={})=>{let r=new kt(e,t);return n=n.filter(o=>r.match(o)),r.options.nonull&&!n.length&&n.push(e),n};ft.match=lI;var Ly=/[?*]|[+@!]\(.*?\)|\[|\]/,cI=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),kt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){ki(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Ny,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let o=this.globParts.map((i,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!Ly.test(i[2]))&&!Ly.test(i[3]),c=/^[a-z]:/i.test(i[0]);if(l)return[...i.slice(0,4),...i.slice(4).map(d=>this.parse(d))];if(c)return[i[0],...i.slice(1).map(d=>this.parse(d))]}return i.map(l=>this.parse(l))});if(this.debug(this.pattern,o),this.set=o.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let s=this.set[i];s[0]===""&&s[1]===""&&this.globParts[i][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let o=0;o<e[r].length;o++)e[r][o]==="**"&&(e[r][o]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let r=-1;for(;(r=t.indexOf("**",r+1))!==-1;){let o=r;for(;t[o+1]==="**";)o++;o!==r&&t.splice(r,o-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((r,o)=>{let i=r[r.length-1];return o==="**"&&i==="**"?r:o===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(o),r)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let i=e[o];o===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let o=e[r-1];o&&o!=="."&&o!==".."&&o!=="**"&&(t=!0,e.splice(r-1,2),r-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let r of e){let o=-1;for(;(o=r.indexOf("**",o+1))!==-1;){let s=o;for(;r[s+1]==="**";)s++;s>o&&r.splice(o+1,s-o);let a=r[o+1],l=r[o+2],c=r[o+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=!0,r.splice(o,1);let d=r.slice(0);d[o]="**",e.push(d),o--}if(!this.preserveMultipleSlashes){for(let s=1;s<r.length-1;s++){let a=r[s];s===1&&a===""&&r[0]===""||(a==="."||a==="")&&(t=!0,r.splice(s,1),s--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let s=r[i-1];if(s&&s!=="."&&s!==".."&&s!=="**"){t=!0;let l=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...l),r.length===0&&r.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let r=t+1;r<e.length;r++){let o=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(o){e[t]=[],e[r]=o;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let o=0,i=0,s=[],a="";for(;o<e.length&&i<t.length;)if(e[o]===t[i])s.push(a==="b"?t[i]:e[o]),o++,i++;else if(r&&e[o]==="**"&&t[i]===e[o+1])s.push(e[o]),o++;else if(r&&t[i]==="**"&&e[o]===t[i+1])s.push(t[i]),i++;else if(e[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="b")return!1;a="a",s.push(e[o]),o++,i++}else if(t[i]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(a==="a")return!1;a="b",s.push(t[i]),o++,i++}else return!1;return e.length===t.length&&s}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let o=this.options;if(this.isWindows){let g=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),f=!g&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),y=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),v=!y&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),b=f?3:g?0:void 0,E=v?3:y?0:void 0;if(typeof b=="number"&&typeof E=="number"){let[x,C]=[e[b],t[E]];x.toLowerCase()===C.toLowerCase()&&(t[E]=x,E>b?t=t.slice(E):b>E&&(e=e.slice(b)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var s=0,a=0,l=e.length,c=t.length;s<l&&a<c;s++,a++){this.debug("matchOne loop");var d=t[a],p=e[s];if(this.debug(t,d,p),d===!1)return!1;if(d===ot){this.debug("GLOBSTAR",[t,d,p]);var u=s,m=a+1;if(m===c){for(this.debug("** at the end");s<l;s++)if(e[s]==="."||e[s]===".."||!o.dot&&e[s].charAt(0)===".")return!1;return!0}for(;u<l;){var h=e[u];if(this.debug(`
2975
2975
  globstar while`,e,u,t,m,h),this.matchOne(e.slice(u),t.slice(m),r))return this.debug("globstar found match!",u,l,h),!0;if(h==="."||h===".."||!o.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,u,t,m);break}this.debug("globstar swallow a segment, and continue"),u++}return!!(r&&(this.debug(`
2976
- >>> no match, partial?`,e,u,t,m),u===l))}let g;if(typeof d=="string"?(g=p===d,this.debug("string match",d,p,g)):(g=d.test(p),this.debug("pattern match",d,p,g)),!g)return!1}if(s===l&&a===c)return!0;if(s===l)return r;if(a===c)return s===l-1&&e[s]==="";throw new Error("wtf?")}braceExpand(){return _y(this.pattern,this.options)}parse(e){ki(e);let t=this.options;if(e==="**")return ot;if(e==="")return"";let r,o=null;(r=e.match(VR))?o=t.dot?KR:qR:(r=e.match(FR))?o=(t.nocase?t.dot?BR:zR:t.dot?UR:DR)(r[1]):(r=e.match(YR))?o=(t.nocase?t.dot?JR:XR:t.dot?ZR:QR)(r):(r=e.match(jR))?o=t.dot?HR:$R:(r=e.match(WR))&&(o=GR);let i=fo.fromGlob(e,this.options).toMMPattern();return o&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:o}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?nI:t.dot?rI:oI,o=new Set(t.nocase?["i"]:[]),i=e.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let p of d.flags.split(""))o.add(p);return typeof d=="string"?cI(d):d===ot?ot:d._src});return c.forEach((d,p)=>{let u=c[p+1],m=c[p-1];d!==ot||m===ot||(m===void 0?u!==void 0&&u!==ot?c[p+1]="(?:\\/|"+r+"\\/)?"+u:c[p]=r:u===void 0?c[p-1]=m+"(?:\\/|"+r+")?":u!==ot&&(c[p-1]=m+"(?:\\/|\\/"+r+"\\/)"+u,c[p+1]=ot))}),c.filter(d=>d!==ot).join("/")}).join("|"),[s,a]=e.length>1?["(?:",")"]:["",""];i="^"+s+i+a+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let i=this.set;this.debug(this.pattern,"set",i);let s=o[o.length-1];if(!s)for(let a=o.length-2;!s&&a>=0;a--)s=o[a];for(let a=0;a<i.length;a++){let l=i[a],c=o;if(r.matchBase&&l.length===1&&(c=[s]),this.matchOne(c,l,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return ft.defaults(e).Minimatch}};ft.AST=fo;ft.Minimatch=kt;ft.escape=yo;ft.unescape=rn;import{fileURLToPath as jI}from"node:url";var bo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Dy=new Set,Sd=typeof process=="object"&&process?process:{},Uy=(n,e,t,r)=>{typeof Sd.emitWarning=="function"?Sd.emitWarning(n,e,t,r):console.error(`[${t}] ${e}: ${n}`)},Aa=globalThis.AbortController,Fy=globalThis.AbortSignal;if(typeof Aa>"u"){Fy=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},Aa=class{constructor(){e()}signal=new Fy;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}}};let n=Sd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,Uy("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var dI=n=>!Dy.has(n),W7=Symbol("type"),Vn=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),zy=n=>Vn(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?So:null:null,So=class extends Array{constructor(e){super(e),this.fill(0)}},wd=class n{heap;length;static#e=!1;static create(e){let t=zy(e);if(!t)return[];n.#e=!0;let r=new n(e,t);return n.#e=!1,r}constructor(e,t){if(!n.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Ni=class n{#e;#t;#i;#r;#s;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#p;#a;#l;#o;#f;#y;#m;#u;#T;#g;#C;#E;#S;#v;#x;#h;static unsafeExposeInternals(e){return{starts:e.#E,ttls:e.#S,sizes:e.#C,keyMap:e.#a,keyList:e.#l,valList:e.#o,next:e.#f,prev:e.#y,get head(){return e.#m},get tail(){return e.#u},free:e.#T,isBackgroundFetch:t=>e.#d(t),backgroundFetch:(t,r,o,i)=>e.#U(t,r,o,i),moveToTail:t=>e.#B(t),indexes:t=>e.#R(t),rindexes:t=>e.#I(t),isStale:t=>e.#b(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#p}get size(){return this.#c}get fetchMethod(){return this.#s}get memoMethod(){return this.#w}get dispose(){return this.#i}get disposeAfter(){return this.#r}constructor(e){let{max:t=0,ttl:r,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:d,noDisposeOnSet:p,noUpdateTTL:u,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:f,memoMethod:y,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:x,ignoreFetchAbort:C}=e;if(t!==0&&!Vn(t))throw new TypeError("max option must be a nonnegative integer");let L=t?zy(t):Array;if(!L)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=y,f!==void 0&&typeof f!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#s=f,this.#x=!!f,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#f=new L(t),this.#y=new L(t),this.#m=0,this.#u=0,this.#T=wd.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof d=="function"?(this.#r=d,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#v=!!this.#i,this.#h=!!this.#r,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!x,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(this.#t!==0&&!Vn(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!Vn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Vn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!Vn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let N="LRU_CACHE_UNBOUNDED";dI(N)&&(Dy.add(N),Uy("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",N,n))}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#P(){let e=new So(this.#e),t=new So(this.#e);this.#S=e,this.#E=t,this.#k=(i,s,a=bo.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#b(i)&&this.#O(this.#l[i],"expire")},s+1);l.unref&&l.unref()}},this.#A=i=>{t[i]=e[i]!==0?bo.now():0},this.#n=(i,s)=>{if(e[s]){let a=e[s],l=t[s];if(!a||!l)return;i.ttl=a,i.start=l,i.now=r||o();let c=i.now-l;i.remainingTTL=a-c}};let r=0,o=()=>{let i=bo.now();if(this.ttlResolution>0){r=i;let s=setTimeout(()=>r=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#a.get(i);if(s===void 0)return 0;let a=e[s],l=t[s];if(!a||!l)return 1/0;let c=(r||o())-l;return a-c},this.#b=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(r||o())-s>a}}#A=()=>{};#n=()=>{};#k=()=>{};#b=()=>!1;#L(){let e=new So(this.#e);this.#p=0,this.#C=e,this.#M=t=>{this.#p-=e[t],e[t]=0},this.#_=(t,r,o,i)=>{if(this.#d(r))return 0;if(!Vn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(r,t),!Vn(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(t,r,o)=>{if(e[t]=r,this.#t){let i=this.#t-e[t];for(;this.#p>i;)this.#D(!0)}this.#p+=e[t],o&&(o.entrySize=r,o.totalCalculatedSize=this.#p)}}#M=e=>{};#N=(e,t,r)=>{};#_=(e,t,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#u;!(!this.#F(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#F(t)||((e||!this.#b(t))&&(yield t),t===this.#u));)t=this.#f[t]}#F(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#R())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*rentries(){for(let e of this.#I())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*keys(){for(let e of this.#R()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*rkeys(){for(let e of this.#I()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*values(){for(let e of this.#R())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}*rvalues(){for(let e of this.#I())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let r of this.#R()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#l[r],this))return this.get(this.#l[r],t)}}forEach(e,t=this){for(let r of this.#R()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[r],this)}}rforEach(e,t=this){for(let r of this.#I()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[r],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#b(t)&&(this.#O(this.#l[t],"expire"),e=!0);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let r=this.#o[t],o=this.#d(r)?r.__staleWhileFetching:r;if(o===void 0)return;let i={value:o};if(this.#S&&this.#E){let s=this.#S[t],a=this.#E[t];if(s&&a){let l=s-(bo.now()-a);i.ttl=l,i.start=Date.now()}}return this.#C&&(i.size=this.#C[t]),i}dump(){let e=[];for(let t of this.#R({allowStale:!0})){let r=this.#l[t],o=this.#o[t],i=this.#d(o)?o.__staleWhileFetching:o;if(i===void 0||r===void 0)continue;let s={value:i};if(this.#S&&this.#E){s.ttl=this.#S[t];let a=bo.now()-this.#E[t];s.start=Math.floor(Date.now()-a)}this.#C&&(s.size=this.#C[t]),e.unshift([r,s])}return e}load(e){this.clear();for(let[t,r]of e){if(r.start){let o=Date.now()-r.start;r.start=bo.now()-o}this.set(t,r.value,r)}}set(e,t,r={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,d=this.#_(e,t,r.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#O(e,"set"),this;let p=this.#c===0?void 0:this.#a.get(e);if(p===void 0)p=this.#c===0?this.#u:this.#T.length!==0?this.#T.pop():this.#c===this.#e?this.#D(!1):this.#c,this.#l[p]=e,this.#o[p]=t,this.#a.set(e,p),this.#f[this.#u]=p,this.#y[p]=this.#u,this.#u=p,this.#c++,this.#N(p,d,l),l&&(l.set="add"),c=!1;else{this.#B(p);let u=this.#o[p];if(t!==u){if(this.#x&&this.#d(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=u;m!==void 0&&!s&&(this.#v&&this.#i?.(m,e,"set"),this.#h&&this.#g?.push([m,e,"set"]))}else s||(this.#v&&this.#i?.(u,e,"set"),this.#h&&this.#g?.push([u,e,"set"]));if(this.#M(p),this.#N(p,d,l),this.#o[p]=t,l){l.set="replace";let m=u&&this.#d(u)?u.__staleWhileFetching:u;m!==void 0&&(l.oldValue=m)}}else l&&(l.set="update")}if(o!==0&&!this.#S&&this.#P(),this.#S&&(c||this.#k(p,o,i),l&&this.#n(l,p)),!s&&this.#h&&this.#g){let u=this.#g,m;for(;m=u?.shift();)this.#r?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#m];if(this.#D(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#D(e){let t=this.#m,r=this.#l[t],o=this.#o[t];return this.#x&&this.#d(o)?o.__abortController.abort(new Error("evicted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(o,r,"evict"),this.#h&&this.#g?.push([o,r,"evict"])),this.#M(t),e&&(this.#l[t]=void 0,this.#o[t]=void 0,this.#T.push(t)),this.#c===1?(this.#m=this.#u=0,this.#T.length=0):this.#m=this.#f[t],this.#a.delete(r),this.#c--,t}has(e,t={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=t,i=this.#a.get(e);if(i!==void 0){let s=this.#o[i];if(this.#d(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#b(i))o&&(o.has="stale",this.#n(o,i));else return r&&this.#A(i),o&&(o.has="hit",this.#n(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:r=this.allowStale}=t,o=this.#a.get(e);if(o===void 0||!r&&this.#b(o))return;let i=this.#o[o];return this.#d(i)?i.__staleWhileFetching:i}#U(e,t,r,o){let i=t===void 0?void 0:this.#o[t];if(this.#d(i))return i;let s=new Aa,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let l={signal:s.signal,options:r,context:o},c=(g,f=!1)=>{let{aborted:y}=s.signal,v=r.ignoreFetchAbort&&g!==void 0;if(r.status&&(y&&!f?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,v&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),y&&!v&&!f)return p(s.signal.reason);let b=m;return this.#o[t]===m&&(g===void 0?b.__staleWhileFetching?this.#o[t]=b.__staleWhileFetching:this.#O(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,g,l.options))),g},d=g=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=g),p(g)),p=g=>{let{aborted:f}=s.signal,y=f&&r.allowStaleOnFetchAbort,v=y||r.allowStaleOnFetchRejection,b=v||r.noDeleteOnFetchRejection,E=m;if(this.#o[t]===m&&(!b||E.__staleWhileFetching===void 0?this.#O(e,"fetch"):y||(this.#o[t]=E.__staleWhileFetching)),v)return r.status&&E.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw g},u=(g,f)=>{let y=this.#s?.(e,i,l);y&&y instanceof Promise&&y.then(v=>g(v===void 0?void 0:v),f),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(g(void 0),r.allowStaleOnFetchAbort&&(g=v=>c(v,!0)))})};r.status&&(r.status.fetchDispatched=!0);let m=new Promise(u).then(c,d),h=Object.assign(m,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#a.get(e)):this.#o[t]=h,h}#d(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Aa}async fetch(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:g,forceRefresh:f=!1,status:y,signal:v}=t;if(!this.#x)return y&&(y.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:y});let b={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:d,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:h,ignoreFetchAbort:m,status:y,signal:v},E=this.#a.get(e);if(E===void 0){y&&(y.fetch="miss");let x=this.#U(e,E,b,g);return x.__returned=x}else{let x=this.#o[E];if(this.#d(x)){let U=r&&x.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",U&&(y.returnedStale=!0)),U?x.__staleWhileFetching:x.__returned=x}let C=this.#b(E);if(!f&&!C)return y&&(y.fetch="hit"),this.#B(E),o&&this.#A(E),y&&this.#n(y,E),x;let L=this.#U(e,E,b,g),P=L.__staleWhileFetching!==void 0&&r;return y&&(y.fetch=C?"stale":"refresh",P&&C&&(y.returnedStale=!0)),P?L.__staleWhileFetching:L.__returned=L}}async forceFetch(e,t={}){let r=await this.fetch(e,t);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,t={}){let r=this.#w;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=t,a=this.get(e,s);if(!i&&a!==void 0)return a;let l=r(e,a,{options:s,context:o});return this.set(e,l,s),l}get(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#o[a],c=this.#d(l);return s&&this.#n(s,a),this.#b(a)?(s&&(s.get="stale"),c?(s&&r&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),r?l.__staleWhileFetching:void 0):(i||this.#O(e,"expire"),s&&r&&(s.returnedStale=!0),r?l:void 0)):(s&&(s.get="hit"),c?l.__staleWhileFetching:(this.#B(a),o&&this.#A(a),l))}else s&&(s.get="miss")}#z(e,t){this.#y[t]=e,this.#f[e]=t}#B(e){e!==this.#u&&(e===this.#m?this.#m=this.#f[e]:this.#z(this.#y[e],this.#f[e]),this.#z(this.#u,e),this.#u=e)}delete(e){return this.#O(e,"delete")}#O(e,t){let r=!1;if(this.#c!==0){let o=this.#a.get(e);if(o!==void 0)if(r=!0,this.#c===1)this.#j(t);else{this.#M(o);let i=this.#o[o];if(this.#d(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(i,e,t),this.#h&&this.#g?.push([i,e,t])),this.#a.delete(e),this.#l[o]=void 0,this.#o[o]=void 0,o===this.#u)this.#u=this.#y[o];else if(o===this.#m)this.#m=this.#f[o];else{let s=this.#y[o];this.#f[s]=this.#f[o];let a=this.#f[o];this.#y[a]=this.#y[o]}this.#c--,this.#T.push(o)}}if(this.#h&&this.#g?.length){let o=this.#g,i;for(;i=o?.shift();)this.#r?.(...i)}return r}clear(){return this.#j("delete")}#j(e){for(let t of this.#I({allowStale:!0})){let r=this.#o[t];if(this.#d(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#l[t];this.#v&&this.#i?.(r,o,e),this.#h&&this.#g?.push([r,o,e])}}if(this.#a.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#S&&this.#E&&(this.#S.fill(0),this.#E.fill(0)),this.#C&&this.#C.fill(0),this.#m=0,this.#u=0,this.#T.length=0,this.#p=0,this.#c=0,this.#h&&this.#g){let t=this.#g,r;for(;r=t?.shift();)this.#r?.(...r)}}};import{posix as vI,win32 as Ld}from"node:path";import{fileURLToPath as xI}from"node:url";import{lstatSync as TI,readdir as CI,readdirSync as EI,readlinkSync as AI,realpathSync as RI}from"fs";import*as II from"node:fs";import{lstat as LI,readdir as OI,readlink as kI,realpath as MI}from"node:fs/promises";import{EventEmitter as Rd}from"node:events";import Wy from"node:stream";import{StringDecoder as pI}from"node:string_decoder";var By=typeof process=="object"&&process?process:{stdout:null,stderr:null},uI=n=>!!n&&typeof n=="object"&&(n instanceof Kn||n instanceof Wy||mI(n)||hI(n)),mI=n=>!!n&&typeof n=="object"&&n instanceof Rd&&typeof n.pipe=="function"&&n.pipe!==Wy.Writable.prototype.pipe,hI=n=>!!n&&typeof n=="object"&&n instanceof Rd&&typeof n.write=="function"&&typeof n.end=="function",Ln=Symbol("EOF"),On=Symbol("maybeEmitEnd"),qn=Symbol("emittedEnd"),Ra=Symbol("emittingEnd"),_i=Symbol("emittedError"),Ia=Symbol("closed"),jy=Symbol("read"),Pa=Symbol("flush"),$y=Symbol("flushChunk"),on=Symbol("encoding"),wo=Symbol("decoder"),Ye=Symbol("flowing"),Fi=Symbol("paused"),vo=Symbol("resume"),Xe=Symbol("buffer"),yt=Symbol("pipes"),Je=Symbol("bufferLength"),vd=Symbol("bufferPush"),La=Symbol("bufferShift"),pt=Symbol("objectMode"),_e=Symbol("destroyed"),xd=Symbol("error"),Td=Symbol("emitData"),Hy=Symbol("emitEnd"),Cd=Symbol("emitEnd2"),bn=Symbol("async"),Ed=Symbol("abort"),Oa=Symbol("aborted"),Di=Symbol("signal"),Or=Symbol("dataListeners"),Mt=Symbol("discarded"),Ui=n=>Promise.resolve().then(n),gI=n=>n(),fI=n=>n==="end"||n==="finish"||n==="prefinish",yI=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,bI=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),ka=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[vo](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ad=class extends ka{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=o=>t.emit("error",o),e.on("error",this.proxyErrors)}},SI=n=>!!n.objectMode,wI=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",Kn=class extends Rd{[Ye]=!1;[Fi]=!1;[yt]=[];[Xe]=[];[pt];[on];[bn];[wo];[Ln]=!1;[qn]=!1;[Ra]=!1;[Ia]=!1;[_i]=null;[Je]=0;[_e]=!1;[Di];[Oa]=!1;[Or]=0;[Mt]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");SI(t)?(this[pt]=!0,this[on]=null):wI(t)?(this[on]=t.encoding,this[pt]=!1):(this[pt]=!1,this[on]=null),this[bn]=!!t.async,this[wo]=this[on]?new pI(this[on]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Xe]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[yt]});let{signal:r}=t;r&&(this[Di]=r,r.aborted?this[Ed]():r.addEventListener("abort",()=>this[Ed]()))}get bufferLength(){return this[Je]}get encoding(){return this[on]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[pt]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[bn]}set async(e){this[bn]=this[bn]||!!e}[Ed](){this[Oa]=!0,this.emit("abort",this[Di]?.reason),this.destroy(this[Di]?.reason)}get aborted(){return this[Oa]}set aborted(e){}write(e,t,r){if(this[Oa])return!1;if(this[Ln])throw new Error("write after end");if(this[_e])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let o=this[bn]?Ui:gI;if(!this[pt]&&!Buffer.isBuffer(e)){if(bI(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(yI(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[pt]?(this[Ye]&&this[Je]!==0&&this[Pa](!0),this[Ye]?this.emit("data",e):this[vd](e),this[Je]!==0&&this.emit("readable"),r&&o(r),this[Ye]):e.length?(typeof e=="string"&&!(t===this[on]&&!this[wo]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[on]&&(e=this[wo].write(e)),this[Ye]&&this[Je]!==0&&this[Pa](!0),this[Ye]?this.emit("data",e):this[vd](e),this[Je]!==0&&this.emit("readable"),r&&o(r),this[Ye]):(this[Je]!==0&&this.emit("readable"),r&&o(r),this[Ye])}read(e){if(this[_e])return null;if(this[Mt]=!1,this[Je]===0||e===0||e&&e>this[Je])return this[On](),null;this[pt]&&(e=null),this[Xe].length>1&&!this[pt]&&(this[Xe]=[this[on]?this[Xe].join(""):Buffer.concat(this[Xe],this[Je])]);let t=this[jy](e||null,this[Xe][0]);return this[On](),t}[jy](e,t){if(this[pt])this[La]();else{let r=t;e===r.length||e===null?this[La]():typeof r=="string"?(this[Xe][0]=r.slice(e),t=r.slice(0,e),this[Je]-=e):(this[Xe][0]=r.subarray(e),t=r.subarray(0,e),this[Je]-=e)}return this.emit("data",t),!this[Xe].length&&!this[Ln]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[Ln]=!0,this.writable=!1,(this[Ye]||!this[Fi])&&this[On](),this}[vo](){this[_e]||(!this[Or]&&!this[yt].length&&(this[Mt]=!0),this[Fi]=!1,this[Ye]=!0,this.emit("resume"),this[Xe].length?this[Pa]():this[Ln]?this[On]():this.emit("drain"))}resume(){return this[vo]()}pause(){this[Ye]=!1,this[Fi]=!0,this[Mt]=!1}get destroyed(){return this[_e]}get flowing(){return this[Ye]}get paused(){return this[Fi]}[vd](e){this[pt]?this[Je]+=1:this[Je]+=e.length,this[Xe].push(e)}[La](){return this[pt]?this[Je]-=1:this[Je]-=this[Xe][0].length,this[Xe].shift()}[Pa](e=!1){do;while(this[$y](this[La]())&&this[Xe].length);!e&&!this[Xe].length&&!this[Ln]&&this.emit("drain")}[$y](e){return this.emit("data",e),this[Ye]}pipe(e,t){if(this[_e])return e;this[Mt]=!1;let r=this[qn];return t=t||{},e===By.stdout||e===By.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[yt].push(t.proxyErrors?new Ad(this,e,t):new ka(this,e,t)),this[bn]?Ui(()=>this[vo]()):this[vo]()),e}unpipe(e){let t=this[yt].find(r=>r.dest===e);t&&(this[yt].length===1?(this[Ye]&&this[Or]===0&&(this[Ye]=!1),this[yt]=[]):this[yt].splice(this[yt].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[Mt]=!1,this[Or]++,!this[yt].length&&!this[Ye]&&this[vo]();else if(e==="readable"&&this[Je]!==0)super.emit("readable");else if(fI(e)&&this[qn])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[_i]){let o=t;this[bn]?Ui(()=>o.call(this,this[_i])):o.call(this,this[_i])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[Or]=this.listeners("data").length,this[Or]===0&&!this[Mt]&&!this[yt].length&&(this[Ye]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Or]=0,!this[Mt]&&!this[yt].length&&(this[Ye]=!1)),t}get emittedEnd(){return this[qn]}[On](){!this[Ra]&&!this[qn]&&!this[_e]&&this[Xe].length===0&&this[Ln]&&(this[Ra]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ia]&&this.emit("close"),this[Ra]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==_e&&this[_e])return!1;if(e==="data")return!this[pt]&&!r?!1:this[bn]?(Ui(()=>this[Td](r)),!0):this[Td](r);if(e==="end")return this[Hy]();if(e==="close"){if(this[Ia]=!0,!this[qn]&&!this[_e])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[_i]=r,super.emit(xd,r);let i=!this[Di]||this.listeners("error").length?super.emit("error",r):!1;return this[On](),i}else if(e==="resume"){let i=super.emit("resume");return this[On](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let o=super.emit(e,...t);return this[On](),o}[Td](e){for(let r of this[yt])r.dest.write(e)===!1&&this.pause();let t=this[Mt]?!1:super.emit("data",e);return this[On](),t}[Hy](){return this[qn]?!1:(this[qn]=!0,this.readable=!1,this[bn]?(Ui(()=>this[Cd]()),!0):this[Cd]())}[Cd](){if(this[wo]){let t=this[wo].end();if(t){for(let r of this[yt])r.dest.write(t);this[Mt]||super.emit("data",t)}}for(let t of this[yt])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[pt]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[pt]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[pt])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[on]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(_e,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Mt]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let o=this.read();if(o!==null)return Promise.resolve({done:!1,value:o});if(this[Ln])return t();let i,s,a=p=>{this.off("data",l),this.off("end",c),this.off(_e,d),t(),s(p)},l=p=>{this.off("error",a),this.off("end",c),this.off(_e,d),this.pause(),i({value:p,done:!!this[Ln]})},c=()=>{this.off("error",a),this.off("data",l),this.off(_e,d),t(),i({done:!0,value:void 0})},d=()=>a(new Error("stream destroyed"));return new Promise((p,u)=>{s=u,i=p,this.once(_e,d),this.once("error",a),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Mt]=!1;let e=!1,t=()=>(this.pause(),this.off(xd,t),this.off(_e,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let o=this.read();return o===null?t():{done:!1,value:o}};return this.once("end",t),this.once(xd,t),this.once(_e,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[_e])return e?this.emit("error",e):this.emit(_e),this;this[_e]=!0,this[Mt]=!0,this[Xe].length=0,this[Je]=0;let t=this;return typeof t.close=="function"&&!this[Ia]&&t.close(),e?this.emit("error",e):this.emit(_e),this}static get isStream(){return uI}};var PI=RI.native,Bi={lstatSync:TI,readdir:CI,readdirSync:EI,readlinkSync:AI,realpathSync:PI,promises:{lstat:LI,readdir:OI,readlink:kI,realpath:MI}},Yy=n=>!n||n===Bi||n===II?Bi:{...Bi,...n,promises:{...Bi.promises,...n.promises||{}}},Xy=/^\\\\\?\\([a-z]:)\\?$/i,NI=n=>n.replace(/\//g,"\\").replace(Xy,"$1\\"),_I=/[\\\/]/,qt=0,Jy=1,Zy=2,Sn=4,Qy=6,eb=8,kr=10,tb=12,Vt=15,zi=~Vt,Id=16,Gy=32,ji=64,sn=128,Ma=256,_a=512,Vy=ji|sn|_a,FI=1023,Pd=n=>n.isFile()?eb:n.isDirectory()?Sn:n.isSymbolicLink()?kr:n.isCharacterDevice()?Zy:n.isBlockDevice()?Qy:n.isSocket()?tb:n.isFIFO()?Jy:qt,qy=new Map,$i=n=>{let e=qy.get(n);if(e)return e;let t=n.normalize("NFKD");return qy.set(n,t),t},Ky=new Map,Na=n=>{let e=Ky.get(n);if(e)return e;let t=$i(n.toLowerCase());return Ky.set(n,t),t},Fa=class extends Ni{constructor(){super({max:256})}},Od=class extends Ni{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},nb=Symbol("PathScurry setAsCwd"),ut=class{name;root;roots;parent;nocase;isCWD=!1;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#r;get nlink(){return this.#r}#s;get uid(){return this.#s}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#p;get blksize(){return this.#p}#a;get ino(){return this.#a}#l;get size(){return this.#l}#o;get blocks(){return this.#o}#f;get atimeMs(){return this.#f}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#u;get birthtimeMs(){return this.#u}#T;get atime(){return this.#T}#g;get mtime(){return this.#g}#C;get ctime(){return this.#C}#E;get birthtime(){return this.#E}#S;#v;#x;#h;#P;#A;#n;#k;#b;#L;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=qt,r,o,i,s,a){this.name=e,this.#S=i?Na(e):$i(e),this.#n=t&FI,this.nocase=i,this.roots=o,this.root=r||this,this.#k=s,this.#x=a.fullpath,this.#P=a.relative,this.#A=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=Yy(a.fs)}depth(){return this.#v!==void 0?this.#v:this.parent?this.#v=this.parent.depth()+1:this.#v=0}childrenCache(){return this.#k}resolve(e){if(!e)return this;let t=this.getRootString(e),o=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#M(o):this.#M(o)}#M(e){let t=this;for(let r of e)t=t.child(r);return t}children(){let e=this.#k.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#k.set(this,t),this.#n&=~Id,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),o=this.nocase?Na(e):$i(e);for(let l of r)if(l.#S===o)return l;let i=this.parent?this.sep:"",s=this.#x?this.#x+i+e:void 0,a=this.newChild(e,qt,{...t,parent:this,fullpath:s});return this.canReaddir()||(a.#n|=sn),r.push(a),a}relative(){if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let e=this.name,t=this.parent;if(!t)return this.#P=this.name;let r=t.relative();return r+(!r||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#A!==void 0)return this.#A;let e=this.name,t=this.parent;if(!t)return this.#A=this.fullpathPosix();let r=t.relativePosix();return r+(!r||!t.parent?"":"/")+e}fullpath(){if(this.#x!==void 0)return this.#x;let e=this.name,t=this.parent;if(!t)return this.#x=this.name;let o=t.fullpath()+(t.parent?this.sep:"")+e;return this.#x=o}fullpathPosix(){if(this.#h!==void 0)return this.#h;if(this.sep==="/")return this.#h=this.fullpath();if(!this.parent){let o=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(o)?this.#h=`//?/${o}`:this.#h=o}let e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#h=r}isUnknown(){return(this.#n&Vt)===qt}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#n&Vt)===eb}isDirectory(){return(this.#n&Vt)===Sn}isCharacterDevice(){return(this.#n&Vt)===Zy}isBlockDevice(){return(this.#n&Vt)===Qy}isFIFO(){return(this.#n&Vt)===Jy}isSocket(){return(this.#n&Vt)===tb}isSymbolicLink(){return(this.#n&kr)===kr}lstatCached(){return this.#n&Gy?this:void 0}readlinkCached(){return this.#b}realpathCached(){return this.#L}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#b)return!0;if(!this.parent)return!1;let e=this.#n&Vt;return!(e!==qt&&e!==kr||this.#n&Ma||this.#n&sn)}calledReaddir(){return!!(this.#n&Id)}isENOENT(){return!!(this.#n&sn)}isNamed(e){return this.nocase?this.#S===Na(e):this.#S===$i(e)}async readlink(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(t);if(r)return this.#b=r}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(t);if(r)return this.#b=r}catch(t){this.#d(t.code);return}}#N(e){this.#n|=Id;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#_()}}#_(){this.#n&sn||(this.#n=(this.#n|sn)&zi,this.#R())}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#_()}#I(){this.#n|=_a,this.#F()}#F(){if(this.#n&ji)return;let e=this.#n;(e&Vt)===Sn&&(e&=zi),this.#n=e|ji,this.#R()}#D(e=""){e==="ENOTDIR"||e==="EPERM"?this.#F():e==="ENOENT"?this.#_():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#F():e==="ENOENT"&&this.#_()}#d(e=""){let t=this.#n;t|=Ma,e==="ENOENT"&&(t|=sn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=zi),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#F()}#z(e,t){return this.#O(e,t)||this.#B(e,t)}#B(e,t){let r=Pd(e),o=this.newChild(e.name,r,{parent:this}),i=o.#n&Vt;return i!==Sn&&i!==kr&&i!==qt&&(o.#n|=ji),t.unshift(o),t.provisional++,o}#O(e,t){for(let r=t.provisional;r<t.length;r++){let o=t[r];if((this.nocase?Na(e.name):$i(e.name))===o.#S)return this.#j(e,o,r,t)}}#j(e,t,r,o){let i=t.name;return t.#n=t.#n&zi|Pd(e),i!==e.name&&(t.name=e.name),r!==o.provisional&&(r===o.length-1?o.pop():o.splice(r,1),o.unshift(t)),o.provisional++,t}async lstat(){if(!(this.#n&sn))try{return this.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&sn))try{return this.#G(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code)}}#G(e){let{atime:t,atimeMs:r,birthtime:o,birthtimeMs:i,blksize:s,blocks:a,ctime:l,ctimeMs:c,dev:d,gid:p,ino:u,mode:m,mtime:h,mtimeMs:g,nlink:f,rdev:y,size:v,uid:b}=e;this.#T=t,this.#f=r,this.#E=o,this.#u=i,this.#p=s,this.#o=a,this.#C=l,this.#m=c,this.#t=d,this.#w=p,this.#a=u,this.#i=m,this.#g=h,this.#y=g,this.#r=f,this.#c=y,this.#l=v,this.#s=b;let E=Pd(e);this.#n=this.#n&zi|E|Gy,E!==qt&&E!==Sn&&E!==kr&&(this.#n|=ji)}#H=[];#W=!1;#V(e){this.#W=!1;let t=this.#H.slice();this.#H.length=0,t.forEach(r=>r(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#H.push(e),this.#W)return;this.#W=!0;let o=this.fullpath();this.#e.readdir(o,{withFileTypes:!0},(i,s)=>{if(i)this.#D(i.code),r.provisional=0;else{for(let a of s)this.#z(a,r);this.#N(r)}this.#V(r.slice(0,r.provisional))})}#$;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#$)await this.#$;else{let r=()=>{};this.#$=new Promise(o=>r=o);try{for(let o of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#z(o,e);this.#N(e)}catch(o){this.#D(o.code),e.provisional=0}this.#$=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let r of this.#e.readdirSync(t,{withFileTypes:!0}))this.#z(r,e);this.#N(e)}catch(r){this.#D(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&Vy)return!1;let e=Vt&this.#n;return e===qt||e===Sn||e===kr}shouldWalk(e,t){return(this.#n&Sn)===Sn&&!(this.#n&Vy)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((_a|Ma|sn)&this.#n))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}realpathSync(){if(this.#L)return this.#L;if(!((_a|Ma|sn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[nb](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],o=this;for(;o&&o.parent;)t.add(o),o.#P=r.join(this.sep),o.#A=r.join("/"),o=o.parent,r.push("..");for(o=e;o&&o.parent&&!t.has(o);)o.#P=void 0,o.#A=void 0,o=o.parent}},Da=class n extends ut{sep="\\";splitSep=_I;constructor(e,t=qt,r,o,i,s,a){super(e,t,r,o,i,s,a)}newChild(e,t=qt,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return Ld.parse(e).root}getRoot(e){if(e=NI(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,r]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=r;return this.roots[e]=new xo(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Xy,"$1\\"),e===t}},Ua=class n extends ut{splitSep="/";sep="/";constructor(e,t=qt,r,o,i,s,a){super(e,t,r,o,i,s,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=qt,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}},za=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,r,{nocase:o,childrenCacheSize:i=16*1024,fs:s=Bi}={}){this.#r=Yy(s),(e instanceof URL||e.startsWith("file://"))&&(e=xI(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new Fa,this.#t=new Fa,this.#i=new Od(i);let l=a.substring(this.rootPath.length).split(r);if(l.length===1&&!l[0]&&l.pop(),o===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=o,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let c=this.root,d=l.length-1,p=t.sep,u=this.rootPath,m=!1;for(let h of l){let g=d--;c=c.child(h,{relative:new Array(g).fill("..").join(p),relativePosix:new Array(g).fill("..").join("/"),fullpath:u+=(m?"":p)+h}),m=!0}this.cwd=c}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let s=e[i];if(!(!s||s===".")&&(t=t?`${s}/${t}`:s,this.isAbsolute(s)))break}let r=this.#e.get(t);if(r!==void 0)return r;let o=this.cwd.resolve(t).fullpath();return this.#e.set(t,o),o}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let s=e[i];if(!(!s||s===".")&&(t=t?`${s}/${t}`:s,this.isAbsolute(s)))break}let r=this.#t.get(t);if(r!==void 0)return r;let o=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,o),o}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r}=t;if(e.canReaddir()){let o=await e.readdir();return r?o:o.map(i=>i.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0}=t;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(o=>o.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e.withFileTypes,e=this.cwd);let r=await e.readlink();return t?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return t?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e.withFileTypes,e=this.cwd);let r=await e.realpath();return t?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return t?r:r?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=[];(!i||i(e))&&a.push(r?e:e.fullpath());let l=new Set,c=(p,u)=>{l.add(p),p.readdirCB((m,h)=>{if(m)return u(m);let g=h.length;if(!g)return u();let f=()=>{--g===0&&u()};for(let y of h)(!i||i(y))&&a.push(r?y:y.fullpath()),o&&y.isSymbolicLink()?y.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(l,s)?c(v,f):f()):y.shouldWalk(l,s)?c(y,f):f()},!0)},d=e;return new Promise((p,u)=>{c(d,m=>{if(m)return u(m);p(a)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=[];(!i||i(e))&&a.push(r?e:e.fullpath());let l=new Set([e]);for(let c of l){let d=c.readdirSync();for(let p of d){(!i||i(p))&&a.push(r?p:p.fullpath());let u=p;if(p.isSymbolicLink()){if(!(o&&(u=p.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(l,s)&&l.add(u)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t;(!i||i(e))&&(yield r?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let d of c){(!i||i(d))&&(yield r?d:d.fullpath());let p=d;if(d.isSymbolicLink()){if(!(o&&(p=d.realpathSync())))continue;p.isUnknown()&&p.lstatSync()}p.shouldWalk(a,s)&&a.add(p)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new Kn({objectMode:!0});(!i||i(e))&&a.write(r?e:e.fullpath());let l=new Set,c=[e],d=0,p=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){d===0&&a.end();return}d++,l.add(m);let h=(f,y,v=!1)=>{if(f)return a.emit("error",f);if(o&&!v){let b=[];for(let E of y)E.isSymbolicLink()&&b.push(E.realpath().then(x=>x?.isUnknown()?x.lstat():x));if(b.length){Promise.all(b).then(()=>h(null,y,!0));return}}for(let b of y)b&&(!i||i(b))&&(a.write(r?b:b.fullpath())||(u=!0));d--;for(let b of y){let E=b.realpathCached()||b;E.shouldWalk(l,s)&&c.push(E)}u&&!a.flowing?a.once("drain",p):g||p()},g=!0;m.readdirCB(h,!0),g=!1}};return p(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new Kn({objectMode:!0}),l=new Set;(!i||i(e))&&a.write(r?e:e.fullpath());let c=[e],d=0,p=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){d===0&&a.end();return}d++,l.add(m);let h=m.readdirSync();for(let g of h)(!i||i(g))&&(a.write(r?g:g.fullpath())||(u=!0));d--;for(let g of h){let f=g;if(g.isSymbolicLink()){if(!(o&&(f=g.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(l,s)&&c.push(f)}}u&&!a.flowing&&a.once("drain",p)};return p(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[nb](t)}},xo=class extends za{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Ld,"\\",{...t,nocase:r}),this.nocase=r;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return Ld.parse(e).root.toUpperCase()}newRoot(e){return new Da(this.rootPath,Sn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},To=class extends za{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,vI,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new Ua(this.rootPath,Sn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Hi=class extends To{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},nee=process.platform==="win32"?Da:Ua,rb=process.platform==="win32"?xo:process.platform==="darwin"?Hi:To;var DI=n=>n.length>=1,UI=n=>n.length>=1,Co=class n{#e;#t;#i;length;#r;#s;#w;#c;#p;#a;#l=!0;constructor(e,t,r,o){if(!DI(e))throw new TypeError("empty pattern list");if(!UI(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,r<0||r>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=r,this.#r=o,this.#i===0){if(this.isUNC()){let[i,s,a,l,...c]=this.#e,[d,p,u,m,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let g=[i,s,a,l,""].join("/"),f=[d,p,u,m,""].join("/");this.#e=[g,...c],this.#t=[f,...h],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[i,...s]=this.#e,[a,...l]=this.#t;s[0]===""&&(s.shift(),l.shift());let c=i+"/",d=a+"/";this.#e=[c,...s],this.#t=[d,...l],this.length=this.#e.length}}}pattern(){return this.#e[this.#i]}isString(){return typeof this.#e[this.#i]=="string"}isGlobstar(){return this.#e[this.#i]===ot}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#w=this.#w||(this.#i===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#s!==void 0?this.#s:this.hasMore()?(this.#s=new n(this.#e,this.#t,this.#i+1,this.#r),this.#s.#a=this.#a,this.#s.#p=this.#p,this.#s.#c=this.#c,this.#s):this.#s=null}isUNC(){let e=this.#e;return this.#p!==void 0?this.#p:this.#p=this.#r==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return!(this.#i===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#l?!1:(this.#l=!1,!0)}};var zI=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Eo=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:o,noglobstar:i,platform:s=zI}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=s,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:o,noglobstar:i,optimizationLevel:2,platform:s,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let t=new kt(e,this.mmopts);for(let r=0;r<t.set.length;r++){let o=t.set[r],i=t.globParts[r];if(!o||!i)throw new Error("invalid pattern object");for(;o[0]==="."&&i[0]===".";)o.shift(),i.shift();let s=new Co(o,i,0,this.platform),a=new kt(s.globString(),this.mmopts),l=i[i.length-1]==="**",c=s.isAbsolute();c?this.absolute.push(a):this.relative.push(a),l&&(c?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let t=e.fullpath(),r=`${t}/`,o=e.relative()||".",i=`${o}/`;for(let s of this.relative)if(s.match(o)||s.match(i))return!0;for(let s of this.absolute)if(s.match(t)||s.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let o of this.relativeChildren)if(o.match(r))return!0;for(let o of this.absoluteChildren)if(o.match(t))return!0;return!1}};var kd=class n{store;constructor(e=new Map){this.store=e}copy(){return new n(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let r=e.fullpath(),o=this.store.get(r);o?o.add(t.globString()):this.store.set(r,new Set([t.globString()]))}},Md=class{store=new Map;add(e,t,r){let o=(t?2:0)|(r?1:0),i=this.store.get(e);this.store.set(e,i===void 0?o:o&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Nd=class{store=new Map;add(e,t){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(o=>o.globString()===t.globString())||r.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},Wi=class n{hasWalkedCache;matches=new Md;subwalks=new Nd;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new kd}processPatterns(e,t){this.patterns=t;let r=t.map(o=>[e,o]);for(let[o,i]of r){this.hasWalkedCache.storeWalked(o,i);let s=i.root(),a=i.isAbsolute()&&this.opts.absolute!==!1;if(s){o=o.resolve(s==="/"&&this.opts.root!==void 0?this.opts.root:s);let p=i.rest();if(p)i=p;else{this.matches.add(o,!0,!1);continue}}if(o.isENOENT())continue;let l,c,d=!1;for(;typeof(l=i.pattern())=="string"&&(c=i.rest());)o=o.resolve(l),i=c,d=!0;if(l=i.pattern(),c=i.rest(),d){if(this.hasWalkedCache.hasWalked(o,i))continue;this.hasWalkedCache.storeWalked(o,i)}if(typeof l=="string"){let p=l===".."||l===""||l===".";this.matches.add(o.resolve(l),a,p);continue}else if(l===ot){(!o.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(o,i);let p=c?.pattern(),u=c?.rest();if(!c||(p===""||p===".")&&!u)this.matches.add(o,a,p===""||p===".");else if(p===".."){let m=o.parent||o;u?this.hasWalkedCache.hasWalked(m,u)||this.subwalks.add(m,u):this.matches.add(m,a,!0)}}else l instanceof RegExp&&this.subwalks.add(o,i)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(e,t){let r=this.subwalks.get(e),o=this.child();for(let i of t)for(let s of r){let a=s.isAbsolute(),l=s.pattern(),c=s.rest();l===ot?o.testGlobstar(i,s,c,a):l instanceof RegExp?o.testRegExp(i,l,c,a):o.testString(i,l,c,a)}return o}testGlobstar(e,t,r,o){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,o,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(r&&t.checkFollowGlobstar()?this.subwalks.add(e,r):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),r){let i=r.pattern();if(typeof i=="string"&&i!==".."&&i!==""&&i!==".")this.testString(e,i,r.rest(),o);else if(i===".."){let s=e.parent||e;this.subwalks.add(s,r)}else i instanceof RegExp&&this.testRegExp(e,i,r.rest(),o)}}testRegExp(e,t,r,o){t.test(e.name)&&(r?this.subwalks.add(e,r):this.matches.add(e,o,!1))}testString(e,t,r,o){e.isNamed(t)&&(r?this.subwalks.add(e,r):this.matches.add(e,o,!1))}};var BI=(n,e)=>typeof n=="string"?new Eo([n],e):Array.isArray(n)?new Eo(n,e):n,Ba=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,r){if(this.patterns=e,this.path=t,this.opts=r,this.#i=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#t=BI(r.ignore??[],r),!this.includeChildMatches&&typeof this.#t.add!="function")){let o="cannot ignore child matches, ignore lacks add() method.";throw new Error(o)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#r(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#s(e){return!!this.#t?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let s=await i.realpath();s&&(s.isUnknown()||this.opts.stat)&&await s.lstat()}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#r(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let s=i.realpathSync();s&&(s?.isUnknown()||this.opts.stat)&&s.lstatSync()}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#r(e))return;if(!this.includeChildMatches&&this.#t?.add){let i=`${e.relativePosix()}/**`;this.#t.add(i)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let o=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+o)}else{let i=this.opts.posix?e.relativePosix():e.relative(),s=this.opts.dotRelative&&!i.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(i?s+i+o:"."+o)}}async match(e,t,r){let o=await this.matchCheck(e,r);o&&this.matchFinish(o,t)}matchSync(e,t,r){let o=this.matchCheckSync(e,r);o&&this.matchFinish(o,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new Wi(this.opts),r)}walkCB2(e,t,r,o){if(this.#s(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,o));return}r.processPatterns(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||(i++,this.match(a,l,c).then(()=>s()));for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,r,s):a.readdirCB((c,d)=>this.walkCB3(a,d,r,s),!0)}s()}walkCB3(e,t,r,o){r=r.filterEntries(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||(i++,this.match(a,l,c).then(()=>s()));for(let[a,l]of r.subwalks.entries())i++,this.walkCB2(a,l,r.child(),s);s()}walkCBSync(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new Wi(this.opts),r)}walkCB2Sync(e,t,r,o){if(this.#s(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,o));return}r.processPatterns(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||this.matchSync(a,l,c);for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirSync();this.walkCB3Sync(a,l,r,s)}s()}walkCB3Sync(e,t,r,o){r=r.filterEntries(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||this.matchSync(a,l,c);for(let[a,l]of r.subwalks.entries())i++,this.walkCB2Sync(a,l,r.child(),s);s()}},Gi=class extends Ba{matches=new Set;constructor(e,t,r){super(e,t,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Vi=class extends Ba{results;constructor(e,t,r){super(e,t,r),this.results=new Kn({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var $I=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",an=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=jI(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(l=>l.includes("/")?l:`./**/${l}`)}if(this.pattern=e,this.platform=t.platform||$I,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let l=t.platform==="win32"?xo:t.platform==="darwin"?Hi:t.platform?To:rb;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",o={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(l=>new kt(l,o)),[s,a]=i.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=s.map((l,c)=>{let d=a[c];if(!d)throw new Error("invalid pattern object");return new Co(l,d,0,this.platform)})}async walk(){return[...await new Gi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new Gi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Vi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Vi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var _d=(n,e={})=>{Array.isArray(n)||(n=[n]);for(let t of n)if(new kt(t,e).hasMagic())return!0;return!1};function ja(n,e={}){return new an(n,e).streamSync()}function sb(n,e={}){return new an(n,e).stream()}function Ao(n,e={}){return new an(n,e).walkSync()}async function ob(n,e={}){return new an(n,e).walk()}function $a(n,e={}){return new an(n,e).iterateSync()}function ab(n,e={}){return new an(n,e).iterate()}var HI=ja,WI=Object.assign(sb,{sync:ja}),GI=$a,VI=Object.assign(ab,{sync:$a}),qI=Object.assign(Ao,{stream:ja,iterate:$a}),ib=Object.assign(ob,{glob:ob,globSync:Ao,sync:qI,globStream:sb,stream:WI,globStreamSync:ja,streamSync:HI,globIterate:ab,iterate:VI,globIterateSync:$a,iterateSync:GI,Glob:an,hasMagic:_d,escape:yo,unescape:rn});ib.glob=ib;import tP from"os";import Yn,{dirname as pb}from"path";import{cwd as zd}from"process";import ub from"yaml";import{z as Ie}from"zod";import lb from"fs";import Ha from"path";import KI from"yaml";import{z as Fd}from"zod";var cb=!1,qi=[`**/*.${Cn.TEST}`,`**/*.${Cn.MODULE}`],Dd=Fd.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),Ud=50,YI=Fd.object({fileType:Fd.nativeEnum(be)});function Ze(n,e){let t={project:n,tests:{},modules:{}},r=n.config.include??qi,o=Array.from(n.config.exclude??[]).concat(vm),i=Ao(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:Ud,nodir:!0});for(let s of i)XI(n.rootDir,s,t,e);return cb=!0,t}function XI(n,e,t,r){let o=Ha.join(n,e),i;try{i=lb.readFileSync(o,"utf-8")}catch(p){r.warn(`Could not read possible Momentic file at ${o}, skipping: ${p}`);return}let s;try{if(s=KI.parse(i),typeof s!="object"||s===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(p){r.warn(`Could not parse possible Momentic file at ${o}, skipping: ${p}`);return}let a=YI.safeParse(s);if(a.error){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${a.error}`);return}let l=a.data.fileType,c;try{c=lb.statSync(o)}catch(p){r.warn(`Skipping path '${o}' because it could not be stat, skipping: ${p}`);return}let d={relativePath:e,fullFilePath:o,platformSep:Ha.sep,fullPathSegments:o.split(Ha.sep),fileName:Ha.basename(o),lastModified:c.mtime,createdAt:c.birthtime};switch(l){case be.TEST:try{let p=pn.parse(s);if(t.tests[p.id]){let u=t.tests[p.id].fullFilePath;S.error(`Two tests with the same ID (${p.id}) were found in the same project. Please ensure that all test IDs are unique and avoid copying tests manually. Momentic will ignore the first test when resolving tests.
2976
+ >>> no match, partial?`,e,u,t,m),u===l))}let g;if(typeof d=="string"?(g=p===d,this.debug("string match",d,p,g)):(g=d.test(p),this.debug("pattern match",d,p,g)),!g)return!1}if(s===l&&a===c)return!0;if(s===l)return r;if(a===c)return s===l-1&&e[s]==="";throw new Error("wtf?")}braceExpand(){return _y(this.pattern,this.options)}parse(e){ki(e);let t=this.options;if(e==="**")return ot;if(e==="")return"";let r,o=null;(r=e.match(VR))?o=t.dot?KR:qR:(r=e.match(FR))?o=(t.nocase?t.dot?BR:zR:t.dot?UR:DR)(r[1]):(r=e.match(YR))?o=(t.nocase?t.dot?JR:XR:t.dot?ZR:QR)(r):(r=e.match(jR))?o=t.dot?HR:$R:(r=e.match(WR))&&(o=GR);let i=fo.fromGlob(e,this.options).toMMPattern();return o&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:o}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?nI:t.dot?rI:oI,o=new Set(t.nocase?["i"]:[]),i=e.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let p of d.flags.split(""))o.add(p);return typeof d=="string"?cI(d):d===ot?ot:d._src});return c.forEach((d,p)=>{let u=c[p+1],m=c[p-1];d!==ot||m===ot||(m===void 0?u!==void 0&&u!==ot?c[p+1]="(?:\\/|"+r+"\\/)?"+u:c[p]=r:u===void 0?c[p-1]=m+"(?:\\/|"+r+")?":u!==ot&&(c[p-1]=m+"(?:\\/|\\/"+r+"\\/)"+u,c[p+1]=ot))}),c.filter(d=>d!==ot).join("/")}).join("|"),[s,a]=e.length>1?["(?:",")"]:["",""];i="^"+s+i+a+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let i=this.set;this.debug(this.pattern,"set",i);let s=o[o.length-1];if(!s)for(let a=o.length-2;!s&&a>=0;a--)s=o[a];for(let a=0;a<i.length;a++){let l=i[a],c=o;if(r.matchBase&&l.length===1&&(c=[s]),this.matchOne(c,l,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return ft.defaults(e).Minimatch}};ft.AST=fo;ft.Minimatch=kt;ft.escape=yo;ft.unescape=rn;import{fileURLToPath as jI}from"node:url";var bo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Dy=new Set,Sd=typeof process=="object"&&process?process:{},Uy=(n,e,t,r)=>{typeof Sd.emitWarning=="function"?Sd.emitWarning(n,e,t,r):console.error(`[${t}] ${e}: ${n}`)},Aa=globalThis.AbortController,Fy=globalThis.AbortSignal;if(typeof Aa>"u"){Fy=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},Aa=class{constructor(){e()}signal=new Fy;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}}};let n=Sd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,Uy("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var dI=n=>!Dy.has(n),$7=Symbol("type"),Vn=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),zy=n=>Vn(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?So:null:null,So=class extends Array{constructor(e){super(e),this.fill(0)}},wd=class n{heap;length;static#e=!1;static create(e){let t=zy(e);if(!t)return[];n.#e=!0;let r=new n(e,t);return n.#e=!1,r}constructor(e,t){if(!n.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Ni=class n{#e;#t;#i;#r;#s;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#p;#a;#l;#o;#f;#y;#m;#u;#T;#g;#C;#E;#S;#v;#x;#h;static unsafeExposeInternals(e){return{starts:e.#E,ttls:e.#S,sizes:e.#C,keyMap:e.#a,keyList:e.#l,valList:e.#o,next:e.#f,prev:e.#y,get head(){return e.#m},get tail(){return e.#u},free:e.#T,isBackgroundFetch:t=>e.#d(t),backgroundFetch:(t,r,o,i)=>e.#U(t,r,o,i),moveToTail:t=>e.#B(t),indexes:t=>e.#R(t),rindexes:t=>e.#I(t),isStale:t=>e.#b(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#p}get size(){return this.#c}get fetchMethod(){return this.#s}get memoMethod(){return this.#w}get dispose(){return this.#i}get disposeAfter(){return this.#r}constructor(e){let{max:t=0,ttl:r,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:d,noDisposeOnSet:p,noUpdateTTL:u,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:f,memoMethod:y,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:x,ignoreFetchAbort:C}=e;if(t!==0&&!Vn(t))throw new TypeError("max option must be a nonnegative integer");let L=t?zy(t):Array;if(!L)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=y,f!==void 0&&typeof f!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#s=f,this.#x=!!f,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#f=new L(t),this.#y=new L(t),this.#m=0,this.#u=0,this.#T=wd.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof d=="function"?(this.#r=d,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#v=!!this.#i,this.#h=!!this.#r,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!x,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(this.#t!==0&&!Vn(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!Vn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Vn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!Vn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let N="LRU_CACHE_UNBOUNDED";dI(N)&&(Dy.add(N),Uy("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",N,n))}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#P(){let e=new So(this.#e),t=new So(this.#e);this.#S=e,this.#E=t,this.#k=(i,s,a=bo.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#b(i)&&this.#O(this.#l[i],"expire")},s+1);l.unref&&l.unref()}},this.#A=i=>{t[i]=e[i]!==0?bo.now():0},this.#n=(i,s)=>{if(e[s]){let a=e[s],l=t[s];if(!a||!l)return;i.ttl=a,i.start=l,i.now=r||o();let c=i.now-l;i.remainingTTL=a-c}};let r=0,o=()=>{let i=bo.now();if(this.ttlResolution>0){r=i;let s=setTimeout(()=>r=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#a.get(i);if(s===void 0)return 0;let a=e[s],l=t[s];if(!a||!l)return 1/0;let c=(r||o())-l;return a-c},this.#b=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(r||o())-s>a}}#A=()=>{};#n=()=>{};#k=()=>{};#b=()=>!1;#L(){let e=new So(this.#e);this.#p=0,this.#C=e,this.#M=t=>{this.#p-=e[t],e[t]=0},this.#_=(t,r,o,i)=>{if(this.#d(r))return 0;if(!Vn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(r,t),!Vn(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(t,r,o)=>{if(e[t]=r,this.#t){let i=this.#t-e[t];for(;this.#p>i;)this.#D(!0)}this.#p+=e[t],o&&(o.entrySize=r,o.totalCalculatedSize=this.#p)}}#M=e=>{};#N=(e,t,r)=>{};#_=(e,t,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#u;!(!this.#F(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#F(t)||((e||!this.#b(t))&&(yield t),t===this.#u));)t=this.#f[t]}#F(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#R())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*rentries(){for(let e of this.#I())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*keys(){for(let e of this.#R()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*rkeys(){for(let e of this.#I()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*values(){for(let e of this.#R())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}*rvalues(){for(let e of this.#I())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let r of this.#R()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#l[r],this))return this.get(this.#l[r],t)}}forEach(e,t=this){for(let r of this.#R()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[r],this)}}rforEach(e,t=this){for(let r of this.#I()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[r],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#b(t)&&(this.#O(this.#l[t],"expire"),e=!0);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let r=this.#o[t],o=this.#d(r)?r.__staleWhileFetching:r;if(o===void 0)return;let i={value:o};if(this.#S&&this.#E){let s=this.#S[t],a=this.#E[t];if(s&&a){let l=s-(bo.now()-a);i.ttl=l,i.start=Date.now()}}return this.#C&&(i.size=this.#C[t]),i}dump(){let e=[];for(let t of this.#R({allowStale:!0})){let r=this.#l[t],o=this.#o[t],i=this.#d(o)?o.__staleWhileFetching:o;if(i===void 0||r===void 0)continue;let s={value:i};if(this.#S&&this.#E){s.ttl=this.#S[t];let a=bo.now()-this.#E[t];s.start=Math.floor(Date.now()-a)}this.#C&&(s.size=this.#C[t]),e.unshift([r,s])}return e}load(e){this.clear();for(let[t,r]of e){if(r.start){let o=Date.now()-r.start;r.start=bo.now()-o}this.set(t,r.value,r)}}set(e,t,r={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,d=this.#_(e,t,r.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#O(e,"set"),this;let p=this.#c===0?void 0:this.#a.get(e);if(p===void 0)p=this.#c===0?this.#u:this.#T.length!==0?this.#T.pop():this.#c===this.#e?this.#D(!1):this.#c,this.#l[p]=e,this.#o[p]=t,this.#a.set(e,p),this.#f[this.#u]=p,this.#y[p]=this.#u,this.#u=p,this.#c++,this.#N(p,d,l),l&&(l.set="add"),c=!1;else{this.#B(p);let u=this.#o[p];if(t!==u){if(this.#x&&this.#d(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=u;m!==void 0&&!s&&(this.#v&&this.#i?.(m,e,"set"),this.#h&&this.#g?.push([m,e,"set"]))}else s||(this.#v&&this.#i?.(u,e,"set"),this.#h&&this.#g?.push([u,e,"set"]));if(this.#M(p),this.#N(p,d,l),this.#o[p]=t,l){l.set="replace";let m=u&&this.#d(u)?u.__staleWhileFetching:u;m!==void 0&&(l.oldValue=m)}}else l&&(l.set="update")}if(o!==0&&!this.#S&&this.#P(),this.#S&&(c||this.#k(p,o,i),l&&this.#n(l,p)),!s&&this.#h&&this.#g){let u=this.#g,m;for(;m=u?.shift();)this.#r?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#m];if(this.#D(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#D(e){let t=this.#m,r=this.#l[t],o=this.#o[t];return this.#x&&this.#d(o)?o.__abortController.abort(new Error("evicted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(o,r,"evict"),this.#h&&this.#g?.push([o,r,"evict"])),this.#M(t),e&&(this.#l[t]=void 0,this.#o[t]=void 0,this.#T.push(t)),this.#c===1?(this.#m=this.#u=0,this.#T.length=0):this.#m=this.#f[t],this.#a.delete(r),this.#c--,t}has(e,t={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=t,i=this.#a.get(e);if(i!==void 0){let s=this.#o[i];if(this.#d(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#b(i))o&&(o.has="stale",this.#n(o,i));else return r&&this.#A(i),o&&(o.has="hit",this.#n(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:r=this.allowStale}=t,o=this.#a.get(e);if(o===void 0||!r&&this.#b(o))return;let i=this.#o[o];return this.#d(i)?i.__staleWhileFetching:i}#U(e,t,r,o){let i=t===void 0?void 0:this.#o[t];if(this.#d(i))return i;let s=new Aa,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let l={signal:s.signal,options:r,context:o},c=(g,f=!1)=>{let{aborted:y}=s.signal,v=r.ignoreFetchAbort&&g!==void 0;if(r.status&&(y&&!f?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,v&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),y&&!v&&!f)return p(s.signal.reason);let b=m;return this.#o[t]===m&&(g===void 0?b.__staleWhileFetching?this.#o[t]=b.__staleWhileFetching:this.#O(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,g,l.options))),g},d=g=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=g),p(g)),p=g=>{let{aborted:f}=s.signal,y=f&&r.allowStaleOnFetchAbort,v=y||r.allowStaleOnFetchRejection,b=v||r.noDeleteOnFetchRejection,E=m;if(this.#o[t]===m&&(!b||E.__staleWhileFetching===void 0?this.#O(e,"fetch"):y||(this.#o[t]=E.__staleWhileFetching)),v)return r.status&&E.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw g},u=(g,f)=>{let y=this.#s?.(e,i,l);y&&y instanceof Promise&&y.then(v=>g(v===void 0?void 0:v),f),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(g(void 0),r.allowStaleOnFetchAbort&&(g=v=>c(v,!0)))})};r.status&&(r.status.fetchDispatched=!0);let m=new Promise(u).then(c,d),h=Object.assign(m,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#a.get(e)):this.#o[t]=h,h}#d(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Aa}async fetch(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:g,forceRefresh:f=!1,status:y,signal:v}=t;if(!this.#x)return y&&(y.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:y});let b={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:d,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:h,ignoreFetchAbort:m,status:y,signal:v},E=this.#a.get(e);if(E===void 0){y&&(y.fetch="miss");let x=this.#U(e,E,b,g);return x.__returned=x}else{let x=this.#o[E];if(this.#d(x)){let U=r&&x.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",U&&(y.returnedStale=!0)),U?x.__staleWhileFetching:x.__returned=x}let C=this.#b(E);if(!f&&!C)return y&&(y.fetch="hit"),this.#B(E),o&&this.#A(E),y&&this.#n(y,E),x;let L=this.#U(e,E,b,g),P=L.__staleWhileFetching!==void 0&&r;return y&&(y.fetch=C?"stale":"refresh",P&&C&&(y.returnedStale=!0)),P?L.__staleWhileFetching:L.__returned=L}}async forceFetch(e,t={}){let r=await this.fetch(e,t);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,t={}){let r=this.#w;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=t,a=this.get(e,s);if(!i&&a!==void 0)return a;let l=r(e,a,{options:s,context:o});return this.set(e,l,s),l}get(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#o[a],c=this.#d(l);return s&&this.#n(s,a),this.#b(a)?(s&&(s.get="stale"),c?(s&&r&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),r?l.__staleWhileFetching:void 0):(i||this.#O(e,"expire"),s&&r&&(s.returnedStale=!0),r?l:void 0)):(s&&(s.get="hit"),c?l.__staleWhileFetching:(this.#B(a),o&&this.#A(a),l))}else s&&(s.get="miss")}#z(e,t){this.#y[t]=e,this.#f[e]=t}#B(e){e!==this.#u&&(e===this.#m?this.#m=this.#f[e]:this.#z(this.#y[e],this.#f[e]),this.#z(this.#u,e),this.#u=e)}delete(e){return this.#O(e,"delete")}#O(e,t){let r=!1;if(this.#c!==0){let o=this.#a.get(e);if(o!==void 0)if(r=!0,this.#c===1)this.#j(t);else{this.#M(o);let i=this.#o[o];if(this.#d(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(i,e,t),this.#h&&this.#g?.push([i,e,t])),this.#a.delete(e),this.#l[o]=void 0,this.#o[o]=void 0,o===this.#u)this.#u=this.#y[o];else if(o===this.#m)this.#m=this.#f[o];else{let s=this.#y[o];this.#f[s]=this.#f[o];let a=this.#f[o];this.#y[a]=this.#y[o]}this.#c--,this.#T.push(o)}}if(this.#h&&this.#g?.length){let o=this.#g,i;for(;i=o?.shift();)this.#r?.(...i)}return r}clear(){return this.#j("delete")}#j(e){for(let t of this.#I({allowStale:!0})){let r=this.#o[t];if(this.#d(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#l[t];this.#v&&this.#i?.(r,o,e),this.#h&&this.#g?.push([r,o,e])}}if(this.#a.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#S&&this.#E&&(this.#S.fill(0),this.#E.fill(0)),this.#C&&this.#C.fill(0),this.#m=0,this.#u=0,this.#T.length=0,this.#p=0,this.#c=0,this.#h&&this.#g){let t=this.#g,r;for(;r=t?.shift();)this.#r?.(...r)}}};import{posix as vI,win32 as Ld}from"node:path";import{fileURLToPath as xI}from"node:url";import{lstatSync as TI,readdir as CI,readdirSync as EI,readlinkSync as AI,realpathSync as RI}from"fs";import*as II from"node:fs";import{lstat as LI,readdir as OI,readlink as kI,realpath as MI}from"node:fs/promises";import{EventEmitter as Rd}from"node:events";import Wy from"node:stream";import{StringDecoder as pI}from"node:string_decoder";var By=typeof process=="object"&&process?process:{stdout:null,stderr:null},uI=n=>!!n&&typeof n=="object"&&(n instanceof Kn||n instanceof Wy||mI(n)||hI(n)),mI=n=>!!n&&typeof n=="object"&&n instanceof Rd&&typeof n.pipe=="function"&&n.pipe!==Wy.Writable.prototype.pipe,hI=n=>!!n&&typeof n=="object"&&n instanceof Rd&&typeof n.write=="function"&&typeof n.end=="function",Ln=Symbol("EOF"),On=Symbol("maybeEmitEnd"),qn=Symbol("emittedEnd"),Ra=Symbol("emittingEnd"),_i=Symbol("emittedError"),Ia=Symbol("closed"),jy=Symbol("read"),Pa=Symbol("flush"),$y=Symbol("flushChunk"),on=Symbol("encoding"),wo=Symbol("decoder"),Ye=Symbol("flowing"),Fi=Symbol("paused"),vo=Symbol("resume"),Xe=Symbol("buffer"),yt=Symbol("pipes"),Je=Symbol("bufferLength"),vd=Symbol("bufferPush"),La=Symbol("bufferShift"),pt=Symbol("objectMode"),_e=Symbol("destroyed"),xd=Symbol("error"),Td=Symbol("emitData"),Hy=Symbol("emitEnd"),Cd=Symbol("emitEnd2"),bn=Symbol("async"),Ed=Symbol("abort"),Oa=Symbol("aborted"),Di=Symbol("signal"),Or=Symbol("dataListeners"),Mt=Symbol("discarded"),Ui=n=>Promise.resolve().then(n),gI=n=>n(),fI=n=>n==="end"||n==="finish"||n==="prefinish",yI=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,bI=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),ka=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[vo](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ad=class extends ka{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=o=>t.emit("error",o),e.on("error",this.proxyErrors)}},SI=n=>!!n.objectMode,wI=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",Kn=class extends Rd{[Ye]=!1;[Fi]=!1;[yt]=[];[Xe]=[];[pt];[on];[bn];[wo];[Ln]=!1;[qn]=!1;[Ra]=!1;[Ia]=!1;[_i]=null;[Je]=0;[_e]=!1;[Di];[Oa]=!1;[Or]=0;[Mt]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");SI(t)?(this[pt]=!0,this[on]=null):wI(t)?(this[on]=t.encoding,this[pt]=!1):(this[pt]=!1,this[on]=null),this[bn]=!!t.async,this[wo]=this[on]?new pI(this[on]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Xe]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[yt]});let{signal:r}=t;r&&(this[Di]=r,r.aborted?this[Ed]():r.addEventListener("abort",()=>this[Ed]()))}get bufferLength(){return this[Je]}get encoding(){return this[on]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[pt]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[bn]}set async(e){this[bn]=this[bn]||!!e}[Ed](){this[Oa]=!0,this.emit("abort",this[Di]?.reason),this.destroy(this[Di]?.reason)}get aborted(){return this[Oa]}set aborted(e){}write(e,t,r){if(this[Oa])return!1;if(this[Ln])throw new Error("write after end");if(this[_e])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let o=this[bn]?Ui:gI;if(!this[pt]&&!Buffer.isBuffer(e)){if(bI(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(yI(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[pt]?(this[Ye]&&this[Je]!==0&&this[Pa](!0),this[Ye]?this.emit("data",e):this[vd](e),this[Je]!==0&&this.emit("readable"),r&&o(r),this[Ye]):e.length?(typeof e=="string"&&!(t===this[on]&&!this[wo]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[on]&&(e=this[wo].write(e)),this[Ye]&&this[Je]!==0&&this[Pa](!0),this[Ye]?this.emit("data",e):this[vd](e),this[Je]!==0&&this.emit("readable"),r&&o(r),this[Ye]):(this[Je]!==0&&this.emit("readable"),r&&o(r),this[Ye])}read(e){if(this[_e])return null;if(this[Mt]=!1,this[Je]===0||e===0||e&&e>this[Je])return this[On](),null;this[pt]&&(e=null),this[Xe].length>1&&!this[pt]&&(this[Xe]=[this[on]?this[Xe].join(""):Buffer.concat(this[Xe],this[Je])]);let t=this[jy](e||null,this[Xe][0]);return this[On](),t}[jy](e,t){if(this[pt])this[La]();else{let r=t;e===r.length||e===null?this[La]():typeof r=="string"?(this[Xe][0]=r.slice(e),t=r.slice(0,e),this[Je]-=e):(this[Xe][0]=r.subarray(e),t=r.subarray(0,e),this[Je]-=e)}return this.emit("data",t),!this[Xe].length&&!this[Ln]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[Ln]=!0,this.writable=!1,(this[Ye]||!this[Fi])&&this[On](),this}[vo](){this[_e]||(!this[Or]&&!this[yt].length&&(this[Mt]=!0),this[Fi]=!1,this[Ye]=!0,this.emit("resume"),this[Xe].length?this[Pa]():this[Ln]?this[On]():this.emit("drain"))}resume(){return this[vo]()}pause(){this[Ye]=!1,this[Fi]=!0,this[Mt]=!1}get destroyed(){return this[_e]}get flowing(){return this[Ye]}get paused(){return this[Fi]}[vd](e){this[pt]?this[Je]+=1:this[Je]+=e.length,this[Xe].push(e)}[La](){return this[pt]?this[Je]-=1:this[Je]-=this[Xe][0].length,this[Xe].shift()}[Pa](e=!1){do;while(this[$y](this[La]())&&this[Xe].length);!e&&!this[Xe].length&&!this[Ln]&&this.emit("drain")}[$y](e){return this.emit("data",e),this[Ye]}pipe(e,t){if(this[_e])return e;this[Mt]=!1;let r=this[qn];return t=t||{},e===By.stdout||e===By.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[yt].push(t.proxyErrors?new Ad(this,e,t):new ka(this,e,t)),this[bn]?Ui(()=>this[vo]()):this[vo]()),e}unpipe(e){let t=this[yt].find(r=>r.dest===e);t&&(this[yt].length===1?(this[Ye]&&this[Or]===0&&(this[Ye]=!1),this[yt]=[]):this[yt].splice(this[yt].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[Mt]=!1,this[Or]++,!this[yt].length&&!this[Ye]&&this[vo]();else if(e==="readable"&&this[Je]!==0)super.emit("readable");else if(fI(e)&&this[qn])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[_i]){let o=t;this[bn]?Ui(()=>o.call(this,this[_i])):o.call(this,this[_i])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[Or]=this.listeners("data").length,this[Or]===0&&!this[Mt]&&!this[yt].length&&(this[Ye]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Or]=0,!this[Mt]&&!this[yt].length&&(this[Ye]=!1)),t}get emittedEnd(){return this[qn]}[On](){!this[Ra]&&!this[qn]&&!this[_e]&&this[Xe].length===0&&this[Ln]&&(this[Ra]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ia]&&this.emit("close"),this[Ra]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==_e&&this[_e])return!1;if(e==="data")return!this[pt]&&!r?!1:this[bn]?(Ui(()=>this[Td](r)),!0):this[Td](r);if(e==="end")return this[Hy]();if(e==="close"){if(this[Ia]=!0,!this[qn]&&!this[_e])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[_i]=r,super.emit(xd,r);let i=!this[Di]||this.listeners("error").length?super.emit("error",r):!1;return this[On](),i}else if(e==="resume"){let i=super.emit("resume");return this[On](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let o=super.emit(e,...t);return this[On](),o}[Td](e){for(let r of this[yt])r.dest.write(e)===!1&&this.pause();let t=this[Mt]?!1:super.emit("data",e);return this[On](),t}[Hy](){return this[qn]?!1:(this[qn]=!0,this.readable=!1,this[bn]?(Ui(()=>this[Cd]()),!0):this[Cd]())}[Cd](){if(this[wo]){let t=this[wo].end();if(t){for(let r of this[yt])r.dest.write(t);this[Mt]||super.emit("data",t)}}for(let t of this[yt])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[pt]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[pt]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[pt])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[on]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(_e,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Mt]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let o=this.read();if(o!==null)return Promise.resolve({done:!1,value:o});if(this[Ln])return t();let i,s,a=p=>{this.off("data",l),this.off("end",c),this.off(_e,d),t(),s(p)},l=p=>{this.off("error",a),this.off("end",c),this.off(_e,d),this.pause(),i({value:p,done:!!this[Ln]})},c=()=>{this.off("error",a),this.off("data",l),this.off(_e,d),t(),i({done:!0,value:void 0})},d=()=>a(new Error("stream destroyed"));return new Promise((p,u)=>{s=u,i=p,this.once(_e,d),this.once("error",a),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Mt]=!1;let e=!1,t=()=>(this.pause(),this.off(xd,t),this.off(_e,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let o=this.read();return o===null?t():{done:!1,value:o}};return this.once("end",t),this.once(xd,t),this.once(_e,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[_e])return e?this.emit("error",e):this.emit(_e),this;this[_e]=!0,this[Mt]=!0,this[Xe].length=0,this[Je]=0;let t=this;return typeof t.close=="function"&&!this[Ia]&&t.close(),e?this.emit("error",e):this.emit(_e),this}static get isStream(){return uI}};var PI=RI.native,Bi={lstatSync:TI,readdir:CI,readdirSync:EI,readlinkSync:AI,realpathSync:PI,promises:{lstat:LI,readdir:OI,readlink:kI,realpath:MI}},Yy=n=>!n||n===Bi||n===II?Bi:{...Bi,...n,promises:{...Bi.promises,...n.promises||{}}},Xy=/^\\\\\?\\([a-z]:)\\?$/i,NI=n=>n.replace(/\//g,"\\").replace(Xy,"$1\\"),_I=/[\\\/]/,qt=0,Jy=1,Zy=2,Sn=4,Qy=6,eb=8,kr=10,tb=12,Vt=15,zi=~Vt,Id=16,Gy=32,ji=64,sn=128,Ma=256,_a=512,Vy=ji|sn|_a,FI=1023,Pd=n=>n.isFile()?eb:n.isDirectory()?Sn:n.isSymbolicLink()?kr:n.isCharacterDevice()?Zy:n.isBlockDevice()?Qy:n.isSocket()?tb:n.isFIFO()?Jy:qt,qy=new Map,$i=n=>{let e=qy.get(n);if(e)return e;let t=n.normalize("NFKD");return qy.set(n,t),t},Ky=new Map,Na=n=>{let e=Ky.get(n);if(e)return e;let t=$i(n.toLowerCase());return Ky.set(n,t),t},Fa=class extends Ni{constructor(){super({max:256})}},Od=class extends Ni{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},nb=Symbol("PathScurry setAsCwd"),ut=class{name;root;roots;parent;nocase;isCWD=!1;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#r;get nlink(){return this.#r}#s;get uid(){return this.#s}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#p;get blksize(){return this.#p}#a;get ino(){return this.#a}#l;get size(){return this.#l}#o;get blocks(){return this.#o}#f;get atimeMs(){return this.#f}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#u;get birthtimeMs(){return this.#u}#T;get atime(){return this.#T}#g;get mtime(){return this.#g}#C;get ctime(){return this.#C}#E;get birthtime(){return this.#E}#S;#v;#x;#h;#P;#A;#n;#k;#b;#L;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=qt,r,o,i,s,a){this.name=e,this.#S=i?Na(e):$i(e),this.#n=t&FI,this.nocase=i,this.roots=o,this.root=r||this,this.#k=s,this.#x=a.fullpath,this.#P=a.relative,this.#A=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=Yy(a.fs)}depth(){return this.#v!==void 0?this.#v:this.parent?this.#v=this.parent.depth()+1:this.#v=0}childrenCache(){return this.#k}resolve(e){if(!e)return this;let t=this.getRootString(e),o=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#M(o):this.#M(o)}#M(e){let t=this;for(let r of e)t=t.child(r);return t}children(){let e=this.#k.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#k.set(this,t),this.#n&=~Id,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),o=this.nocase?Na(e):$i(e);for(let l of r)if(l.#S===o)return l;let i=this.parent?this.sep:"",s=this.#x?this.#x+i+e:void 0,a=this.newChild(e,qt,{...t,parent:this,fullpath:s});return this.canReaddir()||(a.#n|=sn),r.push(a),a}relative(){if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let e=this.name,t=this.parent;if(!t)return this.#P=this.name;let r=t.relative();return r+(!r||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#A!==void 0)return this.#A;let e=this.name,t=this.parent;if(!t)return this.#A=this.fullpathPosix();let r=t.relativePosix();return r+(!r||!t.parent?"":"/")+e}fullpath(){if(this.#x!==void 0)return this.#x;let e=this.name,t=this.parent;if(!t)return this.#x=this.name;let o=t.fullpath()+(t.parent?this.sep:"")+e;return this.#x=o}fullpathPosix(){if(this.#h!==void 0)return this.#h;if(this.sep==="/")return this.#h=this.fullpath();if(!this.parent){let o=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(o)?this.#h=`//?/${o}`:this.#h=o}let e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#h=r}isUnknown(){return(this.#n&Vt)===qt}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#n&Vt)===eb}isDirectory(){return(this.#n&Vt)===Sn}isCharacterDevice(){return(this.#n&Vt)===Zy}isBlockDevice(){return(this.#n&Vt)===Qy}isFIFO(){return(this.#n&Vt)===Jy}isSocket(){return(this.#n&Vt)===tb}isSymbolicLink(){return(this.#n&kr)===kr}lstatCached(){return this.#n&Gy?this:void 0}readlinkCached(){return this.#b}realpathCached(){return this.#L}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#b)return!0;if(!this.parent)return!1;let e=this.#n&Vt;return!(e!==qt&&e!==kr||this.#n&Ma||this.#n&sn)}calledReaddir(){return!!(this.#n&Id)}isENOENT(){return!!(this.#n&sn)}isNamed(e){return this.nocase?this.#S===Na(e):this.#S===$i(e)}async readlink(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(t);if(r)return this.#b=r}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(t);if(r)return this.#b=r}catch(t){this.#d(t.code);return}}#N(e){this.#n|=Id;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#_()}}#_(){this.#n&sn||(this.#n=(this.#n|sn)&zi,this.#R())}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#_()}#I(){this.#n|=_a,this.#F()}#F(){if(this.#n&ji)return;let e=this.#n;(e&Vt)===Sn&&(e&=zi),this.#n=e|ji,this.#R()}#D(e=""){e==="ENOTDIR"||e==="EPERM"?this.#F():e==="ENOENT"?this.#_():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#F():e==="ENOENT"&&this.#_()}#d(e=""){let t=this.#n;t|=Ma,e==="ENOENT"&&(t|=sn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=zi),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#F()}#z(e,t){return this.#O(e,t)||this.#B(e,t)}#B(e,t){let r=Pd(e),o=this.newChild(e.name,r,{parent:this}),i=o.#n&Vt;return i!==Sn&&i!==kr&&i!==qt&&(o.#n|=ji),t.unshift(o),t.provisional++,o}#O(e,t){for(let r=t.provisional;r<t.length;r++){let o=t[r];if((this.nocase?Na(e.name):$i(e.name))===o.#S)return this.#j(e,o,r,t)}}#j(e,t,r,o){let i=t.name;return t.#n=t.#n&zi|Pd(e),i!==e.name&&(t.name=e.name),r!==o.provisional&&(r===o.length-1?o.pop():o.splice(r,1),o.unshift(t)),o.provisional++,t}async lstat(){if(!(this.#n&sn))try{return this.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&sn))try{return this.#G(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code)}}#G(e){let{atime:t,atimeMs:r,birthtime:o,birthtimeMs:i,blksize:s,blocks:a,ctime:l,ctimeMs:c,dev:d,gid:p,ino:u,mode:m,mtime:h,mtimeMs:g,nlink:f,rdev:y,size:v,uid:b}=e;this.#T=t,this.#f=r,this.#E=o,this.#u=i,this.#p=s,this.#o=a,this.#C=l,this.#m=c,this.#t=d,this.#w=p,this.#a=u,this.#i=m,this.#g=h,this.#y=g,this.#r=f,this.#c=y,this.#l=v,this.#s=b;let E=Pd(e);this.#n=this.#n&zi|E|Gy,E!==qt&&E!==Sn&&E!==kr&&(this.#n|=ji)}#H=[];#W=!1;#V(e){this.#W=!1;let t=this.#H.slice();this.#H.length=0,t.forEach(r=>r(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#H.push(e),this.#W)return;this.#W=!0;let o=this.fullpath();this.#e.readdir(o,{withFileTypes:!0},(i,s)=>{if(i)this.#D(i.code),r.provisional=0;else{for(let a of s)this.#z(a,r);this.#N(r)}this.#V(r.slice(0,r.provisional))})}#$;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#$)await this.#$;else{let r=()=>{};this.#$=new Promise(o=>r=o);try{for(let o of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#z(o,e);this.#N(e)}catch(o){this.#D(o.code),e.provisional=0}this.#$=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let r of this.#e.readdirSync(t,{withFileTypes:!0}))this.#z(r,e);this.#N(e)}catch(r){this.#D(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&Vy)return!1;let e=Vt&this.#n;return e===qt||e===Sn||e===kr}shouldWalk(e,t){return(this.#n&Sn)===Sn&&!(this.#n&Vy)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((_a|Ma|sn)&this.#n))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}realpathSync(){if(this.#L)return this.#L;if(!((_a|Ma|sn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[nb](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],o=this;for(;o&&o.parent;)t.add(o),o.#P=r.join(this.sep),o.#A=r.join("/"),o=o.parent,r.push("..");for(o=e;o&&o.parent&&!t.has(o);)o.#P=void 0,o.#A=void 0,o=o.parent}},Da=class n extends ut{sep="\\";splitSep=_I;constructor(e,t=qt,r,o,i,s,a){super(e,t,r,o,i,s,a)}newChild(e,t=qt,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return Ld.parse(e).root}getRoot(e){if(e=NI(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,r]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=r;return this.roots[e]=new xo(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Xy,"$1\\"),e===t}},Ua=class n extends ut{splitSep="/";sep="/";constructor(e,t=qt,r,o,i,s,a){super(e,t,r,o,i,s,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=qt,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}},za=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,r,{nocase:o,childrenCacheSize:i=16*1024,fs:s=Bi}={}){this.#r=Yy(s),(e instanceof URL||e.startsWith("file://"))&&(e=xI(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new Fa,this.#t=new Fa,this.#i=new Od(i);let l=a.substring(this.rootPath.length).split(r);if(l.length===1&&!l[0]&&l.pop(),o===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=o,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let c=this.root,d=l.length-1,p=t.sep,u=this.rootPath,m=!1;for(let h of l){let g=d--;c=c.child(h,{relative:new Array(g).fill("..").join(p),relativePosix:new Array(g).fill("..").join("/"),fullpath:u+=(m?"":p)+h}),m=!0}this.cwd=c}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let s=e[i];if(!(!s||s===".")&&(t=t?`${s}/${t}`:s,this.isAbsolute(s)))break}let r=this.#e.get(t);if(r!==void 0)return r;let o=this.cwd.resolve(t).fullpath();return this.#e.set(t,o),o}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let s=e[i];if(!(!s||s===".")&&(t=t?`${s}/${t}`:s,this.isAbsolute(s)))break}let r=this.#t.get(t);if(r!==void 0)return r;let o=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,o),o}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r}=t;if(e.canReaddir()){let o=await e.readdir();return r?o:o.map(i=>i.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0}=t;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(o=>o.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e.withFileTypes,e=this.cwd);let r=await e.readlink();return t?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return t?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e.withFileTypes,e=this.cwd);let r=await e.realpath();return t?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return t?r:r?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=[];(!i||i(e))&&a.push(r?e:e.fullpath());let l=new Set,c=(p,u)=>{l.add(p),p.readdirCB((m,h)=>{if(m)return u(m);let g=h.length;if(!g)return u();let f=()=>{--g===0&&u()};for(let y of h)(!i||i(y))&&a.push(r?y:y.fullpath()),o&&y.isSymbolicLink()?y.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(l,s)?c(v,f):f()):y.shouldWalk(l,s)?c(y,f):f()},!0)},d=e;return new Promise((p,u)=>{c(d,m=>{if(m)return u(m);p(a)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=[];(!i||i(e))&&a.push(r?e:e.fullpath());let l=new Set([e]);for(let c of l){let d=c.readdirSync();for(let p of d){(!i||i(p))&&a.push(r?p:p.fullpath());let u=p;if(p.isSymbolicLink()){if(!(o&&(u=p.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(l,s)&&l.add(u)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t;(!i||i(e))&&(yield r?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let d of c){(!i||i(d))&&(yield r?d:d.fullpath());let p=d;if(d.isSymbolicLink()){if(!(o&&(p=d.realpathSync())))continue;p.isUnknown()&&p.lstatSync()}p.shouldWalk(a,s)&&a.add(p)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new Kn({objectMode:!0});(!i||i(e))&&a.write(r?e:e.fullpath());let l=new Set,c=[e],d=0,p=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){d===0&&a.end();return}d++,l.add(m);let h=(f,y,v=!1)=>{if(f)return a.emit("error",f);if(o&&!v){let b=[];for(let E of y)E.isSymbolicLink()&&b.push(E.realpath().then(x=>x?.isUnknown()?x.lstat():x));if(b.length){Promise.all(b).then(()=>h(null,y,!0));return}}for(let b of y)b&&(!i||i(b))&&(a.write(r?b:b.fullpath())||(u=!0));d--;for(let b of y){let E=b.realpathCached()||b;E.shouldWalk(l,s)&&c.push(E)}u&&!a.flowing?a.once("drain",p):g||p()},g=!0;m.readdirCB(h,!0),g=!1}};return p(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ut||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new Kn({objectMode:!0}),l=new Set;(!i||i(e))&&a.write(r?e:e.fullpath());let c=[e],d=0,p=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){d===0&&a.end();return}d++,l.add(m);let h=m.readdirSync();for(let g of h)(!i||i(g))&&(a.write(r?g:g.fullpath())||(u=!0));d--;for(let g of h){let f=g;if(g.isSymbolicLink()){if(!(o&&(f=g.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(l,s)&&c.push(f)}}u&&!a.flowing&&a.once("drain",p)};return p(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[nb](t)}},xo=class extends za{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Ld,"\\",{...t,nocase:r}),this.nocase=r;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return Ld.parse(e).root.toUpperCase()}newRoot(e){return new Da(this.rootPath,Sn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},To=class extends za{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,vI,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new Ua(this.rootPath,Sn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Hi=class extends To{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},eee=process.platform==="win32"?Da:Ua,rb=process.platform==="win32"?xo:process.platform==="darwin"?Hi:To;var DI=n=>n.length>=1,UI=n=>n.length>=1,Co=class n{#e;#t;#i;length;#r;#s;#w;#c;#p;#a;#l=!0;constructor(e,t,r,o){if(!DI(e))throw new TypeError("empty pattern list");if(!UI(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,r<0||r>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=r,this.#r=o,this.#i===0){if(this.isUNC()){let[i,s,a,l,...c]=this.#e,[d,p,u,m,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let g=[i,s,a,l,""].join("/"),f=[d,p,u,m,""].join("/");this.#e=[g,...c],this.#t=[f,...h],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[i,...s]=this.#e,[a,...l]=this.#t;s[0]===""&&(s.shift(),l.shift());let c=i+"/",d=a+"/";this.#e=[c,...s],this.#t=[d,...l],this.length=this.#e.length}}}pattern(){return this.#e[this.#i]}isString(){return typeof this.#e[this.#i]=="string"}isGlobstar(){return this.#e[this.#i]===ot}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#w=this.#w||(this.#i===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#s!==void 0?this.#s:this.hasMore()?(this.#s=new n(this.#e,this.#t,this.#i+1,this.#r),this.#s.#a=this.#a,this.#s.#p=this.#p,this.#s.#c=this.#c,this.#s):this.#s=null}isUNC(){let e=this.#e;return this.#p!==void 0?this.#p:this.#p=this.#r==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return!(this.#i===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#l?!1:(this.#l=!1,!0)}};var zI=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Eo=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:o,noglobstar:i,platform:s=zI}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=s,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:o,noglobstar:i,optimizationLevel:2,platform:s,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let t=new kt(e,this.mmopts);for(let r=0;r<t.set.length;r++){let o=t.set[r],i=t.globParts[r];if(!o||!i)throw new Error("invalid pattern object");for(;o[0]==="."&&i[0]===".";)o.shift(),i.shift();let s=new Co(o,i,0,this.platform),a=new kt(s.globString(),this.mmopts),l=i[i.length-1]==="**",c=s.isAbsolute();c?this.absolute.push(a):this.relative.push(a),l&&(c?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let t=e.fullpath(),r=`${t}/`,o=e.relative()||".",i=`${o}/`;for(let s of this.relative)if(s.match(o)||s.match(i))return!0;for(let s of this.absolute)if(s.match(t)||s.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let o of this.relativeChildren)if(o.match(r))return!0;for(let o of this.absoluteChildren)if(o.match(t))return!0;return!1}};var kd=class n{store;constructor(e=new Map){this.store=e}copy(){return new n(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let r=e.fullpath(),o=this.store.get(r);o?o.add(t.globString()):this.store.set(r,new Set([t.globString()]))}},Md=class{store=new Map;add(e,t,r){let o=(t?2:0)|(r?1:0),i=this.store.get(e);this.store.set(e,i===void 0?o:o&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Nd=class{store=new Map;add(e,t){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(o=>o.globString()===t.globString())||r.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},Wi=class n{hasWalkedCache;matches=new Md;subwalks=new Nd;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new kd}processPatterns(e,t){this.patterns=t;let r=t.map(o=>[e,o]);for(let[o,i]of r){this.hasWalkedCache.storeWalked(o,i);let s=i.root(),a=i.isAbsolute()&&this.opts.absolute!==!1;if(s){o=o.resolve(s==="/"&&this.opts.root!==void 0?this.opts.root:s);let p=i.rest();if(p)i=p;else{this.matches.add(o,!0,!1);continue}}if(o.isENOENT())continue;let l,c,d=!1;for(;typeof(l=i.pattern())=="string"&&(c=i.rest());)o=o.resolve(l),i=c,d=!0;if(l=i.pattern(),c=i.rest(),d){if(this.hasWalkedCache.hasWalked(o,i))continue;this.hasWalkedCache.storeWalked(o,i)}if(typeof l=="string"){let p=l===".."||l===""||l===".";this.matches.add(o.resolve(l),a,p);continue}else if(l===ot){(!o.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(o,i);let p=c?.pattern(),u=c?.rest();if(!c||(p===""||p===".")&&!u)this.matches.add(o,a,p===""||p===".");else if(p===".."){let m=o.parent||o;u?this.hasWalkedCache.hasWalked(m,u)||this.subwalks.add(m,u):this.matches.add(m,a,!0)}}else l instanceof RegExp&&this.subwalks.add(o,i)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(e,t){let r=this.subwalks.get(e),o=this.child();for(let i of t)for(let s of r){let a=s.isAbsolute(),l=s.pattern(),c=s.rest();l===ot?o.testGlobstar(i,s,c,a):l instanceof RegExp?o.testRegExp(i,l,c,a):o.testString(i,l,c,a)}return o}testGlobstar(e,t,r,o){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,o,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(r&&t.checkFollowGlobstar()?this.subwalks.add(e,r):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),r){let i=r.pattern();if(typeof i=="string"&&i!==".."&&i!==""&&i!==".")this.testString(e,i,r.rest(),o);else if(i===".."){let s=e.parent||e;this.subwalks.add(s,r)}else i instanceof RegExp&&this.testRegExp(e,i,r.rest(),o)}}testRegExp(e,t,r,o){t.test(e.name)&&(r?this.subwalks.add(e,r):this.matches.add(e,o,!1))}testString(e,t,r,o){e.isNamed(t)&&(r?this.subwalks.add(e,r):this.matches.add(e,o,!1))}};var BI=(n,e)=>typeof n=="string"?new Eo([n],e):Array.isArray(n)?new Eo(n,e):n,Ba=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,r){if(this.patterns=e,this.path=t,this.opts=r,this.#i=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#t=BI(r.ignore??[],r),!this.includeChildMatches&&typeof this.#t.add!="function")){let o="cannot ignore child matches, ignore lacks add() method.";throw new Error(o)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#r(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#s(e){return!!this.#t?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let s=await i.realpath();s&&(s.isUnknown()||this.opts.stat)&&await s.lstat()}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#r(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let s=i.realpathSync();s&&(s?.isUnknown()||this.opts.stat)&&s.lstatSync()}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#r(e))return;if(!this.includeChildMatches&&this.#t?.add){let i=`${e.relativePosix()}/**`;this.#t.add(i)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let o=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+o)}else{let i=this.opts.posix?e.relativePosix():e.relative(),s=this.opts.dotRelative&&!i.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(i?s+i+o:"."+o)}}async match(e,t,r){let o=await this.matchCheck(e,r);o&&this.matchFinish(o,t)}matchSync(e,t,r){let o=this.matchCheckSync(e,r);o&&this.matchFinish(o,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new Wi(this.opts),r)}walkCB2(e,t,r,o){if(this.#s(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,o));return}r.processPatterns(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||(i++,this.match(a,l,c).then(()=>s()));for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,r,s):a.readdirCB((c,d)=>this.walkCB3(a,d,r,s),!0)}s()}walkCB3(e,t,r,o){r=r.filterEntries(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||(i++,this.match(a,l,c).then(()=>s()));for(let[a,l]of r.subwalks.entries())i++,this.walkCB2(a,l,r.child(),s);s()}walkCBSync(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new Wi(this.opts),r)}walkCB2Sync(e,t,r,o){if(this.#s(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,o));return}r.processPatterns(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||this.matchSync(a,l,c);for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirSync();this.walkCB3Sync(a,l,r,s)}s()}walkCB3Sync(e,t,r,o){r=r.filterEntries(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||this.matchSync(a,l,c);for(let[a,l]of r.subwalks.entries())i++,this.walkCB2Sync(a,l,r.child(),s);s()}},Gi=class extends Ba{matches=new Set;constructor(e,t,r){super(e,t,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Vi=class extends Ba{results;constructor(e,t,r){super(e,t,r),this.results=new Kn({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var $I=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",an=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=jI(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(l=>l.includes("/")?l:`./**/${l}`)}if(this.pattern=e,this.platform=t.platform||$I,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let l=t.platform==="win32"?xo:t.platform==="darwin"?Hi:t.platform?To:rb;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",o={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(l=>new kt(l,o)),[s,a]=i.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=s.map((l,c)=>{let d=a[c];if(!d)throw new Error("invalid pattern object");return new Co(l,d,0,this.platform)})}async walk(){return[...await new Gi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new Gi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Vi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Vi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var _d=(n,e={})=>{Array.isArray(n)||(n=[n]);for(let t of n)if(new kt(t,e).hasMagic())return!0;return!1};function ja(n,e={}){return new an(n,e).streamSync()}function sb(n,e={}){return new an(n,e).stream()}function Ao(n,e={}){return new an(n,e).walkSync()}async function ob(n,e={}){return new an(n,e).walk()}function $a(n,e={}){return new an(n,e).iterateSync()}function ab(n,e={}){return new an(n,e).iterate()}var HI=ja,WI=Object.assign(sb,{sync:ja}),GI=$a,VI=Object.assign(ab,{sync:$a}),qI=Object.assign(Ao,{stream:ja,iterate:$a}),ib=Object.assign(ob,{glob:ob,globSync:Ao,sync:qI,globStream:sb,stream:WI,globStreamSync:ja,streamSync:HI,globIterate:ab,iterate:VI,globIterateSync:$a,iterateSync:GI,Glob:an,hasMagic:_d,escape:yo,unescape:rn});ib.glob=ib;import tP from"os";import Yn,{dirname as pb}from"path";import{cwd as zd}from"process";import ub from"yaml";import{z as Ie}from"zod";import lb from"fs";import Ha from"path";import KI from"yaml";import{z as Fd}from"zod";var cb=!1,qi=[`**/*.${Cn.TEST}`,`**/*.${Cn.MODULE}`],Dd=Fd.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),Ud=50,YI=Fd.object({fileType:Fd.nativeEnum(be)});function Ze(n,e){let t={project:n,tests:{},modules:{}},r=n.config.include??qi,o=Array.from(n.config.exclude??[]).concat(vm),i=Ao(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:Ud,nodir:!0});for(let s of i)XI(n.rootDir,s,t,e);return cb=!0,t}function XI(n,e,t,r){let o=Ha.join(n,e),i;try{i=lb.readFileSync(o,"utf-8")}catch(p){r.warn(`Could not read possible Momentic file at ${o}, skipping: ${p}`);return}let s;try{if(s=KI.parse(i),typeof s!="object"||s===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(p){r.warn(`Could not parse possible Momentic file at ${o}, skipping: ${p}`);return}let a=YI.safeParse(s);if(a.error){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${a.error}`);return}let l=a.data.fileType,c;try{c=lb.statSync(o)}catch(p){r.warn(`Skipping path '${o}' because it could not be stat, skipping: ${p}`);return}let d={relativePath:e,fullFilePath:o,platformSep:Ha.sep,fullPathSegments:o.split(Ha.sep),fileName:Ha.basename(o),lastModified:c.mtime,createdAt:c.birthtime};switch(l){case be.TEST:try{let p=pn.parse(s);if(t.tests[p.id]){let u=t.tests[p.id].fullFilePath;S.error(`Two tests with the same ID (${p.id}) were found in the same project. Please ensure that all test IDs are unique and avoid copying tests manually. Momentic will ignore the first test when resolving tests.
2977
2977
 
2978
2978
  First test path: ${u}
2979
2979
 
@@ -2985,11 +2985,11 @@ ${i.stack}`),a.status(500).send("Internal Server Error")}),n){let i=_b.static(n)
2985
2985
 
2986
2986
  Using Command Prompt on Windows:
2987
2987
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
2988
- `)}import zL from"events";import zS from"fs";import BL from"open";import pl from"path";import{fileURLToPath as jL}from"url";import KP from"diff-lines";import{gt as YP}from"semver";import{execSync as OP}from"child_process";import{platform as kP}from"os";function Qd(){return zb()?(S.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),S.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),S.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(S.info("Setting device pixel ratio to 1."),S.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),S.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function zb(){return kP()==="darwin"&&OP("system_profiler SPDisplaysDataType").toString().includes("Retina")}function ep(n){zb()&&n===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 MP from"@actions/exec";import NP from"@actions/io";import _P from"quote";import FP from"string-argv";async function Bb(n,e=!0){let t=FP(n),r=await NP.which(t[0],!0),o=t.slice(1),i=MP.exec(_P(r),o,{delay:100});if(e)return i}import{existsSync as DP,statSync as UP}from"fs";var Ya=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Ji(n){try{return DP(n)&&UP(n).isDirectory()}catch(e){return S.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import zP from"csv-parser";import{createReadStream as BP}from"fs";function tp(n){return new Promise((e,t)=>{let r=[];BP(n).pipe(zP()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import Xa from"semver";import{z as Ja}from"zod";var No="1.0.91",jP="https://registry.npmjs.org/momentic",$P=Ja.object({versions:Ja.record(Ja.string(),Ja.unknown()).optional()});async function jb(n){if(!No){n.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await B(fetch(jP),{milliseconds:2e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=$P.parse(i).versions;break}catch(o){n.warn({err:o},"Failed to fetch npm registry data")}if(!e){n.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let r of Object.keys(e))Xa.valid(r)&&(!t||Xa.gt(r,t))&&Xa.gt(r,No)&&Xa.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(S.warn(`Update available: v${No} -> v${t}`),S.warn("This version may be missing critical fixes, features, and security updates."),S.warn(`Run "npx momentic@${t} -V" to update`))}import{existsSync as WP,mkdirSync as GP,statSync as VP}from"fs";import{dirname as qP}from"path";import Hb from"readline/promises";import{hostname as HP}from"os";var H=Wa({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:HP(),disableConsoleLogs:!0}).child({version:"1.0.91"});var np=!1,Wb=(()=>{try{return VP("/.dockerenv"),!0}catch{return!1}})();async function it(n,e){if(Ya||np||Wb)return!0;H.flush(),await new Promise(s=>setTimeout(s,500));let t=Hb.createInterface({input:process.stdin,output:process.stdout}),r=n.split("."),o;if(r.length===1)o=n;else{let s=`${r.slice(0,r.length-1).join(".").trim()}.`;e?S.warn(s):S.log(s),o=r[r.length-1].trim()}let i=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),i==="A"?(np=!0,setTimeout(()=>{np=!1},3e3),!0):i.toLowerCase()==="y"}async function rp(n){let e=qP(n);return Ji(e)?WP(n)?it(`File '${$b(n)}' already exists. Overwrite existing content?`,!0):!0:await it(`Directory '${$b(e)}' doesn't exist. Create it now?`,!0)?(GP(e,{recursive:!0}),!0):!1}function $b(n){return n.replace(/(\s+)/g,"\\$1")}async function Gb(n,e){if(Ya||Wb)return e;let t=Hb.createInterface({input:process.stdin,output:process.stdout}),r=await t.question(`${n} `);return t.close(),r.trim()||e}async function Vb({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){YP(e.schemaVersion,mt)&&(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)),sh(e.steps).forEach(g=>{t.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&&!i&&!await it("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let a=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<a&&!i&&!await it("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=gd(n.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${n.fullFilePath} is missing steps array`);let d,p;if(e.schemaVersion!==mt){let{steps:g,newVersion:f}=await yi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:S});d=f,p=Ae.array().parse(g)}else p=Ae.array().parse(e.steps);let{stepsToSave:u,moduleUpdates:m}=await Lt({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=KP(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});S.dimmed("=".repeat(30)),S.dimmed(h),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.`),!i&&!await it("Do you want to apply this patch?")&&(S.dimmed("Cancelled."),process.exit(1)),Pi(n.relativePath,u,d??e.schemaVersion,t.project),S.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{cloneDeep as XP}from"lodash-es";async function Za({client:n,skipPrompts:e,project:t}){let r=await n.getAllEnvironments(),o=XP(t.config);o.environments||(o.environments=[]);for(let i of r){let s=o.environments?.find(a=>a.name===i.name);if(s)!e&&!await it(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),s.baseUrl=i.variables[ve],delete i.variables[ve],s.envVariables=i.variables;else{let a=i.variables[ve];delete i.variables[ve],o.environments.push({name:i.name,baseUrl:a,envVariables:i.variables})}}Io(o,t.configFilePath),S.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as qb}from"crypto";import Kb from"fs";async function Xb({testsToFetch:n,client:e,all:t,yes:r}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:n,all:t}),s=0;for(let[l,c]of Object.entries(o)){let d=Yb(l,be.TEST);!r&&!await rp(d)||(s+=1,Kb.writeFileSync(d,c,"utf-8"),H.info({checksum:qb("md5").update(c).digest("hex")},`Wrote '${d}'`))}let a=0;for(let[l,c]of Object.entries(i)){let d=Yb(l,be.MODULE);!r&&!await rp(d)||(a+=1,Kb.writeFileSync(d,c,"utf-8"),H.info({checksum:qb("md5").update(c).digest("hex")},`Wrote '${d}'`))}s===0?S.success("Pulled 0 tests."):S.success(`Pulled ${s} test${s>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function Yb(n,e){switch(e){case be.TEST:return`${Me(n)}.${Cn.TEST}`;case be.MODULE:return`${Me(n)}.${Cn.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function Jb(n){let{project:e,client:t,skipPrompts:r}=n;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 it("Are you sure you want to proceed?",!0)||(S.info("Aborting..."),process.exit(1)),await Za({client:t,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 Xb({testsToFetch:[],client:t,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.")}import Nt from"fs";import Nr from"path";import JP from"yaml";function Zb(){Ji("momentic")||(S.error(`The migration command should be ran from the v0 root Momentic directory, which should contain a folder called 'momentic'. No folder named 'momentic' was found in the current working directory (${process.cwd()}).`),process.exit(1));let n={name:"default",include:qi,environments:[]};S.info("Migrating environments");let e=Qb(["momentic/environments"],ZP);for(let r of e){let o=JP.parse(Nt.readFileSync(r,"utf-8"));try{let i=bs.parse(o),s=i.variables[ve]??"";delete i.variables[ve],n.environments?.push({name:i.name,baseUrl:s,envVariables:i.variables})}catch(i){S.error(`${r} failed to parse as a valid environment file.`),S.error(i),process.exit(1)}}S.info("Migrating tests");let t=hd("./momentic",S);for(let r of t){let o=Nr.join(...r.fullPathSegments),i=Nr.join(Nr.dirname(o),`${r.fileName.slice(0,-5)}.test.yaml`);S.info(`Moving test ${o} to ${i}`),Nt.renameSync(o,i)}if(Ji("momentic/modules")){S.info("Migrating modules");for(let r of Nt.readdirSync("./momentic/modules")){if(!r.endsWith(".yaml"))continue;let o=Nr.resolve(Nr.join("./momentic/modules",r));if(!Nt.readFileSync(o,"utf-8").includes("schemaVersion")){S.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let s=`${o.slice(0,-5)}.module.yaml`;S.info(`Moving module ${o} to ${s}`),Nt.renameSync(o,s)}}return S.info("Writing new project configuration file"),Io(n,"momentic.config.yaml"),Nt.rmSync("./momentic/environments",{recursive:!0,force:!0}),Nt.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),S.success("Migration succeeded!"),S.info("Going forward:"),S.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),S.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),n}function Qb(n,e,t=new Set){for(let r of n){let o=Nr.resolve(r),i=!1;try{i=Nt.existsSync(o)&&Nt.statSync(o).isDirectory()}catch(s){S.error({err:s},`Error reading path ${o} during collect paths`)}if(o&&i){let s=Nt.readdirSync(o).map(a=>Nr.join(o,a));Qb(s,e,t);continue}if(o.endsWith(".yaml")){try{if(!Nt.existsSync(o)||!Nt.statSync(o).isFile()){S.warn(`File not found or unreadable: ${o}`);continue}}catch(s){S.error({err:s},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function ZP(n){return n.endsWith(".yaml")?Nt.readFileSync(n,"utf8").includes("momentic/environment")?!0:(S.warn(`Skipping YAML that is not a Momentic environment: ${n}`),!1):!1}import{Argument as Qa,Option as Ue}from"@commander-js/extra-typings";import{validateHeaderValue as QP}from"http";import{cpus as eS}from"os";import{parse as cie}from"yaml";import{z as W}from"zod";var el=58888,op=30*60*1e3,Xn=new Ue("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),_r=new Ue("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Jn=new Ue("-y, --yes","Skip all confirmation prompts."),ip=new Ue("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),sp=new Ue("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${op/1e3} seconds.`),tl=new Ue("--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."),ap=new Ue("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),nS=new Ue("--reporter <reporter>","Output report files in a standardized format to a local directory. See the --reporter-dir flag for information on the output directory.").choices(Object.values(Ls)),rS=new Ue("--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. Defaults to 'reports' if unset."),oS=new Ue("--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."),iS=new Ue("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),lp=new Ue("--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."),sS=new Ue("--port <port>",`Port to run the app on. Defaults to ${el}.`),cp=new Ue("--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."),nl=new Ue("--env <env>","Name of the environment to use when running tests."),rl=new Ue("--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."),aS=new Ue("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),Fr=new Ue("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),dp=new Ue("-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."),lS=new Ue("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),cS=new Qa("<tests...>",`One or more test paths to queue on Momentic Cloud.
2988
+ `)}import zL from"events";import zS from"fs";import BL from"open";import pl from"path";import{fileURLToPath as jL}from"url";import KP from"diff-lines";import{gt as YP}from"semver";import{execSync as OP}from"child_process";import{platform as kP}from"os";function Qd(){return zb()?(S.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),S.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),S.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(S.info("Setting device pixel ratio to 1."),S.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),S.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function zb(){return kP()==="darwin"&&OP("system_profiler SPDisplaysDataType").toString().includes("Retina")}function ep(n){zb()&&n===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 MP from"@actions/exec";import NP from"@actions/io";import _P from"quote";import FP from"string-argv";async function Bb(n,e=!0){let t=FP(n),r=await NP.which(t[0],!0),o=t.slice(1),i=MP.exec(_P(r),o,{delay:100});if(e)return i}import{existsSync as DP,statSync as UP}from"fs";var Ya=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Ji(n){try{return DP(n)&&UP(n).isDirectory()}catch(e){return S.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import zP from"csv-parser";import{createReadStream as BP}from"fs";function tp(n){return new Promise((e,t)=>{let r=[];BP(n).pipe(zP()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import Xa from"semver";import{z as Ja}from"zod";var No="1.0.92",jP="https://registry.npmjs.org/momentic",$P=Ja.object({versions:Ja.record(Ja.string(),Ja.unknown()).optional()});async function jb(n){if(!No){n.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await B(fetch(jP),{milliseconds:2e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=$P.parse(i).versions;break}catch(o){n.warn({err:o},"Failed to fetch npm registry data")}if(!e){n.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let r of Object.keys(e))Xa.valid(r)&&(!t||Xa.gt(r,t))&&Xa.gt(r,No)&&Xa.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(S.warn(`Update available: v${No} -> v${t}`),S.warn("This version may be missing critical fixes, features, and security updates."),S.warn(`Run "npx momentic@${t} -V" to update`))}import{existsSync as WP,mkdirSync as GP,statSync as VP}from"fs";import{dirname as qP}from"path";import Hb from"readline/promises";import{hostname as HP}from"os";var H=Wa({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:HP(),disableConsoleLogs:!0}).child({version:"1.0.92"});var np=!1,Wb=(()=>{try{return VP("/.dockerenv"),!0}catch{return!1}})();async function it(n,e){if(Ya||np||Wb)return!0;H.flush(),await new Promise(s=>setTimeout(s,500));let t=Hb.createInterface({input:process.stdin,output:process.stdout}),r=n.split("."),o;if(r.length===1)o=n;else{let s=`${r.slice(0,r.length-1).join(".").trim()}.`;e?S.warn(s):S.log(s),o=r[r.length-1].trim()}let i=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),i==="A"?(np=!0,setTimeout(()=>{np=!1},3e3),!0):i.toLowerCase()==="y"}async function rp(n){let e=qP(n);return Ji(e)?WP(n)?it(`File '${$b(n)}' already exists. Overwrite existing content?`,!0):!0:await it(`Directory '${$b(e)}' doesn't exist. Create it now?`,!0)?(GP(e,{recursive:!0}),!0):!1}function $b(n){return n.replace(/(\s+)/g,"\\$1")}async function Gb(n,e){if(Ya||Wb)return e;let t=Hb.createInterface({input:process.stdin,output:process.stdout}),r=await t.question(`${n} `);return t.close(),r.trim()||e}async function Vb({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){YP(e.schemaVersion,mt)&&(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)),sh(e.steps).forEach(g=>{t.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&&!i&&!await it("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let a=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<a&&!i&&!await it("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=gd(n.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${n.fullFilePath} is missing steps array`);let d,p;if(e.schemaVersion!==mt){let{steps:g,newVersion:f}=await yi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:S});d=f,p=Ae.array().parse(g)}else p=Ae.array().parse(e.steps);let{stepsToSave:u,moduleUpdates:m}=await Lt({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=KP(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});S.dimmed("=".repeat(30)),S.dimmed(h),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.`),!i&&!await it("Do you want to apply this patch?")&&(S.dimmed("Cancelled."),process.exit(1)),Pi(n.relativePath,u,d??e.schemaVersion,t.project),S.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{cloneDeep as XP}from"lodash-es";async function Za({client:n,skipPrompts:e,project:t}){let r=await n.getAllEnvironments(),o=XP(t.config);o.environments||(o.environments=[]);for(let i of r){let s=o.environments?.find(a=>a.name===i.name);if(s)!e&&!await it(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),s.baseUrl=i.variables[ve],delete i.variables[ve],s.envVariables=i.variables;else{let a=i.variables[ve];delete i.variables[ve],o.environments.push({name:i.name,baseUrl:a,envVariables:i.variables})}}Io(o,t.configFilePath),S.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as qb}from"crypto";import Kb from"fs";async function Xb({testsToFetch:n,client:e,all:t,yes:r}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:n,all:t}),s=0;for(let[l,c]of Object.entries(o)){let d=Yb(l,be.TEST);!r&&!await rp(d)||(s+=1,Kb.writeFileSync(d,c,"utf-8"),H.info({checksum:qb("md5").update(c).digest("hex")},`Wrote '${d}'`))}let a=0;for(let[l,c]of Object.entries(i)){let d=Yb(l,be.MODULE);!r&&!await rp(d)||(a+=1,Kb.writeFileSync(d,c,"utf-8"),H.info({checksum:qb("md5").update(c).digest("hex")},`Wrote '${d}'`))}s===0?S.success("Pulled 0 tests."):S.success(`Pulled ${s} test${s>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function Yb(n,e){switch(e){case be.TEST:return`${Me(n)}.${Cn.TEST}`;case be.MODULE:return`${Me(n)}.${Cn.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function Jb(n){let{project:e,client:t,skipPrompts:r}=n;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 it("Are you sure you want to proceed?",!0)||(S.info("Aborting..."),process.exit(1)),await Za({client:t,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 Xb({testsToFetch:[],client:t,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.")}import Nt from"fs";import Nr from"path";import JP from"yaml";function Zb(){Ji("momentic")||(S.error(`The migration command should be ran from the v0 root Momentic directory, which should contain a folder called 'momentic'. No folder named 'momentic' was found in the current working directory (${process.cwd()}).`),process.exit(1));let n={name:"default",include:qi,environments:[]};S.info("Migrating environments");let e=Qb(["momentic/environments"],ZP);for(let r of e){let o=JP.parse(Nt.readFileSync(r,"utf-8"));try{let i=bs.parse(o),s=i.variables[ve]??"";delete i.variables[ve],n.environments?.push({name:i.name,baseUrl:s,envVariables:i.variables})}catch(i){S.error(`${r} failed to parse as a valid environment file.`),S.error(i),process.exit(1)}}S.info("Migrating tests");let t=hd("./momentic",S);for(let r of t){let o=Nr.join(...r.fullPathSegments),i=Nr.join(Nr.dirname(o),`${r.fileName.slice(0,-5)}.test.yaml`);S.info(`Moving test ${o} to ${i}`),Nt.renameSync(o,i)}if(Ji("momentic/modules")){S.info("Migrating modules");for(let r of Nt.readdirSync("./momentic/modules")){if(!r.endsWith(".yaml"))continue;let o=Nr.resolve(Nr.join("./momentic/modules",r));if(!Nt.readFileSync(o,"utf-8").includes("schemaVersion")){S.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let s=`${o.slice(0,-5)}.module.yaml`;S.info(`Moving module ${o} to ${s}`),Nt.renameSync(o,s)}}return S.info("Writing new project configuration file"),Io(n,"momentic.config.yaml"),Nt.rmSync("./momentic/environments",{recursive:!0,force:!0}),Nt.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),S.success("Migration succeeded!"),S.info("Going forward:"),S.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),S.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),n}function Qb(n,e,t=new Set){for(let r of n){let o=Nr.resolve(r),i=!1;try{i=Nt.existsSync(o)&&Nt.statSync(o).isDirectory()}catch(s){S.error({err:s},`Error reading path ${o} during collect paths`)}if(o&&i){let s=Nt.readdirSync(o).map(a=>Nr.join(o,a));Qb(s,e,t);continue}if(o.endsWith(".yaml")){try{if(!Nt.existsSync(o)||!Nt.statSync(o).isFile()){S.warn(`File not found or unreadable: ${o}`);continue}}catch(s){S.error({err:s},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function ZP(n){return n.endsWith(".yaml")?Nt.readFileSync(n,"utf8").includes("momentic/environment")?!0:(S.warn(`Skipping YAML that is not a Momentic environment: ${n}`),!1):!1}import{Argument as Qa,Option as Ue}from"@commander-js/extra-typings";import{validateHeaderValue as QP}from"http";import{cpus as eS}from"os";import{parse as aie}from"yaml";import{z as W}from"zod";var el=58888,op=30*60*1e3,Xn=new Ue("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),_r=new Ue("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Jn=new Ue("-y, --yes","Skip all confirmation prompts."),ip=new Ue("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),sp=new Ue("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${op/1e3} seconds.`),tl=new Ue("--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."),ap=new Ue("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),nS=new Ue("--reporter <reporter>","Output report files in a standardized format to a local directory. See the --reporter-dir flag for information on the output directory.").choices(Object.values(Ls)),rS=new Ue("--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. Defaults to 'reports' if unset."),oS=new Ue("--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."),iS=new Ue("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),lp=new Ue("--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."),sS=new Ue("--port <port>",`Port to run the app on. Defaults to ${el}.`),cp=new Ue("--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."),nl=new Ue("--env <env>","Name of the environment to use when running tests."),rl=new Ue("--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."),aS=new Ue("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),Fr=new Ue("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),dp=new Ue("-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."),lS=new Ue("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),cS=new Qa("<tests...>",`One or more test paths to queue on Momentic Cloud.
2989
2989
 
2990
2990
  A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic@latest pull hello-world'.`),dS=new Qa("<tests...>","One or more test file path or folders that exist on the local machine: 'npx momentic@latest run hello-world.test.yaml'.").argOptional(),pS=new Qa("<suites...>",`One or more suite paths that exist on Momentic Cloud.
2991
2991
 
2992
- The suite path is a lowercased version of your suite name where spaces and special characters are replaced with dashes, such as 'production-tests'.`),uie=new Qa("<envs...>","One or more environment names to push").argOptional(),tS=W.object({apiKey:W.preprocess(n=>n!==void 0?n:process.env.MOMENTIC_API_KEY,W.string()),server:W.string().default("https://api.momentic.ai"),config:W.string().optional(),filter:W.string().optional(),yes:W.preprocess(n=>process.env.CI?!0:n,W.boolean().optional()),pixelRatio:W.coerce.number().optional(),port:W.coerce.number().default(el).optional(),wait:W.preprocess(n=>!!n,W.boolean()).optional(),waitTimeout:W.coerce.number().optional(),start:W.string().optional(),waitOn:W.string().optional(),waitOnTimeout:W.coerce.number().default(60).optional(),customHeaders:W.string().array().optional(),env:W.string().optional(),urlOverride:W.string().url().optional(),all:W.boolean().optional(),parallel:W.coerce.number().optional(),retries:W.coerce.number().optional(),shardIndex:W.coerce.number().optional(),shardCount:W.coerce.number().optional(),inputCsv:W.string().optional(),updateGoldenFiles:W.boolean().optional().default(!1),tests:W.array(W.string()).optional(),suites:W.array(W.string()).optional(),paths:W.array(W.string()).optional(),envs:W.array(W.string()).optional(),include:W.array(W.string()).optional(),exclude:W.array(W.string()).optional(),labels:W.array(W.string()).optional(),report:W.preprocess(()=>!!process.env.CI,W.boolean().optional()),reporter:W.union([W.literal("junit"),W.literal("allure")]).optional(),reporterDir:W.string().optional()}),Zn=async n=>{let e={},t;try{let r=Object.assign(e,tS.partial().parse(n));t=tS.parse(r)}catch(r){S.error(`Error parsing command line arguments: ${r.message}`),process.exit(1)}try{eL(t)}catch(r){S.error(`Invalid command line arguments: ${r.message}`),process.exit(1)}return t};var eL=n=>{for(let[e,t]of Object.entries(n))switch(e){case"shardIndex":if(!n.shardCount)throw new Error("The --shard-count flag must be provided alongside --shard-index");if(n.shardCount&&n.shardIndex&&n.shardIndex>n.shardCount)throw new Error("Shard index cannot be greater than shard count");if(n.shardIndex!==void 0&&n.shardIndex<1)throw new Error("Shard index must be greater than 0");break;case"waitTimeout":case"pixelRatio":try{n[e]=W.number().int().optional().parse(t)}catch{throw new Error(`Invalid ${e} provided does not parse a number: ${t}`)}break;case"urlOverride":if(t===void 0)break;try{W.string().url().parse(t)}catch(r){throw new Error(`Invalid URL provided for ${e}`,{cause:r})}break;case"server":if(typeof t!="string")throw new Error(`Expected a string for ${e}`);if(!t.startsWith("http"))throw new Error("--server option must be a fully qualified URL beginning with http");break;case"parallel":if(t===void 0)break;if(typeof t!="number"||isNaN(t))throw new Error(`Expected a number for ${e}`);eS().length<t*2&&S.warn(`You requested to run tests in parallel ${t} at a time on a machine with ${eS().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`);break;default:break}};function ol(n){if(n===void 0)return;let e={};for(let t of n){let r=t.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,r),i=t.slice(r+1);QP(o,i),e[o]=i}return e}import nL from"fs";import{tmpdir as rL}from"os";import oL from"path";import{registry as il}from"playwright-core/lib/server";import uS from"proper-lockfile";var mS=oL.join(rL(),"momenticBrowserInstallation"),pp=["chrome","chromium"];function hS(n){let e=n.executablePath();return nL.existsSync(e)}function iL(n,e){let t=[],r=[];for(let o of n){let i=il.findExecutable(o);if(!i||i.installType==="none")t.push(o);else{if(!e&&hS(i))return[];r.push(i)}}return r}async function sL(n,e){let t=iL([n],e);if(!t.length){S.debug(`Browser '${n}' is already installed, skipping...`);return}S.info(`Installing browser '${n}'...`);try{await il.installDeps(t,!1),await il.install(t,!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=il.findExecutable(n),i=5*60*1e3,s=Date.now();for(;Date.now()-s<i&&!hS(o);)S.info("Waiting for browser to finish installing..."),await new Promise(a=>setTimeout(a,5e3))}else throw r}}function gS(n){for(let e of n)pp.includes(e)||(S.error(`Got invalid browser ${e} to install`),process.exit(1));return Array.from(new Set(n))}async function Dr(n,e=!1){try{await uS.lock(mS,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(t){S.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${t}. Continuing without installation...`);return}try{for(let t of n)try{await sL(t,e)}catch(r){S.error(`Failed to install the ${t} browser: ${r}`)}}finally{await uS.unlock(mS,{realpath:!1})}}async function up(n){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(S.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),S.debug(`Identified node version ${e}`);let r=await n.client.getAuthInfo();return S.debug("Got auth info from API"),n.installBrowsers&&(await Dr(["chromium"]),S.debug("Installed Chromium browser")),r}import bS from"chalk";import{Console as fS}from"console";import{format as Zi}from"util";var mp=class extends Error{constructor(e,t,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},sl=class n extends fS{_buffer=[];_groupDepth=0;Console=fS;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new mp(void 0,n.write).stack;if(!i)return e;let s=i.split(`
2992
+ The suite path is a lowercased version of your suite name where spaces and special characters are replaced with dashes, such as 'production-tests'.`),die=new Qa("<envs...>","One or more environment names to push").argOptional(),tS=W.object({apiKey:W.preprocess(n=>n!==void 0?n:process.env.MOMENTIC_API_KEY,W.string()),server:W.string().default("https://api.momentic.ai"),config:W.string().optional(),filter:W.string().optional(),yes:W.preprocess(n=>process.env.CI?!0:n,W.boolean().optional()),pixelRatio:W.coerce.number().optional(),port:W.coerce.number().default(el).optional(),wait:W.preprocess(n=>!!n,W.boolean()).optional(),waitTimeout:W.coerce.number().optional(),start:W.string().optional(),waitOn:W.string().optional(),waitOnTimeout:W.coerce.number().default(60).optional(),customHeaders:W.string().array().optional(),env:W.string().optional(),urlOverride:W.string().url().optional(),all:W.boolean().optional(),parallel:W.coerce.number().optional(),retries:W.coerce.number().optional(),shardIndex:W.coerce.number().optional(),shardCount:W.coerce.number().optional(),inputCsv:W.string().optional(),updateGoldenFiles:W.boolean().optional().default(!1),tests:W.array(W.string()).optional(),suites:W.array(W.string()).optional(),paths:W.array(W.string()).optional(),envs:W.array(W.string()).optional(),include:W.array(W.string()).optional(),exclude:W.array(W.string()).optional(),labels:W.array(W.string()).optional(),report:W.preprocess(()=>!!process.env.CI,W.boolean().optional()),reporter:W.union([W.literal("junit"),W.literal("allure")]).optional(),reporterDir:W.string().optional()}),Zn=async n=>{let e={},t;try{let r=Object.assign(e,tS.partial().parse(n));t=tS.parse(r)}catch(r){S.error(`Error parsing command line arguments: ${r.message}`),process.exit(1)}try{eL(t)}catch(r){S.error(`Invalid command line arguments: ${r.message}`),process.exit(1)}return t};var eL=n=>{for(let[e,t]of Object.entries(n))switch(e){case"shardIndex":if(!n.shardCount)throw new Error("The --shard-count flag must be provided alongside --shard-index");if(n.shardCount&&n.shardIndex&&n.shardIndex>n.shardCount)throw new Error("Shard index cannot be greater than shard count");if(n.shardIndex!==void 0&&n.shardIndex<1)throw new Error("Shard index must be greater than 0");break;case"waitTimeout":case"pixelRatio":try{n[e]=W.number().int().optional().parse(t)}catch{throw new Error(`Invalid ${e} provided does not parse a number: ${t}`)}break;case"urlOverride":if(t===void 0)break;try{W.string().url().parse(t)}catch(r){throw new Error(`Invalid URL provided for ${e}`,{cause:r})}break;case"server":if(typeof t!="string")throw new Error(`Expected a string for ${e}`);if(!t.startsWith("http"))throw new Error("--server option must be a fully qualified URL beginning with http");break;case"parallel":if(t===void 0)break;if(typeof t!="number"||isNaN(t))throw new Error(`Expected a number for ${e}`);eS().length<t*2&&S.warn(`You requested to run tests in parallel ${t} at a time on a machine with ${eS().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`);break;default:break}};function ol(n){if(n===void 0)return;let e={};for(let t of n){let r=t.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,r),i=t.slice(r+1);QP(o,i),e[o]=i}return e}import nL from"fs";import{tmpdir as rL}from"os";import oL from"path";import{registry as il}from"playwright-core/lib/server";import uS from"proper-lockfile";var mS=oL.join(rL(),"momenticBrowserInstallation"),pp=["chrome","chromium"];function hS(n){let e=n.executablePath();return nL.existsSync(e)}function iL(n,e){let t=[],r=[];for(let o of n){let i=il.findExecutable(o);if(!i||i.installType==="none")t.push(o);else{if(!e&&hS(i))return[];r.push(i)}}return r}async function sL(n,e){let t=iL([n],e);if(!t.length){S.debug(`Browser '${n}' is already installed, skipping...`);return}S.info(`Installing browser '${n}'...`);try{await il.installDeps(t,!1),await il.install(t,!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=il.findExecutable(n),i=5*60*1e3,s=Date.now();for(;Date.now()-s<i&&!hS(o);)S.info("Waiting for browser to finish installing..."),await new Promise(a=>setTimeout(a,5e3))}else throw r}}function gS(n){for(let e of n)pp.includes(e)||(S.error(`Got invalid browser ${e} to install`),process.exit(1));return Array.from(new Set(n))}async function Dr(n,e=!1){try{await uS.lock(mS,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(t){S.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${t}. Continuing without installation...`);return}try{for(let t of n)try{await sL(t,e)}catch(r){S.error(`Failed to install the ${t} browser: ${r}`)}}finally{await uS.unlock(mS,{realpath:!1})}}async function up(n){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(S.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),S.debug(`Identified node version ${e}`);let r=await n.client.getAuthInfo();return S.debug("Got auth info from API"),n.installBrowsers&&(await Dr(["chromium"]),S.debug("Installed Chromium browser")),r}import bS from"chalk";import{Console as fS}from"console";import{format as Zi}from"util";var mp=class extends Error{constructor(e,t,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},sl=class n extends fS{_buffer=[];_groupDepth=0;Console=fS;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new mp(void 0,n.write).stack;if(!i)return e;let s=i.split(`
2993
2993
  `).slice(o).filter(Boolean).join(`
2994
2994
  `);return e.push({message:r,origin:s,type:t}),e}_log(e,t){n.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",Zi(e,...t))}error(e,...t){this._log("error",Zi(e,...t))}info(e,...t){this._log("info",Zi(e,...t))}log(e,...t){this._log("log",Zi(e,...t))}warn(e,...t){this._log("warn",Zi(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function yS(n){let e=globalThis.console,t=new sl;globalThis.console=t;try{n()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
2995
2995
  `);process.stderr.write(`${o}
@@ -3000,6 +3000,6 @@ ${n.map(p=>` - ${p}`).join(`
3000
3000
  ${n.map(p=>` - ${p}`).join(`
3001
3001
  `)}`),Object.values(e.tests).forEach(p=>{n.some(u=>p.relativePath.includes(u))&&a.add(p.fullFilePath)}))}else{!r&&!await it("No test paths or substrings were provided. Do you want to run all tests?")&&(S.error("Cancelled by user."),process.exit(1));let c=Object.values(e.tests);S.info(`Reading all ${c.length} tests in the project from local disk.`),c.forEach(d=>{a.add(d.fullFilePath)})}for(let c of a){let d=yp.relative(t.rootDir,c);o&&!o.some(p=>new RegExp(p).test(d))&&a.delete(c),i&&i.some(p=>new RegExp(p).test(d))&&a.delete(c)}let l=Array.from(a).map(async c=>{try{let d=await Ca(c,H,e);if(AL.gt(d.schemaVersion,mt)&&S.warn(`Test ${c} has schema version ${d.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),d.disabled)return null;if(s&&s.length>0){let p=d.labels||[];if(!s.some(m=>p.includes(m)))return null}return{...d,fullFilePath:c,relativeFilePath:yp.relative(t.rootDir,c)}}catch(d){S.error(`Failed to read and resolve test at '${c}': ${d}`),process.exit(1)}});return Promise.all(l).then(CL)}import{randomUUID as LL}from"crypto";import{cloneDeep as _S}from"lodash-es";async function LS({orgId:n,codeEvalTools:e,logger:t,outputDefinitions:r,testContext:o}){let i={};for(let s of r){let{name:a,value:l}=s;i[a]=await Ot({orgId:n,s:l,localTools:e,logger:t,context:o})}return i}async function OS({baseUrl:n,envName:e,devicePixelRatio:t,apiClient:r,test:o,storageClient:i,codeEvalTools:s,generator:a,orgId:l,variables:c,logger:d,customHeaders:p,testInputs:u,analytics:m,localBrowserConfig:h,visualDiffScreenshotStorage:g}){let f=await aa({advanced:{...h,...o.advanced},customHeaders:p,envVariables:c,envName:e,baseUrl:n,logger:d,localTools:s,orgId:l}),y=await co.init(l),v={baseUrl:r.baseUrl,apiKey:r.apiKey,logger:H};f.browserType==="Google Chrome"&&await Dr(["chrome"]);let b;try{b=await tn.init({baseUrl:n,logger:d,userBrowserSettings:f,storage:i,flagStore:y,enricher:new Tr(v),contextArgs:{viewport:o.advanced.viewport??Xt,deviceScaleFactor:t}})}catch(C){let L=C.message;if(L.includes("Executable doesn't exist")||L.includes("install your dependencies"))S.error("The headless browser used by Momentic is not installed correctly. Re-installing the necessary dependencies before starting the test. We strongly recommend installing browsers correctly before execution."),await Dr(pp,!0),b=await tn.init({baseUrl:n,logger:d,userBrowserSettings:f,storage:i,flagStore:y,enricher:new Tr(v),contextArgs:{viewport:o.advanced.viewport??Xt,deviceScaleFactor:t}});else throw C}let E=new go({browser:b,generator:a,logger:d,orgId:l,scratchPadId:void 0,storage:i,flagStore:y,localCodeEvalTools:s,visualDiffScreenshotStorage:g,analytics:m}),x=new Tt({baseUrl:n,currentUrl:E.browser.url(),variablesFromEnvironment:c,envName:e});return o.parameters&&await Promise.all(o.parameters.map(async C=>{let{name:L,defaultValue:N,required:P}=C,U=u?.[L];P&&U===void 0&&(S.error(`Required parameter '${L}' is required by test '${o.name}' but not provided`),process.exit(1));let $=await Ot({orgId:l,s:U??N,localTools:s,logger:d,context:Tt.dummyContext(x.getEnvName())});x.setMomenticSystemVariable(L,$)})),{controller:E,context:x,flagStore:y}}import{randomUUID as RL}from"crypto";import{diff as IL}from"deep-object-diff";import{cloneDeep as MS}from"lodash-es";import{debounce as PL}from"ts-debounce";async function kS({testId:n,apiClient:e,testAdvancedSettings:t,aiSettingsFromEnv:r,logger:o,noReport:i}){if(i)return o.debug("The CLI is not running in a CI environment or --no-report was explicitly passed"),!1;if(t.failureRecovery===!1||t.failureRecovery===void 0&&!r?.failureRecovery)return!1;let s;try{s=await e.getPastTestResults(n,{afterTime:Date.now()-7*24*60*60*1e3})}catch(l){return o.error({err:l},"Test is not eligible for recovery since we failed to fetch the recent test results"),!1}return s.some(l=>l.status==="PASSED")?!0:(o.debug({recentRuns:s},"Test is not eligible for recovery because there are only failures in the past 7 days"),!1)}async function NS({attemptInputs:n,attemptFixtures:e,attemptMetadata:t}){let{attemptNumber:r,orgId:o,runId:i,runAttemptId:s}=t,{controller:a,context:l,flagStore:c,analytics:d,codeEvalTools:p,storageClient:u,debugDataClient:m,logger:h,apiClient:g,billingReporter:f}=e,{test:y,orgSettings:v,noReport:b}=n;h.info(`Running test '${y.name}' locally${b?"":` and reporting results to https://app.momentic.ai/runs/${i}`}`);let E=MS({steps:y.steps,beforeSteps:y.beforeSteps,afterSteps:y.afterSteps}),x=async k=>{if(!(b||!i))try{if(k.results){let I=MS(k.results);Vs(I,h),k.results=I}await g.updateRun(i,{...k,updatedAt:new Date})}catch(I){h.warn({err:I},"Failed to update run data. You may see stale data on the Momentic Cloud Server.")}},C=PL(async k=>{b||await x(k)},1e4,{maxWait:3e4}),L=async k=>{try{await C(k)}catch{}},N={controller:a,storage:u,debugDataStorage:m,billingReporter:f,analytics:d,context:l,logger:h,codeEvalTools:p},P={orgId:o,runId:i||RL(),runAttemptId:s,testMetadata:y,steps:y.steps,beforeSteps:y.beforeSteps,afterSteps:y.afterSteps},U={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await kS({noReport:b,currentAttempt:r,testId:y.id,flagStore:c,apiClient:g,testAdvancedSettings:y.advanced,aiSettingsFromEnv:v.ai,logger:h})},$={step:{},test:{onTestComplete:async()=>{await a.browser.cleanup()},onSaveScreenshot:async k=>{if(b)return"";let{key:I}=await g.uploadScreenshot({screenshot:k.toString("base64")});return I},onUpdateRun:k=>{L(k)},onSaveFinalRunResults:async k=>{C.cancel(),await x(k)},onProposedTestSteps:async k=>g.uploadProposedSteps(k,h),onTestSuccess:async k=>{let I=IL(E,k);if(Object.keys(I).length!==0){h.debug({changes:I},"Updating steps post-run success in worker");try{let{cachesToSave:ae}=await Lt({stepLists:k,cacheCreationParams:{testId:y.id,orgId:o}});await g.updateStepCaches({testId:y.id,entries:ae})}catch(ae){h.error({err:ae},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}}};return await f.reportBillableEvent(h,"test-run",{eventId:i,testId:y.id,testName:y.name}),await sa({fixtures:N,inputs:P,options:U,callbacks:$})}async function FS(n){let e=new Date,{testDefinition:t}=n;try{return await OL(n)}catch(r){let o="Fatal error running test";return S.error(`${o}: ${r.message}`),H.error({err:r},o),{parameters:n,failureReason:"UnknownError",failureDetails:{errorMessage:r.message,errorStack:r.stack},status:"FAILED",attempts:0,test:t,filePath:t.relativeFilePath,startedAt:e,finishedAt:new Date,outputs:{}}}}async function OL(n){let{testDefinition:e,project:t,apiClient:r,orgId:o,noReport:i,urlOverride:s,runGroupId:a,runSigIntHandlers:l}=n,c=new to(r,o),d=new Un({httpClient:new At({baseUrl:r.baseUrl,apiKey:r.apiKey})}),p=e.steps,u=_S(e.steps);try{await c.resolveStepCacheEntries({organizationId:o,testId:e.id,steps:u,schemaVersion:e.schemaVersion,logger:H})}catch(v){throw H.error({err:v},"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: ${v}`)}let m=n.envName??ML(e),h,g={};if(m){try{h=Li(m,t,H)}catch(v){let b=`Failed to resolve environment ${m} for test ${e.name}: ${v}`;throw new Error(b)}g=h.variables}let f=e.baseUrl;if(s)f=s;else if(!f){let v=g[ve];typeof v=="string"&&(f=v)}if(!f){let v=`Cannot run test with no base URL and no ${ve} variable defined in its environment`;throw new Error(v)}let y;if(!i)try{y=(await r.createRun({stepsSnapshot:p,runGroupId:a,testId:e.id,testName:e.name,trigger:"CLI",resolvedBaseUrl:f,environmentName:m,schemaVersion:e.schemaVersion})).id}catch(v){throw H.error({err:v,testId:e.id},"Error creating run on Momentic Cloud"),new Error(`Error creating run on Momentic Cloud. Please ensure Momentic is accessible from your environment and try again later.
3002
3002
  Error: ${v.message}`)}try{return l?.push(async()=>{!y||i||await r.updateRun(y,{status:"CANCELLED",updatedAt:new Date})}),kL({...n,variables:g,envName:m,runId:y,stepsWithCaches:u,resolvedEnv:h,baseUrl:f,storageClient:c,codeEvalTools:d})}finally{l?.pop()}}async function kL(n){let{testDefinition:e,stepsWithCaches:t,project:r,regenerateGoldenFiles:o,apiClient:i,generator:s,baseUrl:a,storageClient:l,codeEvalTools:c,runId:d,orgId:p,envName:u,urlOverride:m,customHeaders:h,testInputs:g,variables:f,analytics:y,resolvedEnv:v,noReport:b,retriesOverride:E,billingReporter:x,devicePixelRatio:C,logUpdate:L}=n,N=new Date,P=new Lo(r,o),U={ai:r.config.ai},$=new Qr(i,p),ee={envName:u,urlOverride:m,customHeaders:h,testInputs:g};d&&(f[fg]=d);let k=H.child({testId:e.id,runId:d,orgId:p}),I=y.child({test_id:e.id,test_name:e.name,label_names:e.labels,run_id:d});I.track({type:"execution:test_start"});let ae=async Ce=>{if(!(b||!d))try{await i.updateRun(d,Ce)}catch(Le){k.warn({err:Le},`Failed to update run status for test ${d}. You may see stale data on the Momentic Cloud Server.`)}},O,Qe=Math.abs(E??r.config.retries??e.retries??0),Z=[];k.info("Starting test run using CLI");for(let Ce=0;Ce<=Qe;Ce++){let Le=LL(),le={...e,steps:_S(t)};if(!b&&d)try{Le=(await i.createRunAttempt(d)).id}catch(Fe){throw k.error({err:Fe,testId:le.id,runId:d},"Error creating run attempt on Momentic Cloud"),new Error("Error creating run attempt on Momentic Cloud. Please ensure Momentic is accessible from your environment or pass the --no-report flag.")}Ce!==0&&L("RETRY",`attempt ${Ce+1}/${Qe+1}`);let Ee=async Fe=>{if(!(b||!d))try{await i.updateRunAttempt(d,Le,Fe)}catch(D){k.warn({err:D},`Failed to update run attempt for attempt ${Le}. You may see stale data on the Momentic Cloud Server.`)}};try{await ae({status:"RUNNING",attempts:Ce+1});let{controller:Fe,context:D,flagStore:It}=await OS({baseUrl:a,envName:u,apiClient:i,devicePixelRatio:C,logger:k,storageClient:l,codeEvalTools:c,test:le,generator:s,orgId:p,variables:f,customHeaders:h,testInputs:g,localBrowserConfig:v?.browser??r.config.browser,visualDiffScreenshotStorage:P,analytics:I});O=await NS({attemptMetadata:{attemptNumber:Ce+1,orgId:p,runId:d,runAttemptId:Le},attemptFixtures:{logger:k,storageClient:l,billingReporter:x,analytics:I,debugDataClient:$,codeEvalTools:c,flagStore:It,apiClient:i,context:D,controller:Fe},attemptInputs:{test:le,orgSettings:U,noReport:b}}),await Ee({status:O.status,finishedAt:new Date,results:O.results,beforeResults:O.beforeResults,afterResults:O.afterResults}),Z.unshift(O.status);let me=await LS({orgId:p,codeEvalTools:c,logger:k,outputDefinitions:e.outputs??[],testContext:D}),$e=new Date,Pt=ku(Z),et=$e.getTime()-N.getTime(),ln=Ce+1;if(O.status!=="FAILED")return O.status==="PASSED"&&I.track({type:"execution:test_success",attempt_count:ln,duration_ms:et,is_flake:Pt}),await ae({status:O.status,finishedAt:$e,flake:Pt}),{...O,parameters:ee,runId:d,test:le,filePath:le.relativeFilePath,startedAt:N,finishedAt:$e,attempts:ln,baseUrl:a,outputs:me};let Ur=O.failedStepResult,Yt=Ur?.message||"Unknown failure",Uo=Ur?.failureReason??dm(Yt)??"UnknownError",Qn=k.child({errResult:Ur,failureReason:Uo,errorMessage:Yt,numAttempts:Qe+1,name:le.name});if(Ce<Qe){Qn.warn(`Retrying failed execution attempt for run ${d}: ${Yt}`);continue}Qn.error(`Test failed after all exhausting attempts: ${Yt}`);let zo={errorMessage:Yt};return await ae({status:"FAILED",finishedAt:$e,failureDetails:zo,failureReason:Uo}),I.track({type:"execution:test_fail",attempt_count:Ce+1,duration_ms:$e.getTime()-N.getTime(),fail_reason:zo.errorMessage}),{...O,parameters:ee,runId:d,failureDetails:zo,failureReason:Uo,test:le,filePath:le.relativeFilePath,startedAt:N,finishedAt:new Date,attempts:Ce+1,baseUrl:a,outputs:me}}catch(Fe){let D=`Encountered fatal platform error while running test '${le.name}': ${Fe}`,It=new Date,me=Ce+1;k.error({err:Fe},D),S.error(D);let $e={errorMessage:Fe.message,errStack:Fe.stack},Pt={status:"FAILED",failureDetails:$e,failureReason:"InternalPlatformError",finishedAt:It};return await Promise.all([Ee(Pt),ae(Pt)]),I.track({type:"execution:test_fail",attempt_count:me,duration_ms:It.getTime()-N.getTime(),fail_reason:$e.errorMessage}),{...Pt,parameters:ee,runId:d,test:le,filePath:le.relativeFilePath,startedAt:N,finishedAt:new Date,attempts:me,baseUrl:a,outputs:{}}}}throw new Error("This code should not be reachable")}function ML(n){for(let e of n.envs??[])if(e.default)return e.name}async function DS(n){let{tests:e,yes:t,start:r,waitOn:o,client:i,billingReporter:s,analytics:a,project:l,report:c,retriesOverride:d,urlOverride:p,envName:u,orgId:m,devicePixelRatio:h,customHeaders:g,testInputMatrix:f,reporter:y,include:v,exclude:b,labels:E,reporterDir:x="reports",waitOnTimeout:C=60,parallel:L=l.config.parallel??1,shardIndex:N=1,shardCount:P=1,regenerateGoldenFiles:U}=n;r&&(H.info({orgId:m},`Executing start command: ${r}`),await Bb(r,!1)),o&&(H.info({orgId:m},`Waiting for url: ${o} with timeout: ${C} seconds.`),await _L({resources:[o],interval:2500,timeout:C*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let $=new ro({baseUrl:i.baseUrl,apiKey:i.apiKey,logger:H}),ee=Ze(l,S),k=await PS({tests:e,momenticFiles:ee,yes:t,project:l,include:v,exclude:b,labels:E}),I=[];k.forEach((me,$e)=>{f?f.forEach((Pt,et)=>{I.push({testIndex:$e,inputs:Pt,inputIndex:et})}):I.push({testIndex:$e,inputs:void 0,inputIndex:void 0})}),P&&P>1&&(I=FL(I,N,P));let ae=`Running ${I.length} tests with ${L} workers`;H.info({allTestsToRunWithInputs:I,shardCount:P,shardIndex:N,orgId:m},ae),S.dimmed(ae),I.forEach(me=>{S.dimmed(` - ${[k[me.testIndex].relativeFilePath]}${typeof me.inputIndex=="number"?` with input set ${me.inputIndex}`:""}`)}),S.log("");let O=[],Qe=Date.now(),Z=new Set,Ce=()=>{let me=i.getAppUrl(),$e=_o({results:O,startTime:Qe,onFailed:et=>{ll(et,et.filePath)},getDisplayLine:et=>{let ln=` - ${et.filePath}${et.proposedTest?" [AUTO-HEALED] ":""}`;return c&&et.runId&&(ln+=` (${me}/runs/${et.runId})`),ln},entity:"test"}),Pt=O.filter(et=>!!et.proposedTest);return Pt.length>0&&S.warn(`${Pt.length} tests passed with auto-healing. Please use the run links printed above to review proposed changes and apply them locally.`),$e},Le=await IS(S),le=a.child({commit_sha:Le?.gitCommitSha,commit_sha_short:Le?.gitCommitShaShort,branch_name:Le?.gitBranchName,origin_url:Le?.gitOriginUrl,commit_timestamp:Le?.gitCommitTimestamp,github_repository:Le?.githubRepository,gitlab_project_path:Le?.gitlabProjectPath,pipeline_id:Le?.pipelineId}),Ee;c&&(Ee=(await i.createRunGroup({...Le,trigger:zt.CLI,startedAt:new Date,status:"RUNNING"})).id);let Fe=[],D=async()=>{S.warn("SIGINT received. Stopping tests and printing latest results..."),c&&Ee&&await i.updateRunGroup(Ee,{status:"CANCELLED",finishedAt:new Date}),Ce(),await Promise.allSettled(Fe.map(me=>me())),process.exit(1)};process.on("SIGINT",D);let It={};for(let me=0;me<I.length;me++){let $e=Object.values(It);$e.length===L&&await Promise.race($e.map(ln=>ln.promise));let Pt=I[me],et=`test-${me}`;It[et]={done:!1,promise:(async({testIndex:ln,inputs:Ur})=>{let Yt=k[ln];Z.add({testIndex:ln,inputs:Ur});let Uo=Yt.relativeFilePath.includes("..")?Yt.fullFilePath:Yt.relativeFilePath,Qn=(st,Bo)=>{let zr=(ul,Sp)=>{let jS=Math.floor((Sp-ul.length)/2);return ul.padStart(jS+ul.length).padEnd(Sp)};st=st.toUpperCase();let vn=st;st.includes("FAIL")?vn=Do.bgRed.white(zr("FAIL",8)):st.includes("PASS")?vn=Do.bgGreen.white(zr("PASS",8)):st.includes("START")?vn=Do.bgBlue.white(zr("START",8)):st.includes("CANCEL")?vn=Do.bgYellow.white(zr("CANCEL",8)):st.includes("RETRY")?vn=Do.bgYellow.white(zr("RETRY",8)):st.includes("RUN")||st.includes("PROG")?vn=Do.bgMagenta.white(zr("RUNNING",8)):H.warn(`Unknown status tried to be logged in run test locally: ${st}`),NL||(vn=`[${vn}]`),S.log(`${vn} ${Uo} ${Bo?`${Bo} `:""}(${Z.size}/${I.length})`)};Qn("START");let zo=setInterval(()=>Qn("RUN"),5*60*1e3);try{let st=await FS({testDefinition:Yt,project:l,testInputs:Ur,orgId:m,devicePixelRatio:h,apiClient:i,billingReporter:s,analytics:le,generator:$,retriesOverride:d,urlOverride:p,envName:u,noReport:!c,customHeaders:g,regenerateGoldenFiles:U,logUpdate:Qn,runGroupId:Ee,runSigIntHandlers:c?Fe:void 0});Qn(st.status),O.push(st)}catch(st){let Bo=`Encountered unexpected fatal error when running test '${Yt.name}': ${st.message}`;S.error(Bo),H.error(Bo)}finally{clearInterval(zo),It[et].done=!0,delete It[et]}})(Pt)}}if(await Promise.allSettled(Object.values(It).map(me=>me.promise)),c&&Ee){let me="PASSED";O.some($e=>$e.status==="FAILED")&&(me="FAILED"),await i.updateRunGroup(Ee,{status:me,finishedAt:new Date})}return process.off("SIGINT",D),y&&await RS(y,{suiteName:`on-demand-suite-${Qe}`,startedAt:new Date(Qe),finishedAt:new Date,runs:O},x??"reports"),Ce()}function FL(n,e,t){if(t>n.length&&(S.warn(`Shard count ${t} is greater than the number of tests ${n.length}! Some workers won't have any tests to run.`),t=Math.max(t,n.length),e>t))return[];let r=Math.floor((e-1)*(n.length/t)),o=Math.floor(e*(n.length/t));return n.sort().filter((s,a)=>a>=r&&a<o)}var US=new Mo({platform:"cli"},{flushAt:1,flushInterval:0});hl||H.warn("Sentry is not enabled in this environment due to unsupported node version");var $L=process.argv.some(n=>n.includes("--log-level"))&&process.argv.some(n=>n.includes("debug")),bp=n=>{$L&&S.dimmed(n)},Rt=new DL;Rt.name("momentic").description("CLI").version(No||"unknown");Rt.command("install-browsers").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").argument("[browsers...]","Browsers to install",["chromium"]).action(async(n,e)=>{await Dr(gS(n),e.force)});Rt.addOption(new Kt("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",n=>{n==="debug"&&S.info("Enabling debug logging"),S.setMinLevel(n.toLowerCase())});Rt.addOption(new Kt("--verbose","enable verbose logging")).on("option:verbose",()=>{H.enableConsoleLogs(),S.setMinLevel(0)});Rt.command("check-config").addOption(Fr).action(async n=>{wn({configFilePath:n.config})});var HL=Rt.command("checks").alias("check").description("Perform various project checks");HL.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Fr).action(async n=>{let e=wn({configFilePath:n.config}),t=Ze(e,S),r=Object.values(t.tests),o=await xa(t,H),i={},s={},a={},l={},c=new Set,d=new Set,p=new Set,u=new Set;for(let h of r)i[h.id]?a[h.id]?a[h.id].push(h.fullFilePath):a[h.id]=[i[h.id],h.fullFilePath]:i[h.id]=h.fullFilePath,s[h.name]?l[h.name]?l[h.name].push(h.fullFilePath):l[h.name]=[s[h.name],h.fullFilePath]:s[h.name]=h.fullFilePath;for(let h of o)u.has(h.moduleId)&&c.add(h.moduleId),p.has(h.name)&&d.add(h.name),u.add(h.moduleId),p.add(h.name);if(Object.entries(a).length>0||Object.entries(l).length>0||c.size>0||d.size>0){for(let[h,g]of Object.entries(a))for(let f of g)S.error(`Test ID ${h} is duplicated in ${f}`);for(let[h,g]of Object.entries(l))for(let f of g)S.error(`Test Name ${h} is duplicated in ${f}`);for(let h of c)S.error(`Module id ${h} is duplicated in your project`);for(let h of d)S.error(`Module name ${h} is duplicated in your project`);process.exit(1)}S.success("No duplicates detected. All test and module names and ids are unique."),process.exit(0)});var WL=Rt.command("migrate").description("Migrate and upgrade tooling");WL.command("v0-v1").addOption(Jn).addOption(Xn).action(async n=>{let e=await Zn(n);if(!e.yes&&!await it("This command will migrate and then delete your previous Momentic files. All members of your team should transition to the V1 CLI at the same time. Please backup your local directory for safety before proceeding. Continue?",!0)&&process.exit(1),!Zb().environments?.length&&await it("In the V1 CLI, all environment configuration should be committed to a central `momentic.config.yaml` file, which you should commit to your source control repository. Sensitive data can be managed through `.env` files or by injecting the secret into the environment and then referencing them in `envVariables` with ${VAR} syntax. Would you like to pull the latest environments from Momentic Cloud into your `momentic.config.yaml` file?",!0)){let{apiKey:r,server:o}=e,i=wn({}),s=new dt({baseUrl:o,apiKey:r,logger:H});await Za({client:s,project:i,skipPrompts:e.yes}),S.success("Successfully imported environments from Momentic Cloud.")}});Rt.command("import-from-cloud").addOption(Xn).addOption(_r).addOption(Fr).addOption(Jn).action(async n=>{let e=await Zn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=wn({configFilePath:o}),a=new dt({baseUrl:r,apiKey:t,logger:H});await Jb({client:a,project:s,skipPrompts:i}),process.exit(0)});Rt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Kt("--name <name>","Name of the project")).action(async n=>{S.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3003
- `),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-from-cloud' command after initialization."),zS.existsSync(Ro)&&(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 t={name:n.name??await Gb("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:qi};Io(t,Ro),S.success(`Initialized Momentic project file at ${pl.resolve(Ro)}`)});Rt.command("app").addOption(Xn).addOption(_r).addOption(Jn).addOption(lp).addOption(sS).addOption(Fr).action(async n=>{let e=await Zn(n),{apiKey:t,port:r=el,yes:o,server:i,pixelRatio:s}=e,a=new dt({baseUrl:i,apiKey:t,logger:H});await up({client:a,skipPrompts:o,installBrowsers:!0});let l=jL(import.meta.url),c=pl.dirname(l),d=pl.resolve(c,"..","static"),p=pl.resolve(c,"..","assets"),u=s??Qd();ep(u),jo(),await Db({momenticServerUrl:i,apiKey:t,serverPort:r,appPort:r,staticDir:d,assetsDir:p,devicePixelRatio:u,version:"1.0.91"});let m=`http://localhost:${r}`;await BL(m)});var BS=Rt.command("queue").description("Queue tests or suites to run on Momentic Cloud");BS.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Xn).addOption(_r).addOption(ip).addOption(sp).addOption(Jn).addArgument(pS).addOption(rl).addOption(nl).addOption(tl).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:s,urlOverride:a,customHeaders:l}=await Zn(e),c=new dt({baseUrl:r,apiKey:t,logger:H});(!n||!Array.isArray(n)||!n.length)&&(S.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await wS({client:c,orgId:d,wait:o,suitePaths:n,waitTimeout:i,env:s,urlOverride:a,customHeaders:ol(l)})});BS.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Xn).addOption(_r).addOption(Jn).addOption(tl).addOption(cp).addOption(rl).addOption(nl).addOption(ip).addOption(sp).addArgument(cS).action(async(n,e)=>{let t=await Zn(e),{all:r,apiKey:o,customHeaders:i,env:s,server:a,inputCsv:l,urlOverride:c,wait:d,waitTimeout:p,yes:u}=t,m=ol(i);for(let y of n)(y.endsWith(".yaml")||zS.existsSync(y))&&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 h=new dt({baseUrl:a,apiKey:o,logger:H}),{orgId:g}=await h.getAuthInfo(),f;l&&(f=await tp(l)),await vS({client:h,orgId:g,tests:n,all:r,customHeaders:m,env:s,urlOverride:c,wait:d,waitTimeout:p,testInputMatrix:f,yes:u}),process.exit(0)});var GL=Rt.command("run").alias("test").description("Run tests on the local machine");GL.addOption(Xn).addOption(_r).addOption(Fr).addOption(dp).addOption(Jn).addOption(tl).addOption(cp).addOption(nl).addOption(rl).addOption(ap).addOption(lp).addOption(new Kt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Kt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Kt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new Kt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new Kt("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new Kt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Kt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(ap).addOption(nS).addOption(rS).addOption(aS).addOption(lS).addOption(oS).addOption(iS).addArgument(dS).action(async(n,e)=>{S.debug("Run tests invoked");let t=await Zn(e);S.debug(t,"Parsed CLI options");let r=ol(t.customHeaders),o=wn({configFilePath:t.config,nameFilter:t.filter});S.debug({projectName:o.config.name},"Identified project config");let i=new dt({baseUrl:t.server,apiKey:t.apiKey,logger:H}),s=new Hs(i),a;t.inputCsv&&(a=await tp(t.inputCsv)),S.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await up({client:i,skipPrompts:t.yes,installBrowsers:!0});S.debug("API key check and browser installation complete");let d=t.pixelRatio??Qd();ep(d);let p=US.child({org_id:l,user_id:c,cli_version:No,trigger:"CLI"});t.report||(p=new Ka);try{(await DS({...t,retriesOverride:t.retries,devicePixelRatio:d,tests:n,project:o,client:i,billingReporter:s,analytics:p,customHeaders:r,envName:t.env,orgId:l,testInputMatrix:a,regenerateGoldenFiles:t.updateGoldenFiles})).failed>0?process.exit(1):process.exit(0)}catch(u){S.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),S.error(u),process.exit(1)}});var VL=Rt.command("apply").description("Apply an operation to local resources");VL.command("patch").addOption(Xn).addOption(_r).addOption(Fr).addOption(dp).addOption(Jn).addOption(new Kt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Kt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async n=>{let e=await Zn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=wn({configFilePath:o}),a=new dt({baseUrl:r,apiKey:t,logger:H}),l=Ze(s,S),c=l.tests[n.to]??Object.values(l.tests).find(p=>Me(p.name)===n.to.trim());c||(S.error(`No test matching '${n.to}' could be found in the current project.`),process.exit(1));let d=await a.fetchTestFragment(n.from);await Vb({client:a,test:c,fragment:d,yes:i,entities:l,logger:H}),process.exit(0)});async function qL(){bp("Main program started"),await jb(H),bp("CLI version check complete");try{await Rt.parseAsync(process.argv),jo()}catch(n){let e={};try{e.playwrightVersion=UL("npx playwright --version").toString()}catch(t){H.error({err:t},"Error fetching debug information")}H.error({err:n,debugInfo:e},"Uncaught error in CLI"),H.flush(),ml(n,e),S.error(n),jo(),process.exit(1)}}zL.setMaxListeners(50);process.on("warning",n=>{H.warn({err:n},`Node warning received on CLI: ${n.message}`)});bp("CLI parsing setup complete");qL();
3003
+ `),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-from-cloud' command after initialization."),zS.existsSync(Ro)&&(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 t={name:n.name??await Gb("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:qi};Io(t,Ro),S.success(`Initialized Momentic project file at ${pl.resolve(Ro)}`)});Rt.command("app").addOption(Xn).addOption(_r).addOption(Jn).addOption(lp).addOption(sS).addOption(Fr).action(async n=>{let e=await Zn(n),{apiKey:t,port:r=el,yes:o,server:i,pixelRatio:s}=e,a=new dt({baseUrl:i,apiKey:t,logger:H});await up({client:a,skipPrompts:o,installBrowsers:!0});let l=jL(import.meta.url),c=pl.dirname(l),d=pl.resolve(c,"..","static"),p=pl.resolve(c,"..","assets"),u=s??Qd();ep(u),jo(),await Db({momenticServerUrl:i,apiKey:t,serverPort:r,appPort:r,staticDir:d,assetsDir:p,devicePixelRatio:u,version:"1.0.92"});let m=`http://localhost:${r}`;await BL(m)});var BS=Rt.command("queue").description("Queue tests or suites to run on Momentic Cloud");BS.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Xn).addOption(_r).addOption(ip).addOption(sp).addOption(Jn).addArgument(pS).addOption(rl).addOption(nl).addOption(tl).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:s,urlOverride:a,customHeaders:l}=await Zn(e),c=new dt({baseUrl:r,apiKey:t,logger:H});(!n||!Array.isArray(n)||!n.length)&&(S.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await wS({client:c,orgId:d,wait:o,suitePaths:n,waitTimeout:i,env:s,urlOverride:a,customHeaders:ol(l)})});BS.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Xn).addOption(_r).addOption(Jn).addOption(tl).addOption(cp).addOption(rl).addOption(nl).addOption(ip).addOption(sp).addArgument(cS).action(async(n,e)=>{let t=await Zn(e),{all:r,apiKey:o,customHeaders:i,env:s,server:a,inputCsv:l,urlOverride:c,wait:d,waitTimeout:p,yes:u}=t,m=ol(i);for(let y of n)(y.endsWith(".yaml")||zS.existsSync(y))&&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 h=new dt({baseUrl:a,apiKey:o,logger:H}),{orgId:g}=await h.getAuthInfo(),f;l&&(f=await tp(l)),await vS({client:h,orgId:g,tests:n,all:r,customHeaders:m,env:s,urlOverride:c,wait:d,waitTimeout:p,testInputMatrix:f,yes:u}),process.exit(0)});var GL=Rt.command("run").alias("test").description("Run tests on the local machine");GL.addOption(Xn).addOption(_r).addOption(Fr).addOption(dp).addOption(Jn).addOption(tl).addOption(cp).addOption(nl).addOption(rl).addOption(ap).addOption(lp).addOption(new Kt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Kt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Kt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new Kt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new Kt("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new Kt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Kt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(ap).addOption(nS).addOption(rS).addOption(aS).addOption(lS).addOption(oS).addOption(iS).addArgument(dS).action(async(n,e)=>{S.debug("Run tests invoked");let t=await Zn(e);S.debug(t,"Parsed CLI options");let r=ol(t.customHeaders),o=wn({configFilePath:t.config,nameFilter:t.filter});S.debug({projectName:o.config.name},"Identified project config");let i=new dt({baseUrl:t.server,apiKey:t.apiKey,logger:H}),s=new Hs(i),a;t.inputCsv&&(a=await tp(t.inputCsv)),S.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await up({client:i,skipPrompts:t.yes,installBrowsers:!0});S.debug("API key check and browser installation complete");let d=t.pixelRatio??Qd();ep(d);let p=US.child({org_id:l,user_id:c,cli_version:No,trigger:"CLI"});t.report||(p=new Ka);try{(await DS({...t,retriesOverride:t.retries,devicePixelRatio:d,tests:n,project:o,client:i,billingReporter:s,analytics:p,customHeaders:r,envName:t.env,orgId:l,testInputMatrix:a,regenerateGoldenFiles:t.updateGoldenFiles})).failed>0?process.exit(1):process.exit(0)}catch(u){S.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),S.error(u),process.exit(1)}});var VL=Rt.command("apply").description("Apply an operation to local resources");VL.command("patch").addOption(Xn).addOption(_r).addOption(Fr).addOption(dp).addOption(Jn).addOption(new Kt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Kt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async n=>{let e=await Zn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=wn({configFilePath:o}),a=new dt({baseUrl:r,apiKey:t,logger:H}),l=Ze(s,S),c=l.tests[n.to]??Object.values(l.tests).find(p=>Me(p.name)===n.to.trim());c||(S.error(`No test matching '${n.to}' could be found in the current project.`),process.exit(1));let d=await a.fetchTestFragment(n.from);await Vb({client:a,test:c,fragment:d,yes:i,entities:l,logger:H}),process.exit(0)});async function qL(){bp("Main program started"),await jb(H),bp("CLI version check complete");try{await Rt.parseAsync(process.argv),jo()}catch(n){let e={};try{e.playwrightVersion=UL("npx playwright --version").toString()}catch(t){H.error({err:t},"Error fetching debug information")}H.error({err:n,debugInfo:e},"Uncaught error in CLI"),H.flush(),ml(n,e),S.error(n),jo(),process.exit(1)}}zL.setMaxListeners(50);process.on("warning",n=>{H.warn({err:n},`Node warning received on CLI: ${n.message}`)});bp("CLI parsing setup complete");qL();
3004
3004
  //# sourceMappingURL=cli.js.map
3005
- //# debugId=2d9a3251-b2b9-56ca-9199-8e81915b4aed
3005
+ //# debugId=516fb9a5-624b-5744-9389-945ddcf0c140