momentic 2.10.0 → 2.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="20a6e42e-fc62-5145-882a-a2ccb782ee62")}catch(e){}}();
|
|
4
4
|
var yE=Object.create;var um=Object.defineProperty;var bE=Object.getOwnPropertyDescriptor;var wE=Object.getOwnPropertyNames;var vE=Object.getPrototypeOf,TE=Object.prototype.hasOwnProperty;var mm=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var EE=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wE(e))!TE.call(n,o)&&o!==t&&um(n,o,{get:()=>e[o],enumerable:!(r=bE(e,o))||r.enumerable});return n};var xE=(n,e,t)=>(t=n!=null?yE(vE(n)):{},EE(e||!n||!n.__esModule?um(t,"default",{value:n,enumerable:!0}):t,n));var PS=mm((y4,IS)=>{"use strict";IS.exports=RS;function RS(n,e,t){n instanceof RegExp&&(n=CS(n,t)),e instanceof RegExp&&(e=CS(e,t));var r=AS(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 CS(n,e){var t=e.match(n);return t?t[0]:null}RS.range=AS;function AS(n,e,t){var r,o,i,a,s,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&&!s;)d==l?(r.push(d),l=t.indexOf(n,d+1)):r.length==1?s=[r.pop(),c]:(o=r.pop(),o<i&&(i=o,a=c),c=t.indexOf(e,d+1)),d=l<c&&l>=0?l:c;r.length&&(s=[i,a])}return s}});var FS=mm((b4,DS)=>{"use strict";var LS=PS();DS.exports=EI;var OS="\0SLASH"+Math.random()+"\0",MS="\0OPEN"+Math.random()+"\0",ep="\0CLOSE"+Math.random()+"\0",NS="\0COMMA"+Math.random()+"\0",kS="\0PERIOD"+Math.random()+"\0";function Zd(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function vI(n){return n.split("\\\\").join(OS).split("\\{").join(MS).split("\\}").join(ep).split("\\,").join(NS).split("\\.").join(kS)}function TI(n){return n.split(OS).join("\\").split(MS).join("{").split(ep).join("}").split(NS).join(",").split(kS).join(".")}function _S(n){if(!n)return[""];var e=[],t=LS("{","}",n);if(!t)return n.split(",");var r=t.pre,o=t.body,i=t.post,a=r.split(",");a[a.length-1]+="{"+o+"}";var s=_S(i);return i.length&&(a[a.length-1]+=s.shift(),a.push.apply(a,s)),e.push.apply(e,a),e}function EI(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),Sa(vI(n),!0).map(TI)):[]}function xI(n){return"{"+n+"}"}function CI(n){return/^-?0\d/.test(n)}function RI(n,e){return n<=e}function AI(n,e){return n>=e}function Sa(n,e){var t=[],r=LS("{","}",n);if(!r)return[n];var o=r.pre,i=r.post.length?Sa(r.post,!1):[""];if(/\$$/.test(r.pre))for(var a=0;a<i.length;a++){var s=o+"{"+r.body+"}"+i[a];t.push(s)}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+ep+r.post,Sa(n)):[n];var u;if(d)u=r.body.split(/\.\./);else if(u=_S(r.body),u.length===1&&(u=Sa(u[0],!1).map(xI),u.length===1))return i.map(function($){return r.pre+u[0]+$});var m;if(d){var h=Zd(u[0]),g=Zd(u[1]),f=Math.max(u[0].length,u[1].length),S=u.length==3?Math.abs(Zd(u[2])):1,b=RI,w=g<h;w&&(S*=-1,b=AI);var T=u.some(CI);m=[];for(var C=h;b(C,g);C+=S){var E;if(c)E=String.fromCharCode(C),E==="\\"&&(E="");else if(E=String(C),T){var A=f-E.length;if(A>0){var k=new Array(A+1).join("0");C<0?E="-"+k+E.slice(1):E=k+E}}m.push(E)}}else{m=[];for(var O=0;O<u.length;O++)m.push.apply(m,Sa(u[O],!1))}for(var O=0;O<m.length;O++)for(var a=0;a<i.length;a++){var s=o+m[O]+i[a];(!e||d||s)&&t.push(s)}}return t}});var Ni=(n,e)=>{},Fc=!1;try{let n=await import("@sentry/node");Ni=n.captureException,n.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),Fc=!0}catch{}import{Command as aD,Option as Mt}from"@commander-js/extra-typings";import{execSync as sD}from"child_process";import{randomUUID as lD}from"crypto";import Dv from"body-parser";import Ok from"cors";import Mk from"dedent";import Nk from"events";import Fv,{Router as kk}from"express";import{diff as yI}from"deep-object-diff";import pn from"fs";import eo from"path";import{diff as GA}from"deep-object-diff";import{z as hm}from"zod";var vD=hm.object({input:hm.string()});import{z as qe}from"zod";var xD=qe.object({srcs:qe.array(qe.string()),urls:qe.array(qe.string()),desiredSrc:qe.string().optional(),desiredUrl:qe.string().optional()}),gm=qe.object({srcRegex:qe.string().optional(),urlRegex:qe.string().optional()}),fm=qe.object({x:qe.number(),y:qe.number(),correlation:qe.number()}),CD=qe.object({searchImageBase64String:qe.string(),pageImageBase64String:qe.string(),id:qe.string().uuid(),timeoutMs:qe.number().max(1e4).min(0).optional()});import{z as _}from"zod";import*as U from"zod";function Ie(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}}Ie(U);var cr=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(cr||{}),CE=U.object({mPathSelectorTokens:U.string().array(),frameSrcRegex:U.string().optional(),frameUrlRegex:U.string().optional(),indices:U.number().array()}),Uc=U.object({result:U.number(),traceId:U.string()}).array(),ki=U.object({type:U.literal("GCS_TRACES"),traces:Uc}),Lr=U.object({id:U.number().int(),dataMomenticId:U.number().int().optional(),selector:U.string().optional(),hybridSelector:U.object({textContent:U.string().nullish(),attributes:U.record(U.string(),U.string()),tagName:U.string(),expandShadowRoot:U.boolean().optional(),classNames:U.string().array(),nthChild:U.number()}).array().optional(),generatedSelectors:U.string().array().optional(),role:U.string().optional(),name:U.string().optional(),numChildren:U.number().optional(),content:U.string().optional(),pathFromRoot:U.string().optional(),serializedForm:U.string().optional(),nodeOnlySerializedForm:U.string().optional(),serializedHtml:U.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:U.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:U.string().url().optional(),boundingBox:U.object({x:U.number().optional(),y:U.number().optional(),width:U.number(),height:U.number()}).describe("css pixel bounding box").optional(),frameCache:CE.optional(),inputDescription:U.string().optional().describe("the description that generated this cache"),targetSource:U.nativeEnum(cr).optional(),targetUpdateTime:U.string().optional(),targetUpdateLoggerTags:U.record(U.string(),U.string()).optional(),cacheResolutionUpdateSource:U.string().optional(),cacheResolutionUpdateTime:U.string().optional(),cacheResolutionUpdateLoggerTags:U.record(U.string(),U.string()).optional(),memory:ki.optional()}).openapi({ref:"ElementTargetCache"});function Sm(n){return!!(n.name||n.role||n.content||n.serializedForm||n.serializedHtml||n.screenshotUrl)}var RE=U.object({type:U.literal("description"),elementDescriptor:U.string(),a11yData:Lr.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),AE=U.object({x:U.number(),y:U.number()}),IE=U.object({type:U.literal("coordinates"),pixels:AE}).openapi({ref:"CoordinatesTarget"});function dr(n){return n.type==="description"}function Tn(n){return n.type==="coordinates"}var ct=U.discriminatedUnion("type",[RE,IE]).openapi({ref:"ElementTarget"});function Bc(n){if(!n)return!1;switch(n.type){case"description":return!!n.elementDescriptor}return!0}function dt(n){if(!n)return"";switch(n.type){case"description":return n.elementDescriptor;case"coordinates":return`x: ${n.pixels.x}, y: ${n.pixels.y}`}}import{v4 as ye}from"uuid";import*as v from"zod";import{z as Q}from"zod";import{z as To}from"zod";var zc=To.object({result:To.boolean(),traceId:To.string()}).array(),Hc=To.object({type:To.literal("GCS_TRACES"),traces:zc}),ym=To.object({memory:Hc.optional()});var ns=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};Ie(Q);var bm=Q.object({plan:Q.string().optional(),evidence:Q.string().optional(),thoughts:Q.string(),result:Q.boolean(),relevantElements:Q.array(Q.number()).optional(),updatedMemory:zc.optional()}),pr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(pr||{});var PE=Q.object({type:Q.literal("ELEMENT_NAME"),negated:Q.boolean().optional(),operation:Q.nativeEnum(pr),value:Q.string()}).openapi({ref:"ElementNameAssertion"}),LE=Q.object({type:Q.literal("ELEMENT_STYLE"),negated:Q.boolean().optional(),operation:Q.nativeEnum(pr),property:Q.string(),value:Q.string()}).openapi({ref:"ElementStyleAssertion"}),OE=Q.object({type:Q.literal("ELEMENT_CONTENT"),negated:Q.boolean().optional(),operation:Q.nativeEnum(pr),value:Q.string()}).openapi({ref:"ElementContentAssertion"}),ME=Q.object({type:Q.literal("ELEMENT_ATTRIBUTE"),negated:Q.boolean().optional(),operation:Q.nativeEnum(pr),attr:Q.string(),value:Q.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Eo=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Eo||{}),NE=Q.object({type:Q.literal("ELEMENT_EXISTENCE"),negated:Q.boolean().optional(),condition:Q.nativeEnum(Eo).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),wm=Q.discriminatedUnion("type",[OE,ME,NE,PE,LE]).openapi({ref:"ManualElementAssertion"});var kE=Q.object({type:Q.literal("CONTENT"),negated:Q.boolean().optional(),value:Q.string()}).openapi({ref:"PageContentAssertion"}),vm=Q.discriminatedUnion("type",[kE]).openapi({ref:"ManualPageAssertion"});import{z as ce}from"zod";var rs=ce.object({url:ce.string(),method:ce.union([ce.literal("GET"),ce.literal("POST"),ce.literal("PUT"),ce.literal("DELETE"),ce.literal("PATCH")]),headers:ce.record(ce.string(),ce.string()).optional(),params:ce.record(ce.string(),ce.string()).optional(),body:ce.string().optional(),timeout:ce.number().int().optional().describe("Max seconds to wait for the request to complete")}),Tm=ce.object({url:ce.string(),headers:ce.record(ce.string(),ce.string()).optional(),query:ce.string(),variables:ce.record(ce.string(),ce.string()).optional(),timeout:ce.number().int().optional().describe("Max seconds to wait for the request to complete")}),os=ce.object({code:ce.string(),fragment:ce.boolean().optional(),environment:ce.union([ce.literal("NODE"),ce.literal("BROWSER")]).optional().describe("default NODE"),timeout:ce.number().int().max(60).optional().describe("Max seconds for the code to complete")});var De=(H=>(H.AI_EXTRACT="AI_EXTRACT",H.AI_ASSERTION="AI_ASSERTION",H.AUTH_LOAD="AUTH_LOAD",H.AUTH_SAVE="AUTH_SAVE",H.BLUR="BLUR",H.CAPTCHA="CAPTCHA",H.CLICK="CLICK",H.COOKIE="COOKIE",H.COPY="COPY",H.DIALOG="DIALOG",H.DRAG="DRAG",H.ELEMENT_CHECK="ELEMENT_CHECK",H.FILE_UPLOAD="FILE_UPLOAD",H.FOCUS="FOCUS",H.GO_BACK="GO_BACK",H.GO_FORWARD="GO_FORWARD",H.HOVER="HOVER",H.JAVASCRIPT="JAVASCRIPT",H.LOCAL_STORAGE="LOCAL_STORAGE",H.MOUSE_DRAG="MOUSE_DRAG",H.NAVIGATE="NAVIGATE",H.NEW_TAB="NEW_TAB",H.PAGE_CHECK="PAGE_CHECK",H.PASTE="PASTE",H.PRESS="PRESS",H.KEY_DOWN="KEY_DOWN",H.KEY_UP="KEY_UP",H.REFRESH="REFRESH",H.REQUEST="REQUEST",H.GRAPHQL_REQUEST="GRAPHQL_REQUEST",H.SCROLL_DOWN="SCROLL_DOWN",H.SCROLL_UP="SCROLL_UP",H.SCROLL_LEFT="SCROLL_LEFT",H.SCROLL_RIGHT="SCROLL_RIGHT",H.SELECT_OPTION="SELECT_OPTION",H.SWITCH_TAB="TAB",H.TYPE="TYPE",H.VISUAL_DIFF="VISUAL_DIFF",H.WAIT="WAIT",H.WAIT_FOR_URL="WAIT_FOR_URL",H.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",H.AWAIT_LISTENER="AWAIT_LISTENER",H.RECORD_REQUESTS="RECORD_REQUESTS",H.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",H.SET_HEADER="SET_HEADER",H.OFFLINE_MODE="OFFLINE_MODE",H.SUCCESS="SUCCESS",H))(De||{});Ie(v);var V=v.object({thoughts:v.string().optional(),id:v.string().uuid().describe("unique identifier to this step, used for step cache")}),zt=v.object({useSelector:v.boolean().optional(),force:v.boolean().optional(),disableCache:v.boolean().optional().describe("disable element caching for this step"),iframeUrl:v.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),En=v.object({target:Lr}).optional().openapi({ref:"SingleTargetCache"}),is=v.object({loadTimeout:v.number().int().max(60).optional().describe("Max seconds for the page to load")}),_E=V.merge(is).merge(v.object({type:v.literal("NAVIGATE"),url:v.string()})).openapi({ref:"NavigateCommand"}),as=zt.merge(v.object({cache:En})),xo=V.merge(as.merge(v.object({target:ct.optional(),type:v.literal("SCROLL_UP"),deltaY:v.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Co=V.merge(as.merge(v.object({target:ct.optional(),type:v.literal("SCROLL_DOWN"),deltaY:v.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Ro=V.merge(as.merge(v.object({target:ct.optional(),type:v.literal("SCROLL_LEFT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ao=V.merge(as.merge(v.object({target:ct.optional(),type:v.literal("SCROLL_RIGHT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollRightCommand"}),QD=v.discriminatedUnion("type",[xo,Co,Ro,Ao]).openapi({ref:"AllScrollCommands"}),DE=V.merge(v.object({type:v.literal("DIALOG"),action:v.union([v.literal("ACCEPT"),v.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),FE=V.merge(v.object({type:v.literal("WAIT"),delay:v.number()})).openapi({ref:"WaitCommand"}),UE=v.discriminatedUnion("type",[v.object({type:v.literal("SUBSTRING"),url:v.string()}),v.object({type:v.literal("GLOB"),glob:v.string()}),v.object({type:v.literal("REGEX"),regex:v.string()})]),BE=v.object({caseInsensitive:v.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:v.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:v.number().int().optional().describe("Max seconds to wait for the URL to match")}),zE=V.extend({type:v.literal("WAIT_FOR_URL"),matcher:UE}).merge(BE).openapi({ref:"WaitUrlCommand"}),HE=V.merge(is).merge(v.object({type:v.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),jE=V.merge(v.object({type:v.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),$E=V.merge(v.object({type:v.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),GE=V.extend({type:v.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),WE=V.extend({type:v.literal("AUTH_LOAD"),storageState:v.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),$c=V.merge(zt).extend({type:v.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),VE=V.extend({type:v.literal("COPY"),value:v.string()}).openapi({ref:"CopyCommand"}),qE=V.extend({type:v.literal("PASTE")}).openapi({ref:"PasteCommand"}),KE=V.merge(os).extend({type:v.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Di=V.merge(zt).extend({type:v.literal("CLICK"),target:ct,doubleClick:v.boolean().optional(),rightClick:v.boolean().optional(),waitForDownload:v.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:v.number().optional(),downloadTimeoutMs:v.number().optional(),cache:En,relativePosition:v.object({x:v.number(),y:v.number()}).optional()}).openapi({ref:"ClickCommand"}),Fi=V.merge(zt).merge(v.object({type:v.literal("DRAG"),fromTarget:ct,toTarget:ct,steps:v.number().optional(),hoverSeconds:v.number().optional().describe("Seconds to hover the object before dropping"),cache:v.object({fromTarget:Lr.optional(),toTarget:Lr.optional()}).optional()})).openapi({ref:"DragCommand"}),Ui=V.merge(zt).merge(v.object({type:v.literal("MOUSE_DRAG"),target:ct.optional(),deltaX:v.string().describe("pixels to move horizontally, can be template"),deltaY:v.string().describe("pixels to move vertically, can be template"),steps:v.number().optional(),cache:En})).openapi({ref:"MouseDragCommand"}),Bi=V.merge(zt).merge(v.object({type:v.literal("HOVER"),target:ct,cache:En})).openapi({ref:"HoverCommand"}),zi=V.merge(zt).merge(v.object({type:v.literal("FOCUS"),target:ct,cache:En})).openapi({ref:"FocusCommand"}),Hi=V.merge(zt).extend({type:v.literal("BLUR"),target:ct.optional(),cache:En}).openapi({ref:"BlurCommand"}),YE=v.object({type:v.literal("URL"),url:v.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),XE=v.object({type:v.literal("USER_FILE"),name:v.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),JE=V.extend({type:v.literal("FILE_UPLOAD"),fileSource:v.discriminatedUnion("type",[YE,XE]),filename:v.string().optional()}).openapi({ref:"FileUploadCommand"}),QE=v.discriminatedUnion("type",[v.object({type:v.literal("VALUE"),value:v.string()}),v.object({type:v.literal("LABEL"),label:v.string()}),v.object({type:v.literal("INDEX"),index:v.coerce.string()})]),ji=V.merge(zt).extend({type:v.literal("SELECT_OPTION"),target:ct,cache:En,choice:QE.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Gc=v.union([v.literal("MULTIMODAL"),v.literal("VISION_ONLY")]),ss=V.merge(v.object({type:v.literal("AI_ASSERTION"),assertion:v.string(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional(),contextChoice:Gc.optional(),timeout:v.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:ym.optional()})).openapi({ref:"AIAssertionCommand"}),xn=5,Wc=600,$i=V.merge(zt).extend({type:v.literal("ELEMENT_CHECK"),target:ct,assertion:wm,cache:En,timeout:v.number().int().min(0).max(Wc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),ZE=V.extend({type:v.literal("PAGE_CHECK"),assertion:vm,iframeUrl:v.string().optional().describe("url or url regex for the iframe"),timeout:v.number().int().min(0).max(Wc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),ex=V.merge(v.object({type:v.literal("AI_EXTRACT"),goal:v.string(),schema:v.string().optional(),envKey:v.string().optional(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional()})).openapi({ref:"AIExtractCommand"}),tx=v.object({clearContent:v.boolean().optional(),forceClearContent:v.boolean().optional(),delay:v.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:v.boolean().optional(),pressEnter:v.boolean().optional()}),Em=25,Gi=V.merge(zt).merge(tx).extend({type:v.literal("TYPE"),target:ct.optional(),value:v.string(),cache:En}).openapi({ref:"TypeCommand"}),nx=V.merge(v.object({type:v.literal("PRESS"),value:v.string(),repeat:v.number().optional(),convertMeta:v.boolean().optional(),delayMs:v.number().optional()})).openapi({ref:"PressCommand"}),rx=V.merge(v.object({type:v.literal("KEY_DOWN"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyDownCommand"}),ox=V.merge(v.object({type:v.literal("KEY_UP"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyUpCommand"}),ix=v.object({type:v.literal("SUBSTRING"),substring:v.string()}),ax=v.object({type:v.literal("REGEX"),pattern:v.string()}),sx=v.object({type:v.literal("INDEX"),index:v.coerce.string()}),lx=v.discriminatedUnion("type",[ix,ax,sx]),cx=V.merge(is).merge(v.object({type:v.literal("TAB"),action:lx})).openapi({ref:"TabCommand"}),dx=V.merge(is).merge(v.object({type:v.literal("NEW_TAB"),url:v.string()})).openapi({ref:"NewTabCommand"}),px=V.merge(v.object({type:v.literal("COOKIE"),value:v.string()})).openapi({ref:"CookieCommand"}),ux=V.merge(v.object({type:v.literal("LOCAL_STORAGE"),key:v.string(),value:v.string()})).openapi({ref:"LocalStorageCommand"}),mx=V.extend({type:v.literal("REQUEST")}).merge(rs).openapi({ref:"RequestCommand"}),hx=V.extend({type:v.literal("GRAPHQL_REQUEST")}).merge(Tm).openapi({ref:"GraphQLRequestCommand"}),gx=V.merge(v.object({type:v.literal("SUCCESS"),condition:ss.optional()})).openapi({ref:"SuccessCommand"}),fx=V.merge(v.object({type:v.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Sx=v.object({data:v.string().describe("location at which to find a jpg"),width:v.number(),height:v.number()}),Wi=V.merge(zt).merge(v.object({type:v.literal("VISUAL_DIFF"),threshold:v.number().optional().describe("default 0.1"),target:ct.optional(),screenshot:Sx.optional(),cache:En})).openapi({ref:"VisualDiffCommand"}),yx=V.merge(v.object({type:v.literal("REGISTER_REQUEST_LISTENER"),pattern:v.string(),key:v.string()})).openapi({ref:"RegisterRequestListenerCommand"}),bx=V.merge(v.object({type:v.literal("AWAIT_LISTENER"),key:v.string(),timeout:v.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),wx=V.merge(v.object({type:v.literal("RECORD_REQUESTS"),pattern:v.string(),key:v.string()})).openapi({ref:"RecordRequestsCommand"}),vx=V.merge(v.object({type:v.literal("GET_RECORDED_REQUESTS"),key:v.string()})).openapi({ref:"GetRecordedRequestsCommand"}),Tx=V.merge(v.object({type:v.literal("SET_HEADER"),name:v.string(),value:v.string(),urlPattern:v.string().optional().describe("URL pattern to match")})).openapi({ref:"SetHeaderCommand"}),Ex=V.merge(v.object({type:v.literal("OFFLINE_MODE"),enable:v.boolean()})).openapi({ref:"OfflineModeCommand"}),xm=v.discriminatedUnion("type",[Di,Gi,nx,rx,ox,ji,_E,Co,xo,ss,Bi,FE,gx]),xx=v.discriminatedUnion("type",[ex,WE,GE,$c,px,VE,DE,Fi,$i,JE,jE,$E,KE,ux,Ui,dx,ZE,qE,HE,mx,hx,Ro,Ao,cx,Wi,zi,Hi,zE,yx,bx,wx,vx,Tx,Ex]),Io=v.discriminatedUnion("type",[...xm.options,...xx.options]).openapi({ref:"Command"}),ls=v.discriminatedUnion("type",[...xm.options,fx]);function $n(n){let e;switch(n){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:ye(),type:n};break;case"AUTH_LOAD":{e={id:ye(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:ye(),type:n,goal:""};break;case"DIALOG":e={id:ye(),type:n,action:"DISMISS"};break;case"DRAG":e={id:ye(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ye(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ye(),type:n,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ye(),type:n,delay:1};break;case"BLUR":e={id:ye(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ye(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ye(),type:n,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ye(),type:n,value:""};break;case"SELECT_OPTION":e={id:ye(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ye(),type:n,url:""};case"TAB":e={id:ye(),type:n,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ye(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ye(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ye(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:ye(),type:n,code:""};break;case"AI_ASSERTION":e={id:ye(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:ye(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ye(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ye(),type:n,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ye(),type:n,pattern:"",key:""};break}case"AWAIT_LISTENER":{e={id:ye(),type:n,key:""};break}case"RECORD_REQUESTS":{e={id:ye(),type:n,pattern:"",key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ye(),type:n,key:""};break}case"SET_HEADER":{e={id:ye(),type:n,name:"",value:""};break}case"OFFLINE_MODE":{e={id:ye(),type:n,enable:!0};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}function Cm(n){switch(n.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}import{z as Cx}from"zod";var rF=Cx.discriminatedUnion("type",[Hi,$c,Di,Fi,zi,Bi,Ui,xo,Co,Ro,Ao,ji,Gi,Wi,$i]);function Rm(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as Rx}from"zod";var wt={type:!0,cache:!0},Or=Rx.discriminatedUnion("type",[ss.pick(wt),Hi.pick(wt),Di.pick(wt),Fi.pick(wt),$i.pick(wt),zi.pick(wt),Bi.pick(wt),Ui.pick(wt),xo.pick(wt),Co.pick(wt),Ro.pick(wt),Ao.pick(wt),ji.pick(wt),Gi.pick(wt),Wi.pick(wt)]),Vc=Object.values(De).filter(n=>Or.options.some(e=>e.shape.type.safeParse(n).success));Io.options.forEach(n=>{if("target"in n.shape&&!Vc.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as qc}from"zod";import{z as Am}from"zod";import{z as Mr}from"zod";var Ht=Mr.object({index:Mr.number().optional().describe("global index within a test (in-order traversal)"),id:Mr.string(),skipped:Mr.boolean().optional(),envKey:Mr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Mr.boolean().optional(),retries:Mr.number().optional()});Ie(Am);var Ax=Ht.extend({type:Am.literal("PRESET_ACTION")}),At=Ax.extend({command:Io}).openapi({ref:"PresetAction"});Ie(qc);var Nr=Ht.extend({type:qc.literal("AI_ACTION"),text:qc.string(),steps:At.array().optional()}).openapi({ref:"AIAction"});import{z as vt}from"zod";import{z as cs}from"zod";Ie(cs);var Po=Ht.extend({type:cs.literal("AI_ACTION_DYNAMIC"),text:cs.string(),retries:cs.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Im}from"zod";var Kc=Ht.extend({type:Im.literal("CONDITIONAL"),skipped:Im.boolean().optional()});import{z as ae}from"zod";var Ix=ae.object({cacheKey:ae.string(),cacheExpiryMs:ae.number()}),Yc=Ht.extend({id:ae.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ae.record(ae.string()).optional(),cacheConfig:Ix.optional()}),Gn=Yc.extend({type:ae.literal("MODULE"),moduleId:ae.string().uuid()}),Px=ae.union([Gn.pick({type:!0,moduleId:!0}),ae.record(ae.unknown())]),Lx=ae.object({type:ae.literal("URL_REGEX"),regex:ae.string()}),Ox=ae.object({type:ae.literal("PAGE_CHECK"),substring:ae.string()}),Xc=ae.object({cacheInvalidation:ae.discriminatedUnion("type",[Ox,Lx]).optional()}),It=ae.object({moduleId:ae.string().uuid(),name:ae.string(),description:ae.string().nullish(),enabled:ae.boolean().nullish(),parameters:ae.string().array().nullish(),defaultParameters:ae.record(ae.string(),ae.string()).nullish(),parameterEnums:ae.record(ae.string(),ae.string().array()).nullish(),defaultCacheKey:ae.string().nullish(),defaultCacheTtl:ae.number().nullish(),defaultCacheAllInvocations:ae.boolean().nullish(),autoAuth:ae.boolean().nullish(),advanced:Xc.nullish()});import{z as jt}from"zod";var Jc=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(Jc||{});var Mx=jt.discriminatedUnion("type",[jt.object({type:jt.literal("NAVIGATE_URL"),url:jt.string().url()}),jt.object({type:jt.literal("GO_TO_SECTION_START")})]),Nx=jt.object({trigger:jt.nativeEnum(Jc).optional(),attempts:jt.number().int().optional(),restartBehavior:Mx}),Vi=Ht.extend({type:jt.literal("SECTION"),description:jt.string().describe("user provided goal of what the section should accomplish"),plan:jt.string().array().optional(),autohealingConfig:Nx.optional()});var Pm=It.merge(Yc).extend({type:vt.literal("RESOLVED_MODULE"),steps:vt.lazy(()=>Ne.array())}),Qc=It.extend({steps:vt.lazy(()=>Ne.array())}),Zc=Vi.extend({steps:vt.lazy(()=>Te.array())}),kx=Vi.extend({steps:vt.lazy(()=>Ne.array())}),kr=Kc.extend({blocks:vt.object({assertion:vt.lazy(()=>At),steps:vt.lazy(()=>Te.array())}).array(),elseSteps:vt.lazy(()=>Te.array().optional())}),_x=Kc.extend({blocks:vt.object({assertion:vt.lazy(()=>At),steps:vt.lazy(()=>Ne.array())}).array(),elseSteps:vt.lazy(()=>Ne.array().optional())}),Te=vt.discriminatedUnion("type",[At,Nr,Po,Gn,kr,Zc]),Ne=vt.discriminatedUnion("type",[At,Nr,Po,Pm,_x,kx]);import{z as $t}from"zod";var Dx=$t.object({steps:Te.array(),beforeSteps:Te.array().nullish(),afterSteps:Te.array().nullish()}),Lo=$t.object({steps:Ne.array(),beforeSteps:Ne.array().nullish(),afterSteps:Ne.array().nullish()}),_r=$t.object({steps:$t.record($t.string(),$t.unknown()).array(),beforeSteps:$t.record($t.string(),$t.unknown()).array().nullish(),afterSteps:$t.record($t.string(),$t.unknown()).array().nullish()});var Le="1.0.20";import{z as ur}from"zod";var ed=ur.object({key:ur.string(),testId:ur.string().optional(),moduleId:ur.string().optional(),organizationId:ur.string(),value:Or}),td=ed.extend({uniqueKey:ur.string()}),h0=ur.record(ur.string(),td);var Lm=_.object({phrase:_.string()}),nd=_.object({thoughts:_.string().optional(),result:_.union([_.literal("NOT_FOUND"),_.string(),_.number(),_.array(_.unknown()),_.record(_.unknown(),_.unknown()),_.unknown()])}),Y0=_.object({text:_.string()}),Om=_.object({thoughts:_.string(),review:_.string().optional(),id:_.number().int(),updatedMemory:Uc.optional()}),ds=(u=>(u.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",u.FEW_WORDS="FEW_WORDS",u.STYLE_TAG="STYLE_TAG",u.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",u.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",u.NONE="NONE",u.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",u.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",u.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",u.PREFER_ASSERTION="PREFER_ASSERTION",u.HTML_ELEMENTS="HTML_ELEMENTS",u.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",u))(ds||{});var Mm=_.object({thoughts:_.string(),category:_.nativeEnum(ds)}),Fx=_.discriminatedUnion("op",[_.object({op:_.literal("replace"),path:_.string(),value:_.string()}),_.object({op:_.literal("add"),path:_.string(),value:_.string()}),_.object({op:_.literal("remove"),path:_.string()})]),X0=_.object({thoughts:_.string(),patches:Fx.array()}),Nm=[_.literal("add"),_.literal("replace"),_.literal("remove")],Ux=_.object({op:_.union(Nm),path:_.string(),value:Ne.optional()}),km=_.object({patches:Ux.array(),thoughts:_.string()});var Bx=_.object({thoughts:_.string(),op:_.union(Nm),value:_.union([_.null(),Ne])}),_m=_.object({reasoning:_.string(),scenario:_.string(),patch:Bx.or(_.null())}),J0=_.object({thoughts:_.string(),evaluation:_.number().min(1).max(10)}),Q0=_.object({observations:_.string(),reasoning:_.string(),command:ls});var rd=_.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 M}from"zod";import*as Z from"zod";var oU=Z.object({thoughts:Z.string().optional().describe("only provided if a description was provided"),target:Lr.optional().describe("only provided if a description was provided"),pageState:Z.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:Z.object({label:Z.string(),value:Z.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:Z.object({data:Z.string(),height:Z.number().int(),width:Z.number().int()}).optional().describe("only provided if returnScreenshot is true")}),ps=Z.union([Z.literal("ELEMENT_CHECK"),Z.literal("NEGATED_CHECK"),Z.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),Z.literal("SELECT_OPTION"),Z.literal("TYPE")]);function Dr(n){if(!("useSelector"in n&&n.useSelector)){if(n.type==="SELECT_OPTION")return"SELECT_OPTION";if(n.type==="TYPE")return"TYPE";if(n.type==="ELEMENT_CHECK"&&n.assertion.type==="ELEMENT_EXISTENCE"&&n.assertion.condition==="EXISTS"&&n.assertion.negated)return"NEGATED_CHECK";if(n.type==="ELEMENT_CHECK"&&n.assertion.type==="ELEMENT_EXISTENCE"&&n.assertion.condition==="VISIBLE"&&n.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(n.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var qi=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(qi||{}),Oo=Z.object({matched:Z.boolean(),reason:Z.string().optional().describe("Human understandable description"),logs:Z.string().array().optional().describe("Logs for debugging")}),zx=Oo.extend({type:Z.literal("USER_SELECTOR")}),Hx=Oo.extend({type:Z.literal("CSS_SELECTOR"),selectors:Z.string().array()}),jx=Oo.extend({type:Z.literal("HYBRID_SELECTOR")}),$x=Oo.extend({type:Z.literal("HTML_DISTANCE"),distance:Z.number().optional(),closestElement:Z.string().optional(),savedElement:Z.string().optional()}),Gx=Oo.extend({type:Z.literal("TEMPLATE_MATCHING"),elementImageUrl:Z.string().url()}),Wx=Oo.extend({type:Z.literal("AUTO_FRAME"),logs:Z.string().array().optional()}),Dm=Z.discriminatedUnion("type",[zx,Hx,jx,$x,Gx,Wx]);import{z as Zi}from"zod";import{z as uR}from"zod";import*as q from"zod";import{cloneDeep as Xi}from"lodash-es";var Vx=n=>{let e=Fm(n,0);if(e===void 0||!Kx(n[e]))return;let t=Fm(n,e+1);if(t!==void 0)return Yx(n,e,t)},Um=Vx,Fm=(n,e)=>{for(let t=e;t<n.length;t+=1){let r=n[t];if(!qx(r))return t}},qx=n=>n===" "||n===" "||n===`
|
|
5
5
|
`||n==="\r",Kx=n=>n==="{"||n==="[",Yx=(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 Xx(r);if(r===void 0)r=i;else if(r[0]===i)r+=i;else return}},Xx=n=>n===void 0?0:n[0]===" "?n.length:n;var Bm=(n,e)=>{let t=od(n,"toPrecision",e,e);return t===void 0?od(n,"toExponential",e,e):t},od=(n,e,t,r)=>{let i=n[e](r).replace(Jx,"$1").replace(Qx,"$1");return i.length<=t?i:r===1?void 0:od(n,e,t,r-1)},Jx=/(e)\+/iu,Qx=/\.?0*($|e)/iu;var Hm=(n,e)=>{if(typeof n!="string")throw new TypeError(`Input must be a JSON string: ${n}`);Zx(e)},Zx=n=>{if(eC(n),n<0)throw new TypeError(`"maxSize" argument must be positive: ${n}`);if(n<zm)throw new TypeError(`"maxSize" argument must be at least ${zm}: ${n}`)},eC=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}`)},zm=7;var us=(n,e,t)=>{let r=$m(e,t);return jm(n,e,r)},jm=(n,e,t)=>{if(t>=e)return t;let r=n[t];return r>=cC&&r<=dC?jm(n,e,t+1):t},ms=(n,e,t)=>{if(t===void 0)return t;let r=$m(e,t);return tC(n,r)},tC=(n,e)=>nC(n,e)?e-3:rC(n,e)?e-2:oC(n,e)?e-1:e,nC=(n,e)=>e>=3&&n[e-3]>=iC&&n[e-3]<=aC,rC=(n,e)=>e>=2&&n[e-2]>=sC,oC=(n,e)=>e>=1&&n[e-1]>=lC,$m=(n,e)=>e<0||Object.is(e,-0)?Math.max(n+e,0):e,iC=240,aC=244,sC=224,lC=194,cC=128,dC=191;var Gm=(n,e,t)=>{let r=globalThis.Buffer.from(n),o=us(r,r.length,e),i=ms(r,r.length,t);return o===0&&i>=r.length?r.toString():r.toString("utf8",o,i)};var Wm=/[\uD800-\uDFFF]/gu,Vm="\uFFFD";var hs=n=>pC(n)?n.replace(Wm,Vm):n,pC=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 sd=({input:n,targetByteCount:e,firstStartSurrogate:t,lastStartSurrogate:r,firstEndSurrogate:o,lastEndSurrogate:i,increment:a,canBacktrack:s,shift:l,charIndexInit:c})=>{let d=c,p=d,u=0;for(;u<e;d+=a){p=d;let h=n.charCodeAt(d);if(Number.isNaN(h))break;if(h<=127){u+=1;continue}if(h<=2047){u+=2;continue}if(u+=3,h<t||h>r)continue;let g=n.charCodeAt(d+a);Number.isNaN(g)||g<o||g>i||(u+=1,d+=a)}return(s&&u>e?p:d)+l};var ld=(n,e,t)=>e<0||Object.is(e,-0)?SC(n,e,t):fC(n,e,t),fC=(n,e,t)=>sd({input:n,targetByteCount:e,firstStartSurrogate:55296,lastStartSurrogate:56319,firstEndSurrogate:56320,lastEndSurrogate:57343,increment:1,canBacktrack:t,shift:0,charIndexInit:0}),SC=(n,e,t)=>sd({input:n,targetByteCount:-e,firstStartSurrogate:56320,lastStartSurrogate:57343,firstEndSurrogate:55296,lastEndSurrogate:56319,increment:-1,canBacktrack:!t,shift:1,charIndexInit:n.length-1});var gs=(n,e,t)=>{let r=ld(n,e,!1),o=yC(n,t),i=r===0&&o===void 0?n:n.slice(r,o);return hs(i)},yC=(n,e)=>{if(e===void 0)return e;let t=ld(n,e,!0);return t===n.length?void 0:t};var Km=(n,e,t)=>{let{textEncoder:r,textDecoder:o}=bC(),i=wC(n),{written:a}=r.encodeInto(n,i),s=us(i,a,e),l=ms(i,a,t),c=l===void 0?a:Math.min(l,a),d=i.subarray(s,c);return o.decode(d)},bC=()=>(cd===void 0&&(cd=new globalThis.TextEncoder,qm=new globalThis.TextDecoder("utf8",{fatal:!1})),{textEncoder:cd,textDecoder:qm}),cd,qm,wC=n=>{let e=n.length*3;return e>vC?new Uint8Array(e):((fs===void 0||fs.length<e)&&(fs=new Uint8Array(e)),fs)},vC=1e5,fs;var Ym=(n,e)=>{if(e===void 0)return e;let t=dd(n,e);return t>=n.length*Xm?void 0:t},dd=(n,e)=>e<=n.length*-Xm?0:e,Xm=4;var Jm=(n,e,t)=>{if(typeof n!="string")throw new TypeError(`First argument must be a string: ${n}`);TC(e),EC(t)},TC=n=>{if(n===void 0)throw new TypeError("Second argument is required.");Qm("Second",n)},EC=n=>{n!==void 0&&Qm("Third",n)},Qm=(n,e)=>{if(!Number.isInteger(e))throw new TypeError(`${n} argument must be an integer: ${e}`)};var Zm=n=>{let e=!0,t=0;for(let r=0;r<pd;r+=1){let o=xC(n,r);o<=127||(e&&(e=!1),o>2047&&(t+=1))}return{asciiOnly:e,longCharsPercentage:t/pd}},xC=(n,e)=>{let t=pd-1,r=1-(t-e)/t,o=Math.round(r*(n.length-1));return n.charCodeAt(o)},pd=50;var CC=(n,e,t)=>{if(Jm(n,e,t),n==="")return n;let r=dd(n,e),o=Ym(n,t);return o===void 0&&Object.is(r,0)?hs(n):RC(n,r,o)},eh=CC,RC=(n,e,t)=>{if(n.length<=AC)return gs(n,e,t);let{asciiOnly:r,longCharsPercentage:o}=Zm(n);return r?PC(n,e,t):o>=IC?gs(n,e,t):th(n,e,t)},AC=200,IC=.4,PC=(n,e,t)=>"Buffer"in globalThis&&"from"in globalThis.Buffer?Gm(n,e,t):th(n,e,t),th=(n,e,t)=>"TextEncoder"in globalThis?Km(n,e,t):gs(n,e,t);var rh=(n,e)=>{let t=JSON.stringify(n),r=MC(t),o=eh(r,0,e-nh.length-Ki.length*2),a=`${LC(o)}${nh}`;return NC(a)},LC=n=>n.replace(OC,""),OC=/(\\|\\u[0-9a-fA-F]{0,3})$/u,MC=n=>n.slice(Ki.length,-Ki.length),NC=n=>`${Ki}${n}${Ki}`,Ki='"',nh="...";var oh=n=>globalThis.Buffer.byteLength(n);var ud=n=>{let e=n.length,t=e;for(let r=0;r<e;r+=1){let o=n.charCodeAt(r);if(o<=kC)continue;if(o<=_C){t+=1;continue}if(t+=2,o<DC||o>FC)continue;let i=n.charCodeAt(r+1);i<UC||i>BC||(r+=1)}return t},kC=127,_C=2047,DC=55296,FC=56319,UC=56320,BC=57343;var ih=()=>zC.bind(void 0,new TextEncoder),zC=(n,e)=>{let t=HC(e);return n.encodeInto(e,t).written},HC=n=>{let e=n.length*3;return e>jC?new Uint8Array(e):((Ss===void 0||Ss.length<e)&&(Ss=new Uint8Array(e)),Ss)},jC=1e5,Ss;var GC=()=>"Buffer"in globalThis&&"byteLength"in globalThis.Buffer?oh:"TextEncoder"in globalThis?WC.bind(void 0,ih()):ud,WC=(n,e)=>e.length<100?ud(e):n(e),ah=GC();var sh=n=>{if(n===null)return VC;if(n===!0)return qC;if(n===!1)return KC;let e=typeof n;return e==="object"?YC:e==="number"?JSON.stringify(n).length:md(n)},VC=4,qC=4,KC=5,YC=2,md=n=>ah(JSON.stringify(n));var ys=({size:n,increment:e,maxSize:t,truncatedProps:r,path:o,value:i})=>{let a=n+e,s=a>t;return s?{size:n,stop:s,truncatedProps:[...r,{path:o,value:i}]}:{size:a,stop:s,truncatedProps:r}},ch=n=>sh(n),dh=(n,e,t)=>{let r=uh({empty:n,indent:e,depth:t,keySpaceSize:0}),o=mh(n);return r+o},ph=({key:n,empty:e,indent:t,depth:r})=>{let o=uh({empty:e,indent:t,depth:r,keySpaceSize:1}),i=md(n),a=mh(e);return o+i+XC+a},XC=1,uh=({empty:n,indent:e,depth:t,keySpaceSize:r})=>{if(e===void 0)return 0;let o=lh+e*(t+1),i=n?lh+e*t:0;return r+o+i},lh=1,mh=n=>n?0:JC,JC=1;var bs=({parent:n,truncatedProps:e,path:t,increment:r,maxSize:o,key:i,empty:a,size:s,truncateValue:l,indent:c,depth:d})=>{let p=n[i],u=[...t,i],{size:m,stop:h,truncatedProps:g}=ys({size:s,increment:r,maxSize:o,truncatedProps:e,path:u,value:p});return h?{empty:a,size:m,truncatedProps:g}:QC({value:p,truncatedProps:e,path:u,maxSize:o,empty:a,size:s,newSize:m,truncateValue:l,indent:c,depth:d})},QC=({value:n,truncatedProps:e,path:t,maxSize:r,empty:o,size:i,newSize:a,truncateValue:s,indent:l,depth:c})=>{let{value:d,size:p,truncatedProps:u}=s({value:n,truncatedProps:e,path:t,size:a,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 hh=({array:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:i,indent:a,depth:s})=>{let l=[],c={empty:!0,size:r,truncatedProps:e};for(let d=0;d<n.length;d+=1){let p=dh(c.empty,a,s);c=bs({parent:n,truncatedProps:c.truncatedProps,path:t,increment:p,maxSize:o,key:d,empty:c.empty,size:c.size,truncateValue:i,indent:a,depth:s}),c.value!==void 0&&l.push(c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var gh=({object:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:i,indent:a,depth:s})=>{let l={},c={empty:!0,size:r,truncatedProps:e};for(let d in n){let p=ph({key:d,empty:c.empty,indent:a,depth:s});c=bs({parent:n,truncatedProps:c.truncatedProps,path:t,increment:p,maxSize:o,key:d,empty:c.empty,size:c.size,truncateValue:i,indent:a,depth:s}),c.value!==void 0&&(l[d]=c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var ws=({value:n,truncatedProps:e,path:t,size:r,maxSize:o,indent:i,depth:a})=>{let s=ch(n),{size:l,stop:c,truncatedProps:d}=ys({size:r,increment:s,maxSize:o,truncatedProps:e,path:t,value:n});return c?{value:void 0,size:l,truncatedProps:d}:ZC({value:n,truncatedProps:d,path:t,size:l,maxSize:o,indent:i,depth:a})},ZC=({value:n,truncatedProps:e,path:t,size:r,maxSize:o,indent:i,depth:a})=>typeof n!="object"||n===null?{value:n,size:r,truncatedProps:e}:Array.isArray(n)?hh({array:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:ws,indent:i,depth:a}):gh({object:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:ws,indent:i,depth:a});var eR=(n,e)=>{Hm(n,e);let t=tR(n),r=nR(n),{value:o,truncatedProps:i}=ws({value:r,truncatedProps:[],path:[],size:0,maxSize:e,indent:t,depth:0});return{jsonString:rR({newValue:o,value:r,maxSize:e,indent:t}),truncatedProps:i}},Mo=eR,tR=n=>{let e=Um(n);return typeof e=="string"?e.length:e},nR=n=>{try{return JSON.parse(n)}catch(e){throw new TypeError(`Invalid JSON string: "${n}"
|
|
@@ -38,7 +38,7 @@ ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length
|
|
|
38
38
|
`)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=Wo.parse(r)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return ut.parse(o)}function to(n,e,t){let r=t.project.rootDir,o;try{o=pn.readFileSync(n,"utf-8")}catch(a){throw e.error({err:a,projectRoot:r},a.message),new Error(a.message)}let i=Wo.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${n} is missing steps`);return i}async function ga(n,e,t){let r=to(n,e,t),o;try{o=Xt.parse(r)}catch(a){throw new Error(`Test ${n} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await uS({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:s})=>{let l=t.modules[a]?.fullFilePath;if(l)return Kn(l,s)}}});return i}import bI from"@dotenvx/dotenvx";import wI from"fs";import TS from"path";function xS(n,e){return(n.config.environments??[]).map(t=>fa(t.name,n,e))}function ES(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 fa(n,e,t){let r=(e.config.environments??[]).find(a=>a.name===n);if(!r)throw new Error(`Environment ${n} not found in local project configuration file`);let o={[Qe]:ES(r.baseUrl)};if(r.envVariables){let a={};for(let[s,l]of Object.entries(r.envVariables))if(typeof l=="string"){let c=ES(l);c&&(a[s]=c)}else{let c=l.fromFile,d;try{d=wI.readFileSync(TS.resolve(e.rootDir,c),"utf-8")}catch(p){throw new Error(`Failed to read environment variable '${s}' from file '${c}': ${p}`)}if(l.json)try{a[s]=JSON.parse(d)}catch(p){throw new Error(`Failed to parse environment variable '${s}' from file '${c}' as JSON: ${p}`)}else a[s]=d}Object.keys(a).length>0&&y.debug(a,"Set environment variables with interpolation from project configuration"),Object.assign(o,a)}if(r.envFile){let a={},s=bI.config({path:TS.resolve(e.rootDir,r.envFile),processEnv:a,logLevel:"error",quiet:!0});if(s.error)throw new Error(`Failed to load .env file: ${s.error.message}`);t.debug(a,"Set environment variables from .env file"),Object.assign(o,a)}return r.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:n,variables:o,browser:r.browser}}import{existsSync as JP,readFileSync as QP,readdirSync as ZP,writeFileSync as eL}from"fs";var WS=xE(FS(),1);var ya=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var II={"[: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]},ba=n=>n.replace(/[[\]\\-]/g,"\\$&"),PI=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),US=n=>n.join(""),BS=(n,e)=>{let t=e;if(n.charAt(t)!=="[")throw new Error("not in a brace expression");let r=[],o=[],i=t+1,a=!1,s=!1,l=!1,c=!1,d=t,p="";e:for(;i<n.length;){let g=n.charAt(i);if((g==="!"||g==="^")&&i===t+1){c=!0,i++;continue}if(g==="]"&&a&&!l){d=i+1;break}if(a=!0,g==="\\"&&!l){l=!0,i++;continue}if(g==="["&&!l){for(let[f,[S,b,w]]of Object.entries(II))if(n.startsWith(f,i)){if(p)return["$.",!1,n.length-t,!0];i+=f.length,w?o.push(S):r.push(S),s=s||b;continue e}}if(l=!1,p){g>p?r.push(ba(p)+"-"+ba(g)):g===p&&r.push(ba(g)),p="",i++;continue}if(n.startsWith("-]",i+1)){r.push(ba(g+"-")),i+=2;continue}if(n.startsWith("-",i+1)){p=g,i+=2;continue}r.push(ba(g)),i++}if(d<i)return["",!1,0,!1];if(!r.length&&!o.length)return["$.",!1,n.length-t,!0];if(o.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!c){let g=r[0].length===2?r[0].slice(-1):r[0];return[PI(g),!1,d-t,!1]}let u="["+(c?"^":"")+US(r)+"]",m="["+(c?"":"^")+US(o)+"]";return[r.length&&o.length?"("+u+"|"+m+")":r.length?u:m,s,d-t,!0]};var un=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var LI=new Set(["!","?","+","*","@"]),zS=n=>LI.has(n),OI="(?!(?:^|/)\\.\\.?(?:$|/))",dl="(?!\\.)",MI=new Set(["[","."]),NI=new Set(["..","."]),kI=new Set("().*{}+?[]^$\\!"),_I=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),tp="[^/]",HS=tp+"*?",jS=tp+"+?",Vo=class n{type;#e;#t;#i=!1;#r=[];#a;#w;#c;#p=!1;#s;#l;#o=!1;constructor(e,t,r={}){this.type=e,e&&(this.#t=!0),this.#a=t,this.#e=this.#a?this.#a.#e:this,this.#s=this.#e===this?r:this.#e.#s,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#p&&this.#c.push(this),this.#w=this.#a?this.#a.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#r.map(e=>String(e)).join("|")+")":this.#l=this.#r.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#p)return this;this.toString(),this.#p=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,r=t.#a;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.#a}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof n&&t.#a===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.#a?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#a?.isStart())return!1;if(this.#w===0)return!0;let e=this.#a;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.#a?.type==="!")return!0;if(!this.#a?.isEnd())return!1;if(!this.type)return this.#a?.isEnd();let e=this.#a?this.#a.#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#S(e,t,r,o){let i=!1,a=!1,s=-1,l=!1;if(t.type===null){let m=r,h="";for(;m<e.length;){let g=e.charAt(m++);if(i||g==="\\"){i=!i,h+=g;continue}if(a){m===s+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(m===s+2&&l)&&(a=!1),h+=g;continue}else if(g==="["){a=!0,s=m,l=!1,h+=g;continue}if(!o.noext&&zS(g)&&e.charAt(m)==="("){t.push(h),h="";let f=new n(g,t);m=n.#S(e,f,m,o),t.push(f);continue}h+=g}return t.push(h),m}let c=r+1,d=new n(null,t),p=[],u="";for(;c<e.length;){let m=e.charAt(c++);if(i||m==="\\"){i=!i,u+=m;continue}if(a){c===s+1?(m==="^"||m==="!")&&(l=!0):m==="]"&&!(c===s+2&&l)&&(a=!1),u+=m;continue}else if(m==="["){a=!0,s=c,l=!1,u+=m;continue}if(zS(m)&&e.charAt(c)==="("){d.push(u),u="";let h=new n(m,d);d.push(h),c=n.#S(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.#S(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.#s.nocase&&!this.#s.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let s=(this.#s.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,s),{_src:t,_glob:e})}get options(){return this.#s}toRegExpSource(e){let t=e??!!this.#s.dot;if(this.#e===this&&this.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#r.map(m=>{let[h,g,f,S]=typeof m=="string"?n.#u(m,this.#t,l):m.toRegExpSource(e);return this.#t=this.#t||f,this.#i=this.#i||S,h}).join(""),d="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&NI.has(this.#r[0]))){let h=MI,g=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),f=!t&&!e&&h.has(c.charAt(0));d=g?OI:f?dl:""}let p="";return this.isEnd()&&this.#e.#p&&this.#a?.type==="!"&&(p="(?:$|\\/)"),[d+c+p,un(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,un(this.toString()),!1,!1]}let a=!r||e||t||!dl?"":this.#m(!0);a===i&&(a=""),a&&(i=`(?:${i})(?:${a})*?`);let s="";if(this.type==="!"&&this.#o)s=(this.isStart()&&!t?dl:"")+jS;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?dl:"")+HS+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;s=o+i+l}return[s,un(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,a]=t.toRegExpSource(e);return this.#i=this.#i||a,r}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#u(e,t,r=!1){let o=!1,i="",a=!1;for(let s=0;s<e.length;s++){let l=e.charAt(s);if(o){o=!1,i+=(kI.has(l)?"\\":"")+l;continue}if(l==="\\"){s===e.length-1?i+="\\\\":o=!0;continue}if(l==="["){let[c,d,p,u]=BS(e,s);if(p){i+=c,a=a||d,s+=p-1,t=t||u;continue}}if(l==="*"){r&&e==="*"?i+=jS:i+=HS,t=!0;continue}if(l==="?"){i+=tp,t=!0;continue}i+=_I(l)}return[i,un(e),!!t,a]}};var qo=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var xt=(n,e,t={})=>(ya(e),!t.nocomment&&e.charAt(0)==="#"?!1:new _t(e,t).match(n)),DI=/^\*+([^+@!?\*\[\(]*)$/,FI=n=>e=>!e.startsWith(".")&&e.endsWith(n),UI=n=>e=>e.endsWith(n),BI=n=>(n=n.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(n)),zI=n=>(n=n.toLowerCase(),e=>e.toLowerCase().endsWith(n)),HI=/^\*+\.\*+$/,jI=n=>!n.startsWith(".")&&n.includes("."),$I=n=>n!=="."&&n!==".."&&n.includes("."),GI=/^\.\*+$/,WI=n=>n!=="."&&n!==".."&&n.startsWith("."),VI=/^\*+$/,qI=n=>n.length!==0&&!n.startsWith("."),KI=n=>n.length!==0&&n!=="."&&n!=="..",YI=/^\?+([^+@!?\*\[\(]*)?$/,XI=([n,e=""])=>{let t=VS([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},JI=([n,e=""])=>{let t=qS([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},QI=([n,e=""])=>{let t=qS([n]);return e?r=>t(r)&&r.endsWith(e):t},ZI=([n,e=""])=>{let t=VS([n]);return e?r=>t(r)&&r.endsWith(e):t},VS=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},qS=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},KS=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",$S={win32:{sep:"\\"},posix:{sep:"/"}},eP=KS==="win32"?$S.win32.sep:$S.posix.sep;xt.sep=eP;var st=Symbol("globstar **");xt.GLOBSTAR=st;var tP="[^/]",nP=tP+"*?",rP="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",oP="(?:(?!(?:\\/|^)\\.).)*?",iP=(n,e={})=>t=>xt(t,n,e);xt.filter=iP;var Zt=(n,e={})=>Object.assign({},n,e),aP=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return xt;let e=xt;return Object.assign((r,o,i={})=>e(r,o,Zt(n,i)),{Minimatch:class extends e.Minimatch{constructor(o,i={}){super(o,Zt(n,i))}static defaults(o){return e.defaults(Zt(n,o)).Minimatch}},AST:class extends e.AST{constructor(o,i,a={}){super(o,i,Zt(n,a))}static fromGlob(o,i={}){return e.AST.fromGlob(o,Zt(n,i))}},unescape:(r,o={})=>e.unescape(r,Zt(n,o)),escape:(r,o={})=>e.escape(r,Zt(n,o)),filter:(r,o={})=>e.filter(r,Zt(n,o)),defaults:r=>e.defaults(Zt(n,r)),makeRe:(r,o={})=>e.makeRe(r,Zt(n,o)),braceExpand:(r,o={})=>e.braceExpand(r,Zt(n,o)),match:(r,o,i={})=>e.match(r,o,Zt(n,i)),sep:e.sep,GLOBSTAR:st})};xt.defaults=aP;var YS=(n,e={})=>(ya(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,WS.default)(n));xt.braceExpand=YS;var sP=(n,e={})=>new _t(n,e).makeRe();xt.makeRe=sP;var lP=(n,e,t={})=>{let r=new _t(e,t);return n=n.filter(o=>r.match(o)),r.options.nonull&&!n.length&&n.push(e),n};xt.match=lP;var GS=/[?*]|[+@!]\(.*?\)|\[|\]/,cP=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),_t=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){ya(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||KS,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,a,s)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!GS.test(i[2]))&&!GS.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 a=this.set[i];a[0]===""&&a[1]===""&&this.globParts[i][2]==="?"&&typeof a[3]=="string"&&/^[a-z]:$/i.test(a[3])&&(a[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 a=o;for(;r[a+1]==="**";)a++;a>o&&r.splice(o+1,a-o);let s=r[o+1],l=r[o+2],c=r[o+3];if(s!==".."||!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 a=1;a<r.length-1;a++){let s=r[a];a===1&&s===""&&r[0]===""||(s==="."||s==="")&&(t=!0,r.splice(a,1),a--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let a=r[i-1];if(a&&a!=="."&&a!==".."&&a!=="**"){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,a=[],s="";for(;o<e.length&&i<t.length;)if(e[o]===t[i])a.push(s==="b"?t[i]:e[o]),o++,i++;else if(r&&e[o]==="**"&&t[i]===e[o+1])a.push(e[o]),o++;else if(r&&t[i]==="**"&&e[o]===t[i+1])a.push(t[i]),i++;else if(e[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(s==="b")return!1;s="a",a.push(e[o]),o++,i++}else if(t[i]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(s==="a")return!1;s="b",a.push(t[i]),o++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let o=this.options;if(this.isWindows){let g=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),f=!g&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),S=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),b=!S&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),w=f?3:g?0:void 0,T=b?3:S?0:void 0;if(typeof w=="number"&&typeof T=="number"){let[C,E]=[e[w],t[T]];C.toLowerCase()===E.toLowerCase()&&(t[T]=C,T>w?t=t.slice(T):w>T&&(e=e.slice(w)))}}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 a=0,s=0,l=e.length,c=t.length;a<l&&s<c;a++,s++){this.debug("matchOne loop");var d=t[s],p=e[a];if(this.debug(t,d,p),d===!1)return!1;if(d===st){this.debug("GLOBSTAR",[t,d,p]);var u=a,m=s+1;if(m===c){for(this.debug("** at the end");a<l;a++)if(e[a]==="."||e[a]===".."||!o.dot&&e[a].charAt(0)===".")return!1;return!0}for(;u<l;){var h=e[u];if(this.debug(`
|
|
39
39
|
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(`
|
|
40
40
|
>>> no match, partial?`,e,u,t,m),u===l))}let g;if(typeof d=="string"?(g=p===d,this.debug("string match",d,p,g)):(g=d.test(p),this.debug("pattern match",d,p,g)),!g)return!1}if(a===l&&s===c)return!0;if(a===l)return r;if(s===c)return a===l-1&&e[a]==="";throw new Error("wtf?")}braceExpand(){return YS(this.pattern,this.options)}parse(e){ya(e);let t=this.options;if(e==="**")return st;if(e==="")return"";let r,o=null;(r=e.match(VI))?o=t.dot?KI:qI:(r=e.match(DI))?o=(t.nocase?t.dot?zI:BI:t.dot?UI:FI)(r[1]):(r=e.match(YI))?o=(t.nocase?t.dot?JI:XI:t.dot?QI:ZI)(r):(r=e.match(HI))?o=t.dot?$I:jI:(r=e.match(GI))&&(o=WI);let i=Vo.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?nP:t.dot?rP:oP,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"?cP(d):d===st?st:d._src});return c.forEach((d,p)=>{let u=c[p+1],m=c[p-1];d!==st||m===st||(m===void 0?u!==void 0&&u!==st?c[p+1]="(?:\\/|"+r+"\\/)?"+u:c[p]=r:u===void 0?c[p-1]=m+"(?:\\/|"+r+")?":u!==st&&(c[p-1]=m+"(?:\\/|\\/"+r+"\\/)"+u,c[p+1]=st))}),c.filter(d=>d!==st).join("/")}).join("|"),[a,s]=e.length>1?["(?:",")"]:["",""];i="^"+a+i+s+"$",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 a=o[o.length-1];if(!a)for(let s=o.length-2;!a&&s>=0;s--)a=o[s];for(let s=0;s<i.length;s++){let l=i[s],c=o;if(r.matchBase&&l.length===1&&(c=[a]),this.matchOne(c,l,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return xt.defaults(e).Minimatch}};xt.AST=Vo;xt.Minimatch=_t;xt.escape=qo;xt.unescape=un;import{fileURLToPath as HP}from"node:url";var Ko=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,JS=new Set,np=typeof process=="object"&&process?process:{},QS=(n,e,t,r)=>{typeof np.emitWarning=="function"?np.emitWarning(n,e,t,r):console.error(`[${t}] ${e}: ${n}`)},pl=globalThis.AbortController,XS=globalThis.AbortSignal;if(typeof pl>"u"){XS=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},pl=class{constructor(){e()}signal=new XS;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=np.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,QS("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 dP=n=>!JS.has(n),B4=Symbol("type"),fr=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),ZS=n=>fr(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)}},rp=class n{heap;length;static#e=!1;static create(e){let t=ZS(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]}},wa=class n{#e;#t;#i;#r;#a;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#p;#s;#l;#o;#f;#S;#m;#u;#E;#g;#x;#C;#b;#v;#T;#h;static unsafeExposeInternals(e){return{starts:e.#C,ttls:e.#b,sizes:e.#x,keyMap:e.#s,keyList:e.#l,valList:e.#o,next:e.#f,prev:e.#S,get head(){return e.#m},get tail(){return e.#u},free:e.#E,isBackgroundFetch:t=>e.#d(t),backgroundFetch:(t,r,o,i)=>e.#U(t,r,o,i),moveToTail:t=>e.#z(t),indexes:t=>e.#A(t),rindexes:t=>e.#I(t),isStale:t=>e.#y(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.#a}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:a,updateAgeOnHas:s,allowStale:l,dispose:c,disposeAfter:d,noDisposeOnSet:p,noUpdateTTL:u,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:f,memoMethod:S,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:C,ignoreFetchAbort:E}=e;if(t!==0&&!fr(t))throw new TypeError("max option must be a nonnegative integer");let A=t?ZS(t):Array;if(!A)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=S,f!==void 0&&typeof f!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#a=f,this.#T=!!f,this.#s=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#f=new A(t),this.#S=new A(t),this.#m=0,this.#u=0,this.#E=rp.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof d=="function"?(this.#r=d,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#v=!!this.#i,this.#h=!!this.#r,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!C,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#t!==0&&!fr(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!fr(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!s,this.ttlResolution=fr(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!fr(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";dP(k)&&(JS.add(k),QS("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",k,n))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#P(){let e=new Yo(this.#e),t=new Yo(this.#e);this.#b=e,this.#C=t,this.#M=(i,a,s=Ko.now())=>{if(t[i]=a!==0?s:0,e[i]=a,a!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#y(i)&&this.#O(this.#l[i],"expire")},a+1);l.unref&&l.unref()}},this.#R=i=>{t[i]=e[i]!==0?Ko.now():0},this.#n=(i,a)=>{if(e[a]){let s=e[a],l=t[a];if(!s||!l)return;i.ttl=s,i.start=l,i.now=r||o();let c=i.now-l;i.remainingTTL=s-c}};let r=0,o=()=>{let i=Ko.now();if(this.ttlResolution>0){r=i;let a=setTimeout(()=>r=0,this.ttlResolution);a.unref&&a.unref()}return i};this.getRemainingTTL=i=>{let a=this.#s.get(i);if(a===void 0)return 0;let s=e[a],l=t[a];if(!s||!l)return 1/0;let c=(r||o())-l;return s-c},this.#y=i=>{let a=t[i],s=e[i];return!!s&&!!a&&(r||o())-a>s}}#R=()=>{};#n=()=>{};#M=()=>{};#y=()=>!1;#L(){let e=new Yo(this.#e);this.#p=0,this.#x=e,this.#N=t=>{this.#p-=e[t],e[t]=0},this.#_=(t,r,o,i)=>{if(this.#d(r))return 0;if(!fr(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(r,t),!fr(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.#k=(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)}}#N=e=>{};#k=(e,t,r)=>{};#_=(e,t,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#u;!(!this.#D(t)||((e||!this.#y(t))&&(yield t),t===this.#m));)t=this.#S[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#D(t)||((e||!this.#y(t))&&(yield t),t===this.#u));)t=this.#f[t]}#D(e){return e!==void 0&&this.#s.get(this.#l[e])===e}*entries(){for(let e of this.#A())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.#A()){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.#A())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.#A()){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.#A()){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.#y(t)&&(this.#O(this.#l[t],"expire"),e=!0);return e}info(e){let t=this.#s.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 a=this.#b[t],s=this.#C[t];if(a&&s){let l=a-(Ko.now()-s);i.ttl=l,i.start=Date.now()}}return this.#x&&(i.size=this.#x[t]),i}dump(){let e=[];for(let t of this.#A({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 a={value:i};if(this.#b&&this.#C){a.ttl=this.#b[t];let s=Ko.now()-this.#C[t];a.start=Math.floor(Date.now()-s)}this.#x&&(a.size=this.#x[t]),e.unshift([r,a])}return e}load(e){this.clear();for(let[t,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Ko.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:a=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:l}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,d=this.#_(e,t,r.size||0,s);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.#s.get(e);if(p===void 0)p=this.#c===0?this.#u:this.#E.length!==0?this.#E.pop():this.#c===this.#e?this.#F(!1):this.#c,this.#l[p]=e,this.#o[p]=t,this.#s.set(e,p),this.#f[this.#u]=p,this.#S[p]=this.#u,this.#u=p,this.#c++,this.#k(p,d,l),l&&(l.set="add"),c=!1;else{this.#z(p);let u=this.#o[p];if(t!==u){if(this.#T&&this.#d(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=u;m!==void 0&&!a&&(this.#v&&this.#i?.(m,e,"set"),this.#h&&this.#g?.push([m,e,"set"]))}else a||(this.#v&&this.#i?.(u,e,"set"),this.#h&&this.#g?.push([u,e,"set"]));if(this.#N(p),this.#k(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.#M(p,o,i),l&&this.#n(l,p)),!a&&this.#h&&this.#g){let u=this.#g,m;for(;m=u?.shift();)this.#r?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#m];if(this.#F(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#m,r=this.#l[t],o=this.#o[t];return this.#T&&this.#d(o)?o.__abortController.abort(new Error("evicted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(o,r,"evict"),this.#h&&this.#g?.push([o,r,"evict"])),this.#N(t),e&&(this.#l[t]=void 0,this.#o[t]=void 0,this.#E.push(t)),this.#c===1?(this.#m=this.#u=0,this.#E.length=0):this.#m=this.#f[t],this.#s.delete(r),this.#c--,t}has(e,t={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=t,i=this.#s.get(e);if(i!==void 0){let a=this.#o[i];if(this.#d(a)&&a.__staleWhileFetching===void 0)return!1;if(this.#y(i))o&&(o.has="stale",this.#n(o,i));else return r&&this.#R(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.#s.get(e);if(o===void 0||!r&&this.#y(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 a=new pl,{signal:s}=r;s?.addEventListener("abort",()=>a.abort(s.reason),{signal:a.signal});let l={signal:a.signal,options:r,context:o},c=(g,f=!1)=>{let{aborted:S}=a.signal,b=r.ignoreFetchAbort&&g!==void 0;if(r.status&&(S&&!f?(r.status.fetchAborted=!0,r.status.fetchError=a.signal.reason,b&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),S&&!b&&!f)return p(a.signal.reason);let w=m;return this.#o[t]===m&&(g===void 0?w.__staleWhileFetching?this.#o[t]=w.__staleWhileFetching:this.#O(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,g,l.options))),g},d=g=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=g),p(g)),p=g=>{let{aborted:f}=a.signal,S=f&&r.allowStaleOnFetchAbort,b=S||r.allowStaleOnFetchRejection,w=b||r.noDeleteOnFetchRejection,T=m;if(this.#o[t]===m&&(!w||T.__staleWhileFetching===void 0?this.#O(e,"fetch"):S||(this.#o[t]=T.__staleWhileFetching)),b)return r.status&&T.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw g},u=(g,f)=>{let S=this.#a?.(e,i,l);S&&S instanceof Promise&&S.then(b=>g(b===void 0?void 0:b),f),a.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(g(void 0),r.allowStaleOnFetchAbort&&(g=b=>c(b,!0)))})};r.status&&(r.status.fetchDispatched=!0);let m=new Promise(u).then(c,d),h=Object.assign(m,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#s.get(e)):this.#o[t]=h,h}#d(e){if(!this.#T)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof pl}async fetch(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:g,forceRefresh:f=!1,status:S,signal:b}=t;if(!this.#T)return S&&(S.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:S});let w={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:s,size:l,sizeCalculation:c,noUpdateTTL:d,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:h,ignoreFetchAbort:m,status:S,signal:b},T=this.#s.get(e);if(T===void 0){S&&(S.fetch="miss");let C=this.#U(e,T,w,g);return C.__returned=C}else{let C=this.#o[T];if(this.#d(C)){let $=r&&C.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",$&&(S.returnedStale=!0)),$?C.__staleWhileFetching:C.__returned=C}let E=this.#y(T);if(!f&&!E)return S&&(S.fetch="hit"),this.#z(T),o&&this.#R(T),S&&this.#n(S,T),C;let A=this.#U(e,T,w,g),O=A.__staleWhileFetching!==void 0&&r;return S&&(S.fetch=E?"stale":"refresh",O&&E&&(S.returnedStale=!0)),O?A.__staleWhileFetching:A.__returned=A}}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,...a}=t,s=this.get(e,a);if(!i&&s!==void 0)return s;let l=r(e,s,{options:a,context:o});return this.set(e,l,a),l}get(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,s=this.#s.get(e);if(s!==void 0){let l=this.#o[s],c=this.#d(l);return a&&this.#n(a,s),this.#y(s)?(a&&(a.get="stale"),c?(a&&r&&l.__staleWhileFetching!==void 0&&(a.returnedStale=!0),r?l.__staleWhileFetching:void 0):(i||this.#O(e,"expire"),a&&r&&(a.returnedStale=!0),r?l:void 0)):(a&&(a.get="hit"),c?l.__staleWhileFetching:(this.#z(s),o&&this.#R(s),l))}else a&&(a.get="miss")}#B(e,t){this.#S[t]=e,this.#f[e]=t}#z(e){e!==this.#u&&(e===this.#m?this.#m=this.#f[e]:this.#B(this.#S[e],this.#f[e]),this.#B(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.#s.get(e);if(o!==void 0)if(r=!0,this.#c===1)this.#H(t);else{this.#N(o);let i=this.#o[o];if(this.#d(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(i,e,t),this.#h&&this.#g?.push([i,e,t])),this.#s.delete(e),this.#l[o]=void 0,this.#o[o]=void 0,o===this.#u)this.#u=this.#S[o];else if(o===this.#m)this.#m=this.#f[o];else{let a=this.#S[o];this.#f[a]=this.#f[o];let s=this.#f[o];this.#S[s]=this.#S[o]}this.#c--,this.#E.push(o)}}if(this.#h&&this.#g?.length){let o=this.#g,i;for(;i=o?.shift();)this.#r?.(...i)}return r}clear(){return this.#H("delete")}#H(e){for(let t of this.#I({allowStale:!0})){let r=this.#o[t];if(this.#d(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#l[t];this.#v&&this.#i?.(r,o,e),this.#h&&this.#g?.push([r,o,e])}}if(this.#s.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#b&&this.#C&&(this.#b.fill(0),this.#C.fill(0)),this.#x&&this.#x.fill(0),this.#m=0,this.#u=0,this.#E.length=0,this.#p=0,this.#c=0,this.#h&&this.#g){let t=this.#g,r;for(;r=t?.shift();)this.#r?.(...r)}}};import{posix as vP,win32 as mp}from"node:path";import{fileURLToPath as TP}from"node:url";import{lstatSync as EP,readdir as xP,readdirSync as CP,readlinkSync as RP,realpathSync as AP}from"fs";import*as IP from"node:fs";import{lstat as LP,readdir as OP,readlink as MP,realpath as NP}from"node:fs/promises";import{EventEmitter as dp}from"node:events";import oy from"node:stream";import{StringDecoder as pP}from"node:string_decoder";var ey=typeof process=="object"&&process?process:{stdout:null,stderr:null},uP=n=>!!n&&typeof n=="object"&&(n instanceof yr||n instanceof oy||mP(n)||hP(n)),mP=n=>!!n&&typeof n=="object"&&n instanceof dp&&typeof n.pipe=="function"&&n.pipe!==oy.Writable.prototype.pipe,hP=n=>!!n&&typeof n=="object"&&n instanceof dp&&typeof n.write=="function"&&typeof n.end=="function",Xn=Symbol("EOF"),Jn=Symbol("maybeEmitEnd"),Sr=Symbol("emittedEnd"),ul=Symbol("emittingEnd"),va=Symbol("emittedError"),ml=Symbol("closed"),ty=Symbol("read"),hl=Symbol("flush"),ny=Symbol("flushChunk"),mn=Symbol("encoding"),Xo=Symbol("decoder"),et=Symbol("flowing"),Ta=Symbol("paused"),Jo=Symbol("resume"),tt=Symbol("buffer"),Ct=Symbol("pipes"),nt=Symbol("bufferLength"),op=Symbol("bufferPush"),gl=Symbol("bufferShift"),gt=Symbol("objectMode"),He=Symbol("destroyed"),ip=Symbol("error"),ap=Symbol("emitData"),ry=Symbol("emitEnd"),sp=Symbol("emitEnd2"),On=Symbol("async"),lp=Symbol("abort"),fl=Symbol("aborted"),Ea=Symbol("signal"),no=Symbol("dataListeners"),Dt=Symbol("discarded"),xa=n=>Promise.resolve().then(n),gP=n=>n(),fP=n=>n==="end"||n==="finish"||n==="prefinish",SP=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,yP=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),Sl=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[Jo](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},cp=class extends Sl{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)}},bP=n=>!!n.objectMode,wP=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",yr=class extends dp{[et]=!1;[Ta]=!1;[Ct]=[];[tt]=[];[gt];[mn];[On];[Xo];[Xn]=!1;[Sr]=!1;[ul]=!1;[ml]=!1;[va]=null;[nt]=0;[He]=!1;[Ea];[fl]=!1;[no]=0;[Dt]=!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");bP(t)?(this[gt]=!0,this[mn]=null):wP(t)?(this[mn]=t.encoding,this[gt]=!1):(this[gt]=!1,this[mn]=null),this[On]=!!t.async,this[Xo]=this[mn]?new pP(this[mn]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[tt]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ct]});let{signal:r}=t;r&&(this[Ea]=r,r.aborted?this[lp]():r.addEventListener("abort",()=>this[lp]()))}get bufferLength(){return this[nt]}get encoding(){return this[mn]}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[gt]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[On]}set async(e){this[On]=this[On]||!!e}[lp](){this[fl]=!0,this.emit("abort",this[Ea]?.reason),this.destroy(this[Ea]?.reason)}get aborted(){return this[fl]}set aborted(e){}write(e,t,r){if(this[fl])return!1;if(this[Xn])throw new Error("write after end");if(this[He])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[On]?xa:gP;if(!this[gt]&&!Buffer.isBuffer(e)){if(yP(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(SP(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[gt]?(this[et]&&this[nt]!==0&&this[hl](!0),this[et]?this.emit("data",e):this[op](e),this[nt]!==0&&this.emit("readable"),r&&o(r),this[et]):e.length?(typeof e=="string"&&!(t===this[mn]&&!this[Xo]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[mn]&&(e=this[Xo].write(e)),this[et]&&this[nt]!==0&&this[hl](!0),this[et]?this.emit("data",e):this[op](e),this[nt]!==0&&this.emit("readable"),r&&o(r),this[et]):(this[nt]!==0&&this.emit("readable"),r&&o(r),this[et])}read(e){if(this[He])return null;if(this[Dt]=!1,this[nt]===0||e===0||e&&e>this[nt])return this[Jn](),null;this[gt]&&(e=null),this[tt].length>1&&!this[gt]&&(this[tt]=[this[mn]?this[tt].join(""):Buffer.concat(this[tt],this[nt])]);let t=this[ty](e||null,this[tt][0]);return this[Jn](),t}[ty](e,t){if(this[gt])this[gl]();else{let r=t;e===r.length||e===null?this[gl]():typeof r=="string"?(this[tt][0]=r.slice(e),t=r.slice(0,e),this[nt]-=e):(this[tt][0]=r.subarray(e),t=r.subarray(0,e),this[nt]-=e)}return this.emit("data",t),!this[tt].length&&!this[Xn]&&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[Xn]=!0,this.writable=!1,(this[et]||!this[Ta])&&this[Jn](),this}[Jo](){this[He]||(!this[no]&&!this[Ct].length&&(this[Dt]=!0),this[Ta]=!1,this[et]=!0,this.emit("resume"),this[tt].length?this[hl]():this[Xn]?this[Jn]():this.emit("drain"))}resume(){return this[Jo]()}pause(){this[et]=!1,this[Ta]=!0,this[Dt]=!1}get destroyed(){return this[He]}get flowing(){return this[et]}get paused(){return this[Ta]}[op](e){this[gt]?this[nt]+=1:this[nt]+=e.length,this[tt].push(e)}[gl](){return this[gt]?this[nt]-=1:this[nt]-=this[tt][0].length,this[tt].shift()}[hl](e=!1){do;while(this[ny](this[gl]())&&this[tt].length);!e&&!this[tt].length&&!this[Xn]&&this.emit("drain")}[ny](e){return this.emit("data",e),this[et]}pipe(e,t){if(this[He])return e;this[Dt]=!1;let r=this[Sr];return t=t||{},e===ey.stdout||e===ey.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[Ct].push(t.proxyErrors?new cp(this,e,t):new Sl(this,e,t)),this[On]?xa(()=>this[Jo]()):this[Jo]()),e}unpipe(e){let t=this[Ct].find(r=>r.dest===e);t&&(this[Ct].length===1?(this[et]&&this[no]===0&&(this[et]=!1),this[Ct]=[]):this[Ct].splice(this[Ct].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[Dt]=!1,this[no]++,!this[Ct].length&&!this[et]&&this[Jo]();else if(e==="readable"&&this[nt]!==0)super.emit("readable");else if(fP(e)&&this[Sr])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[va]){let o=t;this[On]?xa(()=>o.call(this,this[va])):o.call(this,this[va])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[no]=this.listeners("data").length,this[no]===0&&!this[Dt]&&!this[Ct].length&&(this[et]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[no]=0,!this[Dt]&&!this[Ct].length&&(this[et]=!1)),t}get emittedEnd(){return this[Sr]}[Jn](){!this[ul]&&!this[Sr]&&!this[He]&&this[tt].length===0&&this[Xn]&&(this[ul]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ml]&&this.emit("close"),this[ul]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==He&&this[He])return!1;if(e==="data")return!this[gt]&&!r?!1:this[On]?(xa(()=>this[ap](r)),!0):this[ap](r);if(e==="end")return this[ry]();if(e==="close"){if(this[ml]=!0,!this[Sr]&&!this[He])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[va]=r,super.emit(ip,r);let i=!this[Ea]||this.listeners("error").length?super.emit("error",r):!1;return this[Jn](),i}else if(e==="resume"){let i=super.emit("resume");return this[Jn](),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[Jn](),o}[ap](e){for(let r of this[Ct])r.dest.write(e)===!1&&this.pause();let t=this[Dt]?!1:super.emit("data",e);return this[Jn](),t}[ry](){return this[Sr]?!1:(this[Sr]=!0,this.readable=!1,this[On]?(xa(()=>this[sp]()),!0):this[sp]())}[sp](){if(this[Xo]){let t=this[Xo].end();if(t){for(let r of this[Ct])r.dest.write(t);this[Dt]||super.emit("data",t)}}for(let t of this[Ct])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[gt]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[gt]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[gt])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[mn]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(He,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Dt]=!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[Xn])return t();let i,a,s=p=>{this.off("data",l),this.off("end",c),this.off(He,d),t(),a(p)},l=p=>{this.off("error",s),this.off("end",c),this.off(He,d),this.pause(),i({value:p,done:!!this[Xn]})},c=()=>{this.off("error",s),this.off("data",l),this.off(He,d),t(),i({done:!0,value:void 0})},d=()=>s(new Error("stream destroyed"));return new Promise((p,u)=>{a=u,i=p,this.once(He,d),this.once("error",s),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Dt]=!1;let e=!1,t=()=>(this.pause(),this.off(ip,t),this.off(He,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(ip,t),this.once(He,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[He])return e?this.emit("error",e):this.emit(He),this;this[He]=!0,this[Dt]=!0,this[tt].length=0,this[nt]=0;let t=this;return typeof t.close=="function"&&!this[ml]&&t.close(),e?this.emit("error",e):this.emit(He),this}static get isStream(){return uP}};var PP=AP.native,Ra={lstatSync:EP,readdir:xP,readdirSync:CP,readlinkSync:RP,realpathSync:PP,promises:{lstat:LP,readdir:OP,readlink:MP,realpath:NP}},cy=n=>!n||n===Ra||n===IP?Ra:{...Ra,...n,promises:{...Ra.promises,...n.promises||{}}},dy=/^\\\\\?\\([a-z]:)\\?$/i,kP=n=>n.replace(/\//g,"\\").replace(dy,"$1\\"),_P=/[\\\/]/,tn=0,py=1,uy=2,Mn=4,my=6,hy=8,ro=10,gy=12,en=15,Ca=~en,pp=16,iy=32,Aa=64,hn=128,yl=256,wl=512,ay=Aa|hn|wl,DP=1023,up=n=>n.isFile()?hy:n.isDirectory()?Mn:n.isSymbolicLink()?ro:n.isCharacterDevice()?uy:n.isBlockDevice()?my:n.isSocket()?gy:n.isFIFO()?py:tn,sy=new Map,Ia=n=>{let e=sy.get(n);if(e)return e;let t=n.normalize("NFKD");return sy.set(n,t),t},ly=new Map,bl=n=>{let e=ly.get(n);if(e)return e;let t=Ia(n.toLowerCase());return ly.set(n,t),t},vl=class extends wa{constructor(){super({max:256})}},hp=class extends wa{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},fy=Symbol("PathScurry setAsCwd"),ft=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}#a;get uid(){return this.#a}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#p;get blksize(){return this.#p}#s;get ino(){return this.#s}#l;get size(){return this.#l}#o;get blocks(){return this.#o}#f;get atimeMs(){return this.#f}#S;get mtimeMs(){return this.#S}#m;get ctimeMs(){return this.#m}#u;get birthtimeMs(){return this.#u}#E;get atime(){return this.#E}#g;get mtime(){return this.#g}#x;get ctime(){return this.#x}#C;get birthtime(){return this.#C}#b;#v;#T;#h;#P;#R;#n;#M;#y;#L;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=tn,r,o,i,a,s){this.name=e,this.#b=i?bl(e):Ia(e),this.#n=t&DP,this.nocase=i,this.roots=o,this.root=r||this,this.#M=a,this.#T=s.fullpath,this.#P=s.relative,this.#R=s.relativePosix,this.parent=s.parent,this.parent?this.#e=this.parent.#e:this.#e=cy(s.fs)}depth(){return this.#v!==void 0?this.#v:this.parent?this.#v=this.parent.depth()+1:this.#v=0}childrenCache(){return this.#M}resolve(e){if(!e)return this;let t=this.getRootString(e),o=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#N(o):this.#N(o)}#N(e){let t=this;for(let r of e)t=t.child(r);return t}children(){let e=this.#M.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#M.set(this,t),this.#n&=~pp,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),o=this.nocase?bl(e):Ia(e);for(let l of r)if(l.#b===o)return l;let i=this.parent?this.sep:"",a=this.#T?this.#T+i+e:void 0,s=this.newChild(e,tn,{...t,parent:this,fullpath:a});return this.canReaddir()||(s.#n|=hn),r.push(s),s}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.#R!==void 0)return this.#R;let e=this.name,t=this.parent;if(!t)return this.#R=this.fullpathPosix();let r=t.relativePosix();return r+(!r||!t.parent?"":"/")+e}fullpath(){if(this.#T!==void 0)return this.#T;let e=this.name,t=this.parent;if(!t)return this.#T=this.name;let o=t.fullpath()+(t.parent?this.sep:"")+e;return this.#T=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&en)===tn}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&en)===hy}isDirectory(){return(this.#n&en)===Mn}isCharacterDevice(){return(this.#n&en)===uy}isBlockDevice(){return(this.#n&en)===my}isFIFO(){return(this.#n&en)===py}isSocket(){return(this.#n&en)===gy}isSymbolicLink(){return(this.#n&ro)===ro}lstatCached(){return this.#n&iy?this:void 0}readlinkCached(){return this.#y}realpathCached(){return this.#L}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#y)return!0;if(!this.parent)return!1;let e=this.#n&en;return!(e!==tn&&e!==ro||this.#n&yl||this.#n&hn)}calledReaddir(){return!!(this.#n&pp)}isENOENT(){return!!(this.#n&hn)}isNamed(e){return this.nocase?this.#b===bl(e):this.#b===Ia(e)}async readlink(){let e=this.#y;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.#y=r}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#y;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.#y=r}catch(t){this.#d(t.code);return}}#k(e){this.#n|=pp;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#_()}}#_(){this.#n&hn||(this.#n=(this.#n|hn)&Ca,this.#A())}#A(){let e=this.children();e.provisional=0;for(let t of e)t.#_()}#I(){this.#n|=wl,this.#D()}#D(){if(this.#n&Aa)return;let e=this.#n;(e&en)===Mn&&(e&=Ca),this.#n=e|Aa,this.#A()}#F(e=""){e==="ENOTDIR"||e==="EPERM"?this.#D():e==="ENOENT"?this.#_():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#D():e==="ENOENT"&&this.#_()}#d(e=""){let t=this.#n;t|=yl,e==="ENOENT"&&(t|=hn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Ca),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#D()}#B(e,t){return this.#O(e,t)||this.#z(e,t)}#z(e,t){let r=up(e),o=this.newChild(e.name,r,{parent:this}),i=o.#n&en;return i!==Mn&&i!==ro&&i!==tn&&(o.#n|=Aa),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?bl(e.name):Ia(e.name))===o.#b)return this.#H(e,o,r,t)}}#H(e,t,r,o){let i=t.name;return t.#n=t.#n&Ca|up(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&hn))try{return this.#W(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&hn))try{return this.#W(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code)}}#W(e){let{atime:t,atimeMs:r,birthtime:o,birthtimeMs:i,blksize:a,blocks:s,ctime:l,ctimeMs:c,dev:d,gid:p,ino:u,mode:m,mtime:h,mtimeMs:g,nlink:f,rdev:S,size:b,uid:w}=e;this.#E=t,this.#f=r,this.#C=o,this.#u=i,this.#p=a,this.#o=s,this.#x=l,this.#m=c,this.#t=d,this.#w=p,this.#s=u,this.#i=m,this.#g=h,this.#S=g,this.#r=f,this.#c=S,this.#l=b,this.#a=w;let T=up(e);this.#n=this.#n&Ca|T|iy,T!==tn&&T!==Mn&&T!==ro&&(this.#n|=Aa)}#$=[];#G=!1;#V(e){this.#G=!1;let t=this.#$.slice();this.#$.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.#$.push(e),this.#G)return;this.#G=!0;let o=this.fullpath();this.#e.readdir(o,{withFileTypes:!0},(i,a)=>{if(i)this.#F(i.code),r.provisional=0;else{for(let s of a)this.#B(s,r);this.#k(r)}this.#V(r.slice(0,r.provisional))})}#j;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.#j)await this.#j;else{let r=()=>{};this.#j=new Promise(o=>r=o);try{for(let o of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#B(o,e);this.#k(e)}catch(o){this.#F(o.code),e.provisional=0}this.#j=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.#B(r,e);this.#k(e)}catch(r){this.#F(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&ay)return!1;let e=en&this.#n;return e===tn||e===Mn||e===ro}shouldWalk(e,t){return(this.#n&Mn)===Mn&&!(this.#n&ay)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((wl|yl|hn)&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(!((wl|yl|hn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[fy](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.#R=r.join("/"),o=o.parent,r.push("..");for(o=e;o&&o.parent&&!t.has(o);)o.#P=void 0,o.#R=void 0,o=o.parent}},Tl=class n extends ft{sep="\\";splitSep=_P;constructor(e,t=tn,r,o,i,a,s){super(e,t,r,o,i,a,s)}newChild(e,t=tn,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return mp.parse(e).root}getRoot(e){if(e=kP(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 Qo(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(dy,"$1\\"),e===t}},El=class n extends ft{splitSep="/";sep="/";constructor(e,t=tn,r,o,i,a,s){super(e,t,r,o,i,a,s)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=tn,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}},xl=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,r,{nocase:o,childrenCacheSize:i=16*1024,fs:a=Ra}={}){this.#r=cy(a),(e instanceof URL||e.startsWith("file://"))&&(e=TP(e));let s=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(s),this.#e=new vl,this.#t=new vl,this.#i=new hp(i);let l=s.substring(this.rootPath.length).split(r);if(l.length===1&&!l[0]&&l.pop(),o===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=o,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let c=this.root,d=l.length-1,p=t.sep,u=this.rootPath,m=!1;for(let h of l){let g=d--;c=c.child(h,{relative:new Array(g).fill("..").join(p),relativePosix:new Array(g).fill("..").join("/"),fullpath:u+=(m?"":p)+h}),m=!0}this.cwd=c}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let a=e[i];if(!(!a||a===".")&&(t=t?`${a}/${t}`:a,this.isAbsolute(a)))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 a=e[i];if(!(!a||a===".")&&(t=t?`${a}/${t}`:a,this.isAbsolute(a)))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 ft||(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 ft||(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 ft||(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 ft||(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 ft||(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 ft||(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 ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=[];(!i||i(e))&&s.push(r?e:e.fullpath());let l=new Set,c=(p,u)=>{l.add(p),p.readdirCB((m,h)=>{if(m)return u(m);let g=h.length;if(!g)return u();let f=()=>{--g===0&&u()};for(let S of h)(!i||i(S))&&s.push(r?S:S.fullpath()),o&&S.isSymbolicLink()?S.realpath().then(b=>b?.isUnknown()?b.lstat():b).then(b=>b?.shouldWalk(l,a)?c(b,f):f()):S.shouldWalk(l,a)?c(S,f):f()},!0)},d=e;return new Promise((p,u)=>{c(d,m=>{if(m)return u(m);p(s)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=[];(!i||i(e))&&s.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))&&s.push(r?p:p.fullpath());let u=p;if(p.isSymbolicLink()){if(!(o&&(u=p.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(l,a)&&l.add(u)}}return s}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(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 ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t;(!i||i(e))&&(yield r?e:e.fullpath());let s=new Set([e]);for(let l of s){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(s,a)&&s.add(p)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=new yr({objectMode:!0});(!i||i(e))&&s.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&&s.end();return}d++,l.add(m);let h=(f,S,b=!1)=>{if(f)return s.emit("error",f);if(o&&!b){let w=[];for(let T of S)T.isSymbolicLink()&&w.push(T.realpath().then(C=>C?.isUnknown()?C.lstat():C));if(w.length){Promise.all(w).then(()=>h(null,S,!0));return}}for(let w of S)w&&(!i||i(w))&&(s.write(r?w:w.fullpath())||(u=!0));d--;for(let w of S){let T=w.realpathCached()||w;T.shouldWalk(l,a)&&c.push(T)}u&&!s.flowing?s.once("drain",p):g||p()},g=!0;m.readdirCB(h,!0),g=!1}};return p(),s}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=new yr({objectMode:!0}),l=new Set;(!i||i(e))&&s.write(r?e:e.fullpath());let c=[e],d=0,p=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){d===0&&s.end();return}d++,l.add(m);let h=m.readdirSync();for(let g of h)(!i||i(g))&&(s.write(r?g:g.fullpath())||(u=!0));d--;for(let g of h){let f=g;if(g.isSymbolicLink()){if(!(o&&(f=g.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(l,a)&&c.push(f)}}u&&!s.flowing&&s.once("drain",p)};return p(),s}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[fy](t)}},Qo=class extends xl{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,mp,"\\",{...t,nocase:r}),this.nocase=r;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return mp.parse(e).root.toUpperCase()}newRoot(e){return new Tl(this.rootPath,Mn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Zo=class extends xl{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,vP,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new El(this.rootPath,Mn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Pa=class extends Zo{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},J4=process.platform==="win32"?Tl:El,Sy=process.platform==="win32"?Qo:process.platform==="darwin"?Pa:Zo;var FP=n=>n.length>=1,UP=n=>n.length>=1,ei=class n{#e;#t;#i;length;#r;#a;#w;#c;#p;#s;#l=!0;constructor(e,t,r,o){if(!FP(e))throw new TypeError("empty pattern list");if(!UP(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,a,s,l,...c]=this.#e,[d,p,u,m,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let g=[i,a,s,l,""].join("/"),f=[d,p,u,m,""].join("/");this.#e=[g,...c],this.#t=[f,...h],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[i,...a]=this.#e,[s,...l]=this.#t;a[0]===""&&(a.shift(),l.shift());let c=i+"/",d=s+"/";this.#e=[c,...a],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]===st}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.#a!==void 0?this.#a:this.hasMore()?(this.#a=new n(this.#e,this.#t,this.#i+1,this.#r),this.#a.#s=this.#s,this.#a.#p=this.#p,this.#a.#c=this.#c,this.#a):this.#a=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.#s!==void 0?this.#s:this.#s=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 BP=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ti=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:o,noglobstar:i,platform:a=BP}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=a,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:o,noglobstar:i,optimizationLevel:2,platform:a,nocomment:!0,nonegate:!0};for(let s of e)this.add(s)}add(e){let t=new _t(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 a=new ei(o,i,0,this.platform),s=new _t(a.globString(),this.mmopts),l=i[i.length-1]==="**",c=a.isAbsolute();c?this.absolute.push(s):this.relative.push(s),l&&(c?this.absoluteChildren.push(s):this.relativeChildren.push(s))}}ignored(e){let t=e.fullpath(),r=`${t}/`,o=e.relative()||".",i=`${o}/`;for(let a of this.relative)if(a.match(o)||a.match(i))return!0;for(let a of this.absolute)if(a.match(t)||a.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 gp=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()]))}},fp=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)])}},Sp=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())}},La=class n{hasWalkedCache;matches=new fp;subwalks=new Sp;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new gp}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 a=i.root(),s=i.isAbsolute()&&this.opts.absolute!==!1;if(a){o=o.resolve(a==="/"&&this.opts.root!==void 0?this.opts.root:a);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),s,p);continue}else if(l===st){(!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,s,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,s,!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 a of r){let s=a.isAbsolute(),l=a.pattern(),c=a.rest();l===st?o.testGlobstar(i,a,c,s):l instanceof RegExp?o.testRegExp(i,l,c,s):o.testString(i,l,c,s)}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 a=e.parent||e;this.subwalks.add(a,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 zP=(n,e)=>typeof n=="string"?new ti([n],e):Array.isArray(n)?new ti(n,e):n,Cl=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=zP(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)}#a(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 a=await i.realpath();a&&(a.isUnknown()||this.opts.stat)&&await a.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 a=i.realpathSync();a&&(a?.isUnknown()||this.opts.stat)&&a.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(),a=this.opts.dotRelative&&!i.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(i?a+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 La(this.opts),r)}walkCB2(e,t,r,o){if(this.#a(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,a=()=>{--i===0&&o()};for(let[s,l,c]of r.matches.entries())this.#r(s)||(i++,this.match(s,l,c).then(()=>a()));for(let s of r.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;let l=s.readdirCached();s.calledReaddir()?this.walkCB3(s,l,r,a):s.readdirCB((c,d)=>this.walkCB3(s,d,r,a),!0)}a()}walkCB3(e,t,r,o){r=r.filterEntries(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of r.matches.entries())this.#r(s)||(i++,this.match(s,l,c).then(()=>a()));for(let[s,l]of r.subwalks.entries())i++,this.walkCB2(s,l,r.child(),a);a()}walkCBSync(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new La(this.opts),r)}walkCB2Sync(e,t,r,o){if(this.#a(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,a=()=>{--i===0&&o()};for(let[s,l,c]of r.matches.entries())this.#r(s)||this.matchSync(s,l,c);for(let s of r.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;let l=s.readdirSync();this.walkCB3Sync(s,l,r,a)}a()}walkCB3Sync(e,t,r,o){r=r.filterEntries(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of r.matches.entries())this.#r(s)||this.matchSync(s,l,c);for(let[s,l]of r.subwalks.entries())i++,this.walkCB2Sync(s,l,r.child(),a);a()}},Oa=class extends Cl{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}},Ma=class extends Cl{results;constructor(e,t,r){super(e,t,r),this.results=new yr({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 jP=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",gn=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=HP(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||jP,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"?Qo:t.platform==="darwin"?Pa:t.platform?Zo:Sy;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 _t(l,o)),[a,s]=i.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=a.map((l,c)=>{let d=s[c];if(!d)throw new Error("invalid pattern object");return new ei(l,d,0,this.platform)})}async walk(){return[...await new Oa(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 Oa(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 Ma(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 Ma(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 yp=(n,e={})=>{Array.isArray(n)||(n=[n]);for(let t of n)if(new _t(t,e).hasMagic())return!0;return!1};function Rl(n,e={}){return new gn(n,e).streamSync()}function wy(n,e={}){return new gn(n,e).stream()}function br(n,e={}){return new gn(n,e).walkSync()}async function yy(n,e={}){return new gn(n,e).walk()}function Al(n,e={}){return new gn(n,e).iterateSync()}function vy(n,e={}){return new gn(n,e).iterate()}var $P=Rl,GP=Object.assign(wy,{sync:Rl}),WP=Al,VP=Object.assign(vy,{sync:Al}),qP=Object.assign(br,{stream:Rl,iterate:Al}),by=Object.assign(yy,{glob:yy,globSync:br,sync:qP,globStream:wy,stream:GP,globStreamSync:Rl,streamSync:$P,globIterate:vy,iterate:VP,globIterateSync:Al,iterateSync:WP,Glob:gn,hasMagic:yp,escape:qo,unescape:un});by.glob=by;import oo,{dirname as Cy}from"path";import{cwd as Ep}from"process";import Ry from"yaml";import{z as Ce}from"zod";import Ty from"fs";import Na from"path";import KP from"yaml";import{z as bp}from"zod";var Ey=!1,wp=[`**/*.${Et.TEST}`,`**/*.${Et.MODULE}`],vp=bp.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),Tp=50,YP=bp.object({fileType:bp.nativeEnum(ve)});function de(n,e){let t={project:n,tests:{},modules:{},duplicateEntities:{}},r=n.config.include??wp,o=Array.from(n.config.exclude??[]).concat(qs),i=br(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:Tp,nodir:!0});for(let a of i){let s=XP(n.rootDir,a,t,e);s&&(t.duplicateEntities[s.id]=s.paths)}return Ey=!0,t}function XP(n,e,t,r){let o=Na.join(n,e),i;try{i=Ty.readFileSync(o,"utf-8")}catch(u){r.warn(`Could not read possible Momentic file at ${o}, skipping: ${u}`);return}let a;try{if(a=KP.parse(i),typeof a!="object"||a===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(u){r.warn(`Could not parse possible Momentic file at ${o}, skipping: ${u}`);return}let s=YP.safeParse(a);if(s.success===!1){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let l=s.data.fileType,c;try{c=Ty.statSync(o)}catch(u){r.warn(`Skipping path '${o}' because it could not be stat, skipping: ${u}`);return}let d={relativePath:e,fullFilePath:o,platformSep:Na.sep,fullPathSegments:o.split(Na.sep),relativePathSegments:e.split(Na.sep),fileName:Na.basename(o),lastModified:c.mtime,createdAt:c.birthtime},p;switch(l){case ve.TEST:try{let u=Xt.parse(a);if(t.tests[u.id]){let m=t.tests[u.id].fullFilePath;p={id:u.id,paths:[m,o]}}return t.tests[u.id]={type:ve.TEST,name:u.name,id:u.id,description:u.description??void 0,labels:u.labels,...d},p}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${u}`);return}case ve.MODULE:try{let u=It.parse(a);if(t.modules[u.moduleId]){let h=t.modules[u.moduleId].fullFilePath;p={id:u.moduleId,paths:[h,o]}}t.modules[u.moduleId]={type:ve.MODULE,name:u.name,id:u.moduleId,description:u.description??void 0,...d};let m=d.fileName.replace(".module.yaml","");return!Ey&&Ee(u.name)!==m&&r.warn(`The module with ID ${u.moduleId} has a name (${u.name}) that does not match its file name (${m}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),p}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${u}`);return}default:r.warn(`Unsupported file type ${l}, skipping...`);return}}var ni="momentic.config.yaml",xy="momentic.workspace.yaml",tL=Ce.object({projects:Ce.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),nL=Ce.union([Ce.string(),Ce.object({fromFile:Ce.string(),json:Ce.boolean().optional()})]),rL=Ce.object({name:vp,baseUrl:Ce.string(),envFile:Ce.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ce.record(Ce.string(),nL).optional(),inheritFromShell:Ce.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Fr.optional()}),oL=Ce.object({postSave:Ce.string().optional()}),iL=Ce.object({name:vp,include:Ce.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ce.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Ce.string().optional(),reporterDir:Ce.string().optional(),outputDir:Ce.string().optional(),retries:Ce.number().optional().describe("number of retries per test"),parallel:Ce.number().optional().describe("degree of parallelism"),environments:Ce.array(rL).optional(),gitMainBranch:Ce.string().optional(),gitProtectedBranches:Ce.string().array().optional(),ai:zd.optional(),browser:Fr.optional(),advanced:Hd.optional(),hooks:oL.optional()});function Ay(n,e){let t;try{t=QP(n,"utf-8")}catch(o){y.warn(`Could not read possible Momentic ${e} file at ${n}: ${o}`);return}let r;try{if(r=Ry.parse(t),typeof r!="object"||r===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof r} instead`)}catch(o){y.warn(`Possible Momentic ${e} file at ${n} does not parse as valid YAML: ${o}`);return}return r}function xp(n){let e=Ay(n,"project configuration");if(e!==void 0)try{return iL.parse(e)}catch(t){y.warn(`Possible Momentic project configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function aL(n){let e=Ay(n,"workspace configuration");if(e!==void 0)try{return tL.parse(e)}catch(t){y.warn(`Possible Momentic workspace configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function sL(){let n=[],e=Ep(),t=oo.parse(e).root,r=15,o=0;for(;o<r;){o++;let i=oo.basename(e);if(Vs.includes(i))return y.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),n;for(let a of ZP(e))if(a.endsWith(ni)){let s=oo.join(e,a),l=xp(s);l&&n.push({configFilePath:s,config:l,rootDir:Cy(s)})}if(n.length)return n;if(e=oo.dirname(e),e===t)break}return n}function rt(n={}){let{configFilePath:e,nameFilter:t}=n,r=Cp(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:
|
|
41
|
-
${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return y.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function lL(n){let e=aL(n);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${ni}`)),r=br(t,{absolute:!1,cwd:Ep(),dotRelative:!1,maxDepth:Tp,nodir:!0}),o=[];for(let i of r){let a=oo.join(Ep(),i),s=xp(a);s&&o.push({configFilePath:a,config:s,rootDir:Cy(a)})}return o}function Cp(n){if(n){n=oo.resolve(n);let t=xp(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:oo.dirname(n)}]}if(JP(xy)){let t=lL(xy);if(t)return t}return sL()}function ri(n,e){let t=Ry.stringify(n);eL(e,t)}import oi from"fs";import Rp from"path";import{z as Ap}from"zod";var Iy="golden/visual-diff",Py="reports",Ly="test-results";var cL=Ap.object({width:Ap.number(),height:Ap.number()}),ii=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=Rp.join(e.rootDir,e.config.goldenFileDir??Iy);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,r){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Rp.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return oi.mkdirSync(Rp.dirname(o),{recursive:!0}),oi.writeFileSync(o,r.buffer),oi.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(oi.existsSync(o)){let a=oi.readFileSync(o),s=cL.parse(JSON.parse(oi.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new R("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var ai=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import dL from"simple-git";var Re=dL();function Il(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function Ae(n,e){try{return(await e).trim()}catch(t){n.error({err:t},"Failed to run git command");return}}function pL(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function uL(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:t,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function mL(n){let[e,t,r]=await Promise.all([Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function hL(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Il(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function gL(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Il(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function fL(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Il(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function SL(n,e){let[t,r,o,i,a,s,l,c]=await Promise.all([Ae(n,Re.revparse(["HEAD"])),Ae(n,Re.revparse(["--short","HEAD"])),Ae(n,Re.revparse(["--abbrev-ref","HEAD"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"])),e?Ae(n,Re.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0)]),d=c?await Ae(n,Re.show(["--no-patch","--format=%ci",c])):void 0,p=i?.includes("github.com"),u=i?.includes("gitlab.com"),m=i?Il(i):void 0;return{gitCommitSha:t,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:l,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?m:void 0,gitlabProjectPath:u?m:void 0,pipelineId:void 0}}async function yL(){let n=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:n?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:n?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function bL(n){let e=n.config.gitProtectedBranches??[];return n.config.gitMainBranch&&e.push(n.config.gitMainBranch),{gitMainBranch:n.config.gitMainBranch,gitProtectedBranches:e}}async function Ip(n,e){let t=pL();if(!t)return SL(n,e);switch(t){case"GithubActions":return uL(n);case"GitlabCI":return mL(n);case"CircleCI":return hL(n);case"Buildkite":return gL(n);case"AzureDevOps":return fL(n);case"GCPCloudBuild":return yL()}}async function wL(n,e,t,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGitlab(t,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let i=await e.getCommitFromGitlab(t,r.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}return o}async function vL(n,e,t,r,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGithub(t,r,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName){let a=await e.getCommitFromGithub(t,r,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}return i}async function TL(n,e,t){try{if(t.githubRepository){let[r,o]=t.githubRepository.split("/");return await vL(n,e,r,o,t)}else if(t.gitlabProjectPath)return await wL(n,e,t.gitlabProjectPath,t)}catch(r){n.warn({err:r},"Failed to get remote git metadata")}return t}async function si(n,e,t){let r=await bL(t),o=await Ip(n,r.gitMainBranch),i={...r,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===r.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await TL(n,e,i);return{...r,...o,...a}}import _k from"http";import{z as Op}from"zod";var j="v1",ka="2.10.0";var wr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Oy=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function z(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,s;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{if(e.signal){let{signal:p}=e;if(p.aborted)return c(Oy(p));s=()=>c(Oy(p)),p.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(p){c(p)}else{typeof n.cancel=="function"&&Promise.resolve().then(()=>n.cancel()).catch(()=>{});let p=o instanceof Error?o:new wr(o??`Promise timed out after ${t}ms`);c(p)}};a=i.setTimeout(d,t),Promise.resolve(n).then(p=>l(p)).catch(p=>c(p))}).finally(()=>{i.clearTimeout(a),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var Pl=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(r),!1)}};var Pp=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];function My(n){return new Array(n).fill(0).map(()=>Pp[Math.floor(Math.random()*Pp.length)]).join("-")}var EL=9e4,xL=3,CL=1500,RL=15e3,fn=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function AL(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Lp=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ka&&(e[Og]=ka),e}async sendRequest(e,t){let{retries:r=xL,requestTimeoutMs:o=EL,initialRetryDelayMs:i=CL,maxRetryDelayMs:a=RL}=t,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,t,o)}catch(p){if(c=p,p instanceof fn&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(c=new wr),s===0)throw c;let u=l-s,m=Math.min(i*Math.pow(2,u-1),a);await new Promise(h=>setTimeout(h,m))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),r),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s);let l={...this.getHeaders(),...t.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let p=await AL(c);throw new fn(c.status,p,`Request to ${t.method} ${e} failed with status ${c.status}: ${p}`)}let d;if(c.status===204)d={};else{let p=await c.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&!t.noLog&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},nn=class extends Lp{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends nn{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${j}/auth/check`,{method:"GET",noLog:!0,retries:10,requestTimeoutMs:5e3});return Jg.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${j}/runs/status`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:1e4});return qg.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${j}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return jg.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${j}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let r=await this.sendRequest(`/${j}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return $g.parse(r)}async queueTests(e){let t=await this.sendRequest(`/${j}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Hg.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${j}/screenshots`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3});return Xg.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${j}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Qg.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${j}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return sf.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${j}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${j}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${j}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Zg.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${j}/run-groups/status`,{method:"POST",body:t,noLog:!0,retries:3,requestTimeoutMs:5e3});return Oh.array().parse(r)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${j}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${j}/billing/events`,{method:"POST",body:t,noLog:!0,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${j}/test-fragments/${e}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return ef.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${j}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${j}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return tf.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${j}/results/uploads`,{method:"POST",noLog:!0,retries:3,requestTimeoutMs:1e4});return nf.parse(e)}async startProcessingResultsUpload(e,t){let r=await this.sendRequest(`/${j}/results/uploads/${e}/process`,{method:"POST",noLog:!0,body:t,retries:3,requestTimeoutMs:1e4});return rf.parse(r)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${j}/knowledge-base/icons`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return mf.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${j}/knowledge-base/icons`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3})}catch(r){t.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,r,o){let i=new URLSearchParams;i.set("base",r),i.set("head",o);let a=await this.sendRequest(`/${j}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(a)}async getCommitFromGithub(e,t,r){let o=await this.sendRequest(`/${j}/git/github/${e}/${t}/commits/${r}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(o)}async getMergeBaseCommitFromGitlab(e,t,r){let o=new URLSearchParams;o.set("base",t),o.set("head",r);let i=await this.sendRequest(`/${j}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return la.parse(i)}async getCommitFromGitlab(e,t){let r=await this.sendRequest(`/${j}/git/gitlab/${e}/commits/${t}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${j}/web-agent/agent-config`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return Op.record(Op.string(),Op.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${j}/quarantine`,{method:"GET",noLog:!0});return of.parse(e)}async quarantineTest(e,t){await this.sendRequest(`/${j}/quarantine`,{method:"POST",body:{testId:e,reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t){await this.sendRequest(`/${j}/quarantine/${e}`,{method:"DELETE",body:{reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}};import{randomUUID as Ny}from"crypto";var Ll=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??Ny(),properties:Od({},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??Ny(),properties:Od({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var li=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as IL,en as PL}from"@faker-js/faker";var ci="v1",di=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new IL({locale:PL}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${ci}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof fn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${ci}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${ci}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${ci}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${ci}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${ci}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as LL}from"zod";var pi=class extends nn{agentConfig;constructor(e,t){super(t),this.agentConfig=e}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${j}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Fh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${j}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ka,...e},signal:t.abortSignal});return Dh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${j}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return LL.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${j}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Bg.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${j}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return jd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${j}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return Ug.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${j}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return jd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${j}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Fg.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${j}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${j}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return rd.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${j}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return zg.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${j}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return nd.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${j}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return gd.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${j}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Vh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${j}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return km.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${j}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return _m.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${j}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return gm.parse(r)}};var ui=class extends nn{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${j}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return fm.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function ky(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ol=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await ky(r,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};function mi({orgId:n,client:e,gitMetadata:t,alwaysSaveCache:r,noCache:o}){return o?new ns:new Mp(n,e,t,r)}var Mp=class{constructor(e,t,{gitMainBranch:r,gitBranchName:o,gitProtectedBranches:i,gitCommitTimestamp:a,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:l},c){this.orgId=e;this.client=t;this.cacheHeaders={},r&&(this.cacheHeaders[Mg]=r),o&&(this.cacheHeaders[Ng]=o),a&&(this.cacheHeaders[kg]=a.toISOString()),s&&(this.cacheHeaders[_g]=s),l&&(this.cacheHeaders[Dg]=l.toISOString()),c?this.writeCaches=!0:o?this.writeCaches=!i.includes(o):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:r,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId,steps:t,schemaVersion:e.schemaVersion},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[t,r,o])s&&Ho({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await mt({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import Dk from"path";import{Server as ok}from"socket.io";var OL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async()=>{e.info({sessionId:r},"Cancel event received");let o=t.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},_y={event:"cancel",createHandler:OL};var ML=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message})}}},Dy={event:"fetchA11yTree",createHandler:ML};var NL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.html();i({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message})}}},Fy={event:"fetchDom",createHandler:NL};var kL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),t.removeSession(r,e)}},Uy={event:"disconnect",createHandler:kL};function Nn(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=_L(t);DL(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await FL(i,e,r,o)}catch(a){n.logger.error({result:n.result,err:a},"Error hoisting scalar result metadata")}})())}function _L(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function DL(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function FL(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import _a from"os";import UL from"v8";var By,kn,BL=_a.platform(),zL=_a.cpus().map(n=>({model:n.model,speed:n.speed}));function zy(n){let e=()=>{try{let t=!1,r=HL(),o=jL();r.freeMemory<1e6&&(t=!0);let i=UL.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;a/s>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:zL,platform:BL}}function HL(){let n=_a.totalmem(),e=_a.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function jL(){let n=_a.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!kn)return kn=t,null;let r={user:t.user-kn.user,nice:t.nice-kn.nice,sys:t.sys-kn.sys,idle:t.idle-kn.idle,irq:t.irq-kn.irq,total:t.total-kn.total};return By={measurementTime:e,intervalMs:e-kn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},kn=t,By}import{randomUUID as JL}from"crypto";import{faker as $L}from"@faker-js/faker";import GL from"assert";import WL from"axios";import*as VL from"child_process";import qL from"moment";import*as KL from"otpauth";import YL from"pg";async function Hy(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Bs(r,e);t.push(...o)}),t}var XL=Object.getPrototypeOf(async function(){}).constructor;async function jy(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,a={},s=(f,S)=>{o[f]=S,a[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let p;r.includes("createAppAuth")&&(p=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new XL("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(WL,qL,i.fakerInstance??$L,GL,YL,d,p,KL,VL,Hy,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await z(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error({err:f,env:o,evalCode:r},`[${n}] Error executing code: ${f}`),m=!1,f instanceof wr?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:a,persistentVariableUpdates:l,success:m,error:g}}async function $y({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:a=mr}){let s=JL(),l=await jy(s,{code:n,options:{fragment:e,timeoutMs:a},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${s}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as QL,randomUUID as ZL}from"crypto";import eO from"fetch-retry";var tO=eO(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),Gy=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Wy=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Vy({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=mr,retries:i=2,signal:a,logger:s}){if(!Gy)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Wy)throw new Error("Missing lambda auth secret.");let p=QL("sha256",Wy).update(n).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let m={id:ZL(),orgId:n,momenticLambdaAuthHash:p,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await z(tO(Gy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw s.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=tg.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function io(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Vy(n);else if(n.localTools)e=await $y({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
41
|
+
${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return y.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function lL(n){let e=aL(n);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${ni}`)),r=br(t,{absolute:!1,cwd:Ep(),dotRelative:!1,maxDepth:Tp,nodir:!0}),o=[];for(let i of r){let a=oo.join(Ep(),i),s=xp(a);s&&o.push({configFilePath:a,config:s,rootDir:Cy(a)})}return o}function Cp(n){if(n){n=oo.resolve(n);let t=xp(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:oo.dirname(n)}]}if(JP(xy)){let t=lL(xy);if(t)return t}return sL()}function ri(n,e){let t=Ry.stringify(n);eL(e,t)}import oi from"fs";import Rp from"path";import{z as Ap}from"zod";var Iy="golden/visual-diff",Py="reports",Ly="test-results";var cL=Ap.object({width:Ap.number(),height:Ap.number()}),ii=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=Rp.join(e.rootDir,e.config.goldenFileDir??Iy);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,r){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Rp.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return oi.mkdirSync(Rp.dirname(o),{recursive:!0}),oi.writeFileSync(o,r.buffer),oi.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(oi.existsSync(o)){let a=oi.readFileSync(o),s=cL.parse(JSON.parse(oi.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new R("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var ai=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import dL from"simple-git";var Re=dL();function Il(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function Ae(n,e){try{return(await e).trim()}catch(t){n.error({err:t},"Failed to run git command");return}}function pL(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function uL(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:t,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function mL(n){let[e,t,r]=await Promise.all([Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function hL(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Il(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function gL(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Il(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function fL(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Il(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function SL(n,e){let[t,r,o,i,a,s,l,c]=await Promise.all([Ae(n,Re.revparse(["HEAD"])),Ae(n,Re.revparse(["--short","HEAD"])),Ae(n,Re.revparse(["--abbrev-ref","HEAD"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"])),e?Ae(n,Re.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0)]),d=c?await Ae(n,Re.show(["--no-patch","--format=%ci",c])):void 0,p=i?.includes("github.com"),u=i?.includes("gitlab.com"),m=i?Il(i):void 0;return{gitCommitSha:t,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:l,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?m:void 0,gitlabProjectPath:u?m:void 0,pipelineId:void 0}}async function yL(){let n=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:n?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:n?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function bL(n){let e=n.config.gitProtectedBranches??[];return n.config.gitMainBranch&&e.push(n.config.gitMainBranch),{gitMainBranch:n.config.gitMainBranch,gitProtectedBranches:e}}async function Ip(n,e){let t=pL();if(!t)return SL(n,e);switch(t){case"GithubActions":return uL(n);case"GitlabCI":return mL(n);case"CircleCI":return hL(n);case"Buildkite":return gL(n);case"AzureDevOps":return fL(n);case"GCPCloudBuild":return yL()}}async function wL(n,e,t,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGitlab(t,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let i=await e.getCommitFromGitlab(t,r.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}return o}async function vL(n,e,t,r,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGithub(t,r,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName){let a=await e.getCommitFromGithub(t,r,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}return i}async function TL(n,e,t){try{if(t.githubRepository){let[r,o]=t.githubRepository.split("/");return await vL(n,e,r,o,t)}else if(t.gitlabProjectPath)return await wL(n,e,t.gitlabProjectPath,t)}catch(r){n.warn({err:r},"Failed to get remote git metadata")}return t}async function si(n,e,t){let r=await bL(t),o=await Ip(n,r.gitMainBranch),i={...r,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===r.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await TL(n,e,i);return{...r,...o,...a}}import _k from"http";import{z as Op}from"zod";var j="v1",ka="2.10.2";var wr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Oy=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function z(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,s;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{if(e.signal){let{signal:p}=e;if(p.aborted)return c(Oy(p));s=()=>c(Oy(p)),p.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(p){c(p)}else{typeof n.cancel=="function"&&Promise.resolve().then(()=>n.cancel()).catch(()=>{});let p=o instanceof Error?o:new wr(o??`Promise timed out after ${t}ms`);c(p)}};a=i.setTimeout(d,t),Promise.resolve(n).then(p=>l(p)).catch(p=>c(p))}).finally(()=>{i.clearTimeout(a),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var Pl=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(r),!1)}};var Pp=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];function My(n){return new Array(n).fill(0).map(()=>Pp[Math.floor(Math.random()*Pp.length)]).join("-")}var EL=9e4,xL=3,CL=1500,RL=15e3,fn=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function AL(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Lp=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ka&&(e[Og]=ka),e}async sendRequest(e,t){let{retries:r=xL,requestTimeoutMs:o=EL,initialRetryDelayMs:i=CL,maxRetryDelayMs:a=RL}=t,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,t,o)}catch(p){if(c=p,p instanceof fn&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(c=new wr),s===0)throw c;let u=l-s,m=Math.min(i*Math.pow(2,u-1),a);await new Promise(h=>setTimeout(h,m))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),r),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s);let l={...this.getHeaders(),...t.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let p=await AL(c);throw new fn(c.status,p,`Request to ${t.method} ${e} failed with status ${c.status}: ${p}`)}let d;if(c.status===204)d={};else{let p=await c.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&!t.noLog&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},nn=class extends Lp{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends nn{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${j}/auth/check`,{method:"GET",noLog:!0,retries:10,requestTimeoutMs:5e3});return Jg.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${j}/runs/status`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:1e4});return qg.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${j}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return jg.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${j}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let r=await this.sendRequest(`/${j}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return $g.parse(r)}async queueTests(e){let t=await this.sendRequest(`/${j}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Hg.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${j}/screenshots`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3});return Xg.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${j}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Qg.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${j}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return sf.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${j}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${j}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${j}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Zg.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${j}/run-groups/status`,{method:"POST",body:t,noLog:!0,retries:3,requestTimeoutMs:5e3});return Oh.array().parse(r)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${j}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${j}/billing/events`,{method:"POST",body:t,noLog:!0,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${j}/test-fragments/${e}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return ef.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${j}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${j}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return tf.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${j}/results/uploads`,{method:"POST",noLog:!0,retries:3,requestTimeoutMs:1e4});return nf.parse(e)}async startProcessingResultsUpload(e,t){let r=await this.sendRequest(`/${j}/results/uploads/${e}/process`,{method:"POST",noLog:!0,body:t,retries:3,requestTimeoutMs:1e4});return rf.parse(r)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${j}/knowledge-base/icons`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return mf.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${j}/knowledge-base/icons`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3})}catch(r){t.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,r,o){let i=new URLSearchParams;i.set("base",r),i.set("head",o);let a=await this.sendRequest(`/${j}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(a)}async getCommitFromGithub(e,t,r){let o=await this.sendRequest(`/${j}/git/github/${e}/${t}/commits/${r}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(o)}async getMergeBaseCommitFromGitlab(e,t,r){let o=new URLSearchParams;o.set("base",t),o.set("head",r);let i=await this.sendRequest(`/${j}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return la.parse(i)}async getCommitFromGitlab(e,t){let r=await this.sendRequest(`/${j}/git/gitlab/${e}/commits/${t}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${j}/web-agent/agent-config`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return Op.record(Op.string(),Op.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${j}/quarantine`,{method:"GET",noLog:!0});return of.parse(e)}async quarantineTest(e,t){await this.sendRequest(`/${j}/quarantine`,{method:"POST",body:{testId:e,reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t){await this.sendRequest(`/${j}/quarantine/${e}`,{method:"DELETE",body:{reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}};import{randomUUID as Ny}from"crypto";var Ll=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??Ny(),properties:Od({},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??Ny(),properties:Od({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var li=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as IL,en as PL}from"@faker-js/faker";var ci="v1",di=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new IL({locale:PL}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${ci}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof fn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${ci}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${ci}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${ci}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${ci}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${ci}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as LL}from"zod";var pi=class extends nn{agentConfig;constructor(e,t){super(t),this.agentConfig=e}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${j}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Fh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${j}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ka,...e},signal:t.abortSignal});return Dh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${j}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return LL.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${j}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Bg.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${j}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return jd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${j}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return Ug.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${j}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return jd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${j}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Fg.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${j}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${j}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return rd.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${j}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return zg.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${j}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return nd.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${j}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return gd.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${j}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Vh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${j}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return km.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${j}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return _m.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${j}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return gm.parse(r)}};var ui=class extends nn{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${j}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return fm.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function ky(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ol=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await ky(r,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};function mi({orgId:n,client:e,gitMetadata:t,alwaysSaveCache:r,noCache:o}){return o?new ns:new Mp(n,e,t,r)}var Mp=class{constructor(e,t,{gitMainBranch:r,gitBranchName:o,gitProtectedBranches:i,gitCommitTimestamp:a,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:l},c){this.orgId=e;this.client=t;this.cacheHeaders={},r&&(this.cacheHeaders[Mg]=r),o&&(this.cacheHeaders[Ng]=o),a&&(this.cacheHeaders[kg]=a.toISOString()),s&&(this.cacheHeaders[_g]=s),l&&(this.cacheHeaders[Dg]=l.toISOString()),c?this.writeCaches=!0:o?this.writeCaches=!i.includes(o):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:r,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId,steps:t,schemaVersion:e.schemaVersion},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[t,r,o])s&&Ho({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await mt({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import Dk from"path";import{Server as ok}from"socket.io";var OL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async()=>{e.info({sessionId:r},"Cancel event received");let o=t.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},_y={event:"cancel",createHandler:OL};var ML=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message})}}},Dy={event:"fetchA11yTree",createHandler:ML};var NL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.html();i({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message})}}},Fy={event:"fetchDom",createHandler:NL};var kL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),t.removeSession(r,e)}},Uy={event:"disconnect",createHandler:kL};function Nn(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=_L(t);DL(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await FL(i,e,r,o)}catch(a){n.logger.error({result:n.result,err:a},"Error hoisting scalar result metadata")}})())}function _L(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function DL(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function FL(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import _a from"os";import UL from"v8";var By,kn,BL=_a.platform(),zL=_a.cpus().map(n=>({model:n.model,speed:n.speed}));function zy(n){let e=()=>{try{let t=!1,r=HL(),o=jL();r.freeMemory<1e6&&(t=!0);let i=UL.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;a/s>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:zL,platform:BL}}function HL(){let n=_a.totalmem(),e=_a.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function jL(){let n=_a.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!kn)return kn=t,null;let r={user:t.user-kn.user,nice:t.nice-kn.nice,sys:t.sys-kn.sys,idle:t.idle-kn.idle,irq:t.irq-kn.irq,total:t.total-kn.total};return By={measurementTime:e,intervalMs:e-kn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},kn=t,By}import{randomUUID as JL}from"crypto";import{faker as $L}from"@faker-js/faker";import GL from"assert";import WL from"axios";import*as VL from"child_process";import qL from"moment";import*as KL from"otpauth";import YL from"pg";async function Hy(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Bs(r,e);t.push(...o)}),t}var XL=Object.getPrototypeOf(async function(){}).constructor;async function jy(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,a={},s=(f,S)=>{o[f]=S,a[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let p;r.includes("createAppAuth")&&(p=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new XL("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(WL,qL,i.fakerInstance??$L,GL,YL,d,p,KL,VL,Hy,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await z(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error({err:f,env:o,evalCode:r},`[${n}] Error executing code: ${f}`),m=!1,f instanceof wr?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:a,persistentVariableUpdates:l,success:m,error:g}}async function $y({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:a=mr}){let s=JL(),l=await jy(s,{code:n,options:{fragment:e,timeoutMs:a},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${s}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as QL,randomUUID as ZL}from"crypto";import eO from"fetch-retry";var tO=eO(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),Gy=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Wy=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Vy({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=mr,retries:i=2,signal:a,logger:s}){if(!Gy)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Wy)throw new Error("Missing lambda auth secret.");let p=QL("sha256",Wy).update(n).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let m={id:ZL(),orgId:n,momenticLambdaAuthHash:p,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await z(tO(Gy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw s.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=tg.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function io(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Vy(n);else if(n.localTools)e=await $y({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
42
42
|
${e.error}
|
|
43
43
|
Code received:
|
|
44
44
|
${n.code}`;throw n.logger.error({err:e.error,code:n.code,env:n.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,r]of Object.entries(e.variableUpdates))n.context.setVariable(t,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await n.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,r]of Object.entries(e.persistentVariableUpdates))n.context.setVariable(t,r)}return e.result}import{set as nO}from"lodash-es";async function Ft(n){let{orgId:e,s:t,context:r,logger:o,signal:i,flagStore:a,retries:s=2,timeoutMs:l=mr,allowUndefined:c=!1}=n,d=/{{(.*?)}}/g,p=t.matchAll(d),u=t;for(let m of p){if(m.length<2)continue;let h=m[1].trim(),g;try{g=await io({orgId:e,code:h,fragment:!0,context:r,timeoutMs:l,logger:o,retries:s,localTools:n.localTools,signal:i,flagStore:a})}catch(S){throw o.error({err:S,value:t},"Error evaluating template string"),S}if(g===void 0&&!c)throw new R("UserConfigurationError",`Template fragment '${h}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let f=typeof g=="string"?g:`${g}`;f=f.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],f)}return u}async function Ml(n){return qy(n)}async function qy({obj:n,bannedKeys:e,allowList:t,context:r,prefixPath:o=[],replacements:i=[],...a}){for(let s in n){if(e.includes(s))continue;let l=!1;if(t)if(t.includes(s))l=!0;else continue;let c=n[s],d=[...o,s];if(typeof c=="string"&&c.includes("{{")){let p=await Ft({s:c,context:r,...a});if(c===p)continue;i.push({path:d,original:c}),n[s]=p}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await qy({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:i,allowList:l?void 0:t,...a})}return i}function Ky(n,e){for(let{path:t,original:r}of e)nO(n,t,r)}import rO from"fetch-retry";var l8=process.env.MAILINATOR_API_KEY,c8=rO(global.fetch,{retryOn:function(n,e,t){return n>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(n){return 500}});import{hostname as cO}from"os";async function Yy(n){let{command:e,tracer:t,timeoutMs:r,targetingWrapper:o,disableCache:i,fixtures:a}=n,{logger:s,abortSignal:l}=a;if(e.target&&!dr(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated&&(e.assertion.condition==="EXISTS"||e.assertion.condition==="VISIBLE"),d=Date.now(),p=0,u,m=500;for(;p<2||Date.now()-d<r;){p++,p>1&&await Y(m,l),l?.throwIfAborted();try{let{newTarget:h,elementInteractedDisplayString:g,result:f}=await o({ctx:a.ctx,tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async S=>oO(S.locator,n),options:{...e,disableCache:i,disableGlobalLocatorRedirect:!0,source:Dr(e),allowZeroOpacityOverride:!0}});if(u={success:f.success,data:f.data,err:f.err,newTarget:h,elementInteractedDisplayString:g},!f.success){u=f,m=Math.min(m*2,1e4);continue}return u}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(s.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof R)||h.reason!="ActionFailureError")throw h;u={success:!1,err:h}}}if(!u)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return u}async function oO(n,{command:e,fixtures:t}){let r=e.assertion;await t.browser.highlight(n);let o=!0,i,a;switch(r.type){case"ELEMENT_CONTENT":{let l=await n.textContent()??"";if(a={elementTextContent:ze(l,500,!0)},!Nl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,i=new R("AssertionFailureError",`The content ${c} '${r.value}': ${l}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:ze(await n.evaluate(c=>c.cloneNode(!1).outerHTML),500,!0)};let l;try{l=await n.getAttribute(r.attr,{timeout:3e3})??""}catch(c){i=new R("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${c}`),o=!1;break}if(!Nl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,r.operation==="EXISTS"?i=new R("AssertionFailureError",`The attribute ${r.attr} ${c}`):i=new R("AssertionFailureError",`The attribute ${r.attr} ${c} '${r.value}': ${l}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await n.evaluate(async(c,d)=>{let p=Date.now();for(;Date.now()-p<d;){await new Promise(m=>setTimeout(m,250));let u=c.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(c).visibility!=="hidden"&&window.getComputedStyle(c).display!=="none")return!0}return!1},xn*1e3);break}case"EDITABLE":{o=await n.isEditable({timeout:xn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await n.isEnabled({timeout:xn*1e3});break}case"FOCUSED":{o=await n.evaluate(c=>c===document.activeElement);break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let l=r.negated?Kd[r.condition]:Yd[r.condition];i=new R("AssertionFailureError",`The element ${l}`)}break}case"ELEMENT_NAME":{let l=await n.evaluate(c=>c.tagName);if(!Nl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,i=new R("AssertionFailureError",`The element tag name ${c} '${r.value}': ${l}`)}break}case"ELEMENT_STYLE":{let l=await n.evaluate((c,d)=>window.getComputedStyle(c).getPropertyValue(d),r.property);if(!Nl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,r.operation==="EXISTS"?i=new R("AssertionFailureError",`The style property ${r.property} ${c}`):i=new R("AssertionFailureError",`The style property ${r.property} ${c} '${r.value}': ${l}`)}break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{success:o,data:a,err:i}}function Nl(n,e,t,r){let o;switch(t){case"CONTAINS":{o=n.includes(e);break}case"EQUALS":{o=n.trim()===e.trim();break}case"STARTS_WITH":{o=n.trim().startsWith(e);break}case"EXISTS":{o=n.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return r?!o:o}import{Jimp as iO}from"jimp";async function Da(n,e){let t=await n.screenshot(e),r=await iO.fromBuffer(t);return{buffer:t,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as Xy}from"jimp";import Np from"jpeg-js";import aO from"pixelmatch";async function Jy({ctx:n,tracer:e,command:t,disableCache:r,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!dr(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let l={clearHighlights:!0,hideCaret:!0},c;t.target?.elementDescriptor?c=(await i({ctx:n,tracer:e,command:t,target:t.target,cache:t.cache?.target??t.target?.a11yData,action:async D=>Da(o,{locator:D.locator,...l}),options:{...t,disableCache:r,disableGlobalLocatorRedirect:!0}})).result:c=await Da(o,l);let d=await s.prepareGoldenScreenshotForComparison(a,t,c);if((c.height!==d.height||c.width!==d.width)&&a.debug({currHeight:c.height,currWidth:c.width,savedHeight:d.height,savedWidth:d.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-d.height)>10||Math.abs(c.width-d.width)>10){let $=`${c.width}x${c.height}`,D=`${d.width}x${d.height}`;return{fail:!0,thoughts:`Current screenshot (${$}) does not match saved screenshot dimensions (${D}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:d.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let p=await Xy.fromBuffer(c.buffer),u={width:c.width,height:c.height},m=await Xy.fromBuffer(d.buffer),h={width:d.width,height:d.height},g,f=u.width*u.height,S=h.width*h.height,b=Math.abs(u.height-h.height),w=Math.abs(u.width-h.width);if(f>S){let $=p.cover({w:h.width,h:h.height});c.buffer=await $.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height}else if(S>f){let $=m.cover({w:u.width,h:u.height});d.buffer=await $.getBuffer("image/jpeg"),g="saved"}let T={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},C=t.threshold??.1,A=aO(Np.decode(d.buffer).data,Np.decode(c.buffer).data,T.data,c.width,c.height,{threshold:C,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,k=A>C*100,O=`Visual diff of ${A.toFixed(2)}% detected, which is ${k?"over":"under"} the threshold of ${C*100}%.`;if(g&&(O+=` The ${g} screenshot was cropped since it was taller by ${b} pixels and wider by ${w} pixels.`),k)throw new R("ActionFailureError",O);return{fail:k,thoughts:O,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:Np.encode(T,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var sO=3e4;async function Qy({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??sO/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([m,h])=>m&&h)),a=new URLSearchParams;Object.entries(n.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{a.append(m,h)});let s=a.toString(),l;if($o(n.url)&&(l=n.url),t&&Go(n.url,t)&&(l=new URL(n.url,t).toString()),!l)throw new R("ActionFailureError",`Invalid URL: ${n.url}`);e.debug({url:l,searchParams:s,headers:i,body:n.body,method:n.method},"Making HTTP request");let d=await z((async()=>{let m=s?`${l}?${s}`:l;try{return await r(m,{headers:i,method:n.method,body:n.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let m;try{m=await d.text()}catch(h){m=`Failed to read response body: ${h}`}throw new R("ActionFailureError",`Fetch request failed with status ${d.status}: ${m}`)}let p={};d.headers.forEach((m,h)=>{p[h]=m});let u={status:d.status,headers:p};if(d.headers.get("content-type")?.includes("json"))try{u.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(u.text=await d.text());return u}var lO=5e3;async function kl({timeout:n=xn,...e}){let t=Date.now(),r=n*1e3,o=r+1e4,i,a=0,s=500;for(;a-t<r;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();i=await Zy(e),a=Date.now();let c=a-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Y(s,e.signal),s=Math.min(Math.floor(s*1.5),lO);else return i}return i=await Zy(e),i}async function Zy({assertion:n,browser:e,autoExpandIframes:t}){switch(n.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t){let l=await e.evaluateFunctionInAllFrames(eb,{value:n.value,negated:!!n.negated,returnHtml:!1});i=n.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(eb,{value:n.value,negated:!!n.negated,returnHtml:!0},"checking page content"));if(!i){let l=n.negated?Jt.CONTAINS:Qt.CONTAINS;a=new R("AssertionFailureError",`The page ${l} '${n.value}'.`),o=s}}catch(s){a=new R("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function eb({value:n,negated:e,returnHtml:t}){let r=document.documentElement.outerHTML,o=r.includes(n)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?r:void 0}}var kp=async n=>{let{step:e,resolvedInputs:t}=n.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:a,controller:s}=n.fixtures,l=s.browser,{orgId:c,runId:d}=n.inputs,p=s.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),r.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await Ft({orgId:c,s:f,context:o,logger:r,localTools:a,signal:p,flagStore:s.flagStore});g={orgId:c,cacheKeys:[S,...Object.entries(t).map(([w,T])=>`${w}:${T}`)]},r.debug({original:f,keyParams:g},"Module cache key params");let b=Date.now();for(;Date.now()-b<Lg;){p?.throwIfAborted();let w=await i.getCacheResult(g);if(w){r.debug({cacheResult:w},"Got result from module execution cache"),u=_l(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(w),m=!0;break}else r.debug({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let T=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${cO()};runId:${d}`},p);if(T.acquired){h=T.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await Y(2500+Math.random()*1e4,p)}}try{if(!u)u=await dO(n);else if(e.autoAuth){let f=zs.safeParse(u.data);if(!f.success)throw new R("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);r.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let S=!1,b=e.advanced?.cacheInvalidation;if(b&&b.type==="PAGE_CHECK"){let w={type:"CONTENT",value:b.substring},T=await kl({timeout:xn,assertion:w,browser:l,logger:r,signal:p,autoExpandIframes:!!l.userBrowserSettings.autoExpandIframes});T.success?r.debug({invalResult:T},"Cached result still valid after page check, continuing..."):(r.info({invalResult:T},"Invalidating cached result due to page check failure"),S=!0)}if(g&&S)return await i.deleteCacheResult(g),kp(n)}}finally{try{h!==void 0&&!m&&u?.status==="SUCCESS"&&await pO({step:e,result:u,browser:s.browser,cacheKeyPrefix:h,logger:r,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return u},dO=async n=>{let{step:e,tracer:t}=n.moduleParams,r=_l(e,n.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await vr(n.work,()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}}));return r.results=a,r.status=i,r.finishedAt=new Date,Nn({asyncTasks:n.work.asyncTasks,nestedResults:a,result:r,logger:n.fixtures.logger}),r};function _l(n,e,t){let r={};return Object.entries(e).forEach(([i,a])=>{r[i]=JSON.stringify(a)}),{type:"MODULE",id:n.id,moduleId:n.moduleId,moduleName:n.name,startedAt:new Date,cacheConfig:n.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:t}}async function tb({orgId:n,step:e,context:t,logger:r,flagStore:o,codeEvalTools:i,signal:a}){let s={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){r.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}s[l]=await io({orgId:n,code:c,fragment:!0,context:t,logger:r,localTools:i,signal:a,flagStore:o})}return s}catch(l){throw a?.throwIfAborted(),new R("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function pO({step:n,result:e,browser:t,cacheKeyPrefix:r,logger:o,storage:i}){let a=n.cacheConfig?.cacheExpiryMs;(!a||a===lf)&&(a=n.defaultCacheTtl??cf);let s;n.autoAuth?s=JSON.stringify(await t.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:r,ttlMs:a,truncatedCacheResultJson:Ff(s)},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:r,ttlMs:a})}async function ao(n,e,t){return uO(n,e,t)}async function uO(n,e,t){let r=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof R?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,n.type==="RESOLVED_MODULE"){let l=_l(n,{},"FAILED");return l.message=s,l.startedAt=r,l.finishedAt=i,l}return{...il(n),startedAt:r,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function vr(n,e){let t=!1;try{return n&&!n.state.failureRecoveryDisabled&&(n.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{n&&t&&(n.state.failureRecoveryDisabled=void 0)}}import{randomUUID as nb}from"crypto";import{cloneDeep as hO}from"lodash-es";function Dl(n,e){n.state.healingDetails?n.state.healingDetails.push(e):n.state.healingDetails=[e]}var Fl=async n=>{let{step:e,tracer:t}=n.presetParams,{logger:r,controller:o,context:i,billingReporter:a}=n.fixtures,{collectDebugData:s}=n.options,{testMetadata:l,suiteMetadata:c}=n.inputs,d=e.command.type,p=r.child({commandType:d,stepId:e.id,commandId:e.command.id}),u=ra(e.command);n.work.asyncTasks.push(a.reportCreditsUsed(p,d,u,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let m=o.browser.url(),h=new Date,g,f=nb(),S=nb();if(s)try{g=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75});let E=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:p,snapshotId:f,html:E}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(p,f,E))}catch(E){p.debug({err:E},"Failed to take before screenshot, continuing...")}let b,w,T,C=Ds();try{let E=await o.executePresetCommand(C,t,e.command,i,l?.advanced.disableAICaching??!1);E.beforeScreenshotOverride&&(g=E.beforeScreenshotOverride),T=E.afterScreenshotOverride;let{proposedStep:A}=gO({work:n.work,step:e,newTargets:E.newTargets,logger:p}),k=new Date,O=o.browser.url();w={beforeUrl:m,afterUrl:O,startedAt:h,finishedAt:k,viewport:o.browser.getViewport(),status:E.fail?"FAILED":"SUCCESS",elementInteracted:E.elementInteracted},b={...e,message:E.thoughts??fO(E.newTargets)??"Successfully executed preset action.",beforeUrl:m,afterUrl:O,finishedAt:k,startedAt:h,status:E.fail?"FAILED":"SUCCESS",data:E.data,results:[w],details:C.details,proposedStep:A},"assertion"in e.command&&(b.message=E.thoughts||"Assertion passed.")}catch(E){p.error({message:E.message,stack:E.stack},`Failed executing preset step ${qr(e.command)}`);let A=o.browser.url(),k=new Date,O=E instanceof Error?E.message:`${E}`;E instanceof R&&E.getLastScreenshotBuffer()&&(T=E.getLastScreenshotBuffer()),w={beforeUrl:m,afterUrl:A,startedAt:h,finishedAt:k,viewport:o.browser.getViewport(),status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:O},b={...e,startedAt:h,finishedAt:k,beforeUrl:m,afterUrl:A,status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:O,failureReason:E instanceof R?E.reason:void 0,results:[w],details:C.details}}if(s)try{T||(T=await o.browser.screenshot({retries:1,quality:75}));let E=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:p,snapshotId:S,html:E}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(p,S,E))}catch(E){p.debug({err:E},"Failed store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return w.beforeSnapshot=f,b.beforeSnapshot=f,w.afterSnapshot=S,b.afterSnapshot=S,g&&(t.attachBeforeScreenshot({logger:p,snapshotId:f,screenshot:g}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(p,f,g))),T&&(t.attachAfterScreenshot({logger:p,snapshotId:S,screenshot:T}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(p,S,T))),b};function gO({work:n,step:e,newTargets:t,logger:r}){if(!t?.length)return{proposedStep:void 0};let o=e.command;Lf(o,t,r);let i=t[0]?.description;if(i&&"target"in o&&o.target&&o.target.type==="description"){let a={...o,target:{...o.target,elementDescriptor:i}},s={...hO(e),command:a};return Dl(n,{type:"DESCRIPTION_UPDATE",thoughts:`Updated element description after the original element could not be found on the page. New element location reasoning: ${t[0]?.thoughts}`}),{proposedStep:s}}return{proposedStep:void 0}}function fO(n){if(n?.length){if(n.length===1&&n[0]?.thoughts)return n[0].thoughts;if(n.length===2&&n.every(e=>e.thoughts))return`Located first element: ${n[0]?.thoughts}
|
|
@@ -3928,7 +3928,7 @@ ${a.stack}`),l.status(500).send("Internal Server Error")}),n){let a=Fv.static(n,
|
|
|
3928
3928
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
3929
3929
|
`)}import cD from"events";import Dc from"fs";import dD from"open";import{cpus as lE}from"os";import _c from"path";import{fileURLToPath as pD}from"url";import i_ from"diff-lines";import{gt as a_}from"semver";import{execSync as Uk}from"child_process";import{platform as Bk}from"os";function Lu(){return Hv()?(y.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),y.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
3930
3930
|
`),2):(y.dimmed("Setting device pixel ratio to 1."),y.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
3931
|
-
l.`),1)}function Hv(){return Bk()==="darwin"&&Uk("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Ou(n){Hv()&&n===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import zk from"@actions/exec";import Hk from"@actions/io";import jk from"quote";import $k from"string-argv";async function jv(n,e=!0){let t=$k(n),r=await Hk.which(t[0],!0),o=t.slice(1),i=zk.exec(jk(r),o,{delay:100});if(e)return i}import{existsSync as Gk,statSync as Wk}from"fs";var Va=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;function $v(n){try{return Gk(n)&&Wk(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Vk from"csv-parser";import{createReadStream as qk}from"fs";function Mu(n){return new Promise((e,t)=>{let r=[];qk(n).pipe(Vk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import pc from"semver";import{z as uc}from"zod";var zn="2.10.0",Kk="https://registry.npmjs.org/momentic",Yk=uc.object({versions:uc.record(uc.string(),uc.unknown()).optional()});async function Gv(n){try{await Xk(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function Xk(n){if(!zn){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 z(fetch(Kk),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=Yk.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))pc.valid(r)&&(!t||pc.gt(r,t))&&pc.gt(r,zn)&&pc.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${zn} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{confirm as Qk,input as Zk}from"@inquirer/prompts";import{existsSync as e_,mkdirSync as t_,statSync as n_}from"fs";import{dirname as r_}from"path";import{hostname as Jk}from"os";var X=rc({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Jk(),disableConsoleLogs:!0}).child({version:"2.10.0"});var o_=!1,Vv=(()=>{try{return n_("/.dockerenv"),!0}catch{return!1}})();async function St(n,e){return Va||o_||Vv?!0:(X.flush(),await new Promise(r=>setTimeout(r,500)),await Qk({message:n}))}async function Nu(n){let e=r_(n);return $v(e)?e_(n)?St(`File '${Wv(n)}' already exists. Overwrite existing content?`,!0):!0:await St(`Directory '${Wv(e)}' doesn't exist. Create it now?`,!0)?(t_(e,{recursive:!0}),!0):!1}function Wv(n){return n.replace(/(\s+)/g,"\\$1")}async function qv(n,e){return Va||Vv?e:(await Zk({message:n,default:e})).trim()||e}async function Kv({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){a_(e.schemaVersion,Le)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Pf(e.steps).forEach(h=>{t.modules[h]||(y.error(`The test patch contains a module with id ${h} 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 St("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!i&&!await St("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=to(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!==Le){let{steps:h,newVersion:g}=await da({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=g,p=Ne.array().parse(h)}else p=Ne.array().parse(e.steps);let{stepsToSave:u}=await mt({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let m=i_(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(m),y.dimmed("=".repeat(30)),y.dimmed(""),d&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await St("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Yn({relativeTestPath:n.relativePath,steps:u,schemaVersion:d??e.schemaVersion,project:t.project}),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Bt}from"crypto";import{z as gT}from"zod";var it=" ".repeat(6);import hT from"chalk";import{Argument as go,InvalidArgumentError as qa,Option as we}from"@commander-js/extra-typings";import{validateHeaderValue as s_}from"http";import{z as Xv}from"zod";var Yv=58888,mc=30*60*1e3;function rr(n){let e=parseInt(n,10);if(isNaN(e))throw new qa("Not a number.");return e}function hc(n){if(n===void 0)return;let e={};for(let t of n){let r=t.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,r),i=t.slice(r+1);s_(o,i),e[o]=i}return e}var yn=new we("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(n=>{if(!n)throw new qa("API key is required.");return n}).makeOptionMandatory(),bn=new we("--server <server>","Momentic server to use.").default("https://api.momentic.ai").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new qa("Not a valid URL.")}}),Rr=new we("-y, --yes","Skip all confirmation prompts.").env("CI"),ku=new we("-w, --wait","Wait for tests to finish running before exiting."),_u=new we("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${mc/1e3} seconds.`).default(mc/1e3).implies({wait:!0}).argParser(rr),gc=new we("--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."),Jv=new we("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(_s)),Qv=new we("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),Du=new we("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zv=new we("--upload-results","Upload test results to Momentic Cloud.").default(!1),Fu=new we("--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."),Uu=new we("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Bu=new we("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(rr),eT=new we("--port <port>",`Port to run the app on. Defaults to ${Yv}.`).default(Yv).argParser(rr),zu=new we("--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."),fc=new we("--env <env>","Name of the environment to use when running tests."),Sc=new we("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new qa("Not a valid URL.")}}),tT=new we("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>{let e=rr(n);if(e<1)throw new qa("Shard index must be greater than 0.");return e}),nT=new we("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(rr),Ut=new we("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),xi=new we("-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."),rT=new we("--fix","Attempt to fix any issues found."),Hu=new we("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),ju=new we("--disable-cache","Disable caching of test results."),oT=new we("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),iT=new we("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),aT=new we("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),sT=new go("<tests...>","One or more test paths to queue on Momentic Cloud."),lT=new go("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),$u=new go("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),cT=new go("<suites...>","One or more suite paths that exist on Momentic Cloud."),dT=new go("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),pT=new go("<results>","Path to the results archive.").argRequired(),Gu=new we("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Wu=new go("<test>","Name of the test to quarantine.").argOptional();async function Vu(n){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(y.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),y.debug(`Identified node version ${e}`);let r=await n.client.getAuthInfo();return y.debug("Got auth info from API"),r}import{Console as uT}from"console";import{format as Ka}from"util";var qu=class extends Error{constructor(e,t,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},yc=class n extends uT{_buffer=[];_groupDepth=0;Console=uT;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new qu(void 0,n.write).stack;if(!i)return e;let a=i.split(`
|
|
3931
|
+
l.`),1)}function Hv(){return Bk()==="darwin"&&Uk("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Ou(n){Hv()&&n===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import zk from"@actions/exec";import Hk from"@actions/io";import jk from"quote";import $k from"string-argv";async function jv(n,e=!0){let t=$k(n),r=await Hk.which(t[0],!0),o=t.slice(1),i=zk.exec(jk(r),o,{delay:100});if(e)return i}import{existsSync as Gk,statSync as Wk}from"fs";var Va=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;function $v(n){try{return Gk(n)&&Wk(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Vk from"csv-parser";import{createReadStream as qk}from"fs";function Mu(n){return new Promise((e,t)=>{let r=[];qk(n).pipe(Vk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import pc from"semver";import{z as uc}from"zod";var zn="2.10.2",Kk="https://registry.npmjs.org/momentic",Yk=uc.object({versions:uc.record(uc.string(),uc.unknown()).optional()});async function Gv(n){try{await Xk(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function Xk(n){if(!zn){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 z(fetch(Kk),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=Yk.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))pc.valid(r)&&(!t||pc.gt(r,t))&&pc.gt(r,zn)&&pc.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${zn} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{confirm as Qk,input as Zk}from"@inquirer/prompts";import{existsSync as e_,mkdirSync as t_,statSync as n_}from"fs";import{dirname as r_}from"path";import{hostname as Jk}from"os";var X=rc({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Jk(),disableConsoleLogs:!0}).child({version:"2.10.2"});var o_=!1,Vv=(()=>{try{return n_("/.dockerenv"),!0}catch{return!1}})();async function St(n,e){return Va||o_||Vv?!0:(X.flush(),await new Promise(r=>setTimeout(r,500)),await Qk({message:n}))}async function Nu(n){let e=r_(n);return $v(e)?e_(n)?St(`File '${Wv(n)}' already exists. Overwrite existing content?`,!0):!0:await St(`Directory '${Wv(e)}' doesn't exist. Create it now?`,!0)?(t_(e,{recursive:!0}),!0):!1}function Wv(n){return n.replace(/(\s+)/g,"\\$1")}async function qv(n,e){return Va||Vv?e:(await Zk({message:n,default:e})).trim()||e}async function Kv({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){a_(e.schemaVersion,Le)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Pf(e.steps).forEach(h=>{t.modules[h]||(y.error(`The test patch contains a module with id ${h} 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 St("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!i&&!await St("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=to(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!==Le){let{steps:h,newVersion:g}=await da({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=g,p=Ne.array().parse(h)}else p=Ne.array().parse(e.steps);let{stepsToSave:u}=await mt({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let m=i_(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(m),y.dimmed("=".repeat(30)),y.dimmed(""),d&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await St("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Yn({relativeTestPath:n.relativePath,steps:u,schemaVersion:d??e.schemaVersion,project:t.project}),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Bt}from"crypto";import{z as gT}from"zod";var it=" ".repeat(6);import hT from"chalk";import{Argument as go,InvalidArgumentError as qa,Option as we}from"@commander-js/extra-typings";import{validateHeaderValue as s_}from"http";import{z as Xv}from"zod";var Yv=58888,mc=30*60*1e3;function rr(n){let e=parseInt(n,10);if(isNaN(e))throw new qa("Not a number.");return e}function hc(n){if(n===void 0)return;let e={};for(let t of n){let r=t.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,r),i=t.slice(r+1);s_(o,i),e[o]=i}return e}var yn=new we("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(n=>{if(!n)throw new qa("API key is required.");return n}).makeOptionMandatory(),bn=new we("--server <server>","Momentic server to use.").default("https://api.momentic.ai").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new qa("Not a valid URL.")}}),Rr=new we("-y, --yes","Skip all confirmation prompts.").env("CI"),ku=new we("-w, --wait","Wait for tests to finish running before exiting."),_u=new we("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${mc/1e3} seconds.`).default(mc/1e3).implies({wait:!0}).argParser(rr),gc=new we("--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."),Jv=new we("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(_s)),Qv=new we("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),Du=new we("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zv=new we("--upload-results","Upload test results to Momentic Cloud.").default(!1),Fu=new we("--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."),Uu=new we("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Bu=new we("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(rr),eT=new we("--port <port>",`Port to run the app on. Defaults to ${Yv}.`).default(Yv).argParser(rr),zu=new we("--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."),fc=new we("--env <env>","Name of the environment to use when running tests."),Sc=new we("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new qa("Not a valid URL.")}}),tT=new we("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>{let e=rr(n);if(e<1)throw new qa("Shard index must be greater than 0.");return e}),nT=new we("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(rr),Ut=new we("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),xi=new we("-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."),rT=new we("--fix","Attempt to fix any issues found."),Hu=new we("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),ju=new we("--disable-cache","Disable caching of test results."),oT=new we("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),iT=new we("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),aT=new we("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),sT=new go("<tests...>","One or more test paths to queue on Momentic Cloud."),lT=new go("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),$u=new go("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),cT=new go("<suites...>","One or more suite paths that exist on Momentic Cloud."),dT=new go("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),pT=new go("<results>","Path to the results archive.").argRequired(),Gu=new we("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Wu=new go("<test>","Name of the test to quarantine.").argOptional();async function Vu(n){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(y.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),y.debug(`Identified node version ${e}`);let r=await n.client.getAuthInfo();return y.debug("Got auth info from API"),r}import{Console as uT}from"console";import{format as Ka}from"util";var qu=class extends Error{constructor(e,t,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},yc=class n extends uT{_buffer=[];_groupDepth=0;Console=uT;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new qu(void 0,n.write).stack;if(!i)return e;let a=i.split(`
|
|
3932
3932
|
`).slice(o).filter(Boolean).join(`
|
|
3933
3933
|
`);return e.push({message:r,origin:a,type:t}),e}_log(e,t){n.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",Ka(e,...t))}error(e,...t){this._log("error",Ka(e,...t))}info(e,...t){this._log("info",Ka(e,...t))}log(e,...t){this._log("log",Ka(e,...t))}warn(e,...t){this._log("warn",Ka(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function mT(n){let e=globalThis.console,t=new yc;globalThis.console=t;try{n()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
3934
3934
|
`);process.stderr.write(`${o}
|
|
@@ -3937,7 +3937,7 @@ ${[...r].map(i=>`${it}- ${i}`).join(`
|
|
|
3937
3937
|
`)}`),o.size>0&&y.warn(`Modified the following module files:
|
|
3938
3938
|
${[...o].map(i=>`${it}- ${i}`).join(`
|
|
3939
3939
|
`)}`)):y.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(y.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function ST({project:n}){let e=de(n,y),t=Object.values(e.tests),r=await ll(e,X),o={},i={},a=new Set,s=new Set;for(let c of t)o[c.name]?i[c.name]?i[c.name].push(c.fullFilePath):i[c.name]=[o[c.name],c.fullFilePath]:o[c.name]=c.fullFilePath;for(let c of r)s.has(c.name)&&a.add(c.name),s.add(c.name);if(Object.entries(i).length>0||a.size>0){for(let[c,d]of Object.entries(i))for(let p of d)y.error(`Test Name ${c} is duplicated in ${p}`);for(let c of a)y.error(`Module name ${c} is duplicated in your project`);process.exit(1)}y.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as d_}from"lodash-es";async function yT({client:n,skipPrompts:e,project:t}){let r=await n.getAllEnvironments(),o=d_(t.config);o.environments||(o.environments=[]);for(let i of r){let a=o.environments?.find(s=>s.name===i.name);if(a)!e&&!await St(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[Qe],delete i.variables[Qe],a.envVariables=i.variables;else{let s=i.variables[Qe];delete i.variables[Qe],o.environments.push({name:i.name,baseUrl:s,envVariables:i.variables})}}ri(o,t.configFilePath),y.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as bT}from"crypto";import wT from"fs";async function Ku({testsToFetch:n,client:e,all:t,yes:r}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:n,all:t}),a=0;for(let[l,c]of Object.entries(o)){let d=vT(l,ve.TEST);!r&&!await Nu(d)||(a+=1,wT.writeFileSync(d,c,"utf-8"),X.info({checksum:bT("md5").update(c).digest("hex")},`Wrote '${d}'`))}let s=0;for(let[l,c]of Object.entries(i)){let d=vT(l,ve.MODULE);!r&&!await Nu(d)||(s+=1,wT.writeFileSync(d,c,"utf-8"),X.info({checksum:bT("md5").update(c).digest("hex")},`Wrote '${d}'`))}a===0?y.success("Pulled 0 tests."):y.success(`Pulled ${a} test${a>1?"s":""}${s?` and ${s} module${s>1?"s":""}`:""}!`)}function vT(n,e){switch(e){case ve.TEST:return`${Ee(n)}.${Et.TEST}`;case ve.MODULE:return`${Ee(n)}.${Et.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function TT(n){let{project:e,client:t,skipPrompts:r}=n;y.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),y.info("Importing environments from Momentic Cloud."),y.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await St("Are you sure you want to proceed?",!0)||(y.info("Aborting..."),process.exit(1)),await yT({client:t,project:e,skipPrompts:r}),y.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.`),y.info("Importing tests and modules from Momentic Cloud."),await Ku({testsToFetch:[],client:t,all:!0,yes:r}),y.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}async function ET(n){let{client:e,skipPrompts:t,paths:r}=n;await Ku({testsToFetch:r,client:e,all:void 0,yes:t}),y.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 p_ from"fs";import{tmpdir as u_}from"os";import m_ from"path";import{registry as Xa}from"playwright-core/lib/server";import xT from"proper-lockfile";var CT=m_.join(u_(),"momenticBrowserInstallation");var Yu=["chrome","chromium","chrome-for-testing"],h_={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},RT={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function AT(n){let e=RT[h_[n]??""]??"",t=Xa.findExecutable(e);return!t||t.installType==="none"?!1:Xu(t)}function Xu(n){let e=n.executablePath();return p_.existsSync(e)}function g_(n,e){let t=RT[n];if(!t)throw new Error(`Requested install of unknown browser type ${n}`);let r=Xa.findExecutable(t);if(!r||r.installType==="none")throw new Error(`Requested install of unknown browser type ${n}`);if(!(!e&&Xu(r)))return r}async function f_({browser:n,force:e}){let t=g_(n,e);if(!t){y.info(`Browser '${n}' is already installed, skipping...`);return}y.info(`Installing browser '${n}'...`);try{await Xa.installDeps([t],!1),await Xa.install([t],!1)}catch(r){if(r.message.includes("Lock file is already being held")){y.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Xa.findExecutable(n),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Xu(o);)y.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw r}}async function IT({rawBrowsers:n,force:e=!1,all:t=!1}){let r=t?Yu:Array.from(new Set(n));try{await xT.lock(CT,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){y.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of r)try{await f_({browser:i,force:e})}catch(a){o=a,y.error(`Failed to install the ${i} browser: ${a}`)}}finally{await xT.unlock(CT,{realpath:!1})}if(o)throw o}async function PT(n){let e=de(n,y),t=Object.values(e.tests);for(let r of t)try{let o=to(r.fullFilePath,y,e),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){y.debug(`Test ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let a=ut.parse(o),s=await Yr(a,i,y);y.dimmed(`Updating ${r.relativePath}`),Yn({relativeTestPath:r.relativePath,steps:{beforeSteps:o.beforeSteps,steps:s.steps,afterSteps:o.afterSteps},schemaVersion:Le,project:n,forceSaveOnNoDiffs:!0})}catch(o){y.error({err:o},`Failed to read or migrate test ${r.name} (${r.relativePath}), continuing...`)}for(let r of Object.values(e.modules)){y.dimmed(`Updating ${r.relativePath}`);try{let o=Kn(r.fullFilePath,y),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){y.debug(`Module ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let a=await Yr({id:o.moduleId,schemaVersion:o.schemaVersion},i,y);Zr({content:{...o,steps:a.steps},schemaVersion:Le,momenticFiles:e,project:n,forceSaveOnNoDiffs:!0})}catch(o){y.error({err:o},`Failed to read or migrate module ${r.name} (${r.relativePath}), continuing...`)}}}import{spawnSync as y_}from"child_process";import{PostHog as S_}from"posthog-node";async function LT(n,e){let t,r=0,o=3,i,a;for(;r<o;)try{let s=await z(n.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=s.featureFlags||{},a=s.featureFlagPayloads||{};break}catch(s){t=s,r++,await new Promise(l=>setTimeout(l,100*r))}if(i&&a)return{flags:i,payloads:a};throw t}var Tc=class n extends aa{constructor(t,r,o,i){super(o,i);this.client=t;this.orgId=r}static async init(t){let r=new S_("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await LT(r,t);return new n(r,t,o,i)}async refresh(){let{flags:t,payloads:r}=await LT(this.client,this.orgId);this.flags=t,this.payloads=r}};function b_(){try{let e=y_("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();y.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(n){let e=n instanceof Error?n.message:String(n);y.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
|
|
3940
|
-
${e}`)}}async function OT({project:n,orgId:e,apiClient:t}){y.info("Pulling browser and AI configuration options from Cloud");let r=await Tc.init(e);n.config.browser={autoExpandIframes:r.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:r.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:r.isBooleanFlagEnabled("global_locator_redirect"),visualActions:r.isBooleanFlagEnabled("visual_actions"),...n.config.browser},n.config.advanced={fakerConstantSeed:r.isBooleanFlagEnabled("faker_constant_seed"),...n.config.advanced},n.config.ai={aiPageFiltering:r.isBooleanFlagEnabled("rag_v2"),agentConfig:await t.getAgentConfig(),...n.config.ai},y.info(`Updated ${n.configFilePath} to include V2 browser and AI configuration options`),y.info("Determining main Git branch"),n.config.gitMainBranch=b_(),ri(n.config,n.configFilePath),y.success("Migration complete!")}import{input as w_,search as v_}from"@inquirer/prompts";import T_ from"fuse.js";async function Ec({prompt:n,inputtedTest:e,testOptions:t}){if(e){let o=t.find(i=>i.name===e);if(!o)y.error(`${e} is not a valid test option.`);else return o.value}let r=new T_(t,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1});return v_({message:n,source:async o=>!o||o.length===0?t:r.search({name:o}).map(a=>a.item)})}async function xc({prompt:n,inputtedReason:e}){return e||w_({message:n})}async function MT({test:n,reason:e,apiClient:t,project:r,logger:o}){let i=de(r,y).tests,a=Object.values(i).map(d=>({value:d.id,name:d.name})),s=await Ec({prompt:"Select a test to quarantine.",inputtedTest:n,testOptions:a}),l=await xc({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await t.quarantineTest(s,l);let c=i[s].name;y.success(`Test ${c} has been successfully quarantined. Navigate to ${t.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${c}'.`)}async function NT({test:n,reason:e,apiClient:t,project:r,logger:o}){let i=de(r,y).tests,a=Object.values(i).map(m=>({value:m.id,name:m.name})),s=(await t.getQuarantinedTests()).quarantined,l=new Set(s.map(m=>m.testId)),c=a.filter(m=>l.has(m.value)),d=await Ec({prompt:"Select a test to unquarantine.",inputtedTest:n,testOptions:c}),p=await xc({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await t.unquarantineTest(d,p);let u=i[d].name;y.success(`Test ${u} has been successfully removed from quarantine.`)}function kT(n){return n?Ee(n):"Unknown suite"}async function _T({client:n,orgId:e,suitePaths:t,wait:r,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:s}=await n.queueSuiteRuns({paths:t,...i});X.info({orgId:e,suiteRunIds:a,runGroupIds:s,suitePaths:t},"Queued suites remotely"),y.dimmed(`Queued ${t.length} suites.`),r||process.exit(0);let l=Date.now();y.dimmed(`Waiting for ${t.length} suites to finish. You can view results upon completion at:`);for(let f of s)y.dimmed(`${it}- ${n.getAppUrl()}/run-groups/${f}`);let c=new Set,d=[],p=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(b=>b.status==="FAILED"&&(b.failureReason||b.finishedAt&&Date.now()-b.finishedAt.getTime()>30*1e3)||b.status==="PASSED"||b.status==="CANCELLED"),u=await bc({name:"suites",getResults:async()=>{let f=s.filter(w=>!d.some(T=>T.id===w)),S=await n.bulkGetRunGroupStatus(f),b=[];for(let w of S)p(w)?d.push(w):b.push(w);return[...d,...b]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(c.has(S.id)||(c.add(S.id),y.log(`${c.size}/${s.length} ${kT(S.suite?.name)}`)))}),f.every(p))}),m=n.getAppUrl(),g=Ci({results:u,startTime:l,onFailed:f=>{let S=kT(f.suite?.name),b=f.runs.filter(T=>T.status==="FAILED").length,w=f.runs.length;y.error(`${S} (${b}/${w} tests failed):`);for(let T of f.runs)if(T.status==="FAILED"){let C=T.testName||T.test?.name;y.error(` ${C?Ee(C):"Unknown test"} (${m}/runs/${T.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Ee(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(g.failed>0?1:0)}async function DT({tests:n,client:e,orgId:t,...r}){!r.yes&&!await St(`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(X.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),y.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;y.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,s=[],l=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",c=e.getAppUrl(),d=Date.now(),p=await bc({name:"runs",getResults:async()=>{let m=i.filter(f=>!s.some(S=>S.id===f)),h=await e.bulkGetRunStatus(m),g=[];for(let f of h)l(f)?s.push(f):g.push(f);return[...s,...g]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(h=>{if(h.status==="RUNNING"&&!a.has(h.id)){a.add(h.id);let g=h.testName||h.test?.name;g&&y.log(`${a.size}/${o.length} ${Ee(g)}`)}}),m.every(l))}),u=Ci({results:p,startTime:d,onFailed:m=>{let h=m.testName||m.test?.name;wc(m,h?Ee(h):"Unknown test")},getDisplayLine:m=>{let h=m.testName||m.test?.name,g=` ${h?Ee(h):"Unknown test"}`;return m.id&&(g+=` (${c}/runs/${m.id})`),g},entity:"test"});process.exit(u.failed>0?1:0)}import Pi,{supportsColor as Q_}from"chalk";import{randomUUID as Z_}from"crypto";import eD from"fs";import{existsSync as __,mkdirSync as D_,statSync as F_}from"fs";import{randomUUID as Ju}from"crypto";import Cc from"fs";import{hostname as E_}from"os";import Ja from"path";async function Rc(n,e,t,r,o){if(r){let i=Ja.extname(r),a=`${Ju()}-screenshot${i}`,s=Ja.join(t,a),c=await(await fetch(r)).arrayBuffer();return Cc.writeFileSync(s,Buffer.from(c)),a}if(o){let i=await e.getScreenshot(n,o);if(i){let a=`${o}-screenshot.jpeg`,s=Ja.join(t,a);return Cc.writeFileSync(s,i),a}}}async function x_(n,e,t,r){let o=r.runId??Ju(),i={uuid:o,historyId:o,testCaseId:r.test.id,fullName:r.test.name,name:Ee(r.test.name),status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"skipped":"failed",start:r.lastAttemptStartedAt.getTime(),stop:r.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:t.suiteName},{name:"host",value:E_()},{name:"platform",value:"momentic"},{name:"attempts",value:r.attempts.toString()}],steps:[]};r.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${r.runId}`});for(let[s,l]of Object.entries(r.parameters))l!=null&&i.parameters.push({name:s,value:JSON.stringify(l)});r.results&&await C_(n,e,t.folder,i.steps,r.results);let a=`${o}-result.json`;Cc.writeFileSync(Ja.join(t.folder,a),JSON.stringify(i,void 0,2))}async function Ri(n,e,t,r){let o={name:dn(r),start:r.startedAt.getTime(),stop:r.finishedAt.getTime(),status:r.status==="SUCCESS"?"passed":r.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};r.beforeUrl&&o.labels?.push({name:"URL before step",value:r.beforeUrl}),r.afterUrl&&o.labels?.push({name:"URL after step",value:r.afterUrl});let i=await Rc(n,e,t,r.beforeScreenshot,r.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await Rc(n,e,t,r.afterScreenshot,r.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),r.message&&(o.statusDetails={message:r.message}),r.data){let s=`${Ju()}-attachment.json`,l=Ja.join(t,s);Cc.writeFileSync(l,JSON.stringify(r.data,null,2)),o.attachments.push({name:"Step output data",source:s,type:"text/plain"})}return o}async function C_(n,e,t,r,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{r.push(await Ri(n,e,t,i));break}case"CONDITIONAL":{let a=await Ri(n,e,t,i);a.steps=[],i.assertion&&a.steps.push(await Ri(n,e,t,i.assertion)),a.steps.push(...await Promise.all(i.results.map(s=>Ri(n,e,t,s)))),r.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await Ri(n,e,t,i);if(a.steps=await Promise.all(i.results.map(s=>Ri(n,e,t,s))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[s,l]of Object.entries(i.inputs))a.parameters.push({name:s,value:l})}r.push(a)}}}async function FT(n,e,t,r){for(let o of r.runs)await x_(n,e,{folder:t,suiteName:r.suiteName},o)}import UT from"junit-report-builder";import Ac from"path";function R_(n,e){let t=e??UT.testCase();if(t.name(n.test.name).className(n.test.name).file(Ac.relative(".",n.filePath)).property("id",n.test.id),n.test.labels&&(t.property("labels",n.test.labels.join(",")),n.test.labels.forEach(r=>{t.property("dd_tags[label]",r)})),n.baseUrl&&t.property("baseUrl",n.baseUrl),n.runId&&t.property("runUrl",`https://app.momentic.ai/runs/${n.runId}`),n.quarantined&&(t.property("quarantined","true"),n.quarantinedReason&&t.property("quarantinedReason",n.quarantinedReason)),n.status==="FAILED"){if(n.failureReason){let r=Ts[n.failureDetails?.classification?.reason||n.failureReason],o=n.failureDetails?.classification?.summary||ko[n.failureReason];n.runId&&(o+=` See details: https://app.momentic.ai/runs/${n.runId}`),t.failure(o,r)}n.failureDetails?.errorStack&&t.stacktrace(n.failureDetails.errorStack)}else n.status==="CANCELLED"&&t.skipped();t.time((n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime())/1e3).property("startedAt",n.lastAttemptStartedAt.toISOString()).property("finishedAt",n.finishedAt.toISOString()),t.property("attempts",n.attempts.toString()).property("dd_tags[attempts]",n.attempts.toString()),n.parameters.envName&&(t.property("environment",n.parameters.envName),t.property("dd_tags[environment]",n.parameters.envName)),n.parameters.urlOverride&&t.property("urlOverride",n.parameters.urlOverride);for(let r of["testInputs","customHeaders"]){let o=n.parameters[r];Object.keys(o??{}).length>0&&t.multilineProperty(r,JSON.stringify(o))}return Object.keys(n.outputs).length&&t.multilineProperty("testOutputs",JSON.stringify(n.outputs)),t}function A_(n,{suiteId:e,suiteName:t,startedAt:r,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:s,quarantinedTestReasons:l}){let c=n.testSuite().name(t);e&&c.property("id",e),c.timestamp(r).property("startedAt",r.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-r.getTime())/1e3);for(let d of i){let p=c.testCase();R_(d,p)}for(let d of a){let p=c.testCase();p.name(d.name).className(d.name).file(Ac.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&p.property("baseUrl",d.baseUrl),d.labels&&(p.property("labels",d.labels.join(",")),d.labels.forEach(u=>{p.property("dd_tags[label]",u)})),p.skipped()}for(let d of s){let p=c.testCase();p.name(d.name).className(d.name).file(Ac.relative(".",d.relativeFilePath)).property("id",d.id).property("quarantined","true");let u=l[d.id];u&&p.property("quarantinedReason",u),d.baseUrl&&p.property("baseUrl",d.baseUrl),d.labels&&(p.property("labels",d.labels.join(",")),d.labels.forEach(m=>{p.property("dd_tags[label]",m)})),p.skipped()}return c}function BT(n,e){let t=UT.newBuilder();A_(t,e),t.writeTo(Ac.join(n,`${e.suiteName}.xml`))}import I_ from"fs";import P_ from"path";function zT(n){return{title:dn(n),duration:n.finishedAt.getTime()-n.startedAt.getTime(),error:n.status==="FAILED"?{value:n.failureReason}:void 0,steps:n.results&&n.type!=="PRESET_ACTION"?n.results.map(zT):[]}}async function L_(n,e,t,r){if(r.results?.length){let o=await Rc(n,e,t,r.results[r.results.length-1].afterScreenshot,r.results[r.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function O_(n,e,t,r){return{status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"interrupted":"failed",duration:r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime(),error:r.status==="FAILED"&&r.failureReason?{value:r.failureDetails?.classification?.reason||r.failureReason,message:r.failureDetails?.classification?.summary||ko[r.failureReason]}:void 0,retry:r.attempts-1,steps:r.results?.map(zT)||[],startTime:r.lastAttemptStartedAt.toISOString(),attachments:await L_(n,e,t,r)}}async function M_(n,e,t,r){return{expectedStatus:"passed",status:r.status==="PASSED"?"expected":"unexpected",results:[await O_(n,e,t,r)]}}async function N_(n,e,t,r){return{tags:[],title:r.test.name,ok:r.status==="PASSED",tests:[await M_(n,e,t,r)],id:r.runId,file:r.filePath}}function Qu(n,e){return n.reduce((t,r)=>e(r)?t+1:t,0)}async function k_(n,e,t,r){return{suites:[{title:r.suiteName,file:r.projectConfigPath,specs:await Promise.all(r.runs.map(o=>N_(n,e,t,o)))}],errors:[],stats:{startTime:r.startedAt.toISOString(),duration:r.finishedAt.getTime()-r.startedAt.getTime(),expected:Qu(r.runs,o=>o.status==="PASSED"),unexpected:Qu(r.runs,o=>o.status!=="PASSED"),flaky:Qu(r.runs,o=>!!o.isFlake),skipped:0}}}async function HT(n,e,t,r){let o=await k_(n,e,t,r);I_.writeFileSync(P_.join(t,`${r.suiteName}.json`),JSON.stringify(o,null,2))}async function jT(n,e,t,r,o){switch(__(o)?F_(o).isDirectory()||(y.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(y.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),D_(o,{recursive:!0})),t){case"junit":BT(o,r);return;case"allure":case"allure-json":await FT(n,e,o,r);return;case"playwright-json":await HT(n,e,o,r);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import tD from"wait-on";import Zu from"fs";import{compact as U_,partition as Ic}from"lodash-es";import em from"path";import{cwd as B_}from"process";import z_ from"semver";async function Pc({tests:n,momenticFiles:e,project:t,yes:r,include:o,exclude:i,labels:a,logger:s}){let l=new Set;if(n&&n.length>0){let d=n.some(u=>Zu.existsSync(u)),p=B_();d?(p!==t.rootDir&&s.warn(`The current working directory ('${p}') 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.`),s.info(`Reading tests from the following local file paths:
|
|
3940
|
+
${e}`)}}async function OT({project:n,orgId:e,apiClient:t}){y.info("Pulling browser and AI configuration options from Cloud");let r=await Tc.init(e);n.config.browser={autoExpandIframes:r.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:r.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:r.isBooleanFlagEnabled("global_locator_redirect"),visualActions:r.isBooleanFlagEnabled("visual_actions"),...n.config.browser},n.config.advanced={fakerConstantSeed:r.isBooleanFlagEnabled("faker_constant_seed"),...n.config.advanced},n.config.ai={aiPageFiltering:r.isBooleanFlagEnabled("rag_v2"),agentConfig:await t.getAgentConfig(),...n.config.ai},y.info(`Updated ${n.configFilePath} to include V2 browser and AI configuration options`),y.info("Determining main Git branch"),n.config.gitMainBranch=b_(),ri(n.config,n.configFilePath),y.success("Migration complete!")}import{input as w_,search as v_}from"@inquirer/prompts";import T_ from"fuse.js";async function Ec({prompt:n,inputtedTest:e,testOptions:t}){if(e){let o=t.find(i=>i.name===e);if(!o)y.error(`${e} is not a valid test option.`);else return o.value}let r=new T_(t,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1});return v_({message:n,source:async o=>!o||o.length===0?t:r.search({name:o}).map(a=>a.item)})}async function xc({prompt:n,inputtedReason:e}){return e||w_({message:n})}async function MT({test:n,reason:e,apiClient:t,project:r,logger:o}){let i=de(r,y).tests,a=Object.values(i).map(d=>({value:d.id,name:d.name})),s=await Ec({prompt:"Select a test to quarantine.",inputtedTest:n,testOptions:a}),l=await xc({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await t.quarantineTest(s,l);let c=i[s].name;y.success(`Test ${c} has been successfully quarantined. Navigate to ${t.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${c}'.`)}async function NT({test:n,reason:e,apiClient:t,project:r,logger:o}){let i=de(r,y).tests,a=Object.values(i).map(m=>({value:m.id,name:m.name})),s=(await t.getQuarantinedTests()).quarantined,l=new Set(s.map(m=>m.testId)),c=a.filter(m=>l.has(m.value)),d=await Ec({prompt:"Select a test to unquarantine.",inputtedTest:n,testOptions:c}),p=await xc({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await t.unquarantineTest(d,p);let u=i[d].name;y.success(`Test ${u} has been successfully removed from quarantine.`)}function kT(n){return n?Ee(n):"Unknown suite"}async function _T({client:n,orgId:e,suitePaths:t,wait:r,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:s}=await n.queueSuiteRuns({paths:t,...i});X.info({orgId:e,suiteRunIds:a,runGroupIds:s,suitePaths:t},"Queued suites remotely"),y.dimmed(`Queued ${t.length} suites.`),r||process.exit(0);let l=Date.now();y.dimmed(`Waiting for ${t.length} suites to finish. You can view results upon completion at:`);for(let f of s)y.dimmed(`${it}- ${n.getAppUrl()}/run-groups/${f}`);let c=new Set,d=[],p=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(b=>b.status==="FAILED"&&(b.failureReason||b.finishedAt&&Date.now()-b.finishedAt.getTime()>30*1e3)||b.status==="PASSED"||b.status==="CANCELLED"),u=await bc({name:"suites",getResults:async()=>{let f=s.filter(w=>!d.some(T=>T.id===w)),S=await n.bulkGetRunGroupStatus(f),b=[];for(let w of S)p(w)?d.push(w):b.push(w);return[...d,...b]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(c.has(S.id)||(c.add(S.id),y.log(`${c.size}/${s.length} ${kT(S.suite?.name)}`)))}),f.every(p))}),m=n.getAppUrl(),g=Ci({results:u,startTime:l,onFailed:f=>{let S=kT(f.suite?.name),b=f.runs.filter(T=>T.status==="FAILED").length,w=f.runs.length;y.error(`${S} (${b}/${w} tests failed):`);for(let T of f.runs)if(T.status==="FAILED"){let C=T.testName||T.test?.name;y.error(` ${C?Ee(C):"Unknown test"} (${m}/runs/${T.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Ee(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(g.failed>0?1:0)}async function DT({tests:n,client:e,orgId:t,...r}){!r.yes&&!await St(`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(X.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),y.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;y.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,s=[],l=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",c=e.getAppUrl(),d=Date.now(),p=await bc({name:"runs",getResults:async()=>{let m=i.filter(f=>!s.some(S=>S.id===f)),h=await e.bulkGetRunStatus(m),g=[];for(let f of h)l(f)?s.push(f):g.push(f);return[...s,...g]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(h=>{if(h.status==="RUNNING"&&!a.has(h.id)){a.add(h.id);let g=h.testName||h.test?.name;g&&y.log(`${a.size}/${o.length} ${Ee(g)}`)}}),m.every(l))}),u=Ci({results:p,startTime:d,onFailed:m=>{let h=m.testName||m.test?.name;wc(m,h?Ee(h):"Unknown test")},getDisplayLine:m=>{let h=m.testName||m.test?.name,g=` ${h?Ee(h):"Unknown test"}`;return m.id&&(g+=` (${c}/runs/${m.id})`),g},entity:"test"});process.exit(u.failed>0?1:0)}import Pi,{supportsColor as Q_}from"chalk";import{randomUUID as Z_}from"crypto";import eD from"fs";import{existsSync as __,mkdirSync as D_,statSync as F_}from"fs";import{randomUUID as Ju}from"crypto";import Cc from"fs";import{hostname as E_}from"os";import Ja from"path";async function Rc(n,e,t,r,o){if(r){let i=Ja.extname(r),a=`${Ju()}-screenshot${i}`,s=Ja.join(t,a),c=await(await fetch(r)).arrayBuffer();return Cc.writeFileSync(s,Buffer.from(c)),a}if(o){let i=await e.getScreenshot(n,o);if(i){let a=`${o}-screenshot.jpeg`,s=Ja.join(t,a);return Cc.writeFileSync(s,i),a}}}async function x_(n,e,t,r){let o=r.runId??Ju(),i={uuid:o,historyId:o,testCaseId:r.test.id,fullName:r.test.name,name:Ee(r.test.name),status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"skipped":"failed",start:r.lastAttemptStartedAt.getTime(),stop:r.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:t.suiteName},{name:"host",value:E_()},{name:"platform",value:"momentic"},{name:"attempts",value:r.attempts.toString()}],steps:[]};r.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${r.runId}`});for(let[s,l]of Object.entries(r.parameters))l!=null&&i.parameters.push({name:s,value:JSON.stringify(l)});r.results&&await C_(n,e,t.folder,i.steps,r.results);let a=`${o}-result.json`;Cc.writeFileSync(Ja.join(t.folder,a),JSON.stringify(i,void 0,2))}async function Ri(n,e,t,r){let o={name:dn(r),start:r.startedAt.getTime(),stop:r.finishedAt.getTime(),status:r.status==="SUCCESS"?"passed":r.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};r.beforeUrl&&o.labels?.push({name:"URL before step",value:r.beforeUrl}),r.afterUrl&&o.labels?.push({name:"URL after step",value:r.afterUrl});let i=await Rc(n,e,t,r.beforeScreenshot,r.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await Rc(n,e,t,r.afterScreenshot,r.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),r.message&&(o.statusDetails={message:r.message}),r.data){let s=`${Ju()}-attachment.json`,l=Ja.join(t,s);Cc.writeFileSync(l,JSON.stringify(r.data,null,2)),o.attachments.push({name:"Step output data",source:s,type:"text/plain"})}return o}async function C_(n,e,t,r,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{r.push(await Ri(n,e,t,i));break}case"CONDITIONAL":{let a=await Ri(n,e,t,i);a.steps=[],i.assertion&&a.steps.push(await Ri(n,e,t,i.assertion)),a.steps.push(...await Promise.all(i.results.map(s=>Ri(n,e,t,s)))),r.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await Ri(n,e,t,i);if(a.steps=await Promise.all(i.results.map(s=>Ri(n,e,t,s))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[s,l]of Object.entries(i.inputs))a.parameters.push({name:s,value:l})}r.push(a)}}}async function FT(n,e,t,r){for(let o of r.runs)await x_(n,e,{folder:t,suiteName:r.suiteName},o)}import UT from"junit-report-builder";import Ac from"path";function R_(n,e){let t=e??UT.testCase();if(t.name(n.test.name).className(n.test.name).file(Ac.relative(".",n.filePath)).property("id",n.test.id).property("dd_tags[id]",n.test.id),n.test.labels&&(t.property("labels",n.test.labels.join(",")),n.test.labels.forEach(r=>{t.property("dd_tags[label]",r)})),n.baseUrl&&(t.property("base_url",n.baseUrl),t.property("dd_tags[base_url]",n.baseUrl)),n.runId&&(t.property("run_url",`https://app.momentic.ai/runs/${n.runId}`),t.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${n.runId}`)),n.quarantined&&(t.property("quarantined","true"),t.property("dd_tags[quarantined]","true"),n.quarantinedReason&&(t.property("quarantined_reason",n.quarantinedReason),t.property("dd_tags[quarantined_reason]",n.quarantinedReason))),n.status==="FAILED"){if(n.failureReason){let r=Ts[n.failureDetails?.classification?.reason||n.failureReason],o=n.failureDetails?.classification?.summary||ko[n.failureReason];n.runId&&(o+=` See details: https://app.momentic.ai/runs/${n.runId}`),t.failure(o,r)}n.failureDetails?.errorStack&&t.stacktrace(n.failureDetails.errorStack)}else n.status==="CANCELLED"&&t.skipped();return t.time((n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime())/1e3).property("started_at",n.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",n.lastAttemptStartedAt.toISOString()).property("finished_at",n.finishedAt.toISOString()).property("dd_tags[finished_at]",n.finishedAt.toISOString()),t.property("attempts",n.attempts.toString()).property("dd_tags[attempts]",n.attempts.toString()),n.parameters.envName&&(t.property("environment",n.parameters.envName),t.property("dd_tags[environment]",n.parameters.envName)),n.parameters.urlOverride&&t.property("url_override",n.parameters.urlOverride),t}function A_(n,{suiteId:e,suiteName:t,startedAt:r,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:s,quarantinedTestReasons:l}){let c=n.testSuite().name(t);e&&c.property("id",e),c.timestamp(r).property("startedAt",r.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-r.getTime())/1e3);for(let d of i){let p=c.testCase();R_(d,p)}for(let d of a){let p=c.testCase();p.name(d.name).className(d.name).file(Ac.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&p.property("baseUrl",d.baseUrl),d.labels&&(p.property("labels",d.labels.join(",")),d.labels.forEach(u=>{p.property("dd_tags[label]",u)})),p.skipped()}for(let d of s){let p=c.testCase();p.name(d.name).className(d.name).file(Ac.relative(".",d.relativeFilePath)).property("id",d.id).property("quarantined","true");let u=l[d.id];u&&p.property("quarantinedReason",u),d.baseUrl&&p.property("baseUrl",d.baseUrl),d.labels&&(p.property("labels",d.labels.join(",")),d.labels.forEach(m=>{p.property("dd_tags[label]",m)})),p.skipped()}return c}function BT(n,e){let t=UT.newBuilder();A_(t,e),t.writeTo(Ac.join(n,`${e.suiteName}.xml`))}import I_ from"fs";import P_ from"path";function zT(n){return{title:dn(n),duration:n.finishedAt.getTime()-n.startedAt.getTime(),error:n.status==="FAILED"?{value:n.failureReason}:void 0,steps:n.results&&n.type!=="PRESET_ACTION"?n.results.map(zT):[]}}async function L_(n,e,t,r){if(r.results?.length){let o=await Rc(n,e,t,r.results[r.results.length-1].afterScreenshot,r.results[r.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function O_(n,e,t,r){return{status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"interrupted":"failed",duration:r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime(),error:r.status==="FAILED"&&r.failureReason?{value:r.failureDetails?.classification?.reason||r.failureReason,message:r.failureDetails?.classification?.summary||ko[r.failureReason]}:void 0,retry:r.attempts-1,steps:r.results?.map(zT)||[],startTime:r.lastAttemptStartedAt.toISOString(),attachments:await L_(n,e,t,r)}}async function M_(n,e,t,r){return{expectedStatus:"passed",status:r.status==="PASSED"?"expected":"unexpected",results:[await O_(n,e,t,r)]}}async function N_(n,e,t,r){return{tags:[],title:r.test.name,ok:r.status==="PASSED",tests:[await M_(n,e,t,r)],id:r.runId,file:r.filePath}}function Qu(n,e){return n.reduce((t,r)=>e(r)?t+1:t,0)}async function k_(n,e,t,r){return{suites:[{title:r.suiteName,file:r.projectConfigPath,specs:await Promise.all(r.runs.map(o=>N_(n,e,t,o)))}],errors:[],stats:{startTime:r.startedAt.toISOString(),duration:r.finishedAt.getTime()-r.startedAt.getTime(),expected:Qu(r.runs,o=>o.status==="PASSED"),unexpected:Qu(r.runs,o=>o.status!=="PASSED"),flaky:Qu(r.runs,o=>!!o.isFlake),skipped:0}}}async function HT(n,e,t,r){let o=await k_(n,e,t,r);I_.writeFileSync(P_.join(t,`${r.suiteName}.json`),JSON.stringify(o,null,2))}async function jT(n,e,t,r,o){switch(__(o)?F_(o).isDirectory()||(y.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(y.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),D_(o,{recursive:!0})),t){case"junit":BT(o,r);return;case"allure":case"allure-json":await FT(n,e,o,r);return;case"playwright-json":await HT(n,e,o,r);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import tD from"wait-on";import Zu from"fs";import{compact as U_,partition as Ic}from"lodash-es";import em from"path";import{cwd as B_}from"process";import z_ from"semver";async function Pc({tests:n,momenticFiles:e,project:t,yes:r,include:o,exclude:i,labels:a,logger:s}){let l=new Set;if(n&&n.length>0){let d=n.some(u=>Zu.existsSync(u)),p=B_();d?(p!==t.rootDir&&s.warn(`The current working directory ('${p}') 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.`),s.info(`Reading tests from the following local file paths:
|
|
3941
3941
|
${n.map(u=>`${it}- ${u}`).join(`
|
|
3942
3942
|
`)}
|
|
3943
3943
|
`),n.forEach(u=>{if(!Zu.existsSync(u))throw new Error(`Path '${u}' does not exist.`);let m,h;try{m=Zu.statSync(u),h=m.isDirectory()}catch(f){s.warn({err:f},`Skipping path ${u} because it cannot be read`);return}let g=em.resolve(u);Object.values(e.tests).filter(f=>h?f.fullFilePath.startsWith(g):f.fullFilePath===g).forEach(f=>{l.add(f.fullFilePath)})})):(s.info(`Reading all tests from the project and running those matching the following substring filters:
|
|
@@ -3946,4 +3946,4 @@ ${n.map(u=>`${it}- ${u}`).join(`
|
|
|
3946
3946
|
`),y.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),Dc.existsSync(ni)&&(y.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:n.name??await qv("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:wp};ri(t,ni),y.success(`Initialized Momentic project file at ${_c.resolve(ni)}`)});yt.command("app").addOption(yn).addOption(bn).addOption(Rr).addOption(Bu).addOption(eT).addOption(Ut).addOption(Hu).addOption(ju).action(async n=>{let{apiKey:e,port:t,yes:r,server:o,pixelRatio:i,disableCache:a,saveCache:s}=n,l=rt({configFilePath:n.config,nameFilter:void 0}),{errors:c}=await vc({project:l,fix:!1});c>0&&(y.error(`Found ${c} errors`),y.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let d=new Xe({baseUrl:o,apiKey:e,logger:X});await Vu({client:d,skipPrompts:r});let p=pD(import.meta.url),u=_c.dirname(p),m=_c.resolve(u,"..","static"),h=_c.resolve(u,"..","assets"),g=i??Lu();Ou(g),await Bv({momenticServerUrl:o,apiKey:e,serverPort:t,appPort:t,staticDir:m,assetsDir:h,devicePixelRatio:g,version:zn,noCache:a,alwaysSaveCache:s,initialProject:l});let f=`http://localhost:${t}`;await dD(f)});var dE=yt.command("queue").description("Queue tests or suites to run on Momentic Cloud");dE.command("suites").description("Run one or more suites on Momentic Cloud").addOption(yn).addOption(bn).addOption(ku).addOption(_u).addOption(Rr).addArgument(cT).addOption(Sc).addOption(fc).addOption(gc).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:a,urlOverride:s}=e,l=hc(e.customHeaders),c=new Xe({baseUrl:r,apiKey:t,logger:X});(!n||!Array.isArray(n)||!n.length)&&(y.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await _T({client:c,orgId:d,wait:o,suitePaths:n,waitTimeout:i,env:a,urlOverride:s,customHeaders:l})});dE.command("tests").description("Run one or more tests on Momentic Cloud").addOption(yn).addOption(bn).addOption(Rr).addOption(gc).addOption(zu).addOption(Sc).addOption(fc).addOption(new Mt("--all","Run all tests.").default(!1)).addOption(ku).addOption(_u).addArgument(sT).action(async(n,e)=>{let{all:t,apiKey:r,env:o,server:i,inputCsv:a,urlOverride:s,wait:l,waitTimeout:c,yes:d}=e,p=hc(e.customHeaders);for(let g of n)(g.endsWith(".yaml")||Dc.existsSync(g))&&y.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let u=new Xe({baseUrl:i,apiKey:r,logger:X}),{orgId:m}=await u.getAuthInfo(),h;a&&(h=await Mu(a)),await DT({client:u,orgId:m,tests:n,all:t,customHeaders:p,env:o,urlOverride:s,wait:l,waitTimeout:c,testInputMatrix:h,yes:d}),process.exit(0)});var mD=yt.command("list").description("List test paths");mD.addOption(Ut).addOption(xi).addOption(Fu).addOption(Uu).addOption(new Mt("--labels <labels...>","Only run tests with the specified label(s).")).addArgument($u).action(async(n,e)=>{let t=rt({configFilePath:e.config,nameFilter:e.filter}),r=de(t,y),o=await Pc({tests:n,momenticFiles:r,yes:!0,project:t,include:e.include,exclude:e.exclude,labels:e.labels,logger:new sa(2,{})});y.info(o.map(i=>i.relativeFilePath).join(`
|
|
3947
3947
|
`)),process.exit(0)});var hD=yt.command("run").alias("test").description("Run tests on the local machine");hD.addOption(yn).addOption(bn).addOption(Ut).addOption(xi).addOption(Rr).addOption(gc).addOption(zu).addOption(Hu).addOption(ju).addOption(oT).addOption(iT).addOption(aT).addOption(fc).addOption(Sc).addOption(Bu).addOption(new Mt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Mt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Mt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(rr)).addOption(new Mt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(rr)).addOption(new Mt("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.").argParser(rr)).addOption(new Mt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Mt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(Jv).addOption(Qv).addOption(Du).addOption(Zv).addOption(nT).addOption(tT).addOption(Fu).addOption(Uu).addArgument($u).action(async(n,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let t=hc(e.customHeaders),r=rt({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??r.config.parallel??1;lE().length<o*2&&y.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${lE().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),y.debug({projectName:r.config.name},"Identified project config");let{errors:i}=await vc({project:r,fix:!1});i>0&&(y.error(`Found ${i} errors`),y.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let a=new Xe({baseUrl:e.server,apiKey:e.apiKey,logger:X});y.debug("Checking API key and dependencies");let{orgId:s,userId:l}=await Vu({client:a,skipPrompts:e.yes});y.debug("API key check and browser installation complete");let c=new Ll(a),d=new Vn,p=e.outputDir??r.config.outputDir,u=e.reporterDir??r.config.reporterDir,m=lD(),h=X.child({runGroupId:m,orgId:s,userId:l,cliVersion:zn,trigger:"CLI"}),g=await si(X,a,r);h.info(g,"Got local git metadata");let f=new ai(r.config),S;e.inputCsv&&(S=await Mu(e.inputCsv));let b=e.pixelRatio??Lu();Ou(b);try{(await oE({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:b,tests:n,project:r,client:a,debugDataStorage:d,billingReporter:c,flagStore:f,outputDir:p,uploadResults:e.uploadResults,reporterDir:u,customHeaders:t,envName:e.env,orgId:s,testInputMatrix:S,logger:h,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:g,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:m})).failed>0?process.exit(1):process.exit(0)}catch(w){y.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),y.error(w),process.exit(1)}});var gD=yt.command("apply").description("Apply an operation to local resources");gD.command("patch").addOption(yn).addOption(bn).addOption(Ut).addOption(xi).addOption(Rr).addOption(new Mt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Mt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async n=>{let{apiKey:e,server:t,config:r,yes:o}=n,i=rt({configFilePath:r}),a=X,s=new Xe({baseUrl:t,apiKey:e,logger:a}),l=de(i,y),c=l.tests[n.to]??Object.values(l.tests).find(p=>Ee(p.name)===n.to.trim());c||(y.error(`No test matching '${n.to}' could be found in the current project.`),process.exit(1));let d=await s.fetchTestFragment(n.from);await Kv({client:s,test:c,fragment:d,yes:o,entities:l,logger:X}),process.exit(0)});var pE=yt.command("results").description("Merge and upload test results.");pE.command("merge").description("Merge test results files.").addOption(Du).addArgument(dT).action(async(n,e)=>{let{outputDir:t}=e;t||(y.error("Output directory is required."),process.exit(1)),Dc.existsSync(n)||(y.warn("Results path does not exist, skipping merge."),process.exit(0)),Dc.existsSync(t)&&y.warn(`Output directory ${t} already exists, removing before merging...`),sE(X,t,n)});pE.command("upload").description("Upload test results to Momentic cloud.").addOption(yn).addOption(bn).addArgument(pT).action(async(n,e)=>{let{apiKey:t,server:r}=e,o=X,i=new Xe({baseUrl:r,apiKey:t,logger:o});await kc({consoleLogger:y,resultsPath:n,client:i}),process.exit(0)});var uE=yt.command("quarantine").description("Manage test quarantines");uE.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(yn).addOption(bn).addOption(Ut).addOption(xi).addOption(Gu).addArgument(Wu).action(async(n,e)=>{let{apiKey:t,server:r,config:o,reason:i}=e,a=X,s=rt({configFilePath:o}),l=new Xe({baseUrl:r,apiKey:t,logger:a});await MT({test:n,reason:i,apiClient:l,project:s,logger:a})});uE.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(yn).addOption(bn).addOption(Ut).addOption(xi).addOption(Gu).addArgument(Wu).action(async(n,e)=>{let{apiKey:t,server:r,config:o,reason:i}=e,a=X,s=rt({configFilePath:o}),l=new Xe({baseUrl:r,apiKey:t,logger:a});await NT({test:n,reason:i,apiClient:l,project:s,logger:a})});async function fD(){am("Main program started"),await Gv(X),am("CLI version check complete");try{await yt.parseAsync(process.argv)}catch(n){let e={};try{e.playwrightVersion=sD("npx playwright --version").toString()}catch(t){X.error({err:t},"Error fetching debug information")}X.error({err:n,debugInfo:e},"Uncaught error in CLI"),X.flush(),Ni(n,e),y.error(n),process.exit(1)}}cD.setMaxListeners(50);process.on("warning",n=>{X.warn({err:n},`Node warning received on CLI: ${n.message}`)});am("CLI parsing setup complete");fD();
|
|
3948
3948
|
//# sourceMappingURL=cli.js.map
|
|
3949
|
-
//# debugId=
|
|
3949
|
+
//# debugId=20a6e42e-fc62-5145-882a-a2ccb782ee62
|