momentic 1.0.87 → 1.0.89

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,17 +1,17 @@
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]="21e59e86-f837-5b15-851d-f3319cc9f773")}catch(e){}}();
4
- var Lb=Object.create;var yp=Object.defineProperty;var Ob=Object.getOwnPropertyDescriptor;var kb=Object.getOwnPropertyNames;var _b=Object.getPrototypeOf,Nb=Object.prototype.hasOwnProperty;var Sp=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Mb=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kb(e))!Nb.call(n,o)&&o!==t&&yp(n,o,{get:()=>e[o],enumerable:!(r=Ob(e,o))||r.enumerable});return n};var Db=(n,e,t)=>(t=n!=null?Lb(_b(n)):{},Mb(e||!n||!n.__esModule?yp(t,"default",{value:n,enumerable:!0}):t,n));var oy=Sp((vQ,ry)=>{"use strict";ry.exports=ty;function ty(n,e,t){n instanceof RegExp&&(n=ey(n,t)),e instanceof RegExp&&(e=ey(e,t));var r=ny(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 ey(n,e){var t=e.match(n);return t?t[0]:null}ty.range=ny;function ny(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 uy=Sp((xQ,py)=>{"use strict";var iy=oy();py.exports=nR;var sy="\0SLASH"+Math.random()+"\0",ay="\0OPEN"+Math.random()+"\0",hd="\0CLOSE"+Math.random()+"\0",ly="\0COMMA"+Math.random()+"\0",cy="\0PERIOD"+Math.random()+"\0";function md(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function eR(n){return n.split("\\\\").join(sy).split("\\{").join(ay).split("\\}").join(hd).split("\\,").join(ly).split("\\.").join(cy)}function tR(n){return n.split(sy).join("\\").split(ay).join("{").split(hd).join("}").split(ly).join(",").split(cy).join(".")}function dy(n){if(!n)return[""];var e=[],t=iy("{","}",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=dy(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function nR(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),Ri(eR(n),!0).map(tR)):[]}function rR(n){return"{"+n+"}"}function oR(n){return/^-?0\d/.test(n)}function iR(n,e){return n<=e}function sR(n,e){return n>=e}function Ri(n,e){var t=[],r=iy("{","}",n);if(!r)return[n];var o=r.pre,i=r.post.length?Ri(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+hd+r.post,Ri(n)):[n];var u;if(d)u=r.body.split(/\.\./);else if(u=dy(r.body),u.length===1&&(u=Ri(u[0],!1).map(rR),u.length===1))return i.map(function(J){return r.pre+u[0]+J});var m;if(d){var h=md(u[0]),f=md(u[1]),g=Math.max(u[0].length,u[1].length),y=u.length==3?Math.abs(md(u[2])):1,v=iR,S=f<h;S&&(y*=-1,v=sR);var E=u.some(oR);m=[];for(var T=h;v(T,f);T+=y){var C;if(c)C=String.fromCharCode(T),C==="\\"&&(C="");else if(C=String(T),E){var P=g-C.length;if(P>0){var k=new Array(P+1).join("0");T<0?C="-"+k+C.slice(1):C=k+C}}m.push(C)}}else{m=[];for(var N=0;N<u.length;N++)m.push.apply(m,Ri(u[N],!1))}for(var N=0;N<m.length;N++)for(var s=0;s<i.length;s++){var a=o+m[N]+i[s];(!e||d||a)&&t.push(a)}}return t}});var al=(n,e)=>{},zo=()=>{},ll=!1;try{let n=await import("@sentry/node"),{nodeProfilingIntegration:e}=await import("@sentry/profiling-node");al=n.captureException,zo=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(),ll=!0}catch{}import{Command as gL,Option as qt}from"@commander-js/extra-typings";import{execSync as yL}from"child_process";import TS from"body-parser";import oP from"cors";import iP from"dedent";import sP from"events";import ES,{Router as aP}from"express";import lP from"http";import{z as vn}from"zod";var Ki=vn.object({x:vn.number(),y:vn.number(),correlation:vn.number()}),OL=vn.object({searchImageBase64String:vn.string(),pageImageBase64String:vn.string(),id:vn.string().uuid(),timeoutMs:vn.number().max(1e4).min(0).optional()});import{z as _}from"zod";import{v4 as Le}from"uuid";import*as w from"zod";function me(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 ie}from"zod";me(ie);var bp=ie.object({plan:ie.string().optional(),evidence:ie.string().optional(),thoughts:ie.string(),result:ie.boolean(),relevantElements:ie.array(ie.number()).optional()}),Bo=(r=>(r.CONTAINS="CONTAINS",r.STARTS_WITH="STARTS_WITH",r.EQUALS="EQUALS",r))(Bo||{});var Fb=ie.object({type:ie.literal("ELEMENT_CONTENT"),negated:ie.boolean().optional(),operation:ie.nativeEnum(Bo),value:ie.string()}).openapi({ref:"ElementContentAssertion"}),Ub=ie.object({type:ie.literal("ELEMENT_ATTRIBUTE"),negated:ie.boolean().optional(),operation:ie.nativeEnum(Bo),attr:ie.string(),value:ie.string()}).openapi({ref:"ElementAttributeValueAssertion"}),jo=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(jo||{}),zb=ie.object({type:ie.literal("ELEMENT_EXISTENCE"),negated:ie.boolean().optional(),condition:ie.nativeEnum(jo)}).openapi({ref:"ElementExistenceAssertion"}),wp=ie.discriminatedUnion("type",[Fb,Ub,zb]).openapi({ref:"ManualElementAssertion"});var Bb=ie.object({type:ie.literal("CONTENT"),negated:ie.boolean().optional(),value:ie.string()}).openapi({ref:"PageContentAssertion"}),vp=ie.discriminatedUnion("type",[Bb]).openapi({ref:"ManualPageAssertion"});import*as K from"zod";me(K);var Qn=(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))(Qn||{}),er=K.object({id:K.number().int(),dataMomenticId:K.number().int().optional(),selector:K.string().optional(),generatedSelectors:K.string().array().optional(),role:K.string().optional(),name:K.string().optional(),numChildren:K.number().optional(),content:K.string().optional(),pathFromRoot:K.string().optional(),serializedForm:K.string().optional(),nodeOnlySerializedForm:K.string().optional(),serializedHtml:K.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:K.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:K.string().url().optional(),boundingBox:K.object({x:K.number().optional(),y:K.number().optional(),width:K.number(),height:K.number()}).describe("css pixel bounding box").optional(),inputDescription:K.string().optional().describe("the description that generated this cache"),targetSource:K.nativeEnum(Qn).optional(),targetUpdateTime:K.string().optional()}).openapi({ref:"A11yTargetWithCache"});function Yi(n){return!!(n.name||n.role||n.content||n.serializedForm||n.serializedHtml||n.screenshotUrl)}var jb=K.object({type:K.literal("description"),elementDescriptor:K.string(),a11yData:er.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),$b=K.object({x:K.number(),y:K.number()}),Hb=K.object({type:K.literal("coordinates"),pixels:$b}).openapi({ref:"CoordinatesTarget"});function Ln(n){return n.type==="description"}function ln(n){return n.type==="coordinates"}var it=K.discriminatedUnion("type",[jb,Hb]).openapi({ref:"ElementTarget"});function cl(n){if(!n)return!1;switch(n.type){case"description":return!!n.elementDescriptor}return!0}function st(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 ee}from"zod";var Ji=ee.object({url:ee.string(),method:ee.union([ee.literal("GET"),ee.literal("POST"),ee.literal("PUT"),ee.literal("DELETE"),ee.literal("PATCH")]),headers:ee.record(ee.string(),ee.string()).optional(),params:ee.record(ee.string(),ee.string()).optional(),body:ee.string().optional(),timeout:ee.number().int().optional().describe("Max seconds to wait for the request to complete")}),xp=ee.object({url:ee.string(),headers:ee.record(ee.string(),ee.string()).optional(),query:ee.string(),variables:ee.record(ee.string(),ee.string()).optional(),timeout:ee.number().int().optional().describe("Max seconds to wait for the request to complete")}),Xi=ee.object({code:ee.string(),fragment:ee.boolean().optional(),environment:ee.union([ee.literal("NODE"),ee.literal("BROWSER")]).optional().describe("default NODE"),timeout:ee.number().int().max(60).optional().describe("Max seconds for the code to complete")});var je=(F=>(F.AI_EXTRACT="AI_EXTRACT",F.AI_ASSERTION="AI_ASSERTION",F.AI_WAIT="AI_WAIT",F.AUTH_LOAD="AUTH_LOAD",F.AUTH_SAVE="AUTH_SAVE",F.BLUR="BLUR",F.CAPTCHA="CAPTCHA",F.CLICK="CLICK",F.COOKIE="COOKIE",F.COPY="COPY",F.DIALOG="DIALOG",F.DRAG="DRAG",F.ELEMENT_CHECK="ELEMENT_CHECK",F.FILE_UPLOAD="FILE_UPLOAD",F.FOCUS="FOCUS",F.GO_BACK="GO_BACK",F.GO_FORWARD="GO_FORWARD",F.HOVER="HOVER",F.JAVASCRIPT="JAVASCRIPT",F.LOCAL_STORAGE="LOCAL_STORAGE",F.MOUSE_DRAG="MOUSE_DRAG",F.NAVIGATE="NAVIGATE",F.NEW_TAB="NEW_TAB",F.PAGE_CHECK="PAGE_CHECK",F.PASTE="PASTE",F.PRESS="PRESS",F.REFRESH="REFRESH",F.REQUEST="REQUEST",F.GRAPHQL_REQUEST="GRAPHQL_REQUEST",F.SCROLL_DOWN="SCROLL_DOWN",F.SCROLL_UP="SCROLL_UP",F.SCROLL_LEFT="SCROLL_LEFT",F.SCROLL_RIGHT="SCROLL_RIGHT",F.SELECT_OPTION="SELECT_OPTION",F.TAB="TAB",F.TYPE="TYPE",F.VISUAL_DIFF="VISUAL_DIFF",F.WAIT="WAIT",F.WAIT_FOR_URL="WAIT_FOR_URL",F.SUCCESS="SUCCESS",F))(je||{});me(w);var q=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),_t=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),cn=w.object({target:er}).optional().openapi({ref:"SingleTargetCache"}),Zi=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),Wb=q.merge(Zi).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Qi=_t.merge(w.object({cache:cn})),Mr=q.merge(Qi.merge(w.object({target:it.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Dr=q.merge(Qi.merge(w.object({target:it.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Fr=q.merge(Qi.merge(w.object({target:it.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ur=q.merge(Qi.merge(w.object({target:it.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),KL=w.discriminatedUnion("type",[Mr,Dr,Fr,Ur]).openapi({ref:"AllScrollCommands"}),Gb=q.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Vb=q.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),qb=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()})]),Kb=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")}),Yb=q.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:qb.optional()}).merge(Kb).openapi({ref:"WaitUrlCommand"}),Jb=q.merge(Zi).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Xb=q.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Zb=q.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),Qb=q.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),ew=q.extend({type:w.literal("AUTH_LOAD"),storageState:w.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),ul=q.merge(_t).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),tw=q.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),nw=q.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),rw=q.merge(Xi).extend({type:w.literal("JAVASCRIPT"),envKey:w.string().optional()}).openapi({ref:"JavaScriptCommand"}),$o=q.merge(_t).merge(w.object({type:w.literal("CLICK"),target:it,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:cn})).openapi({ref:"ClickCommand"}),Ho=q.merge(_t).merge(w.object({type:w.literal("DRAG"),fromTarget:it,toTarget:it,hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:w.object({fromTarget:er.optional(),toTarget:er.optional()}).optional()})).openapi({ref:"DragCommand"}),Wo=q.merge(_t).merge(w.object({type:w.literal("MOUSE_DRAG"),target:it.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:cn})).openapi({ref:"MouseDragCommand"}),Go=q.merge(_t).merge(w.object({type:w.literal("HOVER"),target:it,cache:cn})).openapi({ref:"HoverCommand"}),Vo=q.merge(_t).merge(w.object({type:w.literal("FOCUS"),target:it,cache:cn})).openapi({ref:"FocusCommand"}),qo=q.merge(_t).extend({type:w.literal("BLUR"),target:it.optional(),cache:cn}).openapi({ref:"BlurCommand"}),ow=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),iw=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=q.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[ow,iw]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),aw=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()})]),Ko=q.merge(_t).extend({type:w.literal("SELECT_OPTION"),target:it,cache:cn,option:w.string().describe("option value, deprecated old field").optional(),choice:aw.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),ml=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),hl=q.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:ml.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),lw=hl.extend({type:w.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),xn=5,fl=600,Yo=q.merge(_t).extend({type:w.literal("ELEMENT_CHECK"),target:it,assertion:wp,cache:cn,timeout:w.number().int().min(0).max(fl).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),cw=q.extend({type:w.literal("PAGE_CHECK"),assertion:vp,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(fl).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),dw=q.merge(w.object({type:w.literal("AI_EXTRACT"),goal:w.string(),schema:w.string().optional(),envKey:w.string().optional(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional()})).openapi({ref:"AIExtractCommand"}),pw=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()}),Jo=q.merge(_t).merge(pw).extend({type:w.literal("TYPE"),target:it.optional(),value:w.string(),cache:cn}).openapi({ref:"TypeCommand"}),uw=q.merge(w.object({type:w.literal("PRESS"),value:w.string(),repeat:w.number().optional(),convertMeta:w.boolean().optional()})).openapi({ref:"PressCommand"}),mw=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),hw=w.object({type:w.literal("REGEX"),pattern:w.string()}),fw=w.object({type:w.literal("INDEX"),index:w.number()}),gw=w.discriminatedUnion("type",[mw,hw,fw]),yw=q.merge(Zi).merge(w.object({type:w.literal("TAB"),url:w.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:gw.optional()})).openapi({ref:"TabCommand"}),Sw=q.merge(Zi).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),bw=q.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),ww=q.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),vw=q.extend({type:w.literal("REQUEST")}).merge(Ji).openapi({ref:"RequestCommand"}),xw=q.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(xp).openapi({ref:"GraphQLRequestCommand"}),Tw=q.merge(w.object({type:w.literal("SUCCESS"),condition:hl.optional()})).openapi({ref:"SuccessCommand"}),Ew=q.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Cw=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),Xo=q.merge(_t).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:it.optional(),screenshot:Cw.optional(),cache:cn})).openapi({ref:"VisualDiffCommand"}),Tp=w.discriminatedUnion("type",[$o,Jo,uw,Ko,Wb,Dr,Mr,hl,Go,Vb,Tw]),Aw=w.discriminatedUnion("type",[lw,dw,ew,Qb,ul,bw,tw,Gb,Ho,Yo,sw,Xb,Zb,rw,ww,Wo,Sw,cw,nw,Jb,vw,xw,Fr,Ur,yw,Xo,Vo,qo,Yb]),es=w.discriminatedUnion("type",[...Tp.options,...Aw.options]).openapi({ref:"Command"}),ts=w.discriminatedUnion("type",[...Tp.options,Ew]);function On(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:Le(),type:n};break;case"AUTH_LOAD":{e={id:Le(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:Le(),type:n,goal:""};break;case"DIALOG":e={id:Le(),type:n,action:"DISMISS"};break;case"DRAG":e={id:Le(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Le(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Le(),type:n,url:""};break;case"WAIT":e={id:Le(),type:n,delay:1};break;case"BLUR":e={id:Le(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Le(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Le(),type:n,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Le(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Le(),type:n,url:""};break;case"REQUEST":e={id:Le(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Le(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Le(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:Le(),type:n,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Le(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:Le(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Le(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Le(),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 Rw}from"zod";var QL=Rw.discriminatedUnion("type",[qo,ul,$o,Ho,Vo,Go,Wo,Mr,Dr,Fr,Ur,Ko,Jo,Xo,Yo]);function Ep(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as Iw}from"zod";var gt={type:!0,cache:!0},tr=Iw.discriminatedUnion("type",[qo.pick(gt),$o.pick(gt),Ho.pick(gt),Yo.pick(gt),Vo.pick(gt),Go.pick(gt),Wo.pick(gt),Mr.pick(gt),Dr.pick(gt),Fr.pick(gt),Ur.pick(gt),Ko.pick(gt),Jo.pick(gt),Xo.pick(gt)]),gl=Object.values(je).filter(n=>tr.options.some(e=>e.shape.type.safeParse(n).success));es.options.forEach(n=>{if("target"in n.shape&&!gl.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as Sl}from"zod";import{z as yl}from"zod";import{z as zr}from"zod";var yt=zr.object({index:zr.number().optional().describe("global index within a test (in-order traversal)"),id:zr.string(),skipped:zr.boolean().optional(),envKey:zr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:zr.boolean().optional()});me(yl);var St=yt.extend({type:yl.literal("PRESET_ACTION"),command:es,skipped:yl.boolean().optional()}).openapi({ref:"PresetAction"});me(Sl);var nr=yt.extend({type:Sl.literal("AI_ACTION"),text:Sl.string(),steps:St.array().optional()}).openapi({ref:"AIAction"});import{z as ne}from"zod";var Pw=ne.object({cacheKey:ne.string(),cacheExpiryMs:ne.number()}),bl=yt.extend({id:ne.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ne.record(ne.string()).optional(),cacheConfig:Pw.optional()}),Tn=bl.extend({type:ne.literal("MODULE"),moduleId:ne.string().uuid()}),Lw=ne.union([Tn.pick({type:!0,moduleId:!0}),ne.record(ne.unknown())]),Ow=ne.object({type:ne.literal("URL_REGEX"),regex:ne.string()}),kw=ne.object({type:ne.literal("PAGE_CHECK"),substring:ne.string()}),wl=ne.object({cacheInvalidation:ne.discriminatedUnion("type",[kw,Ow]).optional()}),bt=ne.object({moduleId:ne.string().uuid(),name:ne.string(),description:ne.string().nullish(),enabled:ne.boolean().nullish(),parameters:ne.string().array().nullish(),defaultParameters:ne.record(ne.string(),ne.string()).nullish(),defaultCacheKey:ne.string().nullish(),defaultCacheTtl:ne.number().nullish(),defaultCacheAllInvocations:ne.boolean().nullish(),autoAuth:ne.boolean().nullish(),advanced:wl.nullish()});import{z as Xe}from"zod";import{z as vl}from"zod";me(vl);var Br=yt.extend({type:vl.literal("AI_ACTION_DYNAMIC"),text:vl.string()}).openapi({ref:"AIActionDynamic"});import{z as Cp}from"zod";var xl=yt.extend({type:Cp.literal("CONDITIONAL"),skipped:Cp.boolean().optional()});import{z as Nt}from"zod";var _w=Nt.object({type:Nt.literal("attr"),name:Nt.string(),value:Nt.string()}),Nw=Nt.object({type:Nt.literal("css"),selector:Nt.string()}),Mw=Nt.object({type:Nt.literal("url"),url:Nt.string()}),Dw=Nt.union([_w,Mw,Nw]),Zo=yt.extend({type:Nt.literal("IFRAME"),identifier:Dw});import{z as Mt}from"zod";var Tl=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(Tl||{});var Fw=Mt.discriminatedUnion("type",[Mt.object({type:Mt.literal("NAVIGATE_URL"),url:Mt.string().url()}),Mt.object({type:Mt.literal("GO_TO_SECTION_START")})]),Uw=Mt.object({trigger:Mt.nativeEnum(Tl).optional(),attempts:Mt.number().int().optional(),restartBehavior:Fw}),Qo=yt.extend({type:Mt.literal("SECTION"),description:Mt.string().describe("user provided goal of what the section should accomplish"),plan:Mt.string().array().optional(),autohealingConfig:Uw.optional()});var Ap=bt.merge(bl).extend({type:Xe.literal("RESOLVED_MODULE"),steps:Xe.lazy(()=>Re.array())}),El=bt.extend({steps:Xe.lazy(()=>Re.array())}),Cl=Zo.extend({steps:Xe.lazy(()=>$e.array())}),zw=Zo.extend({steps:Xe.lazy(()=>Re.array())}),Al=Qo.extend({steps:Xe.lazy(()=>$e.array())}),Bw=Qo.extend({steps:Xe.lazy(()=>Re.array())}),rr=xl.extend({blocks:Xe.object({assertion:Xe.lazy(()=>St),steps:Xe.lazy(()=>$e.array())}).array(),elseSteps:Xe.lazy(()=>$e.array().optional())}),jw=xl.extend({blocks:Xe.object({assertion:Xe.lazy(()=>St),steps:Xe.lazy(()=>Re.array())}).array(),elseSteps:Xe.lazy(()=>Re.array().optional())}),$e=Xe.discriminatedUnion("type",[St,nr,Br,Tn,rr,Cl,Al]),Re=Xe.discriminatedUnion("type",[St,nr,Br,Ap,jw,zw,Bw]);import{z as Dt}from"zod";var $w=Dt.object({steps:$e.array(),beforeSteps:$e.array().nullish(),afterSteps:$e.array().nullish()}),jr=Dt.object({steps:Re.array(),beforeSteps:Re.array().nullish(),afterSteps:Re.array().nullish()}),or=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 ut="1.0.19";import{z as ir}from"zod";var Rl=ir.object({key:ir.string(),testId:ir.string().optional(),moduleId:ir.string().optional(),organizationId:ir.string(),value:tr}),Rp=ir.record(ir.string(),Rl);var Ip=_.object({phrase:_.string()}),Il=_.object({thoughts:_.string().optional(),result:_.union([_.literal("NOT_FOUND"),_.string(),_.number(),_.array(_.unknown()),_.record(_.unknown(),_.unknown()),_.unknown()])}),Zk=_.object({text:_.string()}),Pp=_.object({thoughts:_.string(),id:_.number().int()}),Hw=_.discriminatedUnion("op",[_.object({op:_.literal("replace"),path:_.string(),value:_.string()}),_.object({op:_.literal("add"),path:_.string(),value:_.string()}),_.object({op:_.literal("remove"),path:_.string()})]),Qk=_.object({thoughts:_.string(),patches:Hw.array()}),Lp=[_.literal("add"),_.literal("replace"),_.literal("remove")],Ww=_.object({op:_.union(Lp),path:_.string(),value:Re.optional()}),Op=_.object({patches:Ww.array(),thoughts:_.string()});var Gw=_.object({thoughts:_.string(),op:_.union(Lp),value:_.union([_.null(),Re])}),kp=_.object({reasoning:_.string(),scenario:_.string(),patch:Gw.or(_.null())}),e_=_.object({thoughts:_.string(),evaluation:_.number().min(1).max(10)}),t_=_.object({observations:_.string(),reasoning:_.string(),command:ts});var Pl=_.object({summary:_.string(),reasoning:_.string(),evaluation:_.discriminatedUnion("type",[_.object({type:_.literal("DONE")}),_.object({type:_.literal("RIGHT_TRACK")}),_.object({type:_.literal("WRONG_TRACK"),feedback:_.string()}),_.object({type:_.literal("IMPOSSIBLE")})])});import{z as mt}from"zod";var Ll=mt.object({content:mt.string(),ids:mt.string().array(),tokenLength:mt.number()}),Vw=mt.object({chunks:Ll.array()}),o_=mt.object({ids:mt.string().array(),score:mt.number(),tokenLength:mt.number()}),i_=Vw.extend({description:mt.string().describe("Input to pass to RAG engine"),tokenLimit:mt.number()}),_p=mt.object({ids:mt.number().array()}),Np=mt.object({indices:mt.number().array()});import{z as D}from"zod";import{z as oi}from"zod";import{z as hx}from"zod";import*as W from"zod";import{cloneDeep as ti}from"lodash-es";var qw=n=>{let e=Mp(n,0);if(e===void 0||!Yw(n[e]))return;let t=Mp(n,e+1);if(t!==void 0)return Jw(n,e,t)},Dp=qw,Mp=(n,e)=>{for(let t=e;t<n.length;t+=1){let r=n[t];if(!Kw(r))return t}},Kw=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]="480b6943-ca59-5780-955c-50915548ced6")}catch(e){}}();
4
+ var Lb=Object.create;var yp=Object.defineProperty;var Ob=Object.getOwnPropertyDescriptor;var kb=Object.getOwnPropertyNames;var _b=Object.getPrototypeOf,Nb=Object.prototype.hasOwnProperty;var Sp=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Mb=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kb(e))!Nb.call(n,o)&&o!==t&&yp(n,o,{get:()=>e[o],enumerable:!(r=Ob(e,o))||r.enumerable});return n};var Db=(n,e,t)=>(t=n!=null?Lb(_b(n)):{},Mb(e||!n||!n.__esModule?yp(t,"default",{value:n,enumerable:!0}):t,n));var oy=Sp((vQ,ry)=>{"use strict";ry.exports=ty;function ty(n,e,t){n instanceof RegExp&&(n=ey(n,t)),e instanceof RegExp&&(e=ey(e,t));var r=ny(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 ey(n,e){var t=e.match(n);return t?t[0]:null}ty.range=ny;function ny(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 uy=Sp((xQ,py)=>{"use strict";var iy=oy();py.exports=nR;var sy="\0SLASH"+Math.random()+"\0",ay="\0OPEN"+Math.random()+"\0",hd="\0CLOSE"+Math.random()+"\0",ly="\0COMMA"+Math.random()+"\0",cy="\0PERIOD"+Math.random()+"\0";function md(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function eR(n){return n.split("\\\\").join(sy).split("\\{").join(ay).split("\\}").join(hd).split("\\,").join(ly).split("\\.").join(cy)}function tR(n){return n.split(sy).join("\\").split(ay).join("{").split(hd).join("}").split(ly).join(",").split(cy).join(".")}function dy(n){if(!n)return[""];var e=[],t=iy("{","}",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=dy(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function nR(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),Ri(eR(n),!0).map(tR)):[]}function rR(n){return"{"+n+"}"}function oR(n){return/^-?0\d/.test(n)}function iR(n,e){return n<=e}function sR(n,e){return n>=e}function Ri(n,e){var t=[],r=iy("{","}",n);if(!r)return[n];var o=r.pre,i=r.post.length?Ri(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+hd+r.post,Ri(n)):[n];var u;if(d)u=r.body.split(/\.\./);else if(u=dy(r.body),u.length===1&&(u=Ri(u[0],!1).map(rR),u.length===1))return i.map(function(J){return r.pre+u[0]+J});var m;if(d){var h=md(u[0]),f=md(u[1]),g=Math.max(u[0].length,u[1].length),y=u.length==3?Math.abs(md(u[2])):1,v=iR,S=f<h;S&&(y*=-1,v=sR);var E=u.some(oR);m=[];for(var T=h;v(T,f);T+=y){var C;if(c)C=String.fromCharCode(T),C==="\\"&&(C="");else if(C=String(T),E){var P=g-C.length;if(P>0){var k=new Array(P+1).join("0");T<0?C="-"+k+C.slice(1):C=k+C}}m.push(C)}}else{m=[];for(var N=0;N<u.length;N++)m.push.apply(m,Ri(u[N],!1))}for(var N=0;N<m.length;N++)for(var s=0;s<i.length;s++){var a=o+m[N]+i[s];(!e||d||a)&&t.push(a)}}return t}});var al=(n,e)=>{},zo=()=>{},ll=!1;try{let n=await import("@sentry/node"),{nodeProfilingIntegration:e}=await import("@sentry/profiling-node");al=n.captureException,zo=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(),ll=!0}catch{}import{Command as gL,Option as qt}from"@commander-js/extra-typings";import{execSync as yL}from"child_process";import TS from"body-parser";import oP from"cors";import iP from"dedent";import sP from"events";import ES,{Router as aP}from"express";import lP from"http";import{z as vn}from"zod";var Ki=vn.object({x:vn.number(),y:vn.number(),correlation:vn.number()}),OL=vn.object({searchImageBase64String:vn.string(),pageImageBase64String:vn.string(),id:vn.string().uuid(),timeoutMs:vn.number().max(1e4).min(0).optional()});import{z as _}from"zod";import{v4 as Le}from"uuid";import*as w from"zod";function me(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 ie}from"zod";me(ie);var bp=ie.object({plan:ie.string().optional(),evidence:ie.string().optional(),thoughts:ie.string(),result:ie.boolean(),relevantElements:ie.array(ie.number()).optional()}),Bo=(r=>(r.CONTAINS="CONTAINS",r.STARTS_WITH="STARTS_WITH",r.EQUALS="EQUALS",r))(Bo||{});var Fb=ie.object({type:ie.literal("ELEMENT_CONTENT"),negated:ie.boolean().optional(),operation:ie.nativeEnum(Bo),value:ie.string()}).openapi({ref:"ElementContentAssertion"}),Ub=ie.object({type:ie.literal("ELEMENT_ATTRIBUTE"),negated:ie.boolean().optional(),operation:ie.nativeEnum(Bo),attr:ie.string(),value:ie.string()}).openapi({ref:"ElementAttributeValueAssertion"}),jo=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(jo||{}),zb=ie.object({type:ie.literal("ELEMENT_EXISTENCE"),negated:ie.boolean().optional(),condition:ie.nativeEnum(jo)}).openapi({ref:"ElementExistenceAssertion"}),wp=ie.discriminatedUnion("type",[Fb,Ub,zb]).openapi({ref:"ManualElementAssertion"});var Bb=ie.object({type:ie.literal("CONTENT"),negated:ie.boolean().optional(),value:ie.string()}).openapi({ref:"PageContentAssertion"}),vp=ie.discriminatedUnion("type",[Bb]).openapi({ref:"ManualPageAssertion"});import*as K from"zod";me(K);var Qn=(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))(Qn||{}),er=K.object({id:K.number().int(),dataMomenticId:K.number().int().optional(),selector:K.string().optional(),generatedSelectors:K.string().array().optional(),role:K.string().optional(),name:K.string().optional(),numChildren:K.number().optional(),content:K.string().optional(),pathFromRoot:K.string().optional(),serializedForm:K.string().optional(),nodeOnlySerializedForm:K.string().optional(),serializedHtml:K.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:K.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:K.string().url().optional(),boundingBox:K.object({x:K.number().optional(),y:K.number().optional(),width:K.number(),height:K.number()}).describe("css pixel bounding box").optional(),inputDescription:K.string().optional().describe("the description that generated this cache"),targetSource:K.nativeEnum(Qn).optional(),targetUpdateTime:K.string().optional()}).openapi({ref:"A11yTargetWithCache"});function Yi(n){return!!(n.name||n.role||n.content||n.serializedForm||n.serializedHtml||n.screenshotUrl)}var jb=K.object({type:K.literal("description"),elementDescriptor:K.string(),a11yData:er.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),$b=K.object({x:K.number(),y:K.number()}),Hb=K.object({type:K.literal("coordinates"),pixels:$b}).openapi({ref:"CoordinatesTarget"});function Ln(n){return n.type==="description"}function ln(n){return n.type==="coordinates"}var it=K.discriminatedUnion("type",[jb,Hb]).openapi({ref:"ElementTarget"});function cl(n){if(!n)return!1;switch(n.type){case"description":return!!n.elementDescriptor}return!0}function st(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 ee}from"zod";var Ji=ee.object({url:ee.string(),method:ee.union([ee.literal("GET"),ee.literal("POST"),ee.literal("PUT"),ee.literal("DELETE"),ee.literal("PATCH")]),headers:ee.record(ee.string(),ee.string()).optional(),params:ee.record(ee.string(),ee.string()).optional(),body:ee.string().optional(),timeout:ee.number().int().optional().describe("Max seconds to wait for the request to complete")}),xp=ee.object({url:ee.string(),headers:ee.record(ee.string(),ee.string()).optional(),query:ee.string(),variables:ee.record(ee.string(),ee.string()).optional(),timeout:ee.number().int().optional().describe("Max seconds to wait for the request to complete")}),Xi=ee.object({code:ee.string(),fragment:ee.boolean().optional(),environment:ee.union([ee.literal("NODE"),ee.literal("BROWSER")]).optional().describe("default NODE"),timeout:ee.number().int().max(60).optional().describe("Max seconds for the code to complete")});var je=(F=>(F.AI_EXTRACT="AI_EXTRACT",F.AI_ASSERTION="AI_ASSERTION",F.AI_WAIT="AI_WAIT",F.AUTH_LOAD="AUTH_LOAD",F.AUTH_SAVE="AUTH_SAVE",F.BLUR="BLUR",F.CAPTCHA="CAPTCHA",F.CLICK="CLICK",F.COOKIE="COOKIE",F.COPY="COPY",F.DIALOG="DIALOG",F.DRAG="DRAG",F.ELEMENT_CHECK="ELEMENT_CHECK",F.FILE_UPLOAD="FILE_UPLOAD",F.FOCUS="FOCUS",F.GO_BACK="GO_BACK",F.GO_FORWARD="GO_FORWARD",F.HOVER="HOVER",F.JAVASCRIPT="JAVASCRIPT",F.LOCAL_STORAGE="LOCAL_STORAGE",F.MOUSE_DRAG="MOUSE_DRAG",F.NAVIGATE="NAVIGATE",F.NEW_TAB="NEW_TAB",F.PAGE_CHECK="PAGE_CHECK",F.PASTE="PASTE",F.PRESS="PRESS",F.REFRESH="REFRESH",F.REQUEST="REQUEST",F.GRAPHQL_REQUEST="GRAPHQL_REQUEST",F.SCROLL_DOWN="SCROLL_DOWN",F.SCROLL_UP="SCROLL_UP",F.SCROLL_LEFT="SCROLL_LEFT",F.SCROLL_RIGHT="SCROLL_RIGHT",F.SELECT_OPTION="SELECT_OPTION",F.TAB="TAB",F.TYPE="TYPE",F.VISUAL_DIFF="VISUAL_DIFF",F.WAIT="WAIT",F.WAIT_FOR_URL="WAIT_FOR_URL",F.SUCCESS="SUCCESS",F))(je||{});me(w);var q=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),_t=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),cn=w.object({target:er}).optional().openapi({ref:"SingleTargetCache"}),Zi=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),Wb=q.merge(Zi).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Qi=_t.merge(w.object({cache:cn})),Mr=q.merge(Qi.merge(w.object({target:it.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Dr=q.merge(Qi.merge(w.object({target:it.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Fr=q.merge(Qi.merge(w.object({target:it.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ur=q.merge(Qi.merge(w.object({target:it.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),KL=w.discriminatedUnion("type",[Mr,Dr,Fr,Ur]).openapi({ref:"AllScrollCommands"}),Gb=q.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Vb=q.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),qb=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()})]),Kb=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")}),Yb=q.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:qb.optional()}).merge(Kb).openapi({ref:"WaitUrlCommand"}),Jb=q.merge(Zi).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Xb=q.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Zb=q.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),Qb=q.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),ew=q.extend({type:w.literal("AUTH_LOAD"),storageState:w.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),ul=q.merge(_t).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),tw=q.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),nw=q.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),rw=q.merge(Xi).extend({type:w.literal("JAVASCRIPT"),envKey:w.string().optional()}).openapi({ref:"JavaScriptCommand"}),$o=q.merge(_t).merge(w.object({type:w.literal("CLICK"),target:it,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:cn})).openapi({ref:"ClickCommand"}),Ho=q.merge(_t).merge(w.object({type:w.literal("DRAG"),fromTarget:it,toTarget:it,hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:w.object({fromTarget:er.optional(),toTarget:er.optional()}).optional()})).openapi({ref:"DragCommand"}),Wo=q.merge(_t).merge(w.object({type:w.literal("MOUSE_DRAG"),target:it.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:cn})).openapi({ref:"MouseDragCommand"}),Go=q.merge(_t).merge(w.object({type:w.literal("HOVER"),target:it,cache:cn})).openapi({ref:"HoverCommand"}),Vo=q.merge(_t).merge(w.object({type:w.literal("FOCUS"),target:it,cache:cn})).openapi({ref:"FocusCommand"}),qo=q.merge(_t).extend({type:w.literal("BLUR"),target:it.optional(),cache:cn}).openapi({ref:"BlurCommand"}),ow=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),iw=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=q.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[ow,iw]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),aw=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()})]),Ko=q.merge(_t).extend({type:w.literal("SELECT_OPTION"),target:it,cache:cn,option:w.string().describe("option value, deprecated old field").optional(),choice:aw.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),ml=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),hl=q.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:ml.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),lw=hl.extend({type:w.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),xn=5,fl=600,Yo=q.merge(_t).extend({type:w.literal("ELEMENT_CHECK"),target:it,assertion:wp,cache:cn,timeout:w.number().int().min(0).max(fl).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),cw=q.extend({type:w.literal("PAGE_CHECK"),assertion:vp,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(fl).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),dw=q.merge(w.object({type:w.literal("AI_EXTRACT"),goal:w.string(),schema:w.string().optional(),envKey:w.string().optional(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional()})).openapi({ref:"AIExtractCommand"}),pw=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()}),Jo=q.merge(_t).merge(pw).extend({type:w.literal("TYPE"),target:it.optional(),value:w.string(),cache:cn}).openapi({ref:"TypeCommand"}),uw=q.merge(w.object({type:w.literal("PRESS"),value:w.string(),repeat:w.number().optional(),convertMeta:w.boolean().optional()})).openapi({ref:"PressCommand"}),mw=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),hw=w.object({type:w.literal("REGEX"),pattern:w.string()}),fw=w.object({type:w.literal("INDEX"),index:w.number()}),gw=w.discriminatedUnion("type",[mw,hw,fw]),yw=q.merge(Zi).merge(w.object({type:w.literal("TAB"),url:w.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:gw.optional()})).openapi({ref:"TabCommand"}),Sw=q.merge(Zi).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),bw=q.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),ww=q.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),vw=q.extend({type:w.literal("REQUEST")}).merge(Ji).openapi({ref:"RequestCommand"}),xw=q.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(xp).openapi({ref:"GraphQLRequestCommand"}),Tw=q.merge(w.object({type:w.literal("SUCCESS"),condition:hl.optional()})).openapi({ref:"SuccessCommand"}),Ew=q.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Cw=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),Xo=q.merge(_t).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:it.optional(),screenshot:Cw.optional(),cache:cn})).openapi({ref:"VisualDiffCommand"}),Tp=w.discriminatedUnion("type",[$o,Jo,uw,Ko,Wb,Dr,Mr,hl,Go,Vb,Tw]),Aw=w.discriminatedUnion("type",[lw,dw,ew,Qb,ul,bw,tw,Gb,Ho,Yo,sw,Xb,Zb,rw,ww,Wo,Sw,cw,nw,Jb,vw,xw,Fr,Ur,yw,Xo,Vo,qo,Yb]),es=w.discriminatedUnion("type",[...Tp.options,...Aw.options]).openapi({ref:"Command"}),ts=w.discriminatedUnion("type",[...Tp.options,Ew]);function On(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:Le(),type:n};break;case"AUTH_LOAD":{e={id:Le(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:Le(),type:n,goal:""};break;case"DIALOG":e={id:Le(),type:n,action:"DISMISS"};break;case"DRAG":e={id:Le(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Le(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Le(),type:n,url:""};break;case"WAIT":e={id:Le(),type:n,delay:1};break;case"BLUR":e={id:Le(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Le(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Le(),type:n,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Le(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Le(),type:n,url:""};break;case"REQUEST":e={id:Le(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Le(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Le(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:Le(),type:n,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Le(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:Le(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Le(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Le(),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 Rw}from"zod";var QL=Rw.discriminatedUnion("type",[qo,ul,$o,Ho,Vo,Go,Wo,Mr,Dr,Fr,Ur,Ko,Jo,Xo,Yo]);function Ep(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as Iw}from"zod";var gt={type:!0,cache:!0},tr=Iw.discriminatedUnion("type",[qo.pick(gt),$o.pick(gt),Ho.pick(gt),Yo.pick(gt),Vo.pick(gt),Go.pick(gt),Wo.pick(gt),Mr.pick(gt),Dr.pick(gt),Fr.pick(gt),Ur.pick(gt),Ko.pick(gt),Jo.pick(gt),Xo.pick(gt)]),gl=Object.values(je).filter(n=>tr.options.some(e=>e.shape.type.safeParse(n).success));es.options.forEach(n=>{if("target"in n.shape&&!gl.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as Sl}from"zod";import{z as yl}from"zod";import{z as zr}from"zod";var yt=zr.object({index:zr.number().optional().describe("global index within a test (in-order traversal)"),id:zr.string(),skipped:zr.boolean().optional(),envKey:zr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:zr.boolean().optional()});me(yl);var St=yt.extend({type:yl.literal("PRESET_ACTION"),command:es,skipped:yl.boolean().optional()}).openapi({ref:"PresetAction"});me(Sl);var nr=yt.extend({type:Sl.literal("AI_ACTION"),text:Sl.string(),steps:St.array().optional()}).openapi({ref:"AIAction"});import{z as ne}from"zod";var Pw=ne.object({cacheKey:ne.string(),cacheExpiryMs:ne.number()}),bl=yt.extend({id:ne.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ne.record(ne.string()).optional(),cacheConfig:Pw.optional()}),Tn=bl.extend({type:ne.literal("MODULE"),moduleId:ne.string().uuid()}),Lw=ne.union([Tn.pick({type:!0,moduleId:!0}),ne.record(ne.unknown())]),Ow=ne.object({type:ne.literal("URL_REGEX"),regex:ne.string()}),kw=ne.object({type:ne.literal("PAGE_CHECK"),substring:ne.string()}),wl=ne.object({cacheInvalidation:ne.discriminatedUnion("type",[kw,Ow]).optional()}),bt=ne.object({moduleId:ne.string().uuid(),name:ne.string(),description:ne.string().nullish(),enabled:ne.boolean().nullish(),parameters:ne.string().array().nullish(),defaultParameters:ne.record(ne.string(),ne.string()).nullish(),defaultCacheKey:ne.string().nullish(),defaultCacheTtl:ne.number().nullish(),defaultCacheAllInvocations:ne.boolean().nullish(),autoAuth:ne.boolean().nullish(),advanced:wl.nullish()});import{z as Xe}from"zod";import{z as vl}from"zod";me(vl);var Br=yt.extend({type:vl.literal("AI_ACTION_DYNAMIC"),text:vl.string()}).openapi({ref:"AIActionDynamic"});import{z as Cp}from"zod";var xl=yt.extend({type:Cp.literal("CONDITIONAL"),skipped:Cp.boolean().optional()});import{z as Nt}from"zod";var _w=Nt.object({type:Nt.literal("attr"),name:Nt.string(),value:Nt.string()}),Nw=Nt.object({type:Nt.literal("css"),selector:Nt.string()}),Mw=Nt.object({type:Nt.literal("url"),url:Nt.string()}),Dw=Nt.union([_w,Mw,Nw]),Zo=yt.extend({type:Nt.literal("IFRAME"),identifier:Dw});import{z as Mt}from"zod";var Tl=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(Tl||{});var Fw=Mt.discriminatedUnion("type",[Mt.object({type:Mt.literal("NAVIGATE_URL"),url:Mt.string().url()}),Mt.object({type:Mt.literal("GO_TO_SECTION_START")})]),Uw=Mt.object({trigger:Mt.nativeEnum(Tl).optional(),attempts:Mt.number().int().optional(),restartBehavior:Fw}),Qo=yt.extend({type:Mt.literal("SECTION"),description:Mt.string().describe("user provided goal of what the section should accomplish"),plan:Mt.string().array().optional(),autohealingConfig:Uw.optional()});var Ap=bt.merge(bl).extend({type:Xe.literal("RESOLVED_MODULE"),steps:Xe.lazy(()=>Ae.array())}),El=bt.extend({steps:Xe.lazy(()=>Ae.array())}),Cl=Zo.extend({steps:Xe.lazy(()=>$e.array())}),zw=Zo.extend({steps:Xe.lazy(()=>Ae.array())}),Al=Qo.extend({steps:Xe.lazy(()=>$e.array())}),Bw=Qo.extend({steps:Xe.lazy(()=>Ae.array())}),rr=xl.extend({blocks:Xe.object({assertion:Xe.lazy(()=>St),steps:Xe.lazy(()=>$e.array())}).array(),elseSteps:Xe.lazy(()=>$e.array().optional())}),jw=xl.extend({blocks:Xe.object({assertion:Xe.lazy(()=>St),steps:Xe.lazy(()=>Ae.array())}).array(),elseSteps:Xe.lazy(()=>Ae.array().optional())}),$e=Xe.discriminatedUnion("type",[St,nr,Br,Tn,rr,Cl,Al]),Ae=Xe.discriminatedUnion("type",[St,nr,Br,Ap,jw,zw,Bw]);import{z as Dt}from"zod";var $w=Dt.object({steps:$e.array(),beforeSteps:$e.array().nullish(),afterSteps:$e.array().nullish()}),jr=Dt.object({steps:Ae.array(),beforeSteps:Ae.array().nullish(),afterSteps:Ae.array().nullish()}),or=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 ut="1.0.19";import{z as ir}from"zod";var Rl=ir.object({key:ir.string(),testId:ir.string().optional(),moduleId:ir.string().optional(),organizationId:ir.string(),value:tr}),Rp=ir.record(ir.string(),Rl);var Ip=_.object({phrase:_.string()}),Il=_.object({thoughts:_.string().optional(),result:_.union([_.literal("NOT_FOUND"),_.string(),_.number(),_.array(_.unknown()),_.record(_.unknown(),_.unknown()),_.unknown()])}),Zk=_.object({text:_.string()}),Pp=_.object({thoughts:_.string(),id:_.number().int()}),Hw=_.discriminatedUnion("op",[_.object({op:_.literal("replace"),path:_.string(),value:_.string()}),_.object({op:_.literal("add"),path:_.string(),value:_.string()}),_.object({op:_.literal("remove"),path:_.string()})]),Qk=_.object({thoughts:_.string(),patches:Hw.array()}),Lp=[_.literal("add"),_.literal("replace"),_.literal("remove")],Ww=_.object({op:_.union(Lp),path:_.string(),value:Ae.optional()}),Op=_.object({patches:Ww.array(),thoughts:_.string()});var Gw=_.object({thoughts:_.string(),op:_.union(Lp),value:_.union([_.null(),Ae])}),kp=_.object({reasoning:_.string(),scenario:_.string(),patch:Gw.or(_.null())}),e_=_.object({thoughts:_.string(),evaluation:_.number().min(1).max(10)}),t_=_.object({observations:_.string(),reasoning:_.string(),command:ts});var Pl=_.object({summary:_.string(),reasoning:_.string(),evaluation:_.discriminatedUnion("type",[_.object({type:_.literal("DONE")}),_.object({type:_.literal("RIGHT_TRACK")}),_.object({type:_.literal("WRONG_TRACK"),feedback:_.string()}),_.object({type:_.literal("IMPOSSIBLE")})])});import{z as mt}from"zod";var Ll=mt.object({content:mt.string(),ids:mt.string().array(),tokenLength:mt.number()}),Vw=mt.object({chunks:Ll.array()}),o_=mt.object({ids:mt.string().array(),score:mt.number(),tokenLength:mt.number()}),i_=Vw.extend({description:mt.string().describe("Input to pass to RAG engine"),tokenLimit:mt.number()}),_p=mt.object({ids:mt.number().array()}),Np=mt.object({indices:mt.number().array()});import{z as D}from"zod";import{z as oi}from"zod";import{z as hx}from"zod";import*as W from"zod";import{cloneDeep as ti}from"lodash-es";var qw=n=>{let e=Mp(n,0);if(e===void 0||!Yw(n[e]))return;let t=Mp(n,e+1);if(t!==void 0)return Jw(n,e,t)},Dp=qw,Mp=(n,e)=>{for(let t=e;t<n.length;t+=1){let r=n[t];if(!Kw(r))return t}},Kw=n=>n===" "||n===" "||n===`
5
5
  `||n==="\r",Yw=n=>n==="{"||n==="[",Jw=(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 Xw(r);if(r===void 0)r=i;else if(r[0]===i)r+=i;else return}},Xw=n=>n===void 0?0:n[0]===" "?n.length:n;var Fp=(n,e)=>{let t=Ol(n,"toPrecision",e,e);return t===void 0?Ol(n,"toExponential",e,e):t},Ol=(n,e,t,r)=>{let i=n[e](r).replace(Zw,"$1").replace(Qw,"$1");return i.length<=t?i:r===1?void 0:Ol(n,e,t,r-1)},Zw=/(e)\+/iu,Qw=/\.?0*($|e)/iu;var zp=(n,e)=>{if(typeof n!="string")throw new TypeError(`Input must be a JSON string: ${n}`);ev(e)},ev=n=>{if(tv(n),n<0)throw new TypeError(`"maxSize" argument must be positive: ${n}`);if(n<Up)throw new TypeError(`"maxSize" argument must be at least ${Up}: ${n}`)},tv=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}`)},Up=7;var ns=(n,e,t)=>{let r=jp(e,t);return Bp(n,e,r)},Bp=(n,e,t)=>{if(t>=e)return t;let r=n[t];return r>=dv&&r<=pv?Bp(n,e,t+1):t},rs=(n,e,t)=>{if(t===void 0)return t;let r=jp(e,t);return nv(n,r)},nv=(n,e)=>rv(n,e)?e-3:ov(n,e)?e-2:iv(n,e)?e-1:e,rv=(n,e)=>e>=3&&n[e-3]>=sv&&n[e-3]<=av,ov=(n,e)=>e>=2&&n[e-2]>=lv,iv=(n,e)=>e>=1&&n[e-1]>=cv,jp=(n,e)=>e<0||Object.is(e,-0)?Math.max(n+e,0):e,sv=240,av=244,lv=224,cv=194,dv=128,pv=191;var $p=(n,e,t)=>{let r=globalThis.Buffer.from(n),o=ns(r,r.length,e),i=rs(r,r.length,t);return o===0&&i>=r.length?r.toString():r.toString("utf8",o,i)};var Hp=/[\uD800-\uDFFF]/gu,Wp="\uFFFD";var os=n=>uv(n)?n.replace(Hp,Wp):n,uv=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 Nl=({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 f=n.charCodeAt(d+s);Number.isNaN(f)||f<o||f>i||(u+=1,d+=s)}return(a&&u>e?p:d)+l};var Ml=(n,e,t)=>e<0||Object.is(e,-0)?Sv(n,e,t):yv(n,e,t),yv=(n,e,t)=>Nl({input:n,targetByteCount:e,firstStartSurrogate:55296,lastStartSurrogate:56319,firstEndSurrogate:56320,lastEndSurrogate:57343,increment:1,canBacktrack:t,shift:0,charIndexInit:0}),Sv=(n,e,t)=>Nl({input:n,targetByteCount:-e,firstStartSurrogate:56320,lastStartSurrogate:57343,firstEndSurrogate:55296,lastEndSurrogate:56319,increment:-1,canBacktrack:!t,shift:1,charIndexInit:n.length-1});var is=(n,e,t)=>{let r=Ml(n,e,!1),o=bv(n,t),i=r===0&&o===void 0?n:n.slice(r,o);return os(i)},bv=(n,e)=>{if(e===void 0)return e;let t=Ml(n,e,!0);return t===n.length?void 0:t};var Vp=(n,e,t)=>{let{textEncoder:r,textDecoder:o}=wv(),i=vv(n),{written:s}=r.encodeInto(n,i),a=ns(i,s,e),l=rs(i,s,t),c=l===void 0?s:Math.min(l,s),d=i.subarray(a,c);return o.decode(d)},wv=()=>(Dl===void 0&&(Dl=new globalThis.TextEncoder,Gp=new globalThis.TextDecoder("utf8",{fatal:!1})),{textEncoder:Dl,textDecoder:Gp}),Dl,Gp,vv=n=>{let e=n.length*3;return e>xv?new Uint8Array(e):((ss===void 0||ss.length<e)&&(ss=new Uint8Array(e)),ss)},xv=1e5,ss;var qp=(n,e)=>{if(e===void 0)return e;let t=Fl(n,e);return t>=n.length*Kp?void 0:t},Fl=(n,e)=>e<=n.length*-Kp?0:e,Kp=4;var Yp=(n,e,t)=>{if(typeof n!="string")throw new TypeError(`First argument must be a string: ${n}`);Tv(e),Ev(t)},Tv=n=>{if(n===void 0)throw new TypeError("Second argument is required.");Jp("Second",n)},Ev=n=>{n!==void 0&&Jp("Third",n)},Jp=(n,e)=>{if(!Number.isInteger(e))throw new TypeError(`${n} argument must be an integer: ${e}`)};var Xp=n=>{let e=!0,t=0;for(let r=0;r<Ul;r+=1){let o=Cv(n,r);o<=127||(e&&(e=!1),o>2047&&(t+=1))}return{asciiOnly:e,longCharsPercentage:t/Ul}},Cv=(n,e)=>{let t=Ul-1,r=1-(t-e)/t,o=Math.round(r*(n.length-1));return n.charCodeAt(o)},Ul=50;var Av=(n,e,t)=>{if(Yp(n,e,t),n==="")return n;let r=Fl(n,e),o=qp(n,t);return o===void 0&&Object.is(r,0)?os(n):Rv(n,r,o)},Zp=Av,Rv=(n,e,t)=>{if(n.length<=Iv)return is(n,e,t);let{asciiOnly:r,longCharsPercentage:o}=Xp(n);return r?Lv(n,e,t):o>=Pv?is(n,e,t):Qp(n,e,t)},Iv=200,Pv=.4,Lv=(n,e,t)=>"Buffer"in globalThis&&"from"in globalThis.Buffer?$p(n,e,t):Qp(n,e,t),Qp=(n,e,t)=>"TextEncoder"in globalThis?Vp(n,e,t):is(n,e,t);var tu=(n,e)=>{let t=JSON.stringify(n),r=_v(t),o=Zp(r,0,e-eu.length-ei.length*2),s=`${Ov(o)}${eu}`;return Nv(s)},Ov=n=>n.replace(kv,""),kv=/(\\|\\u[0-9a-fA-F]{0,3})$/u,_v=n=>n.slice(ei.length,-ei.length),Nv=n=>`${ei}${n}${ei}`,ei='"',eu="...";var nu=n=>globalThis.Buffer.byteLength(n);var zl=n=>{let e=n.length,t=e;for(let r=0;r<e;r+=1){let o=n.charCodeAt(r);if(o<=Mv)continue;if(o<=Dv){t+=1;continue}if(t+=2,o<Fv||o>Uv)continue;let i=n.charCodeAt(r+1);i<zv||i>Bv||(r+=1)}return t},Mv=127,Dv=2047,Fv=55296,Uv=56319,zv=56320,Bv=57343;var ru=()=>jv.bind(void 0,new TextEncoder),jv=(n,e)=>{let t=$v(e);return n.encodeInto(e,t).written},$v=n=>{let e=n.length*3;return e>Hv?new Uint8Array(e):((as===void 0||as.length<e)&&(as=new Uint8Array(e)),as)},Hv=1e5,as;var Gv=()=>"Buffer"in globalThis&&"byteLength"in globalThis.Buffer?nu:"TextEncoder"in globalThis?Vv.bind(void 0,ru()):zl,Vv=(n,e)=>e.length<100?zl(e):n(e),ou=Gv();var iu=n=>{if(n===null)return qv;if(n===!0)return Kv;if(n===!1)return Yv;let e=typeof n;return e==="object"?Jv:e==="number"?JSON.stringify(n).length:Bl(n)},qv=4,Kv=4,Yv=5,Jv=2,Bl=n=>ou(JSON.stringify(n));var ls=({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}},au=n=>iu(n),lu=(n,e,t)=>{let r=du({empty:n,indent:e,depth:t,keySpaceSize:0}),o=pu(n);return r+o},cu=({key:n,empty:e,indent:t,depth:r})=>{let o=du({empty:e,indent:t,depth:r,keySpaceSize:1}),i=Bl(n),s=pu(e);return o+i+Xv+s},Xv=1,du=({empty:n,indent:e,depth:t,keySpaceSize:r})=>{if(e===void 0)return 0;let o=su+e*(t+1),i=n?su+e*t:0;return r+o+i},su=1,pu=n=>n?0:Zv,Zv=1;var cs=({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:f}=ls({size:a,increment:r,maxSize:o,truncatedProps:e,path:u,value:p});return h?{empty:s,size:m,truncatedProps:f}:Qv({value:p,truncatedProps:e,path:u,maxSize:o,empty:s,size:a,newSize:m,truncateValue:l,indent:c,depth:d})},Qv=({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 uu=({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=lu(c.empty,s,a);c=cs({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 mu=({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=cu({key:d,empty:c.empty,indent:s,depth:a});c=cs({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 ds=({value:n,truncatedProps:e,path:t,size:r,maxSize:o,indent:i,depth:s})=>{let a=au(n),{size:l,stop:c,truncatedProps:d}=ls({size:r,increment:a,maxSize:o,truncatedProps:e,path:t,value:n});return c?{value:void 0,size:l,truncatedProps:d}:ex({value:n,truncatedProps:d,path:t,size:l,maxSize:o,indent:i,depth:s})},ex=({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)?uu({array:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:ds,indent:i,depth:s}):mu({object:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:ds,indent:i,depth:s});var tx=(n,e)=>{zp(n,e);let t=nx(n),r=rx(n),{value:o,truncatedProps:i}=ds({value:r,truncatedProps:[],path:[],size:0,maxSize:e,indent:t,depth:0});return{jsonString:ox({newValue:o,value:r,maxSize:e,indent:t}),truncatedProps:i}},$r=tx,nx=n=>{let e=Dp(n);return typeof e=="string"?e.length:e},rx=n=>{try{return JSON.parse(n)}catch(e){throw new TypeError(`Invalid JSON string: "${n}"
7
- ${e.message}`)}},ox=({newValue:n,value:e,maxSize:t,indent:r})=>n!==void 0?JSON.stringify(n,void 0,r):typeof e=="number"?Fp(e,t):tu(e,t);import*as sr from"zod";import{z as wt}from"zod";var ve="BASE_URL",ps="CURRENT_URL",Hr="ENV_NAME",mN={[ve]:"https://www.google.com"},hu=wt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),us=wt.object({name:wt.string(),variables:wt.record(wt.string().describe("variable name"),wt.string().describe("variable value"))}),ms=wt.object({localChromeExtensionPaths:wt.string().array().optional(),disableGpu:wt.boolean().optional()}),hs=wt.object({name:wt.string(),variables:wt.record(wt.string().describe("variable name"),wt.unknown().describe("variable value")),browser:ms.optional()});me(sr);var ni=sr.object({env:sr.record(sr.unknown())}).openapi({ref:"TestContextSnapshot"}),ix="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",sx=[ve,Hr],fu=[ps,ve,Hr],vt=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[ps]??"about:blank",i=e.env[Hr],s={};for(let[l,c]of Object.entries(e.env))fu.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=ti(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){sx.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Hr]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ti(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>fu.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,ix]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:i}=$r(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(i)}catch{e.env[r]=void 0}}let{jsonString:t}=$r(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[ps]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=ti(e.variablesFromEnvironment),this.setMomenticSystemVariable(ve,e.baseUrl),e.envName&&this.setMomenticSystemVariable(Hr,e.envName)}getDynamicVariablesCopy(){return ti(this.env)}getVariablesFromEnvironmentCopy(){return ti(this.varsFromMomenticEnvironment)}};import{z as ar}from"zod";me(ar);var le=(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))(le||{});var gu=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],yu={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"},Su={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. Please reach out to Momentic Support for assistance."},jl=ar.object({reason:ar.nativeEnum(le),summary:ar.string()}).openapi({ref:"TestResultClassification"}),fs=ar.object({errorMessage:ar.string(),errorStack:ar.string().optional(),classification:jl.optional()}).openapi({ref:"TestFailureDetails"});me(W);var He=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(He||{}),$l=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))($l||{}),Hl=W.object({beforeUrl:W.string().optional(),afterUrl:W.string().optional(),message:W.string().optional(),beforeScreenshot:W.string().optional(),afterScreenshot:W.string().optional(),beforeSnapshot:W.string().optional(),afterSnapshot:W.string().optional(),startedAt:W.coerce.date(),finishedAt:W.coerce.date()}),ax=Hl.extend({viewport:W.object({height:W.number(),width:W.number()}),status:W.nativeEnum($l),message:W.string().optional(),elementInteracted:W.string().optional()}),kn=Hl.extend({status:W.nativeEnum(He),message:W.string().optional(),data:W.unknown().optional(),beforeTestContext:ni.optional(),afterTestContext:ni.optional(),failureReason:W.nativeEnum(le).optional(),details:W.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),gs=kn.merge(St).extend({results:ax.array(),proposedStep:St.optional()}),lx=kn.merge(nr).extend({results:W.lazy(()=>gs.array())}),cx=kn.merge(Br).extend({results:W.lazy(()=>gs.array())}),dx=kn.merge(Tn).extend({moduleName:W.string().optional(),results:W.lazy(()=>Ft.array())}),px=kn.merge(rr).extend({assertion:gs.optional(),results:W.lazy(()=>Ft.array()).describe("results for the block actually executed")}),ux=kn.merge(Zo).extend({results:W.lazy(()=>Ft.array())}),mx=kn.merge(Qo).extend({results:W.lazy(()=>Ft.array()),healingAttempts:W.lazy(()=>Ft.array().array()).optional()}),Ft=W.discriminatedUnion("type",[lx,cx,gs,dx,px,ux,mx]),_n=kn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),bu=Hl.extend({index:W.number().optional(),description:W.string(),pageState:W.string().optional()});var Wl=hx.object({results:Ft.array().describe("main results"),beforeResults:Ft.array().optional(),afterResults:Ft.array().optional()}),ys=Wl.partial();import{z as H}from"zod";import{z as he}from"zod";var fx=he.object({type:he.literal("FAILURE_RECOVERY"),thoughts:he.string()}),gx=he.object({type:he.literal("DESCRIPTION_UPDATE"),thoughts:he.string()}),Ss=he.discriminatedUnion("type",[gx,fx]),bs=(e=>(e.AUTO_HEALING="AUTO_HEALING",e))(bs||{}),yx=he.object({testId:he.string(),name:he.string(),orgId:he.string(),runId:he.string(),purpose:he.nativeEnum(bs).catch("AUTO_HEALING"),steps:Re.array(),details:Ss.or(Ss.array()).optional()}),BN=yx.pick({name:!0,orgId:!0}),Gl=he.object({id:he.string(),name:he.string().nullish(),createdAt:he.string().pipe(he.coerce.date()).or(he.date()),organizationId:he.string(),schemaVersion:he.string(),purpose:he.nativeEnum(bs).catch("AUTO_HEALING"),runId:he.string().nullish(),details:Ss.or(Ss.array()).nullish(),applied:he.boolean().nullish(),appliedAt:he.coerce.date().nullish()}),wu=Gl.extend({steps:Re.array()});import{isValidCron as Sx}from"cron-validator";import{z as Y}from"zod";import{z as Vl}from"zod";var ws=Vl.object({width:Vl.number().min(200).max(1e4),height:Vl.number().min(200).max(1e4)}),vu={"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}},HN=Object.keys(vu);var Yt=vu["Desktop Large"];var xu=1e4,Tu=6e4,lr=(t=>(t.CHROMIUM="Chromium",t.GOOGLE_CHROME="Google Chrome",t))(lr||{}),vs=Y.object({browserType:Y.nativeEnum(lr).optional(),pageLoadTimeoutMs:Y.number().optional().refine(n=>n===void 0||n<=Tu&&n>=-1,{message:`Page load timeout must be between 0 and ${Tu/1e3} seconds`}),smartWaitingTimeoutMs:Y.number().optional().refine(n=>n===void 0||n<=xu&&n>=-1,{message:`Smart waiting timeout must be between 0 and ${xu/1e3} seconds`}),extraHeaders:Y.record(Y.string(),Y.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Y.string().optional(),basicAuthorization:Y.object({username:Y.string().optional(),password:Y.string().optional()}).optional(),disableJavaScript:Y.boolean().optional(),disableGpu:Y.boolean().optional(),localChromeExtensionPaths:Y.string().array().optional()}),Eu=["extraHeaders","basicAuthorization","localChromeExtensionPaths"];var bx=Y.object({disableAICaching:Y.boolean().default(!1),failureRecovery:Y.boolean().optional().describe("undefined means inherit org settings")});var wx=Y.object({viewport:ws.optional()}),Wr=wx.merge(bx).merge(vs),Gr=Y.object({cron:Y.string().refine(n=>Sx(n),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Y.boolean().default(!1),env:Y.string().optional(),timeZone:Y.string().default("America/Los_Angeles"),jobKey:Y.string().optional()}),Vr=Y.object({onSuccess:Y.boolean().default(!1),failureMessage:Y.string().optional(),onFailure:Y.boolean().default(!0),successMessage:Y.string().optional()}),vx=Y.object({name:Y.string(),required:Y.boolean().optional(),defaultValue:Y.string().describe("this is not optional because we need a value when the editor is first loaded")}),xs=vx.array(),xx=Y.object({name:Y.string(),value:Y.string()}),Cu=xx.array(),Ts=Y.object({name:Y.string(),default:Y.boolean().optional(),fixtures:hu.array().optional()});me(H);var Ut={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ce=(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))(ce||{}),Es=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Es||{});var Ie=H.string().pipe(H.coerce.date()).or(H.date()),ri=H.object({id:H.string(),runKey:H.string(),organizationId:H.string(),createdAt:Ie,createdBy:H.string(),flake:H.boolean().nullish(),scheduledAt:Ie.or(H.null()),startedAt:Ie.or(H.null()),updatedAt:Ie.nullish(),finishedAt:Ie.or(H.null()),resolvedBaseUrl:H.string().nullish(),environmentName:H.string().nullish(),section:H.nativeEnum(Es).nullish(),status:H.nativeEnum(ce),trigger:H.nativeEnum(Ut),attempts:H.number(),runAttempts:H.array(H.object({id:H.string(),status:H.nativeEnum(ce),startedAt:Ie.or(H.null()),finishedAt:Ie.or(H.null())})).optional(),videos:H.array(H.string()).optional(),failureReason:H.nativeEnum(le).nullish(),failureDetails:fs.nullish(),testFragments:H.array(Gl).nullish(),localTestId:H.string().nullish(),testId:H.string().nullish(),testName:H.string().nullish(),test:H.object({name:H.string(),id:H.string()}).nullish().default(null),suiteId:H.string().nullish()}).openapi({ref:"RunMetadata"}),Tx={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Cs=ri.pick({...Tx,test:!0}),Au=ri.omit({failureReason:!0,failureDetails:!0,test:!0}),ql=ri.extend({stepsSnapshot:H.array(H.record(H.unknown())).nullish(),resolvedInputs:H.record(H.string(),H.string()).nullish(),test:H.object({name:H.string(),id:H.string(),baseUrl:H.string().nullish(),advanced:Wr.nullish()}).nullish()}).merge(Wl),Ru=n=>n.includes("PASSED")&&n.includes("FAILED");var Ex=oi.object({id:oi.string().uuid(),startedAt:Ie.or(oi.null()),finishedAt:Ie.or(oi.null()),status:oi.nativeEnum(ce)}).merge(ys),lM=Ex.array();var As=(t=>(t.JUNIT="junit",t.ALLURE="allure",t))(As||{});import{z as We}from"zod";var Cx=We.object({id:We.string(),status:We.nativeEnum(ce),trigger:We.nativeEnum(Ut),createdAt:Ie,startedAt:Ie.nullish(),finishedAt:Ie.nullish(),gitCommitSha:We.string().nullish(),gitCommitShaShort:We.string().nullish(),gitCommitTimestamp:Ie.nullish(),gitBranchName:We.string().nullish(),gitOriginUrl:We.string().nullish(),gitCommitMessage:We.string().nullish(),gitCommitAuthorName:We.string().nullish(),githubRepository:We.string().nullish(),gitlabProjectPath:We.string().nullish(),pipelineId:We.string().nullish(),suite:We.object({id:We.string(),name:We.string()}).nullish(),runs:We.object({status:We.nativeEnum(ce)}).array()}).openapi({ref:"RunGroup"}),Iu=Cx.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Cs.array()});import{z as Ge}from"zod";import*as re from"zod";var SM=re.object({thoughts:re.string().optional().describe("only provided if a description was provided"),target:er.optional().describe("only provided if a description was provided"),pageState:re.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:re.object({label:re.string(),value:re.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:re.object({data:re.string(),height:re.number().int(),width:re.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Pu="<select> element",Lu="text input or contenteditable element",Ax="text input element",Kl=[Pu,Lu,Ax];function Ou(n,e){if(n===e)return!0;for(let t of Kl){if(!n.startsWith(t))continue;let r=n.slice(t.length+2);if(Kl.some(o=>e.startsWith(o)&&e.slice(o.length+2)===r)||r===e)return!0}return!!Kl.some(t=>e.startsWith(t)&&e.slice(t.length+2)===n)}function Rs(n,e){if(!e||"useSelector"in n&&n.useSelector)return e;switch(n.type){case"SELECT_OPTION":return`${Pu}: ${e}`;case"TYPE":return`${Lu}: ${e}`;default:return e}return e}var ii=re.object({matched:re.boolean(),reason:re.string().optional().describe("Human understandable description"),logs:re.string().array().optional().describe("Logs for debugging")}),Rx=ii.extend({type:re.literal("A11Y_ID")}),Ix=ii.extend({type:re.literal("USER_SELECTOR")}),Px=ii.extend({type:re.literal("CSS_SELECTOR"),selectors:re.string().array()}),Lx=ii.extend({type:re.literal("HTML_DISTANCE"),distance:re.number().optional(),closestElement:re.string().optional(),savedElement:re.string().optional()}),Ox=ii.extend({type:re.literal("TEMPLATE_MATCHING"),elementImageUrl:re.string().url()}),ku=re.discriminatedUnion("type",[Rx,Ix,Px,Lx,Ox]);var kx=Ge.object({type:Ge.literal("TARGETING"),name:Ge.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:ku.array(),pageState:Ge.string().optional(),targetSource:Ge.nativeEnum(Qn).optional(),targetUpdateTime:Ge.string().optional()}),_x=Ge.object({type:Ge.literal("AI_LOCATION"),matched:Ge.boolean(),pageState:Ge.string().optional(),ragUsed:Ge.boolean().optional(),thoughts:Ge.string().optional()}),Nx=Ge.object({type:Ge.literal("ASSERTION"),relevantElementsSerialized:Ge.string().array().optional(),pageState:Ge.string().optional(),ragUsed:Ge.boolean().optional()}),_u=Ge.discriminatedUnion("type",[kx,_x,Nx]);function Is(){return{details:[]}}import{z as Oe}from"zod";var Mx=Oe.object({id:Oe.string(),name:Oe.string()}),RM=Mx.merge(Oe.object({createdAt:Ie,createdBy:Oe.string(),schedule:Gr,notification:Vr,environment:Oe.object({name:Oe.string()}).nullish(),beforeTests:Oe.object({id:Oe.string()}).array().nullish(),afterTests:Oe.object({id:Oe.string()}).array().nullish()})),Nu=Oe.object({id:Oe.string().uuid(),orgId:Oe.string(),createdAt:Ie,startedAt:Ie.or(Oe.null()),finishedAt:Ie.or(Oe.null()),status:Oe.nativeEnum(ce),trigger:Oe.nativeEnum(Ut),suite:Oe.object({id:Oe.string(),name:Oe.string()}).nullish(),runs:ri.array()}),IM=Nu.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Mu=Nu.extend({runs:Cs.array()});var Jt=D.object({disableCache:D.boolean().optional(),loggerTags:D.record(D.string(),D.string()).optional(),langfuseSessionId:D.string().optional()}),Dx=D.object({screenshotBase64AfterCommand:D.string(),urlAfterCommand:D.string(),serializedCommand:D.string(),elementInteracted:D.string().optional(),thoughts:D.string().optional()}),WM=D.object({goal:D.string(),browserState:D.string(),screenshot:D.string(),feedback:D.string().optional()}),GM=D.object({goal:D.string(),browserState:D.string()}),Du=D.object({goal:D.string(),browserState:D.string(),screenshot:D.string().optional(),returnSchema:D.string().optional()}),Fu=D.object({goal:D.string(),browserState:D.string(),screenshot:D.string(),url:D.string(),contextChoice:ml.optional()}),Yl=D.object({goal:D.string(),browserState:D.string(),startingScreenshot:D.string().optional(),screenshot:D.string(),url:D.string(),history:Dx.array(),actionHint:D.string().optional(),lastError:D.string().optional()}),Uu=D.object({results:Ft.array(),errorMessage:D.string(),errorStack:D.string().optional()}),zu=D.object({results:D.array(Ft),goal:D.string(),errorMessage:D.string()}),Bu=D.object({failedResults:bu.array(),nextStepsSerialized:D.string().array(),currentUrl:D.string(),currentPageState:D.string(),currentScreenshot:D.string()}),VM=D.object({description:D.string(),type:D.union([D.literal("locator"),D.literal("assertion"),D.literal("ai-action")]),excerpt:D.string()});import{z as si}from"zod";var YM=si.object({goal:si.string()}),ju=si.object({keywords:si.array(si.string())});import{z as $u}from"zod";var ZM=$u.object({input:$u.string()});var Hu=n=>!(!n.org_id||!n.user_id||!n.platform);import{z as cr}from"zod";var Wu=cr.object({id:cr.string().uuid(),skipped:cr.boolean().optional(),envKey:cr.string().optional().describe("key in the environment to save the result of this step to")}),Jl=Wu.merge(Ji).extend({type:cr.literal("REQUEST")}),Xl=Wu.merge(Xi).extend({type:cr.literal("JAVASCRIPT")}),Zl=cr.discriminatedUnion("type",[Xl,Jl]);import{z as zt}from"zod";import{z as dr}from"zod";var Fx=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Pe=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 Ps=dr.string().min(1).max(255).superRefine((n,e)=>{try{ai(n)}catch(t){return e.addIssue({code:dr.ZodIssueCode.custom,message:t.message,fatal:!0}),dr.NEVER}});function ai(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(Fx))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ls=dr.preprocess(n=>n===null?"":n,dr.union([dr.string().url(),dr.literal("")])).optional();var Gu=zt.object({id:zt.string(),name:Ps,description:zt.string().optional().nullish(),baseUrl:Ls.nullish(),schemaVersion:zt.string(),advanced:zt.unknown().optional(),retries:zt.number(),envs:zt.array(Ts).nullish(),parameters:xs.nullish()}),Ux=zt.object({createdAt:zt.coerce.date(),updatedAt:zt.coerce.date(),schedule:Gr.nullish(),notification:Vr.nullish(),createdBy:zt.string(),organizationId:zt.string()}),zx=Gu.merge(Ux),SD=zx.extend({steps:Zl.array()}),bD=Gu.extend({steps:Zl.array()});import{z as xt}from"zod";var Vu=xt.object({startedAt:xt.coerce.date(),finishedAt:xt.coerce.date(),status:xt.nativeEnum(He),message:xt.string().optional(),data:xt.unknown().optional()}),jx=Vu.merge(Xl).extend({type:xt.literal("JAVASCRIPT")}),$x=Vu.merge(Jl).extend({type:xt.literal("REQUEST")}),Hx=xt.discriminatedUnion("type",[jx,$x]),qu=xt.object({startedAt:xt.coerce.date(),finishedAt:xt.coerce.date().nullish(),status:xt.nativeEnum(ce),results:Hx.array(),failureReason:xt.string().nullish(),failureDetails:fs.nullish()});import{z as Tt}from"zod";var Wx=Tt.object({id:Tt.string(),organizationId:Tt.string(),createdAt:Tt.coerce.date(),updatedAt:Tt.coerce.date(),createdBy:Tt.string(),scheduledAt:Tt.coerce.date().nullish(),startedAt:Tt.coerce.date().nullish(),finishedAt:Tt.coerce.date().nullish(),status:Tt.nativeEnum(ce),trigger:Tt.nativeEnum(Ut),results:qu.array().nullish(),apiTestName:Tt.string().nullish(),apiTestPath:Tt.string().nullish(),apiTestId:Tt.string().nullish()}),ID=Wx.pick({status:!0,startedAt:!0,finishedAt:!0});var li=(t=>(t.TestRun="test-run",t.CreditsUsed="credits-used",t))(li||{}),Ku=3;function Gx(n){return n==="MODULE"||n==="IFRAME"||n==="CONDITIONAL"||n==="SECTION"||n==="RESOLVED_MODULE"}function Ql(n){if(!Gx(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 ec(n){switch(n.type){case"AI_EXTRACT":return 3;case"AI_ASSERTION":return Ku;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 Os=class{async reportBillableEvent(e,t,r){}async reportCreditsUsed(e,t,r,o){}};function tc(n,e){return{...n,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as Vx,splitCookiesString as qx}from"set-cookie-parser";import{z as oe}from"zod";var nc=oe.object({name:oe.string(),value:oe.string(),url:oe.string().optional(),domain:oe.string().optional(),path:oe.string().optional(),expires:oe.number().default(Date.now()/1e3+60*60*24*365),httpOnly:oe.boolean().optional(),secure:oe.boolean().default(!0),sameSite:oe.union([oe.literal("Strict"),oe.literal("Lax"),oe.literal("None")]).default("None")});function ks(n,e){let t=[],r=qx(n);for(let o of r){let i=Vx(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=nc.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 Kx=oe.object({origin:oe.string(),localStorage:oe.array(oe.object({name:oe.string(),value:oe.string()}))}),Yx=oe.object({entries:oe.record(oe.string(),oe.array(oe.tuple([oe.unknown(),oe.unknown()]))),version:oe.number().optional()}),_s=oe.object({cookies:nc.array().optional(),origins:Kx.array().optional(),idb:oe.record(oe.string(),Yx).optional().describe("key is db name")});function Ns(n,e){let t=[];return n.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=nc.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 JD=new Set(Object.values(je));var Jx={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"},XD={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:[]},ZD={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 B}from"zod";var r0=B.object({body:B.string(),to:B.string(),from:B.string()}),o0=B.object({from:B.string().optional(),to:B.string(),timeout:B.number().optional(),beforeDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional()}),i0=B.object({to:B.string(),from:B.string(),subject:B.string(),body:B.string()}),s0=B.object({inbox:B.string(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),timeout:B.number().optional(),trimWhitespace:B.boolean().optional()}),a0=B.object({inbox:B.string(),limit:B.number().optional(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),trimWhitespace:B.boolean().optional()});var Yu=B.object({result:B.unknown(),variableUpdates:B.record(B.string(),B.unknown()).optional(),persistentVariableUpdates:B.record(B.string(),B.unknown()).optional(),error:B.string().optional(),success:B.boolean()}),l0=B.object({id:B.string().optional(),orgId:B.string(),momenticLambdaAuthHash:B.string(),code:B.string(),fragment:B.boolean(),state:ni,timeoutMs:B.number().optional()}),qr=15e3;import*as at from"zod";me(at);var Xx=at.object({url:at.string(),lineNumber:at.number(),columnNumber:at.number()}).openapi({ref:"CodeLocation"}),Ms=at.object({timestamp:at.number(),text:at.string(),type:at.string(),tabIndex:at.number(),args:at.unknown().array().optional(),url:at.string().optional(),location:Xx.optional()}).openapi({ref:"ConsoleLog"}),Ju=Ms.array(),Zx=Ju.array();import*as oc from"zod";import{z as R}from"zod";var Qx=R.object({name:R.string(),version:R.string(),comment:R.string().optional()}),eT=R.object({name:R.string(),version:R.string(),comment:R.string().optional()}),tT=R.object({onContentLoad:R.number().optional(),onLoad:R.number().optional(),comment:R.string().optional()}),Zu=R.object({startedDateTime:R.string(),id:R.string(),title:R.string().optional(),pageTimings:tT,comment:R.string().optional()}),nT=R.array(Zu),rT=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()}),Qu=R.array(rT),oT=R.object({name:R.string(),value:R.string(),comment:R.string().optional()}),em=R.array(oT),iT=R.object({name:R.string(),value:R.string(),comment:R.string().optional()}),sT=R.array(iT),aT=R.object({name:R.string(),value:R.string().optional(),fileName:R.string().optional(),contentType:R.string().optional(),comment:R.string().optional()}),lT=R.array(aT),cT=R.object({mimeType:R.string(),params:lT,text:R.string(),comment:R.string().optional()}),dT=R.object({method:R.string(),url:R.string(),httpVersion:R.string().optional(),cookies:Qu,headers:em,queryString:sT,postData:cT.optional(),headersSize:R.number().optional(),bodySize:R.number().optional(),comment:R.string().optional()}),pT=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()}),uT=R.object({status:R.number(),statusText:R.string(),httpVersion:R.string().optional(),cookies:Qu,headers:em,content:pT,redirectURL:R.string().optional(),headersSize:R.number().optional(),bodySize:R.number().optional(),comment:R.string().optional()}),Xu=R.object({expires:R.string().optional(),lastAccess:R.string(),eTag:R.string(),hitCount:R.number(),comment:R.string().optional()}),mT=R.object({beforeRequest:Xu.optional(),afterRequest:Xu.optional(),comment:R.string().optional()}),hT=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()}),tm=R.object({pageref:R.string().optional(),startedDateTime:R.string(),time:R.number().optional(),request:dT,response:uT.optional(),cache:mT.optional(),timings:hT,serverIPAddress:R.string().optional(),connection:R.string().optional(),comment:R.string().optional(),_resourceType:R.string().optional()}),fT=R.array(tm),gT=R.object({version:R.string().default("1.1"),creator:Qx.optional(),browser:eT.optional(),pages:nT.optional(),entries:fT,comment:R.string().optional()}),yT=R.object({log:gT}),nm=R.record(R.string(),Zu),rm=R.record(R.string(),tm);function rc(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())}}}me(oc);var ST=oc.object({logsPerPage:Ms.array().array(),harPages:nm.optional(),harEntries:rm.optional()}).openapi({ref:"DebugData"});var Ds=class extends Error{constructor(e,t,r,o={}){super(`The ${r} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};var Fs=class extends Error{constructor(e,t={}){super(e,t),this.name="TemplateMatcherThresholdError"}};function om(n){for(let e of Object.values(le))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(le))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}}},Kr=class extends Error{decisions;constructor(e,t,r={}){super(e,r),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
7
+ ${e.message}`)}},ox=({newValue:n,value:e,maxSize:t,indent:r})=>n!==void 0?JSON.stringify(n,void 0,r):typeof e=="number"?Fp(e,t):tu(e,t);import*as sr from"zod";import{z as wt}from"zod";var ve="BASE_URL",ps="CURRENT_URL",Hr="ENV_NAME",mN={[ve]:"https://www.google.com"},hu=wt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),us=wt.object({name:wt.string(),variables:wt.record(wt.string().describe("variable name"),wt.string().describe("variable value"))}),ms=wt.object({localChromeExtensionPaths:wt.string().array().optional(),disableGpu:wt.boolean().optional()}),hs=wt.object({name:wt.string(),variables:wt.record(wt.string().describe("variable name"),wt.unknown().describe("variable value")),browser:ms.optional()});me(sr);var ni=sr.object({env:sr.record(sr.unknown())}).openapi({ref:"TestContextSnapshot"}),ix="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",sx=[ve,Hr],fu=[ps,ve,Hr],vt=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[ps]??"about:blank",i=e.env[Hr],s={};for(let[l,c]of Object.entries(e.env))fu.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=ti(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){sx.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Hr]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ti(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>fu.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,ix]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:i}=$r(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(i)}catch{e.env[r]=void 0}}let{jsonString:t}=$r(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[ps]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=ti(e.variablesFromEnvironment),this.setMomenticSystemVariable(ve,e.baseUrl),e.envName&&this.setMomenticSystemVariable(Hr,e.envName)}getDynamicVariablesCopy(){return ti(this.env)}getVariablesFromEnvironmentCopy(){return ti(this.varsFromMomenticEnvironment)}};import{z as ar}from"zod";me(ar);var le=(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))(le||{});var gu=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],yu={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"},Su={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. Please reach out to Momentic Support for assistance."},jl=ar.object({reason:ar.nativeEnum(le),summary:ar.string()}).openapi({ref:"TestResultClassification"}),fs=ar.object({errorMessage:ar.string(),errorStack:ar.string().optional(),classification:jl.optional()}).openapi({ref:"TestFailureDetails"});me(W);var He=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(He||{}),$l=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))($l||{}),Hl=W.object({beforeUrl:W.string().optional(),afterUrl:W.string().optional(),message:W.string().optional(),beforeScreenshot:W.string().optional(),afterScreenshot:W.string().optional(),beforeSnapshot:W.string().optional(),afterSnapshot:W.string().optional(),startedAt:W.coerce.date(),finishedAt:W.coerce.date()}),ax=Hl.extend({viewport:W.object({height:W.number(),width:W.number()}),status:W.nativeEnum($l),message:W.string().optional(),elementInteracted:W.string().optional()}),kn=Hl.extend({status:W.nativeEnum(He),message:W.string().optional(),data:W.unknown().optional(),beforeTestContext:ni.optional(),afterTestContext:ni.optional(),failureReason:W.nativeEnum(le).optional(),details:W.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),gs=kn.merge(St).extend({results:ax.array(),proposedStep:St.optional()}),lx=kn.merge(nr).extend({results:W.lazy(()=>gs.array())}),cx=kn.merge(Br).extend({results:W.lazy(()=>gs.array())}),dx=kn.merge(Tn).extend({moduleName:W.string().optional(),results:W.lazy(()=>Ft.array())}),px=kn.merge(rr).extend({assertion:gs.optional(),results:W.lazy(()=>Ft.array()).describe("results for the block actually executed")}),ux=kn.merge(Zo).extend({results:W.lazy(()=>Ft.array())}),mx=kn.merge(Qo).extend({results:W.lazy(()=>Ft.array()),healingAttempts:W.lazy(()=>Ft.array().array()).optional()}),Ft=W.discriminatedUnion("type",[lx,cx,gs,dx,px,ux,mx]),_n=kn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),bu=Hl.extend({index:W.number().optional(),description:W.string(),pageState:W.string().optional()});var Wl=hx.object({results:Ft.array().describe("main results"),beforeResults:Ft.array().optional(),afterResults:Ft.array().optional()}),ys=Wl.partial();import{z as H}from"zod";import{z as he}from"zod";var fx=he.object({type:he.literal("FAILURE_RECOVERY"),thoughts:he.string()}),gx=he.object({type:he.literal("DESCRIPTION_UPDATE"),thoughts:he.string()}),Ss=he.discriminatedUnion("type",[gx,fx]),bs=(e=>(e.AUTO_HEALING="AUTO_HEALING",e))(bs||{}),yx=he.object({testId:he.string(),name:he.string(),orgId:he.string(),runId:he.string(),purpose:he.nativeEnum(bs).catch("AUTO_HEALING"),steps:Ae.array(),details:Ss.or(Ss.array()).optional()}),BN=yx.pick({name:!0,orgId:!0}),Gl=he.object({id:he.string(),name:he.string().nullish(),createdAt:he.string().pipe(he.coerce.date()).or(he.date()),organizationId:he.string(),schemaVersion:he.string(),purpose:he.nativeEnum(bs).catch("AUTO_HEALING"),runId:he.string().nullish(),details:Ss.or(Ss.array()).nullish(),applied:he.boolean().nullish(),appliedAt:he.coerce.date().nullish()}),wu=Gl.extend({steps:Ae.array()});import{isValidCron as Sx}from"cron-validator";import{z as Y}from"zod";import{z as Vl}from"zod";var ws=Vl.object({width:Vl.number().min(200).max(1e4),height:Vl.number().min(200).max(1e4)}),vu={"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}},HN=Object.keys(vu);var Yt=vu["Desktop Large"];var xu=1e4,Tu=6e4,lr=(t=>(t.CHROMIUM="Chromium",t.GOOGLE_CHROME="Google Chrome",t))(lr||{}),vs=Y.object({browserType:Y.nativeEnum(lr).optional(),pageLoadTimeoutMs:Y.number().optional().refine(n=>n===void 0||n<=Tu&&n>=-1,{message:`Page load timeout must be between 0 and ${Tu/1e3} seconds`}),smartWaitingTimeoutMs:Y.number().optional().refine(n=>n===void 0||n<=xu&&n>=-1,{message:`Smart waiting timeout must be between 0 and ${xu/1e3} seconds`}),extraHeaders:Y.record(Y.string(),Y.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Y.string().optional(),basicAuthorization:Y.object({username:Y.string().optional(),password:Y.string().optional()}).optional(),disableJavaScript:Y.boolean().optional(),disableGpu:Y.boolean().optional(),localChromeExtensionPaths:Y.string().array().optional()}),Eu=["extraHeaders","basicAuthorization","localChromeExtensionPaths"];var bx=Y.object({disableAICaching:Y.boolean().default(!1),failureRecovery:Y.boolean().optional().describe("undefined means inherit org settings")});var wx=Y.object({viewport:ws.optional()}),Wr=wx.merge(bx).merge(vs),Gr=Y.object({cron:Y.string().refine(n=>Sx(n),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Y.boolean().default(!1),env:Y.string().optional(),timeZone:Y.string().default("America/Los_Angeles"),jobKey:Y.string().optional()}),Vr=Y.object({onSuccess:Y.boolean().default(!1),failureMessage:Y.string().optional(),onFailure:Y.boolean().default(!0),successMessage:Y.string().optional()}),vx=Y.object({name:Y.string(),required:Y.boolean().optional(),defaultValue:Y.string().describe("this is not optional because we need a value when the editor is first loaded")}),xs=vx.array(),xx=Y.object({name:Y.string(),value:Y.string()}),Cu=xx.array(),Ts=Y.object({name:Y.string(),default:Y.boolean().optional(),fixtures:hu.array().optional()});me(H);var Ut={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ce=(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))(ce||{}),Es=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Es||{});var Re=H.string().pipe(H.coerce.date()).or(H.date()),ri=H.object({id:H.string(),runKey:H.string(),organizationId:H.string(),createdAt:Re,createdBy:H.string(),flake:H.boolean().nullish(),scheduledAt:Re.or(H.null()),startedAt:Re.or(H.null()),updatedAt:Re.nullish(),finishedAt:Re.or(H.null()),resolvedBaseUrl:H.string().nullish(),environmentName:H.string().nullish(),section:H.nativeEnum(Es).nullish(),status:H.nativeEnum(ce),trigger:H.nativeEnum(Ut),attempts:H.number(),runAttempts:H.array(H.object({id:H.string(),status:H.nativeEnum(ce),startedAt:Re.or(H.null()),finishedAt:Re.or(H.null())})).optional(),videos:H.array(H.string()).optional(),failureReason:H.nativeEnum(le).nullish(),failureDetails:fs.nullish(),testFragments:H.array(Gl).nullish(),localTestId:H.string().nullish(),testId:H.string().nullish(),testName:H.string().nullish(),test:H.object({name:H.string(),id:H.string()}).nullish().default(null),suiteId:H.string().nullish()}).openapi({ref:"RunMetadata"}),Tx={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Cs=ri.pick({...Tx,test:!0}),Au=ri.omit({failureReason:!0,failureDetails:!0,test:!0}),ql=ri.extend({stepsSnapshot:H.array(H.record(H.unknown())).nullish(),resolvedInputs:H.record(H.string(),H.string()).nullish(),test:H.object({name:H.string(),id:H.string(),baseUrl:H.string().nullish(),advanced:Wr.nullish()}).nullish()}).merge(Wl),Ru=n=>n.includes("PASSED")&&n.includes("FAILED");var Ex=oi.object({id:oi.string().uuid(),startedAt:Re.or(oi.null()),finishedAt:Re.or(oi.null()),status:oi.nativeEnum(ce)}).merge(ys),lM=Ex.array();var As=(t=>(t.JUNIT="junit",t.ALLURE="allure",t))(As||{});import{z as We}from"zod";var Cx=We.object({id:We.string(),status:We.nativeEnum(ce),trigger:We.nativeEnum(Ut),createdAt:Re,startedAt:Re.nullish(),finishedAt:Re.nullish(),gitCommitSha:We.string().nullish(),gitCommitShaShort:We.string().nullish(),gitCommitTimestamp:Re.nullish(),gitBranchName:We.string().nullish(),gitOriginUrl:We.string().nullish(),gitCommitMessage:We.string().nullish(),gitCommitAuthorName:We.string().nullish(),githubRepository:We.string().nullish(),gitlabProjectPath:We.string().nullish(),pipelineId:We.string().nullish(),suite:We.object({id:We.string(),name:We.string()}).nullish(),runs:We.object({status:We.nativeEnum(ce)}).array()}).openapi({ref:"RunGroup"}),Iu=Cx.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Cs.array()});import{z as Ge}from"zod";import*as re from"zod";var SM=re.object({thoughts:re.string().optional().describe("only provided if a description was provided"),target:er.optional().describe("only provided if a description was provided"),pageState:re.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:re.object({label:re.string(),value:re.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:re.object({data:re.string(),height:re.number().int(),width:re.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Pu="<select> element",Lu="text input or contenteditable element",Ax="text input element",Kl=[Pu,Lu,Ax];function Ou(n,e){if(n===e)return!0;for(let t of Kl){if(!n.startsWith(t))continue;let r=n.slice(t.length+2);if(Kl.some(o=>e.startsWith(o)&&e.slice(o.length+2)===r)||r===e)return!0}return!!Kl.some(t=>e.startsWith(t)&&e.slice(t.length+2)===n)}function Rs(n,e){if(!e||"useSelector"in n&&n.useSelector)return e;switch(n.type){case"SELECT_OPTION":return`${Pu}: ${e}`;case"TYPE":return`${Lu}: ${e}`;default:return e}return e}var ii=re.object({matched:re.boolean(),reason:re.string().optional().describe("Human understandable description"),logs:re.string().array().optional().describe("Logs for debugging")}),Rx=ii.extend({type:re.literal("A11Y_ID")}),Ix=ii.extend({type:re.literal("USER_SELECTOR")}),Px=ii.extend({type:re.literal("CSS_SELECTOR"),selectors:re.string().array()}),Lx=ii.extend({type:re.literal("HTML_DISTANCE"),distance:re.number().optional(),closestElement:re.string().optional(),savedElement:re.string().optional()}),Ox=ii.extend({type:re.literal("TEMPLATE_MATCHING"),elementImageUrl:re.string().url()}),ku=re.discriminatedUnion("type",[Rx,Ix,Px,Lx,Ox]);var kx=Ge.object({type:Ge.literal("TARGETING"),name:Ge.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:ku.array(),pageState:Ge.string().optional(),targetSource:Ge.nativeEnum(Qn).optional(),targetUpdateTime:Ge.string().optional()}),_x=Ge.object({type:Ge.literal("AI_LOCATION"),matched:Ge.boolean(),pageState:Ge.string().optional(),ragUsed:Ge.boolean().optional(),thoughts:Ge.string().optional()}),Nx=Ge.object({type:Ge.literal("ASSERTION"),relevantElementsSerialized:Ge.string().array().optional(),pageState:Ge.string().optional(),ragUsed:Ge.boolean().optional()}),_u=Ge.discriminatedUnion("type",[kx,_x,Nx]);function Is(){return{details:[]}}import{z as Oe}from"zod";var Mx=Oe.object({id:Oe.string(),name:Oe.string()}),RM=Mx.merge(Oe.object({createdAt:Re,createdBy:Oe.string(),schedule:Gr,notification:Vr,environment:Oe.object({name:Oe.string()}).nullish(),beforeTests:Oe.object({id:Oe.string()}).array().nullish(),afterTests:Oe.object({id:Oe.string()}).array().nullish()})),Nu=Oe.object({id:Oe.string().uuid(),orgId:Oe.string(),createdAt:Re,startedAt:Re.or(Oe.null()),finishedAt:Re.or(Oe.null()),status:Oe.nativeEnum(ce),trigger:Oe.nativeEnum(Ut),suite:Oe.object({id:Oe.string(),name:Oe.string()}).nullish(),runs:ri.array()}),IM=Nu.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Mu=Nu.extend({runs:Cs.array()});var Jt=D.object({disableCache:D.boolean().optional(),loggerTags:D.record(D.string(),D.string()).optional(),langfuseSessionId:D.string().optional()}),Dx=D.object({screenshotBase64AfterCommand:D.string(),urlAfterCommand:D.string(),serializedCommand:D.string(),elementInteracted:D.string().optional(),thoughts:D.string().optional()}),WM=D.object({goal:D.string(),browserState:D.string(),screenshot:D.string(),feedback:D.string().optional()}),GM=D.object({goal:D.string(),browserState:D.string()}),Du=D.object({goal:D.string(),browserState:D.string(),screenshot:D.string().optional(),returnSchema:D.string().optional()}),Fu=D.object({goal:D.string(),browserState:D.string(),screenshot:D.string(),url:D.string(),contextChoice:ml.optional()}),Yl=D.object({goal:D.string(),browserState:D.string(),startingScreenshot:D.string().optional(),screenshot:D.string(),url:D.string(),history:Dx.array(),actionHint:D.string().optional(),lastError:D.string().optional()}),Uu=D.object({results:Ft.array(),errorMessage:D.string(),errorStack:D.string().optional()}),zu=D.object({results:D.array(Ft),goal:D.string(),errorMessage:D.string()}),Bu=D.object({failedResults:bu.array(),nextStepsSerialized:D.string().array(),currentUrl:D.string(),currentPageState:D.string(),currentScreenshot:D.string()}),VM=D.object({description:D.string(),type:D.union([D.literal("locator"),D.literal("assertion"),D.literal("ai-action")]),excerpt:D.string()});import{z as si}from"zod";var YM=si.object({goal:si.string()}),ju=si.object({keywords:si.array(si.string())});import{z as $u}from"zod";var ZM=$u.object({input:$u.string()});var Hu=n=>!(!n.org_id||!n.user_id||!n.platform);import{z as cr}from"zod";var Wu=cr.object({id:cr.string().uuid(),skipped:cr.boolean().optional(),envKey:cr.string().optional().describe("key in the environment to save the result of this step to")}),Jl=Wu.merge(Ji).extend({type:cr.literal("REQUEST")}),Xl=Wu.merge(Xi).extend({type:cr.literal("JAVASCRIPT")}),Zl=cr.discriminatedUnion("type",[Xl,Jl]);import{z as zt}from"zod";import{z as dr}from"zod";var Fx=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Ie=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 Ps=dr.string().min(1).max(255).superRefine((n,e)=>{try{ai(n)}catch(t){return e.addIssue({code:dr.ZodIssueCode.custom,message:t.message,fatal:!0}),dr.NEVER}});function ai(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(Fx))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ls=dr.preprocess(n=>n===null?"":n,dr.union([dr.string().url(),dr.literal("")])).optional();var Gu=zt.object({id:zt.string(),name:Ps,description:zt.string().optional().nullish(),baseUrl:Ls.nullish(),schemaVersion:zt.string(),advanced:zt.unknown().optional(),retries:zt.number(),envs:zt.array(Ts).nullish(),parameters:xs.nullish()}),Ux=zt.object({createdAt:zt.coerce.date(),updatedAt:zt.coerce.date(),schedule:Gr.nullish(),notification:Vr.nullish(),createdBy:zt.string(),organizationId:zt.string()}),zx=Gu.merge(Ux),SD=zx.extend({steps:Zl.array()}),bD=Gu.extend({steps:Zl.array()});import{z as xt}from"zod";var Vu=xt.object({startedAt:xt.coerce.date(),finishedAt:xt.coerce.date(),status:xt.nativeEnum(He),message:xt.string().optional(),data:xt.unknown().optional()}),jx=Vu.merge(Xl).extend({type:xt.literal("JAVASCRIPT")}),$x=Vu.merge(Jl).extend({type:xt.literal("REQUEST")}),Hx=xt.discriminatedUnion("type",[jx,$x]),qu=xt.object({startedAt:xt.coerce.date(),finishedAt:xt.coerce.date().nullish(),status:xt.nativeEnum(ce),results:Hx.array(),failureReason:xt.string().nullish(),failureDetails:fs.nullish()});import{z as Tt}from"zod";var Wx=Tt.object({id:Tt.string(),organizationId:Tt.string(),createdAt:Tt.coerce.date(),updatedAt:Tt.coerce.date(),createdBy:Tt.string(),scheduledAt:Tt.coerce.date().nullish(),startedAt:Tt.coerce.date().nullish(),finishedAt:Tt.coerce.date().nullish(),status:Tt.nativeEnum(ce),trigger:Tt.nativeEnum(Ut),results:qu.array().nullish(),apiTestName:Tt.string().nullish(),apiTestPath:Tt.string().nullish(),apiTestId:Tt.string().nullish()}),ID=Wx.pick({status:!0,startedAt:!0,finishedAt:!0});var li=(t=>(t.TestRun="test-run",t.CreditsUsed="credits-used",t))(li||{}),Ku=3;function Gx(n){return n==="MODULE"||n==="IFRAME"||n==="CONDITIONAL"||n==="SECTION"||n==="RESOLVED_MODULE"}function Ql(n){if(!Gx(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 ec(n){switch(n.type){case"AI_EXTRACT":return 3;case"AI_ASSERTION":return Ku;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 Os=class{async reportBillableEvent(e,t,r){}async reportCreditsUsed(e,t,r,o){}};function tc(n,e){return{...n,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as Vx,splitCookiesString as qx}from"set-cookie-parser";import{z as oe}from"zod";var nc=oe.object({name:oe.string(),value:oe.string(),url:oe.string().optional(),domain:oe.string().optional(),path:oe.string().optional(),expires:oe.number().default(Date.now()/1e3+60*60*24*365),httpOnly:oe.boolean().optional(),secure:oe.boolean().default(!0),sameSite:oe.union([oe.literal("Strict"),oe.literal("Lax"),oe.literal("None")]).default("None")});function ks(n,e){let t=[],r=qx(n);for(let o of r){let i=Vx(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=nc.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 Kx=oe.object({origin:oe.string(),localStorage:oe.array(oe.object({name:oe.string(),value:oe.string()}))}),Yx=oe.object({entries:oe.record(oe.string(),oe.array(oe.tuple([oe.unknown(),oe.unknown()]))),version:oe.number().optional()}),_s=oe.object({cookies:nc.array().optional(),origins:Kx.array().optional(),idb:oe.record(oe.string(),Yx).optional().describe("key is db name")});function Ns(n,e){let t=[];return n.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=nc.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 JD=new Set(Object.values(je));var Jx={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"},XD={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:[]},ZD={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 B}from"zod";var r0=B.object({body:B.string(),to:B.string(),from:B.string()}),o0=B.object({from:B.string().optional(),to:B.string(),timeout:B.number().optional(),beforeDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional()}),i0=B.object({to:B.string(),from:B.string(),subject:B.string(),body:B.string()}),s0=B.object({inbox:B.string(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),timeout:B.number().optional(),trimWhitespace:B.boolean().optional()}),a0=B.object({inbox:B.string(),limit:B.number().optional(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),trimWhitespace:B.boolean().optional()});var Yu=B.object({result:B.unknown(),variableUpdates:B.record(B.string(),B.unknown()).optional(),persistentVariableUpdates:B.record(B.string(),B.unknown()).optional(),error:B.string().optional(),success:B.boolean()}),l0=B.object({id:B.string().optional(),orgId:B.string(),momenticLambdaAuthHash:B.string(),code:B.string(),fragment:B.boolean(),state:ni,timeoutMs:B.number().optional()}),qr=15e3;import*as at from"zod";me(at);var Xx=at.object({url:at.string(),lineNumber:at.number(),columnNumber:at.number()}).openapi({ref:"CodeLocation"}),Ms=at.object({timestamp:at.number(),text:at.string(),type:at.string(),tabIndex:at.number(),args:at.unknown().array().optional(),url:at.string().optional(),location:Xx.optional()}).openapi({ref:"ConsoleLog"}),Ju=Ms.array(),Zx=Ju.array();import*as oc from"zod";import{z as R}from"zod";var Qx=R.object({name:R.string(),version:R.string(),comment:R.string().optional()}),eT=R.object({name:R.string(),version:R.string(),comment:R.string().optional()}),tT=R.object({onContentLoad:R.number().optional(),onLoad:R.number().optional(),comment:R.string().optional()}),Zu=R.object({startedDateTime:R.string(),id:R.string(),title:R.string().optional(),pageTimings:tT,comment:R.string().optional()}),nT=R.array(Zu),rT=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()}),Qu=R.array(rT),oT=R.object({name:R.string(),value:R.string(),comment:R.string().optional()}),em=R.array(oT),iT=R.object({name:R.string(),value:R.string(),comment:R.string().optional()}),sT=R.array(iT),aT=R.object({name:R.string(),value:R.string().optional(),fileName:R.string().optional(),contentType:R.string().optional(),comment:R.string().optional()}),lT=R.array(aT),cT=R.object({mimeType:R.string(),params:lT,text:R.string(),comment:R.string().optional()}),dT=R.object({method:R.string(),url:R.string(),httpVersion:R.string().optional(),cookies:Qu,headers:em,queryString:sT,postData:cT.optional(),headersSize:R.number().optional(),bodySize:R.number().optional(),comment:R.string().optional()}),pT=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()}),uT=R.object({status:R.number(),statusText:R.string(),httpVersion:R.string().optional(),cookies:Qu,headers:em,content:pT,redirectURL:R.string().optional(),headersSize:R.number().optional(),bodySize:R.number().optional(),comment:R.string().optional()}),Xu=R.object({expires:R.string().optional(),lastAccess:R.string(),eTag:R.string(),hitCount:R.number(),comment:R.string().optional()}),mT=R.object({beforeRequest:Xu.optional(),afterRequest:Xu.optional(),comment:R.string().optional()}),hT=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()}),tm=R.object({pageref:R.string().optional(),startedDateTime:R.string(),time:R.number().optional(),request:dT,response:uT.optional(),cache:mT.optional(),timings:hT,serverIPAddress:R.string().optional(),connection:R.string().optional(),comment:R.string().optional(),_resourceType:R.string().optional()}),fT=R.array(tm),gT=R.object({version:R.string().default("1.1"),creator:Qx.optional(),browser:eT.optional(),pages:nT.optional(),entries:fT,comment:R.string().optional()}),yT=R.object({log:gT}),nm=R.record(R.string(),Zu),rm=R.record(R.string(),tm);function rc(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())}}}me(oc);var ST=oc.object({logsPerPage:Ms.array().array(),harPages:nm.optional(),harEntries:rm.optional()}).openapi({ref:"DebugData"});var Ds=class extends Error{constructor(e,t,r,o={}){super(`The ${r} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};var Fs=class extends Error{constructor(e,t={}){super(e,t),this.name="TemplateMatcherThresholdError"}};function om(n){for(let e of Object.values(le))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(le))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}}},Kr=class extends Error{decisions;constructor(e,t,r={}){super(e,r),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
8
8
  Decisions:
9
9
  ${this.decisions.map(e=>e.toString()).join(`
10
- `)}`}};var ci=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCssDataError"}};import{z as ic}from"zod";var di=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return this.flags[e]===!0}getAllFlags(){return this.flags}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},K0=new di({},{}),Y0=ic.object({globalOverrides:ic.record(ic.string()).optional()});var sc={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},im=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],X0=Object.keys(sc);import*as sm from"zod";var Q0=sm.custom().refine(n=>n&&n.length>0).refine(n=>n&&n[0]instanceof File,{message:"Please upload a valid file."});import{z as Nn}from"zod";var nF=Nn.object({id:Nn.string(),name:Nn.string(),createdAt:Nn.coerce.date(),createdBy:Nn.string(),updatedAt:Nn.coerce.date(),updatedBy:Nn.string().nullable(),organizationId:Nn.string()});import{z as X}from"zod";import{z as Fe}from"zod";var Bt=Fe.object({id:Fe.string(),name:Ps,baseUrl:Ls,description:Fe.string().optional().nullish(),schemaVersion:Fe.string(),advanced:Wr,retries:Fe.number(),envs:Fe.array(Ts).nullish(),parameters:xs.nullish(),disabled:Fe.boolean().optional(),labels:Fe.array(Fe.string()).optional().catch([])}),cF=Bt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),bT=Fe.object({labels:Fe.array(Fe.string()).optional(),outputs:Cu.nullish()}),dn=Bt.merge(bT),wT=Fe.object({createdAt:Fe.coerce.date(),updatedAt:Fe.coerce.date(),updatedBy:Fe.string().nullable(),schedule:Gr,notification:Vr,createdBy:Fe.string(),organizationId:Fe.string(),folderId:Fe.string().nullable().optional()}),vT=Bt.merge(wT),dF=vT.merge(jr),pi=Bt.merge(jr),pF=Bt.merge(or);var am=X.object({platformSep:X.string(),fullPathSegments:X.string().array(),relativePath:X.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:X.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:X.coerce.date(),createdAt:X.coerce.date()}),wF=X.array(am.extend({id:X.string(),name:X.string(),description:X.string().optional(),labels:X.string().array().optional()})),vF=X.array(am.extend({id:X.string(),name:X.string(),content:El})),xF=pi.merge(dn),lm=X.object({schemaVersion:X.string(),stepLists:jr}),cm=dn.partial().merge(Bt.pick({id:!0})),dm=X.object({name:X.string(),description:X.string().optional(),baseUrl:X.string().url().optional(),environment:X.string().optional(),browserType:X.nativeEnum(lr).optional(),viewport:ws.optional(),folderPath:X.string().optional()}),TF=pi.merge(X.object({relativeFilePath:X.string().describe("relative to project root")})),pm=X.object({name:X.string(),description:X.string(),enabled:X.boolean(),steps:X.lazy(()=>Re.array()),testFilePath:X.string().describe("relative to the project root")});var EF=X.array(hs),um=X.object({defaultEnv:X.string().optional().describe("name of the default env, or undefined to unset")}),mm=X.object({configFilePath:X.string().describe("full path on disk")}),CF=X.string().array();var ui=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],hm=ui.map(n=>`**/${n}/**`);import pn from"chalk";var xT=["app","version","env","namespace","host"];function Ze(n){let e=n.bindings()??{},t={};for(let r of Object.keys(e)){let o=e[r];!xT.includes(r)&&typeof o=="string"&&(t[r]=o)}return t}var ac=class n{minLogLevel;logBindings;constructor(e,t){this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...r){if(e<this.minLogLevel)return;let o;Array.isArray(r[0])?(o=r[0],r=r.slice(1)):typeof r[0]=="object"&&!(r[0]instanceof Error)&&Object.entries(r[0]).length&&(o={...r[0],...this.logBindings},r=r.slice(1));let i=[];if(i.push(...r),console.log(t(...i)),o&&!Array.isArray(o)){let s=Object.entries(o);for(let[a,l]of s){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=JSON.stringify(l,void 0,2),c=c.split(`
10
+ `)}`}};var ci=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCssDataError"}};import{z as ic}from"zod";var di=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return this.flags[e]===!0}getAllFlags(){return this.flags}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},K0=new di({},{}),Y0=ic.object({globalOverrides:ic.record(ic.string()).optional()});var sc={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},im=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],X0=Object.keys(sc);import*as sm from"zod";var Q0=sm.custom().refine(n=>n&&n.length>0).refine(n=>n&&n[0]instanceof File,{message:"Please upload a valid file."});import{z as Nn}from"zod";var nF=Nn.object({id:Nn.string(),name:Nn.string(),createdAt:Nn.coerce.date(),createdBy:Nn.string(),updatedAt:Nn.coerce.date(),updatedBy:Nn.string().nullable(),organizationId:Nn.string()});import{z as X}from"zod";import{z as Fe}from"zod";var Bt=Fe.object({id:Fe.string(),name:Ps,baseUrl:Ls,description:Fe.string().optional().nullish(),schemaVersion:Fe.string(),advanced:Wr,retries:Fe.number(),envs:Fe.array(Ts).nullish(),parameters:xs.nullish(),disabled:Fe.boolean().optional(),labels:Fe.array(Fe.string()).optional().catch([])}),cF=Bt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),bT=Fe.object({labels:Fe.array(Fe.string()).optional(),outputs:Cu.nullish()}),dn=Bt.merge(bT),wT=Fe.object({createdAt:Fe.coerce.date(),updatedAt:Fe.coerce.date(),updatedBy:Fe.string().nullable(),schedule:Gr,notification:Vr,createdBy:Fe.string(),organizationId:Fe.string(),folderId:Fe.string().nullable().optional()}),vT=Bt.merge(wT),dF=vT.merge(jr),pi=Bt.merge(jr),pF=Bt.merge(or);var am=X.object({platformSep:X.string(),fullPathSegments:X.string().array(),relativePath:X.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:X.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:X.coerce.date(),createdAt:X.coerce.date()}),wF=X.array(am.extend({id:X.string(),name:X.string(),description:X.string().optional(),labels:X.string().array().optional()})),vF=X.array(am.extend({id:X.string(),name:X.string(),content:El})),xF=pi.merge(dn),lm=X.object({schemaVersion:X.string(),stepLists:jr}),cm=dn.partial().merge(Bt.pick({id:!0})),dm=X.object({name:X.string(),description:X.string().optional(),baseUrl:X.string().url().optional(),environment:X.string().optional(),browserType:X.nativeEnum(lr).optional(),viewport:ws.optional(),folderPath:X.string().optional()}),TF=pi.merge(X.object({relativeFilePath:X.string().describe("relative to project root")})),pm=X.object({name:X.string(),description:X.string(),enabled:X.boolean(),steps:X.lazy(()=>Ae.array()),testFilePath:X.string().describe("relative to the project root")});var EF=X.array(hs),um=X.object({defaultEnv:X.string().optional().describe("name of the default env, or undefined to unset")}),mm=X.object({configFilePath:X.string().describe("full path on disk")}),CF=X.string().array();var ui=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],hm=ui.map(n=>`**/${n}/**`);import pn from"chalk";var xT=["app","version","env","namespace","host"];function Ze(n){let e=n.bindings()??{},t={};for(let r of Object.keys(e)){let o=e[r];!xT.includes(r)&&typeof o=="string"&&(t[r]=o)}return t}var ac=class n{minLogLevel;logBindings;constructor(e,t){this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...r){if(e<this.minLogLevel)return;let o;Array.isArray(r[0])?(o=r[0],r=r.slice(1)):typeof r[0]=="object"&&!(r[0]instanceof Error)&&Object.entries(r[0]).length&&(o={...r[0],...this.logBindings},r=r.slice(1));let i=[];if(i.push(...r),console.log(t(...i)),o&&!Array.isArray(o)){let s=Object.entries(o);for(let[a,l]of s){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=JSON.stringify(l,void 0,2),c=c.split(`
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,pn.reset,...e)}info(...e){this.logWithLevel(1,pn.blue,...e)}debug(...e){this.logWithLevel(0,pn.dim,...e)}warn(...e){this.logWithLevel(2,pn.yellow,...e)}error(...e){this.logWithLevel(3,pn.red,...e)}success(...e){this.logWithLevel(4,pn.green,...e)}dimmed(...e){this.logWithLevel(1,pn.dim,...e)}underline(...e){this.logWithLevel(2,pn.underline,...e)}bold(...e){this.logWithLevel(2,pn.bold,...e)}grey(...e){this.logWithLevel(0,pn.grey,...e)}child(e){return new n(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},b=new ac(1,{}),mi={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>mi,flush:()=>{},bindings:()=>({})},Us={},Yr=({logger:n,logKey:e,maxCount:t,intervalMs:r},o,i,...s)=>{let a=Us[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},Us[e]=a),a.totalCount++,a.count<t&&(a.count++,n.debug(o,i,...s)),a.timer=setTimeout(()=>{let l=Us[e];l?.totalCount!==l?.count&&n.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete Us[e]},r)};import{z as Ve}from"zod";var fm=Ve.object({id:Ve.string(),createdAt:Ve.coerce.date(),createdBy:Ve.string(),organizationId:Ve.string(),name:Ve.string(),description:Ve.string().nullish(),enabled:Ve.boolean(),schemaVersion:Ve.string().describe("Schema version for steps"),parameters:Ve.string().array().nullish().describe("Parameter list"),defaultParameters:Ve.record(Ve.string(),Ve.string()).nullish(),defaultCacheKey:Ve.string().nullish(),defaultCacheTtl:Ve.number().nullish(),defaultCacheAllInvocations:Ve.boolean().nullish(),autoAuth:Ve.boolean().nullish(),advanced:wl.nullish()}),FF=fm.extend({steps:Ve.lazy(()=>$e.array())}),gm=5*60*1e3,ym=bt.merge(fm.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as BF}from"date-fns-tz";import{z as pr}from"zod";var lc=pr.object({failureRecovery:pr.boolean().optional(),aiAction:pr.boolean().optional()}),HF=pr.object({ai:lc.optional(),githubAppInstallationId:pr.number().nullish(),gitlabAppAccessToken:pr.string().nullish().optional(),gitlabAppBaseUrl:pr.string().nullish().optional()});import*as x from"zod";var rU=x.object({error:x.boolean(),reason:x.string(),message:x.string()}),oU=Jt.merge(Yl),Sm=ts,iU=Jt.merge(Yl);var sU=Jt.merge(Fu).extend({useConsensus:x.boolean().optional()}),cc=bp,aU=Jt.extend({browserState:x.string(),goal:x.string(),screenshot:x.string()}),bm=Pp,lU=Jt.extend({goal:x.string(),browserState:x.string()}),wm=Ip,cU=Jt.merge(Du);var dU=x.object({testPaths:x.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:x.string().optional(),all:x.boolean().optional(),urlOverride:x.string().optional(),customHeaders:x.record(x.string(),x.string()).optional(),testInputMatrix:x.record(x.string(),x.string()).array().optional()}),vm=x.object({queuedTests:x.unknown().array(),runIds:x.string().uuid().array(),runGroupId:x.string().optional()}),xm=pi,Tm=x.string().array(),pU=x.union([x.object({paths:x.string().array().describe("run specific test paths (e.g. todo-test)"),all:x.boolean().describe("run all tests").optional()}),x.object({path:x.string().describe("deprecated; present for backcompat")})]),Em=x.object({tests:x.record(x.string().describe("Test name"),x.string().describe("Test YAML")),modules:x.record(x.string().describe("Module name"),x.string().describe("Module YAML"))}),TT=x.object({test:x.string().describe("test YAML"),modules:x.record(x.string().describe("moduleId"),x.string().describe("module YAML"))}),uU=TT.array(),mU=x.object({testId:x.string(),schemaVersion:x.string()}).merge(or),hU=x.object({entries:x.array(Rl),testId:x.string()}),fU=x.object({steps:x.array(x.record(x.unknown())),testId:x.string(),schemaVersion:x.string(),organizationId:x.string()}),Cm=Rp,gU=x.object({trigger:x.nativeEnum(Ut),status:x.nativeEnum(ce),startedAt:x.coerce.date().optional(),gitCommitSha:x.string().optional(),gitCommitShaShort:x.string().optional(),gitCommitTimestamp:x.coerce.date().optional(),gitBranchName:x.string().optional(),gitOriginUrl:x.string().optional(),gitCommitMessage:x.string().optional(),gitCommitAuthorName:x.string().optional(),githubRepository:x.string().optional(),gitlabProjectPath:x.string().optional(),pipelineId:x.string().optional()}),Am=x.object({id:x.string()}),yU=x.object({status:x.nativeEnum(ce),updatedAt:x.coerce.date().optional(),finishedAt:x.coerce.date().optional()}),SU=x.object({stepsSnapshot:x.array(x.record(x.unknown())).optional(),runGroupId:x.string().optional(),testId:x.string(),testName:x.string(),resolvedBaseUrl:x.string().optional(),environmentName:x.string().optional(),trigger:x.nativeEnum(Ut),schemaVersion:x.string().optional(),section:x.nativeEnum(Es).optional()}),Rm=x.object({id:x.string()}),ET=ql.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Im=ET.array(),bU=ql.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(),Pm=x.object({id:x.string()}),wU=x.object({status:x.nativeEnum(ce),finishedAt:Ie.optional()}).merge(ys),vU=x.object({screenshot:x.string()}),Lm=x.object({key:x.string()}),Om=x.object({orgId:x.string(),userId:x.string()}),km=x.array(us),_m=x.record(x.string(),x.union([x.string(),x.boolean()])),xU=x.object({paths:x.string().array(),env:x.string().optional(),urlOverride:x.string().optional(),customHeaders:x.record(x.string(),x.string()).optional()}),Nm=x.object({suiteRunIds:x.string().array()});var Mm=Mu.array(),TU=x.object({runGroupIds:x.string().array()}),hi=x.object({uploadUrl:x.string()}),EU=Jt.merge(Uu),CU=Jt.merge(Bu),AU=Jt.merge(zu),CT=x.object({testId:x.string().optional().default(""),testName:x.string().optional().default(""),suiteId:x.string().optional().default(""),suiteName:x.string().optional().default(""),creditsUsed:x.number().optional(),usedBy:x.string().optional()}),RU=x.object({transactionId:x.string(),timestamp:x.string(),event:x.nativeEnum(li),properties:CT}).array(),Dm=wu.omit({steps:!0}).extend({steps:x.array(x.record(x.string(),x.unknown())).describe("unparsed ResolvedStep[]")}),IU=x.object({limit:x.number().max(10).optional(),afterTime:x.number().optional()}),Fm=Au.array(),PU=x.object({applied:x.boolean().optional(),appliedAt:x.coerce.date().optional()}),LU=Jt.extend({chunks:Ll.array(),description:x.string().describe("Input to pass to AI"),type:x.union([x.literal("locator"),x.literal("assertion"),x.literal("ai-action")]),softTokenLimit:x.number(),hardTokenLimit:x.number()});import{z as ge}from"zod";var Um=ge.object({orgId:ge.string(),cacheKeys:ge.string().array()}),_U=ge.object({keyParams:Um,clientMetadata:ge.string(),lockAcquisitionTimeoutMs:ge.number().optional()}),zm=ge.object({acquired:ge.boolean(),acquiredByMetadata:ge.string(),keyPrefix:ge.string()}),NU=ge.object({keyPrefix:ge.string(),result:ge.string(),ttlMs:ge.number()}),MU=ge.union([ge.object({keyPrefix:ge.string()}),Um]),AT=ge.object({remainingTtlMs:ge.number(),value:ge.string().nullish()}),DU=ge.object({results:ge.record(ge.string(),AT),activeLocks:ge.string().array()}),Bm=0,jm=5*60*1e3;import{z as Xt}from"zod";var $m="test",Hm="module",En=(t=>(t.TEST=`${$m}.yaml`,t.MODULE=`${Hm}.yaml`,t))(En||{}),xe=(o=>(o.TEST=`momentic/${$m}`,o.MODULE=`momentic/${Hm}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(xe||{}),WU=Bt.merge(or),dc=bt.extend({steps:Xt.array(Xt.record(Xt.string(),Xt.unknown())),schemaVersion:Xt.string()}),GU=dc.extend({fileType:Xt.literal(xe.MODULE)}),VU=Xt.object({test:Xt.string().describe("YAML for the test, including metadata and steps"),modules:Xt.record(Xt.string(),Xt.string()).describe("Map of module name to YAML for the module")});import{validator as ZU}from"@exodus/schemasafe";import{z as e1}from"zod";var Wm=n=>{n.extraHeaders&&(n.extraHeaders=Object.fromEntries(Object.entries(n.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as u1}from"zod";import{z as zs}from"zod";var f1=zs.object({repositoriesIndexed:zs.boolean(),indexingInProgress:zs.boolean(),indexesOutdated:zs.boolean()});import{z as Te}from"zod";var pc=Te.object({assertion:Te.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),RT=Te.object({instruction:Te.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:pc.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.")}),Gm=RT.extend({subSteps:Te.lazy(()=>Gm.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Vm=Te.object({name:Te.string().describe("Short name describing the test plan"),description:Te.string().nullish().transform(n=>n??void 0).describe("Longer form description of the high level goal of the test plan")}),qm=Vm.extend({id:Te.string(),createdAt:Te.coerce.date(),updatedAt:Te.coerce.date(),updatedBy:Te.string(),createdBy:Te.string(),test:Te.object({id:Te.string(),name:Te.string()}).nullish().transform(n=>n??void 0)}),b1=qm.extend({testGenRuns:Te.tuple([]).or(Te.tuple([Te.object({id:Te.string(),startedAt:Te.coerce.date(),status:Te.nativeEnum(ce)})]))}),Km=Te.object({preConditions:pc.array(),postConditions:pc.array(),steps:Gm.array()}),w1=qm.extend({plan:Km.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),v1=Vm.extend({plan:Km.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})});var M="v1";var Zt=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function IT(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var uc=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;for(;r>0;)try{r--;let a=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:this.getHeaders(),signal:o});if(!a.ok){let c=await IT(a);throw new Zt(a.status,c,`Request to ${e} failed with status ${a.status}: ${c}`)}let l;return a.status===204?l=await a.text():l=await a.json(),this.logger&&!t.noLog&&this.logger.debug({result:l,path:e,baseUrl:this.baseUrl,status:a.status},"Got response from Momentic server"),l}catch(a){if(s=a,this.logger&&this.logger.warn({path:e,baseUrl:this.baseUrl,err:a},`Got error response from Momentic server${r>0?", retrying":""}`),a instanceof Zt&&a.status>=400&&a.status<500||r===0)throw a;let l=1500,c=i-r,d=l*Math.pow(2,c-1);await new Promise(p=>setTimeout(p,d))}throw s}},Et=class extends uc{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var lt=class extends Et{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${M}/auth/check`,{method:"GET",noLog:!0}),{orgId:t,userId:r}=Om.parse(e);return{orgId:t,userId:r}}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${M}/runs/status`,{method:"POST",body:e,noLog:!0});return Im.parse(t)}async createRunGroup(e){let t=await this.sendRequest(`/${M}/run-groups`,{method:"POST",body:e,noLog:!0});return Am.parse(t)}async updateRunGroup(e,t){await this.sendRequest(`/${M}/run-groups/${e}`,{method:"PATCH",body:t,noLog:!0})}async createRun(e){let t=await this.sendRequest(`/${M}/runs`,{method:"POST",body:e,noLog:!0});return Rm.parse(t)}async updateRun(e,t){await this.sendRequest(`/${M}/runs/${e}`,{method:"PATCH",body:t,noLog:!0})}async createRunAttempt(e){let t=await this.sendRequest(`/${M}/runs/${e}/attempts`,{method:"POST",noLog:!0});return Pm.parse(t)}async updateRunAttempt(e,t,r){await this.sendRequest(`/${M}/runs/${e}/attempts/${t}`,{method:"PATCH",body:r,noLog:!0})}async getTest(e){let t=await this.sendRequest(`/${M}/tests/${e}`,{method:"GET"});return xm.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${M}/tests`,{method:"GET"});return Tm.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${M}/tests/export`,{method:"POST",body:e});return Em.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${M}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${M}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${M}/cache`,{method:"POST",body:e,noLog:!0});return Cm.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${M}/tests/queue`,{method:"POST",body:e});return vm.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${M}/screenshots`,{method:"POST",body:e,noLog:!0});return Lm.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${M}/environments`,{method:"GET"});return km.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${M}/environments/${e}`,{method:"GET"});return us.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${M}/auth/flags`,{method:"GET",noLog:!0});return _m.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${M}/result-cache/lock`,{method:"POST",body:e,signal:t});return zm.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${M}/result-cache/lock`,{method:"DELETE",body:{key:e}})}async deleteCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"DELETE",body:e})}async setCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${M}/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(`/${M}/suites/queue`,{method:"POST",body:e});return Nm.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},r=await this.sendRequest(`/${M}/suites/status`,{method:"POST",body:t,noLog:!0});return Mm.parse(r)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${M}/run-groups/status`,{method:"POST",body:t,noLog:!0});return Iu.array().parse(r)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${M}/cache/lastUsedAt`,{method:"PATCH",body:e})}catch(r){t.error({err:r},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${M}/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(`/${M}/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(`/${M}/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(`/${M}/runs/${t}/attempts/${r}/console-logs`,{method:"POST"});return hi.parse(o)}async generateNetworkLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${M}/runs/${t}/attempts/${r}/network-logs`,{method:"POST",noLog:!0});return hi.parse(o)}async generateHtmlSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/html`,{method:"POST",noLog:!0});return hi.parse(r)}async generateA11yTreeSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/a11y`,{method:"POST",noLog:!0});return hi.parse(r)}async reportBillableEvents(e,t){try{await this.sendRequest(`/${M}/billing/events`,{method:"POST",body:t,noLog:!0})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"GET"});return Dm.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"PATCH",body:t})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${M}/results/tests/${e}`,{method:"POST",body:t});return Fm.parse(r)}};import{randomUUID as Ym}from"crypto";var Bs=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??Ym(),properties:tc({},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??Ym(),properties:tc({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var Jr=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 mc(n){let e={parentChain:[]};return js(n,e),e}function js(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||js({...n,steps:l.steps},e)&&i)return!0;if(js({...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),js({...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 mc({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 Jm(n,e){e(n);for(let t in n){let r=n[t];r&&(Array.isArray(r)?$s(r,e):typeof r=="object"&&Jm(r,e))}}function $s(n,e){for(let t of n)t&&(Array.isArray(t)?$s(t,e):typeof t=="object"&&Jm(t,e))}function Xr({steps:n,topLevel:e=!0,...t}){let{stepCacheEntries:r,logger:o,keyPrefix:i}=t,s=[],a=[],l=0,c=(p,u)=>{try{let m=tr.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=PT(p.id,u),h=m.find(f=>!!r[f]);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}=Xr({...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}=Xr({...t,steps:p.steps,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!gl.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:f}=Xr({...t,steps:m.steps,topLevel:!1});s=s.concat(h),a=a.concat(f);break}if(p.elseSteps){l+=p.elseSteps.length;let{hits:m,misses:h}=Xr({...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 Xm(n,e){return e?`${e}:${n}`:n}function PT(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}function Zm(n){let{moduleStepParents:e=[],moduleIdParents:t=[]}=n;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
14
+ `)),console.log(" ",t(a))}}setMinLevel(e){this.minLogLevel=e}log(...e){this.logWithLevel(1,pn.reset,...e)}info(...e){this.logWithLevel(1,pn.blue,...e)}debug(...e){this.logWithLevel(0,pn.dim,...e)}warn(...e){this.logWithLevel(2,pn.yellow,...e)}error(...e){this.logWithLevel(3,pn.red,...e)}success(...e){this.logWithLevel(4,pn.green,...e)}dimmed(...e){this.logWithLevel(1,pn.dim,...e)}underline(...e){this.logWithLevel(2,pn.underline,...e)}bold(...e){this.logWithLevel(2,pn.bold,...e)}grey(...e){this.logWithLevel(0,pn.grey,...e)}child(e){return new n(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},b=new ac(1,{}),mi={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>mi,flush:()=>{},bindings:()=>({})},Us={},Yr=({logger:n,logKey:e,maxCount:t,intervalMs:r},o,i,...s)=>{let a=Us[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},Us[e]=a),a.totalCount++,a.count<t&&(a.count++,n.debug(o,i,...s)),a.timer=setTimeout(()=>{let l=Us[e];l?.totalCount!==l?.count&&n.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete Us[e]},r)};import{z as Ve}from"zod";var fm=Ve.object({id:Ve.string(),createdAt:Ve.coerce.date(),createdBy:Ve.string(),organizationId:Ve.string(),name:Ve.string(),description:Ve.string().nullish(),enabled:Ve.boolean(),schemaVersion:Ve.string().describe("Schema version for steps"),parameters:Ve.string().array().nullish().describe("Parameter list"),defaultParameters:Ve.record(Ve.string(),Ve.string()).nullish(),defaultCacheKey:Ve.string().nullish(),defaultCacheTtl:Ve.number().nullish(),defaultCacheAllInvocations:Ve.boolean().nullish(),autoAuth:Ve.boolean().nullish(),advanced:wl.nullish()}),FF=fm.extend({steps:Ve.lazy(()=>$e.array())}),gm=5*60*1e3,ym=bt.merge(fm.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as BF}from"date-fns-tz";import{z as pr}from"zod";var lc=pr.object({failureRecovery:pr.boolean().optional(),aiAction:pr.boolean().optional()}),HF=pr.object({ai:lc.optional(),githubAppInstallationId:pr.number().nullish(),gitlabAppAccessToken:pr.string().nullish().optional(),gitlabAppBaseUrl:pr.string().nullish().optional()});import*as x from"zod";var rU=x.object({error:x.boolean(),reason:x.string(),message:x.string()}),oU=Jt.merge(Yl),Sm=ts,iU=Jt.merge(Yl);var sU=Jt.merge(Fu).extend({useConsensus:x.boolean().optional()}),cc=bp,aU=Jt.extend({browserState:x.string(),goal:x.string(),screenshot:x.string()}),bm=Pp,lU=Jt.extend({goal:x.string(),browserState:x.string()}),wm=Ip,cU=Jt.merge(Du);var dU=x.object({testPaths:x.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:x.string().optional(),all:x.boolean().optional(),urlOverride:x.string().optional(),customHeaders:x.record(x.string(),x.string()).optional(),testInputMatrix:x.record(x.string(),x.string()).array().optional()}),vm=x.object({queuedTests:x.unknown().array(),runIds:x.string().uuid().array(),runGroupId:x.string().optional()}),xm=pi,Tm=x.string().array(),pU=x.union([x.object({paths:x.string().array().describe("run specific test paths (e.g. todo-test)"),all:x.boolean().describe("run all tests").optional()}),x.object({path:x.string().describe("deprecated; present for backcompat")})]),Em=x.object({tests:x.record(x.string().describe("Test name"),x.string().describe("Test YAML")),modules:x.record(x.string().describe("Module name"),x.string().describe("Module YAML"))}),TT=x.object({test:x.string().describe("test YAML"),modules:x.record(x.string().describe("moduleId"),x.string().describe("module YAML"))}),uU=TT.array(),mU=x.object({testId:x.string(),schemaVersion:x.string()}).merge(or),hU=x.object({entries:x.array(Rl),testId:x.string()}),fU=x.object({steps:x.array(x.record(x.unknown())),testId:x.string(),schemaVersion:x.string(),organizationId:x.string()}),Cm=Rp,gU=x.object({trigger:x.nativeEnum(Ut),status:x.nativeEnum(ce),startedAt:x.coerce.date().optional(),gitCommitSha:x.string().optional(),gitCommitShaShort:x.string().optional(),gitCommitTimestamp:x.coerce.date().optional(),gitBranchName:x.string().optional(),gitOriginUrl:x.string().optional(),gitCommitMessage:x.string().optional(),gitCommitAuthorName:x.string().optional(),githubRepository:x.string().optional(),gitlabProjectPath:x.string().optional(),pipelineId:x.string().optional()}),Am=x.object({id:x.string()}),yU=x.object({status:x.nativeEnum(ce),updatedAt:x.coerce.date().optional(),finishedAt:x.coerce.date().optional()}),SU=x.object({stepsSnapshot:x.array(x.record(x.unknown())).optional(),runGroupId:x.string().optional(),testId:x.string(),testName:x.string(),resolvedBaseUrl:x.string().optional(),environmentName:x.string().optional(),trigger:x.nativeEnum(Ut),schemaVersion:x.string().optional(),section:x.nativeEnum(Es).optional()}),Rm=x.object({id:x.string()}),ET=ql.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Im=ET.array(),bU=ql.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(),Pm=x.object({id:x.string()}),wU=x.object({status:x.nativeEnum(ce),finishedAt:Re.optional()}).merge(ys),vU=x.object({screenshot:x.string()}),Lm=x.object({key:x.string()}),Om=x.object({orgId:x.string(),userId:x.string()}),km=x.array(us),_m=x.record(x.string(),x.union([x.string(),x.boolean()])),xU=x.object({paths:x.string().array(),env:x.string().optional(),urlOverride:x.string().optional(),customHeaders:x.record(x.string(),x.string()).optional()}),Nm=x.object({suiteRunIds:x.string().array()});var Mm=Mu.array(),TU=x.object({runGroupIds:x.string().array()}),hi=x.object({uploadUrl:x.string()}),EU=Jt.merge(Uu),CU=Jt.merge(Bu),AU=Jt.merge(zu),CT=x.object({testId:x.string().optional().default(""),testName:x.string().optional().default(""),suiteId:x.string().optional().default(""),suiteName:x.string().optional().default(""),creditsUsed:x.number().optional(),usedBy:x.string().optional()}),RU=x.object({transactionId:x.string(),timestamp:x.string(),event:x.nativeEnum(li),properties:CT}).array(),Dm=wu.omit({steps:!0}).extend({steps:x.array(x.record(x.string(),x.unknown())).describe("unparsed ResolvedStep[]")}),IU=x.object({limit:x.number().max(10).optional(),afterTime:x.number().optional()}),Fm=Au.array(),PU=x.object({applied:x.boolean().optional(),appliedAt:x.coerce.date().optional()}),LU=Jt.extend({chunks:Ll.array(),description:x.string().describe("Input to pass to AI"),type:x.union([x.literal("locator"),x.literal("assertion"),x.literal("ai-action")]),softTokenLimit:x.number(),hardTokenLimit:x.number()});import{z as ge}from"zod";var Um=ge.object({orgId:ge.string(),cacheKeys:ge.string().array()}),_U=ge.object({keyParams:Um,clientMetadata:ge.string(),lockAcquisitionTimeoutMs:ge.number().optional()}),zm=ge.object({acquired:ge.boolean(),acquiredByMetadata:ge.string(),keyPrefix:ge.string()}),NU=ge.object({keyPrefix:ge.string(),result:ge.string(),ttlMs:ge.number()}),MU=ge.union([ge.object({keyPrefix:ge.string()}),Um]),AT=ge.object({remainingTtlMs:ge.number(),value:ge.string().nullish()}),DU=ge.object({results:ge.record(ge.string(),AT),activeLocks:ge.string().array()}),Bm=0,jm=5*60*1e3;import{z as Xt}from"zod";var $m="test",Hm="module",En=(t=>(t.TEST=`${$m}.yaml`,t.MODULE=`${Hm}.yaml`,t))(En||{}),xe=(o=>(o.TEST=`momentic/${$m}`,o.MODULE=`momentic/${Hm}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(xe||{}),WU=Bt.merge(or),dc=bt.extend({steps:Xt.array(Xt.record(Xt.string(),Xt.unknown())),schemaVersion:Xt.string()}),GU=dc.extend({fileType:Xt.literal(xe.MODULE)}),VU=Xt.object({test:Xt.string().describe("YAML for the test, including metadata and steps"),modules:Xt.record(Xt.string(),Xt.string()).describe("Map of module name to YAML for the module")});import{validator as ZU}from"@exodus/schemasafe";import{z as e1}from"zod";var Wm=n=>{n.extraHeaders&&(n.extraHeaders=Object.fromEntries(Object.entries(n.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as u1}from"zod";import{z as zs}from"zod";var f1=zs.object({repositoriesIndexed:zs.boolean(),indexingInProgress:zs.boolean(),indexesOutdated:zs.boolean()});import{z as Te}from"zod";var pc=Te.object({assertion:Te.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),RT=Te.object({instruction:Te.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:pc.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.")}),Gm=RT.extend({subSteps:Te.lazy(()=>Gm.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Vm=Te.object({name:Te.string().describe("Short name describing the test plan"),description:Te.string().nullish().transform(n=>n??void 0).describe("Longer form description of the high level goal of the test plan")}),qm=Vm.extend({id:Te.string(),createdAt:Te.coerce.date(),updatedAt:Te.coerce.date(),updatedBy:Te.string(),createdBy:Te.string(),test:Te.object({id:Te.string(),name:Te.string()}).nullish().transform(n=>n??void 0)}),b1=qm.extend({testGenRuns:Te.tuple([]).or(Te.tuple([Te.object({id:Te.string(),startedAt:Te.coerce.date(),status:Te.nativeEnum(ce)})]))}),Km=Te.object({preConditions:pc.array(),postConditions:pc.array(),steps:Gm.array()}),w1=qm.extend({plan:Km.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),v1=Vm.extend({plan:Km.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})});var M="v1";var Zt=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function IT(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var uc=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;for(;r>0;)try{r--;let a=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:this.getHeaders(),signal:o});if(!a.ok){let c=await IT(a);throw new Zt(a.status,c,`Request to ${e} failed with status ${a.status}: ${c}`)}let l;return a.status===204?l=await a.text():l=await a.json(),this.logger&&!t.noLog&&this.logger.debug({result:l,path:e,baseUrl:this.baseUrl,status:a.status},"Got response from Momentic server"),l}catch(a){if(s=a,this.logger&&this.logger.warn({path:e,baseUrl:this.baseUrl,err:a},`Got error response from Momentic server${r>0?", retrying":""}`),a instanceof Zt&&a.status>=400&&a.status<500||r===0)throw a;let l=1500,c=i-r,d=l*Math.pow(2,c-1);await new Promise(p=>setTimeout(p,d))}throw s}},Et=class extends uc{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var lt=class extends Et{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${M}/auth/check`,{method:"GET",noLog:!0}),{orgId:t,userId:r}=Om.parse(e);return{orgId:t,userId:r}}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${M}/runs/status`,{method:"POST",body:e,noLog:!0});return Im.parse(t)}async createRunGroup(e){let t=await this.sendRequest(`/${M}/run-groups`,{method:"POST",body:e,noLog:!0});return Am.parse(t)}async updateRunGroup(e,t){await this.sendRequest(`/${M}/run-groups/${e}`,{method:"PATCH",body:t,noLog:!0})}async createRun(e){let t=await this.sendRequest(`/${M}/runs`,{method:"POST",body:e,noLog:!0});return Rm.parse(t)}async updateRun(e,t){await this.sendRequest(`/${M}/runs/${e}`,{method:"PATCH",body:t,noLog:!0})}async createRunAttempt(e){let t=await this.sendRequest(`/${M}/runs/${e}/attempts`,{method:"POST",noLog:!0});return Pm.parse(t)}async updateRunAttempt(e,t,r){await this.sendRequest(`/${M}/runs/${e}/attempts/${t}`,{method:"PATCH",body:r,noLog:!0})}async getTest(e){let t=await this.sendRequest(`/${M}/tests/${e}`,{method:"GET"});return xm.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${M}/tests`,{method:"GET"});return Tm.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${M}/tests/export`,{method:"POST",body:e});return Em.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${M}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${M}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${M}/cache`,{method:"POST",body:e,noLog:!0});return Cm.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${M}/tests/queue`,{method:"POST",body:e});return vm.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${M}/screenshots`,{method:"POST",body:e,noLog:!0});return Lm.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${M}/environments`,{method:"GET"});return km.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${M}/environments/${e}`,{method:"GET"});return us.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${M}/auth/flags`,{method:"GET",noLog:!0});return _m.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${M}/result-cache/lock`,{method:"POST",body:e,signal:t});return zm.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${M}/result-cache/lock`,{method:"DELETE",body:{key:e}})}async deleteCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"DELETE",body:e})}async setCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${M}/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(`/${M}/suites/queue`,{method:"POST",body:e});return Nm.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},r=await this.sendRequest(`/${M}/suites/status`,{method:"POST",body:t,noLog:!0});return Mm.parse(r)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${M}/run-groups/status`,{method:"POST",body:t,noLog:!0});return Iu.array().parse(r)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${M}/cache/lastUsedAt`,{method:"PATCH",body:e})}catch(r){t.error({err:r},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${M}/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(`/${M}/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(`/${M}/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(`/${M}/runs/${t}/attempts/${r}/console-logs`,{method:"POST"});return hi.parse(o)}async generateNetworkLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${M}/runs/${t}/attempts/${r}/network-logs`,{method:"POST",noLog:!0});return hi.parse(o)}async generateHtmlSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/html`,{method:"POST",noLog:!0});return hi.parse(r)}async generateA11yTreeSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/a11y`,{method:"POST",noLog:!0});return hi.parse(r)}async reportBillableEvents(e,t){try{await this.sendRequest(`/${M}/billing/events`,{method:"POST",body:t,noLog:!0})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"GET"});return Dm.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"PATCH",body:t})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${M}/results/tests/${e}`,{method:"POST",body:t});return Fm.parse(r)}};import{randomUUID as Ym}from"crypto";var Bs=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??Ym(),properties:tc({},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??Ym(),properties:tc({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var Jr=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 mc(n){let e={parentChain:[]};return js(n,e),e}function js(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||js({...n,steps:l.steps},e)&&i)return!0;if(js({...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),js({...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 mc({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 Jm(n,e){e(n);for(let t in n){let r=n[t];r&&(Array.isArray(r)?$s(r,e):typeof r=="object"&&Jm(r,e))}}function $s(n,e){for(let t of n)t&&(Array.isArray(t)?$s(t,e):typeof t=="object"&&Jm(t,e))}function Xr({steps:n,topLevel:e=!0,...t}){let{stepCacheEntries:r,logger:o,keyPrefix:i}=t,s=[],a=[],l=0,c=(p,u)=>{try{let m=tr.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=PT(p.id,u),h=m.find(f=>!!r[f]);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}=Xr({...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}=Xr({...t,steps:p.steps,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!gl.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:f}=Xr({...t,steps:m.steps,topLevel:!1});s=s.concat(h),a=a.concat(f);break}if(p.elseSteps){l+=p.elseSteps.length;let{hits:m,misses:h}=Xr({...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 Xm(n,e){return e?`${e}:${n}`:n}function PT(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}function Zm(n){let{moduleStepParents:e=[],moduleIdParents:t=[]}=n;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
15
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:Xm(n.id,s),moduleId:i,organizationId:n.orgId,value:n.value})}return r.push({key:Xm(n.id,e.join(":")),organizationId:n.orgId,value:n.value,testId:n.testId}),r}function Qm(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 eh(n){let e=new Set;return $s(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 th(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 Qe(n,e,t=!1){return n.length<e?n:n.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var ur={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with"},mr={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with"},hc={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},fc={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function LT(n){switch(n.type){case"ELEMENT_CONTENT":return`${n.negated?mr[n.operation]:ur[n.operation]} '${n.value}'`;case"ELEMENT_ATTRIBUTE":{let t=n.negated?mr[n.operation]:ur[n.operation];return`attribute '${n.attr}' ${t} '${n.value}'`}case"ELEMENT_EXISTENCE":return n.negated?fc[n.condition]:hc[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 JB={CONTENT:"The page"};function OT(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 gc(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 kT(n){switch(n.type){case"CONTENT":return`${n.negated?mr.CONTAINS:ur.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 hr(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: ${Qe(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: ${st(n.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${st(n.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${st(n.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${st(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: ${st(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 ${st(n.target)}`;case"BLUR":return`Focus ${st(n.target)}`;case"DRAG":return`Drag ${st(n.fromTarget)} onto ${st(n.toTarget)}`;case"MOUSE_DRAG":return n.target?.type==="description"&&n.target.elementDescriptor?`Click and drag ${st(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: ${st(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: ${st(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??OT(n.choice);return n.target.type==="coordinates"?t=` from element at coordinates: ${st(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: ${Qe(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: ${st(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 ${st(n.target)} ${LT(n.assertion)}`;case"PAGE_CHECK":return`Assert the page ${kT(n.assertion)}`;case"WAIT_FOR_URL":return n.url?`Wait for page URL to match: ${n.url}`:n.matcher?`Wait for page URL to ${gc(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 nh(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 ej,unset as tj}from"lodash-es";function Cn(n){switch(n.type){case"AI_ACTION":return`AI action: ${Qe(n.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Qe(n.text,100)}`;case"PRESET_ACTION":return hr(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: ${Qe(n.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(n)}}var _T="[FAILED]";async function oh(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?fr(c):Cn(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=`${_T} ${p.description}`,t&&(a=l);try{let m=_u.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 g=await(await fetch(h)).arrayBuffer();p[m]=`data:image/jpeg;base64,${Buffer.from(g).toString("base64")}`}else h&&(p[m]=h.startsWith("data:")?h:`data:image/jpeg;base64,${h}`)}s.push(p)}return{results:s,failureIndex:a}}function fr(n){let e=Cn(n);switch(n.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":e+=`
16
16
  `;for(let t=0;t<n.results.length;t++)e+=Ue(`Sub-step ${t} in AI action:
17
17
  `,2),e+=`${Ue(fr(n.results[t]),2)}
@@ -43,7 +43,7 @@ ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length
43
43
  ${P}`}),u;case"RIGHT_TRACK":{S=void 0,y===0?c.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:P}):N&&c.onDynamicAIActionEvaluatingEvent?.({stepId:N,status:"SUCCESS",message:P});break}case"WRONG_TRACK":{if(S=`${P}
44
44
  ${C.feedback}`,v++,v>=3)return u.message=`Our AI agent requires additional information to achieve this goal:
45
45
  ${P}
46
- ${C.feedback}`,u.status="FAILED",c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:u.message}),u;N&&c.onDynamicAIActionEvaluatingEvent?.({stepId:N,status:"FAILED",message:C.feedback});break}case"IMPOSSIBLE":return u.message=`Our AI evaluator determined this task cannot be achieved: ${P}`,u.status="FAILED",c.onDynamicAIActionEvaluatingEvent?.({stepId:N??e.id,status:"FAILED",message:u.message}),u}let J=setTimeout(()=>{c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);p.info({commandIndex:y,lastActionHint:S},`Generating new sub-command ${y} within AI action`);let V,de;try{({command:V,reasoning:de}=await o.promptToCommand({goal:m,history:g,startingScreenshot:f,disableCache:t?.advanced.disableAICaching??!1,logger:p,actionHint:S,langfuseSessionId:d})),p.info({command:V,reasoning:de},"Got proposed command")}finally{clearTimeout(J)}if(V.type==="FAILURE")return clearTimeout(J),u.status="FAILED",u.message=`Our AI agent determined that no supported actions can fulfill the goals: ${de}`,u;let O={id:ME(),type:"PRESET_ACTION",command:V},I={substepIndex:y+1,message:de||"Generated new command."};c.onDynamicCommandGenerated?.({...I,step:O,parentStepId:e.id}),p.info({commandId:V.id},`Executing sub-command ${y} within AI step: ${hr(V)}`);let L=(await n.executeStepList({...n,options:{...n.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[O]}})).results[0];c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await o.browser.waitForDOMStability({logger:p});let fe=await o.browser.screenshot({clearHighlights:!0,retries:1});u.results.push(L),g.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${fe.toString("base64")}`,urlAfterCommand:o.browser.url(),serializedCommand:hr(V),elementInteracted:L.results[0]?.elementInteracted,thoughts:de});let se={substepIndex:y,output:{...L,message:L.message??"Successfully executed preset action."},step:O,parentStepId:e.id};if(c.onDynamicCommandExecuted?.(se),L.status==="FAILED")if(c.onFailure?.({output:_n.parse(L),step:L,message:L.message}),u.status="FAILED",u.message=L.message,v<3)v++,E=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${L.message}`;else return u;else{if(L.status==="CANCELLED")return c.onCancelled?.({output:_n.parse(L),step:L,message:L.message}),u.status="CANCELLED",u.message=L.message,u;c.onSuccess?.({output:_n.parse(L),step:L,message:L.message})}y++}return u};async function bf(n){let{results:e}=n.failureRecoveryParams,t=e[e.length-1],r=UE(t);if(r)return n.fixtures.logger.info({failedResult:t,isNotEligible:r},"Skipping failure recovery because of ineligible failure"),null;try{return await FE(n)}catch(o){return n.fixtures.logger.error({err:o},"Error during failure recovery attempt"),null}}async function Sf({controller:n,currentPageState:e,newStep:t,patch:r,logger:o}){if(t.aiSuggested=!0,t.type==="PRESET_ACTION"&&"cache"in t.command&&t.command.cache&&"target"in t.command.cache&&"target"in t.command&&t.command.target?.type==="description")try{let i=t.command.cache.target.id,s=await n.getReverseMappedTarget(e,i,!1);t.command.target.elementDescriptor=s}catch(i){o.error({err:i},"Error while reverse mapping target in failure recovery")}t.type==="PRESET_ACTION"&&(t.command.thoughts=r.thoughts)}async function FE(n){let{fixtures:e,work:t,failureRecoveryParams:r}=n,{controller:o,logger:i}=e,{results:s,failedStep:a,nextSteps:l}=r;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.asyncTasks??[]);let c=o.browser.url(),d=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,p=(await o.browser.getBrowserState({skipWait:!0})).serialize(),{results:u}=await oh(s,{numScreenshots:3,addIndices:!0}),m=l.map(y=>Cn(y)),h=await o.runFailureRecovery({currentUrl:c,currentScreenshot:d,failedResults:u,currentPageState:p,nextStepsSerialized:m});if(h.scenario==="INELIGIBLE"||!h.patch)return null;let f=[];if(h.patch.op==="add"){let y=h.patch.value;if(!y)throw new Error("No value in add patch in failure recovery");await Sf({controller:o,currentPageState:p,newStep:y,patch:h.patch,logger:i}),f=[y,a]}else if(h.patch.op==="replace"){let y=h.patch.value;if(!y)throw new Error("No value in replace patch in failure recovery");await Sf({controller:o,currentPageState:p,newStep:y,patch:h.patch,logger:i}),f=[y]}else if(h.patch.op==="remove"&&a.type==="PRESET_ACTION"&&["AI_ASSERTION","PAGE_CHECK"].includes(a.command.type))throw new Error("Cannot modify assertion step in failure recovery");let g;if(f.length){g=await zn(n.work,()=>n.executeStepList({...n,fixtures:{...n.fixtures},listParams:{steps:f,containerName:"AI-recovered step list"}}));for(let y of g.results)y.aiSuggested&&y.type==="PRESET_ACTION"&&(y.message=`AI suggested step: ${y.command.thoughts}`)}else g={status:"SUCCESS",results:[],proposedSteps:[]};return ea(t,{type:"FAILURE_RECOVERY",thoughts:h.reasoning}),t.state.failureRecoveryDisabled=!0,g}function UE(n){if(!n)return"No failed result";if(n.type!=="PRESET_ACTION")return"Not a preset action";let e=n.message;return e?e.includes("AbortError:")?"AbortError":gu.some(t=>e.includes(t))?"User fault and likely irrecoverable":"":"No error message available"}async function wf(n){let{step:e}=n.frameParams,{logger:t,controller:r}=n.fixtures,o=new Date,i=r.browser.getActiveFrameIdentifier();r.browser.setActiveFrame(e.identifier);let s;try{s=await n.executeStepList({...n,listParams:{steps:e.steps,containerName:"frame step list"}})}finally{r.browser.setActiveFrame(i)}let l={...e,...s,startedAt:o,finishedAt:new Date};return jt({asyncTasks:n.work.asyncTasks,nestedResults:s.results,result:l,logger:t}),l}import{randomUUID as na}from"crypto";import zE from"fast-json-patch";import{cloneDeep as BE}from"lodash-es";async function vf(n){let e=n.failedResults,t=[],{sectionParams:r,fixtures:o,work:i,startingUrl:s,startingContextSnapshot:a}=n,{step:l}=r,{controller:c}=o,d=l?.autohealingConfig,p=d?.restartBehavior??{type:"GO_TO_SECTION_START"},u=d?.attempts??1;for(let m=0;m<u;m++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let h=BE(l.steps);await Promise.allSettled(i.asyncTasks??[]);let f=await c.runSectionAutohealing({results:e.results,errorMessage:e.terminalResult?.message,goal:l.description});h=zE.applyPatch(h,f.patches).newDocument;let g=vt.fromSnapshot({snapshot:a,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await jE({controller:c,context:g,restartConfig:p,startingUrl:s});let y=await zn(n.work,()=>n.executeStepList({...n,fixtures:{...n.fixtures,context:g},listParams:{steps:h,containerName:"auto-healed step list"}}));if(t.push(y.results),y.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:h},listResult:y,context:g},healingAttempts:t};e=y}return{healingAttempts:t}}async function jE({controller:n,restartConfig:e,context:t,startingUrl:r}){switch(e.type){case"NAVIGATE_URL":{let o={id:na(),type:"PRESET_ACTION",command:{id:na(),type:"NAVIGATE",url:e.url}};await n.executePresetCommand(null,o.command,t,!1);break}case"GO_TO_SECTION_START":{let o={id:na(),type:"PRESET_ACTION",command:{id:na(),type:"NAVIGATE",url:r}};await n.executePresetCommand(null,o.command,t,!1);break}}}function xf(n,e){switch(n||(n="ON_FAILURE"),n){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Ep(e.command.type))}}async function Tf(n){let{step:e}=n.sectionParams,{logger:t,controller:r,context:o}=n.fixtures,i=new Date,s=r.browser.url(),a=o.toObjectCopy(),l=async()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:"section step list"}}),c=e.autohealingConfig?await zn(n.work,l):await l(),d,p;if(c.status==="FAILED"&&e.autohealingConfig&&!n.work.state.autoHealingDisabled&&xf(e.autohealingConfig.trigger,c.terminalResult)){let m=await vf({...n,startingContextSnapshot:a,startingUrl:s,failedResults:c});m.successfulHealing&&(d=m.successfulHealing.proposedStep,c=m.successfulHealing.listResult,n.fixtures.context=m.successfulHealing.context),p=m.healingAttempts}let u={...e,...c,startedAt:i,finishedAt:new Date,proposedStep:d,healingAttempts:p};return jt({asyncTasks:n.work.asyncTasks,nestedResults:c.results,result:u,logger:t}),u}async function hn(n){let{results:e=[],containerName:t,steps:r}=n.listParams,{logger:o,context:i,controller:s,codeEvalTools:a,billingReporter:l,analytics:c}=n.fixtures,{step:d}=n.callbacks,{orgId:p,fromStepId:u,toStepId:m}=n.inputs,h=n.work,f=[],g="SUCCESS",y,v=0;for(v;v<r.length;v++){let S=r[v],E,T=Cn(S);if(S.skipped)continue;if(h.fastForwardingToStepId&&u){if(S.id===u)h.fastForwardingToStepId=!1;else if(!fi([S],u).result)continue}let C=new Date,P=c.child({step_id:S.id});P.track({type:"execution:step_start",step_type:S.type==="RESOLVED_MODULE"?"MODULE":S.type,command_type:"command"in S?S.command.type:void 0}),o.info({step:S},`Executing step ${v+1}/${r.length} in ${t}: ${T}`),d.onStarted?.(S.id);let k=$E(S),N=i.toRedactedDisplayCopy(),J=s.browser.url(),V=s.executeAbortController.signal,de=Ql(S.type);h.asyncTasks.push(l.reportCreditsUsed(o,S.type,de,{testId:n.inputs.testMetadata?.id,testName:n.inputs.testMetadata?.name,suiteId:n.inputs.suiteMetadata?.id,suiteName:n.inputs.suiteMetadata?.name}));let O,I;switch(S.type){case"PRESET_ACTION":{O="Preset action",I=await Bn(S,async()=>await ta({...n,presetParams:{step:S}}),V),"proposedStep"in I&&I.proposedStep&&(E=I.proposedStep,I.proposedStep=void 0);break}case"AI_ACTION":{O="AI action",I=await Bn(S,()=>ff({...n,aiStepParams:{step:S},executeStepList:hn}),V);break}case"AI_ACTION_DYNAMIC":{O="AI action",I=await Bn(S,()=>yf({...n,aiStepParams:{step:S},executeStepList:hn}),V);break}case"RESOLVED_MODULE":{O=`Module (${S.name})`,I=await Bn(S,async()=>{let se=await Qs({orgId:p,step:S,context:i,logger:o,codeEvalTools:a,signal:V});return Tc({...n,executeStepList:hn,moduleParams:{step:S,resolvedInputs:se}})},V);break}case"CONDITIONAL":{O="Conditional step",I=await Bn(S,()=>hf({...n,conditionalParams:{step:S},executeStepList:hn}),V);break}case"IFRAME":{O="Frame step",I=await Bn(S,()=>wf({...n,frameParams:{step:S},executeStepList:hn}),V);break}case"SECTION":{O="Section";let se=await Bn(S,()=>Tf({...n,sectionParams:{step:S},executeStepList:hn}),V);"proposedStep"in se&&se.proposedStep&&(E=se.proposedStep,se.proposedStep=void 0),I=se;break}default:return(Ae=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(S)}I.beforeUrl=I.beforeUrl??J,I.beforeTestContext=N,S.envKey&&i.setVariable(S.envKey,I.data);let te=s.browser.url();i.setCurrentUrl(te),I.afterUrl=I.afterUrl??te,I.afterTestContext=i.toRedactedDisplayCopy(),e.push(I),HE({startedAt:C,stepTypeName:O,result:I,callbacks:n.callbacks,analytics:P,globalWorkRef:n.work});let L;if(I.status==="FAILED"&&!h.state.failureRecoveryDisabled&&u===void 0&&m===void 0){let se=await bf({...n,executeStepList:hn,failureRecoveryParams:{failedStep:k,nextSteps:r.slice(v+1),results:e}});se&&se.status==="SUCCESS"&&(L=se.proposedSteps,e.push(...se.results))}if(L?f.push(...L):E?f.push(E):f.push(S),h.fastForwardingToStepId&&n.inputs.fromStepId&&fi([S],n.inputs.fromStepId).result&&(h.fastForwardingToStepId=!1),I.status!=="SUCCESS"&&!L||s.closed){g=I.status,y=I;break}else if(S.id===m){s.setClosed();break}}return{status:g,results:e,terminalResult:y,proposedSteps:f}}function HE({startedAt:n,stepTypeName:e,result:t,callbacks:r,analytics:o,globalWorkRef:i}){let{step:s,test:a}=r,l=e.toLowerCase(),c=e.charAt(0).toUpperCase()+e.slice(1),d=new Date;switch(t.status){case"SUCCESS":o.track({type:"execution:step_success",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:d.getTime()-n.getTime()}),s.onSuccess?.({step:t,message:t.message??`${c} executed successfully.`,output:_n.parse(t)});break;case"FAILED":o.track({type:"execution:step_fail",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:d.getTime()-n.getTime(),fail_reason:t.message??`${c} failed.`}),s.onFailure?.({step:t,message:t.message??`${c} failed.`,output:_n.parse(t)});break;case"CANCELLED":o.track({type:"execution:step_cancel",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:d.getTime()-n.getTime()}),s.onCancelled?.({step:t,message:t.message??`${c} cancelled.`,output:_n.parse(t)});break;default:throw new Error(`Unexpected ${l} status: ${t.status}`)}t.status==="SUCCESS"&&i&&a.onUpdateRun?.({results:i.results})}import{randomUUID as Ef}from"crypto";async function Cf(n){let e=new Date;try{return await n.navigate({url:n.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(t){let r={id:Ef(),type:"PRESET_ACTION",status:t.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:t.message,startedAt:e,finishedAt:new Date,results:[],command:{id:Ef(),type:"NAVIGATE",url:n.baseUrl}};return{status:t.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:r}}}var ra=async n=>{let{orgId:e,runId:t,runAttemptId:r,testMetadata:o,steps:i,beforeSteps:s,afterSteps:a}=n.inputs;n.fixtures.logger=n.fixtures.logger.child({orgId:e,runId:t,runAttemptId:r,testId:o?.id}),n.fixtures.analytics=n.fixtures.analytics.child({run_id:t,test_id:o?.id,test_name:o?.name});let{logger:l,controller:c}=n.fixtures,{onTestComplete:d,onTestSuccess:p}=n.callbacks.test;if(n.options.reinitializeBrowser){let h=await Cf(c.browser);if(c.executeAbortController.signal.aborted)return h.status="CANCELLED",await d?.(),h;if(h.status==="FAILED")return await d?.(),h}let u;u=nf(l);let m;try{return l.info(`Starting run for Momentic test '${o?.name??"Unnamed test"}'`),m=await WE(n),m}finally{if(l.info({status:m?.status},"Momentic test final result"),clearInterval(u),await d?.(),m?.status==="PASSED")try{await p?.({steps:i,beforeSteps:s,afterSteps:a})}catch(h){l.warn({err:h},"Error running test success handler, continuing...")}}},WE=async n=>{let{runId:e,runAttemptId:t,testMetadata:r,fromStepId:o,toStepId:i,steps:s,beforeSteps:a,afterSteps:l,orgId:c}=n.inputs,{logger:d,controller:p,context:u,codeEvalTools:m,storage:h}=n.fixtures,{collectDebugData:f,disableHealing:g}=n.options;u.setCurrentUrl(p.browser.url());let y="test",v=s,S=[],E=g||o!==void 0||i!==void 0||void 0,T={results:S,state:{failureRecoveryDisabled:E,autoHealingDisabled:E},asyncTasks:[]},C=!1;if(o&&o===i){y="filtered step";let{result:O,parentChain:I}=fi(s,o);if(!O)throw new Error(`Could not find filtered step using ID: ${o}`);for(let te of I){if(te.type!=="RESOLVED_MODULE")continue;let L=await Qs({orgId:c,step:te,context:u,logger:d,codeEvalTools:m,signal:p.executeAbortController.signal});u.setInputs(L)}v=[O]}else o?(y="partial steps list from step",T.fastForwardingToStepId=!0):i?y="partial steps list until step":(y="entire test",C=!0);let P;if(C&&a&&a.length>0){let{status:O,results:I}=await Af(a,"beforeSteps",n);if(P=I,O!=="PASSED")return f&&Rf({debugDataStorage:n.fixtures.debugDataStorage,work:T,controller:p,storage:h,context:u,orgId:c,runId:e,runAttemptId:t,logger:d,status:O}),T.asyncTasks.push(Promise.resolve(n.callbacks.test.onSaveFinalRunResults?.({beforeResults:P,results:[]}))),await Promise.allSettled(T.asyncTasks),{status:O,beforeResults:P,results:[]}}d.debug({stepsToExecute:v,fromStepId:o,toStepId:i},`Starting step execution for ${y}`);let{status:k,terminalResult:N,proposedSteps:J}=await hn({...n,work:T,listParams:{steps:v,containerName:y,results:S}}),V;if(C&&l&&l.length>0){d.debug("Starting step execution for after step list");try{let{results:O}=await Af(l,"afterSteps",n);V=O}catch(O){d.error({err:O},"Failed to execute after steps list, continuing...")}}if(await Promise.allSettled(T.asyncTasks),T.asyncTasks.push(Promise.resolve(n.callbacks.test.onSaveFinalRunResults?.({results:S,beforeResults:P,afterResults:V}))),f&&Rf({debugDataStorage:n.fixtures.debugDataStorage,work:T,controller:p,storage:h,context:u,orgId:c,runId:e,runAttemptId:t,logger:d,status:k}),k==="FAILED")return{status:"FAILED",results:S,beforeResults:P,afterResults:V,failedStepResult:N};if(k==="CANCELLED")return{status:"CANCELLED",results:S,beforeResults:P,afterResults:V};let de;if(J&&T.state.healingDetails&&r){let O=df(3);await n.callbacks.test.onProposedTestSteps?.({name:O,testId:r.id,orgId:n.inputs.orgId,runId:n.inputs.runId,steps:J,details:T.state.healingDetails,purpose:"AUTO_HEALING"}),de={orgId:n.inputs.orgId,name:O}}return{proposedTest:de,status:"PASSED",results:S,beforeResults:P,afterResults:V}};async function Af(n,e,t){let r=t.fixtures.logger,o=t.callbacks.test.onUpdateRun;r.debug({stepsToExecute:n},`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0}},s={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0,onProposedTestSteps:void 0}},{status:a,results:l}=await hn({...t,work:i,callbacks:s,listParams:{steps:n,containerName:e}});await Promise.allSettled(i.asyncTasks),o?.({[e==="beforeSteps"?"beforeResults":"afterResults"]:l});let d;return a==="SUCCESS"?d="PASSED":a==="CANCELLED"?d="CANCELLED":d="FAILED",{status:d,results:l}}function Rf({debugDataStorage:n,work:e,controller:t,storage:r,logger:o,context:i,orgId:s,runId:a,runAttemptId:l,status:c}){let d=t.browser.retrieveAndClearDebugData(),p=nh(d.logsPerPage),u=rc(d.harPages||{},d.harEntries||{});e.asyncTasks.push((async()=>{try{let m=await t.browser.screenshot({}),h=await pf({codePath:"test-complete-final",storage:r,screenshotBuff:m,logger:o}),f=await U(t.browser.html(),{milliseconds:2e3});i.setVariable(mf,h),c!=="PASSED"&&c!=="SUCCESS"&&(o.debug({finalPageHtml:f},"Final page state HTML"),o.debug({finalScreenshotUrl:h},"Uploaded final screenshot URL"))}catch{}})(),l?n.storeConsoleLogsForRunAttempt(o,s,a,l,p):Promise.resolve(null),l?n.storeNetworkLogsForRunAttempt(o,s,a,l,u):Promise.resolve(null))}async function oa({advanced:n,customHeaders:e,envVariables:t,envName:r,baseUrl:o,logger:i,localTools:s,orgId:a}){let l=vs.parse(n);e&&(l.extraHeaders={...l.extraHeaders,...e});let c=new vt({baseUrl:o,envName:r,variablesFromEnvironment:t,currentUrl:o});await no({obj:l,context:c,bannedKeys:[],allowList:Eu,localTools:s,logger:i,orgId:a});try{return vs.parse(l)}catch(d){throw new A("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as kA}from"lodash-es";import{PostHog as GE}from"posthog-node";async function If(n,e){let t,r=0,o=3,i,s;for(;r<o;)try{let a=await n.getAllFlagsAndPayloads(e);i=a.featureFlags,s=a.featureFlagPayloads;break}catch(a){t=a,r++,await new Promise(l=>setTimeout(l,500*r))}if(i&&s)return{flags:i,payloads:s};throw t}var so=class n extends di{orgId;client;constructor(e,t,r,o){super(r,o),this.orgId=t,this.client=e}static async init(e){let t=new GE("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:r,payloads:o}=await If(t,e);return new n(t,e,r,o)}async refresh(){let{flags:e,payloads:t}=await If(this.client,this.orgId);this.flags=e,this.payloads=t}};var Cc={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
46
+ ${C.feedback}`,u.status="FAILED",c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:u.message}),u;N&&c.onDynamicAIActionEvaluatingEvent?.({stepId:N,status:"FAILED",message:C.feedback});break}case"IMPOSSIBLE":return u.message=`Our AI evaluator determined this task cannot be achieved: ${P}`,u.status="FAILED",c.onDynamicAIActionEvaluatingEvent?.({stepId:N??e.id,status:"FAILED",message:u.message}),u}let J=setTimeout(()=>{c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);p.info({commandIndex:y,lastActionHint:S},`Generating new sub-command ${y} within AI action`);let V,de;try{({command:V,reasoning:de}=await o.promptToCommand({goal:m,history:g,startingScreenshot:f,disableCache:t?.advanced.disableAICaching??!1,logger:p,actionHint:S,langfuseSessionId:d})),p.info({command:V,reasoning:de},"Got proposed command")}finally{clearTimeout(J)}if(V.type==="FAILURE")return clearTimeout(J),u.status="FAILED",u.message=`Our AI agent determined that no supported actions can fulfill the goals: ${de}`,u;let O={id:ME(),type:"PRESET_ACTION",command:V},I={substepIndex:y+1,message:de||"Generated new command."};c.onDynamicCommandGenerated?.({...I,step:O,parentStepId:e.id}),p.info({commandId:V.id},`Executing sub-command ${y} within AI step: ${hr(V)}`);let L=(await n.executeStepList({...n,options:{...n.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[O]}})).results[0];c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await o.browser.waitForDOMStability({logger:p});let fe=await o.browser.screenshot({clearHighlights:!0,retries:1});u.results.push(L),g.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${fe.toString("base64")}`,urlAfterCommand:o.browser.url(),serializedCommand:hr(V),elementInteracted:L.results[0]?.elementInteracted,thoughts:de});let se={substepIndex:y,output:{...L,message:L.message??"Successfully executed preset action."},step:O,parentStepId:e.id};if(c.onDynamicCommandExecuted?.(se),L.status==="FAILED")if(c.onFailure?.({output:_n.parse(L),step:L,message:L.message}),u.status="FAILED",u.message=L.message,v<3)v++,E=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${L.message}`;else return u;else{if(L.status==="CANCELLED")return c.onCancelled?.({output:_n.parse(L),step:L,message:L.message}),u.status="CANCELLED",u.message=L.message,u;c.onSuccess?.({output:_n.parse(L),step:L,message:L.message})}y++}return u};async function bf(n){let{results:e}=n.failureRecoveryParams,t=e[e.length-1],r=UE(t);if(r)return n.fixtures.logger.info({failedResult:t,isNotEligible:r},"Skipping failure recovery because of ineligible failure"),null;try{return await FE(n)}catch(o){return n.fixtures.logger.error({err:o},"Error during failure recovery attempt"),null}}async function Sf({controller:n,currentPageState:e,newStep:t,patch:r,logger:o}){if(t.aiSuggested=!0,t.type==="PRESET_ACTION"&&"cache"in t.command&&t.command.cache&&"target"in t.command.cache&&"target"in t.command&&t.command.target?.type==="description")try{let i=t.command.cache.target.id,s=await n.getReverseMappedTarget(e,i,!1);t.command.target.elementDescriptor=s}catch(i){o.error({err:i},"Error while reverse mapping target in failure recovery")}t.type==="PRESET_ACTION"&&(t.command.thoughts=r.thoughts)}async function FE(n){let{fixtures:e,work:t,failureRecoveryParams:r}=n,{controller:o,logger:i}=e,{results:s,failedStep:a,nextSteps:l}=r;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.asyncTasks??[]);let c=o.browser.url(),d=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,p=(await o.browser.getBrowserState({skipWait:!0})).serialize(),{results:u}=await oh(s,{numScreenshots:3,addIndices:!0}),m=l.map(y=>Cn(y)),h=await o.runFailureRecovery({currentUrl:c,currentScreenshot:d,failedResults:u,currentPageState:p,nextStepsSerialized:m});if(h.scenario==="INELIGIBLE"||!h.patch)return null;let f=[];if(h.patch.op==="add"){let y=h.patch.value;if(!y)throw new Error("No value in add patch in failure recovery");await Sf({controller:o,currentPageState:p,newStep:y,patch:h.patch,logger:i}),f=[y,a]}else if(h.patch.op==="replace"){let y=h.patch.value;if(!y)throw new Error("No value in replace patch in failure recovery");await Sf({controller:o,currentPageState:p,newStep:y,patch:h.patch,logger:i}),f=[y]}else if(h.patch.op==="remove"&&a.type==="PRESET_ACTION"&&["AI_ASSERTION","PAGE_CHECK"].includes(a.command.type))throw new Error("Cannot modify assertion step in failure recovery");let g;if(f.length){g=await zn(n.work,()=>n.executeStepList({...n,fixtures:{...n.fixtures},listParams:{steps:f,containerName:"AI-recovered step list"}}));for(let y of g.results)y.aiSuggested&&y.type==="PRESET_ACTION"&&(y.message=`AI suggested step: ${y.command.thoughts}`)}else g={status:"SUCCESS",results:[],proposedSteps:[]};return ea(t,{type:"FAILURE_RECOVERY",thoughts:h.reasoning}),t.state.failureRecoveryDisabled=!0,g}function UE(n){if(!n)return"No failed result";if(n.type!=="PRESET_ACTION")return"Not a preset action";let e=n.message;return e?e.includes("AbortError:")?"AbortError":gu.some(t=>e.includes(t))?"User fault and likely irrecoverable":"":"No error message available"}async function wf(n){let{step:e}=n.frameParams,{logger:t,controller:r}=n.fixtures,o=new Date,i=r.browser.getActiveFrameIdentifier();r.browser.setActiveFrame(e.identifier);let s;try{s=await n.executeStepList({...n,listParams:{steps:e.steps,containerName:"frame step list"}})}finally{r.browser.setActiveFrame(i)}let l={...e,...s,startedAt:o,finishedAt:new Date};return jt({asyncTasks:n.work.asyncTasks,nestedResults:s.results,result:l,logger:t}),l}import{randomUUID as na}from"crypto";import zE from"fast-json-patch";import{cloneDeep as BE}from"lodash-es";async function vf(n){let e=n.failedResults,t=[],{sectionParams:r,fixtures:o,work:i,startingUrl:s,startingContextSnapshot:a}=n,{step:l}=r,{controller:c}=o,d=l?.autohealingConfig,p=d?.restartBehavior??{type:"GO_TO_SECTION_START"},u=d?.attempts??1;for(let m=0;m<u;m++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let h=BE(l.steps);await Promise.allSettled(i.asyncTasks??[]);let f=await c.runSectionAutohealing({results:e.results,errorMessage:e.terminalResult?.message,goal:l.description});h=zE.applyPatch(h,f.patches).newDocument;let g=vt.fromSnapshot({snapshot:a,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await jE({controller:c,context:g,restartConfig:p,startingUrl:s});let y=await zn(n.work,()=>n.executeStepList({...n,fixtures:{...n.fixtures,context:g},listParams:{steps:h,containerName:"auto-healed step list"}}));if(t.push(y.results),y.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:h},listResult:y,context:g},healingAttempts:t};e=y}return{healingAttempts:t}}async function jE({controller:n,restartConfig:e,context:t,startingUrl:r}){switch(e.type){case"NAVIGATE_URL":{let o={id:na(),type:"PRESET_ACTION",command:{id:na(),type:"NAVIGATE",url:e.url}};await n.executePresetCommand(null,o.command,t,!1);break}case"GO_TO_SECTION_START":{let o={id:na(),type:"PRESET_ACTION",command:{id:na(),type:"NAVIGATE",url:r}};await n.executePresetCommand(null,o.command,t,!1);break}}}function xf(n,e){switch(n||(n="ON_FAILURE"),n){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Ep(e.command.type))}}async function Tf(n){let{step:e}=n.sectionParams,{logger:t,controller:r,context:o}=n.fixtures,i=new Date,s=r.browser.url(),a=o.toObjectCopy(),l=async()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:"section step list"}}),c=e.autohealingConfig?await zn(n.work,l):await l(),d,p;if(c.status==="FAILED"&&e.autohealingConfig&&!n.work.state.autoHealingDisabled&&xf(e.autohealingConfig.trigger,c.terminalResult)){let m=await vf({...n,startingContextSnapshot:a,startingUrl:s,failedResults:c});m.successfulHealing&&(d=m.successfulHealing.proposedStep,c=m.successfulHealing.listResult,n.fixtures.context=m.successfulHealing.context),p=m.healingAttempts}let u={...e,...c,startedAt:i,finishedAt:new Date,proposedStep:d,healingAttempts:p};return jt({asyncTasks:n.work.asyncTasks,nestedResults:c.results,result:u,logger:t}),u}async function hn(n){let{results:e=[],containerName:t,steps:r}=n.listParams,{logger:o,context:i,controller:s,codeEvalTools:a,billingReporter:l,analytics:c}=n.fixtures,{step:d}=n.callbacks,{orgId:p,fromStepId:u,toStepId:m}=n.inputs,h=n.work,f=[],g="SUCCESS",y,v=0;for(v;v<r.length;v++){let S=r[v],E,T=Cn(S);if(S.skipped)continue;if(h.fastForwardingToStepId&&u){if(S.id===u)h.fastForwardingToStepId=!1;else if(!fi([S],u).result)continue}let C=new Date,P=c.child({step_id:S.id});P.track({type:"execution:step_start",step_type:S.type==="RESOLVED_MODULE"?"MODULE":S.type,command_type:"command"in S?S.command.type:void 0}),o.info({step:S},`Executing step ${v+1}/${r.length} in ${t}: ${T}`),d.onStarted?.(S.id);let k=$E(S),N=i.toRedactedDisplayCopy(),J=s.browser.url(),V=s.executeAbortController.signal,de=Ql(S.type);h.asyncTasks.push(l.reportCreditsUsed(o,S.type,de,{testId:n.inputs.testMetadata?.id,testName:n.inputs.testMetadata?.name,suiteId:n.inputs.suiteMetadata?.id,suiteName:n.inputs.suiteMetadata?.name}));let O,I;switch(S.type){case"PRESET_ACTION":{O="Preset action",I=await Bn(S,async()=>await ta({...n,presetParams:{step:S}}),V),"proposedStep"in I&&I.proposedStep&&(E=I.proposedStep,I.proposedStep=void 0);break}case"AI_ACTION":{O="AI action",I=await Bn(S,()=>ff({...n,aiStepParams:{step:S},executeStepList:hn}),V);break}case"AI_ACTION_DYNAMIC":{O="AI action",I=await Bn(S,()=>yf({...n,aiStepParams:{step:S},executeStepList:hn}),V);break}case"RESOLVED_MODULE":{O=`Module (${S.name})`,I=await Bn(S,async()=>{let se=await Qs({orgId:p,step:S,context:i,logger:o,codeEvalTools:a,signal:V});return Tc({...n,executeStepList:hn,moduleParams:{step:S,resolvedInputs:se}})},V);break}case"CONDITIONAL":{O="Conditional step",I=await Bn(S,()=>hf({...n,conditionalParams:{step:S},executeStepList:hn}),V);break}case"IFRAME":{O="Frame step",I=await Bn(S,()=>wf({...n,frameParams:{step:S},executeStepList:hn}),V);break}case"SECTION":{O="Section";let se=await Bn(S,()=>Tf({...n,sectionParams:{step:S},executeStepList:hn}),V);"proposedStep"in se&&se.proposedStep&&(E=se.proposedStep,se.proposedStep=void 0),I=se;break}default:return(Ce=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(S)}I.beforeUrl=I.beforeUrl??J,I.beforeTestContext=N,S.envKey&&i.setVariable(S.envKey,I.data);let te=s.browser.url();i.setCurrentUrl(te),I.afterUrl=I.afterUrl??te,I.afterTestContext=i.toRedactedDisplayCopy(),e.push(I),HE({startedAt:C,stepTypeName:O,result:I,callbacks:n.callbacks,analytics:P,globalWorkRef:n.work});let L;if(I.status==="FAILED"&&!h.state.failureRecoveryDisabled&&u===void 0&&m===void 0){let se=await bf({...n,executeStepList:hn,failureRecoveryParams:{failedStep:k,nextSteps:r.slice(v+1),results:e}});se&&se.status==="SUCCESS"&&(L=se.proposedSteps,e.push(...se.results))}if(L?f.push(...L):E?f.push(E):f.push(S),h.fastForwardingToStepId&&n.inputs.fromStepId&&fi([S],n.inputs.fromStepId).result&&(h.fastForwardingToStepId=!1),I.status!=="SUCCESS"&&!L||s.closed){g=I.status,y=I;break}else if(S.id===m){s.setClosed();break}}return{status:g,results:e,terminalResult:y,proposedSteps:f}}function HE({startedAt:n,stepTypeName:e,result:t,callbacks:r,analytics:o,globalWorkRef:i}){let{step:s,test:a}=r,l=e.toLowerCase(),c=e.charAt(0).toUpperCase()+e.slice(1),d=new Date;switch(t.status){case"SUCCESS":o.track({type:"execution:step_success",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:d.getTime()-n.getTime()}),s.onSuccess?.({step:t,message:t.message??`${c} executed successfully.`,output:_n.parse(t)});break;case"FAILED":o.track({type:"execution:step_fail",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:d.getTime()-n.getTime(),fail_reason:t.message??`${c} failed.`}),s.onFailure?.({step:t,message:t.message??`${c} failed.`,output:_n.parse(t)});break;case"CANCELLED":o.track({type:"execution:step_cancel",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:d.getTime()-n.getTime()}),s.onCancelled?.({step:t,message:t.message??`${c} cancelled.`,output:_n.parse(t)});break;default:throw new Error(`Unexpected ${l} status: ${t.status}`)}t.status==="SUCCESS"&&i&&a.onUpdateRun?.({results:i.results})}import{randomUUID as Ef}from"crypto";async function Cf(n){let e=new Date;try{return await n.navigate({url:n.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(t){let r={id:Ef(),type:"PRESET_ACTION",status:t.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:t.message,startedAt:e,finishedAt:new Date,results:[],command:{id:Ef(),type:"NAVIGATE",url:n.baseUrl}};return{status:t.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:r}}}var ra=async n=>{let{orgId:e,runId:t,runAttemptId:r,testMetadata:o,steps:i,beforeSteps:s,afterSteps:a}=n.inputs;n.fixtures.logger=n.fixtures.logger.child({orgId:e,runId:t,runAttemptId:r,testId:o?.id}),n.fixtures.analytics=n.fixtures.analytics.child({run_id:t,test_id:o?.id,test_name:o?.name});let{logger:l,controller:c}=n.fixtures,{onTestComplete:d,onTestSuccess:p}=n.callbacks.test;if(n.options.reinitializeBrowser){let h=await Cf(c.browser);if(c.executeAbortController.signal.aborted)return h.status="CANCELLED",await d?.(),h;if(h.status==="FAILED")return await d?.(),h}let u;u=nf(l);let m;try{return l.info(`Starting run for Momentic test '${o?.name??"Unnamed test"}'`),m=await WE(n),m}finally{if(l.info({status:m?.status},"Momentic test final result"),clearInterval(u),await d?.(),m?.status==="PASSED")try{await p?.({steps:i,beforeSteps:s,afterSteps:a})}catch(h){l.warn({err:h},"Error running test success handler, continuing...")}}},WE=async n=>{let{runId:e,runAttemptId:t,testMetadata:r,fromStepId:o,toStepId:i,steps:s,beforeSteps:a,afterSteps:l,orgId:c}=n.inputs,{logger:d,controller:p,context:u,codeEvalTools:m,storage:h}=n.fixtures,{collectDebugData:f,disableHealing:g}=n.options;u.setCurrentUrl(p.browser.url());let y="test",v=s,S=[],E=g||o!==void 0||i!==void 0||void 0,T={results:S,state:{failureRecoveryDisabled:E,autoHealingDisabled:E},asyncTasks:[]},C=!1;if(o&&o===i){y="filtered step";let{result:O,parentChain:I}=fi(s,o);if(!O)throw new Error(`Could not find filtered step using ID: ${o}`);for(let te of I){if(te.type!=="RESOLVED_MODULE")continue;let L=await Qs({orgId:c,step:te,context:u,logger:d,codeEvalTools:m,signal:p.executeAbortController.signal});u.setInputs(L)}v=[O]}else o?(y="partial steps list from step",T.fastForwardingToStepId=!0):i?y="partial steps list until step":(y="entire test",C=!0);let P;if(C&&a&&a.length>0){let{status:O,results:I}=await Af(a,"beforeSteps",n);if(P=I,O!=="PASSED")return f&&Rf({debugDataStorage:n.fixtures.debugDataStorage,work:T,controller:p,storage:h,context:u,orgId:c,runId:e,runAttemptId:t,logger:d,status:O}),T.asyncTasks.push(Promise.resolve(n.callbacks.test.onSaveFinalRunResults?.({beforeResults:P,results:[]}))),await Promise.allSettled(T.asyncTasks),{status:O,beforeResults:P,results:[]}}d.debug({stepsToExecute:v,fromStepId:o,toStepId:i},`Starting step execution for ${y}`);let{status:k,terminalResult:N,proposedSteps:J}=await hn({...n,work:T,listParams:{steps:v,containerName:y,results:S}}),V;if(C&&l&&l.length>0){d.debug("Starting step execution for after step list");try{let{results:O}=await Af(l,"afterSteps",n);V=O}catch(O){d.error({err:O},"Failed to execute after steps list, continuing...")}}if(await Promise.allSettled(T.asyncTasks),T.asyncTasks.push(Promise.resolve(n.callbacks.test.onSaveFinalRunResults?.({results:S,beforeResults:P,afterResults:V}))),f&&Rf({debugDataStorage:n.fixtures.debugDataStorage,work:T,controller:p,storage:h,context:u,orgId:c,runId:e,runAttemptId:t,logger:d,status:k}),k==="FAILED")return{status:"FAILED",results:S,beforeResults:P,afterResults:V,failedStepResult:N};if(k==="CANCELLED")return{status:"CANCELLED",results:S,beforeResults:P,afterResults:V};let de;if(J&&T.state.healingDetails&&r){let O=df(3);await n.callbacks.test.onProposedTestSteps?.({name:O,testId:r.id,orgId:n.inputs.orgId,runId:n.inputs.runId,steps:J,details:T.state.healingDetails,purpose:"AUTO_HEALING"}),de={orgId:n.inputs.orgId,name:O}}return{proposedTest:de,status:"PASSED",results:S,beforeResults:P,afterResults:V}};async function Af(n,e,t){let r=t.fixtures.logger,o=t.callbacks.test.onUpdateRun;r.debug({stepsToExecute:n},`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0}},s={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0,onProposedTestSteps:void 0}},{status:a,results:l}=await hn({...t,work:i,callbacks:s,listParams:{steps:n,containerName:e}});await Promise.allSettled(i.asyncTasks),o?.({[e==="beforeSteps"?"beforeResults":"afterResults"]:l});let d;return a==="SUCCESS"?d="PASSED":a==="CANCELLED"?d="CANCELLED":d="FAILED",{status:d,results:l}}function Rf({debugDataStorage:n,work:e,controller:t,storage:r,logger:o,context:i,orgId:s,runId:a,runAttemptId:l,status:c}){let d=t.browser.retrieveAndClearDebugData(),p=nh(d.logsPerPage),u=rc(d.harPages||{},d.harEntries||{});e.asyncTasks.push((async()=>{try{let m=await t.browser.screenshot({}),h=await pf({codePath:"test-complete-final",storage:r,screenshotBuff:m,logger:o}),f=await U(t.browser.html(),{milliseconds:2e3});i.setVariable(mf,h),c!=="PASSED"&&c!=="SUCCESS"&&(o.debug({finalPageHtml:f},"Final page state HTML"),o.debug({finalScreenshotUrl:h},"Uploaded final screenshot URL"))}catch{}})(),l?n.storeConsoleLogsForRunAttempt(o,s,a,l,p):Promise.resolve(null),l?n.storeNetworkLogsForRunAttempt(o,s,a,l,u):Promise.resolve(null))}async function oa({advanced:n,customHeaders:e,envVariables:t,envName:r,baseUrl:o,logger:i,localTools:s,orgId:a}){let l=vs.parse(n);e&&(l.extraHeaders={...l.extraHeaders,...e});let c=new vt({baseUrl:o,envName:r,variablesFromEnvironment:t,currentUrl:o});await no({obj:l,context:c,bannedKeys:[],allowList:Eu,localTools:s,logger:i,orgId:a});try{return vs.parse(l)}catch(d){throw new A("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as kA}from"lodash-es";import{PostHog as GE}from"posthog-node";async function If(n,e){let t,r=0,o=3,i,s;for(;r<o;)try{let a=await n.getAllFlagsAndPayloads(e);i=a.featureFlags,s=a.featureFlagPayloads;break}catch(a){t=a,r++,await new Promise(l=>setTimeout(l,500*r))}if(i&&s)return{flags:i,payloads:s};throw t}var so=class n extends di{orgId;client;constructor(e,t,r,o){super(r,o),this.orgId=t,this.client=e}static async init(e){let t=new GE("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:r,payloads:o}=await If(t,e);return new n(t,e,r,o)}async refresh(){let{flags:e,payloads:t}=await If(this.client,this.orgId);this.flags=e,this.payloads=t}};var Cc={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
47
47
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
48
48
  var __hasOwnProp = Object.prototype.hasOwnProperty;
49
49
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -2948,7 +2948,7 @@ function registerAllMomenticListeners() {
2948
2948
 
2949
2949
  // src/html/index.ts
2950
2950
  registerAllMomenticListeners();
2951
- `,cssGeneratorLibJs:'// Taken from https://cdn.jsdelivr.net/npm/css-selector-generator@3.6.8/build/index.min.js\n!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.CssSelectorGenerator=e():t.CssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return"object"==typeof t&&null!==t&&t.nodeType===Node.ELEMENT_NODE}t.r(e),t.d(e,{default:()=>K,getCssSelector:()=>J});const o={NONE:"",DESCENDANT:" ",CHILD:" > "},r={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"},i="CssSelectorGenerator";function c(t="unknown problem",...e){console.warn(`${i}: ${t}`,...e)}const u={selectors:[r.id,r.class,r.tag,r.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function s(t){return t instanceof RegExp}function a(t){return["string","function"].includes(typeof t)||s(t)}function l(t){return Array.isArray(t)?t.filter(a):[]}function f(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function d(t,e){if(f(t))return t.contains(e)||c("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return f(n)?(n!==document&&c("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function m(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function p(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function h(t){return[].concat(...t)}function g(t){const e=t.map((t=>{if(s(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(c("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return c("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function y(t,e,n){const o=Array.from(d(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function b(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const o=[];let r=t;for(;n(r)&&r!==e;)o.push(r),r=r.parentElement;return o}function N(t,e){return p(t.map((t=>b(t,e))))}const S=", ",E=new RegExp(["^$","\\\\s"].join("|")),w=new RegExp(["^$"].join("|")),I=[r.nthoftype,r.tag,r.id,r.class,r.attribute,r.nthchild],v=g(["class","id","ng-*"]);function T({name:t}){return`[${t}]`}function C({name:t,value:e}){return`[${t}=\'${e}\']`}function O({nodeName:t,nodeValue:e}){return{name:V(t),value:V(e)}}function x(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t))).map(O);return[...e.map(T),...e.map(C)]}function j(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!w.test(t))).map((t=>`.${V(t)}`))}function A(t){const e=t.getAttribute("id")||"",n=`#${V(e)}`,o=t.getRootNode({composed:!1});return!E.test(e)&&y([t],n,o)?[n]:[]}function $(t){const e=t.parentNode;if(e){const o=Array.from(e.childNodes).filter(n).indexOf(t);if(o>-1)return[`:nth-child(${o+1})`]}return[]}function D(t){return[V(t.tagName.toLowerCase())]}function R(t){const e=[...new Set(h(t.map(D)))];return 0===e.length||e.length>1?[]:[e[0]]}function P(t){const e=R([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function _(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(function*(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,o=L(1);for(;o.length<=t.length&&n<e;){n+=1;const e=o.map((e=>t[e]));yield e,o=k(o,t.length-1)}}(t,{maxResults:e}))}function k(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return L(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?L(n+1):o}function L(t=1){return Array.from(Array(t).keys())}const M=":".charCodeAt(0).toString(16).toUpperCase(),F=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function V(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${M} `:F.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const Y={tag:R,id:function(t){return 0===t.length||t.length>1?[]:A(t[0])},class:function(t){return p(t.map(j))},attribute:function(t){return p(t.map(x))},nthchild:function(t){return p(t.map($))},nthoftype:function(t){return p(t.map(P))}},q={tag:D,id:A,class:j,attribute:x,nthchild:$,nthoftype:P};function B(t){return t.includes(r.tag)||t.includes(r.nthoftype)?[...t]:[...t,r.tag]}function G(t={}){const e=[...I];return t[r.tag]&&t[r.nthoftype]&&e.splice(e.indexOf(r.tag),1),e.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function H(t,e,n="",r){const i=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+o.DESCENDANT+t)),...t.map((t=>e+o.CHILD+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=g(n),u=g(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=Y[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),a=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?_(a,{maxResults:i}):a.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?_(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(B):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(G)}(e,t))).filter((t=>t.length>0))}(o,n),i=h(r);return[...new Set(i)]}(t,r.root,r),n);for(const e of i)if(y(t,e,r.root))return e;return null}function W(t){return{value:t,include:!1}}function U({selectors:t,operator:e}){let n=[...I];t[r.tag]&&t[r.nthoftype]&&(n=n.filter((t=>t!==r.tag)));let o="";return n.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(o+=t)}))})),e+o}function z(t){return[":root",...b(t).reverse().map((t=>{const e=function(t,e,n=o.NONE){const r={};return e.forEach((e=>{Reflect.set(r,e,function(t,e){return q[e](t)}(t,e).map(W))})),{element:t,operator:n,selectors:r}}(t,[r.nthchild],o.CHILD);return e.selectors.nthchild.forEach((t=>{t.include=!0})),e})).map(U)].join("")}function J(t,e={}){const o=function(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(n);return[...new Set(e)]}(t),i=function(t,e={}){const n=Object.assign(Object.assign({},u),e);return{selectors:(o=n.selectors,Array.isArray(o)?o.filter((t=>{return e=r,n=t,Object.values(e).includes(n);var e,n})):[]),whitelist:l(n.whitelist),blacklist:l(n.blacklist),root:d(n.root,t),combineWithinSelector:!!n.combineWithinSelector,combineBetweenSelectors:!!n.combineBetweenSelectors,includeTag:!!n.includeTag,maxCombinations:m(n.maxCombinations),maxCandidates:m(n.maxCandidates)};var o}(o[0],e);let c="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...N(t,e).map((t=>[t]))];for(const t of r){const e=H(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,c,i)}let f=a();for(;f;){const{foundElements:t,selector:e}=f;if(y(o,e,i.root))return e;s=t[0],c=e,f=a()}return o.length>1?o.map((t=>J(t,i))).join(S):function(t){return t.map(z).join(S)}(o)}const K=J;return e})()));'};import{randomUUID as wg}from"crypto";import{existsSync as pa,mkdirSync as XC,readFileSync as ZC,writeFileSync as QC}from"fs";import{Jimp as eA}from"jimp";import tA from"js-beautify";import{cloneDeep as nA}from"lodash-es";var Pf={"application/prs.cww":["cww"],"application/prs.xsf+xml":["xsf"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["*xfdf"],"application/vnd.age":["age"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["*fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["*mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.pwg-xhtml-print+xml":["xhtm"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml","uo"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["*prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["*sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["*aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif","btf"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.cld":["cld"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.pytha.pyox":["pyo","pyox"],"model/vnd.sap.vds":["vds"],"model/vnd.usda":["usda"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.familysearch.gedcom":["ged"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]};Object.freeze(Pf);var Lf=Pf;var Of={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(Of);var kf=Of;var $t=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},ao,wi,br,Ac=class{constructor(...e){ao.set(this,new Map),wi.set(this,new Map),br.set(this,new Map);for(let t of e)this.define(t)}define(e,t=!1){for(let[r,o]of Object.entries(e)){r=r.toLowerCase(),o=o.map(a=>a.toLowerCase()),$t(this,br,"f").has(r)||$t(this,br,"f").set(r,new Set);let i=$t(this,br,"f").get(r),s=!0;for(let a of o){let l=a.startsWith("*");if(a=l?a.slice(1):a,i?.add(a),s&&$t(this,wi,"f").set(r,a),s=!1,l)continue;let c=$t(this,ao,"f").get(a);if(c&&c!=r&&!t)throw new Error(`"${r} -> ${a}" conflicts with "${c} -> ${a}". Pass \`force=true\` to override this definition.`);$t(this,ao,"f").set(a,r)}}return this}getType(e){if(typeof e!="string")return null;let t=e.replace(/^.*[/\\]/,"").toLowerCase(),r=t.replace(/^.*\./,"").toLowerCase(),o=t.length<e.length;return!(r.length<t.length-1)&&o?null:$t(this,ao,"f").get(r)??null}getExtension(e){return typeof e!="string"?null:(e=e?.split?.(";")[0],(e&&$t(this,wi,"f").get(e.trim().toLowerCase()))??null)}getAllExtensions(e){return typeof e!="string"?null:$t(this,br,"f").get(e.toLowerCase())??null}_freeze(){this.define=()=>{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(let e of $t(this,br,"f").values())Object.freeze(e);return this}_getTestState(){return{types:$t(this,ao,"f"),extensions:$t(this,wi,"f")}}};ao=new WeakMap,wi=new WeakMap,br=new WeakMap;var Rc=Ac;var _f=new Rc(kf,Lf)._freeze();import{homedir as xg}from"os";import{basename as rA,extname as oA,join as Ti,resolve as iA}from"path";import{chromium as Tg,devices as sA}from"playwright";import{addExtra as aA}from"playwright-extra";import lA from"puppeteer-extra-plugin-recaptcha";import{v4 as cA}from"uuid";var lo={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","title","meta","iframe","script","style","path","svg","br","::marker","noscript"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-aria-hidden","data-hidden","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-"],alwaysInterestingTruthyPropertyNames:["contenteditable"]};function Nf(n){if(n[0]?.match(/[0-9a-zA-Z]/)===null)return!0;if(n.length>10){let p=Math.floor(n.length/8);if((n.match(/[-_:A-Z/ ]/g)??[]).length<p)return!0}if((n.match(/[^0-9a-zA-Z.]/g)??[]).length/n.length>.2)return!0;let t=(n.match(/[0-9]/g)??[]).length;if(t/n.length>.3)return!0;let r=(n.toLowerCase().match(/[aeiou]/gi)??[]).length;if((n.toLowerCase().match(/[bcdfghjklmnpqrstvwxyz]/gi)??[]).length/r>5)return!0;let i=new Set(["a","e","i","o","u","y"]),s=0,a=0;for(let p of n.toLowerCase())p>="a"&&p<="z"&&!i.has(p)?(a++,a>s&&(s=a)):a=0;if(s>4)return!0;let l=(n.match(/[A-Z]/g)??[]).length,c=(n.match(/[a-z]/g)??[]).length,d=Math.ceil(n.length*.3);return!!(c&&t&&Math.abs(c-t)<d||c&&l&&Math.abs(c-l)<d)}import{randomUUID as Ff}from"crypto";import{cloneDeep as Pc}from"lodash-es";var wr={r:147,g:196,b:125,a:.55},Mf={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:wr,paddingColor:wr,borderColor:wr,marginColor:wr,eventTargetColor:wr,shapeColor:wr,shapeMarginColor:wr,showInfo:!0,showAccessibilityInfo:!0},ia=["display","opacity","visibility","height","max-height","overflow"];function Df({snapshot:n,devicePixelRatio:e,frameIdFilter:t,processAllFrames:r,logger:o}){let i=n.strings,s=n.documents;t?s=s.filter(d=>i[d.frameId]===t):r||(s=[s[0]]);let a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return s.forEach((d,p)=>{let u=qE({document:d,stringConstants:i,frameIndex:p,devicePixelRatio:e,backendIdToNode:a,frameIndexToIframeNode:l,logger:o});c.roots.push(u)}),c}function qE({document:n,stringConstants:e,devicePixelRatio:t,frameIndex:r,frameIndexToIframeNode:o,backendIdToNode:i,logger:s}){let a=n.layout,l={};a.nodeIndex.forEach((T,C)=>{l[T]=C});let c=a.styles,d=a.bounds??[],p=n.nodes,u=p.contentDocumentIndex??{index:[],value:[]},m=p.backendNodeId??[],h=p.attributes??[],f=p.parentIndex??[],g=p.nodeName??[],y=p.nodeType??[],v=p.pseudoType??{index:[],value:[]},S=p.inputChecked??{index:[]},E=n.frameId;for(let T=0;T<m.length;T++){let C=m[T],P=y[T],k=h[T]??[],N=f[T]&&f[T]>=0?f[T]:null,J=N?m[N]:null,V=J?i[J]:null,de=v.index.indexOf(T),O=de!==-1?e[v.value[de]]:void 0,I=l[T],te;I?te=d[I]??[]:te=[];let L=g[T]!==void 0?e[g[T]]?.toLowerCase():void 0;if(!L){s.warn({backendNodeId:C,frameId:E,frameIndex:r,nodeBounds:te},"DOM node has no tag name");continue}let fe={backendNodeId:C,psuedoType:O,nodeType:P,parentFrameId:E,frameIndex:r,bounds:{x:te[0]??null,y:te[1]??null,width:te[2]??null,height:te[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:J,tagName:L,parent:V??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};V&&P==1&&!O&&V.childrenBackendIds.push(C);let se=u.index.indexOf(T);if(se!==-1){let Q=u.value[se];o[Q]=fe}for(let Q of Object.keys(fe.bounds)){let we=Q;fe.bounds[we]!==null&&(fe.bounds[we]/=t)}let Ae=c[T]??[];for(let Q=0;Q<Ae.length&&!(Q>=ia.length);Q++){let we=Ae[Q];if(!we||isNaN(we))continue;let pt=e[we];if(!pt)continue;let De=ia[Q];fe.computedStyles[De]=pt}for(let Q=0;Q<k.length;Q+=2){let we=k[Q],pt=k[Q+1];if(!we||!pt)continue;let De=e[we],F=e[pt];!De||!F||(fe.attributes[De]=F)}S.index.includes(T)&&(fe.attributes.checked="true"),i[fe.backendNodeId]=fe}return i[m[0]]}function Ic(n){if(n.mPathSelector)return n.mPathSelector;let e=n.parent,t;if(!e)t=n.tagName;else if(n.tagName==="body")t="body";else{let r=e.childrenBackendIds.indexOf(n.backendNodeId),o=` > ${n.tagName}:nth-child(${r+1})`;t=`${Ic(e)}${o}`}return n.mPathSelector=t,t}var KE=["focusable","keyshortcuts","controls","live","relevant","orientation"],YE=["selected","readonly","modal","required","invalid"],JE=["id","name","role","content"],XE=["path"],ZE=["statictext","textbox","checkbox","combobox","table","caption","columnheader","rowheader","gridcell","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch"],QE=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog","ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],eC=["menulistpopup","statictext","inlinetextbox"],tC=80,Uf=100,sa=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],nC=["cite"],rC={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},oC={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},zf={indentLevel:0},Lc=class n{id;role;name;nameSources;tagName;content;properties;internalProperties;dataMomenticId;pathFromRoot;parent;children;domNode;backendNodeId;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&!Nf(t)?t:""),this.role=this.role||(e.domNode.attributes.role??""),lC(this.properties,e.domNode)}dC(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(){if(this.domNode&&XE.includes(this.domNode.tagName))return!1;if(ZE.includes(this.role.toLowerCase())||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||lo.alwaysInterestingTruthyPropertyNames.some(t=>!!this.properties[t]))return!0;let e=this.properties.class;return typeof e=="string"&&e.split(" ").some(t=>Wf(t))?!0:this.children.every(t=>t.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(t=>t.role==="StaticText")?!0:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(t=>t.startsWith("data"))}serialize(e=zf){let t=Object.assign({},zf,e),{indentLevel:r,noChildren:o,noProperties:i,noId:s,noContent:a,condensedMode:l}=t,c=Pc(this.properties),d=" ".repeat(r),p=this.role||"",u=this.tagName??"unknown",m=this.name;p==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(T=>!T.superseded&&T.type==="contents")&&this.children.length>0&&(m="");let f=this.nameSources?.find(T=>!T.superseded);if(f&&!f.nativeSource&&f.type==="relatedElement"){let T=f.attributeValue?.relatedNodes??[];T.length===1&&T[0].text&&T[0].text===m&&(m="")}let g=sa.includes(this.role)||nC.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${d}${m}
2951
+ `,cssGeneratorLibJs:'// Taken from https://cdn.jsdelivr.net/npm/css-selector-generator@3.6.8/build/index.min.js\n!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.CssSelectorGenerator=e():t.CssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return"object"==typeof t&&null!==t&&t.nodeType===Node.ELEMENT_NODE}t.r(e),t.d(e,{default:()=>K,getCssSelector:()=>J});const o={NONE:"",DESCENDANT:" ",CHILD:" > "},r={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"},i="CssSelectorGenerator";function c(t="unknown problem",...e){console.warn(`${i}: ${t}`,...e)}const u={selectors:[r.id,r.class,r.tag,r.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function s(t){return t instanceof RegExp}function a(t){return["string","function"].includes(typeof t)||s(t)}function l(t){return Array.isArray(t)?t.filter(a):[]}function f(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function d(t,e){if(f(t))return t.contains(e)||c("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return f(n)?(n!==document&&c("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function m(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function p(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function h(t){return[].concat(...t)}function g(t){const e=t.map((t=>{if(s(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(c("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return c("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function y(t,e,n){const o=Array.from(d(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function b(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const o=[];let r=t;for(;n(r)&&r!==e;)o.push(r),r=r.parentElement;return o}function N(t,e){return p(t.map((t=>b(t,e))))}const S=", ",E=new RegExp(["^$","\\\\s"].join("|")),w=new RegExp(["^$"].join("|")),I=[r.nthoftype,r.tag,r.id,r.class,r.attribute,r.nthchild],v=g(["class","id","ng-*"]);function T({name:t}){return`[${t}]`}function C({name:t,value:e}){return`[${t}=\'${e}\']`}function O({nodeName:t,nodeValue:e}){return{name:V(t),value:V(e)}}function x(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t))).map(O);return[...e.map(T),...e.map(C)]}function j(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!w.test(t))).map((t=>`.${V(t)}`))}function A(t){const e=t.getAttribute("id")||"",n=`#${V(e)}`,o=t.getRootNode({composed:!1});return!E.test(e)&&y([t],n,o)?[n]:[]}function $(t){const e=t.parentNode;if(e){const o=Array.from(e.childNodes).filter(n).indexOf(t);if(o>-1)return[`:nth-child(${o+1})`]}return[]}function D(t){return[V(t.tagName.toLowerCase())]}function R(t){const e=[...new Set(h(t.map(D)))];return 0===e.length||e.length>1?[]:[e[0]]}function P(t){const e=R([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function _(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(function*(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,o=L(1);for(;o.length<=t.length&&n<e;){n+=1;const e=o.map((e=>t[e]));yield e,o=k(o,t.length-1)}}(t,{maxResults:e}))}function k(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return L(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?L(n+1):o}function L(t=1){return Array.from(Array(t).keys())}const M=":".charCodeAt(0).toString(16).toUpperCase(),F=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function V(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${M} `:F.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const Y={tag:R,id:function(t){return 0===t.length||t.length>1?[]:A(t[0])},class:function(t){return p(t.map(j))},attribute:function(t){return p(t.map(x))},nthchild:function(t){return p(t.map($))},nthoftype:function(t){return p(t.map(P))}},q={tag:D,id:A,class:j,attribute:x,nthchild:$,nthoftype:P};function B(t){return t.includes(r.tag)||t.includes(r.nthoftype)?[...t]:[...t,r.tag]}function G(t={}){const e=[...I];return t[r.tag]&&t[r.nthoftype]&&e.splice(e.indexOf(r.tag),1),e.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function H(t,e,n="",r){const i=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+o.DESCENDANT+t)),...t.map((t=>e+o.CHILD+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=g(n),u=g(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=Y[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),a=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?_(a,{maxResults:i}):a.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?_(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(B):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(G)}(e,t))).filter((t=>t.length>0))}(o,n),i=h(r);return[...new Set(i)]}(t,r.root,r),n);for(const e of i)if(y(t,e,r.root))return e;return null}function W(t){return{value:t,include:!1}}function U({selectors:t,operator:e}){let n=[...I];t[r.tag]&&t[r.nthoftype]&&(n=n.filter((t=>t!==r.tag)));let o="";return n.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(o+=t)}))})),e+o}function z(t){return[":root",...b(t).reverse().map((t=>{const e=function(t,e,n=o.NONE){const r={};return e.forEach((e=>{Reflect.set(r,e,function(t,e){return q[e](t)}(t,e).map(W))})),{element:t,operator:n,selectors:r}}(t,[r.nthchild],o.CHILD);return e.selectors.nthchild.forEach((t=>{t.include=!0})),e})).map(U)].join("")}function J(t,e={}){const o=function(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(n);return[...new Set(e)]}(t),i=function(t,e={}){const n=Object.assign(Object.assign({},u),e);return{selectors:(o=n.selectors,Array.isArray(o)?o.filter((t=>{return e=r,n=t,Object.values(e).includes(n);var e,n})):[]),whitelist:l(n.whitelist),blacklist:l(n.blacklist),root:d(n.root,t),combineWithinSelector:!!n.combineWithinSelector,combineBetweenSelectors:!!n.combineBetweenSelectors,includeTag:!!n.includeTag,maxCombinations:m(n.maxCombinations),maxCandidates:m(n.maxCandidates)};var o}(o[0],e);let c="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...N(t,e).map((t=>[t]))];for(const t of r){const e=H(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,c,i)}let f=a();for(;f;){const{foundElements:t,selector:e}=f;if(y(o,e,i.root))return e;s=t[0],c=e,f=a()}return o.length>1?o.map((t=>J(t,i))).join(S):function(t){return t.map(z).join(S)}(o)}const K=J;return e})()));'};import{randomUUID as wg}from"crypto";import{existsSync as pa,mkdirSync as XC,readFileSync as ZC,writeFileSync as QC}from"fs";import{Jimp as eA}from"jimp";import tA from"js-beautify";import{cloneDeep as nA}from"lodash-es";var Pf={"application/prs.cww":["cww"],"application/prs.xsf+xml":["xsf"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["*xfdf"],"application/vnd.age":["age"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["*fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["*mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.pwg-xhtml-print+xml":["xhtm"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml","uo"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["*prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["*sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["*aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif","btf"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.cld":["cld"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.pytha.pyox":["pyo","pyox"],"model/vnd.sap.vds":["vds"],"model/vnd.usda":["usda"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.familysearch.gedcom":["ged"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]};Object.freeze(Pf);var Lf=Pf;var Of={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(Of);var kf=Of;var $t=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},ao,wi,br,Ac=class{constructor(...e){ao.set(this,new Map),wi.set(this,new Map),br.set(this,new Map);for(let t of e)this.define(t)}define(e,t=!1){for(let[r,o]of Object.entries(e)){r=r.toLowerCase(),o=o.map(a=>a.toLowerCase()),$t(this,br,"f").has(r)||$t(this,br,"f").set(r,new Set);let i=$t(this,br,"f").get(r),s=!0;for(let a of o){let l=a.startsWith("*");if(a=l?a.slice(1):a,i?.add(a),s&&$t(this,wi,"f").set(r,a),s=!1,l)continue;let c=$t(this,ao,"f").get(a);if(c&&c!=r&&!t)throw new Error(`"${r} -> ${a}" conflicts with "${c} -> ${a}". Pass \`force=true\` to override this definition.`);$t(this,ao,"f").set(a,r)}}return this}getType(e){if(typeof e!="string")return null;let t=e.replace(/^.*[/\\]/,"").toLowerCase(),r=t.replace(/^.*\./,"").toLowerCase(),o=t.length<e.length;return!(r.length<t.length-1)&&o?null:$t(this,ao,"f").get(r)??null}getExtension(e){return typeof e!="string"?null:(e=e?.split?.(";")[0],(e&&$t(this,wi,"f").get(e.trim().toLowerCase()))??null)}getAllExtensions(e){return typeof e!="string"?null:$t(this,br,"f").get(e.toLowerCase())??null}_freeze(){this.define=()=>{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(let e of $t(this,br,"f").values())Object.freeze(e);return this}_getTestState(){return{types:$t(this,ao,"f"),extensions:$t(this,wi,"f")}}};ao=new WeakMap,wi=new WeakMap,br=new WeakMap;var Rc=Ac;var _f=new Rc(kf,Lf)._freeze();import{homedir as xg}from"os";import{basename as rA,extname as oA,join as Ti,resolve as iA}from"path";import{chromium as Tg,devices as sA}from"playwright";import{addExtra as aA}from"playwright-extra";import lA from"puppeteer-extra-plugin-recaptcha";import{v4 as cA}from"uuid";var lo={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","title","meta","iframe","script","style","path","svg","br","::marker","noscript"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-aria-hidden","data-hidden","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-"],alwaysInterestingTruthyPropertyNames:["contenteditable"]};function Nf(n){if(n[0]?.match(/[0-9a-zA-Z]/)===null)return!0;if(n.length>10){let p=Math.floor(n.length/8);if((n.match(/[-_:A-Z/ ]/g)??[]).length<p)return!0}if((n.match(/[^0-9a-zA-Z.]/g)??[]).length/n.length>.2)return!0;let t=(n.match(/[0-9]/g)??[]).length;if(t/n.length>.3)return!0;let r=(n.toLowerCase().match(/[aeiou]/gi)??[]).length;if((n.toLowerCase().match(/[bcdfghjklmnpqrstvwxyz]/gi)??[]).length/r>5)return!0;let i=new Set(["a","e","i","o","u","y"]),s=0,a=0;for(let p of n.toLowerCase())p>="a"&&p<="z"&&!i.has(p)?(a++,a>s&&(s=a)):a=0;if(s>4)return!0;let l=(n.match(/[A-Z]/g)??[]).length,c=(n.match(/[a-z]/g)??[]).length,d=Math.ceil(n.length*.3);return!!(c&&t&&Math.abs(c-t)<d||c&&l&&Math.abs(c-l)<d)}import{randomUUID as Ff}from"crypto";import{cloneDeep as Pc}from"lodash-es";var wr={r:147,g:196,b:125,a:.55},Mf={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:wr,paddingColor:wr,borderColor:wr,marginColor:wr,eventTargetColor:wr,shapeColor:wr,shapeMarginColor:wr,showInfo:!0,showAccessibilityInfo:!0},ia=["display","opacity","visibility","height","max-height","overflow"];function Df({snapshot:n,devicePixelRatio:e,frameIdFilter:t,processAllFrames:r,logger:o}){let i=n.strings,s=n.documents;t?s=s.filter(d=>i[d.frameId]===t):r||(s=[s[0]]);let a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return s.forEach((d,p)=>{let u=qE({document:d,stringConstants:i,frameIndex:p,devicePixelRatio:e,backendIdToNode:a,frameIndexToIframeNode:l,logger:o});c.roots.push(u)}),c}function qE({document:n,stringConstants:e,devicePixelRatio:t,frameIndex:r,frameIndexToIframeNode:o,backendIdToNode:i,logger:s}){let a=n.layout,l={};a.nodeIndex.forEach((T,C)=>{l[T]=C});let c=a.styles,d=a.bounds??[],p=n.nodes,u=p.contentDocumentIndex??{index:[],value:[]},m=p.backendNodeId??[],h=p.attributes??[],f=p.parentIndex??[],g=p.nodeName??[],y=p.nodeType??[],v=p.pseudoType??{index:[],value:[]},S=p.inputChecked??{index:[]},E=n.frameId;for(let T=0;T<m.length;T++){let C=m[T],P=y[T],k=h[T]??[],N=f[T]&&f[T]>=0?f[T]:null,J=N?m[N]:null,V=J?i[J]:null,de=v.index.indexOf(T),O=de!==-1?e[v.value[de]]:void 0,I=l[T],te;I?te=d[I]??[]:te=[];let L=g[T]!==void 0?e[g[T]]?.toLowerCase():void 0;if(!L){s.warn({backendNodeId:C,frameId:E,frameIndex:r,nodeBounds:te},"DOM node has no tag name");continue}let fe={backendNodeId:C,psuedoType:O,nodeType:P,parentFrameId:E,frameIndex:r,bounds:{x:te[0]??null,y:te[1]??null,width:te[2]??null,height:te[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:J,tagName:L,parent:V??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};V&&P==1&&!O&&V.childrenBackendIds.push(C);let se=u.index.indexOf(T);if(se!==-1){let Q=u.value[se];o[Q]=fe}for(let Q of Object.keys(fe.bounds)){let we=Q;fe.bounds[we]!==null&&(fe.bounds[we]/=t)}let Ce=c[T]??[];for(let Q=0;Q<Ce.length&&!(Q>=ia.length);Q++){let we=Ce[Q];if(!we||isNaN(we))continue;let pt=e[we];if(!pt)continue;let De=ia[Q];fe.computedStyles[De]=pt}for(let Q=0;Q<k.length;Q+=2){let we=k[Q],pt=k[Q+1];if(!we||!pt)continue;let De=e[we],F=e[pt];!De||!F||(fe.attributes[De]=F)}S.index.includes(T)&&(fe.attributes.checked="true"),i[fe.backendNodeId]=fe}return i[m[0]]}function Ic(n){if(n.mPathSelector)return n.mPathSelector;let e=n.parent,t;if(!e)t=n.tagName;else if(n.tagName==="body")t="body";else{let r=e.childrenBackendIds.indexOf(n.backendNodeId),o=` > ${n.tagName}:nth-child(${r+1})`;t=`${Ic(e)}${o}`}return n.mPathSelector=t,t}var KE=["focusable","keyshortcuts","controls","live","relevant","orientation"],YE=["selected","readonly","modal","required","invalid"],JE=["id","name","role","content"],XE=["path"],ZE=["statictext","textbox","checkbox","combobox","table","caption","columnheader","rowheader","gridcell","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch"],QE=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog","ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],eC=["menulistpopup","statictext","inlinetextbox"],tC=80,Uf=100,sa=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],nC=["cite"],rC={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},oC={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},zf={indentLevel:0},Lc=class n{id;role;name;nameSources;tagName;content;properties;internalProperties;dataMomenticId;pathFromRoot;parent;children;domNode;backendNodeId;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&!Nf(t)?t:""),this.role=this.role||(e.domNode.attributes.role??""),lC(this.properties,e.domNode)}dC(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(){if(this.domNode&&XE.includes(this.domNode.tagName))return!1;if(ZE.includes(this.role.toLowerCase())||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||lo.alwaysInterestingTruthyPropertyNames.some(t=>!!this.properties[t]))return!0;let e=this.properties.class;return typeof e=="string"&&e.split(" ").some(t=>Wf(t))?!0:this.children.every(t=>t.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(t=>t.role==="StaticText")?!0:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(t=>t.startsWith("data"))}serialize(e=zf){let t=Object.assign({},zf,e),{indentLevel:r,noChildren:o,noProperties:i,noId:s,noContent:a,condensedMode:l}=t,c=Pc(this.properties),d=" ".repeat(r),p=this.role||"",u=this.tagName??"unknown",m=this.name;p==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(T=>!T.superseded&&T.type==="contents")&&this.children.length>0&&(m="");let f=this.nameSources?.find(T=>!T.superseded);if(f&&!f.nativeSource&&f.type==="relatedElement"){let T=f.attributeValue?.relatedNodes??[];T.length===1&&T[0].text&&T[0].text===m&&(m="")}let g=sa.includes(this.role)||nC.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${d}${m}
2952
2952
  `;let y=`${d}<${u}`;!s&&!g&&(y+=` id="${this.id}"`);let v=a??!1;(c.multiline||c.contenteditable)&&this.children.length>0&&(v=!0),p&&p!=="generic"&&p!==u&&!(rC[p]??[]).includes(u)&&(y+=` role=${JSON.stringify(p)}`),m&&(y+=` name=${JSON.stringify(m)}`),this.content&&!v&&(y+=` content=${JSON.stringify(this.content)}`);let S=Date.now();if(Object.keys(c).length>0&&!i){if(Date.now()-S>1e3)throw new Error(`Serialization for the HTML element with tag ${u} and internal ID ${this.id} took too long. Please reach out to Momentic Support.`);Object.entries(c).forEach(([T,C])=>{if(!KE.includes(T)){{if(YE.includes(T)&&(!C||C==="false"))return;if(T==="value"&&v&&(c.type==="text"||this.role==="textbox"))return;if(T==="level"&&`${C}`=="1")return;if(T==="url"&&c.src&&u==="img")return;if(T==="url"&&c.href&&u==="a")return;if(T==="editable"&&C==="plaintext")return;if(T==="type"&&C===u)return;if(l&&!oC[T])return}typeof C=="string"?y+=` ${T}="${Qe(C,Uf,!0)}"`:typeof C=="boolean"?C?y+=` ${T}`:y+=` ${T}={false}`:typeof C<"u"&&(y+=` ${T}={${Qe(JSON.stringify(C),Uf,!0)}}`)}})}if(u==="::before"||u==="::after"){let T="";for(let C of this.children)T+=C.serialize({...e,indentLevel:r,neighbors:0});return T}let E=e.maxLevel!==void 0&&r/2>=e.maxLevel;if(this.children.length===0||o||E)y+=` />
2953
2953
  `;else{let T="";for(let P of this.children)T+=P.serialize({...e,indentLevel:r+2,neighbors:0});let C=T.trim();C.length<=tC&&!C.includes(`
2954
2954
  `)?y+=`>${C}</${u}>
@@ -2970,22 +2970,22 @@ Available pages:${JSON.stringify(r.map(i=>i.url))}`);if(!Un(o.url,this.logger)){
2970
2970
  `,""),t=t.replaceAll(" ","");let r=uA(t);return t.length-r+uo*r}if(typeof n>"u")return 0;if(typeof n=="number")return String(n).length;if(Array.isArray(n))return n.forEach(t=>{e+=Qc(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*uo:e+=85*uo:e+=Qc(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 Cg=1e6,Rg={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Ig={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:15e3,maxLineLength:500},Ag=/<(\S+) id="(\d+)".*?>/g,mA=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Pg=["h1","h2","section","footer","nav","aside","form","label","dialog"],hA=[...Pg,"span","div","h3"],fA=["table","select","form","ul","ol","menu","pre","code","dialog"],gA=["table","form","dialog","nav","section","ul","select"];function ed(n){return n.serializedTree.length>Cg&&(n.logger.warn({serializedTreeLength:n.serializedTree.length},"Serialized condensed tree is too long to chunk, truncating before chunking"),n.serializedTree=n.serializedTree.slice(0,Cg)),yA(n)}function yA({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 f=l[c],g=Ei(f);p+=g,f.length>s&&(f=f.slice(0,s));let S=Array.from(f.matchAll(Ag)).map(I=>I&&I.length>=3?{tagName:I[1],id:I[2]}:void 0).filter(I=>!!I),T=Array.from(f.matchAll(mA)).map(I=>I&&(I[2]||I[4])).filter(I=>!!I);T.reverse();let C=f.replace(/ id="[0-9]+"/g,"");d.push(C);for(let I of S)u.push(I.id),m.push(I);for(let I of T){let te=m[m.length-1];te&&te.tagName===I&&m.pop()}let P=m.some(I=>fA.includes(I.tagName)),k=l[c+1]??"",N=Ei(k),V=Array.from(k.matchAll(Ag)).map(I=>I&&I.length>2?I[1]:void 0).filter(I=>!!I),de=V.some(I=>Pg.includes(I)),O=V.some(I=>hA.includes(I));p+N>=i&&(h=!0),p>=r&&(de&&!P||T.some(I=>gA.includes(I)))&&(h=!0),p>=o&&O&&!P&&(h=!0),c++}return d.length&&a.push({ids:u,content:d.join(`
2973
- `),tokenLength:p}),a.forEach((f,g)=>{t.debug({chunk:f},`Chunk for page filtering (index ${g+1}/${a.length})`)}),{chunks:a}}var td=4e4,nd=8e4;async function Tr(n){let{serializedTree:e,logger:t,flagStore:r,softTokenLimit:o=td}=n;if(Ei(e)<o)return e;let s=ed({serializedTree:e,options:Ig,logger:t});try{return r.isBooleanFlagEnabled("rag_v2")?await U(SA({...n,chunks:s.chunks}),{milliseconds:15e3}):await U(wA(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,nd*uo)}}}async function SA({chunks:n,generator:e,description:t,type:r,logger:o,signal:i,orgId:s,tree:a,softTokenLimit:l=td,hardTokenLimit:c=nd}){let d=await e.rankChunksWithAi({chunks:n,description:t,type:r,softTokenLimit:l,hardTokenLimit:c},{abortSignal:i,orgId:s,logger:o,loggerTags:Ze(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=nd}=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:Ze(n.logger)});for(let c of l.keywords){let d=n.chunks.filter(h=>h.content.includes(c));if(!d.length||d.reduce((h,f)=>h+f.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 wA(n){let{description:e,generator:t,orgId:r,tree:o,logger:i,signal:s,softTokenLimit:a=td}=n,l=ed({serializedTree:o.serialize(),options:Rg,logger:i}),c=await t.rankChunksWithRag({description:e,chunks:l.chunks,tokenLimit:a},{abortSignal:s,orgId:r,logger:i,loggerTags:Ze(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 rd(n,e){if(!n.description)throw new A("ActionFailureError","Cannot locate element with empty description");return mn({action:()=>vA(n,e),frameUrl:n.iframeUrl,browser:e.browser,logger:e.logger})}async function vA(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 Pt({orgId:a,s:m,context:r,logger:e.logger,localTools:d,signal:e.abortSignal}));let{serializedTree:h,tree:f}=await Wn(c,{filterByViewport:o,abortSignal:u,skipWait:i,logger:l}),g,y=Date.now(),v;for(;!g&&Date.now()-y<3e3;){u.throwIfAborted();try{g=await c.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(J){v=J}}if(!g)throw new A("InternalWebAgentError",`Failed to take screenshot of page to locate element: ${v?.message}`);let S=h,E=!1;S=await Tr({type:"locator",description:m,serializedTree:h,flagStore:e.flagStore,tree:f,logger:l,generator:p,orgId:a}),S!==h&&(E=!0);let T=g.toString("base64"),C=await p.getElementLocation({browserState:S,goal:m,screenshot:T,feedback:void 0},{disableCache:t,orgId:a,abortSignal:u,loggerTags:Ze(l)});l.debug({usedRag:E,result:C},"Got locator result");let P=C.id>0;if(s?.details?.push({type:"AI_LOCATION",matched:P,pageState:S,ragUsed:E,thoughts:C.thoughts}),!P)throw new A("ActionFailureError",`Could not find any relevant element: ${C.thoughts}`);let k={id:C.id,inputDescription:m,targetSource:"AI",targetUpdateTime:new Date().toUTCString()},N=await c.resolveTarget(null,k);if(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:k,resolution:N}}var xA=15;async function od({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=TA(o),s=0,a=Date.now(),l,c,d;try{await mn({action:()=>t.clearHighlights(),frameUrl:n.iframeUrl,browser:t,logger:r})}catch(u){r.warn({err:u},"Failed to clear highlights before AI assertion, continuing...")}let p;for(;s<xA&&(!p||p-a<o);){e.abortSignal.throwIfAborted(),s!==0&&(r.info(`Waiting ${i}ms before retrying AI assertion`),await Z(i,e.abortSignal)),p=Date.now();try{let u=await mn({action:async()=>{let m=await Lg(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,Og({command:n,state:m,fixtures:e,useConsensus:!1,highlightElementsOnFailure:!1}))},frameUrl:n.iframeUrl,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 mn({action:async()=>Og({command:n,state:await Lg(t,r,e.abortSignal),fixtures:e,useConsensus:!0,highlightElementsOnFailure:!0}),frameUrl:n.iframeUrl,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 Lg(n,e,t){let[r,o]=await Promise.all([Wn(n,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),n.screenshot({retries:1,respectActiveFrame:!0})]);return{...r,screenshotBuff:o}}async function Og({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(),f=p;f=await Tr({type:"assertion",serializedTree:p,description:n.assertion,flagStore:t.flagStore,tree:u,generator:a,orgId:l,logger:s,signal:c}),f!==p&&(d.ragUsed=!0),d.pageState=f;let g={goal:n.assertion,url:h,browserState:f,screenshot:m.toString("base64"),contextChoice:n.contextChoice},v=await(n.contextChoice==="VISION_ONLY"?(S,E)=>a.getVisualAssertionResult(S,E):(S,E)=>a.getAssertionResult(S,E))(g,{useConsensus:r,disableCache:!!n.disableCache,logger:s,orgId:l,abortSignal:c,loggerTags:Ze(s)});if(s.debug({usedRag:d.ragUsed,result:v},"Got assertion attempt result"),(v.result||o)&&v.relevantElements&&(d.relevantElementsSerialized=v.relevantElements.map(S=>i.getSerializedFormFromA11yId(S)).filter(S=>!!S),await EA(v.relevantElements,i,s)),!v.result)throw new A("AssertionFailureError",v.thoughts);return{succeedImmediately:!1,thoughts:v.thoughts,urlAfterCommand:h,afterScreenshotOverride:m}}function TA(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 EA(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 U(e.highlight({id:o},i.signal),{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 CA=3e4;async function kg({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??CA/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(n.headers||{}).filter(([p,u])=>p&&u)),a;if(ro(n.url)&&(a=n.url),t&&oo(n.url,t)&&(a=new URL(n.url,t).toString()),!a)throw new A("ActionFailureError",`Invalid URL: ${n.url}`);let c=await U((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 mo=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([Wn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=await Tr({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:{...Ze(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([Wn(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 Tr({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:{...Ze(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 Wn(this.browser,e)}async locateElement(e){return rd(e,this.getControllerFixtures())}async locateElementWithSelector(e,t){return mn({action:async()=>{let r=await this.browser.resolveHardcodedCssSelector({root:void 0,selector:e,timeoutMs:2e3});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:r}},frameUrl:t,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 mn({action:()=>this.wrapElementTargetingCommandHelper(e),frameUrl:e.options.iframeUrl,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)&&!cl(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 along with non-description target");let f={id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},g=await this.browser.resolveTarget(e,f,{skipFetchTree:i.skipFetchTree,targetName:c,logger:m});return{result:await o({locator:g.locator}),elementInteractedDisplayString:g.displayString,newTarget:{cache:f}}}a&&(this.logger.debug("Cache explicitly disabled for this step"),u=!0,r=void 0),r?.inputDescription&&!Ou(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&&Yi(r);if(!r){let f=new Date;this.logger.debug({targetHealingInProgress:d},"Prompting AI for an updated element location"),u&&await Z(this.browser.smartWaitingTimeout,this.executeAbortController.signal),p--;let g=await rd({description:Rs(s,t.elementDescriptor),disableCache:a,iframeUrl:i.iframeUrl},this.getControllerFixtures(e)),y=i.disableGlobalLocatorRedirect?{locator:g.resolution.locator}:await this.attemptLocatorRedirect(g.resolution.locator,m),v=await o(y),S;if(d){this.analytics.track({type:"execution:step_heal",heal_type:"AI",step_type:"PRESET_ACTION",command_type:s.type,duration_ms:Date.now()-f.getTime()}),g.target={...g.target,targetSource:"AI_HEALED",targetUpdateTime:new Date().toUTCString()};let E=g.resolution.pageState;if(E)try{S=await this.getReverseMappedTarget(E,g.target.id,!0)}catch(T){m.warn({err:T},"Failed to reverse map element auto-healed by AI, continuing...")}}return{result:v,elementInteractedDisplayString:g.resolution.displayString,newTarget:{cache:g.target,thoughts:g.thoughts,description:S}}}try{let f=new Date,g=await this.browser.resolveTarget(e,r,{targetName:c,logger:m}),y=i.disableGlobalLocatorRedirect?{locator:g.locator}:await this.attemptLocatorRedirect(g.locator,m),v=await o(y);if(h){let S=g.decisions.filter(E=>E.matched);if(S.length!==1)m.warn({decisions:g.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let E=S[0].type;this.analytics.track({type:"execution:step_heal",heal_type:E,step_type:"PRESET_ACTION",command_type:s.type,duration_ms:Date.now()-f.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:g.displayString,newTarget:{cache:r}}}catch(f){if(this.throwIfClosed(),f instanceof A)throw f;if(p>0&&t)return m.debug({err:f,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",f.message,{errOptions:{cause:f}})}}async attemptLocatorRedirect(e,t){return this.flagStore.isBooleanFlagEnabled("global_locator_redirect")?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return bi(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(Un(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))Zc(e,r,o)}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>zc(e),getFeatureFlagStore:()=>this.flagStore}}async resolveCommandTemplateStrings(e,t){return no({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()?od({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 od({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:Ze(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 f=h.message;throw f.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."):f.includes("AIProviderError")&&f.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(!ro(t.url)&&!oo(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&&ln(t.target))await this.browser.hoverUsingVisualCoordinates(t.target.pixels);else if(t.target&&t.target.elementDescriptor.trim()){let{newTarget:h,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:t.target,cache:t.cache?.target,action:g=>this.browser.hover(g),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});u=f,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 Z(a,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"CLICK":{if(ln(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:f,result:g}=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});f.cache&&(t.cache={target:f.cache});let y={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,newTargets:[f],data:g};return Ys(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(ln(t.fromTarget)&&ln(t.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(t.fromTarget.pixels,t.toTarget.pixels,{hoverSeconds:t.hoverSeconds});break}if(ln(t.fromTarget)||ln(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,f)=>this.browser.dragAndDrop(h.locator,f.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);if(isNaN(u)||isNaN(m))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);if(t.target&&ln(t.target)){await this.browser.mouseDragUsingVisualCoordinates(u,m,t.steps,t.target.pixels,{force:t.force});break}let h,f,g=[];if(t.target?.elementDescriptor){let{newTarget:y,elementInteractedDisplayString:v,result:S}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:t.target,cache:t.cache?.target,action:async E=>E.locator,options:{useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableCache:o}});h=S,f=v,g.push(y)}return await this.browser.mouseDrag(u,m,t.steps,h,{force:t.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,newTargets:g}}case"SELECT_OPTION":{if(!Ln(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:f}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:{type:"description",elementDescriptor:u},cache:t.cache?.target,action:g=>this.browser.selectOption(g,m,t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,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&&ln(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=[],f=RA(t.target);if(f){let{elementInteractedDisplayString:y,newTarget:v}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:f,cache:t.cache?.target,action:S=>this.browser.typeIntoTarget(t.value,S,{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 g={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:m,newTargets:h};return Ys(u,g.urlAfterCommand)&&(g.succeedImmediately=!0,g.succeedImmediatelyReason="URL changed"),g}case"HOVER":{if(ln(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(!Ln(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&&!Ln(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});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Ys(c,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;case"REQUEST":{let u=new IA,m=AA(fetch,u),h;try{h=new URL(t.url).hostname}catch{}return{data:{...await Js({command:t,baseUrl:this.browser.baseUrl,logger:this.logger,fetchImplementation:m}),cookies:Ns(u,h)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await kg({command:t,baseUrl:this.browser.baseUrl,logger:this.logger}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return lf({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 Qf({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=_s.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 sf({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 mn({frameUrl:t.iframeUrl,browser:this.browser,logger:this.logger,action:async()=>Xs({assertion:t.assertion,browser:this.browser,logger:this.logger,timeout:t.timeout,signal:this.executeAbortController.signal})});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:Ze(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode(e){this.recordAbortController=new AbortController;let t=new ma({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:Ze(this.logger)})}async runFailureRecovery(e){return this.generator.getFailureRecoveryProposal(e,{disableCache:!0,orgId:this.orgId,abortSignal:this.executeAbortController.signal,loggerTags:Ze(this.logger)})}};var PA=4;async function _g({socket:n,logger:e,analytics:t,storage:r,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:s,devicePixelRatio:a,generatorFactory:l,browserbase:c,authorization:d}){let p=n.id,u=n.handshake.query.testId;if(!u)throw new Error("Socket connection request is missing testId");let m=await r.getOrgId({type:"e2e",testId:u});e=e.child({testId:u,orgId:m,sessionId:p});let h=await l(m,e),{testMetadata:f,baseUrl:g,envName:y,localBrowserConfigFromEnv:v,environmentVariables:S,localCodeEvalTools:E}=await Er({testId:u,orgId:m,logger:e,storage:r,authorization:d});if(G.getSession(p))return e.info("Associating connection with existing session (likely reconnect)"),{type:"e2e",sessionId:p,orgId:m,testId:u};let C=n.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:C,event:"connect",args:n.handshake.query},"Websocket event (connect)"),C&&G.getCurrentConnectionsByIp(C)>=PA)throw e.error({clientIp:C,sessions:G.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 retry or contact Momentic support if you believe this is in error.");G.reserveCapacityByIp(C);try{await LA({socket:n,baseUrl:g,envName:y,testMetadata:f,orgId:m,sessionId:p,logger:e,analytics:t,environmentVariables:S,clientIp:C,devicePixelRatio:a,storage:r,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:s,localCodeEvalTools:E,generator:h,browserbase:c,localBrowserConfigFromEnv:v})}catch(P){throw e.warn({err:P},"Error setting up socket session, possibly due to client closing the connection"),G.releaseCapacityByIp(C),P}return{type:"e2e",sessionId:p,testId:u,orgId:m}}async function LA({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:f,localBrowserConfigFromEnv:g,clientIp:y,authorization:v}){let S={};S.viewport=o.advanced?.viewport,r&&(S.deviceScaleFactor=r);let E=o.id,T=await u?.initializeServicesForTest(i,E),C=await oa({advanced:{...g,...o.advanced},orgId:i,baseUrl:e,envName:t,localTools:m,envVariables:f,logger:a,customHeaders:void 0});a=a.child({orgId:i,sessionId:s,testId:E});let P=await so.init(i),k=await en.init({baseUrl:e,userBrowserSettings:C,enricher:v?new Sr({baseUrl:v.baseUrl,apiKey:v.apiKey,logger:a}):new ua(a),timeout:C.pageLoadTimeoutMs,storage:c,featureFlagStore:P,mockedServices:T,logger:a,contextArgs:S,onTabsChange:(O,I)=>{n.emit("tabs",{tabs:O,activeTab:I})}});await k.navigate({url:e,initialNavigation:!0});let N=new mo({browser:k,generator:h,logger:a,analytics:l,flagStore:P,orgId:i,scratchPadId:void 0,storage:c,localCodeEvalTools:m,uploadedFileStorage:d,visualDiffScreenshotStorage:p}),J=Dh(n,s,a),V=async()=>{J.timers.forEach(O=>clearInterval(O))},de=new vt({baseUrl:e,currentUrl:N.browser.url(),variablesFromEnvironment:f,envName:t});if(!n.connected)throw await k.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");n.emit("session",{url:e,userAgent:en.USER_AGENT,viewport:N.browser.getViewport(),sessionId:s}),G.registerSession({controller:N,context:de,sessionId:s,cleanup:V,clientIp:y})}async function Er({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 Dn({httpClient:new Et(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 Pt({orgId:e,s:u.defaultValue,context:vt.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 id={currentlyExecutingRequests:{}},_A=n=>async(e,t)=>{let r,{testId:o,orgId:i}=n.metadata,s=await Er({testId:o,orgId:i,logger:n.logger,storage:n.storage,authorization:n.authorization}),a=`${o}|${s.baseUrl}`;try{let l=id.currentlyExecutingRequests[a]??0;id.currentlyExecutingRequests[a]=l+1,r=await NA({...n,...e,...s,done:t})}finally{n.logger.info({result:r,sessionId:n.metadata.sessionId},"Test execution complete"),id.currentlyExecutingRequests[a]--}},NA=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:f})=>{let{testId:g,sessionId:y,orgId:v}=c,S=y,E=G.getSession(y);if(!E)throw new Error("No active session found");let{controller:T,context:C}=E;T.setOpen(),d=d.child({testId:g,orgId:v,baseUrl:t,sessionId:y,runId:S}),d.info({steps:e.map(L=>`${L.type}${"command"in L?` - ${L.command.type}`:""}`),toStepId:i,fromStepId:s,reInitialize:o,envName:u,baseUrl:t,context:C,flags:T.flagStore.getAllFlags()},"Socket execution parameters");let P=m??{},k=async()=>{o&&(await T.browser.reset({newUrl:t}),C.reset({baseUrl:t,currentUrl:T.browser.url(),variablesFromEnvironment:P,envName:u}))},N=async()=>{try{await a.resolveStepCacheEntries({schemaVersion:r.schemaVersion,organizationId:v,testId:g,steps:e,logger:d})}catch(L){d.error({err:L},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Mn({promise:Promise.all([k(),N()]),signal:T.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),T.setOpen()}catch(L){if(n.emit("finished"),L.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${L}`)}let J=kA(e),V={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},de={orgId:v,runId:S,testMetadata:r,steps:e,fromStepId:s,toStepId:i},O={controller:T,context:C,storage:a,debugDataStorage:l,codeEvalTools:h,billingReporter:new Os,logger:d,analytics:p},te=await ra({fixtures:O,options:V,callbacks:{test:{onTestComplete:async()=>{n.emit("finished")},onSaveScreenshot:MA,onTestSuccess:async L=>{let fe=L.steps,se=OA(J,fe);if(Object.keys(se).length>0){d.debug({changes:se},"Updating steps post-run success");let{cachesToSave:Ae}=await It({stepLists:{steps:fe},cacheCreationParams:{testId:g,orgId:v}});try{await a.saveStepCacheEntries(Ae,r.id,d)}catch(Q){d.warn({err:Q},"Failed to save step cache entries after execution success")}}else d.debug("No changes detected in steps post-run success")}},step:{onStarted:L=>n.emit("started",{stepId:L}),onSuccess:L=>{n.emit("success",L)},onFailure:L=>{n.emit("failure",L)},onCancelled:L=>{n.emit("cancelled",L)},onCommandGenerated:L=>{n.emit("commandGenerated",L)},onCommandExecuted:L=>{n.emit("commandExecuted",L)},onDynamicAIActionStatusUpdateEvent:L=>{n.emit("dynamicCommandStatusUpdate",L)},onDynamicAIActionEvaluatingEvent:L=>{n.emit("dynamicCommandEvaluating",L)},onDynamicCommandGenerated:L=>{n.emit("dynamicCommandGenerated",L)},onDynamicCommandExecuted:L=>{n.emit("dynamicCommandExecuted",L)}}},inputs:de});return f?.(te),te.status},MA=async n=>n.toString("base64");var Ng={event:"execute",createHandler:_A};var DA=({metadata:n,logger:e,storage:t})=>{let{sessionId:r}=n;return async(o,i)=>{let{command:s,testMetadata:a,returnScreenshot:l}=o,c=Rs(s,o.description);e.info({params:o},`Locate handler called - ${c}`);let d=G.getSession(r);if(!d)throw new Error("No active session found");let{controller:p,context:u}=d;p.setOpen();let m=Wr.parse(a.advanced??{}),h={},f;if(c){if("useSelector"in s&&s.useSelector)try{let g=await p.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);f=g.resolution.locator,h={target:g.target,thoughts:g.thoughts}}catch(g){e.warn({err:g},"Failed resolving target with selector"),i({err:`Failed locating element: ${g.message}`,decisions:g instanceof Kr?g.decisions:void 0});return}else try{let g=await p.locateElement({description:c,disableCache:m.disableAICaching,iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,skipWait:!0,testContext:u});h={target:g.target,thoughts:g.thoughts},f=g.resolution.locator}catch(g){(async()=>{try{let y=await p.browser.getCondensedHtml({skipWait:!0});e.warn({err:g,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: ${g.message}`});return}if(s.type==="SELECT_OPTION"&&f)try{h.options=await p.browser.getSelectOptions(f)}catch(g){e.warn({err:g},"Failed getting select options"),i({err:`Failed getting select options: ${g.message}`});return}e.info({result:h},"Locate handler result")}if(l)try{let{buffer:g,width:y,height:v}=await p.screenshotWithDimensions({clearHighlights:!0,locator:f,hideCaret:!0}),S=await t.uploadScreenshot(g);h.screenshot={data:S,width:y,height:v}}catch(g){e.error({err:g},"Error capturing screenshot during locate"),i({err:`Error taking screenshot: ${g.message}`});return}if(i({result:h}),f)try{await Promise.all([p.browser.scrollIntoView(f),p.browser.highlightTarget(f)])}catch(g){e.warn({err:g},"Error highlighting element, continuing...")}}},Mg={event:"locate",createHandler:DA};var FA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async({percentX:r,percentY:o},i)=>{let s=G.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})}}},Dg={event:"cloudClick",createHandler:FA};var UA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=G.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}}},Fg={event:"recordTargetClick",createHandler:UA};var zA=({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=G.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")}}}},Ug={event:"cloudMouseMove",createHandler:zA};var BA=({metadata:n})=>{let{sessionId:e}=n;return async({percentDeltaX:t,percentDeltaY:r})=>{let o=G.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()})}},zg={event:"cloudScroll",createHandler:BA};var jA=({metadata:n,generatorFactory:e,socket:t,logger:r})=>{let{sessionId:o,orgId:i,testId:s}=n;return async({stepId:a})=>{let l=G.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}},Bg={event:"cloudStartRecording",createHandler:jA};var $A=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{let r=G.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}},jg={event:"cloudStopRecording",createHandler:$A};var HA=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],WA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async({key:r})=>{let o=G.getSession(t);if(!o)throw new Error("No active session found");if(HA.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}}},$g={event:"cloudType",createHandler:WA};var GA=({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 Er({testId:a,orgId:c,logger:t,storage:r,authorization:o}),p=G.getSession(l);if(!p){n.emit("error",{message:"No session to refresh"});return}let{controller:u}=p;await u.browser.refresh();let m=u.browser.getViewport();t.info({baseUrl:d,viewport:m},`Session refreshed for test ${a} at ${d}`),s()},Hg={event:"refresh",createHandler:GA};var VA=({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 Er({testId:i,orgId:a,logger:t,storage:r,authorization:o}),p=G.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 f=u.browser.getViewport(),g=en.USER_AGENT;t.info({baseUrl:l,viewport:f},`Session reset for test ${i} at ${h}`),n.emit("session",{url:h,userAgent:g,viewport:f,sessionId:s})},Wg={event:"reset",createHandler:VA};var qA=({metadata:n})=>{let{sessionId:e}=n;return async({url:t})=>{let r=G.getSession(e);if(!r)throw new Error("No active session found");await r.controller.browser.switchToPage({type:"SUBSTRING",substring:t})}},Gg={event:"switchTab",createHandler:qA};async function Vg(n){let{socket:e}=n;return e.handshake.query.type==="api-test"?Yh(n):_g(n)}var qg=[ef,Ng,Mg,Wg,Hg,Xh,Gg,Fg,Bg,jg,Ug,Dg,$g,zg,Jh,Fh,Qh,Zh];var Kg=n=>{let{logger:e}=n,t=new KA(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 Vg({...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}qg.forEach(i=>YA(i,{socket:r,metadata:o,...n,logger:e}))}),t},YA=(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 JI}from"express";import Ht from"fs";import gn from"path";import Cr from"yaml";import sd from"fs";import JA from"path";import{v4 as XA}from"uuid";import ad from"yaml";function ld(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:xe.MODULE,...ym.parse(o),steps:n.steps},s=ad.stringify(i);sd.writeFileSync(r,s,"utf-8")}async function Yg({name:n,description:e,enabled:t,steps:r,folder:o}){let i=Pe(n),s=JA.join(o,`${i}.module.yaml`),a=XA(),{stepsToSave:l}=await It({stepLists:{steps:r}}),c={fileType:xe.MODULE,schemaVersion:ut,moduleId:a,name:n,description:e,enabled:t,steps:l.steps},d=ad.stringify(c);return sd.writeFileSync(s,d,"utf-8"),{moduleId:a,name:n,description:e,enabled:t,steps:r}}function ha(n,e){let t=sd.readFileSync(n,"utf-8"),r=ad.parse(t);try{return dc.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 cd(n,e,t,r){let o=ha(n.fullFilePath,t),{resolvedSteps:i}=await Vs({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 ha(l,t)}}}),s={...o,steps:i};return r&&(r[n.id]=s),s}async function fa(n,e){let t={};return await Promise.all(Object.values(n.modules).map(async r=>{await cd(r,n,e,t)})),Array.from(Object.values(t))}async function Jg({test:n,name:e,folder:t}){let r=await Nh(n);if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${Pe(e)}.${En.TEST}`,s=gn.join(t,i);return Ht.writeFileSync(s,r.test,"utf-8"),s}function dd(n,e,t){let r=gn.join(t.rootDir,n);if(!Ht.existsSync(r))throw new Error(`Test not found at path '${n}' in project '${t.rootDir}'`);let o=Ht.readFileSync(r,"utf-8"),i=Cr.parse(o),s={...i,...e},a=dn.parse(s),l={fileType:xe.TEST,...dn.parse(a),steps:i.steps},c=Cr.stringify(l);Ht.writeFileSync(r,c,"utf-8")}function Ci(n,e,t,r){let o=gn.join(r.rootDir,n);if(!Ht.existsSync(o))throw new Error(`Test not found at path '${n}' in project '${r.rootDir}'`);let i=Ht.readFileSync(o,"utf-8"),s=Cr.parse(i),a=dn.parse({...s,schemaVersion:t}),l={fileType:xe.TEST,...a,beforeSteps:e.beforeSteps??void 0,steps:e.steps,afterSteps:e.afterSteps??void 0},c=Cr.stringify(l);Ht.writeFileSync(o,c,"utf-8")}function pd(n,e,t=n){let r=n.split(gn.sep).pop()??"";if(ui.includes(r))return e.warn(`Skipping directory '${n}' because it is likely an artifact folder.`),[];let o=Ht.readdirSync(n),i=[];return o.forEach(s=>{let a=gn.join(n,s),l;try{l=Ht.statSync(a)}catch(c){e.warn({err:c},`Skipping path '${a}' because it could not be read.`);return}if(l.isDirectory())i=i.concat(pd(a,e,t));else if(s.endsWith(".yaml")){let c=Ht.readFileSync(a,"utf-8"),d=gn.relative(gn.resolve(t),gn.resolve(a));try{let p=Cr.parse(c),u=Bt.parse(p);i.push({id:u.id,name:u.name,fullPathSegments:a.split(gn.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 ga(n,e){let t=gn.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=Ht.readFileSync(t,"utf8"),r=r.replace(/\r\n|\r/g,`
2973
+ `),tokenLength:p}),a.forEach((f,g)=>{t.debug({chunk:f},`Chunk for page filtering (index ${g+1}/${a.length})`)}),{chunks:a}}var td=4e4,nd=8e4;async function Tr(n){let{serializedTree:e,logger:t,flagStore:r,softTokenLimit:o=td}=n;if(Ei(e)<o)return e;let s=ed({serializedTree:e,options:Ig,logger:t});try{return r.isBooleanFlagEnabled("rag_v2")?await U(SA({...n,chunks:s.chunks}),{milliseconds:15e3}):await U(wA(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,nd*uo)}}}async function SA({chunks:n,generator:e,description:t,type:r,logger:o,signal:i,orgId:s,tree:a,softTokenLimit:l=td,hardTokenLimit:c=nd}){let d=await e.rankChunksWithAi({chunks:n,description:t,type:r,softTokenLimit:l,hardTokenLimit:c},{abortSignal:i,orgId:s,logger:o,loggerTags:Ze(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=nd}=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:Ze(n.logger)});for(let c of l.keywords){let d=n.chunks.filter(h=>h.content.includes(c));if(!d.length||d.reduce((h,f)=>h+f.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 wA(n){let{description:e,generator:t,orgId:r,tree:o,logger:i,signal:s,softTokenLimit:a=td}=n,l=ed({serializedTree:o.serialize(),options:Rg,logger:i}),c=await t.rankChunksWithRag({description:e,chunks:l.chunks,tokenLimit:a},{abortSignal:s,orgId:r,logger:i,loggerTags:Ze(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 rd(n,e){if(!n.description)throw new A("ActionFailureError","Cannot locate element with empty description");return mn({action:()=>vA(n,e),frameUrl:n.iframeUrl,browser:e.browser,logger:e.logger})}async function vA(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 Pt({orgId:a,s:m,context:r,logger:e.logger,localTools:d,signal:e.abortSignal}));let{serializedTree:h,tree:f}=await Wn(c,{filterByViewport:o,abortSignal:u,skipWait:i,logger:l}),g,y=Date.now(),v;for(;!g&&Date.now()-y<3e3;){u.throwIfAborted();try{g=await c.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(J){v=J}}if(!g)throw new A("InternalWebAgentError",`Failed to take screenshot of page to locate element: ${v?.message}`);let S=h,E=!1;S=await Tr({type:"locator",description:m,serializedTree:h,flagStore:e.flagStore,tree:f,logger:l,generator:p,orgId:a}),S!==h&&(E=!0);let T=g.toString("base64"),C=await p.getElementLocation({browserState:S,goal:m,screenshot:T,feedback:void 0},{disableCache:t,orgId:a,abortSignal:u,loggerTags:Ze(l)});l.debug({usedRag:E,result:C},"Got locator result");let P=C.id>0;if(s?.details?.push({type:"AI_LOCATION",matched:P,pageState:S,ragUsed:E,thoughts:C.thoughts}),!P)throw new A("ActionFailureError",`Could not find any relevant element: ${C.thoughts}`);let k={id:C.id,inputDescription:m,targetSource:"AI",targetUpdateTime:new Date().toUTCString()},N=await c.resolveTarget(null,k);if(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:k,resolution:N}}var xA=15;async function od({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=TA(o),s=0,a=Date.now(),l,c,d;try{await mn({action:()=>t.clearHighlights(),frameUrl:n.iframeUrl,browser:t,logger:r})}catch(u){r.warn({err:u},"Failed to clear highlights before AI assertion, continuing...")}let p;for(;s<xA&&(!p||p-a<o);){e.abortSignal.throwIfAborted(),s!==0&&(r.info(`Waiting ${i}ms before retrying AI assertion`),await Z(i,e.abortSignal)),p=Date.now();try{let u=await mn({action:async()=>{let m=await Lg(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,Og({command:n,state:m,fixtures:e,useConsensus:!1,highlightElementsOnFailure:!1}))},frameUrl:n.iframeUrl,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 mn({action:async()=>Og({command:n,state:await Lg(t,r,e.abortSignal),fixtures:e,useConsensus:!0,highlightElementsOnFailure:!0}),frameUrl:n.iframeUrl,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 Lg(n,e,t){let[r,o]=await Promise.all([Wn(n,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),n.screenshot({retries:1,respectActiveFrame:!0})]);return{...r,screenshotBuff:o}}async function Og({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(),f=p;f=await Tr({type:"assertion",serializedTree:p,description:n.assertion,flagStore:t.flagStore,tree:u,generator:a,orgId:l,logger:s,signal:c}),f!==p&&(d.ragUsed=!0),d.pageState=f;let g={goal:n.assertion,url:h,browserState:f,screenshot:m.toString("base64"),contextChoice:n.contextChoice},v=await(n.contextChoice==="VISION_ONLY"?(S,E)=>a.getVisualAssertionResult(S,E):(S,E)=>a.getAssertionResult(S,E))(g,{useConsensus:r,disableCache:!!n.disableCache,logger:s,orgId:l,abortSignal:c,loggerTags:Ze(s)});if(s.debug({usedRag:d.ragUsed,result:v},"Got assertion attempt result"),(v.result||o)&&v.relevantElements&&(d.relevantElementsSerialized=v.relevantElements.map(S=>i.getSerializedFormFromA11yId(S)).filter(S=>!!S),await EA(v.relevantElements,i,s)),!v.result)throw new A("AssertionFailureError",v.thoughts);return{succeedImmediately:!1,thoughts:v.thoughts,urlAfterCommand:h,afterScreenshotOverride:m}}function TA(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 EA(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 U(e.highlight({id:o},i.signal),{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 CA=3e4;async function kg({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??CA/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(n.headers||{}).filter(([p,u])=>p&&u)),a;if(ro(n.url)&&(a=n.url),t&&oo(n.url,t)&&(a=new URL(n.url,t).toString()),!a)throw new A("ActionFailureError",`Invalid URL: ${n.url}`);let c=await U((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 mo=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([Wn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=await Tr({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:{...Ze(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([Wn(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 Tr({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:{...Ze(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 Wn(this.browser,e)}async locateElement(e){return rd(e,this.getControllerFixtures())}async locateElementWithSelector(e,t){return mn({action:async()=>{let r=await this.browser.resolveHardcodedCssSelector({root:void 0,selector:e,timeoutMs:2e3});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:r}},frameUrl:t,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 mn({action:()=>this.wrapElementTargetingCommandHelper(e),frameUrl:e.options.iframeUrl,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)&&!cl(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 along with non-description target");let f={id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},g=await this.browser.resolveTarget(e,f,{skipFetchTree:i.skipFetchTree,targetName:c,logger:m});return{result:await o({locator:g.locator}),elementInteractedDisplayString:g.displayString,newTarget:{cache:f}}}a&&(this.logger.debug("Cache explicitly disabled for this step"),u=!0,r=void 0),r?.inputDescription&&!Ou(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&&Yi(r);if(!r){let f=new Date;this.logger.debug({targetHealingInProgress:d},"Prompting AI for an updated element location"),u&&await Z(this.browser.smartWaitingTimeout,this.executeAbortController.signal),p--;let g=await rd({description:Rs(s,t.elementDescriptor),disableCache:a,iframeUrl:i.iframeUrl},this.getControllerFixtures(e)),y=i.disableGlobalLocatorRedirect?{locator:g.resolution.locator}:await this.attemptLocatorRedirect(g.resolution.locator,m),v=await o(y),S;if(d){this.analytics.track({type:"execution:step_heal",heal_type:"AI",step_type:"PRESET_ACTION",command_type:s.type,duration_ms:Date.now()-f.getTime()}),g.target={...g.target,targetSource:"AI_HEALED",targetUpdateTime:new Date().toUTCString()};let E=g.resolution.pageState;if(E)try{S=await this.getReverseMappedTarget(E,g.target.id,!0)}catch(T){m.warn({err:T},"Failed to reverse map element auto-healed by AI, continuing...")}}return{result:v,elementInteractedDisplayString:g.resolution.displayString,newTarget:{cache:g.target,thoughts:g.thoughts,description:S}}}try{let f=new Date,g=await this.browser.resolveTarget(e,r,{targetName:c,logger:m}),y=i.disableGlobalLocatorRedirect?{locator:g.locator}:await this.attemptLocatorRedirect(g.locator,m),v=await o(y);if(h){let S=g.decisions.filter(E=>E.matched);if(S.length!==1)m.warn({decisions:g.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let E=S[0].type;this.analytics.track({type:"execution:step_heal",heal_type:E,step_type:"PRESET_ACTION",command_type:s.type,duration_ms:Date.now()-f.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:g.displayString,newTarget:{cache:r}}}catch(f){if(this.throwIfClosed(),f instanceof A)throw f;if(p>0&&t)return m.debug({err:f,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",f.message,{errOptions:{cause:f}})}}async attemptLocatorRedirect(e,t){return this.flagStore.isBooleanFlagEnabled("global_locator_redirect")?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return bi(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(Un(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))Zc(e,r,o)}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>zc(e),getFeatureFlagStore:()=>this.flagStore}}async resolveCommandTemplateStrings(e,t){return no({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()?od({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 od({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:Ze(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 f=h.message;throw f.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."):f.includes("AIProviderError")&&f.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(!ro(t.url)&&!oo(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&&ln(t.target))await this.browser.hoverUsingVisualCoordinates(t.target.pixels);else if(t.target&&t.target.elementDescriptor.trim()){let{newTarget:h,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:t.target,cache:t.cache?.target,action:g=>this.browser.hover(g),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});u=f,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 Z(a,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"CLICK":{if(ln(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:f,result:g}=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});f.cache&&(t.cache={target:f.cache});let y={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,newTargets:[f],data:g};return Ys(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(ln(t.fromTarget)&&ln(t.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(t.fromTarget.pixels,t.toTarget.pixels,{hoverSeconds:t.hoverSeconds});break}if(ln(t.fromTarget)||ln(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,f)=>this.browser.dragAndDrop(h.locator,f.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);if(isNaN(u)||isNaN(m))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);if(t.target&&ln(t.target)){await this.browser.mouseDragUsingVisualCoordinates(u,m,t.steps,t.target.pixels,{force:t.force});break}let h,f,g=[];if(t.target?.elementDescriptor){let{newTarget:y,elementInteractedDisplayString:v,result:S}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:t.target,cache:t.cache?.target,action:async E=>E.locator,options:{useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableCache:o}});h=S,f=v,g.push(y)}return await this.browser.mouseDrag(u,m,t.steps,h,{force:t.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,newTargets:g}}case"SELECT_OPTION":{if(!Ln(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:f}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:{type:"description",elementDescriptor:u},cache:t.cache?.target,action:g=>this.browser.selectOption(g,m,t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,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&&ln(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=[],f=RA(t.target);if(f){let{elementInteractedDisplayString:y,newTarget:v}=await this.wrapElementTargetingCommand({ctx:e,command:t,target:f,cache:t.cache?.target,action:S=>this.browser.typeIntoTarget(t.value,S,{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 g={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:m,newTargets:h};return Ys(u,g.urlAfterCommand)&&(g.succeedImmediately=!0,g.succeedImmediatelyReason="URL changed"),g}case"HOVER":{if(ln(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(!Ln(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&&!Ln(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});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Ys(c,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;case"REQUEST":{let u=new IA,m=AA(fetch,u),h;try{h=new URL(t.url).hostname}catch{}return{data:{...await Js({command:t,baseUrl:this.browser.baseUrl,logger:this.logger,fetchImplementation:m}),cookies:Ns(u,h)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await kg({command:t,baseUrl:this.browser.baseUrl,logger:this.logger}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return lf({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 Qf({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=_s.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 sf({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 mn({frameUrl:t.iframeUrl,browser:this.browser,logger:this.logger,action:async()=>Xs({assertion:t.assertion,browser:this.browser,logger:this.logger,timeout:t.timeout,signal:this.executeAbortController.signal})});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:Ze(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode(e){this.recordAbortController=new AbortController;let t=new ma({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:Ze(this.logger)})}async runFailureRecovery(e){return this.generator.getFailureRecoveryProposal(e,{disableCache:!0,orgId:this.orgId,abortSignal:this.executeAbortController.signal,loggerTags:Ze(this.logger)})}};var PA=4;async function _g({socket:n,logger:e,analytics:t,storage:r,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:s,devicePixelRatio:a,generatorFactory:l,browserbase:c,authorization:d}){let p=n.id,u=n.handshake.query.testId;if(!u)throw new Error("Socket connection request is missing testId");let m=await r.getOrgId({type:"e2e",testId:u});e=e.child({testId:u,orgId:m,sessionId:p});let h=await l(m,e),{testMetadata:f,baseUrl:g,envName:y,localBrowserConfigFromEnv:v,environmentVariables:S,localCodeEvalTools:E}=await Er({testId:u,orgId:m,logger:e,storage:r,authorization:d});if(G.getSession(p))return e.info("Associating connection with existing session (likely reconnect)"),{type:"e2e",sessionId:p,orgId:m,testId:u};let C=n.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:C,event:"connect",args:n.handshake.query},"Websocket event (connect)"),C&&G.getCurrentConnectionsByIp(C)>=PA)throw e.error({clientIp:C,sessions:G.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 retry or contact Momentic support if you believe this is in error.");G.reserveCapacityByIp(C);try{await LA({socket:n,baseUrl:g,envName:y,testMetadata:f,orgId:m,sessionId:p,logger:e,analytics:t,environmentVariables:S,clientIp:C,devicePixelRatio:a,storage:r,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:s,localCodeEvalTools:E,generator:h,browserbase:c,localBrowserConfigFromEnv:v})}catch(P){throw e.warn({err:P},"Error setting up socket session, possibly due to client closing the connection"),G.releaseCapacityByIp(C),P}return{type:"e2e",sessionId:p,testId:u,orgId:m}}async function LA({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:f,localBrowserConfigFromEnv:g,clientIp:y,authorization:v}){let S={};S.viewport=o.advanced?.viewport,r&&(S.deviceScaleFactor=r);let E=o.id,T=await u?.initializeServicesForTest(i,E),C=await oa({advanced:{...g,...o.advanced},orgId:i,baseUrl:e,envName:t,localTools:m,envVariables:f,logger:a,customHeaders:void 0});a=a.child({orgId:i,sessionId:s,testId:E});let P=await so.init(i),k=await en.init({baseUrl:e,userBrowserSettings:C,enricher:v?new Sr({baseUrl:v.baseUrl,apiKey:v.apiKey,logger:a}):new ua(a),timeout:C.pageLoadTimeoutMs,storage:c,featureFlagStore:P,mockedServices:T,logger:a,contextArgs:S,onTabsChange:(O,I)=>{n.emit("tabs",{tabs:O,activeTab:I})}});await k.navigate({url:e,initialNavigation:!0});let N=new mo({browser:k,generator:h,logger:a,analytics:l,flagStore:P,orgId:i,scratchPadId:void 0,storage:c,localCodeEvalTools:m,uploadedFileStorage:d,visualDiffScreenshotStorage:p}),J=Dh(n,s,a),V=async()=>{J.timers.forEach(O=>clearInterval(O))},de=new vt({baseUrl:e,currentUrl:N.browser.url(),variablesFromEnvironment:f,envName:t});if(!n.connected)throw await k.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");n.emit("session",{url:e,userAgent:en.USER_AGENT,viewport:N.browser.getViewport(),sessionId:s}),G.registerSession({controller:N,context:de,sessionId:s,cleanup:V,clientIp:y})}async function Er({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 Dn({httpClient:new Et(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 Pt({orgId:e,s:u.defaultValue,context:vt.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 id={currentlyExecutingRequests:{}},_A=n=>async(e,t)=>{let r,{testId:o,orgId:i}=n.metadata,s=await Er({testId:o,orgId:i,logger:n.logger,storage:n.storage,authorization:n.authorization}),a=`${o}|${s.baseUrl}`;try{let l=id.currentlyExecutingRequests[a]??0;id.currentlyExecutingRequests[a]=l+1,r=await NA({...n,...e,...s,done:t})}finally{n.logger.info({result:r,sessionId:n.metadata.sessionId},"Test execution complete"),id.currentlyExecutingRequests[a]--}},NA=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:f})=>{let{testId:g,sessionId:y,orgId:v}=c,S=y,E=G.getSession(y);if(!E)throw new Error("No active session found");let{controller:T,context:C}=E;T.setOpen(),d=d.child({testId:g,orgId:v,baseUrl:t,sessionId:y,runId:S}),d.info({steps:e.map(L=>`${L.type}${"command"in L?` - ${L.command.type}`:""}`),toStepId:i,fromStepId:s,reInitialize:o,envName:u,baseUrl:t,context:C,flags:T.flagStore.getAllFlags()},"Socket execution parameters");let P=m??{},k=async()=>{o&&(await T.browser.reset({newUrl:t}),C.reset({baseUrl:t,currentUrl:T.browser.url(),variablesFromEnvironment:P,envName:u}))},N=async()=>{try{await a.resolveStepCacheEntries({schemaVersion:r.schemaVersion,organizationId:v,testId:g,steps:e,logger:d})}catch(L){d.error({err:L},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Mn({promise:Promise.all([k(),N()]),signal:T.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),T.setOpen()}catch(L){if(n.emit("finished"),L.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${L}`)}let J=kA(e),V={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},de={orgId:v,runId:S,testMetadata:r,steps:e,fromStepId:s,toStepId:i},O={controller:T,context:C,storage:a,debugDataStorage:l,codeEvalTools:h,billingReporter:new Os,logger:d,analytics:p},te=await ra({fixtures:O,options:V,callbacks:{test:{onTestComplete:async()=>{n.emit("finished")},onSaveScreenshot:MA,onTestSuccess:async L=>{let fe=L.steps,se=OA(J,fe);if(Object.keys(se).length>0){d.debug({changes:se},"Updating steps post-run success");let{cachesToSave:Ce}=await It({stepLists:{steps:fe},cacheCreationParams:{testId:g,orgId:v}});try{await a.saveStepCacheEntries(Ce,r.id,d)}catch(Q){d.warn({err:Q},"Failed to save step cache entries after execution success")}}else d.debug("No changes detected in steps post-run success")}},step:{onStarted:L=>n.emit("started",{stepId:L}),onSuccess:L=>{n.emit("success",L)},onFailure:L=>{n.emit("failure",L)},onCancelled:L=>{n.emit("cancelled",L)},onCommandGenerated:L=>{n.emit("commandGenerated",L)},onCommandExecuted:L=>{n.emit("commandExecuted",L)},onDynamicAIActionStatusUpdateEvent:L=>{n.emit("dynamicCommandStatusUpdate",L)},onDynamicAIActionEvaluatingEvent:L=>{n.emit("dynamicCommandEvaluating",L)},onDynamicCommandGenerated:L=>{n.emit("dynamicCommandGenerated",L)},onDynamicCommandExecuted:L=>{n.emit("dynamicCommandExecuted",L)}}},inputs:de});return f?.(te),te.status},MA=async n=>n.toString("base64");var Ng={event:"execute",createHandler:_A};var DA=({metadata:n,logger:e,storage:t})=>{let{sessionId:r}=n;return async(o,i)=>{let{command:s,testMetadata:a,returnScreenshot:l}=o,c=Rs(s,o.description);e.info({params:o},`Locate handler called - ${c}`);let d=G.getSession(r);if(!d)throw new Error("No active session found");let{controller:p,context:u}=d;p.setOpen();let m=Wr.parse(a.advanced??{}),h={},f;if(c){if("useSelector"in s&&s.useSelector)try{let g=await p.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);f=g.resolution.locator,h={target:g.target,thoughts:g.thoughts}}catch(g){e.warn({err:g},"Failed resolving target with selector"),i({err:`Failed locating element: ${g.message}`,decisions:g instanceof Kr?g.decisions:void 0});return}else try{let g=await p.locateElement({description:c,disableCache:m.disableAICaching,iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,skipWait:!0,testContext:u});h={target:g.target,thoughts:g.thoughts},f=g.resolution.locator}catch(g){(async()=>{try{let y=await p.browser.getCondensedHtml({skipWait:!0});e.warn({err:g,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: ${g.message}`});return}if(s.type==="SELECT_OPTION"&&f)try{h.options=await p.browser.getSelectOptions(f)}catch(g){e.warn({err:g},"Failed getting select options"),i({err:`Failed getting select options: ${g.message}`});return}e.info({result:h},"Locate handler result")}if(l)try{let{buffer:g,width:y,height:v}=await p.screenshotWithDimensions({clearHighlights:!0,locator:f,hideCaret:!0}),S=await t.uploadScreenshot(g);h.screenshot={data:S,width:y,height:v}}catch(g){e.error({err:g},"Error capturing screenshot during locate"),i({err:`Error taking screenshot: ${g.message}`});return}if(i({result:h}),f)try{await Promise.all([p.browser.scrollIntoView(f),p.browser.highlightTarget(f)])}catch(g){e.warn({err:g},"Error highlighting element, continuing...")}}},Mg={event:"locate",createHandler:DA};var FA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async({percentX:r,percentY:o},i)=>{let s=G.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})}}},Dg={event:"cloudClick",createHandler:FA};var UA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=G.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}}},Fg={event:"recordTargetClick",createHandler:UA};var zA=({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=G.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")}}}},Ug={event:"cloudMouseMove",createHandler:zA};var BA=({metadata:n})=>{let{sessionId:e}=n;return async({percentDeltaX:t,percentDeltaY:r})=>{let o=G.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()})}},zg={event:"cloudScroll",createHandler:BA};var jA=({metadata:n,generatorFactory:e,socket:t,logger:r})=>{let{sessionId:o,orgId:i,testId:s}=n;return async({stepId:a})=>{let l=G.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}},Bg={event:"cloudStartRecording",createHandler:jA};var $A=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{let r=G.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}},jg={event:"cloudStopRecording",createHandler:$A};var HA=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],WA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async({key:r})=>{let o=G.getSession(t);if(!o)throw new Error("No active session found");if(HA.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}}},$g={event:"cloudType",createHandler:WA};var GA=({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 Er({testId:a,orgId:c,logger:t,storage:r,authorization:o}),p=G.getSession(l);if(!p){n.emit("error",{message:"No session to refresh"});return}let{controller:u}=p;await u.browser.refresh();let m=u.browser.getViewport();t.info({baseUrl:d,viewport:m},`Session refreshed for test ${a} at ${d}`),s()},Hg={event:"refresh",createHandler:GA};var VA=({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 Er({testId:i,orgId:a,logger:t,storage:r,authorization:o}),p=G.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 f=u.browser.getViewport(),g=en.USER_AGENT;t.info({baseUrl:l,viewport:f},`Session reset for test ${i} at ${h}`),n.emit("session",{url:h,userAgent:g,viewport:f,sessionId:s})},Wg={event:"reset",createHandler:VA};var qA=({metadata:n})=>{let{sessionId:e}=n;return async({url:t})=>{let r=G.getSession(e);if(!r)throw new Error("No active session found");await r.controller.browser.switchToPage({type:"SUBSTRING",substring:t})}},Gg={event:"switchTab",createHandler:qA};async function Vg(n){let{socket:e}=n;return e.handshake.query.type==="api-test"?Yh(n):_g(n)}var qg=[ef,Ng,Mg,Wg,Hg,Xh,Gg,Fg,Bg,jg,Ug,Dg,$g,zg,Jh,Fh,Qh,Zh];var Kg=n=>{let{logger:e}=n,t=new KA(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 Vg({...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}qg.forEach(i=>YA(i,{socket:r,metadata:o,...n,logger:e}))}),t},YA=(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 JI}from"express";import Ht from"fs";import gn from"path";import Cr from"yaml";import sd from"fs";import JA from"path";import{v4 as XA}from"uuid";import ad from"yaml";function ld(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:xe.MODULE,...ym.parse(o),steps:n.steps},s=ad.stringify(i);sd.writeFileSync(r,s,"utf-8")}async function Yg({name:n,description:e,enabled:t,steps:r,folder:o}){let i=Ie(n),s=JA.join(o,`${i}.module.yaml`),a=XA(),{stepsToSave:l}=await It({stepLists:{steps:r}}),c={fileType:xe.MODULE,schemaVersion:ut,moduleId:a,name:n,description:e,enabled:t,steps:l.steps},d=ad.stringify(c);return sd.writeFileSync(s,d,"utf-8"),{moduleId:a,name:n,description:e,enabled:t,steps:r}}function ha(n,e){let t=sd.readFileSync(n,"utf-8"),r=ad.parse(t);try{return dc.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 cd(n,e,t,r){let o=ha(n.fullFilePath,t),{resolvedSteps:i}=await Vs({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 ha(l,t)}}}),s={...o,steps:i};return r&&(r[n.id]=s),s}async function fa(n,e){let t={};return await Promise.all(Object.values(n.modules).map(async r=>{await cd(r,n,e,t)})),Array.from(Object.values(t))}async function Jg({test:n,name:e,folder:t}){let r=await Nh(n);if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${Ie(e)}.${En.TEST}`,s=gn.join(t,i);return Ht.writeFileSync(s,r.test,"utf-8"),s}function dd(n,e,t){let r=gn.join(t.rootDir,n);if(!Ht.existsSync(r))throw new Error(`Test not found at path '${n}' in project '${t.rootDir}'`);let o=Ht.readFileSync(r,"utf-8"),i=Cr.parse(o),s={...i,...e},a=dn.parse(s),l={fileType:xe.TEST,...dn.parse(a),steps:i.steps},c=Cr.stringify(l);Ht.writeFileSync(r,c,"utf-8")}function Ci(n,e,t,r){let o=gn.join(r.rootDir,n);if(!Ht.existsSync(o))throw new Error(`Test not found at path '${n}' in project '${r.rootDir}'`);let i=Ht.readFileSync(o,"utf-8"),s=Cr.parse(i),a=dn.parse({...s,schemaVersion:t}),l={fileType:xe.TEST,...a,beforeSteps:e.beforeSteps??void 0,steps:e.steps,afterSteps:e.afterSteps??void 0},c=Cr.stringify(l);Ht.writeFileSync(o,c,"utf-8")}function pd(n,e,t=n){let r=n.split(gn.sep).pop()??"";if(ui.includes(r))return e.warn(`Skipping directory '${n}' because it is likely an artifact folder.`),[];let o=Ht.readdirSync(n),i=[];return o.forEach(s=>{let a=gn.join(n,s),l;try{l=Ht.statSync(a)}catch(c){e.warn({err:c},`Skipping path '${a}' because it could not be read.`);return}if(l.isDirectory())i=i.concat(pd(a,e,t));else if(s.endsWith(".yaml")){let c=Ht.readFileSync(a,"utf-8"),d=gn.relative(gn.resolve(t),gn.resolve(a));try{let p=Cr.parse(c),u=Bt.parse(p);i.push({id:u.id,name:u.name,fullPathSegments:a.split(gn.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 ga(n,e){let t=gn.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=Ht.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=Cr.parse(r)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return Bt.parse(o)}function ud(n,e,t){let r=t.project.rootDir,o;try{o=Ht.readFileSync(n,"utf-8")}catch(s){throw e.error({err:s,projectRoot:r},s.message),new Error(s.message)}let i=Cr.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${n} is missing steps`);return i}async function ya(n,e,t){let r=ud(n,e,t),o;try{o=dn.parse(r)}catch(s){throw new Error(`Test ${n} is missing metadata or has invalid metadata: ${s}`)}let{resolvedTest:i}=await Oh({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 ha(l,a)}}});return i}import ZA from"@dotenvx/dotenvx";import QA from"fs";import Xg from"path";function Qg(n,e){return(n.config.environments??[]).map(t=>Ai(t.name,n,e))}function Zg(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 Ai(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]:Zg(r.baseUrl)};if(r.envVariables){let s={};for(let[a,l]of Object.entries(r.envVariables))if(typeof l=="string"){let c=Zg(l);c&&(s[a]=c)}else{let c=l.fromFile,d;try{d=QA.readFileSync(Xg.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&&t.debug(s,"Set environment variables with interpolation from project configuration"),Object.assign(o,s)}if(r.envFile){let s={},a=ZA.config({path:Xg.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 LI,readFileSync as OI,readdirSync as kI,writeFileSync as _I}from"fs";var wy=Db(uy(),1);var Ii=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var aR={"[: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]},Pi=n=>n.replace(/[[\]\\-]/g,"\\$&"),lR=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),my=n=>n.join(""),hy=(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 f=n.charAt(i);if((f==="!"||f==="^")&&i===t+1){c=!0,i++;continue}if(f==="]"&&s&&!l){d=i+1;break}if(s=!0,f==="\\"&&!l){l=!0,i++;continue}if(f==="["&&!l){for(let[g,[y,v,S]]of Object.entries(aR))if(n.startsWith(g,i)){if(p)return["$.",!1,n.length-t,!0];i+=g.length,S?o.push(y):r.push(y),a=a||v;continue e}}if(l=!1,p){f>p?r.push(Pi(p)+"-"+Pi(f)):f===p&&r.push(Pi(f)),p="",i++;continue}if(n.startsWith("-]",i+1)){r.push(Pi(f+"-")),i+=2;continue}if(n.startsWith("-",i+1)){p=f,i+=2;continue}r.push(Pi(f)),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 f=r[0].length===2?r[0].slice(-1):r[0];return[lR(f),!1,d-t,!1]}let u="["+(c?"^":"")+my(r)+"]",m="["+(c?"":"^")+my(o)+"]";return[r.length&&o.length?"("+u+"|"+m+")":r.length?u:m,a,d-t,!0]};var tn=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var cR=new Set(["!","?","+","*","@"]),fy=n=>cR.has(n),dR="(?!(?:^|/)\\.\\.?(?:$|/))",Sa="(?!\\.)",pR=new Set(["[","."]),uR=new Set(["..","."]),mR=new Set("().*{}+?[]^$\\!"),hR=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),fd="[^/]",gy=fd+"*?",yy=fd+"+?",ho=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("")}#g(){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 f=e.charAt(m++);if(i||f==="\\"){i=!i,h+=f;continue}if(s){m===a+1?(f==="^"||f==="!")&&(l=!0):f==="]"&&!(m===a+2&&l)&&(s=!1),h+=f;continue}else if(f==="["){s=!0,a=m,l=!1,h+=f;continue}if(!o.noext&&fy(f)&&e.charAt(m)==="("){t.push(h),h="";let g=new n(f,t);m=n.#y(e,g,m,o),t.push(g);continue}h+=f}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(fy(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.#g(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#r.map(m=>{let[h,f,g,y]=typeof m=="string"?n.#u(m,this.#t,l):m.toRegExpSource(e);return this.#t=this.#t||g,this.#i=this.#i||y,h}).join(""),d="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&uR.has(this.#r[0]))){let h=pR,f=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),g=!t&&!e&&h.has(c.charAt(0));d=f?dR:g?Sa:""}let p="";return this.isEnd()&&this.#e.#p&&this.#s?.type==="!"&&(p="(?:$|\\/)"),[d+c+p,tn(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,tn(this.toString()),!1,!1]}let s=!r||e||t||!Sa?"":this.#m(!0);s===i&&(s=""),s&&(i=`(?:${i})(?:${s})*?`);let a="";if(this.type==="!"&&this.#o)a=(this.isStart()&&!t?Sa:"")+yy;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?Sa:"")+gy+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=o+i+l}return[a,tn(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+=(mR.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?i+="\\\\":o=!0;continue}if(l==="["){let[c,d,p,u]=hy(e,a);if(p){i+=c,s=s||d,a+=p-1,t=t||u;continue}}if(l==="*"){r&&e==="*"?i+=yy:i+=gy,t=!0;continue}if(l==="?"){i+=fd,t=!0;continue}i+=hR(l)}return[i,tn(e),!!t,s]}};var fo=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var ht=(n,e,t={})=>(Ii(e),!t.nocomment&&e.charAt(0)==="#"?!1:new Lt(e,t).match(n)),fR=/^\*+([^+@!?\*\[\(]*)$/,gR=n=>e=>!e.startsWith(".")&&e.endsWith(n),yR=n=>e=>e.endsWith(n),SR=n=>(n=n.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(n)),bR=n=>(n=n.toLowerCase(),e=>e.toLowerCase().endsWith(n)),wR=/^\*+\.\*+$/,vR=n=>!n.startsWith(".")&&n.includes("."),xR=n=>n!=="."&&n!==".."&&n.includes("."),TR=/^\.\*+$/,ER=n=>n!=="."&&n!==".."&&n.startsWith("."),CR=/^\*+$/,AR=n=>n.length!==0&&!n.startsWith("."),RR=n=>n.length!==0&&n!=="."&&n!=="..",IR=/^\?+([^+@!?\*\[\(]*)?$/,PR=([n,e=""])=>{let t=vy([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},LR=([n,e=""])=>{let t=xy([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},OR=([n,e=""])=>{let t=xy([n]);return e?r=>t(r)&&r.endsWith(e):t},kR=([n,e=""])=>{let t=vy([n]);return e?r=>t(r)&&r.endsWith(e):t},vy=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},xy=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},Ty=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Sy={win32:{sep:"\\"},posix:{sep:"/"}},_R=Ty==="win32"?Sy.win32.sep:Sy.posix.sep;ht.sep=_R;var tt=Symbol("globstar **");ht.GLOBSTAR=tt;var NR="[^/]",MR=NR+"*?",DR="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",FR="(?:(?!(?:\\/|^)\\.).)*?",UR=(n,e={})=>t=>ht(t,n,e);ht.filter=UR;var Wt=(n,e={})=>Object.assign({},n,e),zR=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return ht;let e=ht;return Object.assign((r,o,i={})=>e(r,o,Wt(n,i)),{Minimatch:class extends e.Minimatch{constructor(o,i={}){super(o,Wt(n,i))}static defaults(o){return e.defaults(Wt(n,o)).Minimatch}},AST:class extends e.AST{constructor(o,i,s={}){super(o,i,Wt(n,s))}static fromGlob(o,i={}){return e.AST.fromGlob(o,Wt(n,i))}},unescape:(r,o={})=>e.unescape(r,Wt(n,o)),escape:(r,o={})=>e.escape(r,Wt(n,o)),filter:(r,o={})=>e.filter(r,Wt(n,o)),defaults:r=>e.defaults(Wt(n,r)),makeRe:(r,o={})=>e.makeRe(r,Wt(n,o)),braceExpand:(r,o={})=>e.braceExpand(r,Wt(n,o)),match:(r,o,i={})=>e.match(r,o,Wt(n,i)),sep:e.sep,GLOBSTAR:tt})};ht.defaults=zR;var Ey=(n,e={})=>(Ii(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,wy.default)(n));ht.braceExpand=Ey;var BR=(n,e={})=>new Lt(n,e).makeRe();ht.makeRe=BR;var jR=(n,e,t={})=>{let r=new Lt(e,t);return n=n.filter(o=>r.match(o)),r.options.nonull&&!n.length&&n.push(e),n};ht.match=jR;var by=/[?*]|[+@!]\(.*?\)|\[|\]/,$R=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Lt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Ii(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Ty,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]==="?"||!by.test(i[2]))&&!by.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 f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),g=!f&&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]),S=g?3:f?0:void 0,E=v?3:y?0:void 0;if(typeof S=="number"&&typeof E=="number"){let[T,C]=[e[S],t[E]];T.toLowerCase()===C.toLowerCase()&&(t[E]=T,E>S?t=t.slice(E):S>E&&(e=e.slice(S)))}}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===tt){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 f;if(typeof d=="string"?(f=p===d,this.debug("string match",d,p,f)):(f=d.test(p),this.debug("pattern match",d,p,f)),!f)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 Ey(this.pattern,this.options)}parse(e){Ii(e);let t=this.options;if(e==="**")return tt;if(e==="")return"";let r,o=null;(r=e.match(CR))?o=t.dot?RR:AR:(r=e.match(fR))?o=(t.nocase?t.dot?bR:SR:t.dot?yR:gR)(r[1]):(r=e.match(IR))?o=(t.nocase?t.dot?LR:PR:t.dot?OR:kR)(r):(r=e.match(wR))?o=t.dot?xR:vR:(r=e.match(TR))&&(o=ER);let i=ho.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?MR:t.dot?DR:FR,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"?$R(d):d===tt?tt:d._src});return c.forEach((d,p)=>{let u=c[p+1],m=c[p-1];d!==tt||m===tt||(m===void 0?u!==void 0&&u!==tt?c[p+1]="(?:\\/|"+r+"\\/)?"+u:c[p]=r:u===void 0?c[p-1]=m+"(?:\\/|"+r+")?":u!==tt&&(c[p-1]=m+"(?:\\/|\\/"+r+"\\/)"+u,c[p+1]=tt))}),c.filter(d=>d!==tt).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 ht.defaults(e).Minimatch}};ht.AST=ho;ht.Minimatch=Lt;ht.escape=fo;ht.unescape=tn;import{fileURLToPath as wI}from"node:url";var go=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Ay=new Set,gd=typeof process=="object"&&process?process:{},Ry=(n,e,t,r)=>{typeof gd.emitWarning=="function"?gd.emitWarning(n,e,t,r):console.error(`[${t}] ${e}: ${n}`)},ba=globalThis.AbortController,Cy=globalThis.AbortSignal;if(typeof ba>"u"){Cy=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},ba=class{constructor(){e()}signal=new Cy;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=gd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,Ry("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 HR=n=>!Ay.has(n),$Q=Symbol("type"),Gn=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),Iy=n=>Gn(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?yo:null:null,yo=class extends Array{constructor(e){super(e),this.fill(0)}},yd=class n{heap;length;static#e=!1;static create(e){let t=Iy(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]}},Li=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;#g;#y;#m;#u;#T;#f;#E;#C;#b;#v;#x;#h;static unsafeExposeInternals(e){return{starts:e.#C,ttls:e.#b,sizes:e.#E,keyMap:e.#a,keyList:e.#l,valList:e.#o,next:e.#g,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.#S(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:f,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:T,ignoreFetchAbort:C}=e;if(t!==0&&!Gn(t))throw new TypeError("max option must be a nonnegative integer");let P=t?Iy(t):Array;if(!P)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=f,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,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#s=g,this.#x=!!g,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#g=new P(t),this.#y=new P(t),this.#m=0,this.#u=0,this.#T=yd.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof d=="function"?(this.#r=d,this.#f=[]):(this.#r=void 0,this.#f=void 0),this.#v=!!this.#i,this.#h=!!this.#r,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(this.#t!==0&&!Gn(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!Gn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Gn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!Gn(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 k="LRU_CACHE_UNBOUNDED";HR(k)&&(Ay.add(k),Ry("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",k,n))}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#P(){let e=new yo(this.#e),t=new yo(this.#e);this.#b=e,this.#C=t,this.#k=(i,s,a=go.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#S(i)&&this.#O(this.#l[i],"expire")},s+1);l.unref&&l.unref()}},this.#A=i=>{t[i]=e[i]!==0?go.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=go.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.#S=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(r||o())-s>a}}#A=()=>{};#n=()=>{};#k=()=>{};#S=()=>!1;#L(){let e=new yo(this.#e);this.#p=0,this.#E=e,this.#_=t=>{this.#p-=e[t],e[t]=0},this.#M=(t,r,o,i)=>{if(this.#d(r))return 0;if(!Gn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(r,t),!Gn(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.#F(!0)}this.#p+=e[t],o&&(o.entrySize=r,o.totalCalculatedSize=this.#p)}}#_=e=>{};#N=(e,t,r)=>{};#M=(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.#D(t)||((e||!this.#S(t))&&(yield t),t===this.#m));)t=this.#y[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#D(t)||((e||!this.#S(t))&&(yield t),t===this.#u));)t=this.#g[t]}#D(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.#S(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.#b&&this.#C){let s=this.#b[t],a=this.#C[t];if(s&&a){let l=s-(go.now()-a);i.ttl=l,i.start=Date.now()}}return this.#E&&(i.size=this.#E[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.#b&&this.#C){s.ttl=this.#b[t];let a=go.now()-this.#C[t];s.start=Math.floor(Date.now()-a)}this.#E&&(s.size=this.#E[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=go.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.#M(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.#F(!1):this.#c,this.#l[p]=e,this.#o[p]=t,this.#a.set(e,p),this.#g[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.#f?.push([m,e,"set"]))}else s||(this.#v&&this.#i?.(u,e,"set"),this.#h&&this.#f?.push([u,e,"set"]));if(this.#_(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.#b&&this.#P(),this.#b&&(c||this.#k(p,o,i),l&&this.#n(l,p)),!s&&this.#h&&this.#f){let u=this.#f,m;for(;m=u?.shift();)this.#r?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#m];if(this.#F(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#f){let e=this.#f,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(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.#f?.push([o,r,"evict"])),this.#_(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.#g[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.#S(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.#S(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 ba,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let l={signal:s.signal,options:r,context:o},c=(f,g=!1)=>{let{aborted:y}=s.signal,v=r.ignoreFetchAbort&&f!==void 0;if(r.status&&(y&&!g?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,v&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),y&&!v&&!g)return p(s.signal.reason);let S=m;return this.#o[t]===m&&(f===void 0?S.__staleWhileFetching?this.#o[t]=S.__staleWhileFetching:this.#O(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,f,l.options))),f},d=f=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=f),p(f)),p=f=>{let{aborted:g}=s.signal,y=g&&r.allowStaleOnFetchAbort,v=y||r.allowStaleOnFetchRejection,S=v||r.noDeleteOnFetchRejection,E=m;if(this.#o[t]===m&&(!S||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 f},u=(f,g)=>{let y=this.#s?.(e,i,l);y&&y instanceof Promise&&y.then(v=>f(v===void 0?void 0:v),g),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(f(void 0),r.allowStaleOnFetchAbort&&(f=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 ba}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:f,forceRefresh:g=!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 S={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 T=this.#U(e,E,S,f);return T.__returned=T}else{let T=this.#o[E];if(this.#d(T)){let J=r&&T.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",J&&(y.returnedStale=!0)),J?T.__staleWhileFetching:T.__returned=T}let C=this.#S(E);if(!g&&!C)return y&&(y.fetch="hit"),this.#B(E),o&&this.#A(E),y&&this.#n(y,E),T;let P=this.#U(e,E,S,f),N=P.__staleWhileFetching!==void 0&&r;return y&&(y.fetch=C?"stale":"refresh",N&&C&&(y.returnedStale=!0)),N?P.__staleWhileFetching:P.__returned=P}}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.#S(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.#g[e]=t}#B(e){e!==this.#u&&(e===this.#m?this.#m=this.#g[e]:this.#z(this.#y[e],this.#g[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.#_(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.#f?.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.#g[o];else{let s=this.#y[o];this.#g[s]=this.#g[o];let a=this.#g[o];this.#y[a]=this.#y[o]}this.#c--,this.#T.push(o)}}if(this.#h&&this.#f?.length){let o=this.#f,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.#f?.push([r,o,e])}}if(this.#a.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#b&&this.#C&&(this.#b.fill(0),this.#C.fill(0)),this.#E&&this.#E.fill(0),this.#m=0,this.#u=0,this.#T.length=0,this.#p=0,this.#c=0,this.#h&&this.#f){let t=this.#f,r;for(;r=t?.shift();)this.#r?.(...r)}}};import{posix as eI,win32 as Rd}from"node:path";import{fileURLToPath as tI}from"node:url";import{lstatSync as nI,readdir as rI,readdirSync as oI,readlinkSync as iI,realpathSync as sI}from"fs";import*as aI from"node:fs";import{lstat as cI,readdir as dI,readlink as pI,realpath as uI}from"node:fs/promises";import{EventEmitter as Ed}from"node:events";import _y from"node:stream";import{StringDecoder as WR}from"node:string_decoder";var Py=typeof process=="object"&&process?process:{stdout:null,stderr:null},GR=n=>!!n&&typeof n=="object"&&(n instanceof qn||n instanceof _y||VR(n)||qR(n)),VR=n=>!!n&&typeof n=="object"&&n instanceof Ed&&typeof n.pipe=="function"&&n.pipe!==_y.Writable.prototype.pipe,qR=n=>!!n&&typeof n=="object"&&n instanceof Ed&&typeof n.write=="function"&&typeof n.end=="function",In=Symbol("EOF"),Pn=Symbol("maybeEmitEnd"),Vn=Symbol("emittedEnd"),wa=Symbol("emittingEnd"),Oi=Symbol("emittedError"),va=Symbol("closed"),Ly=Symbol("read"),xa=Symbol("flush"),Oy=Symbol("flushChunk"),nn=Symbol("encoding"),So=Symbol("decoder"),qe=Symbol("flowing"),ki=Symbol("paused"),bo=Symbol("resume"),Ke=Symbol("buffer"),ft=Symbol("pipes"),Ye=Symbol("bufferLength"),Sd=Symbol("bufferPush"),Ta=Symbol("bufferShift"),ct=Symbol("objectMode"),ke=Symbol("destroyed"),bd=Symbol("error"),wd=Symbol("emitData"),ky=Symbol("emitEnd"),vd=Symbol("emitEnd2"),yn=Symbol("async"),xd=Symbol("abort"),Ea=Symbol("aborted"),_i=Symbol("signal"),Ar=Symbol("dataListeners"),Ot=Symbol("discarded"),Ni=n=>Promise.resolve().then(n),KR=n=>n(),YR=n=>n==="end"||n==="finish"||n==="prefinish",JR=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,XR=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),Ca=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[bo](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Td=class extends Ca{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)}},ZR=n=>!!n.objectMode,QR=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",qn=class extends Ed{[qe]=!1;[ki]=!1;[ft]=[];[Ke]=[];[ct];[nn];[yn];[So];[In]=!1;[Vn]=!1;[wa]=!1;[va]=!1;[Oi]=null;[Ye]=0;[ke]=!1;[_i];[Ea]=!1;[Ar]=0;[Ot]=!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");ZR(t)?(this[ct]=!0,this[nn]=null):QR(t)?(this[nn]=t.encoding,this[ct]=!1):(this[ct]=!1,this[nn]=null),this[yn]=!!t.async,this[So]=this[nn]?new WR(this[nn]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ke]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[ft]});let{signal:r}=t;r&&(this[_i]=r,r.aborted?this[xd]():r.addEventListener("abort",()=>this[xd]()))}get bufferLength(){return this[Ye]}get encoding(){return this[nn]}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[ct]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[yn]}set async(e){this[yn]=this[yn]||!!e}[xd](){this[Ea]=!0,this.emit("abort",this[_i]?.reason),this.destroy(this[_i]?.reason)}get aborted(){return this[Ea]}set aborted(e){}write(e,t,r){if(this[Ea])return!1;if(this[In])throw new Error("write after end");if(this[ke])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[yn]?Ni:KR;if(!this[ct]&&!Buffer.isBuffer(e)){if(XR(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(JR(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[ct]?(this[qe]&&this[Ye]!==0&&this[xa](!0),this[qe]?this.emit("data",e):this[Sd](e),this[Ye]!==0&&this.emit("readable"),r&&o(r),this[qe]):e.length?(typeof e=="string"&&!(t===this[nn]&&!this[So]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[nn]&&(e=this[So].write(e)),this[qe]&&this[Ye]!==0&&this[xa](!0),this[qe]?this.emit("data",e):this[Sd](e),this[Ye]!==0&&this.emit("readable"),r&&o(r),this[qe]):(this[Ye]!==0&&this.emit("readable"),r&&o(r),this[qe])}read(e){if(this[ke])return null;if(this[Ot]=!1,this[Ye]===0||e===0||e&&e>this[Ye])return this[Pn](),null;this[ct]&&(e=null),this[Ke].length>1&&!this[ct]&&(this[Ke]=[this[nn]?this[Ke].join(""):Buffer.concat(this[Ke],this[Ye])]);let t=this[Ly](e||null,this[Ke][0]);return this[Pn](),t}[Ly](e,t){if(this[ct])this[Ta]();else{let r=t;e===r.length||e===null?this[Ta]():typeof r=="string"?(this[Ke][0]=r.slice(e),t=r.slice(0,e),this[Ye]-=e):(this[Ke][0]=r.subarray(e),t=r.subarray(0,e),this[Ye]-=e)}return this.emit("data",t),!this[Ke].length&&!this[In]&&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[In]=!0,this.writable=!1,(this[qe]||!this[ki])&&this[Pn](),this}[bo](){this[ke]||(!this[Ar]&&!this[ft].length&&(this[Ot]=!0),this[ki]=!1,this[qe]=!0,this.emit("resume"),this[Ke].length?this[xa]():this[In]?this[Pn]():this.emit("drain"))}resume(){return this[bo]()}pause(){this[qe]=!1,this[ki]=!0,this[Ot]=!1}get destroyed(){return this[ke]}get flowing(){return this[qe]}get paused(){return this[ki]}[Sd](e){this[ct]?this[Ye]+=1:this[Ye]+=e.length,this[Ke].push(e)}[Ta](){return this[ct]?this[Ye]-=1:this[Ye]-=this[Ke][0].length,this[Ke].shift()}[xa](e=!1){do;while(this[Oy](this[Ta]())&&this[Ke].length);!e&&!this[Ke].length&&!this[In]&&this.emit("drain")}[Oy](e){return this.emit("data",e),this[qe]}pipe(e,t){if(this[ke])return e;this[Ot]=!1;let r=this[Vn];return t=t||{},e===Py.stdout||e===Py.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[ft].push(t.proxyErrors?new Td(this,e,t):new Ca(this,e,t)),this[yn]?Ni(()=>this[bo]()):this[bo]()),e}unpipe(e){let t=this[ft].find(r=>r.dest===e);t&&(this[ft].length===1?(this[qe]&&this[Ar]===0&&(this[qe]=!1),this[ft]=[]):this[ft].splice(this[ft].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[Ot]=!1,this[Ar]++,!this[ft].length&&!this[qe]&&this[bo]();else if(e==="readable"&&this[Ye]!==0)super.emit("readable");else if(YR(e)&&this[Vn])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Oi]){let o=t;this[yn]?Ni(()=>o.call(this,this[Oi])):o.call(this,this[Oi])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[Ar]=this.listeners("data").length,this[Ar]===0&&!this[Ot]&&!this[ft].length&&(this[qe]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Ar]=0,!this[Ot]&&!this[ft].length&&(this[qe]=!1)),t}get emittedEnd(){return this[Vn]}[Pn](){!this[wa]&&!this[Vn]&&!this[ke]&&this[Ke].length===0&&this[In]&&(this[wa]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[va]&&this.emit("close"),this[wa]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==ke&&this[ke])return!1;if(e==="data")return!this[ct]&&!r?!1:this[yn]?(Ni(()=>this[wd](r)),!0):this[wd](r);if(e==="end")return this[ky]();if(e==="close"){if(this[va]=!0,!this[Vn]&&!this[ke])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Oi]=r,super.emit(bd,r);let i=!this[_i]||this.listeners("error").length?super.emit("error",r):!1;return this[Pn](),i}else if(e==="resume"){let i=super.emit("resume");return this[Pn](),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[Pn](),o}[wd](e){for(let r of this[ft])r.dest.write(e)===!1&&this.pause();let t=this[Ot]?!1:super.emit("data",e);return this[Pn](),t}[ky](){return this[Vn]?!1:(this[Vn]=!0,this.readable=!1,this[yn]?(Ni(()=>this[vd]()),!0):this[vd]())}[vd](){if(this[So]){let t=this[So].end();if(t){for(let r of this[ft])r.dest.write(t);this[Ot]||super.emit("data",t)}}for(let t of this[ft])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[ct]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[ct]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[ct])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[nn]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(ke,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Ot]=!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[In])return t();let i,s,a=p=>{this.off("data",l),this.off("end",c),this.off(ke,d),t(),s(p)},l=p=>{this.off("error",a),this.off("end",c),this.off(ke,d),this.pause(),i({value:p,done:!!this[In]})},c=()=>{this.off("error",a),this.off("data",l),this.off(ke,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(ke,d),this.once("error",a),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Ot]=!1;let e=!1,t=()=>(this.pause(),this.off(bd,t),this.off(ke,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(bd,t),this.once(ke,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[ke])return e?this.emit("error",e):this.emit(ke),this;this[ke]=!0,this[Ot]=!0,this[Ke].length=0,this[Ye]=0;let t=this;return typeof t.close=="function"&&!this[va]&&t.close(),e?this.emit("error",e):this.emit(ke),this}static get isStream(){return GR}};var lI=sI.native,Di={lstatSync:nI,readdir:rI,readdirSync:oI,readlinkSync:iI,realpathSync:lI,promises:{lstat:cI,readdir:dI,readlink:pI,realpath:uI}},Uy=n=>!n||n===Di||n===aI?Di:{...Di,...n,promises:{...Di.promises,...n.promises||{}}},zy=/^\\\\\?\\([a-z]:)\\?$/i,mI=n=>n.replace(/\//g,"\\").replace(zy,"$1\\"),hI=/[\\\/]/,Vt=0,By=1,jy=2,Sn=4,$y=6,Hy=8,Rr=10,Wy=12,Gt=15,Mi=~Gt,Cd=16,Ny=32,Fi=64,rn=128,Aa=256,Ia=512,My=Fi|rn|Ia,fI=1023,Ad=n=>n.isFile()?Hy:n.isDirectory()?Sn:n.isSymbolicLink()?Rr:n.isCharacterDevice()?jy:n.isBlockDevice()?$y:n.isSocket()?Wy:n.isFIFO()?By:Vt,Dy=new Map,Ui=n=>{let e=Dy.get(n);if(e)return e;let t=n.normalize("NFKD");return Dy.set(n,t),t},Fy=new Map,Ra=n=>{let e=Fy.get(n);if(e)return e;let t=Ui(n.toLowerCase());return Fy.set(n,t),t},Pa=class extends Li{constructor(){super({max:256})}},Id=class extends Li{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},Gy=Symbol("PathScurry setAsCwd"),dt=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}#g;get atimeMs(){return this.#g}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#u;get birthtimeMs(){return this.#u}#T;get atime(){return this.#T}#f;get mtime(){return this.#f}#E;get ctime(){return this.#E}#C;get birthtime(){return this.#C}#b;#v;#x;#h;#P;#A;#n;#k;#S;#L;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=Vt,r,o,i,s,a){this.name=e,this.#b=i?Ra(e):Ui(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=Uy(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).#_(o):this.#_(o)}#_(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&=~Cd,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),o=this.nocase?Ra(e):Ui(e);for(let l of r)if(l.#b===o)return l;let i=this.parent?this.sep:"",s=this.#x?this.#x+i+e:void 0,a=this.newChild(e,Vt,{...t,parent:this,fullpath:s});return this.canReaddir()||(a.#n|=rn),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&Gt)===Vt}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&Gt)===Hy}isDirectory(){return(this.#n&Gt)===Sn}isCharacterDevice(){return(this.#n&Gt)===jy}isBlockDevice(){return(this.#n&Gt)===$y}isFIFO(){return(this.#n&Gt)===By}isSocket(){return(this.#n&Gt)===Wy}isSymbolicLink(){return(this.#n&Rr)===Rr}lstatCached(){return this.#n&Ny?this:void 0}readlinkCached(){return this.#S}realpathCached(){return this.#L}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#S)return!0;if(!this.parent)return!1;let e=this.#n&Gt;return!(e!==Vt&&e!==Rr||this.#n&Aa||this.#n&rn)}calledReaddir(){return!!(this.#n&Cd)}isENOENT(){return!!(this.#n&rn)}isNamed(e){return this.nocase?this.#b===Ra(e):this.#b===Ui(e)}async readlink(){let e=this.#S;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.#S=r}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#S;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.#S=r}catch(t){this.#d(t.code);return}}#N(e){this.#n|=Cd;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#M()}}#M(){this.#n&rn||(this.#n=(this.#n|rn)&Mi,this.#R())}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#M()}#I(){this.#n|=Ia,this.#D()}#D(){if(this.#n&Fi)return;let e=this.#n;(e&Gt)===Sn&&(e&=Mi),this.#n=e|Fi,this.#R()}#F(e=""){e==="ENOTDIR"||e==="EPERM"?this.#D():e==="ENOENT"?this.#M():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#D():e==="ENOENT"&&this.#M()}#d(e=""){let t=this.#n;t|=Aa,e==="ENOENT"&&(t|=rn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Mi),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#D()}#z(e,t){return this.#O(e,t)||this.#B(e,t)}#B(e,t){let r=Ad(e),o=this.newChild(e.name,r,{parent:this}),i=o.#n&Gt;return i!==Sn&&i!==Rr&&i!==Vt&&(o.#n|=Fi),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?Ra(e.name):Ui(e.name))===o.#b)return this.#j(e,o,r,t)}}#j(e,t,r,o){let i=t.name;return t.#n=t.#n&Mi|Ad(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&rn))try{return this.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&rn))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:f,nlink:g,rdev:y,size:v,uid:S}=e;this.#T=t,this.#g=r,this.#C=o,this.#u=i,this.#p=s,this.#o=a,this.#E=l,this.#m=c,this.#t=d,this.#w=p,this.#a=u,this.#i=m,this.#f=h,this.#y=f,this.#r=g,this.#c=y,this.#l=v,this.#s=S;let E=Ad(e);this.#n=this.#n&Mi|E|Ny,E!==Vt&&E!==Sn&&E!==Rr&&(this.#n|=Fi)}#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.#F(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.#F(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.#F(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&My)return!1;let e=Gt&this.#n;return e===Vt||e===Sn||e===Rr}shouldWalk(e,t){return(this.#n&Sn)===Sn&&!(this.#n&My)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((Ia|Aa|rn)&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(!((Ia|Aa|rn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[Gy](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}},La=class n extends dt{sep="\\";splitSep=hI;constructor(e,t=Vt,r,o,i,s,a){super(e,t,r,o,i,s,a)}newChild(e,t=Vt,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return Rd.parse(e).root}getRoot(e){if(e=mI(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 wo(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(zy,"$1\\"),e===t}},Oa=class n extends dt{splitSep="/";sep="/";constructor(e,t=Vt,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=Vt,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}},ka=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,r,{nocase:o,childrenCacheSize:i=16*1024,fs:s=Di}={}){this.#r=Uy(s),(e instanceof URL||e.startsWith("file://"))&&(e=tI(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new Pa,this.#t=new Pa,this.#i=new Id(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 f=d--;c=c.child(h,{relative:new Array(f).fill("..").join(p),relativePosix:new Array(f).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 dt||(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 dt||(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 dt||(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 dt||(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 dt||(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 dt||(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 dt||(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 f=h.length;if(!f)return u();let g=()=>{--f===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,g):g()):y.shouldWalk(l,s)?c(y,g):g()},!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 dt||(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 dt||(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 dt||(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 dt||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new qn({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=(g,y,v=!1)=>{if(g)return a.emit("error",g);if(o&&!v){let S=[];for(let E of y)E.isSymbolicLink()&&S.push(E.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(S.length){Promise.all(S).then(()=>h(null,y,!0));return}}for(let S of y)S&&(!i||i(S))&&(a.write(r?S:S.fullpath())||(u=!0));d--;for(let S of y){let E=S.realpathCached()||S;E.shouldWalk(l,s)&&c.push(E)}u&&!a.flowing?a.once("drain",p):f||p()},f=!0;m.readdirCB(h,!0),f=!1}};return p(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof dt||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new qn({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 f of h)(!i||i(f))&&(a.write(r?f:f.fullpath())||(u=!0));d--;for(let f of h){let g=f;if(f.isSymbolicLink()){if(!(o&&(g=f.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(l,s)&&c.push(g)}}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[Gy](t)}},wo=class extends ka{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Rd,"\\",{...t,nocase:r}),this.nocase=r;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return Rd.parse(e).root.toUpperCase()}newRoot(e){return new La(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)}},vo=class extends ka{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,eI,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new Oa(this.rootPath,Sn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},zi=class extends vo{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},e7=process.platform==="win32"?La:Oa,Vy=process.platform==="win32"?wo:process.platform==="darwin"?zi:vo;var gI=n=>n.length>=1,yI=n=>n.length>=1,xo=class n{#e;#t;#i;length;#r;#s;#w;#c;#p;#a;#l=!0;constructor(e,t,r,o){if(!gI(e))throw new TypeError("empty pattern list");if(!yI(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 f=[i,s,a,l,""].join("/"),g=[d,p,u,m,""].join("/");this.#e=[f,...c],this.#t=[g,...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]===tt}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 SI=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",To=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:o,noglobstar:i,platform:s=SI}){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 Lt(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 xo(o,i,0,this.platform),a=new Lt(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 Pd=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()]))}},Ld=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)])}},Od=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())}},Bi=class n{hasWalkedCache;matches=new Ld;subwalks=new Od;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Pd}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===tt){(!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===tt?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 To([n],e):Array.isArray(n)?new To(n,e):n,_a=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 Bi(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 Bi(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()}},ji=class extends _a{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}},$i=class extends _a{results;constructor(e,t,r){super(e,t,r),this.results=new qn({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 vI=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",on=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=wI(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||vI,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"?wo:t.platform==="darwin"?zi:t.platform?vo:Vy;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 Lt(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 xo(l,d,0,this.platform)})}async walk(){return[...await new ji(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 ji(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 $i(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 $i(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 kd=(n,e={})=>{Array.isArray(n)||(n=[n]);for(let t of n)if(new Lt(t,e).hasMagic())return!0;return!1};function Na(n,e={}){return new on(n,e).streamSync()}function Yy(n,e={}){return new on(n,e).stream()}function Eo(n,e={}){return new on(n,e).walkSync()}async function qy(n,e={}){return new on(n,e).walk()}function Ma(n,e={}){return new on(n,e).iterateSync()}function Jy(n,e={}){return new on(n,e).iterate()}var xI=Na,TI=Object.assign(Yy,{sync:Na}),EI=Ma,CI=Object.assign(Jy,{sync:Ma}),AI=Object.assign(Eo,{stream:Na,iterate:Ma}),Ky=Object.assign(qy,{glob:qy,globSync:Eo,sync:AI,globStream:Yy,stream:TI,globStreamSync:Na,streamSync:xI,globIterate:Jy,iterate:CI,globIterateSync:Ma,iterateSync:EI,Glob:on,hasMagic:kd,escape:fo,unescape:tn});Ky.glob=Ky;import NI from"os";import Kn,{dirname as eS}from"path";import{cwd as Dd}from"process";import tS from"yaml";import{z as Ee}from"zod";import Xy from"fs";import Da from"path";import RI from"yaml";import{z as _d}from"zod";var Zy=!1,Hi=[`**/*.${En.TEST}`,`**/*.${En.MODULE}`],Nd=_d.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),Md=50,II=_d.object({fileType:_d.nativeEnum(xe)});function nt(n,e){let t={project:n,tests:{},modules:{}},r=n.config.include??Hi,o=Array.from(n.config.exclude??[]).concat(hm),i=Eo(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:Md,nodir:!0});for(let s of i)PI(n.rootDir,s,t,e);return Zy=!0,t}function PI(n,e,t,r){let o=Da.join(n,e),i;try{i=Xy.readFileSync(o,"utf-8")}catch(p){r.warn(`Could not read possible Momentic file at ${o}, skipping: ${p}`);return}let s;try{if(s=RI.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=II.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=Xy.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:Da.sep,fullPathSegments:o.split(Da.sep),fileName:Da.basename(o),lastModified:c.mtime,createdAt:c.birthtime};switch(l){case xe.TEST:try{let p=dn.parse(s);if(t.tests[p.id]){let u=t.tests[p.id].fullFilePath;b.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 f;if(typeof d=="string"?(f=p===d,this.debug("string match",d,p,f)):(f=d.test(p),this.debug("pattern match",d,p,f)),!f)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 Ey(this.pattern,this.options)}parse(e){Ii(e);let t=this.options;if(e==="**")return tt;if(e==="")return"";let r,o=null;(r=e.match(CR))?o=t.dot?RR:AR:(r=e.match(fR))?o=(t.nocase?t.dot?bR:SR:t.dot?yR:gR)(r[1]):(r=e.match(IR))?o=(t.nocase?t.dot?LR:PR:t.dot?OR:kR)(r):(r=e.match(wR))?o=t.dot?xR:vR:(r=e.match(TR))&&(o=ER);let i=ho.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?MR:t.dot?DR:FR,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"?$R(d):d===tt?tt:d._src});return c.forEach((d,p)=>{let u=c[p+1],m=c[p-1];d!==tt||m===tt||(m===void 0?u!==void 0&&u!==tt?c[p+1]="(?:\\/|"+r+"\\/)?"+u:c[p]=r:u===void 0?c[p-1]=m+"(?:\\/|"+r+")?":u!==tt&&(c[p-1]=m+"(?:\\/|\\/"+r+"\\/)"+u,c[p+1]=tt))}),c.filter(d=>d!==tt).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 ht.defaults(e).Minimatch}};ht.AST=ho;ht.Minimatch=Lt;ht.escape=fo;ht.unescape=tn;import{fileURLToPath as wI}from"node:url";var go=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Ay=new Set,gd=typeof process=="object"&&process?process:{},Ry=(n,e,t,r)=>{typeof gd.emitWarning=="function"?gd.emitWarning(n,e,t,r):console.error(`[${t}] ${e}: ${n}`)},ba=globalThis.AbortController,Cy=globalThis.AbortSignal;if(typeof ba>"u"){Cy=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},ba=class{constructor(){e()}signal=new Cy;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=gd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,Ry("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 HR=n=>!Ay.has(n),$Q=Symbol("type"),Gn=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),Iy=n=>Gn(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?yo:null:null,yo=class extends Array{constructor(e){super(e),this.fill(0)}},yd=class n{heap;length;static#e=!1;static create(e){let t=Iy(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]}},Li=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;#g;#y;#m;#u;#T;#f;#E;#C;#b;#v;#x;#h;static unsafeExposeInternals(e){return{starts:e.#C,ttls:e.#b,sizes:e.#E,keyMap:e.#a,keyList:e.#l,valList:e.#o,next:e.#g,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.#S(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:f,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:T,ignoreFetchAbort:C}=e;if(t!==0&&!Gn(t))throw new TypeError("max option must be a nonnegative integer");let P=t?Iy(t):Array;if(!P)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=f,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,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#s=g,this.#x=!!g,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#g=new P(t),this.#y=new P(t),this.#m=0,this.#u=0,this.#T=yd.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof d=="function"?(this.#r=d,this.#f=[]):(this.#r=void 0,this.#f=void 0),this.#v=!!this.#i,this.#h=!!this.#r,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(this.#t!==0&&!Gn(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!Gn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Gn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!Gn(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 k="LRU_CACHE_UNBOUNDED";HR(k)&&(Ay.add(k),Ry("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",k,n))}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#P(){let e=new yo(this.#e),t=new yo(this.#e);this.#b=e,this.#C=t,this.#k=(i,s,a=go.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#S(i)&&this.#O(this.#l[i],"expire")},s+1);l.unref&&l.unref()}},this.#A=i=>{t[i]=e[i]!==0?go.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=go.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.#S=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(r||o())-s>a}}#A=()=>{};#n=()=>{};#k=()=>{};#S=()=>!1;#L(){let e=new yo(this.#e);this.#p=0,this.#E=e,this.#_=t=>{this.#p-=e[t],e[t]=0},this.#M=(t,r,o,i)=>{if(this.#d(r))return 0;if(!Gn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(r,t),!Gn(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.#F(!0)}this.#p+=e[t],o&&(o.entrySize=r,o.totalCalculatedSize=this.#p)}}#_=e=>{};#N=(e,t,r)=>{};#M=(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.#D(t)||((e||!this.#S(t))&&(yield t),t===this.#m));)t=this.#y[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#D(t)||((e||!this.#S(t))&&(yield t),t===this.#u));)t=this.#g[t]}#D(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.#S(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.#b&&this.#C){let s=this.#b[t],a=this.#C[t];if(s&&a){let l=s-(go.now()-a);i.ttl=l,i.start=Date.now()}}return this.#E&&(i.size=this.#E[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.#b&&this.#C){s.ttl=this.#b[t];let a=go.now()-this.#C[t];s.start=Math.floor(Date.now()-a)}this.#E&&(s.size=this.#E[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=go.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.#M(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.#F(!1):this.#c,this.#l[p]=e,this.#o[p]=t,this.#a.set(e,p),this.#g[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.#f?.push([m,e,"set"]))}else s||(this.#v&&this.#i?.(u,e,"set"),this.#h&&this.#f?.push([u,e,"set"]));if(this.#_(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.#b&&this.#P(),this.#b&&(c||this.#k(p,o,i),l&&this.#n(l,p)),!s&&this.#h&&this.#f){let u=this.#f,m;for(;m=u?.shift();)this.#r?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#m];if(this.#F(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#f){let e=this.#f,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(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.#f?.push([o,r,"evict"])),this.#_(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.#g[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.#S(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.#S(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 ba,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let l={signal:s.signal,options:r,context:o},c=(f,g=!1)=>{let{aborted:y}=s.signal,v=r.ignoreFetchAbort&&f!==void 0;if(r.status&&(y&&!g?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,v&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),y&&!v&&!g)return p(s.signal.reason);let S=m;return this.#o[t]===m&&(f===void 0?S.__staleWhileFetching?this.#o[t]=S.__staleWhileFetching:this.#O(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,f,l.options))),f},d=f=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=f),p(f)),p=f=>{let{aborted:g}=s.signal,y=g&&r.allowStaleOnFetchAbort,v=y||r.allowStaleOnFetchRejection,S=v||r.noDeleteOnFetchRejection,E=m;if(this.#o[t]===m&&(!S||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 f},u=(f,g)=>{let y=this.#s?.(e,i,l);y&&y instanceof Promise&&y.then(v=>f(v===void 0?void 0:v),g),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(f(void 0),r.allowStaleOnFetchAbort&&(f=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 ba}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:f,forceRefresh:g=!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 S={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 T=this.#U(e,E,S,f);return T.__returned=T}else{let T=this.#o[E];if(this.#d(T)){let J=r&&T.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",J&&(y.returnedStale=!0)),J?T.__staleWhileFetching:T.__returned=T}let C=this.#S(E);if(!g&&!C)return y&&(y.fetch="hit"),this.#B(E),o&&this.#A(E),y&&this.#n(y,E),T;let P=this.#U(e,E,S,f),N=P.__staleWhileFetching!==void 0&&r;return y&&(y.fetch=C?"stale":"refresh",N&&C&&(y.returnedStale=!0)),N?P.__staleWhileFetching:P.__returned=P}}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.#S(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.#g[e]=t}#B(e){e!==this.#u&&(e===this.#m?this.#m=this.#g[e]:this.#z(this.#y[e],this.#g[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.#_(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.#f?.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.#g[o];else{let s=this.#y[o];this.#g[s]=this.#g[o];let a=this.#g[o];this.#y[a]=this.#y[o]}this.#c--,this.#T.push(o)}}if(this.#h&&this.#f?.length){let o=this.#f,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.#f?.push([r,o,e])}}if(this.#a.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#b&&this.#C&&(this.#b.fill(0),this.#C.fill(0)),this.#E&&this.#E.fill(0),this.#m=0,this.#u=0,this.#T.length=0,this.#p=0,this.#c=0,this.#h&&this.#f){let t=this.#f,r;for(;r=t?.shift();)this.#r?.(...r)}}};import{posix as eI,win32 as Rd}from"node:path";import{fileURLToPath as tI}from"node:url";import{lstatSync as nI,readdir as rI,readdirSync as oI,readlinkSync as iI,realpathSync as sI}from"fs";import*as aI from"node:fs";import{lstat as cI,readdir as dI,readlink as pI,realpath as uI}from"node:fs/promises";import{EventEmitter as Ed}from"node:events";import _y from"node:stream";import{StringDecoder as WR}from"node:string_decoder";var Py=typeof process=="object"&&process?process:{stdout:null,stderr:null},GR=n=>!!n&&typeof n=="object"&&(n instanceof qn||n instanceof _y||VR(n)||qR(n)),VR=n=>!!n&&typeof n=="object"&&n instanceof Ed&&typeof n.pipe=="function"&&n.pipe!==_y.Writable.prototype.pipe,qR=n=>!!n&&typeof n=="object"&&n instanceof Ed&&typeof n.write=="function"&&typeof n.end=="function",In=Symbol("EOF"),Pn=Symbol("maybeEmitEnd"),Vn=Symbol("emittedEnd"),wa=Symbol("emittingEnd"),Oi=Symbol("emittedError"),va=Symbol("closed"),Ly=Symbol("read"),xa=Symbol("flush"),Oy=Symbol("flushChunk"),nn=Symbol("encoding"),So=Symbol("decoder"),qe=Symbol("flowing"),ki=Symbol("paused"),bo=Symbol("resume"),Ke=Symbol("buffer"),ft=Symbol("pipes"),Ye=Symbol("bufferLength"),Sd=Symbol("bufferPush"),Ta=Symbol("bufferShift"),ct=Symbol("objectMode"),ke=Symbol("destroyed"),bd=Symbol("error"),wd=Symbol("emitData"),ky=Symbol("emitEnd"),vd=Symbol("emitEnd2"),yn=Symbol("async"),xd=Symbol("abort"),Ea=Symbol("aborted"),_i=Symbol("signal"),Ar=Symbol("dataListeners"),Ot=Symbol("discarded"),Ni=n=>Promise.resolve().then(n),KR=n=>n(),YR=n=>n==="end"||n==="finish"||n==="prefinish",JR=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,XR=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),Ca=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[bo](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Td=class extends Ca{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)}},ZR=n=>!!n.objectMode,QR=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",qn=class extends Ed{[qe]=!1;[ki]=!1;[ft]=[];[Ke]=[];[ct];[nn];[yn];[So];[In]=!1;[Vn]=!1;[wa]=!1;[va]=!1;[Oi]=null;[Ye]=0;[ke]=!1;[_i];[Ea]=!1;[Ar]=0;[Ot]=!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");ZR(t)?(this[ct]=!0,this[nn]=null):QR(t)?(this[nn]=t.encoding,this[ct]=!1):(this[ct]=!1,this[nn]=null),this[yn]=!!t.async,this[So]=this[nn]?new WR(this[nn]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ke]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[ft]});let{signal:r}=t;r&&(this[_i]=r,r.aborted?this[xd]():r.addEventListener("abort",()=>this[xd]()))}get bufferLength(){return this[Ye]}get encoding(){return this[nn]}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[ct]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[yn]}set async(e){this[yn]=this[yn]||!!e}[xd](){this[Ea]=!0,this.emit("abort",this[_i]?.reason),this.destroy(this[_i]?.reason)}get aborted(){return this[Ea]}set aborted(e){}write(e,t,r){if(this[Ea])return!1;if(this[In])throw new Error("write after end");if(this[ke])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[yn]?Ni:KR;if(!this[ct]&&!Buffer.isBuffer(e)){if(XR(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(JR(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[ct]?(this[qe]&&this[Ye]!==0&&this[xa](!0),this[qe]?this.emit("data",e):this[Sd](e),this[Ye]!==0&&this.emit("readable"),r&&o(r),this[qe]):e.length?(typeof e=="string"&&!(t===this[nn]&&!this[So]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[nn]&&(e=this[So].write(e)),this[qe]&&this[Ye]!==0&&this[xa](!0),this[qe]?this.emit("data",e):this[Sd](e),this[Ye]!==0&&this.emit("readable"),r&&o(r),this[qe]):(this[Ye]!==0&&this.emit("readable"),r&&o(r),this[qe])}read(e){if(this[ke])return null;if(this[Ot]=!1,this[Ye]===0||e===0||e&&e>this[Ye])return this[Pn](),null;this[ct]&&(e=null),this[Ke].length>1&&!this[ct]&&(this[Ke]=[this[nn]?this[Ke].join(""):Buffer.concat(this[Ke],this[Ye])]);let t=this[Ly](e||null,this[Ke][0]);return this[Pn](),t}[Ly](e,t){if(this[ct])this[Ta]();else{let r=t;e===r.length||e===null?this[Ta]():typeof r=="string"?(this[Ke][0]=r.slice(e),t=r.slice(0,e),this[Ye]-=e):(this[Ke][0]=r.subarray(e),t=r.subarray(0,e),this[Ye]-=e)}return this.emit("data",t),!this[Ke].length&&!this[In]&&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[In]=!0,this.writable=!1,(this[qe]||!this[ki])&&this[Pn](),this}[bo](){this[ke]||(!this[Ar]&&!this[ft].length&&(this[Ot]=!0),this[ki]=!1,this[qe]=!0,this.emit("resume"),this[Ke].length?this[xa]():this[In]?this[Pn]():this.emit("drain"))}resume(){return this[bo]()}pause(){this[qe]=!1,this[ki]=!0,this[Ot]=!1}get destroyed(){return this[ke]}get flowing(){return this[qe]}get paused(){return this[ki]}[Sd](e){this[ct]?this[Ye]+=1:this[Ye]+=e.length,this[Ke].push(e)}[Ta](){return this[ct]?this[Ye]-=1:this[Ye]-=this[Ke][0].length,this[Ke].shift()}[xa](e=!1){do;while(this[Oy](this[Ta]())&&this[Ke].length);!e&&!this[Ke].length&&!this[In]&&this.emit("drain")}[Oy](e){return this.emit("data",e),this[qe]}pipe(e,t){if(this[ke])return e;this[Ot]=!1;let r=this[Vn];return t=t||{},e===Py.stdout||e===Py.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[ft].push(t.proxyErrors?new Td(this,e,t):new Ca(this,e,t)),this[yn]?Ni(()=>this[bo]()):this[bo]()),e}unpipe(e){let t=this[ft].find(r=>r.dest===e);t&&(this[ft].length===1?(this[qe]&&this[Ar]===0&&(this[qe]=!1),this[ft]=[]):this[ft].splice(this[ft].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[Ot]=!1,this[Ar]++,!this[ft].length&&!this[qe]&&this[bo]();else if(e==="readable"&&this[Ye]!==0)super.emit("readable");else if(YR(e)&&this[Vn])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Oi]){let o=t;this[yn]?Ni(()=>o.call(this,this[Oi])):o.call(this,this[Oi])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[Ar]=this.listeners("data").length,this[Ar]===0&&!this[Ot]&&!this[ft].length&&(this[qe]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Ar]=0,!this[Ot]&&!this[ft].length&&(this[qe]=!1)),t}get emittedEnd(){return this[Vn]}[Pn](){!this[wa]&&!this[Vn]&&!this[ke]&&this[Ke].length===0&&this[In]&&(this[wa]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[va]&&this.emit("close"),this[wa]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==ke&&this[ke])return!1;if(e==="data")return!this[ct]&&!r?!1:this[yn]?(Ni(()=>this[wd](r)),!0):this[wd](r);if(e==="end")return this[ky]();if(e==="close"){if(this[va]=!0,!this[Vn]&&!this[ke])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Oi]=r,super.emit(bd,r);let i=!this[_i]||this.listeners("error").length?super.emit("error",r):!1;return this[Pn](),i}else if(e==="resume"){let i=super.emit("resume");return this[Pn](),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[Pn](),o}[wd](e){for(let r of this[ft])r.dest.write(e)===!1&&this.pause();let t=this[Ot]?!1:super.emit("data",e);return this[Pn](),t}[ky](){return this[Vn]?!1:(this[Vn]=!0,this.readable=!1,this[yn]?(Ni(()=>this[vd]()),!0):this[vd]())}[vd](){if(this[So]){let t=this[So].end();if(t){for(let r of this[ft])r.dest.write(t);this[Ot]||super.emit("data",t)}}for(let t of this[ft])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[ct]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[ct]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[ct])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[nn]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(ke,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Ot]=!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[In])return t();let i,s,a=p=>{this.off("data",l),this.off("end",c),this.off(ke,d),t(),s(p)},l=p=>{this.off("error",a),this.off("end",c),this.off(ke,d),this.pause(),i({value:p,done:!!this[In]})},c=()=>{this.off("error",a),this.off("data",l),this.off(ke,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(ke,d),this.once("error",a),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Ot]=!1;let e=!1,t=()=>(this.pause(),this.off(bd,t),this.off(ke,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(bd,t),this.once(ke,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[ke])return e?this.emit("error",e):this.emit(ke),this;this[ke]=!0,this[Ot]=!0,this[Ke].length=0,this[Ye]=0;let t=this;return typeof t.close=="function"&&!this[va]&&t.close(),e?this.emit("error",e):this.emit(ke),this}static get isStream(){return GR}};var lI=sI.native,Di={lstatSync:nI,readdir:rI,readdirSync:oI,readlinkSync:iI,realpathSync:lI,promises:{lstat:cI,readdir:dI,readlink:pI,realpath:uI}},Uy=n=>!n||n===Di||n===aI?Di:{...Di,...n,promises:{...Di.promises,...n.promises||{}}},zy=/^\\\\\?\\([a-z]:)\\?$/i,mI=n=>n.replace(/\//g,"\\").replace(zy,"$1\\"),hI=/[\\\/]/,Vt=0,By=1,jy=2,Sn=4,$y=6,Hy=8,Rr=10,Wy=12,Gt=15,Mi=~Gt,Cd=16,Ny=32,Fi=64,rn=128,Aa=256,Ia=512,My=Fi|rn|Ia,fI=1023,Ad=n=>n.isFile()?Hy:n.isDirectory()?Sn:n.isSymbolicLink()?Rr:n.isCharacterDevice()?jy:n.isBlockDevice()?$y:n.isSocket()?Wy:n.isFIFO()?By:Vt,Dy=new Map,Ui=n=>{let e=Dy.get(n);if(e)return e;let t=n.normalize("NFKD");return Dy.set(n,t),t},Fy=new Map,Ra=n=>{let e=Fy.get(n);if(e)return e;let t=Ui(n.toLowerCase());return Fy.set(n,t),t},Pa=class extends Li{constructor(){super({max:256})}},Id=class extends Li{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},Gy=Symbol("PathScurry setAsCwd"),dt=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}#g;get atimeMs(){return this.#g}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#u;get birthtimeMs(){return this.#u}#T;get atime(){return this.#T}#f;get mtime(){return this.#f}#E;get ctime(){return this.#E}#C;get birthtime(){return this.#C}#b;#v;#x;#h;#P;#A;#n;#k;#S;#L;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=Vt,r,o,i,s,a){this.name=e,this.#b=i?Ra(e):Ui(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=Uy(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).#_(o):this.#_(o)}#_(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&=~Cd,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),o=this.nocase?Ra(e):Ui(e);for(let l of r)if(l.#b===o)return l;let i=this.parent?this.sep:"",s=this.#x?this.#x+i+e:void 0,a=this.newChild(e,Vt,{...t,parent:this,fullpath:s});return this.canReaddir()||(a.#n|=rn),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&Gt)===Vt}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&Gt)===Hy}isDirectory(){return(this.#n&Gt)===Sn}isCharacterDevice(){return(this.#n&Gt)===jy}isBlockDevice(){return(this.#n&Gt)===$y}isFIFO(){return(this.#n&Gt)===By}isSocket(){return(this.#n&Gt)===Wy}isSymbolicLink(){return(this.#n&Rr)===Rr}lstatCached(){return this.#n&Ny?this:void 0}readlinkCached(){return this.#S}realpathCached(){return this.#L}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#S)return!0;if(!this.parent)return!1;let e=this.#n&Gt;return!(e!==Vt&&e!==Rr||this.#n&Aa||this.#n&rn)}calledReaddir(){return!!(this.#n&Cd)}isENOENT(){return!!(this.#n&rn)}isNamed(e){return this.nocase?this.#b===Ra(e):this.#b===Ui(e)}async readlink(){let e=this.#S;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.#S=r}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#S;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.#S=r}catch(t){this.#d(t.code);return}}#N(e){this.#n|=Cd;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#M()}}#M(){this.#n&rn||(this.#n=(this.#n|rn)&Mi,this.#R())}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#M()}#I(){this.#n|=Ia,this.#D()}#D(){if(this.#n&Fi)return;let e=this.#n;(e&Gt)===Sn&&(e&=Mi),this.#n=e|Fi,this.#R()}#F(e=""){e==="ENOTDIR"||e==="EPERM"?this.#D():e==="ENOENT"?this.#M():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#D():e==="ENOENT"&&this.#M()}#d(e=""){let t=this.#n;t|=Aa,e==="ENOENT"&&(t|=rn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Mi),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#D()}#z(e,t){return this.#O(e,t)||this.#B(e,t)}#B(e,t){let r=Ad(e),o=this.newChild(e.name,r,{parent:this}),i=o.#n&Gt;return i!==Sn&&i!==Rr&&i!==Vt&&(o.#n|=Fi),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?Ra(e.name):Ui(e.name))===o.#b)return this.#j(e,o,r,t)}}#j(e,t,r,o){let i=t.name;return t.#n=t.#n&Mi|Ad(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&rn))try{return this.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&rn))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:f,nlink:g,rdev:y,size:v,uid:S}=e;this.#T=t,this.#g=r,this.#C=o,this.#u=i,this.#p=s,this.#o=a,this.#E=l,this.#m=c,this.#t=d,this.#w=p,this.#a=u,this.#i=m,this.#f=h,this.#y=f,this.#r=g,this.#c=y,this.#l=v,this.#s=S;let E=Ad(e);this.#n=this.#n&Mi|E|Ny,E!==Vt&&E!==Sn&&E!==Rr&&(this.#n|=Fi)}#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.#F(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.#F(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.#F(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&My)return!1;let e=Gt&this.#n;return e===Vt||e===Sn||e===Rr}shouldWalk(e,t){return(this.#n&Sn)===Sn&&!(this.#n&My)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((Ia|Aa|rn)&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(!((Ia|Aa|rn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[Gy](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}},La=class n extends dt{sep="\\";splitSep=hI;constructor(e,t=Vt,r,o,i,s,a){super(e,t,r,o,i,s,a)}newChild(e,t=Vt,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return Rd.parse(e).root}getRoot(e){if(e=mI(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 wo(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(zy,"$1\\"),e===t}},Oa=class n extends dt{splitSep="/";sep="/";constructor(e,t=Vt,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=Vt,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}},ka=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,r,{nocase:o,childrenCacheSize:i=16*1024,fs:s=Di}={}){this.#r=Uy(s),(e instanceof URL||e.startsWith("file://"))&&(e=tI(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new Pa,this.#t=new Pa,this.#i=new Id(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 f=d--;c=c.child(h,{relative:new Array(f).fill("..").join(p),relativePosix:new Array(f).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 dt||(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 dt||(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 dt||(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 dt||(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 dt||(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 dt||(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 dt||(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 f=h.length;if(!f)return u();let g=()=>{--f===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,g):g()):y.shouldWalk(l,s)?c(y,g):g()},!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 dt||(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 dt||(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 dt||(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 dt||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new qn({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=(g,y,v=!1)=>{if(g)return a.emit("error",g);if(o&&!v){let S=[];for(let E of y)E.isSymbolicLink()&&S.push(E.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(S.length){Promise.all(S).then(()=>h(null,y,!0));return}}for(let S of y)S&&(!i||i(S))&&(a.write(r?S:S.fullpath())||(u=!0));d--;for(let S of y){let E=S.realpathCached()||S;E.shouldWalk(l,s)&&c.push(E)}u&&!a.flowing?a.once("drain",p):f||p()},f=!0;m.readdirCB(h,!0),f=!1}};return p(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof dt||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new qn({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 f of h)(!i||i(f))&&(a.write(r?f:f.fullpath())||(u=!0));d--;for(let f of h){let g=f;if(f.isSymbolicLink()){if(!(o&&(g=f.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(l,s)&&c.push(g)}}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[Gy](t)}},wo=class extends ka{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Rd,"\\",{...t,nocase:r}),this.nocase=r;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return Rd.parse(e).root.toUpperCase()}newRoot(e){return new La(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)}},vo=class extends ka{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,eI,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new Oa(this.rootPath,Sn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},zi=class extends vo{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},e7=process.platform==="win32"?La:Oa,Vy=process.platform==="win32"?wo:process.platform==="darwin"?zi:vo;var gI=n=>n.length>=1,yI=n=>n.length>=1,xo=class n{#e;#t;#i;length;#r;#s;#w;#c;#p;#a;#l=!0;constructor(e,t,r,o){if(!gI(e))throw new TypeError("empty pattern list");if(!yI(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 f=[i,s,a,l,""].join("/"),g=[d,p,u,m,""].join("/");this.#e=[f,...c],this.#t=[g,...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]===tt}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 SI=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",To=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:o,noglobstar:i,platform:s=SI}){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 Lt(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 xo(o,i,0,this.platform),a=new Lt(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 Pd=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()]))}},Ld=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)])}},Od=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())}},Bi=class n{hasWalkedCache;matches=new Ld;subwalks=new Od;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Pd}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===tt){(!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===tt?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 To([n],e):Array.isArray(n)?new To(n,e):n,_a=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 Bi(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 Bi(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()}},ji=class extends _a{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}},$i=class extends _a{results;constructor(e,t,r){super(e,t,r),this.results=new qn({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 vI=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",on=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=wI(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||vI,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"?wo:t.platform==="darwin"?zi:t.platform?vo:Vy;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 Lt(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 xo(l,d,0,this.platform)})}async walk(){return[...await new ji(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 ji(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 $i(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 $i(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 kd=(n,e={})=>{Array.isArray(n)||(n=[n]);for(let t of n)if(new Lt(t,e).hasMagic())return!0;return!1};function Na(n,e={}){return new on(n,e).streamSync()}function Yy(n,e={}){return new on(n,e).stream()}function Eo(n,e={}){return new on(n,e).walkSync()}async function qy(n,e={}){return new on(n,e).walk()}function Ma(n,e={}){return new on(n,e).iterateSync()}function Jy(n,e={}){return new on(n,e).iterate()}var xI=Na,TI=Object.assign(Yy,{sync:Na}),EI=Ma,CI=Object.assign(Jy,{sync:Ma}),AI=Object.assign(Eo,{stream:Na,iterate:Ma}),Ky=Object.assign(qy,{glob:qy,globSync:Eo,sync:AI,globStream:Yy,stream:TI,globStreamSync:Na,streamSync:xI,globIterate:Jy,iterate:CI,globIterateSync:Ma,iterateSync:EI,Glob:on,hasMagic:kd,escape:fo,unescape:tn});Ky.glob=Ky;import NI from"os";import Kn,{dirname as eS}from"path";import{cwd as Dd}from"process";import tS from"yaml";import{z as Pe}from"zod";import Xy from"fs";import Da from"path";import RI from"yaml";import{z as _d}from"zod";var Zy=!1,Hi=[`**/*.${En.TEST}`,`**/*.${En.MODULE}`],Nd=_d.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),Md=50,II=_d.object({fileType:_d.nativeEnum(xe)});function nt(n,e){let t={project:n,tests:{},modules:{}},r=n.config.include??Hi,o=Array.from(n.config.exclude??[]).concat(hm),i=Eo(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:Md,nodir:!0});for(let s of i)PI(n.rootDir,s,t,e);return Zy=!0,t}function PI(n,e,t,r){let o=Da.join(n,e),i;try{i=Xy.readFileSync(o,"utf-8")}catch(p){r.warn(`Could not read possible Momentic file at ${o}, skipping: ${p}`);return}let s;try{if(s=RI.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=II.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=Xy.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:Da.sep,fullPathSegments:o.split(Da.sep),fileName:Da.basename(o),lastModified:c.mtime,createdAt:c.birthtime};switch(l){case xe.TEST:try{let p=dn.parse(s);if(t.tests[p.id]){let u=t.tests[p.id].fullFilePath;b.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
 
2980
- Second test path: ${o}`)}t.tests[p.id]={type:xe.TEST,name:p.name,id:p.id,description:p.description??void 0,labels:p.labels,...d};return}catch(p){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${p}`);return}case xe.MODULE:try{let p=bt.parse(s);t.modules[p.moduleId]={type:xe.MODULE,name:p.name,id:p.moduleId,...d};let u=d.fileName.replace(".module.yaml","");!Zy&&Pe(p.name)!==u&&r.warn(`The module with ID ${p.moduleId} has a name (${p.name}) that does not match its file name (${u}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`);return}catch(p){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${p}`);return}default:r.warn(`Unsupported file type ${l}, skipping...`);return}}var Co="momentic.config.yaml",Qy="momentic.workspace.yaml",MI=Ee.object({projects:Ee.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),DI=Ee.union([Ee.string(),Ee.object({fromFile:Ee.string(),json:Ee.boolean().optional()})]),FI=Ee.object({name:Nd,baseUrl:Ee.string(),envFile:Ee.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ee.record(Ee.string(),DI).optional(),inheritFromShell:Ee.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:ms.optional().transform(n=>n&&(n.localChromeExtensionPaths&&(n.localChromeExtensionPaths=n.localChromeExtensionPaths.map(e=>e.startsWith("~")?Kn.join(NI.homedir(),e.slice(1)):e)),n))}),UI=Ee.object({name:Nd,include:Ee.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ee.string().array().optional().describe("opposite of include, takes precedence over include"),moduleCreationDir:Ee.string().optional(),testCreationDir:Ee.string().optional(),goldenFileDir:Ee.string().optional(),reporterDir:Ee.string().optional(),retries:Ee.number().optional().describe("number of retries per test"),parallel:Ee.number().optional().describe("degree of parallelism"),browser:ms.optional(),environments:Ee.array(FI).optional(),ai:lc.optional()});function nS(n,e){let t;try{t=OI(n,"utf-8")}catch(o){b.warn(`Could not read possible Momentic ${e} file at ${n}: ${o}`);return}let r;try{if(r=tS.parse(t),typeof r!="object"||r===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof r} instead`)}catch(o){b.warn(`Possible Momentic ${e} file at ${n} does not parse as valid YAML: ${o}`);return}return r}function Fd(n){let e=nS(n,"project configuration");if(e!==void 0)try{return UI.parse(e)}catch(t){b.warn(`Possible Momentic project configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function zI(n){let e=nS(n,"workspace configuration");if(e!==void 0)try{return MI.parse(e)}catch(t){b.warn(`Possible Momentic workspace configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function BI(){let n=[],e=Dd(),t=Kn.parse(e).root,r=15,o=0;for(;o<r;){o++;let i=Kn.basename(e);if(ui.includes(i))return b.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),n;for(let s of kI(e))if(s.endsWith(Co)){let a=Kn.join(e,s),l=Fd(a);l&&n.push({configFilePath:a,config:l,rootDir:eS(a)})}if(n.length)return n;if(e=Kn.dirname(e),e===t)break}return n}function bn(n={}){let{configFilePath:e,nameFilter:t}=n,r=Ud(e);if(t&&(r=r.filter(o=>o.config.name===t)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
2981
- ${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return b.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function jI(n){let e=zI(n);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${Co}`)),r=Eo(t,{absolute:!1,cwd:Dd(),dotRelative:!1,maxDepth:Md,nodir:!0}),o=[];for(let i of r){let s=Kn.join(Dd(),i),a=Fd(s);a&&o.push({configFilePath:s,config:a,rootDir:eS(s)})}return o}function Ud(n){if(n){n=Kn.resolve(n);let t=Fd(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:Kn.dirname(n)}]}if(LI(Qy)){let t=jI(Qy);if(t)return t}return BI()}function Ao(n,e){let t=tS.stringify(n);_I(e,t)}import Ro from"fs";import zd from"path";import{z as Bd}from"zod";var $I=Bd.object({width:Bd.number(),height:Bd.number()}),Io=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=zd.join(e.rootDir,e.config.goldenFileDir??"golden/visual-diff");this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,r){if(t.screenshot?.data?.startsWith("https://")){let s=await fetch(t.screenshot.data);return{buffer:Buffer.from(await s.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=zd.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return Ro.mkdirSync(zd.dirname(o),{recursive:!0}),Ro.writeFileSync(o,r.buffer),Ro.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(Ro.existsSync(o)){let s=Ro.readFileSync(o),a=$I.parse(JSON.parse(Ro.readFileSync(i,"utf-8")));return{buffer:s,width:a.width,height:a.height}}else throw new A("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};import Wd from"fs";import qI from"path";import oS,{multistream as HI}from"pino";import WI from"pino-pretty";var rS=["lastScreenshotBuffer"];var jd=new Map,GI=!0,$d=class n{consoleLogger;ddClientToken;hostname;bindingAttributes;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:r,disableConsoleLogs:o}){this.ddClientToken=t,this.hostname=r,this.disableConsoleLogs=o,this.bindingAttributes={...e,env:"production"};let i={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=GI?oS(i):oS(i,HI([{stream:WI({colorize:!0})}]))}child(e){return new n({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,r,...o){if(t&&r===void 0&&(r=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},r,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let s={};for(let a of Object.getOwnPropertyNames(t.err))rS.includes(a)||(s[a]=t.err[a]);s.name=t.err.name,t.err=s}let i=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(i.args=o),(async()=>{try{let s=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,ddtags:["env:production"],hostname:this.hostname??"vercel",service:"momentic",message:{message:r||"",...i,level:e}}])});if(!s.ok)throw new Error(`Failed to log to Datadog: ${s.statusText})}`)}catch(s){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:r,args:o,err:s},"Failed to log to Datadog")}})()}debug(e,t,...r){this.log("debug",e,t,...r)}info(e,t,...r){this.log("info",e,t,...r)}warn(e,t,...r){this.log("warn",e,t,...r)}error(e,t,...r){this.log("error",e,t,...r)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},Fa=({app:n,clientToken:e,hostname:t,disableConsoleLogs:r})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return jd.has(n)||jd.set(n,new $d({bindings:{app:n},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,disableConsoleLogs:r})),jd.get(n)};import{hostname as VI}from"os";var Ce=Fa({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:VI(),disableConsoleLogs:!0}),iS=n=>{Ce.addBinding("version",n)};var KI=new la(10,60*1e3),qd="https://api.momentic.ai",Kd,Hd,sS=n=>{qd=n},Ua=()=>qd,aS=(n,e)=>{Kd=n,Hd?.abort(),Hd=new AbortController;let t=Hd.signal,r=[n.configFilePath];n.config.environments?.forEach(o=>{if(!o.envFile)return;let i=qI.resolve(n.rootDir,o.envFile);try{if(Wd.lstatSync(i).isSymbolicLink())return;Wd.existsSync(i)&&r.push(i)}catch(s){Ce.warn({err:s},`Failed to check if env file ${i} exists`)}});try{YI({filesToWatch:r,revalidator:e,signal:t,project:n})}catch(o){Ce.error({err:o},"Failed to start config file watchers")}},ye=()=>Kd,Po,Gd,Vd,lS=async n=>{if(Po)return Po;let e=new lt({baseUrl:qd,apiKey:n});try{let t=await e.getAuthInfo();return Po=t.orgId,Gd=t.userId,Vd=n,Po}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Lo=()=>{if(!Po)throw new Error("Your organization ID appears invalid. Please contact Momentic support.");return Po},cS=()=>{if(!Gd)throw new Error("Your user ID appears invalid. Please contact Momentic support.");return Gd},dS=()=>{if(!Vd)throw new Error("Your API key appears invalid. Please contact Momentic support.");return Vd};function YI({filesToWatch:n,revalidator:e,signal:t,project:r}){n.forEach(o=>{Wd.watch(o,{signal:t,persistent:!1,recursive:!1},(i,s)=>{s&&(KI.increment("setLocalProject")&&b.warn(`A file change under the ${r.rootDir} directory has caused Momentic to reload its configuration more than 10 times in the last minute. Please avoid making rapid changes to files in this directory as this may cause performance issues.`),Kd=e(r.configFilePath))})})}function _e(n){return function(...e){let t=e[e.length-1],r=n(...e);Promise.resolve(r).catch(t)}}var pS=JI();pS.get("/",_e((n,e)=>{let t=Qg(ye(),Ce);e.status(200).json(t)}));var uS=pS;import{Router as XI}from"express";var za=class extends Zr{constructor(t,r){super(t,r);this.client=t;this.orgId=r}async getOrgId(t){return this.orgId}async fetchTestMetadata(t,r,o){let i=ye(),a=nt(i,o).tests[t];if(a)return ga(a.relativePath,i)}async fetchApiTestMetadata(t,r,o){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(t,r,o){let i=ye();return Ai(r,i,mi)}};var mS=XI();mS.get("/",_e((n,e)=>{let t=ye(),r=nt(t,b),o=new Set;r?.tests&&Object.values(r.tests).forEach(s=>{s.labels?.forEach(a=>o.add(a))});let i=Array.from(o).sort();e.status(200).json(i)}));var hS=mS;import{Router as ZI}from"express";import fS from"fs";import gS from"path";var Ba=ZI();Ba.get("/",_e(async(n,e)=>{let t=ye(),r=nt(t,b),i=(await fa(r,Ce)).filter(s=>s.enabled!==!1).map(s=>{let a=r.modules[s.moduleId];if(!a){b.warn(`Found a dangling module with ID ${s.moduleId} that could not be found on disk.`);return}return{...a,content:s}}).filter(s=>s!==void 0);e.status(200).json(i)}));Ba.post("/",_e(async(n,e)=>{let t;try{t=pm.parse(n.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}try{ai(t.name)}catch(a){e.status(400).json({error:`Invalid module name: ${a}`});return}let r=ye(),o=nt(r,b).modules;if(Object.values(o).find(a=>a.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=gS.join(r.rootDir,r.config.moduleCreationDir??gS.dirname(t.testFilePath));if(!fS.existsSync(i)||!fS.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let s=await Yg({...t,folder:i});e.status(201).json(s)}));Ba.get("/:moduleId",_e(async(n,e)=>{if(!n.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=nt(ye(),b),r=t.modules[n.params.moduleId];if(!r){e.status(404).json({error:"Module not found."});return}try{let o=await cd(r,t,b);e.json(o)}catch(o){e.status(400).json({err:o})}}));var yS=Ba;import{Router as QI}from"express";var ja=QI();ja.get("/",_e((n,e)=>{let t=Ud().map(r=>({name:r.config.name,configFilePath:r.configFilePath}));e.status(200).json(t)}));ja.get("/current",_e((n,e)=>{let t=ye(),r={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(r)}));ja.post("/set",_e((n,e)=>{let t;try{t=mm.parse(n.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}try{let r=bn({configFilePath:t.configFilePath});aS(r,o=>bn({configFilePath:o}))}catch(r){e.status(400).json({error:`Error setting project: ${r}`});return}e.sendStatus(204)}));var SS=ja;import{Router as eP}from"express";var bS=eP();bS.get("/",_e((n,e)=>{let r={ai:ye().config.ai};e.status(200).json(r)}));var wS=bS;import{Router as nP}from"express";import Yd from"path";import{v4 as rP}from"uuid";import{PostHog as tP}from"posthog-node";var $a=class{identify(){return this}child(){return this}track(){return this}async shutdown(){}},Oo=class n{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new tP("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new n({...this.bindings,...e},this.options)}track(e){if(!Hu(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:t,...r}=e;return this.client.capture({distinctId:this.bindings.user_id,event:t,properties:{...this.bindings,...r}}),this}};var Wi=new Oo({platform:"local_app"},{flushAt:1,flushInterval:0});var Ir=nP();function vS(n){let e=nt(n,b);return Object.values(e.tests)}Ir.get("/",_e((n,e)=>{let t=vS(ye());e.status(200).json(t)}));Ir.post("/",_e(async(n,e)=>{let t;try{t=dm.parse(n.body)}catch(d){e.status(400).json({error:`Invalid request body: ${d}`});return}try{ai(t.name)}catch(d){e.status(400).json({error:d.message});return}let o={id:rP(),name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:ut,advanced:{disableAICaching:!1,browserType:t.browserType??"Chromium",viewport:t.viewport??Yt},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let i=ye();if(vS(i).find(d=>d.name===t.name)){e.status(400).send(`A test with the name "${t.name}" already exists. Please use a different name.`);return}let a=Yd.join(i.rootDir,t.folderPath??i.config.testCreationDir??""),l=await Jg({test:o,name:t.name,folder:a}),c={...o,relativeFilePath:Yd.relative(i.rootDir,l)};Wi.track({type:"test_editor:test_create"}),e.status(201).json(c)}));Ir.get("/:testPath",_e(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r=ye(),o=nt(r,b),i;try{i=await ya(Yd.join(r.rootDir,t),Ce,o),e.status(200).json(i)}catch(s){e.status(400).send({error:s.message});return}(async()=>{try{let{stepsToSave:s,moduleUpdates:a}=await It({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});a.forEach(l=>{ld(l,ut,o)}),Ci(t,s,ut,r)}catch(s){Ce.error({err:s},"Failed to save migrated test to disk after initial fetch")}})()}));Ir.patch("/:testPath/metadata",_e(async(n,e)=>{if(!n.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=cm.parse(n.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}dd(n.params.testPath,t,ye()),e.status(201).json({message:"ok"})}));Ir.patch("/:testPath",_e(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=lm.parse(n.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}let o=ye(),i=nt(o,b),s;try{s=ga(t,o)}catch(p){e.status(400).json({error:`Existing test file on disk is invalid: ${p}`});return}let{stepsToSave:a,moduleUpdates:l,cachesToSave:c}=await It({stepLists:r.stepLists,cacheCreationParams:{testId:s.id,orgId:Lo()}});await new lt({apiKey:dS(),baseUrl:Ua()}).updateStepCaches({entries:c,testId:s.id}),l.forEach(p=>{ld(p,r.schemaVersion,i)}),Ci(t,a,r.schemaVersion,o),e.status(201).json({message:"ok"})}));Ir.patch("/:testPath/environments",_e(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=um.parse(n.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}dd(t,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},ye()),e.status(201).json({message:"ok"})}));var xS=Ir;var Gi=class{async prepareGoldenScreenshotForComparison(e,t,r){return await new Io(ye(),!1).prepareGoldenScreenshotForComparison(e,t,r)}};async function AS(n){let{momenticServerUrl:e,apiKey:t,serverPort:r,staticDir:o,devicePixelRatio:i,version:s}=n;iS(s),e&&sS(e),Ce.debug(n,"Initializing desktop server"),await lS(t);let a=Lo(),l=cS();Wi.identify({user_id:l,org_id:a}),Ce.debug({orgId:a,userId:l},"Checking API key successful");let c=cP(o,r),d=`http://localhost:${r}`;b.info(`Desktop server is running at ${d}`),await new Promise(v=>{try{c.listen(r,()=>{Ce.info(`Desktop server is running at ${d}`),v()})}catch(S){S.message.includes("EADDRINUSE")?RS(r):b.error(`An unexpected error occurred while starting the server: ${S.message}`),process.exit(1)}});let u={type:"API_KEY",baseUrl:Ua(),apiKey:t,logger:Ce},m=new eo(u),h=new lt(u),f=new za(h,Lo()),g=new Jr(h,Lo()),y=new Gi;Kg({baseServer:c,generatorFactory:async()=>m,storage:f,debugDataStorage:g,logger:Ce,devicePixelRatio:i,authorization:u,visualDiffScreenshotStorage:y,analytics:Wi})}var CS="25mb";function cP(n,e){let t=ES();t.use(oP()),t.use(TS.json({limit:CS})),t.use(TS.urlencoded({extended:!1,limit:CS}));let r=aP();if(r.use("/tests",xS),r.use("/modules",yS),r.use("/environments",uS),r.use("/projects",SS),r.use("/labels",hS),r.use("/settings",wS),t.use("/api",r),t.use((i,s,a)=>{i.path!=="/healthcheck"&&Ce.debug({url:i.url,path:i.path,query:i.query,method:i.method,body:i.body,headers:i.rawHeaders,client:i.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&Ce.error({url:i.url,method:i.method,statusCode:s.statusCode},"Request completed in error")}),a()}),t.use((i,s,a,l)=>{if(i instanceof Error&&i.message.includes("BadRequestError: request aborted")){a.status(400).send("Client disconnected");return}Ce.error({stack:i.stack,msg:i.message,err:i,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),b.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${i.message}
2982
- ${i.stack}`),a.status(500).send("Internal Server Error")}),n){let i=ES.static(n);t.use("/",i),t.use("*",i)}let o=lP.createServer(t);return o.once("error",i=>{"code"in i&&i.code==="EADDRINUSE"?(RS(e),process.exit(1)):console.error("An unexpected server error occurred:",i.message)}),o}sP.setMaxListeners(50);process.on("warning",n=>{Ce.warn({err:n},`Node warning received on desktop-server: ${n.message}`)});process.on("uncaughtException",n=>{Ce.error({err:n},"Uncaught exception leading to exit on desktop-server"),b.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${n.message}`)});process.on("unhandledRejection",(n,e)=>{Ce.error({reason:`${n}`,promise:`${e}`,stack:n?.stack},"Uncaught exception leading to exit on desktop-server (promise rejection)"),b.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${n}`)});function RS(n){b.error(iP`Port ${n} is already in use by another process. Please close the other process and try again.
2980
+ Second test path: ${o}`)}t.tests[p.id]={type:xe.TEST,name:p.name,id:p.id,description:p.description??void 0,labels:p.labels,...d};return}catch(p){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${p}`);return}case xe.MODULE:try{let p=bt.parse(s);t.modules[p.moduleId]={type:xe.MODULE,name:p.name,id:p.moduleId,...d};let u=d.fileName.replace(".module.yaml","");!Zy&&Ie(p.name)!==u&&r.warn(`The module with ID ${p.moduleId} has a name (${p.name}) that does not match its file name (${u}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`);return}catch(p){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${p}`);return}default:r.warn(`Unsupported file type ${l}, skipping...`);return}}var Co="momentic.config.yaml",Qy="momentic.workspace.yaml",MI=Pe.object({projects:Pe.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),DI=Pe.union([Pe.string(),Pe.object({fromFile:Pe.string(),json:Pe.boolean().optional()})]),FI=Pe.object({name:Nd,baseUrl:Pe.string(),envFile:Pe.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Pe.record(Pe.string(),DI).optional(),inheritFromShell:Pe.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:ms.optional().transform(n=>n&&(n.localChromeExtensionPaths&&(n.localChromeExtensionPaths=n.localChromeExtensionPaths.map(e=>e.startsWith("~")?Kn.join(NI.homedir(),e.slice(1)):e)),n))}),UI=Pe.object({name:Nd,include:Pe.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Pe.string().array().optional().describe("opposite of include, takes precedence over include"),moduleCreationDir:Pe.string().optional(),goldenFileDir:Pe.string().optional(),reporterDir:Pe.string().optional(),retries:Pe.number().optional().describe("number of retries per test"),parallel:Pe.number().optional().describe("degree of parallelism"),browser:ms.optional(),environments:Pe.array(FI).optional(),ai:lc.optional()});function nS(n,e){let t;try{t=OI(n,"utf-8")}catch(o){b.warn(`Could not read possible Momentic ${e} file at ${n}: ${o}`);return}let r;try{if(r=tS.parse(t),typeof r!="object"||r===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof r} instead`)}catch(o){b.warn(`Possible Momentic ${e} file at ${n} does not parse as valid YAML: ${o}`);return}return r}function Fd(n){let e=nS(n,"project configuration");if(e!==void 0)try{return UI.parse(e)}catch(t){b.warn(`Possible Momentic project configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function zI(n){let e=nS(n,"workspace configuration");if(e!==void 0)try{return MI.parse(e)}catch(t){b.warn(`Possible Momentic workspace configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function BI(){let n=[],e=Dd(),t=Kn.parse(e).root,r=15,o=0;for(;o<r;){o++;let i=Kn.basename(e);if(ui.includes(i))return b.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),n;for(let s of kI(e))if(s.endsWith(Co)){let a=Kn.join(e,s),l=Fd(a);l&&n.push({configFilePath:a,config:l,rootDir:eS(a)})}if(n.length)return n;if(e=Kn.dirname(e),e===t)break}return n}function bn(n={}){let{configFilePath:e,nameFilter:t}=n,r=Ud(e);if(t&&(r=r.filter(o=>o.config.name===t)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
2981
+ ${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return b.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function jI(n){let e=zI(n);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${Co}`)),r=Eo(t,{absolute:!1,cwd:Dd(),dotRelative:!1,maxDepth:Md,nodir:!0}),o=[];for(let i of r){let s=Kn.join(Dd(),i),a=Fd(s);a&&o.push({configFilePath:s,config:a,rootDir:eS(s)})}return o}function Ud(n){if(n){n=Kn.resolve(n);let t=Fd(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:Kn.dirname(n)}]}if(LI(Qy)){let t=jI(Qy);if(t)return t}return BI()}function Ao(n,e){let t=tS.stringify(n);_I(e,t)}import Ro from"fs";import zd from"path";import{z as Bd}from"zod";var $I=Bd.object({width:Bd.number(),height:Bd.number()}),Io=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=zd.join(e.rootDir,e.config.goldenFileDir??"golden/visual-diff");this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,r){if(t.screenshot?.data?.startsWith("https://")){let s=await fetch(t.screenshot.data);return{buffer:Buffer.from(await s.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=zd.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return Ro.mkdirSync(zd.dirname(o),{recursive:!0}),Ro.writeFileSync(o,r.buffer),Ro.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(Ro.existsSync(o)){let s=Ro.readFileSync(o),a=$I.parse(JSON.parse(Ro.readFileSync(i,"utf-8")));return{buffer:s,width:a.width,height:a.height}}else throw new A("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};import Wd from"fs";import qI from"path";import oS,{multistream as HI}from"pino";import WI from"pino-pretty";var rS=["lastScreenshotBuffer"];var jd=new Map,GI=!0,$d=class n{consoleLogger;ddClientToken;hostname;bindingAttributes;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:r,disableConsoleLogs:o}){this.ddClientToken=t,this.hostname=r,this.disableConsoleLogs=o,this.bindingAttributes={...e,env:"production"};let i={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=GI?oS(i):oS(i,HI([{stream:WI({colorize:!0})}]))}child(e){return new n({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,r,...o){if(t&&r===void 0&&(r=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},r,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let s={};for(let a of Object.getOwnPropertyNames(t.err))rS.includes(a)||(s[a]=t.err[a]);s.name=t.err.name,t.err=s}let i=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(i.args=o),(async()=>{try{let s=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,ddtags:["env:production"],hostname:this.hostname??"vercel",service:"momentic",message:{message:r||"",...i,level:e}}])});if(!s.ok)throw new Error(`Failed to log to Datadog: ${s.statusText})}`)}catch(s){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:r,args:o,err:s},"Failed to log to Datadog")}})()}debug(e,t,...r){this.log("debug",e,t,...r)}info(e,t,...r){this.log("info",e,t,...r)}warn(e,t,...r){this.log("warn",e,t,...r)}error(e,t,...r){this.log("error",e,t,...r)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},Fa=({app:n,clientToken:e,hostname:t,disableConsoleLogs:r})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return jd.has(n)||jd.set(n,new $d({bindings:{app:n},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,disableConsoleLogs:r})),jd.get(n)};import{hostname as VI}from"os";var Ee=Fa({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:VI(),disableConsoleLogs:!0}),iS=n=>{Ee.addBinding("version",n)};var KI=new la(10,60*1e3),qd="https://api.momentic.ai",Kd,Hd,sS=n=>{qd=n},Ua=()=>qd,aS=(n,e)=>{Kd=n,Hd?.abort(),Hd=new AbortController;let t=Hd.signal,r=[n.configFilePath];n.config.environments?.forEach(o=>{if(!o.envFile)return;let i=qI.resolve(n.rootDir,o.envFile);try{if(Wd.lstatSync(i).isSymbolicLink())return;Wd.existsSync(i)&&r.push(i)}catch(s){Ee.warn({err:s},`Failed to check if env file ${i} exists`)}});try{YI({filesToWatch:r,revalidator:e,signal:t,project:n})}catch(o){Ee.error({err:o},"Failed to start config file watchers")}},ye=()=>Kd,Po,Gd,Vd,lS=async n=>{if(Po)return Po;let e=new lt({baseUrl:qd,apiKey:n});try{let t=await e.getAuthInfo();return Po=t.orgId,Gd=t.userId,Vd=n,Po}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Lo=()=>{if(!Po)throw new Error("Your organization ID appears invalid. Please contact Momentic support.");return Po},cS=()=>{if(!Gd)throw new Error("Your user ID appears invalid. Please contact Momentic support.");return Gd},dS=()=>{if(!Vd)throw new Error("Your API key appears invalid. Please contact Momentic support.");return Vd};function YI({filesToWatch:n,revalidator:e,signal:t,project:r}){n.forEach(o=>{Wd.watch(o,{signal:t,persistent:!1,recursive:!1},(i,s)=>{s&&(KI.increment("setLocalProject")&&b.warn(`A file change under the ${r.rootDir} directory has caused Momentic to reload its configuration more than 10 times in the last minute. Please avoid making rapid changes to files in this directory as this may cause performance issues.`),Kd=e(r.configFilePath))})})}function _e(n){return function(...e){let t=e[e.length-1],r=n(...e);Promise.resolve(r).catch(t)}}var pS=JI();pS.get("/",_e((n,e)=>{let t=Qg(ye(),Ee);e.status(200).json(t)}));var uS=pS;import{Router as XI}from"express";var za=class extends Zr{constructor(t,r){super(t,r);this.client=t;this.orgId=r}async getOrgId(t){return this.orgId}async fetchTestMetadata(t,r,o){let i=ye(),a=nt(i,o).tests[t];if(a)return ga(a.relativePath,i)}async fetchApiTestMetadata(t,r,o){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(t,r,o){let i=ye();return Ai(r,i,mi)}};var mS=XI();mS.get("/",_e((n,e)=>{let t=ye(),r=nt(t,b),o=new Set;r?.tests&&Object.values(r.tests).forEach(s=>{s.labels?.forEach(a=>o.add(a))});let i=Array.from(o).sort();e.status(200).json(i)}));var hS=mS;import{Router as ZI}from"express";import fS from"fs";import gS from"path";var Ba=ZI();Ba.get("/",_e(async(n,e)=>{let t=ye(),r=nt(t,b),i=(await fa(r,Ee)).filter(s=>s.enabled!==!1).map(s=>{let a=r.modules[s.moduleId];if(!a){b.warn(`Found a dangling module with ID ${s.moduleId} that could not be found on disk.`);return}return{...a,content:s}}).filter(s=>s!==void 0);e.status(200).json(i)}));Ba.post("/",_e(async(n,e)=>{let t;try{t=pm.parse(n.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}try{ai(t.name)}catch(a){e.status(400).json({error:`Invalid module name: ${a}`});return}let r=ye(),o=nt(r,b).modules;if(Object.values(o).find(a=>a.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=gS.join(r.rootDir,r.config.moduleCreationDir??gS.dirname(t.testFilePath));if(!fS.existsSync(i)||!fS.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let s=await Yg({...t,folder:i});e.status(201).json(s)}));Ba.get("/:moduleId",_e(async(n,e)=>{if(!n.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=nt(ye(),b),r=t.modules[n.params.moduleId];if(!r){e.status(404).json({error:"Module not found."});return}try{let o=await cd(r,t,b);e.json(o)}catch(o){e.status(400).json({err:o})}}));var yS=Ba;import{Router as QI}from"express";var ja=QI();ja.get("/",_e((n,e)=>{let t=Ud().map(r=>({name:r.config.name,configFilePath:r.configFilePath}));e.status(200).json(t)}));ja.get("/current",_e((n,e)=>{let t=ye(),r={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(r)}));ja.post("/set",_e((n,e)=>{let t;try{t=mm.parse(n.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}try{let r=bn({configFilePath:t.configFilePath});aS(r,o=>bn({configFilePath:o}))}catch(r){e.status(400).json({error:`Error setting project: ${r}`});return}e.sendStatus(204)}));var SS=ja;import{Router as eP}from"express";var bS=eP();bS.get("/",_e((n,e)=>{let r={ai:ye().config.ai};e.status(200).json(r)}));var wS=bS;import{Router as nP}from"express";import Yd from"path";import{v4 as rP}from"uuid";import{PostHog as tP}from"posthog-node";var $a=class{identify(){return this}child(){return this}track(){return this}async shutdown(){}},Oo=class n{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new tP("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new n({...this.bindings,...e},this.options)}track(e){if(!Hu(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:t,...r}=e;return this.client.capture({distinctId:this.bindings.user_id,event:t,properties:{...this.bindings,...r}}),this}};var Wi=new Oo({platform:"local_app"},{flushAt:1,flushInterval:0});var Ir=nP();function vS(n){let e=nt(n,b);return Object.values(e.tests)}Ir.get("/",_e((n,e)=>{let t=vS(ye());e.status(200).json(t)}));Ir.post("/",_e(async(n,e)=>{let t;try{t=dm.parse(n.body)}catch(d){e.status(400).json({error:`Invalid request body: ${d}`});return}try{ai(t.name)}catch(d){e.status(400).json({error:d.message});return}let o={id:rP(),name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:ut,advanced:{disableAICaching:!1,browserType:t.browserType??"Chromium",viewport:t.viewport??Yt},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let i=ye();if(vS(i).find(d=>d.name===t.name)){e.status(400).send(`A test with the name "${t.name}" already exists. Please use a different name.`);return}let a=Yd.join(i.rootDir,t.folderPath??""),l=await Jg({test:o,name:t.name,folder:a}),c={...o,relativeFilePath:Yd.relative(i.rootDir,l)};Wi.track({type:"test_editor:test_create"}),e.status(201).json(c)}));Ir.get("/:testPath",_e(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r=ye(),o=nt(r,b),i;try{i=await ya(Yd.join(r.rootDir,t),Ee,o),e.status(200).json(i)}catch(s){e.status(400).send({error:s.message});return}(async()=>{try{let{stepsToSave:s,moduleUpdates:a}=await It({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});a.forEach(l=>{ld(l,ut,o)}),Ci(t,s,ut,r)}catch(s){Ee.error({err:s},"Failed to save migrated test to disk after initial fetch")}})()}));Ir.patch("/:testPath/metadata",_e(async(n,e)=>{if(!n.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=cm.parse(n.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}dd(n.params.testPath,t,ye()),e.status(201).json({message:"ok"})}));Ir.patch("/:testPath",_e(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=lm.parse(n.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}let o=ye(),i=nt(o,b),s;try{s=ga(t,o)}catch(p){e.status(400).json({error:`Existing test file on disk is invalid: ${p}`});return}let{stepsToSave:a,moduleUpdates:l,cachesToSave:c}=await It({stepLists:r.stepLists,cacheCreationParams:{testId:s.id,orgId:Lo()}});await new lt({apiKey:dS(),baseUrl:Ua()}).updateStepCaches({entries:c,testId:s.id}),l.forEach(p=>{ld(p,r.schemaVersion,i)}),Ci(t,a,r.schemaVersion,o),e.status(201).json({message:"ok"})}));Ir.patch("/:testPath/environments",_e(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=um.parse(n.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}dd(t,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},ye()),e.status(201).json({message:"ok"})}));var xS=Ir;var Gi=class{async prepareGoldenScreenshotForComparison(e,t,r){return await new Io(ye(),!1).prepareGoldenScreenshotForComparison(e,t,r)}};async function AS(n){let{momenticServerUrl:e,apiKey:t,serverPort:r,staticDir:o,devicePixelRatio:i,version:s}=n;iS(s),e&&sS(e),Ee.debug(n,"Initializing desktop server"),await lS(t);let a=Lo(),l=cS();Wi.identify({user_id:l,org_id:a}),Ee.debug({orgId:a,userId:l},"Checking API key successful");let c=cP(o,r),d=`http://localhost:${r}`;b.info(`Desktop server is running at ${d}`),await new Promise(v=>{try{c.listen(r,()=>{Ee.info(`Desktop server is running at ${d}`),v()})}catch(S){S.message.includes("EADDRINUSE")?RS(r):b.error(`An unexpected error occurred while starting the server: ${S.message}`),process.exit(1)}});let u={type:"API_KEY",baseUrl:Ua(),apiKey:t,logger:Ee},m=new eo(u),h=new lt(u),f=new za(h,Lo()),g=new Jr(h,Lo()),y=new Gi;Kg({baseServer:c,generatorFactory:async()=>m,storage:f,debugDataStorage:g,logger:Ee,devicePixelRatio:i,authorization:u,visualDiffScreenshotStorage:y,analytics:Wi})}var CS="25mb";function cP(n,e){let t=ES();t.use(oP()),t.use(TS.json({limit:CS})),t.use(TS.urlencoded({extended:!1,limit:CS}));let r=aP();if(r.use("/tests",xS),r.use("/modules",yS),r.use("/environments",uS),r.use("/projects",SS),r.use("/labels",hS),r.use("/settings",wS),t.use("/api",r),t.use((i,s,a)=>{i.path!=="/healthcheck"&&Ee.debug({url:i.url,path:i.path,query:i.query,method:i.method,body:i.body,headers:i.rawHeaders,client:i.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&Ee.error({url:i.url,method:i.method,statusCode:s.statusCode},"Request completed in error")}),a()}),t.use((i,s,a,l)=>{if(i instanceof Error&&i.message.includes("BadRequestError: request aborted")){a.status(400).send("Client disconnected");return}Ee.error({stack:i.stack,msg:i.message,err:i,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),b.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${i.message}
2982
+ ${i.stack}`),a.status(500).send("Internal Server Error")}),n){let i=ES.static(n);t.use("/",i),t.use("*",i)}let o=lP.createServer(t);return o.once("error",i=>{"code"in i&&i.code==="EADDRINUSE"?(RS(e),process.exit(1)):console.error("An unexpected server error occurred:",i.message)}),o}sP.setMaxListeners(50);process.on("warning",n=>{Ee.warn({err:n},`Node warning received on desktop-server: ${n.message}`)});process.on("uncaughtException",n=>{Ee.error({err:n},"Uncaught exception leading to exit on desktop-server"),b.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${n.message}`)});process.on("unhandledRejection",(n,e)=>{Ee.error({reason:`${n}`,promise:`${e}`,stack:n?.stack},"Uncaught exception leading to exit on desktop-server (promise rejection)"),b.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${n}`)});function RS(n){b.error(iP`Port ${n} is already in use by another process. Please close the other process and try again.
2983
2983
  Using Bash on MacOS or Linux:
2984
2984
  lsof -t -i :58888 | xargs kill -9
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 SL from"events";import Rb from"fs";import bL from"open";import il from"path";import{fileURLToPath as wL}from"url";import RP from"diff-lines";import{gt as IP}from"semver";import{execSync as dP}from"child_process";import{platform as pP}from"os";function Jd(){return IS()?(b.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),b.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),b.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(b.info("Setting device pixel ratio to 1."),b.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),b.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function IS(){return pP()==="darwin"&&dP("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Xd(n){IS()&&n===1&&(b.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),b.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import uP from"@actions/exec";import mP from"@actions/io";import hP from"quote";import fP from"string-argv";async function PS(n,e=!0){let t=fP(n),r=await mP.which(t[0],!0),o=t.slice(1),i=uP.exec(hP(r),o,{delay:100});if(e)return i}import{existsSync as gP,statSync as yP}from"fs";var Ha=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Vi(n){try{return gP(n)&&yP(n).isDirectory()}catch(e){return b.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import SP from"csv-parser";import{createReadStream as bP}from"fs";function Zd(n){return new Promise((e,t)=>{let r=[];bP(n).pipe(SP()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import Wa from"semver";import{z as Ga}from"zod";var ko="1.0.87",wP="https://registry.npmjs.org/momentic",vP=Ga.object({versions:Ga.record(Ga.string(),Ga.unknown()).optional()});async function LS(n){if(!ko){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 U(fetch(wP),{milliseconds:2e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=vP.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))Wa.valid(r)&&(!t||Wa.gt(r,t))&&Wa.gt(r,ko)&&Wa.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(b.warn(`Update available: v${ko} -> v${t}`),b.warn("This version may be missing critical fixes, features, and security updates."),b.warn(`Run "npx momentic@${t} -V" to update`))}import{existsSync as TP,mkdirSync as EP,statSync as CP}from"fs";import{dirname as AP}from"path";import kS from"readline/promises";import{hostname as xP}from"os";var j=Fa({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:xP(),disableConsoleLogs:!0}).child({version:"1.0.87"});var Qd=!1,_S=(()=>{try{return CP("/.dockerenv"),!0}catch{return!1}})();async function rt(n,e){if(Ha||Qd||_S)return!0;j.flush(),await new Promise(s=>setTimeout(s,500));let t=kS.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?b.warn(s):b.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"?(Qd=!0,setTimeout(()=>{Qd=!1},3e3),!0):i.toLowerCase()==="y"}async function ep(n){let e=AP(n);return Vi(e)?TP(n)?rt(`File '${OS(n)}' already exists. Overwrite existing content?`,!0):!0:await rt(`Directory '${OS(e)}' doesn't exist. Create it now?`,!0)?(EP(e,{recursive:!0}),!0):!1}function OS(n){return n.replace(/(\s+)/g,"\\$1")}async function NS(n,e){if(Ha||_S)return e;let t=kS.createInterface({input:process.stdin,output:process.stdout}),r=await t.question(`${n} `);return t.close(),r.trim()||e}async function MS({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){IP(e.schemaVersion,ut)&&(b.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)),eh(e.steps).forEach(f=>{t.modules[f]||(b.error(`The test patch contains a module with id ${f} 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 rt("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 rt("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=ud(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!==ut){let{steps:f,newVersion:g}=await gi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:b});d=g,p=Re.array().parse(f)}else p=Re.array().parse(e.steps);let{stepsToSave:u,moduleUpdates:m}=await It({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=RP(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});b.dimmed("=".repeat(30)),b.dimmed(h),b.dimmed("=".repeat(30)),b.dimmed(""),d&&b.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 rt("Do you want to apply this patch?")&&(b.dimmed("Cancelled."),process.exit(1)),Ci(n.relativePath,u,d??e.schemaVersion,t.project),b.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{cloneDeep as PP}from"lodash-es";async function Va({client:n,skipPrompts:e,project:t}){let r=await n.getAllEnvironments(),o=PP(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 rt(`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})}}Ao(o,t.configFilePath),b.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as DS}from"crypto";import FS from"fs";async function zS({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=US(l,xe.TEST);!r&&!await ep(d)||(s+=1,FS.writeFileSync(d,c,"utf-8"),j.info({checksum:DS("md5").update(c).digest("hex")},`Wrote '${d}'`))}let a=0;for(let[l,c]of Object.entries(i)){let d=US(l,xe.MODULE);!r&&!await ep(d)||(a+=1,FS.writeFileSync(d,c,"utf-8"),j.info({checksum:DS("md5").update(c).digest("hex")},`Wrote '${d}'`))}s===0?b.success("Pulled 0 tests."):b.success(`Pulled ${s} test${s>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function US(n,e){switch(e){case xe.TEST:return`${Pe(n)}.${En.TEST}`;case xe.MODULE:return`${Pe(n)}.${En.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function BS(n){let{project:e,client:t,skipPrompts:r}=n;b.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),b.info("Importing environments from Momentic Cloud."),b.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await rt("Are you sure you want to proceed?",!0)||(b.info("Aborting..."),process.exit(1)),await Va({client:t,project:e,skipPrompts:r}),b.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.`),b.info("Importing tests and modules from Momentic Cloud."),await zS({testsToFetch:[],client:t,all:!0,yes:r}),b.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 kt from"fs";import Pr from"path";import LP from"yaml";function jS(){Vi("momentic")||(b.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:Hi,environments:[]};b.info("Migrating environments");let e=$S(["momentic/environments"],OP);for(let r of e){let o=LP.parse(kt.readFileSync(r,"utf-8"));try{let i=hs.parse(o),s=i.variables[ve]??"";delete i.variables[ve],n.environments?.push({name:i.name,baseUrl:s,envVariables:i.variables})}catch(i){b.error(`${r} failed to parse as a valid environment file.`),b.error(i),process.exit(1)}}b.info("Migrating tests");let t=pd("./momentic",b);for(let r of t){let o=Pr.join(...r.fullPathSegments),i=Pr.join(Pr.dirname(o),`${r.fileName.slice(0,-5)}.test.yaml`);b.info(`Moving test ${o} to ${i}`),kt.renameSync(o,i)}if(Vi("momentic/modules")){b.info("Migrating modules");for(let r of kt.readdirSync("./momentic/modules")){if(!r.endsWith(".yaml"))continue;let o=Pr.resolve(Pr.join("./momentic/modules",r));if(!kt.readFileSync(o,"utf-8").includes("schemaVersion")){b.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let s=`${o.slice(0,-5)}.module.yaml`;b.info(`Moving module ${o} to ${s}`),kt.renameSync(o,s)}}return b.info("Writing new project configuration file"),Ao(n,"momentic.config.yaml"),kt.rmSync("./momentic/environments",{recursive:!0,force:!0}),kt.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),b.success("Migration succeeded!"),b.info("Going forward:"),b.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),b.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),n}function $S(n,e,t=new Set){for(let r of n){let o=Pr.resolve(r),i=!1;try{i=kt.existsSync(o)&&kt.statSync(o).isDirectory()}catch(s){b.error({err:s},`Error reading path ${o} during collect paths`)}if(o&&i){let s=kt.readdirSync(o).map(a=>Pr.join(o,a));$S(s,e,t);continue}if(o.endsWith(".yaml")){try{if(!kt.existsSync(o)||!kt.statSync(o).isFile()){b.warn(`File not found or unreadable: ${o}`);continue}}catch(s){b.error({err:s},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function OP(n){return n.endsWith(".yaml")?kt.readFileSync(n,"utf8").includes("momentic/environment")?!0:(b.warn(`Skipping YAML that is not a Momentic environment: ${n}`),!1):!1}import{Argument as qa,Option as Me}from"@commander-js/extra-typings";import{validateHeaderValue as kP}from"http";import{cpus as HS}from"os";import{parse as soe}from"yaml";import{z as $}from"zod";var Ka=58888,tp=30*60*1e3,Yn=new Me("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),Lr=new Me("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Jn=new Me("-y, --yes","Skip all confirmation prompts."),np=new Me("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),rp=new Me("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${tp/1e3} seconds.`),Ya=new Me("--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."),op=new Me("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),GS=new Me("--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(As)),VS=new Me("--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."),qS=new Me("--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."),KS=new Me("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),ip=new Me("--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."),YS=new Me("--port <port>",`Port to run the app on. Defaults to ${Ka}.`),sp=new Me("--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."),Ja=new Me("--env <env>","Name of the environment to use when running tests."),Xa=new Me("--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."),JS=new Me("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),Or=new Me("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),ap=new Me("-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."),XS=new Me("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),ZS=new qa("<tests...>",`One or more test paths to queue on Momentic Cloud.
2988
+ `)}import SL from"events";import Rb from"fs";import bL from"open";import il from"path";import{fileURLToPath as wL}from"url";import RP from"diff-lines";import{gt as IP}from"semver";import{execSync as dP}from"child_process";import{platform as pP}from"os";function Jd(){return IS()?(b.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),b.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),b.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(b.info("Setting device pixel ratio to 1."),b.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),b.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function IS(){return pP()==="darwin"&&dP("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Xd(n){IS()&&n===1&&(b.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),b.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import uP from"@actions/exec";import mP from"@actions/io";import hP from"quote";import fP from"string-argv";async function PS(n,e=!0){let t=fP(n),r=await mP.which(t[0],!0),o=t.slice(1),i=uP.exec(hP(r),o,{delay:100});if(e)return i}import{existsSync as gP,statSync as yP}from"fs";var Ha=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Vi(n){try{return gP(n)&&yP(n).isDirectory()}catch(e){return b.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import SP from"csv-parser";import{createReadStream as bP}from"fs";function Zd(n){return new Promise((e,t)=>{let r=[];bP(n).pipe(SP()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import Wa from"semver";import{z as Ga}from"zod";var ko="1.0.89",wP="https://registry.npmjs.org/momentic",vP=Ga.object({versions:Ga.record(Ga.string(),Ga.unknown()).optional()});async function LS(n){if(!ko){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 U(fetch(wP),{milliseconds:2e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=vP.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))Wa.valid(r)&&(!t||Wa.gt(r,t))&&Wa.gt(r,ko)&&Wa.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(b.warn(`Update available: v${ko} -> v${t}`),b.warn("This version may be missing critical fixes, features, and security updates."),b.warn(`Run "npx momentic@${t} -V" to update`))}import{existsSync as TP,mkdirSync as EP,statSync as CP}from"fs";import{dirname as AP}from"path";import kS from"readline/promises";import{hostname as xP}from"os";var j=Fa({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:xP(),disableConsoleLogs:!0}).child({version:"1.0.89"});var Qd=!1,_S=(()=>{try{return CP("/.dockerenv"),!0}catch{return!1}})();async function rt(n,e){if(Ha||Qd||_S)return!0;j.flush(),await new Promise(s=>setTimeout(s,500));let t=kS.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?b.warn(s):b.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"?(Qd=!0,setTimeout(()=>{Qd=!1},3e3),!0):i.toLowerCase()==="y"}async function ep(n){let e=AP(n);return Vi(e)?TP(n)?rt(`File '${OS(n)}' already exists. Overwrite existing content?`,!0):!0:await rt(`Directory '${OS(e)}' doesn't exist. Create it now?`,!0)?(EP(e,{recursive:!0}),!0):!1}function OS(n){return n.replace(/(\s+)/g,"\\$1")}async function NS(n,e){if(Ha||_S)return e;let t=kS.createInterface({input:process.stdin,output:process.stdout}),r=await t.question(`${n} `);return t.close(),r.trim()||e}async function MS({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){IP(e.schemaVersion,ut)&&(b.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)),eh(e.steps).forEach(f=>{t.modules[f]||(b.error(`The test patch contains a module with id ${f} 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 rt("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 rt("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=ud(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!==ut){let{steps:f,newVersion:g}=await gi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:b});d=g,p=Ae.array().parse(f)}else p=Ae.array().parse(e.steps);let{stepsToSave:u,moduleUpdates:m}=await It({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=RP(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});b.dimmed("=".repeat(30)),b.dimmed(h),b.dimmed("=".repeat(30)),b.dimmed(""),d&&b.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 rt("Do you want to apply this patch?")&&(b.dimmed("Cancelled."),process.exit(1)),Ci(n.relativePath,u,d??e.schemaVersion,t.project),b.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{cloneDeep as PP}from"lodash-es";async function Va({client:n,skipPrompts:e,project:t}){let r=await n.getAllEnvironments(),o=PP(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 rt(`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})}}Ao(o,t.configFilePath),b.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as DS}from"crypto";import FS from"fs";async function zS({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=US(l,xe.TEST);!r&&!await ep(d)||(s+=1,FS.writeFileSync(d,c,"utf-8"),j.info({checksum:DS("md5").update(c).digest("hex")},`Wrote '${d}'`))}let a=0;for(let[l,c]of Object.entries(i)){let d=US(l,xe.MODULE);!r&&!await ep(d)||(a+=1,FS.writeFileSync(d,c,"utf-8"),j.info({checksum:DS("md5").update(c).digest("hex")},`Wrote '${d}'`))}s===0?b.success("Pulled 0 tests."):b.success(`Pulled ${s} test${s>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function US(n,e){switch(e){case xe.TEST:return`${Ie(n)}.${En.TEST}`;case xe.MODULE:return`${Ie(n)}.${En.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function BS(n){let{project:e,client:t,skipPrompts:r}=n;b.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),b.info("Importing environments from Momentic Cloud."),b.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await rt("Are you sure you want to proceed?",!0)||(b.info("Aborting..."),process.exit(1)),await Va({client:t,project:e,skipPrompts:r}),b.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.`),b.info("Importing tests and modules from Momentic Cloud."),await zS({testsToFetch:[],client:t,all:!0,yes:r}),b.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 kt from"fs";import Pr from"path";import LP from"yaml";function jS(){Vi("momentic")||(b.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:Hi,environments:[]};b.info("Migrating environments");let e=$S(["momentic/environments"],OP);for(let r of e){let o=LP.parse(kt.readFileSync(r,"utf-8"));try{let i=hs.parse(o),s=i.variables[ve]??"";delete i.variables[ve],n.environments?.push({name:i.name,baseUrl:s,envVariables:i.variables})}catch(i){b.error(`${r} failed to parse as a valid environment file.`),b.error(i),process.exit(1)}}b.info("Migrating tests");let t=pd("./momentic",b);for(let r of t){let o=Pr.join(...r.fullPathSegments),i=Pr.join(Pr.dirname(o),`${r.fileName.slice(0,-5)}.test.yaml`);b.info(`Moving test ${o} to ${i}`),kt.renameSync(o,i)}if(Vi("momentic/modules")){b.info("Migrating modules");for(let r of kt.readdirSync("./momentic/modules")){if(!r.endsWith(".yaml"))continue;let o=Pr.resolve(Pr.join("./momentic/modules",r));if(!kt.readFileSync(o,"utf-8").includes("schemaVersion")){b.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let s=`${o.slice(0,-5)}.module.yaml`;b.info(`Moving module ${o} to ${s}`),kt.renameSync(o,s)}}return b.info("Writing new project configuration file"),Ao(n,"momentic.config.yaml"),kt.rmSync("./momentic/environments",{recursive:!0,force:!0}),kt.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),b.success("Migration succeeded!"),b.info("Going forward:"),b.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),b.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),n}function $S(n,e,t=new Set){for(let r of n){let o=Pr.resolve(r),i=!1;try{i=kt.existsSync(o)&&kt.statSync(o).isDirectory()}catch(s){b.error({err:s},`Error reading path ${o} during collect paths`)}if(o&&i){let s=kt.readdirSync(o).map(a=>Pr.join(o,a));$S(s,e,t);continue}if(o.endsWith(".yaml")){try{if(!kt.existsSync(o)||!kt.statSync(o).isFile()){b.warn(`File not found or unreadable: ${o}`);continue}}catch(s){b.error({err:s},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function OP(n){return n.endsWith(".yaml")?kt.readFileSync(n,"utf8").includes("momentic/environment")?!0:(b.warn(`Skipping YAML that is not a Momentic environment: ${n}`),!1):!1}import{Argument as qa,Option as Me}from"@commander-js/extra-typings";import{validateHeaderValue as kP}from"http";import{cpus as HS}from"os";import{parse as soe}from"yaml";import{z as $}from"zod";var Ka=58888,tp=30*60*1e3,Yn=new Me("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),Lr=new Me("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Jn=new Me("-y, --yes","Skip all confirmation prompts."),np=new Me("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),rp=new Me("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${tp/1e3} seconds.`),Ya=new Me("--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."),op=new Me("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),GS=new Me("--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(As)),VS=new Me("--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."),qS=new Me("--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."),KS=new Me("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),ip=new Me("--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."),YS=new Me("--port <port>",`Port to run the app on. Defaults to ${Ka}.`),sp=new Me("--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."),Ja=new Me("--env <env>","Name of the environment to use when running tests."),Xa=new Me("--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."),JS=new Me("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),Or=new Me("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),ap=new Me("-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."),XS=new Me("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),ZS=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'.`),QS=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(),eb=new qa("<suites...>",`One or more suite paths that exist on Momentic Cloud.
2991
2991
 
@@ -2993,13 +2993,13 @@ The suite path is a lowercased version of your suite name where spaces and speci
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",qi(e,...t))}error(e,...t){this._log("error",qi(e,...t))}info(e,...t){this._log("info",qi(e,...t))}log(e,...t){this._log("log",qi(e,...t))}warn(e,...t){this._log("warn",qi(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function sb(n){let e=globalThis.console,t=new el;globalThis.console=t;try{n()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
2995
2995
  `);process.stderr.write(`${o}
2996
- `),globalThis.console=e}}var BP=5;async function tl({getResults:n,checkDone:e,name:t,timeoutMs:r=tp}){let o=Date.now(),i=0;for(;Date.now()-o<r;){let s;i>BP&&(b.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{s=await n(),i=0}catch(c){i++,j.warn({err:c},"Failed to fetch run status, retrying..."),b.warn({err:c},"Failed to fetch run status, retrying..."),await new Promise(d=>setTimeout(d,1500*i));continue}if(e(s))return s;let l=Math.max(1e4,Math.floor(r/100));await new Promise(c=>setTimeout(c,l))}b.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(r/1e3)}s).`),process.exit(1)}function _o({results:n,startTime:e,entity:t,getDisplayLine:r,onFailed:o}){let i=n.filter(l=>l.status==="PASSED"),s=n.filter(l=>l.status==="FAILED"),a=n.filter(l=>l.status==="CANCELLED");return sb(()=>{s.forEach(l=>{b.log(""),o(l)}),s.length&&(b.log(""),b.error(`${s.length} ${t}s failed:`),s.forEach(l=>{b.dimmed(r(l))})),a.length&&(b.log(""),b.warn(`${a.length} ${t}s cancelled:`),a.forEach(l=>{b.dimmed(r(l))})),i.length&&(b.log(""),b.success(`${i.length} ${t}s passed:`),i.forEach(l=>{b.dimmed(r(l))})),b.log(""),b.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{passed:i.length,failed:s.length,cancelled:a.length}}var nl=(n,e)=>{if(!n.failureDetails||!n.failureReason)return;let t=yu[n.failureDetails?.classification?.reason||n.failureReason],r=n.failureDetails?.classification?.summary||Su[n.failureReason];b.error(e),b.log(` Reason: ${ab.red(t)}`),b.log(` Description: ${ab.red(r)}`)};async function lb({client:n,orgId:e,suitePaths:t,wait:r,waitTimeout:o,...i}){let s=(await n.queueSuiteRuns({paths:t,...i})).suiteRunIds;j.info({orgId:e,suiteRunIds:s,suitePaths:t},"Queued suites remotely"),b.dimmed(`Queued ${t.length} suites.`),r||process.exit(0);let a=Date.now();b.dimmed(`Waiting for ${t.length} suites to complete.`);let l=new Set,c=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(y=>y.status==="FAILED"&&(y.failureReason||y.finishedAt&&Date.now()-y.finishedAt.getTime()>30*1e3)||y.status==="PASSED"||y.status==="CANCELLED"),p=await tl({name:"suites",getResults:async()=>{let f=s.filter(v=>!c.some(S=>S.id===v)),g=await n.bulkGetSuiteStatus(f),y=[];for(let v of g)d(v)?c.push(v):y.push(v);return[...c,...y]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(g=>{if(g.status==="RUNNING"&&!l.has(g.id)){l.add(g.id);let y=g.suite?.name??"Unknown suite";y&&b.log(`${l.size}/${s.length} ${Pe(y)}`)}}),f.every(d))}),u=n.getAppUrl(),h=_o({results:p,startTime:a,onFailed:f=>{let g=f.suite?.name?Pe(f.suite.name):"Unknown suite",y=f.runs.filter(S=>S.status==="FAILED").length,v=f.runs.length;b.error(`${g} (${y}/${v} tests failed):`);for(let S of f.runs)if(S.status==="FAILED"){let E=S.testName||S.test?.name;b.error(` ${E?Pe(E):"Unknown test"} (${u}/runs/${S.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Pe(f.suite.name):"Unknown suite name"} (${u}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function cb({tests:n,client:e,orgId:t,...r}){!r.yes&&!await rt(`This command will queue ${n.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:n,...r});if(j.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),b.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),r.wait||process.exit(0),!i.length)return;b.dimmed(`Waiting for ${o.length} tests to complete.`);let s=new Set,a=[],l=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",c=e.getAppUrl(),d=Date.now(),p=await tl({name:"runs",getResults:async()=>{let m=i.filter(g=>!a.some(y=>y.id===g)),h=await e.bulkGetRunStatus(m),f=[];for(let g of h)l(g)?a.push(g):f.push(g);return[...a,...f]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(h=>{if(h.status==="RUNNING"&&!s.has(h.id)){s.add(h.id);let f=h.testName||h.test?.name;f&&b.log(`${s.size}/${o.length} ${Pe(f)}`)}}),m.every(l))}),u=_o({results:p,startTime:d,onFailed:m=>{let h=m.testName||m.test?.name;nl(m,h?Pe(h):"Unknown test")},getDisplayLine:m=>{let h=m.testName||m.test?.name,f=` ${h?Pe(h):"Unknown test"}`;return m.id&&(f+=` (${c}/runs/${m.id})`),f},entity:"test"});process.exit(u.failed>0?1:0)}import Mo,{supportsColor as mL}from"chalk";import{existsSync as VP,mkdirSync as qP,statSync as KP}from"fs";import{randomUUID as pp}from"crypto";import up from"fs";import{hostname as jP}from"os";import rl from"path";async function db(n,e){let t=rl.extname(e),r=`${pp()}-attachment${t}`,o=rl.join(n,r),s=await(await fetch(e)).arrayBuffer();return up.writeFileSync(o,Buffer.from(s)),r}async function $P(n,e){let t=e.runId??pp(),r={uuid:t,historyId:t,testCaseId:e.test.id,fullName:e.test.name,name:Pe(e.test.name),status:e.status==="PASSED"?"passed":e.status==="CANCELLED"?"skipped":"failed",start:e.startedAt.getTime(),stop:e.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:n.suiteName},{name:"host",value:jP()},{name:"platform",value:"momentic"},{name:"attempts",value:e.attempts.toString()}],steps:[]};for(let[i,s]of Object.entries(e.parameters))s!=null&&r.parameters.push({name:i,value:JSON.stringify(s)});e.results&&await HP(n.folder,r.steps,e.results);let o=`${t}-result.json`;up.writeFileSync(rl.join(n.folder,o),JSON.stringify(r,void 0,2))}async function No(n,e){let t={name:Cn(e),start:e.startedAt.getTime(),stop:e.finishedAt.getTime(),status:e.status==="SUCCESS"?"passed":e.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};if(e.beforeUrl&&t.labels.push({name:"URL before step",value:e.beforeUrl}),e.afterUrl&&t.labels.push({name:"URL after step",value:e.afterUrl}),e.beforeScreenshot&&t.attachments.push({name:"Screenshot before step",source:await db(n,e.beforeScreenshot),type:"image/jpeg"}),e.afterScreenshot&&t.attachments.push({name:"Screenshot after step",source:await db(n,e.afterScreenshot),type:"image/jpeg"}),e.message&&(t.statusDetails={message:e.message}),e.data){let r=`${pp()}-attachment.json`,o=rl.join(n,r);up.writeFileSync(o,JSON.stringify(e.data,null,2)),t.attachments.push({name:"Step output data",source:r,type:"text/plain"})}return t}async function HP(n,e,t){for(let r of t)switch(r.type){case"PRESET_ACTION":{e.push(await No(n,r));break}case"CONDITIONAL":{let o=await No(n,r);o.steps=[],r.assertion&&o.steps.push(await No(n,r.assertion)),o.steps.push(...await Promise.all(r.results.map(i=>No(n,i)))),e.push(o);break}case"AI_ACTION":case"IFRAME":case"SECTION":case"MODULE":{let o=await No(n,r);if(o.steps=await Promise.all(r.results.map(i=>No(n,i))),r.type==="MODULE"&&r.inputs){o.parameters=[];for(let[i,s]of Object.entries(r.inputs))o.parameters.push({name:i,value:s})}e.push(o)}}}async function pb(n,e){for(let t of e.runs)await $P({folder:n,suiteName:e.suiteName},t)}import ub from"junit-report-builder";import mb from"path";function WP(n,e){let t=e??ub.testCase();t.name(n.test.name).property("filePath",mb.relative(".",n.filePath)).property("id",n.test.id),n.baseUrl&&t.property("baseUrl",n.baseUrl),n.status==="FAILED"?(t.failure(n.failureDetails?.errorMessage,n.failureReason),n.failureDetails?.errorStack&&t.stacktrace(n.failureDetails.errorStack)):n.status==="CANCELLED"&&t.skipped(),t.time((n.finishedAt.getTime()-n.startedAt.getTime())/1e3).property("startedAt",n.startedAt.toLocaleString()).property("attempts",n.attempts.toString());for(let r of["testInputs","customHeaders"]){let o=n.parameters[r];Object.keys(o??{}).length>0&&t.multilineProperty(r,JSON.stringify(o))}for(let r of["envName","urlOverride"])n.parameters[r]!==void 0&&t.property(r,n.parameters[r]);return Object.keys(n.outputs).length&&t.multilineProperty("testOutputs",JSON.stringify(n.outputs)),t}function GP(n,{suiteId:e,suiteName:t,startedAt:r,finishedAt:o,runs:i}){let s=n.testSuite().name(t);e&&s.property("id",e),s.timestamp(r).property("startedAt",r.toLocaleDateString()).time((o.getTime()-r.getTime())/1e3);for(let a of i){let l=s.testCase();WP(a,l)}return s}function hb(n,e){let t=ub.newBuilder();GP(t,e),t.writeTo(mb.join(n,`${e.suiteName}.xml`))}async function fb(n,e,t){switch(VP(t)?KP(t).isDirectory()||(b.error(`The specified reporter output directory '${t}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(b.info(`Reporter output directory '${t}' does not exist on disk, creating it now...`),qP(t,{recursive:!0})),n){case"junit":hb(t,e);return;case"allure":await pb(t,e);return;default:throw new Error(`Unknown reporter format requested: '${n}'`)}}import hL from"wait-on";import YP from"simple-git";var Se=YP();function ol(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function be(n){try{return(await n).trim()}catch(e){j.error({err:e},"Failed to run git command");return}}function JP(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps"}async function XP(){let[n,e,t,r]=await Promise.all([be(Se.show(["--no-patch","--format=%ci"])),be(Se.listRemote(["--get-url","origin"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:`${process.env.GITHUB_RUN_ID}:${process.env.GITHUB_RUN_ATTEMPT}`}}async function ZP(){let[n,e,t]=await Promise.all([be(Se.listRemote(["--get-url","origin"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:n,gitCommitMessage:e,gitCommitAuthorName:t,gitlabProjectPath:process.env.CI_SERVER_HOST,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function QP(){let[n,e,t,r]=await Promise.all([be(Se.show(["--no-patch","--format=%ci"])),be(Se.listRemote(["--get-url","origin"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]),o=e?.includes("github.com"),i=e?.includes("gitlab.com"),s=e?ol(e):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.CIRCLE_WORKFLOW_ID}:${process.env.CIRCLE_WORKFLOW_JOB_ID}`}}async function eL(){let[n,e,t]=await Promise.all([be(Se.show(["--no-patch","--format=%ci"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?ol(r):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:r,gitCommitMessage:e,gitCommitAuthorName:t,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function tL(){let[n,e,t]=await Promise.all([be(Se.show(["--no-patch","--format=%ci"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?ol(r):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:r,gitCommitMessage:e,gitCommitAuthorName:t,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function nL(){let[n,e,t,r,o,i,s]=await Promise.all([be(Se.revparse(["HEAD"])),be(Se.revparse(["--short","HEAD"])),be(Se.revparse(["--abbrev-ref","HEAD"])),be(Se.listRemote(["--get-url","origin"])),be(Se.show(["--no-patch","--format=%ci"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]),a=r?.includes("github.com"),l=r?.includes("gitlab.com"),c=r?ol(r):void 0;return{gitCommitSha:n,gitCommitShaShort:e,gitBranchName:t,gitOriginUrl:r,gitCommitTimestamp:o?new Date(o):void 0,gitCommitMessage:i,gitCommitAuthorName:s,githubRepository:a?c:void 0,gitlabProjectPath:l?c:void 0,pipelineId:void 0}}async function gb(n){let e=JP();if(!e)return n.debug("No CI run environment detected, falling back to git"),nL();switch(n.debug(`Using CI runner environment variables from ${e} to get git metadata`),e){case"GithubActions":return XP();case"GitlabCI":return ZP();case"CircleCI":return QP();case"Buildkite":return eL();case"AzureDevOps":return tL()}}import mp from"fs";import{compact as rL}from"lodash-es";import hp from"path";import{cwd as oL}from"process";import iL from"semver";async function yb({tests:n,momenticFiles:e,project:t,yes:r,include:o,exclude:i,labels:s}){let a=new Set;if(n&&n.length>0){let c=n.some(p=>mp.existsSync(p)),d=oL();c?(d!==t.rootDir&&b.warn(`The current working directory ('${d}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),b.info(`Reading tests from the following local file paths:
2996
+ `),globalThis.console=e}}var BP=5;async function tl({getResults:n,checkDone:e,name:t,timeoutMs:r=tp}){let o=Date.now(),i=0;for(;Date.now()-o<r;){let s;i>BP&&(b.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{s=await n(),i=0}catch(c){i++,j.warn({err:c},"Failed to fetch run status, retrying..."),b.warn({err:c},"Failed to fetch run status, retrying..."),await new Promise(d=>setTimeout(d,1500*i));continue}if(e(s))return s;let l=Math.max(1e4,Math.floor(r/100));await new Promise(c=>setTimeout(c,l))}b.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(r/1e3)}s).`),process.exit(1)}function _o({results:n,startTime:e,entity:t,getDisplayLine:r,onFailed:o}){let i=n.filter(l=>l.status==="PASSED"),s=n.filter(l=>l.status==="FAILED"),a=n.filter(l=>l.status==="CANCELLED");return sb(()=>{s.forEach(l=>{b.log(""),o(l)}),s.length&&(b.log(""),b.error(`${s.length} ${t}s failed:`),s.forEach(l=>{b.dimmed(r(l))})),a.length&&(b.log(""),b.warn(`${a.length} ${t}s cancelled:`),a.forEach(l=>{b.dimmed(r(l))})),i.length&&(b.log(""),b.success(`${i.length} ${t}s passed:`),i.forEach(l=>{b.dimmed(r(l))})),b.log(""),b.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{passed:i.length,failed:s.length,cancelled:a.length}}var nl=(n,e)=>{if(!n.failureDetails||!n.failureReason)return;let t=yu[n.failureDetails?.classification?.reason||n.failureReason],r=n.failureDetails?.classification?.summary||Su[n.failureReason];b.error(e),b.log(` Reason: ${ab.red(t)}`),b.log(` Description: ${ab.red(r)}`)};async function lb({client:n,orgId:e,suitePaths:t,wait:r,waitTimeout:o,...i}){let s=(await n.queueSuiteRuns({paths:t,...i})).suiteRunIds;j.info({orgId:e,suiteRunIds:s,suitePaths:t},"Queued suites remotely"),b.dimmed(`Queued ${t.length} suites.`),r||process.exit(0);let a=Date.now();b.dimmed(`Waiting for ${t.length} suites to complete.`);let l=new Set,c=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(y=>y.status==="FAILED"&&(y.failureReason||y.finishedAt&&Date.now()-y.finishedAt.getTime()>30*1e3)||y.status==="PASSED"||y.status==="CANCELLED"),p=await tl({name:"suites",getResults:async()=>{let f=s.filter(v=>!c.some(S=>S.id===v)),g=await n.bulkGetSuiteStatus(f),y=[];for(let v of g)d(v)?c.push(v):y.push(v);return[...c,...y]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(g=>{if(g.status==="RUNNING"&&!l.has(g.id)){l.add(g.id);let y=g.suite?.name??"Unknown suite";y&&b.log(`${l.size}/${s.length} ${Ie(y)}`)}}),f.every(d))}),u=n.getAppUrl(),h=_o({results:p,startTime:a,onFailed:f=>{let g=f.suite?.name?Ie(f.suite.name):"Unknown suite",y=f.runs.filter(S=>S.status==="FAILED").length,v=f.runs.length;b.error(`${g} (${y}/${v} tests failed):`);for(let S of f.runs)if(S.status==="FAILED"){let E=S.testName||S.test?.name;b.error(` ${E?Ie(E):"Unknown test"} (${u}/runs/${S.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Ie(f.suite.name):"Unknown suite name"} (${u}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function cb({tests:n,client:e,orgId:t,...r}){!r.yes&&!await rt(`This command will queue ${n.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:n,...r});if(j.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),b.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),r.wait||process.exit(0),!i.length)return;b.dimmed(`Waiting for ${o.length} tests to complete.`);let s=new Set,a=[],l=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",c=e.getAppUrl(),d=Date.now(),p=await tl({name:"runs",getResults:async()=>{let m=i.filter(g=>!a.some(y=>y.id===g)),h=await e.bulkGetRunStatus(m),f=[];for(let g of h)l(g)?a.push(g):f.push(g);return[...a,...f]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(h=>{if(h.status==="RUNNING"&&!s.has(h.id)){s.add(h.id);let f=h.testName||h.test?.name;f&&b.log(`${s.size}/${o.length} ${Ie(f)}`)}}),m.every(l))}),u=_o({results:p,startTime:d,onFailed:m=>{let h=m.testName||m.test?.name;nl(m,h?Ie(h):"Unknown test")},getDisplayLine:m=>{let h=m.testName||m.test?.name,f=` ${h?Ie(h):"Unknown test"}`;return m.id&&(f+=` (${c}/runs/${m.id})`),f},entity:"test"});process.exit(u.failed>0?1:0)}import Mo,{supportsColor as mL}from"chalk";import{existsSync as VP,mkdirSync as qP,statSync as KP}from"fs";import{randomUUID as pp}from"crypto";import up from"fs";import{hostname as jP}from"os";import rl from"path";async function db(n,e){let t=rl.extname(e),r=`${pp()}-attachment${t}`,o=rl.join(n,r),s=await(await fetch(e)).arrayBuffer();return up.writeFileSync(o,Buffer.from(s)),r}async function $P(n,e){let t=e.runId??pp(),r={uuid:t,historyId:t,testCaseId:e.test.id,fullName:e.test.name,name:Ie(e.test.name),status:e.status==="PASSED"?"passed":e.status==="CANCELLED"?"skipped":"failed",start:e.startedAt.getTime(),stop:e.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:n.suiteName},{name:"host",value:jP()},{name:"platform",value:"momentic"},{name:"attempts",value:e.attempts.toString()}],steps:[]};for(let[i,s]of Object.entries(e.parameters))s!=null&&r.parameters.push({name:i,value:JSON.stringify(s)});e.results&&await HP(n.folder,r.steps,e.results);let o=`${t}-result.json`;up.writeFileSync(rl.join(n.folder,o),JSON.stringify(r,void 0,2))}async function No(n,e){let t={name:Cn(e),start:e.startedAt.getTime(),stop:e.finishedAt.getTime(),status:e.status==="SUCCESS"?"passed":e.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};if(e.beforeUrl&&t.labels.push({name:"URL before step",value:e.beforeUrl}),e.afterUrl&&t.labels.push({name:"URL after step",value:e.afterUrl}),e.beforeScreenshot&&t.attachments.push({name:"Screenshot before step",source:await db(n,e.beforeScreenshot),type:"image/jpeg"}),e.afterScreenshot&&t.attachments.push({name:"Screenshot after step",source:await db(n,e.afterScreenshot),type:"image/jpeg"}),e.message&&(t.statusDetails={message:e.message}),e.data){let r=`${pp()}-attachment.json`,o=rl.join(n,r);up.writeFileSync(o,JSON.stringify(e.data,null,2)),t.attachments.push({name:"Step output data",source:r,type:"text/plain"})}return t}async function HP(n,e,t){for(let r of t)switch(r.type){case"PRESET_ACTION":{e.push(await No(n,r));break}case"CONDITIONAL":{let o=await No(n,r);o.steps=[],r.assertion&&o.steps.push(await No(n,r.assertion)),o.steps.push(...await Promise.all(r.results.map(i=>No(n,i)))),e.push(o);break}case"AI_ACTION":case"IFRAME":case"SECTION":case"MODULE":{let o=await No(n,r);if(o.steps=await Promise.all(r.results.map(i=>No(n,i))),r.type==="MODULE"&&r.inputs){o.parameters=[];for(let[i,s]of Object.entries(r.inputs))o.parameters.push({name:i,value:s})}e.push(o)}}}async function pb(n,e){for(let t of e.runs)await $P({folder:n,suiteName:e.suiteName},t)}import ub from"junit-report-builder";import mb from"path";function WP(n,e){let t=e??ub.testCase();t.name(n.test.name).property("filePath",mb.relative(".",n.filePath)).property("id",n.test.id),n.baseUrl&&t.property("baseUrl",n.baseUrl),n.status==="FAILED"?(t.failure(n.failureDetails?.errorMessage,n.failureReason),n.failureDetails?.errorStack&&t.stacktrace(n.failureDetails.errorStack)):n.status==="CANCELLED"&&t.skipped(),t.time((n.finishedAt.getTime()-n.startedAt.getTime())/1e3).property("startedAt",n.startedAt.toLocaleString()).property("attempts",n.attempts.toString());for(let r of["testInputs","customHeaders"]){let o=n.parameters[r];Object.keys(o??{}).length>0&&t.multilineProperty(r,JSON.stringify(o))}for(let r of["envName","urlOverride"])n.parameters[r]!==void 0&&t.property(r,n.parameters[r]);return Object.keys(n.outputs).length&&t.multilineProperty("testOutputs",JSON.stringify(n.outputs)),t}function GP(n,{suiteId:e,suiteName:t,startedAt:r,finishedAt:o,runs:i}){let s=n.testSuite().name(t);e&&s.property("id",e),s.timestamp(r).property("startedAt",r.toLocaleDateString()).time((o.getTime()-r.getTime())/1e3);for(let a of i){let l=s.testCase();WP(a,l)}return s}function hb(n,e){let t=ub.newBuilder();GP(t,e),t.writeTo(mb.join(n,`${e.suiteName}.xml`))}async function fb(n,e,t){switch(VP(t)?KP(t).isDirectory()||(b.error(`The specified reporter output directory '${t}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(b.info(`Reporter output directory '${t}' does not exist on disk, creating it now...`),qP(t,{recursive:!0})),n){case"junit":hb(t,e);return;case"allure":await pb(t,e);return;default:throw new Error(`Unknown reporter format requested: '${n}'`)}}import hL from"wait-on";import YP from"simple-git";var Se=YP();function ol(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function be(n){try{return(await n).trim()}catch(e){j.error({err:e},"Failed to run git command");return}}function JP(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps"}async function XP(){let[n,e,t,r]=await Promise.all([be(Se.show(["--no-patch","--format=%ci"])),be(Se.listRemote(["--get-url","origin"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:`${process.env.GITHUB_RUN_ID}:${process.env.GITHUB_RUN_ATTEMPT}`}}async function ZP(){let[n,e,t]=await Promise.all([be(Se.listRemote(["--get-url","origin"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:n,gitCommitMessage:e,gitCommitAuthorName:t,gitlabProjectPath:process.env.CI_SERVER_HOST,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function QP(){let[n,e,t,r]=await Promise.all([be(Se.show(["--no-patch","--format=%ci"])),be(Se.listRemote(["--get-url","origin"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]),o=e?.includes("github.com"),i=e?.includes("gitlab.com"),s=e?ol(e):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.CIRCLE_WORKFLOW_ID}:${process.env.CIRCLE_WORKFLOW_JOB_ID}`}}async function eL(){let[n,e,t]=await Promise.all([be(Se.show(["--no-patch","--format=%ci"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?ol(r):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:r,gitCommitMessage:e,gitCommitAuthorName:t,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function tL(){let[n,e,t]=await Promise.all([be(Se.show(["--no-patch","--format=%ci"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?ol(r):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:r,gitCommitMessage:e,gitCommitAuthorName:t,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function nL(){let[n,e,t,r,o,i,s]=await Promise.all([be(Se.revparse(["HEAD"])),be(Se.revparse(["--short","HEAD"])),be(Se.revparse(["--abbrev-ref","HEAD"])),be(Se.listRemote(["--get-url","origin"])),be(Se.show(["--no-patch","--format=%ci"])),be(Se.show(["-s","--pretty=%B"])),be(Se.show(["-s","--pretty=%an"]))]),a=r?.includes("github.com"),l=r?.includes("gitlab.com"),c=r?ol(r):void 0;return{gitCommitSha:n,gitCommitShaShort:e,gitBranchName:t,gitOriginUrl:r,gitCommitTimestamp:o?new Date(o):void 0,gitCommitMessage:i,gitCommitAuthorName:s,githubRepository:a?c:void 0,gitlabProjectPath:l?c:void 0,pipelineId:void 0}}async function gb(n){let e=JP();if(!e)return n.debug("No CI run environment detected, falling back to git"),nL();switch(n.debug(`Using CI runner environment variables from ${e} to get git metadata`),e){case"GithubActions":return XP();case"GitlabCI":return ZP();case"CircleCI":return QP();case"Buildkite":return eL();case"AzureDevOps":return tL()}}import mp from"fs";import{compact as rL}from"lodash-es";import hp from"path";import{cwd as oL}from"process";import iL from"semver";async function yb({tests:n,momenticFiles:e,project:t,yes:r,include:o,exclude:i,labels:s}){let a=new Set;if(n&&n.length>0){let c=n.some(p=>mp.existsSync(p)),d=oL();c?(d!==t.rootDir&&b.warn(`The current working directory ('${d}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),b.info(`Reading tests from the following local file paths:
2997
2997
  ${n.map(p=>` - ${p}`).join(`
2998
2998
  `)}
2999
2999
  `),n.forEach(p=>{if(!mp.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let u,m;try{u=mp.statSync(p),m=u.isDirectory()}catch(f){b.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=hp.resolve(p);Object.values(e.tests).filter(f=>m?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{a.add(f.fullFilePath)})})):(b.info(`Reading all tests from the project and running those matching the following substring filters:
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 rt("No test paths or substrings were provided. Do you want to run all tests?")&&(b.error("Cancelled by user."),process.exit(1));let c=Object.values(e.tests);b.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=hp.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 ya(c,j,e);if(iL.gt(d.schemaVersion,ut)&&b.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:hp.relative(t.rootDir,c)}}catch(d){b.error(`Failed to read and resolve test at '${c}': ${d}`),process.exit(1)}});return Promise.all(l).then(rL)}import{randomUUID as cL}from"crypto";import{cloneDeep as Tb}from"lodash-es";async function Sb({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 Pt({orgId:n,s:l,localTools:e,logger:t,context:o})}return i}async function bb({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:f}){let g=await oa({advanced:{...h,...o.advanced},customHeaders:p,envVariables:c,envName:e,baseUrl:n,logger:d,localTools:s,orgId:l}),y=await so.init(l),v={baseUrl:r.baseUrl,apiKey:r.apiKey,logger:j};g.browserType==="Google Chrome"&&await kr(["chrome"]);let S;try{S=await en.init({baseUrl:n,logger:d,userBrowserSettings:g,storage:i,featureFlagStore:y,enricher:new Sr(v),timeout:g.pageLoadTimeoutMs,contextArgs:{viewport:o.advanced.viewport??Yt,deviceScaleFactor:t}})}catch(C){let P=C.message;if(P.includes("Executable doesn't exist")||P.includes("install your dependencies"))b.error("The headless browser used by Momentic is not installed correctly. Re-installing the necessary dependencies before starting the test. If this issue persists, pleases contact Momentic Support."),await kr(lp,!0),S=await en.init({baseUrl:n,logger:d,userBrowserSettings:g,storage:i,featureFlagStore:y,enricher:new Sr(v),timeout:g.pageLoadTimeoutMs,contextArgs:{viewport:o.advanced.viewport??Yt,deviceScaleFactor:t}});else throw C}let E=new mo({browser:S,generator:a,logger:d,orgId:l,scratchPadId:void 0,storage:i,flagStore:y,localCodeEvalTools:s,visualDiffScreenshotStorage:f,analytics:m}),T=new vt({baseUrl:n,currentUrl:E.browser.url(),variablesFromEnvironment:c,envName:e});return o.parameters&&await Promise.all(o.parameters.map(async C=>{let{name:P,defaultValue:k,required:N}=C,J=u?.[P];N&&J===void 0&&(b.error(`Required parameter '${P}' is required by test '${o.name}' but not provided`),process.exit(1));let V=await Pt({orgId:l,s:J??k,localTools:s,logger:d,context:vt.dummyContext(T.getEnvName())});T.setMomenticSystemVariable(P,V)})),{controller:E,context:T,flagStore:y}}import{randomUUID as sL}from"crypto";import{diff as aL}from"deep-object-diff";import{cloneDeep as vb}from"lodash-es";import{debounce as lL}from"ts-debounce";async function wb({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 xb({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:f,billingReporter:g}=e,{test:y,orgSettings:v,noReport:S}=n;h.info(`Running test '${y.name}' locally${S?"":` and reporting results to https://app.momentic.ai/runs/${i}`}`);let E=vb({steps:y.steps,beforeSteps:y.beforeSteps,afterSteps:y.afterSteps}),T=async O=>{if(!(S||!i))try{if(O.results){let I=vb(O.results);Hs(I,h),O.results=I}await f.updateRun(i,{...O,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=lL(async O=>{S||await T(O)},1e4,{maxWait:3e4}),P=async O=>{try{await C(O)}catch{}},k={controller:a,storage:u,debugDataStorage:m,billingReporter:g,analytics:d,context:l,logger:h,codeEvalTools:p},N={orgId:o,runId:i||sL(),runAttemptId:s,testMetadata:y,steps:y.steps,beforeSteps:y.beforeSteps,afterSteps:y.afterSteps},J={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await wb({noReport:S,currentAttempt:r,testId:y.id,flagStore:c,apiClient:f,testAdvancedSettings:y.advanced,aiSettingsFromEnv:v.ai,logger:h})},V={step:{},test:{onTestComplete:async()=>{await a.browser.cleanup()},onSaveScreenshot:async O=>{if(S)return"";let{key:I}=await f.uploadScreenshot({screenshot:O.toString("base64")});return I},onUpdateRun:O=>{P(O)},onSaveFinalRunResults:async O=>{C.cancel(),await T(O)},onProposedTestSteps:async O=>f.uploadProposedSteps(O,h),onTestSuccess:async O=>{let I=aL(E,O);if(Object.keys(I).length!==0){h.debug({changes:I},"Updating steps post-run success in worker");try{let{cachesToSave:te}=await It({stepLists:O,cacheCreationParams:{testId:y.id,orgId:o}});await f.updateStepCaches({testId:y.id,entries:te})}catch(te){h.error({err:te},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}}};return await g.reportBillableEvent(h,"test-run",{eventId:i,testId:y.id,testName:y.name}),await ra({fixtures:k,inputs:N,options:J,callbacks:V})}async function Eb(n){let e=new Date,{testDefinition:t}=n;try{return await dL(n)}catch(r){let o="Fatal error running test";return b.error(`${o}: ${r.message}`),j.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 dL(n){let{testDefinition:e,project:t,apiClient:r,orgId:o,noReport:i,urlOverride:s,runGroupId:a,runSigIntHandlers:l}=n,c=new Zr(r,o),d=new Dn({httpClient:new Et({baseUrl:r.baseUrl,apiKey:r.apiKey})}),p=e.steps,u=Tb(e.steps);try{await c.resolveStepCacheEntries({organizationId:o,testId:e.id,steps:u,schemaVersion:e.schemaVersion,logger:j})}catch(v){throw j.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 an error, please contact Momentic Support with the following error: ${v}`)}let m=n.envName??uL(e),h,f={};if(m){try{h=Ai(m,t,j)}catch(v){let S=`Failed to resolve environment ${m} for test ${e.name}: ${v}`;throw new Error(S)}f=h.variables}let g=e.baseUrl;if(s)g=s;else if(!g){let v=f[ve];typeof v=="string"&&(g=v)}if(!g){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:g,environmentName:m,schemaVersion:e.schemaVersion})).id}catch(v){throw j.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.
3002
- If you believe this is an error, please contact Momentic Support with the following error message: ${v}`)}try{return l?.push(async()=>{!y||i||await r.updateRun(y,{status:"CANCELLED",updatedAt:new Date})}),pL({...n,variables:f,envName:m,runId:y,stepsWithCaches:u,resolvedEnv:h,baseUrl:g,storageClient:c,codeEvalTools:d})}finally{l?.pop()}}async function pL(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:f,variables:g,analytics:y,resolvedEnv:v,noReport:S,retriesOverride:E,billingReporter:T,devicePixelRatio:C,logUpdate:P}=n,k=new Date,N=new Io(r,o),J={ai:r.config.ai},V=new Jr(i,p),de={envName:u,urlOverride:m,customHeaders:h,testInputs:f};d&&(g[uf]=d);let O=j.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 te=async Ae=>{if(!(S||!d))try{await i.updateRun(d,Ae)}catch(Q){O.warn({err:Q},`Failed to update run status for test ${d}. You may see stale data on the Momentic Cloud Server.`)}},L,fe=Math.abs(E??r.config.retries??e.retries??0),se=[];O.info("Starting test run using CLI");for(let Ae=0;Ae<=fe;Ae++){let Q=cL(),we={...e,steps:Tb(t)};if(!S&&d)try{Q=(await i.createRunAttempt(d)).id}catch(De){throw O.error({err:De,testId:we.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.")}Ae!==0&&P("RETRY",`attempt ${Ae+1}/${fe+1}`);let pt=async De=>{if(!(S||!d))try{await i.updateRunAttempt(d,Q,De)}catch(F){O.warn({err:F},`Failed to update run attempt for attempt ${Q}. You may see stale data on the Momentic Cloud Server.`)}};try{await te({status:"RUNNING",attempts:Ae+1});let{controller:De,context:F,flagStore:sn}=await bb({baseUrl:a,envName:u,apiClient:i,devicePixelRatio:C,logger:O,storageClient:l,codeEvalTools:c,test:we,generator:s,orgId:p,variables:g,customHeaders:h,testInputs:f,localBrowserConfig:v?.browser??r.config.browser,visualDiffScreenshotStorage:N,analytics:I});L=await xb({attemptMetadata:{attemptNumber:Ae+1,orgId:p,runId:d,runAttemptId:Q},attemptFixtures:{logger:O,storageClient:l,billingReporter:T,analytics:I,debugDataClient:V,codeEvalTools:c,flagStore:sn,apiClient:i,context:F,controller:De},attemptInputs:{test:we,orgSettings:J,noReport:S}}),await pt({status:L.status,finishedAt:new Date,results:L.results,beforeResults:L.beforeResults,afterResults:L.afterResults}),se.unshift(L.status);let ue=await Sb({orgId:p,codeEvalTools:c,logger:O,outputDefinitions:e.outputs??[],testContext:F}),Be=new Date,Rt=Ru(se),Je=Be.getTime()-k.getTime(),an=Ae+1;if(L.status!=="FAILED")return L.status==="PASSED"&&I.track({type:"execution:test_success",attempt_count:an,duration_ms:Je,is_flake:Rt}),await te({status:L.status,finishedAt:Be,flake:Rt}),{...L,parameters:de,runId:d,test:we,filePath:we.relativeFilePath,startedAt:k,finishedAt:Be,attempts:an,baseUrl:a,outputs:ue};let _r=L.failedStepResult,Kt=_r?.message||"Unknown failure",Do=_r?.failureReason??om(Kt)??"UnknownError",Zn=O.child({errResult:_r,failureReason:Do,errorMessage:Kt,numAttempts:fe+1,name:we.name});if(Ae<fe){Zn.warn(`Retrying failed execution attempt for run ${d}: ${Kt}`);continue}Zn.error(`Test failed after all exhausting attempts: ${Kt}`);let Fo={errorMessage:Kt};return await te({status:"FAILED",finishedAt:Be,failureDetails:Fo,failureReason:Do}),I.track({type:"execution:test_fail",attempt_count:Ae+1,duration_ms:Be.getTime()-k.getTime(),fail_reason:Fo.errorMessage}),{...L,parameters:de,runId:d,failureDetails:Fo,failureReason:Do,test:we,filePath:we.relativeFilePath,startedAt:k,finishedAt:new Date,attempts:Ae+1,baseUrl:a,outputs:ue}}catch(De){let F=`Encountered fatal platform error while running test '${we.name}': ${De}`,sn=new Date,ue=Ae+1;O.error({err:De},F),b.error(F);let Be={errorMessage:De.message,errStack:De.stack},Rt={status:"FAILED",failureDetails:Be,failureReason:"InternalPlatformError",finishedAt:sn};return await Promise.all([pt(Rt),te(Rt)]),I.track({type:"execution:test_fail",attempt_count:ue,duration_ms:sn.getTime()-k.getTime(),fail_reason:Be.errorMessage}),{...Rt,parameters:de,runId:d,test:we,filePath:we.relativeFilePath,startedAt:k,finishedAt:new Date,attempts:ue,baseUrl:a,outputs:{}}}}throw new Error("This code should not be reachable")}function uL(n){for(let e of n.envs??[])if(e.default)return e.name}async function Cb(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:f,testInputMatrix:g,reporter:y,include:v,exclude:S,labels:E,reporterDir:T="reports",waitOnTimeout:C=60,parallel:P=l.config.parallel??1,shardIndex:k=1,shardCount:N=1,regenerateGoldenFiles:J}=n;r&&(j.info({orgId:m},`Executing start command: ${r}`),await PS(r,!1)),o&&(j.info({orgId:m},`Waiting for url: ${o} with timeout: ${C} seconds.`),await hL({resources:[o],interval:2500,timeout:C*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let V=new eo({baseUrl:i.baseUrl,apiKey:i.apiKey,logger:j}),de=nt(l,b),O=await yb({tests:e,momenticFiles:de,yes:t,project:l,include:v,exclude:S,labels:E}),I=[];O.forEach((ue,Be)=>{g?g.forEach((Rt,Je)=>{I.push({testIndex:Be,inputs:Rt,inputIndex:Je})}):I.push({testIndex:Be,inputs:void 0,inputIndex:void 0})}),N&&N>1&&(I=fL(I,k,N));let te=`Running ${I.length} tests with ${P} workers`;j.info({allTestsToRunWithInputs:I,shardCount:N,shardIndex:k,orgId:m},te),b.dimmed(te),I.forEach(ue=>{b.dimmed(` - ${[O[ue.testIndex].relativeFilePath]}${typeof ue.inputIndex=="number"?` with input set ${ue.inputIndex}`:""}`)}),b.log("");let L=[],fe=Date.now(),se=new Set,Ae=()=>{let ue=i.getAppUrl(),Be=_o({results:L,startTime:fe,onFailed:Je=>{nl(Je,Je.filePath)},getDisplayLine:Je=>{let an=` - ${Je.filePath}${Je.proposedTest?" [AUTO-HEALED] ":""}`;return c&&Je.runId&&(an+=` (${ue}/runs/${Je.runId})`),an},entity:"test"}),Rt=L.filter(Je=>!!Je.proposedTest);return Rt.length>0&&b.warn(`${Rt.length} tests passed with auto-healing. Please use the run links printed above to review proposed changes and apply them locally.`),Be},Q=await gb(b),we=a.child({commit_sha:Q?.gitCommitSha,commit_sha_short:Q?.gitCommitShaShort,branch_name:Q?.gitBranchName,origin_url:Q?.gitOriginUrl,commit_timestamp:Q?.gitCommitTimestamp,github_repository:Q?.githubRepository,gitlab_project_path:Q?.gitlabProjectPath,pipeline_id:Q?.pipelineId}),pt;c&&(pt=(await i.createRunGroup({...Q,trigger:Ut.CLI,startedAt:new Date,status:"RUNNING"})).id);let De=[],F=async()=>{b.warn("SIGINT received. Stopping tests and printing latest results..."),c&&pt&&await i.updateRunGroup(pt,{status:"CANCELLED",finishedAt:new Date}),Ae(),await Promise.allSettled(De.map(ue=>ue())),process.exit(1)};process.on("SIGINT",F);let sn={};for(let ue=0;ue<I.length;ue++){let Be=Object.values(sn);Be.length===P&&await Promise.race(Be.map(an=>an.promise));let Rt=I[ue],Je=`test-${ue}`;sn[Je]={done:!1,promise:(async({testIndex:an,inputs:_r})=>{let Kt=O[an];se.add({testIndex:an,inputs:_r});let Do=Kt.relativeFilePath.includes("..")?Kt.fullFilePath:Kt.relativeFilePath,Zn=(ot,Uo)=>{let Nr=(sl,gp)=>{let Pb=Math.floor((gp-sl.length)/2);return sl.padStart(Pb+sl.length).padEnd(gp)};ot=ot.toUpperCase();let wn=ot;ot.includes("FAIL")?wn=Mo.bgRed.white(Nr("FAIL",8)):ot.includes("PASS")?wn=Mo.bgGreen.white(Nr("PASS",8)):ot.includes("START")?wn=Mo.bgBlue.white(Nr("START",8)):ot.includes("CANCEL")?wn=Mo.bgYellow.white(Nr("CANCEL",8)):ot.includes("RETRY")?wn=Mo.bgYellow.white(Nr("RETRY",8)):ot.includes("RUN")||ot.includes("PROG")?wn=Mo.bgMagenta.white(Nr("RUNNING",8)):j.warn(`Unknown status tried to be logged in run test locally: ${ot}`),mL||(wn=`[${wn}]`),b.log(`${wn} ${Do} ${Uo?`${Uo} `:""}(${se.size}/${I.length})`)};Zn("START");let Fo=setInterval(()=>Zn("RUN"),5*60*1e3);try{let ot=await Eb({testDefinition:Kt,project:l,testInputs:_r,orgId:m,devicePixelRatio:h,apiClient:i,billingReporter:s,analytics:we,generator:V,retriesOverride:d,urlOverride:p,envName:u,noReport:!c,customHeaders:f,regenerateGoldenFiles:J,logUpdate:Zn,runGroupId:pt,runSigIntHandlers:c?De:void 0});Zn(ot.status),L.push(ot)}catch(ot){let Uo=`Encountered unexpected fatal error when running test '${Kt.name}': ${ot.message}`;b.error(Uo),j.error(Uo)}finally{clearInterval(Fo),sn[Je].done=!0,delete sn[Je]}})(Rt)}}if(await Promise.allSettled(Object.values(sn).map(ue=>ue.promise)),c&&pt){let ue="PASSED";L.some(Be=>Be.status==="FAILED")&&(ue="FAILED"),await i.updateRunGroup(pt,{status:ue,finishedAt:new Date})}return process.off("SIGINT",F),y&&await fb(y,{suiteName:`on-demand-suite-${fe}`,startedAt:new Date(fe),finishedAt:new Date,runs:L},T??"reports"),Ae()}function fL(n,e,t){if(t>n.length&&(b.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 Ab=new Oo({platform:"cli"},{flushAt:1,flushInterval:0});ll||j.warn("Sentry is not enabled in this environment due to unsupported node version");var vL=process.argv.some(n=>n.includes("--log-level"))&&process.argv.some(n=>n.includes("debug")),fp=n=>{vL&&b.dimmed(n)},At=new gL;At.name("momentic").description("CLI").version(ko||"unknown");At.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 kr(ob(n),e.force)});At.addOption(new qt("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",n=>{n==="debug"&&b.info("Enabling debug logging"),b.setMinLevel(n.toLowerCase())});At.addOption(new qt("--verbose","enable verbose logging")).on("option:verbose",()=>{j.enableConsoleLogs(),b.setMinLevel(0)});At.command("check-config").addOption(Or).action(async n=>{bn({configFilePath:n.config})});var xL=At.command("checks").alias("check").description("Perform various project checks");xL.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Or).action(async n=>{let e=bn({configFilePath:n.config}),t=nt(e,b),r=Object.values(t.tests),o=await fa(t,j),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,f]of Object.entries(a))for(let g of f)b.error(`Test ID ${h} is duplicated in ${g}`);for(let[h,f]of Object.entries(l))for(let g of f)b.error(`Test Name ${h} is duplicated in ${g}`);for(let h of c)b.error(`Module id ${h} is duplicated in your project`);for(let h of d)b.error(`Module name ${h} is duplicated in your project`);process.exit(1)}b.success("No duplicates detected. All test and module names and ids are unique."),process.exit(0)});var TL=At.command("migrate").description("Migrate and upgrade tooling");TL.command("v0-v1").addOption(Jn).addOption(Yn).action(async n=>{let e=await Xn(n);if(!e.yes&&!await rt("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),!jS().environments?.length&&await rt("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=bn({}),s=new lt({baseUrl:o,apiKey:r,logger:j});await Va({client:s,project:i,skipPrompts:e.yes}),b.success("Successfully imported environments from Momentic Cloud.")}});At.command("import-from-cloud").addOption(Yn).addOption(Lr).addOption(Or).addOption(Jn).action(async n=>{let e=await Xn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=bn({configFilePath:o}),a=new lt({baseUrl:r,apiKey:t,logger:j});await BS({client:a,project:s,skipPrompts:i}),process.exit(0)});At.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new qt("--name <name>","Name of the project")).action(async n=>{b.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3003
- `),b.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."),Rb.existsSync(Co)&&(b.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 NS("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Hi};Ao(t,Co),b.success(`Initialized Momentic project file at ${il.resolve(Co)}`)});At.command("app").addOption(Yn).addOption(Lr).addOption(Jn).addOption(ip).addOption(YS).addOption(Or).action(async n=>{let e=await Xn(n),{apiKey:t,port:r=Ka,yes:o,server:i,pixelRatio:s}=e,a=new lt({baseUrl:i,apiKey:t,logger:j});await cp({client:a,skipPrompts:o,installBrowsers:!0});let l=wL(import.meta.url),c=il.dirname(l),d=il.resolve(c,"..","static"),p=il.resolve(c,"..","assets"),u=s??Jd();Xd(u),zo(),await AS({momenticServerUrl:i,apiKey:t,serverPort:r,appPort:r,staticDir:d,assetsDir:p,devicePixelRatio:u,version:"1.0.87"});let m=`http://localhost:${r}`;await bL(m)});var Ib=At.command("queue").description("Queue tests or suites to run on Momentic Cloud");Ib.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Yn).addOption(Lr).addOption(np).addOption(rp).addOption(Jn).addArgument(eb).addOption(Xa).addOption(Ja).addOption(Ya).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:s,urlOverride:a,customHeaders:l}=await Xn(e),c=new lt({baseUrl:r,apiKey:t,logger:j});(!n||!Array.isArray(n)||!n.length)&&(b.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await lb({client:c,orgId:d,wait:o,suitePaths:n,waitTimeout:i,env:s,urlOverride:a,customHeaders:Za(l)})});Ib.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Yn).addOption(Lr).addOption(Jn).addOption(Ya).addOption(sp).addOption(Xa).addOption(Ja).addOption(np).addOption(rp).addArgument(ZS).action(async(n,e)=>{let t=await Xn(e),{all:r,apiKey:o,customHeaders:i,env:s,server:a,inputCsv:l,urlOverride:c,wait:d,waitTimeout:p,yes:u}=t,m=Za(i);for(let y of n)(y.endsWith(".yaml")||Rb.existsSync(y))&&b.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 lt({baseUrl:a,apiKey:o,logger:j}),{orgId:f}=await h.getAuthInfo(),g;l&&(g=await Zd(l)),await cb({client:h,orgId:f,tests:n,all:r,customHeaders:m,env:s,urlOverride:c,wait:d,waitTimeout:p,testInputMatrix:g,yes:u}),process.exit(0)});var EL=At.command("run").alias("test").description("Run tests on the local machine");EL.addOption(Yn).addOption(Lr).addOption(Or).addOption(ap).addOption(Jn).addOption(Ya).addOption(sp).addOption(Ja).addOption(Xa).addOption(op).addOption(ip).addOption(new qt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new qt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new qt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new qt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new qt("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new qt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new qt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(op).addOption(GS).addOption(VS).addOption(JS).addOption(XS).addOption(qS).addOption(KS).addArgument(QS).action(async(n,e)=>{b.debug("Run tests invoked");let t=await Xn(e);b.debug(t,"Parsed CLI options");let r=Za(t.customHeaders),o=bn({configFilePath:t.config,nameFilter:t.filter});b.debug({projectName:o.config.name},"Identified project config");let i=new lt({baseUrl:t.server,apiKey:t.apiKey,logger:j}),s=new Bs(i),a;t.inputCsv&&(a=await Zd(t.inputCsv)),b.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await cp({client:i,skipPrompts:t.yes,installBrowsers:!0});b.debug("API key check and browser installation complete");let d=t.pixelRatio??Jd();Xd(d);let p=Ab.child({org_id:l,user_id:c,cli_version:ko,trigger:"CLI"});t.report||(p=new $a);try{(await Cb({...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){b.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),b.error(u),process.exit(1)}});var CL=At.command("apply").description("Apply an operation to local resources");CL.command("patch").addOption(Yn).addOption(Lr).addOption(Or).addOption(ap).addOption(Jn).addOption(new qt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new qt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async n=>{let e=await Xn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=bn({configFilePath:o}),a=new lt({baseUrl:r,apiKey:t,logger:j}),l=nt(s,b),c=l.tests[n.to]??Object.values(l.tests).find(p=>Pe(p.name)===n.to.trim());c||(b.error(`No test matching '${n.to}' could be found in the current project.`),process.exit(1));let d=await a.fetchTestFragment(n.from);await MS({client:a,test:c,fragment:d,yes:i,entities:l,logger:j}),process.exit(0)});async function AL(){fp("Main program started"),await LS(j),fp("CLI version check complete");try{await At.parseAsync(process.argv),zo()}catch(n){let e={};try{e.playwrightVersion=yL("npx playwright --version").toString()}catch(t){j.error({err:t},"Error fetching debug information")}j.error({err:n,debugInfo:e},"Uncaught error in CLI"),j.flush(),al(n,e),b.error(n),zo(),process.exit(1)}}SL.setMaxListeners(50);process.on("warning",n=>{j.warn({err:n},`Node warning received on CLI: ${n.message}`)});fp("CLI parsing setup complete");AL();
3002
+ If you believe this is an error, please contact Momentic Support with the following error message: ${v}`)}try{return l?.push(async()=>{!y||i||await r.updateRun(y,{status:"CANCELLED",updatedAt:new Date})}),pL({...n,variables:f,envName:m,runId:y,stepsWithCaches:u,resolvedEnv:h,baseUrl:g,storageClient:c,codeEvalTools:d})}finally{l?.pop()}}async function pL(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:f,variables:g,analytics:y,resolvedEnv:v,noReport:S,retriesOverride:E,billingReporter:T,devicePixelRatio:C,logUpdate:P}=n,k=new Date,N=new Io(r,o),J={ai:r.config.ai},V=new Jr(i,p),de={envName:u,urlOverride:m,customHeaders:h,testInputs:f};d&&(g[uf]=d);let O=j.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 te=async Ce=>{if(!(S||!d))try{await i.updateRun(d,Ce)}catch(Q){O.warn({err:Q},`Failed to update run status for test ${d}. You may see stale data on the Momentic Cloud Server.`)}},L,fe=Math.abs(E??r.config.retries??e.retries??0),se=[];O.info("Starting test run using CLI");for(let Ce=0;Ce<=fe;Ce++){let Q=cL(),we={...e,steps:Tb(t)};if(!S&&d)try{Q=(await i.createRunAttempt(d)).id}catch(De){throw O.error({err:De,testId:we.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&&P("RETRY",`attempt ${Ce+1}/${fe+1}`);let pt=async De=>{if(!(S||!d))try{await i.updateRunAttempt(d,Q,De)}catch(F){O.warn({err:F},`Failed to update run attempt for attempt ${Q}. You may see stale data on the Momentic Cloud Server.`)}};try{await te({status:"RUNNING",attempts:Ce+1});let{controller:De,context:F,flagStore:sn}=await bb({baseUrl:a,envName:u,apiClient:i,devicePixelRatio:C,logger:O,storageClient:l,codeEvalTools:c,test:we,generator:s,orgId:p,variables:g,customHeaders:h,testInputs:f,localBrowserConfig:v?.browser??r.config.browser,visualDiffScreenshotStorage:N,analytics:I});L=await xb({attemptMetadata:{attemptNumber:Ce+1,orgId:p,runId:d,runAttemptId:Q},attemptFixtures:{logger:O,storageClient:l,billingReporter:T,analytics:I,debugDataClient:V,codeEvalTools:c,flagStore:sn,apiClient:i,context:F,controller:De},attemptInputs:{test:we,orgSettings:J,noReport:S}}),await pt({status:L.status,finishedAt:new Date,results:L.results,beforeResults:L.beforeResults,afterResults:L.afterResults}),se.unshift(L.status);let ue=await Sb({orgId:p,codeEvalTools:c,logger:O,outputDefinitions:e.outputs??[],testContext:F}),Be=new Date,Rt=Ru(se),Je=Be.getTime()-k.getTime(),an=Ce+1;if(L.status!=="FAILED")return L.status==="PASSED"&&I.track({type:"execution:test_success",attempt_count:an,duration_ms:Je,is_flake:Rt}),await te({status:L.status,finishedAt:Be,flake:Rt}),{...L,parameters:de,runId:d,test:we,filePath:we.relativeFilePath,startedAt:k,finishedAt:Be,attempts:an,baseUrl:a,outputs:ue};let _r=L.failedStepResult,Kt=_r?.message||"Unknown failure",Do=_r?.failureReason??om(Kt)??"UnknownError",Zn=O.child({errResult:_r,failureReason:Do,errorMessage:Kt,numAttempts:fe+1,name:we.name});if(Ce<fe){Zn.warn(`Retrying failed execution attempt for run ${d}: ${Kt}`);continue}Zn.error(`Test failed after all exhausting attempts: ${Kt}`);let Fo={errorMessage:Kt};return await te({status:"FAILED",finishedAt:Be,failureDetails:Fo,failureReason:Do}),I.track({type:"execution:test_fail",attempt_count:Ce+1,duration_ms:Be.getTime()-k.getTime(),fail_reason:Fo.errorMessage}),{...L,parameters:de,runId:d,failureDetails:Fo,failureReason:Do,test:we,filePath:we.relativeFilePath,startedAt:k,finishedAt:new Date,attempts:Ce+1,baseUrl:a,outputs:ue}}catch(De){let F=`Encountered fatal platform error while running test '${we.name}': ${De}`,sn=new Date,ue=Ce+1;O.error({err:De},F),b.error(F);let Be={errorMessage:De.message,errStack:De.stack},Rt={status:"FAILED",failureDetails:Be,failureReason:"InternalPlatformError",finishedAt:sn};return await Promise.all([pt(Rt),te(Rt)]),I.track({type:"execution:test_fail",attempt_count:ue,duration_ms:sn.getTime()-k.getTime(),fail_reason:Be.errorMessage}),{...Rt,parameters:de,runId:d,test:we,filePath:we.relativeFilePath,startedAt:k,finishedAt:new Date,attempts:ue,baseUrl:a,outputs:{}}}}throw new Error("This code should not be reachable")}function uL(n){for(let e of n.envs??[])if(e.default)return e.name}async function Cb(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:f,testInputMatrix:g,reporter:y,include:v,exclude:S,labels:E,reporterDir:T="reports",waitOnTimeout:C=60,parallel:P=l.config.parallel??1,shardIndex:k=1,shardCount:N=1,regenerateGoldenFiles:J}=n;r&&(j.info({orgId:m},`Executing start command: ${r}`),await PS(r,!1)),o&&(j.info({orgId:m},`Waiting for url: ${o} with timeout: ${C} seconds.`),await hL({resources:[o],interval:2500,timeout:C*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let V=new eo({baseUrl:i.baseUrl,apiKey:i.apiKey,logger:j}),de=nt(l,b),O=await yb({tests:e,momenticFiles:de,yes:t,project:l,include:v,exclude:S,labels:E}),I=[];O.forEach((ue,Be)=>{g?g.forEach((Rt,Je)=>{I.push({testIndex:Be,inputs:Rt,inputIndex:Je})}):I.push({testIndex:Be,inputs:void 0,inputIndex:void 0})}),N&&N>1&&(I=fL(I,k,N));let te=`Running ${I.length} tests with ${P} workers`;j.info({allTestsToRunWithInputs:I,shardCount:N,shardIndex:k,orgId:m},te),b.dimmed(te),I.forEach(ue=>{b.dimmed(` - ${[O[ue.testIndex].relativeFilePath]}${typeof ue.inputIndex=="number"?` with input set ${ue.inputIndex}`:""}`)}),b.log("");let L=[],fe=Date.now(),se=new Set,Ce=()=>{let ue=i.getAppUrl(),Be=_o({results:L,startTime:fe,onFailed:Je=>{nl(Je,Je.filePath)},getDisplayLine:Je=>{let an=` - ${Je.filePath}${Je.proposedTest?" [AUTO-HEALED] ":""}`;return c&&Je.runId&&(an+=` (${ue}/runs/${Je.runId})`),an},entity:"test"}),Rt=L.filter(Je=>!!Je.proposedTest);return Rt.length>0&&b.warn(`${Rt.length} tests passed with auto-healing. Please use the run links printed above to review proposed changes and apply them locally.`),Be},Q=await gb(b),we=a.child({commit_sha:Q?.gitCommitSha,commit_sha_short:Q?.gitCommitShaShort,branch_name:Q?.gitBranchName,origin_url:Q?.gitOriginUrl,commit_timestamp:Q?.gitCommitTimestamp,github_repository:Q?.githubRepository,gitlab_project_path:Q?.gitlabProjectPath,pipeline_id:Q?.pipelineId}),pt;c&&(pt=(await i.createRunGroup({...Q,trigger:Ut.CLI,startedAt:new Date,status:"RUNNING"})).id);let De=[],F=async()=>{b.warn("SIGINT received. Stopping tests and printing latest results..."),c&&pt&&await i.updateRunGroup(pt,{status:"CANCELLED",finishedAt:new Date}),Ce(),await Promise.allSettled(De.map(ue=>ue())),process.exit(1)};process.on("SIGINT",F);let sn={};for(let ue=0;ue<I.length;ue++){let Be=Object.values(sn);Be.length===P&&await Promise.race(Be.map(an=>an.promise));let Rt=I[ue],Je=`test-${ue}`;sn[Je]={done:!1,promise:(async({testIndex:an,inputs:_r})=>{let Kt=O[an];se.add({testIndex:an,inputs:_r});let Do=Kt.relativeFilePath.includes("..")?Kt.fullFilePath:Kt.relativeFilePath,Zn=(ot,Uo)=>{let Nr=(sl,gp)=>{let Pb=Math.floor((gp-sl.length)/2);return sl.padStart(Pb+sl.length).padEnd(gp)};ot=ot.toUpperCase();let wn=ot;ot.includes("FAIL")?wn=Mo.bgRed.white(Nr("FAIL",8)):ot.includes("PASS")?wn=Mo.bgGreen.white(Nr("PASS",8)):ot.includes("START")?wn=Mo.bgBlue.white(Nr("START",8)):ot.includes("CANCEL")?wn=Mo.bgYellow.white(Nr("CANCEL",8)):ot.includes("RETRY")?wn=Mo.bgYellow.white(Nr("RETRY",8)):ot.includes("RUN")||ot.includes("PROG")?wn=Mo.bgMagenta.white(Nr("RUNNING",8)):j.warn(`Unknown status tried to be logged in run test locally: ${ot}`),mL||(wn=`[${wn}]`),b.log(`${wn} ${Do} ${Uo?`${Uo} `:""}(${se.size}/${I.length})`)};Zn("START");let Fo=setInterval(()=>Zn("RUN"),5*60*1e3);try{let ot=await Eb({testDefinition:Kt,project:l,testInputs:_r,orgId:m,devicePixelRatio:h,apiClient:i,billingReporter:s,analytics:we,generator:V,retriesOverride:d,urlOverride:p,envName:u,noReport:!c,customHeaders:f,regenerateGoldenFiles:J,logUpdate:Zn,runGroupId:pt,runSigIntHandlers:c?De:void 0});Zn(ot.status),L.push(ot)}catch(ot){let Uo=`Encountered unexpected fatal error when running test '${Kt.name}': ${ot.message}`;b.error(Uo),j.error(Uo)}finally{clearInterval(Fo),sn[Je].done=!0,delete sn[Je]}})(Rt)}}if(await Promise.allSettled(Object.values(sn).map(ue=>ue.promise)),c&&pt){let ue="PASSED";L.some(Be=>Be.status==="FAILED")&&(ue="FAILED"),await i.updateRunGroup(pt,{status:ue,finishedAt:new Date})}return process.off("SIGINT",F),y&&await fb(y,{suiteName:`on-demand-suite-${fe}`,startedAt:new Date(fe),finishedAt:new Date,runs:L},T??"reports"),Ce()}function fL(n,e,t){if(t>n.length&&(b.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 Ab=new Oo({platform:"cli"},{flushAt:1,flushInterval:0});ll||j.warn("Sentry is not enabled in this environment due to unsupported node version");var vL=process.argv.some(n=>n.includes("--log-level"))&&process.argv.some(n=>n.includes("debug")),fp=n=>{vL&&b.dimmed(n)},At=new gL;At.name("momentic").description("CLI").version(ko||"unknown");At.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 kr(ob(n),e.force)});At.addOption(new qt("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",n=>{n==="debug"&&b.info("Enabling debug logging"),b.setMinLevel(n.toLowerCase())});At.addOption(new qt("--verbose","enable verbose logging")).on("option:verbose",()=>{j.enableConsoleLogs(),b.setMinLevel(0)});At.command("check-config").addOption(Or).action(async n=>{bn({configFilePath:n.config})});var xL=At.command("checks").alias("check").description("Perform various project checks");xL.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Or).action(async n=>{let e=bn({configFilePath:n.config}),t=nt(e,b),r=Object.values(t.tests),o=await fa(t,j),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,f]of Object.entries(a))for(let g of f)b.error(`Test ID ${h} is duplicated in ${g}`);for(let[h,f]of Object.entries(l))for(let g of f)b.error(`Test Name ${h} is duplicated in ${g}`);for(let h of c)b.error(`Module id ${h} is duplicated in your project`);for(let h of d)b.error(`Module name ${h} is duplicated in your project`);process.exit(1)}b.success("No duplicates detected. All test and module names and ids are unique."),process.exit(0)});var TL=At.command("migrate").description("Migrate and upgrade tooling");TL.command("v0-v1").addOption(Jn).addOption(Yn).action(async n=>{let e=await Xn(n);if(!e.yes&&!await rt("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),!jS().environments?.length&&await rt("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=bn({}),s=new lt({baseUrl:o,apiKey:r,logger:j});await Va({client:s,project:i,skipPrompts:e.yes}),b.success("Successfully imported environments from Momentic Cloud.")}});At.command("import-from-cloud").addOption(Yn).addOption(Lr).addOption(Or).addOption(Jn).action(async n=>{let e=await Xn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=bn({configFilePath:o}),a=new lt({baseUrl:r,apiKey:t,logger:j});await BS({client:a,project:s,skipPrompts:i}),process.exit(0)});At.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new qt("--name <name>","Name of the project")).action(async n=>{b.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3003
+ `),b.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."),Rb.existsSync(Co)&&(b.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 NS("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Hi};Ao(t,Co),b.success(`Initialized Momentic project file at ${il.resolve(Co)}`)});At.command("app").addOption(Yn).addOption(Lr).addOption(Jn).addOption(ip).addOption(YS).addOption(Or).action(async n=>{let e=await Xn(n),{apiKey:t,port:r=Ka,yes:o,server:i,pixelRatio:s}=e,a=new lt({baseUrl:i,apiKey:t,logger:j});await cp({client:a,skipPrompts:o,installBrowsers:!0});let l=wL(import.meta.url),c=il.dirname(l),d=il.resolve(c,"..","static"),p=il.resolve(c,"..","assets"),u=s??Jd();Xd(u),zo(),await AS({momenticServerUrl:i,apiKey:t,serverPort:r,appPort:r,staticDir:d,assetsDir:p,devicePixelRatio:u,version:"1.0.89"});let m=`http://localhost:${r}`;await bL(m)});var Ib=At.command("queue").description("Queue tests or suites to run on Momentic Cloud");Ib.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Yn).addOption(Lr).addOption(np).addOption(rp).addOption(Jn).addArgument(eb).addOption(Xa).addOption(Ja).addOption(Ya).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:s,urlOverride:a,customHeaders:l}=await Xn(e),c=new lt({baseUrl:r,apiKey:t,logger:j});(!n||!Array.isArray(n)||!n.length)&&(b.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await lb({client:c,orgId:d,wait:o,suitePaths:n,waitTimeout:i,env:s,urlOverride:a,customHeaders:Za(l)})});Ib.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Yn).addOption(Lr).addOption(Jn).addOption(Ya).addOption(sp).addOption(Xa).addOption(Ja).addOption(np).addOption(rp).addArgument(ZS).action(async(n,e)=>{let t=await Xn(e),{all:r,apiKey:o,customHeaders:i,env:s,server:a,inputCsv:l,urlOverride:c,wait:d,waitTimeout:p,yes:u}=t,m=Za(i);for(let y of n)(y.endsWith(".yaml")||Rb.existsSync(y))&&b.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 lt({baseUrl:a,apiKey:o,logger:j}),{orgId:f}=await h.getAuthInfo(),g;l&&(g=await Zd(l)),await cb({client:h,orgId:f,tests:n,all:r,customHeaders:m,env:s,urlOverride:c,wait:d,waitTimeout:p,testInputMatrix:g,yes:u}),process.exit(0)});var EL=At.command("run").alias("test").description("Run tests on the local machine");EL.addOption(Yn).addOption(Lr).addOption(Or).addOption(ap).addOption(Jn).addOption(Ya).addOption(sp).addOption(Ja).addOption(Xa).addOption(op).addOption(ip).addOption(new qt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new qt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new qt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new qt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new qt("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new qt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new qt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(op).addOption(GS).addOption(VS).addOption(JS).addOption(XS).addOption(qS).addOption(KS).addArgument(QS).action(async(n,e)=>{b.debug("Run tests invoked");let t=await Xn(e);b.debug(t,"Parsed CLI options");let r=Za(t.customHeaders),o=bn({configFilePath:t.config,nameFilter:t.filter});b.debug({projectName:o.config.name},"Identified project config");let i=new lt({baseUrl:t.server,apiKey:t.apiKey,logger:j}),s=new Bs(i),a;t.inputCsv&&(a=await Zd(t.inputCsv)),b.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await cp({client:i,skipPrompts:t.yes,installBrowsers:!0});b.debug("API key check and browser installation complete");let d=t.pixelRatio??Jd();Xd(d);let p=Ab.child({org_id:l,user_id:c,cli_version:ko,trigger:"CLI"});t.report||(p=new $a);try{(await Cb({...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){b.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),b.error(u),process.exit(1)}});var CL=At.command("apply").description("Apply an operation to local resources");CL.command("patch").addOption(Yn).addOption(Lr).addOption(Or).addOption(ap).addOption(Jn).addOption(new qt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new qt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async n=>{let e=await Xn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=bn({configFilePath:o}),a=new lt({baseUrl:r,apiKey:t,logger:j}),l=nt(s,b),c=l.tests[n.to]??Object.values(l.tests).find(p=>Ie(p.name)===n.to.trim());c||(b.error(`No test matching '${n.to}' could be found in the current project.`),process.exit(1));let d=await a.fetchTestFragment(n.from);await MS({client:a,test:c,fragment:d,yes:i,entities:l,logger:j}),process.exit(0)});async function AL(){fp("Main program started"),await LS(j),fp("CLI version check complete");try{await At.parseAsync(process.argv),zo()}catch(n){let e={};try{e.playwrightVersion=yL("npx playwright --version").toString()}catch(t){j.error({err:t},"Error fetching debug information")}j.error({err:n,debugInfo:e},"Uncaught error in CLI"),j.flush(),al(n,e),b.error(n),zo(),process.exit(1)}}SL.setMaxListeners(50);process.on("warning",n=>{j.warn({err:n},`Node warning received on CLI: ${n.message}`)});fp("CLI parsing setup complete");AL();
3004
3004
  //# sourceMappingURL=cli.js.map
3005
- //# debugId=21e59e86-f837-5b15-851d-f3319cc9f773
3005
+ //# debugId=480b6943-ca59-5780-955c-50915548ced6