momentic 1.0.21 → 1.0.22
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 +2 -2
- package/package.json +2 -2
package/bin/cli.js
CHANGED
|
@@ -1978,7 +1978,7 @@ Available pages:${JSON.stringify(n.map(s=>s.url))}`);if(!rn(o.url,this.logger)){
|
|
|
1978
1978
|
`)}catch(s){throw new Error(`Could not read test file ${t}: ${s}`)}let o;try{o=mo.parse(n)}catch(s){throw new Error(`Could not parse test file ${t} as YAML: ${s}`)}return Ne.parse(o)}async function ni(r,e,t){let n=t.project.rootDir,o;try{o=Xt.readFileSync(r,"utf-8")}catch(l){throw e.error({err:l,projectRoot:n},l.message),new Error(l.message)}let s=mo.parse(o);if(!s.steps||!Array.isArray(s.steps))throw new Error(`Test ${r} is missing steps`);let i;try{i=Ne.parse(s)}catch(l){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${l}`)}let{resolvedTest:a}=await Nu({rawSteps:s.steps,metadata:i,logger:e,callbacks:{onFetchModule:async({id:l,logger:c})=>{let u=t.modules[l]?.fullFilePath;if(u)return ti(u,c)}}});return a}import qT from"@dotenvx/dotenvx";import KT from"fs";import Ep from"path";function Cp(r,e){return(r.config.environments??[]).map(t=>ho(t.name,r,e))}function YT(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),s=process.env[n];return t.includes(":-")?s&&s!==""?s:o||"":t.includes("-")?s!==void 0?s:o||"":s||""}):r}function ho(r,e,t){let n=(e.config.environments??[]).find(i=>i.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={[oe]:n.baseUrl};if(n.envVariables){let i={};for(let[a,l]of Object.entries(n.envVariables))if(typeof l=="string"){let c=YT(l);c&&(i[a]=c)}else{let c=l.fromFile,u;try{u=KT.readFileSync(Ep.resolve(e.rootDir,c),"utf-8")}catch(d){throw new Error(`Failed to read environment variable '${a}' from file '${c}': ${d}`)}if(l.json)try{i[a]=JSON.parse(u)}catch(d){throw new Error(`Failed to parse environment variable '${a}' from file '${c}' as JSON: ${d}`)}else i[a]=u}t.debug(i,"Set environment variables with interpolation from project configuration"),Object.assign(o,i)}if(n.envFile){let i={},a=qT.config({path:Ep.resolve(e.rootDir,n.envFile),processEnv:i,logLevel:"error",quiet:!0});if(a.error)throw new Error(`Failed to load .env file: ${a.error.message}`);t.debug(i,"Set environment variables from .env file"),Object.assign(o,i)}return n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o,browser:n.browser}}import{existsSync as xC,readFileSync as RC,readdirSync as IC,writeFileSync as PC}from"fs";var Hp=Hf(Dp(),1);var go=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var nE={"[: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]},yo=r=>r.replace(/[[\]\\-]/g,"\\$&"),oE=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Fp=r=>r.join(""),Up=(r,e)=>{let t=e;if(r.charAt(t)!=="[")throw new Error("not in a brace expression");let n=[],o=[],s=t+1,i=!1,a=!1,l=!1,c=!1,u=t,d="";e:for(;s<r.length;){let f=r.charAt(s);if((f==="!"||f==="^")&&s===t+1){c=!0,s++;continue}if(f==="]"&&i&&!l){u=s+1;break}if(i=!0,f==="\\"&&!l){l=!0,s++;continue}if(f==="["&&!l){for(let[g,[y,S,w]]of Object.entries(nE))if(r.startsWith(g,s)){if(d)return["$.",!1,r.length-t,!0];s+=g.length,w?o.push(y):n.push(y),a=a||S;continue e}}if(l=!1,d){f>d?n.push(yo(d)+"-"+yo(f)):f===d&&n.push(yo(f)),d="",s++;continue}if(r.startsWith("-]",s+1)){n.push(yo(f+"-")),s+=2;continue}if(r.startsWith("-",s+1)){d=f,s+=2;continue}n.push(yo(f)),s++}if(u<s)return["",!1,0,!1];if(!n.length&&!o.length)return["$.",!1,r.length-t,!0];if(o.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let f=n[0].length===2?n[0].slice(-1):n[0];return[oE(f),!1,u-t,!1]}let m="["+(c?"^":"")+Fp(n)+"]",p="["+(c?"":"^")+Fp(o)+"]";return[n.length&&o.length?"("+m+"|"+p+")":n.length?m:p,a,u-t,!0]};var bt=(r,{windowsPathsNoEscape:e=!1}={})=>e?r.replace(/\[([^\/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var sE=new Set(["!","?","+","*","@"]),$p=r=>sE.has(r),iE="(?!(?:^|/)\\.\\.?(?:$|/))",oi="(?!\\.)",aE=new Set(["[","."]),lE=new Set(["..","."]),cE=new Set("().*{}+?[]^$\\!"),dE=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ul="[^/]",Bp=ul+"*?",zp=ul+"+?",pn=class r{type;#e;#t;#s=!1;#n=[];#i;#b;#c;#u=!1;#a;#l;#o=!1;constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#u&&this.#c.push(this),this.#b=this.#i?this.#i.#n.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#n)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.#n.map(e=>String(e)).join("|")+")":this.#l=this.#n.map(e=>String(e)).join("")}#g(){if(this!==this.#e)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,n=t.#i;for(;n;){for(let o=t.#b+1;!n.type&&o<n.#n.length;o++)for(let s of e.#n){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(n.#n[o])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof r&&t.#i===this))throw new Error("invalid part: "+t);this.#n.push(t)}}toJSON(){let e=this.type===null?this.#n.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#n.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#u&&this.#i?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#b===0)return!0;let e=this.#i;for(let t=0;t<this.#b;t++){let n=e.#n[t];if(!(n instanceof r&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type==="!")return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#n.length:0;return this.#b===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new r(this.type,e);for(let n of this.#n)t.copyIn(n);return t}static#y(e,t,n,o){let s=!1,i=!1,a=-1,l=!1;if(t.type===null){let p=n,h="";for(;p<e.length;){let f=e.charAt(p++);if(s||f==="\\"){s=!s,h+=f;continue}if(i){p===a+1?(f==="^"||f==="!")&&(l=!0):f==="]"&&!(p===a+2&&l)&&(i=!1),h+=f;continue}else if(f==="["){i=!0,a=p,l=!1,h+=f;continue}if(!o.noext&&$p(f)&&e.charAt(p)==="("){t.push(h),h="";let g=new r(f,t);p=r.#y(e,g,p,o),t.push(g);continue}h+=f}return t.push(h),p}let c=n+1,u=new r(null,t),d=[],m="";for(;c<e.length;){let p=e.charAt(c++);if(s||p==="\\"){s=!s,m+=p;continue}if(i){c===a+1?(p==="^"||p==="!")&&(l=!0):p==="]"&&!(c===a+2&&l)&&(i=!1),m+=p;continue}else if(p==="["){i=!0,a=c,l=!1,m+=p;continue}if($p(p)&&e.charAt(c)==="("){u.push(m),m="";let h=new r(p,u);u.push(h),c=r.#y(e,h,c,o);continue}if(p==="|"){u.push(m),m="",d.push(u),u=new r(null,t);continue}if(p===")")return m===""&&t.#n.length===0&&(t.#o=!0),u.push(m),m="",t.push(...d,u),c;m+=p}return t.type=null,t.#t=void 0,t.#n=[e.substring(n-1)],c}static fromGlob(e,t={}){let n=new r(null,void 0,t);return r.#y(e,n,0,t),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,o,s]=this.toRegExpSource();if(!(o||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#a}toRegExpSource(e){let t=e??!!this.#a.dot;if(this.#e===this&&this.#g(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#n.map(p=>{let[h,f,g,y]=typeof p=="string"?r.#m(p,this.#t,l):p.toRegExpSource(e);return this.#t=this.#t||g,this.#s=this.#s||y,h}).join(""),u="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&lE.has(this.#n[0]))){let h=aE,f=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),g=!t&&!e&&h.has(c.charAt(0));u=f?iE:g?oi:""}let d="";return this.isEnd()&&this.#e.#u&&this.#i?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,bt(c),this.#t=!!this.#t,this.#s]}let n=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#p(t);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let l=this.toString();return this.#n=[l],this.type=null,this.#t=void 0,[l,bt(this.toString()),!1,!1]}let i=!n||e||t||!oi?"":this.#p(!0);i===s&&(i=""),i&&(s=`(?:${s})(?:${i})*?`);let a="";if(this.type==="!"&&this.#o)a=(this.isStart()&&!t?oi:"")+zp;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?oi:"")+Bp+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;a=o+s+l}return[a,bt(s),this.#t=!!this.#t,this.#s]}#p(e){return this.#n.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[n,o,s,i]=t.toRegExpSource(e);return this.#s=this.#s||i,n}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#m(e,t,n=!1){let o=!1,s="",i=!1;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(o){o=!1,s+=(cE.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?s+="\\\\":o=!0;continue}if(l==="["){let[c,u,d,m]=Up(e,a);if(d){s+=c,i=i||u,a+=d-1,t=t||m;continue}}if(l==="*"){n&&e==="*"?s+=zp:s+=Bp,t=!0;continue}if(l==="?"){s+=ul,t=!0;continue}s+=dE(l)}return[s,bt(e),!!t,i]}};var hn=(r,{windowsPathsNoEscape:e=!1}={})=>e?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var We=(r,e,t={})=>(go(e),!t.nocomment&&e.charAt(0)==="#"?!1:new Qe(e,t).match(r)),uE=/^\*+([^+@!?\*\[\(]*)$/,mE=r=>e=>!e.startsWith(".")&&e.endsWith(r),pE=r=>e=>e.endsWith(r),hE=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),fE=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),gE=/^\*+\.\*+$/,yE=r=>!r.startsWith(".")&&r.includes("."),SE=r=>r!=="."&&r!==".."&&r.includes("."),wE=/^\.\*+$/,bE=r=>r!=="."&&r!==".."&&r.startsWith("."),TE=/^\*+$/,EE=r=>r.length!==0&&!r.startsWith("."),CE=r=>r.length!==0&&r!=="."&&r!=="..",vE=/^\?+([^+@!?\*\[\(]*)?$/,AE=([r,e=""])=>{let t=Gp([r]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},xE=([r,e=""])=>{let t=Vp([r]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},RE=([r,e=""])=>{let t=Vp([r]);return e?n=>t(n)&&n.endsWith(e):t},IE=([r,e=""])=>{let t=Gp([r]);return e?n=>t(n)&&n.endsWith(e):t},Gp=([r])=>{let e=r.length;return t=>t.length===e&&!t.startsWith(".")},Vp=([r])=>{let e=r.length;return t=>t.length===e&&t!=="."&&t!==".."},qp=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Wp={win32:{sep:"\\"},posix:{sep:"/"}},PE=qp==="win32"?Wp.win32.sep:Wp.posix.sep;We.sep=PE;var ve=Symbol("globstar **");We.GLOBSTAR=ve;var OE="[^/]",LE=OE+"*?",ME="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",NE="(?:(?!(?:\\/|^)\\.).)*?",_E=(r,e={})=>t=>We(t,r,e);We.filter=_E;var ut=(r,e={})=>Object.assign({},r,e),kE=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return We;let e=We;return Object.assign((n,o,s={})=>e(n,o,ut(r,s)),{Minimatch:class extends e.Minimatch{constructor(o,s={}){super(o,ut(r,s))}static defaults(o){return e.defaults(ut(r,o)).Minimatch}},AST:class extends e.AST{constructor(o,s,i={}){super(o,s,ut(r,i))}static fromGlob(o,s={}){return e.AST.fromGlob(o,ut(r,s))}},unescape:(n,o={})=>e.unescape(n,ut(r,o)),escape:(n,o={})=>e.escape(n,ut(r,o)),filter:(n,o={})=>e.filter(n,ut(r,o)),defaults:n=>e.defaults(ut(r,n)),makeRe:(n,o={})=>e.makeRe(n,ut(r,o)),braceExpand:(n,o={})=>e.braceExpand(n,ut(r,o)),match:(n,o,s={})=>e.match(n,o,ut(r,s)),sep:e.sep,GLOBSTAR:ve})};We.defaults=kE;var Kp=(r,e={})=>(go(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0,Hp.default)(r));We.braceExpand=Kp;var DE=(r,e={})=>new Qe(r,e).makeRe();We.makeRe=DE;var FE=(r,e,t={})=>{let n=new Qe(e,t);return r=r.filter(o=>n.match(o)),n.options.nonull&&!r.length&&r.push(e),r};We.match=FE;var jp=/[?*]|[+@!]\(.*?\)|\[|\]/,UE=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Qe=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){go(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||qp,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=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let o=this.globParts.map((s,i,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=s[0]===""&&s[1]===""&&(s[2]==="?"||!jp.test(s[2]))&&!jp.test(s[3]),c=/^[a-z]:/i.test(s[0]);if(l)return[...s.slice(0,4),...s.slice(4).map(u=>this.parse(u))];if(c)return[s[0],...s.slice(1).map(u=>this.parse(u))]}return s.map(l=>this.parse(l))});if(this.debug(this.pattern,o),this.set=o.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let i=this.set[s];i[0]===""&&i[1]===""&&this.globParts[s][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let o=0;o<e[n].length;o++)e[n][o]==="**"&&(e[n][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 n=-1;for(;(n=t.indexOf("**",n+1))!==-1;){let o=n;for(;t[o+1]==="**";)o++;o!==n&&t.splice(n,o-n)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((n,o)=>{let s=n[n.length-1];return o==="**"&&s==="**"?n:o===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(n.pop(),n):(n.push(o),n)},[]),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 s=e[o];o===1&&s===""&&e[0]===""||(s==="."||s==="")&&(t=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf("..",n+1))!==-1;){let o=e[n-1];o&&o!=="."&&o!==".."&&o!=="**"&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let o=-1;for(;(o=n.indexOf("**",o+1))!==-1;){let i=o;for(;n[i+1]==="**";)i++;i>o&&n.splice(o+1,i-o);let a=n[o+1],l=n[o+2],c=n[o+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=!0,n.splice(o,1);let u=n.slice(0);u[o]="**",e.push(u),o--}if(!this.preserveMultipleSlashes){for(let i=1;i<n.length-1;i++){let a=n[i];i===1&&a===""&&n[0]===""||(a==="."||a==="")&&(t=!0,n.splice(i,1),i--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(t=!0,n.pop())}let s=0;for(;(s=n.indexOf("..",s+1))!==-1;){let i=n[s-1];if(i&&i!=="."&&i!==".."&&i!=="**"){t=!0;let l=s===1&&n[s+1]==="**"?["."]:[];n.splice(s-1,2,...l),n.length===0&&n.push(""),s-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let o=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(o){e[t]=[],e[n]=o;break}}return e.filter(t=>t.length)}partsMatch(e,t,n=!1){let o=0,s=0,i=[],a="";for(;o<e.length&&s<t.length;)if(e[o]===t[s])i.push(a==="b"?t[s]:e[o]),o++,s++;else if(n&&e[o]==="**"&&t[s]===e[o+1])i.push(e[o]),o++;else if(n&&t[s]==="**"&&e[o]===t[s+1])i.push(t[s]),s++;else if(e[o]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(a==="b")return!1;a="a",i.push(e[o]),o++,s++}else if(t[s]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(a==="a")return!1;a="b",i.push(t[s]),o++,s++}else return!1;return e.length===t.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let o=this.options;if(this.isWindows){let f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),g=!f&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),y=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),S=!y&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),w=g?3:f?0:void 0,E=S?3:y?0:void 0;if(typeof w=="number"&&typeof E=="number"){let[C,A]=[e[w],t[E]];C.toLowerCase()===A.toLowerCase()&&(t[E]=C,E>w?t=t.slice(E):w>E&&(e=e.slice(w)))}}let{optimizationLevel:s=1}=this.options;s>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var i=0,a=0,l=e.length,c=t.length;i<l&&a<c;i++,a++){this.debug("matchOne loop");var u=t[a],d=e[i];if(this.debug(t,u,d),u===!1)return!1;if(u===ve){this.debug("GLOBSTAR",[t,u,d]);var m=i,p=a+1;if(p===c){for(this.debug("** at the end");i<l;i++)if(e[i]==="."||e[i]===".."||!o.dot&&e[i].charAt(0)===".")return!1;return!0}for(;m<l;){var h=e[m];if(this.debug(`
|
|
1979
1979
|
globstar while`,e,m,t,p,h),this.matchOne(e.slice(m),t.slice(p),n))return this.debug("globstar found match!",m,l,h),!0;if(h==="."||h===".."||!o.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,m,t,p);break}this.debug("globstar swallow a segment, and continue"),m++}return!!(n&&(this.debug(`
|
|
1980
1980
|
>>> no match, partial?`,e,m,t,p),m===l))}let f;if(typeof u=="string"?(f=d===u,this.debug("string match",u,d,f)):(f=u.test(d),this.debug("pattern match",u,d,f)),!f)return!1}if(i===l&&a===c)return!0;if(i===l)return n;if(a===c)return i===l-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return Kp(this.pattern,this.options)}parse(e){go(e);let t=this.options;if(e==="**")return ve;if(e==="")return"";let n,o=null;(n=e.match(TE))?o=t.dot?CE:EE:(n=e.match(uE))?o=(t.nocase?t.dot?fE:hE:t.dot?pE:mE)(n[1]):(n=e.match(vE))?o=(t.nocase?t.dot?xE:AE:t.dot?RE:IE)(n):(n=e.match(gE))?o=t.dot?SE:yE:(n=e.match(wE))&&(o=bE);let s=pn.fromGlob(e,this.options).toMMPattern();return o&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:o}),s}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,n=t.noglobstar?LE:t.dot?ME:NE,o=new Set(t.nocase?["i"]:[]),s=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let d of u.flags.split(""))o.add(d);return typeof u=="string"?UE(u):u===ve?ve:u._src});return c.forEach((u,d)=>{let m=c[d+1],p=c[d-1];u!==ve||p===ve||(p===void 0?m!==void 0&&m!==ve?c[d+1]="(?:\\/|"+n+"\\/)?"+m:c[d]=n:m===void 0?c[d-1]=p+"(?:\\/|"+n+")?":m!==ve&&(c[d-1]=p+"(?:\\/|\\/"+n+"\\/)"+m,c[d+1]=ve))}),c.filter(u=>u!==ve).join("/")}).join("|"),[i,a]=e.length>1?["(?:",")"]:["",""];s="^"+i+s+a+"$",this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...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 n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let i=o[o.length-1];if(!i)for(let a=o.length-2;!i&&a>=0;a--)i=o[a];for(let a=0;a<s.length;a++){let l=s[a],c=o;if(n.matchBase&&l.length===1&&(c=[i]),this.matchOne(c,l,t))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return We.defaults(e).Minimatch}};We.AST=pn;We.Minimatch=Qe;We.escape=hn;We.unescape=bt;import{fileURLToPath as gC}from"node:url";var fn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Xp=new Set,ml=typeof process=="object"&&process?process:{},Jp=(r,e,t,n)=>{typeof ml.emitWarning=="function"?ml.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},si=globalThis.AbortController,Yp=globalThis.AbortSignal;if(typeof si>"u"){Yp=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},si=class{constructor(){e()}signal=new Yp;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=ml.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,Jp("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 $E=r=>!Xp.has(r),iK=Symbol("type"),lr=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Zp=r=>lr(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?gn:null:null,gn=class extends Array{constructor(e){super(e),this.fill(0)}},pl=class r{heap;length;static#e=!1;static create(e){let t=Zp(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#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]}},So=class r{#e;#t;#s;#n;#i;#b;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#u;#a;#l;#o;#g;#y;#p;#m;#C;#f;#v;#A;#w;#T;#E;#h;static unsafeExposeInternals(e){return{starts:e.#A,ttls:e.#w,sizes:e.#v,keyMap:e.#a,keyList:e.#l,valList:e.#o,next:e.#g,prev:e.#y,get head(){return e.#p},get tail(){return e.#m},free:e.#C,isBackgroundFetch:t=>e.#d(t),backgroundFetch:(t,n,o,s)=>e.#U(t,n,o,s),moveToTail:t=>e.#B(t),indexes:t=>e.#R(t),rindexes:t=>e.#I(t),isStale:t=>e.#S(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#u}get size(){return this.#c}get fetchMethod(){return this.#i}get memoMethod(){return this.#b}get dispose(){return this.#s}get disposeAfter(){return this.#n}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:m,maxSize:p=0,maxEntrySize:h=0,sizeCalculation:f,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:C,ignoreFetchAbort:A}=e;if(t!==0&&!lr(t))throw new TypeError("max option must be a nonnegative integer");let I=t?Zp(t):Array;if(!I)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=p,this.maxEntrySize=h||this.#t,this.sizeCalculation=f,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#b=y,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#i=g,this.#E=!!g,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#g=new I(t),this.#y=new I(t),this.#p=0,this.#m=0,this.#C=pl.create(t),this.#c=0,this.#u=0,typeof c=="function"&&(this.#s=c),typeof u=="function"?(this.#n=u,this.#f=[]):(this.#n=void 0,this.#f=void 0),this.#T=!!this.#s,this.#h=!!this.#n,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!m,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!C,this.ignoreFetchAbort=!!A,this.maxEntrySize!==0){if(this.#t!==0&&!lr(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!lr(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#O()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=lr(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=n||0,this.ttl){if(!lr(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 O="LRU_CACHE_UNBOUNDED";$E(O)&&(Xp.add(O),Jp("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",O,r))}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#P(){let e=new gn(this.#e),t=new gn(this.#e);this.#w=e,this.#A=t,this.#M=(s,i,a=fn.now())=>{if(t[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#S(s)&&this.#L(this.#l[s],"expire")},i+1);l.unref&&l.unref()}},this.#x=s=>{t[s]=e[s]!==0?fn.now():0},this.#r=(s,i)=>{if(e[i]){let a=e[i],l=t[i];if(!a||!l)return;s.ttl=a,s.start=l,s.now=n||o();let c=s.now-l;s.remainingTTL=a-c}};let n=0,o=()=>{let s=fn.now();if(this.ttlResolution>0){n=s;let i=setTimeout(()=>n=0,this.ttlResolution);i.unref&&i.unref()}return s};this.getRemainingTTL=s=>{let i=this.#a.get(s);if(i===void 0)return 0;let a=e[i],l=t[i];if(!a||!l)return 1/0;let c=(n||o())-l;return a-c},this.#S=s=>{let i=t[s],a=e[s];return!!a&&!!i&&(n||o())-i>a}}#x=()=>{};#r=()=>{};#M=()=>{};#S=()=>!1;#O(){let e=new gn(this.#e);this.#u=0,this.#v=e,this.#N=t=>{this.#u-=e[t],e[t]=0},this.#k=(t,n,o,s)=>{if(this.#d(n))return 0;if(!lr(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(n,t),!lr(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.#_=(t,n,o)=>{if(e[t]=n,this.#t){let s=this.#t-e[t];for(;this.#u>s;)this.#F(!0)}this.#u+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#u)}}#N=e=>{};#_=(e,t,n)=>{};#k=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#D(t)||((e||!this.#S(t))&&(yield t),t===this.#p));)t=this.#y[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#p;!(!this.#D(t)||((e||!this.#S(t))&&(yield t),t===this.#m));)t=this.#g[t]}#D(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#R())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*rentries(){for(let e of this.#I())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*keys(){for(let e of this.#R()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*rkeys(){for(let e of this.#I()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*values(){for(let e of this.#R())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}*rvalues(){for(let e of this.#I())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#R()){let o=this.#o[n],s=this.#d(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#R()){let o=this.#o[n],s=this.#d(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(t,s,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#I()){let o=this.#o[n],s=this.#d(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(t,s,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#S(t)&&(this.#L(this.#l[t],"expire"),e=!0);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let n=this.#o[t],o=this.#d(n)?n.__staleWhileFetching:n;if(o===void 0)return;let s={value:o};if(this.#w&&this.#A){let i=this.#w[t],a=this.#A[t];if(i&&a){let l=i-(fn.now()-a);s.ttl=l,s.start=Date.now()}}return this.#v&&(s.size=this.#v[t]),s}dump(){let e=[];for(let t of this.#R({allowStale:!0})){let n=this.#l[t],o=this.#o[t],s=this.#d(o)?o.__staleWhileFetching:o;if(s===void 0||n===void 0)continue;let i={value:s};if(this.#w&&this.#A){i.ttl=this.#w[t];let a=fn.now()-this.#A[t];i.start=Math.floor(Date.now()-a)}this.#v&&(i.size=this.#v[t]),e.unshift([n,i])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=fn.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,u=this.#k(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#L(e,"set"),this;let d=this.#c===0?void 0:this.#a.get(e);if(d===void 0)d=this.#c===0?this.#m:this.#C.length!==0?this.#C.pop():this.#c===this.#e?this.#F(!1):this.#c,this.#l[d]=e,this.#o[d]=t,this.#a.set(e,d),this.#g[this.#m]=d,this.#y[d]=this.#m,this.#m=d,this.#c++,this.#_(d,u,l),l&&(l.set="add"),c=!1;else{this.#B(d);let m=this.#o[d];if(t!==m){if(this.#E&&this.#d(m)){m.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:p}=m;p!==void 0&&!i&&(this.#T&&this.#s?.(p,e,"set"),this.#h&&this.#f?.push([p,e,"set"]))}else i||(this.#T&&this.#s?.(m,e,"set"),this.#h&&this.#f?.push([m,e,"set"]));if(this.#N(d),this.#_(d,u,l),this.#o[d]=t,l){l.set="replace";let p=m&&this.#d(m)?m.__staleWhileFetching:m;p!==void 0&&(l.oldValue=p)}}else l&&(l.set="update")}if(o!==0&&!this.#w&&this.#P(),this.#w&&(c||this.#M(d,o,s),l&&this.#r(l,d)),!i&&this.#h&&this.#f){let m=this.#f,p;for(;p=m?.shift();)this.#n?.(...p)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#p];if(this.#F(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#f){let e=this.#f,t;for(;t=e?.shift();)this.#n?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],o=this.#o[t];return this.#E&&this.#d(o)?o.__abortController.abort(new Error("evicted")):(this.#T||this.#h)&&(this.#T&&this.#s?.(o,n,"evict"),this.#h&&this.#f?.push([o,n,"evict"])),this.#N(t),e&&(this.#l[t]=void 0,this.#o[t]=void 0,this.#C.push(t)),this.#c===1?(this.#p=this.#m=0,this.#C.length=0):this.#p=this.#g[t],this.#a.delete(n),this.#c--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,s=this.#a.get(e);if(s!==void 0){let i=this.#o[s];if(this.#d(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#S(s))o&&(o.has="stale",this.#r(o,s));else return n&&this.#x(s),o&&(o.has="hit",this.#r(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#a.get(e);if(o===void 0||!n&&this.#S(o))return;let s=this.#o[o];return this.#d(s)?s.__staleWhileFetching:s}#U(e,t,n,o){let s=t===void 0?void 0:this.#o[t];if(this.#d(s))return s;let i=new si,{signal:a}=n;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let l={signal:i.signal,options:n,context:o},c=(f,g=!1)=>{let{aborted:y}=i.signal,S=n.ignoreFetchAbort&&f!==void 0;if(n.status&&(y&&!g?(n.status.fetchAborted=!0,n.status.fetchError=i.signal.reason,S&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),y&&!S&&!g)return d(i.signal.reason);let w=p;return this.#o[t]===p&&(f===void 0?w.__staleWhileFetching?this.#o[t]=w.__staleWhileFetching:this.#L(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,f,l.options))),f},u=f=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=f),d(f)),d=f=>{let{aborted:g}=i.signal,y=g&&n.allowStaleOnFetchAbort,S=y||n.allowStaleOnFetchRejection,w=S||n.noDeleteOnFetchRejection,E=p;if(this.#o[t]===p&&(!w||E.__staleWhileFetching===void 0?this.#L(e,"fetch"):y||(this.#o[t]=E.__staleWhileFetching)),S)return n.status&&E.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw f},m=(f,g)=>{let y=this.#i?.(e,s,l);y&&y instanceof Promise&&y.then(S=>f(S===void 0?void 0:S),g),i.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(f(void 0),n.allowStaleOnFetchAbort&&(f=S=>c(S,!0)))})};n.status&&(n.status.fetchDispatched=!0);let p=new Promise(m).then(c,u),h=Object.assign(p,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#a.get(e)):this.#o[t]=h,h}#d(e){if(!this.#E)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof si}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:f,forceRefresh:g=!1,status:y,signal:S}=t;if(!this.#E)return y&&(y.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:y});let w={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:h,ignoreFetchAbort:p,status:y,signal:S},E=this.#a.get(e);if(E===void 0){y&&(y.fetch="miss");let C=this.#U(e,E,w,f);return C.__returned=C}else{let C=this.#o[E];if(this.#d(C)){let j=n&&C.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",j&&(y.returnedStale=!0)),j?C.__staleWhileFetching:C.__returned=C}let A=this.#S(E);if(!g&&!A)return y&&(y.fetch="hit"),this.#B(E),o&&this.#x(E),y&&this.#r(y,E),C;let I=this.#U(e,E,w,f),x=I.__staleWhileFetching!==void 0&&n;return y&&(y.fetch=A?"stale":"refresh",x&&A&&(y.returnedStale=!0)),x?I.__staleWhileFetching:I.__returned=I}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#b;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=t,a=this.get(e,i);if(!s&&a!==void 0)return a;let l=n(e,a,{options:i,context:o});return this.set(e,l,i),l}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#o[a],c=this.#d(l);return i&&this.#r(i,a),this.#S(a)?(i&&(i.get="stale"),c?(i&&n&&l.__staleWhileFetching!==void 0&&(i.returnedStale=!0),n?l.__staleWhileFetching:void 0):(s||this.#L(e,"expire"),i&&n&&(i.returnedStale=!0),n?l:void 0)):(i&&(i.get="hit"),c?l.__staleWhileFetching:(this.#B(a),o&&this.#x(a),l))}else i&&(i.get="miss")}#$(e,t){this.#y[t]=e,this.#g[e]=t}#B(e){e!==this.#m&&(e===this.#p?this.#p=this.#g[e]:this.#$(this.#y[e],this.#g[e]),this.#$(this.#m,e),this.#m=e)}delete(e){return this.#L(e,"delete")}#L(e,t){let n=!1;if(this.#c!==0){let o=this.#a.get(e);if(o!==void 0)if(n=!0,this.#c===1)this.#z(t);else{this.#N(o);let s=this.#o[o];if(this.#d(s)?s.__abortController.abort(new Error("deleted")):(this.#T||this.#h)&&(this.#T&&this.#s?.(s,e,t),this.#h&&this.#f?.push([s,e,t])),this.#a.delete(e),this.#l[o]=void 0,this.#o[o]=void 0,o===this.#m)this.#m=this.#y[o];else if(o===this.#p)this.#p=this.#g[o];else{let i=this.#y[o];this.#g[i]=this.#g[o];let a=this.#g[o];this.#y[a]=this.#y[o]}this.#c--,this.#C.push(o)}}if(this.#h&&this.#f?.length){let o=this.#f,s;for(;s=o?.shift();)this.#n?.(...s)}return n}clear(){return this.#z("delete")}#z(e){for(let t of this.#I({allowStale:!0})){let n=this.#o[t];if(this.#d(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#l[t];this.#T&&this.#s?.(n,o,e),this.#h&&this.#f?.push([n,o,e])}}if(this.#a.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#w&&this.#A&&(this.#w.fill(0),this.#A.fill(0)),this.#v&&this.#v.fill(0),this.#p=0,this.#m=0,this.#C.length=0,this.#u=0,this.#c=0,this.#h&&this.#f){let t=this.#f,n;for(;n=t?.shift();)this.#n?.(...n)}}};import{posix as XE,win32 as Cl}from"node:path";import{fileURLToPath as JE}from"node:url";import{lstatSync as ZE,readdir as QE,readdirSync as eC,readlinkSync as tC,realpathSync as rC}from"fs";import*as nC from"node:fs";import{lstat as sC,readdir as iC,readlink as aC,realpath as lC}from"node:fs/promises";import{EventEmitter as bl}from"node:events";import nh from"node:stream";import{StringDecoder as BE}from"node:string_decoder";var Qp=typeof process=="object"&&process?process:{stdout:null,stderr:null},zE=r=>!!r&&typeof r=="object"&&(r instanceof dr||r instanceof nh||WE(r)||jE(r)),WE=r=>!!r&&typeof r=="object"&&r instanceof bl&&typeof r.pipe=="function"&&r.pipe!==nh.Writable.prototype.pipe,jE=r=>!!r&&typeof r=="object"&&r instanceof bl&&typeof r.write=="function"&&typeof r.end=="function",Jt=Symbol("EOF"),Zt=Symbol("maybeEmitEnd"),cr=Symbol("emittedEnd"),ii=Symbol("emittingEnd"),wo=Symbol("emittedError"),ai=Symbol("closed"),eh=Symbol("read"),li=Symbol("flush"),th=Symbol("flushChunk"),Tt=Symbol("encoding"),yn=Symbol("decoder"),Se=Symbol("flowing"),bo=Symbol("paused"),Sn=Symbol("resume"),we=Symbol("buffer"),je=Symbol("pipes"),be=Symbol("bufferLength"),hl=Symbol("bufferPush"),ci=Symbol("bufferShift"),ke=Symbol("objectMode"),se=Symbol("destroyed"),fl=Symbol("error"),gl=Symbol("emitData"),rh=Symbol("emitEnd"),yl=Symbol("emitEnd2"),_t=Symbol("async"),Sl=Symbol("abort"),di=Symbol("aborted"),To=Symbol("signal"),Pr=Symbol("dataListeners"),et=Symbol("discarded"),Eo=r=>Promise.resolve().then(r),HE=r=>r(),GE=r=>r==="end"||r==="finish"||r==="prefinish",VE=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,qE=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),ui=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[Sn](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},wl=class extends ui{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=o=>t.emit("error",o),e.on("error",this.proxyErrors)}},KE=r=>!!r.objectMode,YE=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",dr=class extends bl{[Se]=!1;[bo]=!1;[je]=[];[we]=[];[ke];[Tt];[_t];[yn];[Jt]=!1;[cr]=!1;[ii]=!1;[ai]=!1;[wo]=null;[be]=0;[se]=!1;[To];[di]=!1;[Pr]=0;[et]=!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");KE(t)?(this[ke]=!0,this[Tt]=null):YE(t)?(this[Tt]=t.encoding,this[ke]=!1):(this[ke]=!1,this[Tt]=null),this[_t]=!!t.async,this[yn]=this[Tt]?new BE(this[Tt]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[we]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[je]});let{signal:n}=t;n&&(this[To]=n,n.aborted?this[Sl]():n.addEventListener("abort",()=>this[Sl]()))}get bufferLength(){return this[be]}get encoding(){return this[Tt]}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[ke]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[_t]}set async(e){this[_t]=this[_t]||!!e}[Sl](){this[di]=!0,this.emit("abort",this[To]?.reason),this.destroy(this[To]?.reason)}get aborted(){return this[di]}set aborted(e){}write(e,t,n){if(this[di])return!1;if(this[Jt])throw new Error("write after end");if(this[se])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(n=t,t="utf8"),t||(t="utf8");let o=this[_t]?Eo:HE;if(!this[ke]&&!Buffer.isBuffer(e)){if(qE(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(VE(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[ke]?(this[Se]&&this[be]!==0&&this[li](!0),this[Se]?this.emit("data",e):this[hl](e),this[be]!==0&&this.emit("readable"),n&&o(n),this[Se]):e.length?(typeof e=="string"&&!(t===this[Tt]&&!this[yn]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[Tt]&&(e=this[yn].write(e)),this[Se]&&this[be]!==0&&this[li](!0),this[Se]?this.emit("data",e):this[hl](e),this[be]!==0&&this.emit("readable"),n&&o(n),this[Se]):(this[be]!==0&&this.emit("readable"),n&&o(n),this[Se])}read(e){if(this[se])return null;if(this[et]=!1,this[be]===0||e===0||e&&e>this[be])return this[Zt](),null;this[ke]&&(e=null),this[we].length>1&&!this[ke]&&(this[we]=[this[Tt]?this[we].join(""):Buffer.concat(this[we],this[be])]);let t=this[eh](e||null,this[we][0]);return this[Zt](),t}[eh](e,t){if(this[ke])this[ci]();else{let n=t;e===n.length||e===null?this[ci]():typeof n=="string"?(this[we][0]=n.slice(e),t=n.slice(0,e),this[be]-=e):(this[we][0]=n.subarray(e),t=n.subarray(0,e),this[be]-=e)}return this.emit("data",t),!this[we].length&&!this[Jt]&&this.emit("drain"),t}end(e,t,n){return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t="utf8"),e!==void 0&&this.write(e,t),n&&this.once("end",n),this[Jt]=!0,this.writable=!1,(this[Se]||!this[bo])&&this[Zt](),this}[Sn](){this[se]||(!this[Pr]&&!this[je].length&&(this[et]=!0),this[bo]=!1,this[Se]=!0,this.emit("resume"),this[we].length?this[li]():this[Jt]?this[Zt]():this.emit("drain"))}resume(){return this[Sn]()}pause(){this[Se]=!1,this[bo]=!0,this[et]=!1}get destroyed(){return this[se]}get flowing(){return this[Se]}get paused(){return this[bo]}[hl](e){this[ke]?this[be]+=1:this[be]+=e.length,this[we].push(e)}[ci](){return this[ke]?this[be]-=1:this[be]-=this[we][0].length,this[we].shift()}[li](e=!1){do;while(this[th](this[ci]())&&this[we].length);!e&&!this[we].length&&!this[Jt]&&this.emit("drain")}[th](e){return this.emit("data",e),this[Se]}pipe(e,t){if(this[se])return e;this[et]=!1;let n=this[cr];return t=t||{},e===Qp.stdout||e===Qp.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[je].push(t.proxyErrors?new wl(this,e,t):new ui(this,e,t)),this[_t]?Eo(()=>this[Sn]()):this[Sn]()),e}unpipe(e){let t=this[je].find(n=>n.dest===e);t&&(this[je].length===1?(this[Se]&&this[Pr]===0&&(this[Se]=!1),this[je]=[]):this[je].splice(this[je].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e==="data")this[et]=!1,this[Pr]++,!this[je].length&&!this[Se]&&this[Sn]();else if(e==="readable"&&this[be]!==0)super.emit("readable");else if(GE(e)&&this[cr])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[wo]){let o=t;this[_t]?Eo(()=>o.call(this,this[wo])):o.call(this,this[wo])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e==="data"&&(this[Pr]=this.listeners("data").length,this[Pr]===0&&!this[et]&&!this[je].length&&(this[Se]=!1)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Pr]=0,!this[et]&&!this[je].length&&(this[Se]=!1)),t}get emittedEnd(){return this[cr]}[Zt](){!this[ii]&&!this[cr]&&!this[se]&&this[we].length===0&&this[Jt]&&(this[ii]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ai]&&this.emit("close"),this[ii]=!1)}emit(e,...t){let n=t[0];if(e!=="error"&&e!=="close"&&e!==se&&this[se])return!1;if(e==="data")return!this[ke]&&!n?!1:this[_t]?(Eo(()=>this[gl](n)),!0):this[gl](n);if(e==="end")return this[rh]();if(e==="close"){if(this[ai]=!0,!this[cr]&&!this[se])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(e==="error"){this[wo]=n,super.emit(fl,n);let s=!this[To]||this.listeners("error").length?super.emit("error",n):!1;return this[Zt](),s}else if(e==="resume"){let s=super.emit("resume");return this[Zt](),s}else if(e==="finish"||e==="prefinish"){let s=super.emit(e);return this.removeAllListeners(e),s}let o=super.emit(e,...t);return this[Zt](),o}[gl](e){for(let n of this[je])n.dest.write(e)===!1&&this.pause();let t=this[et]?!1:super.emit("data",e);return this[Zt](),t}[rh](){return this[cr]?!1:(this[cr]=!0,this.readable=!1,this[_t]?(Eo(()=>this[yl]()),!0):this[yl]())}[yl](){if(this[yn]){let t=this[yn].end();if(t){for(let n of this[je])n.dest.write(t);this[et]||super.emit("data",t)}}for(let t of this[je])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[ke]||(e.dataLength=0);let t=this.promise();return this.on("data",n=>{e.push(n),this[ke]||(e.dataLength+=n.length)}),await t,e}async concat(){if(this[ke])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[Tt]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(se,()=>t(new Error("stream destroyed"))),this.on("error",n=>t(n)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[et]=!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[Jt])return t();let s,i,a=d=>{this.off("data",l),this.off("end",c),this.off(se,u),t(),i(d)},l=d=>{this.off("error",a),this.off("end",c),this.off(se,u),this.pause(),s({value:d,done:!!this[Jt]})},c=()=>{this.off("error",a),this.off("data",l),this.off(se,u),t(),s({done:!0,value:void 0})},u=()=>a(new Error("stream destroyed"));return new Promise((d,m)=>{i=m,s=d,this.once(se,u),this.once("error",a),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[et]=!1;let e=!1,t=()=>(this.pause(),this.off(fl,t),this.off(se,t),this.off("end",t),e=!0,{done:!0,value:void 0}),n=()=>{if(e)return t();let o=this.read();return o===null?t():{done:!1,value:o}};return this.once("end",t),this.once(fl,t),this.once(se,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[se])return e?this.emit("error",e):this.emit(se),this;this[se]=!0,this[et]=!0,this[we].length=0,this[be]=0;let t=this;return typeof t.close=="function"&&!this[ai]&&t.close(),e?this.emit("error",e):this.emit(se),this}static get isStream(){return zE}};var oC=rC.native,vo={lstatSync:ZE,readdir:QE,readdirSync:eC,readlinkSync:tC,realpathSync:oC,promises:{lstat:sC,readdir:iC,readlink:aC,realpath:lC}},lh=r=>!r||r===vo||r===nC?vo:{...vo,...r,promises:{...vo.promises,...r.promises||{}}},ch=/^\\\\\?\\([a-z]:)\\?$/i,cC=r=>r.replace(/\//g,"\\").replace(ch,"$1\\"),dC=/[\\\/]/,pt=0,dh=1,uh=2,kt=4,mh=6,ph=8,Or=10,hh=12,mt=15,Co=~mt,Tl=16,oh=32,Ao=64,Et=128,mi=256,hi=512,sh=Ao|Et|hi,uC=1023,El=r=>r.isFile()?ph:r.isDirectory()?kt:r.isSymbolicLink()?Or:r.isCharacterDevice()?uh:r.isBlockDevice()?mh:r.isSocket()?hh:r.isFIFO()?dh:pt,ih=new Map,xo=r=>{let e=ih.get(r);if(e)return e;let t=r.normalize("NFKD");return ih.set(r,t),t},ah=new Map,pi=r=>{let e=ah.get(r);if(e)return e;let t=xo(r.toLowerCase());return ah.set(r,t),t},fi=class extends So{constructor(){super({max:256})}},vl=class extends So{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},fh=Symbol("PathScurry setAsCwd"),De=class{name;root;roots;parent;nocase;isCWD=!1;#e;#t;get dev(){return this.#t}#s;get mode(){return this.#s}#n;get nlink(){return this.#n}#i;get uid(){return this.#i}#b;get gid(){return this.#b}#c;get rdev(){return this.#c}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#l;get size(){return this.#l}#o;get blocks(){return this.#o}#g;get atimeMs(){return this.#g}#y;get mtimeMs(){return this.#y}#p;get ctimeMs(){return this.#p}#m;get birthtimeMs(){return this.#m}#C;get atime(){return this.#C}#f;get mtime(){return this.#f}#v;get ctime(){return this.#v}#A;get birthtime(){return this.#A}#w;#T;#E;#h;#P;#x;#r;#M;#S;#O;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=pt,n,o,s,i,a){this.name=e,this.#w=s?pi(e):xo(e),this.#r=t&uC,this.nocase=s,this.roots=o,this.root=n||this,this.#M=i,this.#E=a.fullpath,this.#P=a.relative,this.#x=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=lh(a.fs)}depth(){return this.#T!==void 0?this.#T:this.parent?this.#T=this.parent.depth()+1:this.#T=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 n of e)t=t.child(n);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.#r&=~Tl,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let n=this.children(),o=this.nocase?pi(e):xo(e);for(let l of n)if(l.#w===o)return l;let s=this.parent?this.sep:"",i=this.#E?this.#E+s+e:void 0,a=this.newChild(e,pt,{...t,parent:this,fullpath:i});return this.canReaddir()||(a.#r|=Et),n.push(a),a}relative(){if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let e=this.name,t=this.parent;if(!t)return this.#P=this.name;let n=t.relative();return n+(!n||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#x!==void 0)return this.#x;let e=this.name,t=this.parent;if(!t)return this.#x=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?"":"/")+e}fullpath(){if(this.#E!==void 0)return this.#E;let e=this.name,t=this.parent;if(!t)return this.#E=this.name;let o=t.fullpath()+(t.parent?this.sep:"")+e;return this.#E=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(),n=t+(!t||!e.parent?"":"/")+this.name;return this.#h=n}isUnknown(){return(this.#r&mt)===pt}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.#r&mt)===ph}isDirectory(){return(this.#r&mt)===kt}isCharacterDevice(){return(this.#r&mt)===uh}isBlockDevice(){return(this.#r&mt)===mh}isFIFO(){return(this.#r&mt)===dh}isSocket(){return(this.#r&mt)===hh}isSymbolicLink(){return(this.#r&Or)===Or}lstatCached(){return this.#r&oh?this:void 0}readlinkCached(){return this.#S}realpathCached(){return this.#O}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#S)return!0;if(!this.parent)return!1;let e=this.#r&mt;return!(e!==pt&&e!==Or||this.#r&mi||this.#r&Et)}calledReaddir(){return!!(this.#r&Tl)}isENOENT(){return!!(this.#r&Et)}isNamed(e){return this.nocase?this.#w===pi(e):this.#w===xo(e)}async readlink(){let e=this.#S;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),n=(await this.parent.realpath())?.resolve(t);if(n)return this.#S=n}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#S;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),n=this.parent.realpathSync()?.resolve(t);if(n)return this.#S=n}catch(t){this.#d(t.code);return}}#_(e){this.#r|=Tl;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#k()}}#k(){this.#r&Et||(this.#r=(this.#r|Et)&Co,this.#R())}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#k()}#I(){this.#r|=hi,this.#D()}#D(){if(this.#r&Ao)return;let e=this.#r;(e&mt)===kt&&(e&=Co),this.#r=e|Ao,this.#R()}#F(e=""){e==="ENOTDIR"||e==="EPERM"?this.#D():e==="ENOENT"?this.#k():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#D():e==="ENOENT"&&this.#k()}#d(e=""){let t=this.#r;t|=mi,e==="ENOENT"&&(t|=Et),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Co),this.#r=t,e==="ENOTDIR"&&this.parent&&this.parent.#D()}#$(e,t){return this.#L(e,t)||this.#B(e,t)}#B(e,t){let n=El(e),o=this.newChild(e.name,n,{parent:this}),s=o.#r&mt;return s!==kt&&s!==Or&&s!==pt&&(o.#r|=Ao),t.unshift(o),t.provisional++,o}#L(e,t){for(let n=t.provisional;n<t.length;n++){let o=t[n];if((this.nocase?pi(e.name):xo(e.name))===o.#w)return this.#z(e,o,n,t)}}#z(e,t,n,o){let s=t.name;return t.#r=t.#r&Co|El(e),s!==e.name&&(t.name=e.name),n!==o.provisional&&(n===o.length-1?o.pop():o.splice(n,1),o.unshift(t)),o.provisional++,t}async lstat(){if(!(this.#r&Et))try{return this.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#r&Et))try{return this.#G(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code)}}#G(e){let{atime:t,atimeMs:n,birthtime:o,birthtimeMs:s,blksize:i,blocks:a,ctime:l,ctimeMs:c,dev:u,gid:d,ino:m,mode:p,mtime:h,mtimeMs:f,nlink:g,rdev:y,size:S,uid:w}=e;this.#C=t,this.#g=n,this.#A=o,this.#m=s,this.#u=i,this.#o=a,this.#v=l,this.#p=c,this.#t=u,this.#b=d,this.#a=m,this.#s=p,this.#f=h,this.#y=f,this.#n=g,this.#c=y,this.#l=S,this.#i=w;let E=El(e);this.#r=this.#r&Co|E|oh,E!==pt&&E!==kt&&E!==Or&&(this.#r|=Ao)}#j=[];#H=!1;#V(e){this.#H=!1;let t=this.#j.slice();this.#j.length=0,t.forEach(n=>n(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let s=n.slice(0,n.provisional);t?e(null,s):queueMicrotask(()=>e(null,s));return}if(this.#j.push(e),this.#H)return;this.#H=!0;let o=this.fullpath();this.#e.readdir(o,{withFileTypes:!0},(s,i)=>{if(s)this.#F(s.code),n.provisional=0;else{for(let a of i)this.#$(a,n);this.#_(n)}this.#V(n.slice(0,n.provisional))})}#W;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.#W)await this.#W;else{let n=()=>{};this.#W=new Promise(o=>n=o);try{for(let o of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#$(o,e);this.#_(e)}catch(o){this.#F(o.code),e.provisional=0}this.#W=void 0,n()}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 n of this.#e.readdirSync(t,{withFileTypes:!0}))this.#$(n,e);this.#_(e)}catch(n){this.#F(n.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#r&sh)return!1;let e=mt&this.#r;return e===pt||e===kt||e===Or}shouldWalk(e,t){return(this.#r&kt)===kt&&!(this.#r&sh)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#O)return this.#O;if(!((hi|mi|Et)&this.#r))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#O=this.resolve(e)}catch{this.#I()}}realpathSync(){if(this.#O)return this.#O;if(!((hi|mi|Et)&this.#r))try{let e=this.#e.realpathSync(this.fullpath());return this.#O=this.resolve(e)}catch{this.#I()}}[fh](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),n=[],o=this;for(;o&&o.parent;)t.add(o),o.#P=n.join(this.sep),o.#x=n.join("/"),o=o.parent,n.push("..");for(o=e;o&&o.parent&&!t.has(o);)o.#P=void 0,o.#x=void 0,o=o.parent}},gi=class r extends De{sep="\\";splitSep=dC;constructor(e,t=pt,n,o,s,i,a){super(e,t,n,o,s,i,a)}newChild(e,t=pt,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return Cl.parse(e).root}getRoot(e){if(e=cC(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new wn(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(ch,"$1\\"),e===t}},yi=class r extends De{splitSep="/";sep="/";constructor(e,t=pt,n,o,s,i,a){super(e,t,n,o,s,i,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=pt,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}},Si=class{root;rootPath;roots;cwd;#e;#t;#s;nocase;#n;constructor(e=process.cwd(),t,n,{nocase:o,childrenCacheSize:s=16*1024,fs:i=vo}={}){this.#n=lh(i),(e instanceof URL||e.startsWith("file://"))&&(e=JE(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new fi,this.#t=new fi,this.#s=new vl(s);let l=a.substring(this.rootPath.length).split(n);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.#n),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,d=t.sep,m=this.rootPath,p=!1;for(let h of l){let f=u--;c=c.child(h,{relative:new Array(f).fill("..").join(d),relativePosix:new Array(f).fill("..").join("/"),fullpath:m+=(p?"":d)+h}),p=!0}this.cwd=c}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#s}resolve(...e){let t="";for(let s=e.length-1;s>=0;s--){let i=e[s];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let n=this.#e.get(t);if(n!==void 0)return n;let o=this.cwd.resolve(t).fullpath();return this.#e.set(t,o),o}resolvePosix(...e){let t="";for(let s=e.length-1;s>=0;s--){let i=e[s];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let n=this.#t.get(t);if(n!==void 0)return n;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 De||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let o=await e.readdir();return n?o:o.map(s=>s.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0}=t;return e.canReaddir()?n?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 De||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t,a=[];(!s||s(e))&&a.push(n?e:e.fullpath());let l=new Set,c=(d,m)=>{l.add(d),d.readdirCB((p,h)=>{if(p)return m(p);let f=h.length;if(!f)return m();let g=()=>{--f===0&&m()};for(let y of h)(!s||s(y))&&a.push(n?y:y.fullpath()),o&&y.isSymbolicLink()?y.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(l,i)?c(S,g):g()):y.shouldWalk(l,i)?c(y,g):g()},!0)},u=e;return new Promise((d,m)=>{c(u,p=>{if(p)return m(p);d(a)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t,a=[];(!s||s(e))&&a.push(n?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let d of u){(!s||s(d))&&a.push(n?d:d.fullpath());let m=d;if(d.isSymbolicLink()){if(!(o&&(m=d.realpathSync())))continue;m.isUnknown()&&m.lstatSync()}m.shouldWalk(l,i)&&l.add(m)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(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 De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t;(!s||s(e))&&(yield n?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let u of c){(!s||s(u))&&(yield n?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(o&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,i)&&a.add(d)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t,a=new dr({objectMode:!0});(!s||s(e))&&a.write(n?e:e.fullpath());let l=new Set,c=[e],u=0,d=()=>{let m=!1;for(;!m;){let p=c.shift();if(!p){u===0&&a.end();return}u++,l.add(p);let h=(g,y,S=!1)=>{if(g)return a.emit("error",g);if(o&&!S){let w=[];for(let E of y)E.isSymbolicLink()&&w.push(E.realpath().then(C=>C?.isUnknown()?C.lstat():C));if(w.length){Promise.all(w).then(()=>h(null,y,!0));return}}for(let w of y)w&&(!s||s(w))&&(a.write(n?w:w.fullpath())||(m=!0));u--;for(let w of y){let E=w.realpathCached()||w;E.shouldWalk(l,i)&&c.push(E)}m&&!a.flowing?a.once("drain",d):f||d()},f=!0;p.readdirCB(h,!0),f=!1}};return d(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t,a=new dr({objectMode:!0}),l=new Set;(!s||s(e))&&a.write(n?e:e.fullpath());let c=[e],u=0,d=()=>{let m=!1;for(;!m;){let p=c.shift();if(!p){u===0&&a.end();return}u++,l.add(p);let h=p.readdirSync();for(let f of h)(!s||s(f))&&(a.write(n?f:f.fullpath())||(m=!0));u--;for(let f of h){let g=f;if(f.isSymbolicLink()){if(!(o&&(g=f.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(l,i)&&c.push(g)}}m&&!a.flowing&&a.once("drain",d)};return d(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[fh](t)}},wn=class extends Si{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,Cl,"\\",{...t,nocase:n}),this.nocase=n;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return Cl.parse(e).root.toUpperCase()}newRoot(e){return new gi(this.rootPath,kt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},bn=class extends Si{sep="/";constructor(e=process.cwd(),t={}){let{nocase:n=!1}=t;super(e,XE,"/",{...t,nocase:n}),this.nocase=n}parseRootPath(e){return"/"}newRoot(e){return new yi(this.rootPath,kt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Ro=class extends bn{constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,{...t,nocase:n})}},SK=process.platform==="win32"?gi:yi,gh=process.platform==="win32"?wn:process.platform==="darwin"?Ro:bn;var mC=r=>r.length>=1,pC=r=>r.length>=1,Tn=class r{#e;#t;#s;length;#n;#i;#b;#c;#u;#a;#l=!0;constructor(e,t,n,o){if(!mC(e))throw new TypeError("empty pattern list");if(!pC(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,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#s=n,this.#n=o,this.#s===0){if(this.isUNC()){let[s,i,a,l,...c]=this.#e,[u,d,m,p,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let f=[s,i,a,l,""].join("/"),g=[u,d,m,p,""].join("/");this.#e=[f,...c],this.#t=[g,...h],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[s,...i]=this.#e,[a,...l]=this.#t;i[0]===""&&(i.shift(),l.shift());let c=s+"/",u=a+"/";this.#e=[c,...i],this.#t=[u,...l],this.length=this.#e.length}}}pattern(){return this.#e[this.#s]}isString(){return typeof this.#e[this.#s]=="string"}isGlobstar(){return this.#e[this.#s]===ve}isRegExp(){return this.#e[this.#s]instanceof RegExp}globString(){return this.#b=this.#b||(this.#s===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#s).join("/"))}hasMore(){return this.length>this.#s+1}rest(){return this.#i!==void 0?this.#i:this.hasMore()?(this.#i=new r(this.#e,this.#t,this.#s+1,this.#n),this.#i.#a=this.#a,this.#i.#u=this.#u,this.#i.#c=this.#c,this.#i):this.#i=null}isUNC(){let e=this.#e;return this.#u!==void 0?this.#u:this.#u=this.#n==="win32"&&this.#s===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.#n==="win32"&&this.#s===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#s===0?e:""}checkFollowGlobstar(){return!(this.#s===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#s===0||!this.isGlobstar()||!this.#l?!1:(this.#l=!1,!0)}};var hC=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",En=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:o,noglobstar:s,platform:i=hC}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=i,this.mmopts={dot:!0,nobrace:t,nocase:n,noext:o,noglobstar:s,optimizationLevel:2,platform:i,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let t=new Qe(e,this.mmopts);for(let n=0;n<t.set.length;n++){let o=t.set[n],s=t.globParts[n];if(!o||!s)throw new Error("invalid pattern object");for(;o[0]==="."&&s[0]===".";)o.shift(),s.shift();let i=new Tn(o,s,0,this.platform),a=new Qe(i.globString(),this.mmopts),l=s[s.length-1]==="**",c=i.isAbsolute();c?this.absolute.push(a):this.relative.push(a),l&&(c?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let t=e.fullpath(),n=`${t}/`,o=e.relative()||".",s=`${o}/`;for(let i of this.relative)if(i.match(o)||i.match(s))return!0;for(let i of this.absolute)if(i.match(t)||i.match(n))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",n=(e.relative()||".")+"/";for(let o of this.relativeChildren)if(o.match(n))return!0;for(let o of this.absoluteChildren)if(o.match(t))return!0;return!1}};var Al=class r{store;constructor(e=new Map){this.store=e}copy(){return new r(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let n=e.fullpath(),o=this.store.get(n);o?o.add(t.globString()):this.store.set(n,new Set([t.globString()]))}},xl=class{store=new Map;add(e,t,n){let o=(t?2:0)|(n?1:0),s=this.store.get(e);this.store.set(e,s===void 0?o:o&s)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Rl=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(o=>o.globString()===t.globString())||n.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())}},Io=class r{hasWalkedCache;matches=new xl;subwalks=new Rl;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Al}processPatterns(e,t){this.patterns=t;let n=t.map(o=>[e,o]);for(let[o,s]of n){this.hasWalkedCache.storeWalked(o,s);let i=s.root(),a=s.isAbsolute()&&this.opts.absolute!==!1;if(i){o=o.resolve(i==="/"&&this.opts.root!==void 0?this.opts.root:i);let d=s.rest();if(d)s=d;else{this.matches.add(o,!0,!1);continue}}if(o.isENOENT())continue;let l,c,u=!1;for(;typeof(l=s.pattern())=="string"&&(c=s.rest());)o=o.resolve(l),s=c,u=!0;if(l=s.pattern(),c=s.rest(),u){if(this.hasWalkedCache.hasWalked(o,s))continue;this.hasWalkedCache.storeWalked(o,s)}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(o.resolve(l),a,d);continue}else if(l===ve){(!o.isSymbolicLink()||this.follow||s.checkFollowGlobstar())&&this.subwalks.add(o,s);let d=c?.pattern(),m=c?.rest();if(!c||(d===""||d===".")&&!m)this.matches.add(o,a,d===""||d===".");else if(d===".."){let p=o.parent||o;m?this.hasWalkedCache.hasWalked(p,m)||this.subwalks.add(p,m):this.matches.add(p,a,!0)}}else l instanceof RegExp&&this.subwalks.add(o,s)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),o=this.child();for(let s of t)for(let i of n){let a=i.isAbsolute(),l=i.pattern(),c=i.rest();l===ve?o.testGlobstar(s,i,c,a):l instanceof RegExp?o.testRegExp(s,l,c,a):o.testString(s,l,c,a)}return o}testGlobstar(e,t,n,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()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let s=n.pattern();if(typeof s=="string"&&s!==".."&&s!==""&&s!==".")this.testString(e,s,n.rest(),o);else if(s===".."){let i=e.parent||e;this.subwalks.add(i,n)}else s instanceof RegExp&&this.testRegExp(e,s,n.rest(),o)}}testRegExp(e,t,n,o){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,o,!1))}testString(e,t,n,o){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,o,!1))}};var fC=(r,e)=>typeof r=="string"?new En([r],e):Array.isArray(r)?new En(r,e):r,wi=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#t;#s;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#s=!n.posix&&n.platform==="win32"?"\\":"/",this.includeChildMatches=n.includeChildMatches!==!1,(n.ignore||!this.includeChildMatches)&&(this.#t=fC(n.ignore??[],n),!this.includeChildMatches&&typeof this.#t.add!="function")){let o="cannot ignore child matches, ignore lacks add() method.";throw new Error(o)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#n(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#i(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 n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,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.#n(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,t)}matchFinish(e,t){if(this.#n(e))return;if(!this.includeChildMatches&&this.#t?.add){let s=`${e.relativePosix()}/**`;this.#t.add(s)}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let o=this.opts.mark&&e.isDirectory()?this.#s:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let s=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(s+o)}else{let s=this.opts.posix?e.relativePosix():e.relative(),i=this.opts.dotRelative&&!s.startsWith(".."+this.#s)?"."+this.#s:"";this.matchEmit(s?i+s+o:"."+o)}}async match(e,t,n){let o=await this.matchCheck(e,n);o&&this.matchFinish(o,t)}matchSync(e,t,n){let o=this.matchCheckSync(e,n);o&&this.matchFinish(o,t)}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new Io(this.opts),n)}walkCB2(e,t,n,o){if(this.#i(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,o));return}n.processPatterns(e,t);let s=1,i=()=>{--s===0&&o()};for(let[a,l,c]of n.matches.entries())this.#n(a)||(s++,this.match(a,l,c).then(()=>i()));for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;s++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,n,i):a.readdirCB((c,u)=>this.walkCB3(a,u,n,i),!0)}i()}walkCB3(e,t,n,o){n=n.filterEntries(e,t);let s=1,i=()=>{--s===0&&o()};for(let[a,l,c]of n.matches.entries())this.#n(a)||(s++,this.match(a,l,c).then(()=>i()));for(let[a,l]of n.subwalks.entries())s++,this.walkCB2(a,l,n.child(),i);i()}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new Io(this.opts),n)}walkCB2Sync(e,t,n,o){if(this.#i(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,o));return}n.processPatterns(e,t);let s=1,i=()=>{--s===0&&o()};for(let[a,l,c]of n.matches.entries())this.#n(a)||this.matchSync(a,l,c);for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;s++;let l=a.readdirSync();this.walkCB3Sync(a,l,n,i)}i()}walkCB3Sync(e,t,n,o){n=n.filterEntries(e,t);let s=1,i=()=>{--s===0&&o()};for(let[a,l,c]of n.matches.entries())this.#n(a)||this.matchSync(a,l,c);for(let[a,l]of n.subwalks.entries())s++,this.walkCB2Sync(a,l,n.child(),i);i()}},Po=class extends wi{matches=new Set;constructor(e,t,n){super(e,t,n)}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}},Oo=class extends wi{results;constructor(e,t,n){super(e,t,n),this.results=new dr({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 yC=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ct=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=gC(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||yC,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"?wn:t.platform==="darwin"?Ro:t.platform?bn:gh;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let n=this.platform==="darwin"||this.platform==="win32",o={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},s=this.pattern.map(l=>new Qe(l,o)),[i,a]=s.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=i.map((l,c)=>{let u=a[c];if(!u)throw new Error("invalid pattern object");return new Tn(l,u,0,this.platform)})}async walk(){return[...await new Po(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 Po(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 Oo(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 Oo(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 Il=(r,e={})=>{Array.isArray(r)||(r=[r]);for(let t of r)if(new Qe(t,e).hasMagic())return!0;return!1};function bi(r,e={}){return new Ct(r,e).streamSync()}function wh(r,e={}){return new Ct(r,e).stream()}function Cn(r,e={}){return new Ct(r,e).walkSync()}async function yh(r,e={}){return new Ct(r,e).walk()}function Ti(r,e={}){return new Ct(r,e).iterateSync()}function bh(r,e={}){return new Ct(r,e).iterate()}var SC=bi,wC=Object.assign(wh,{sync:bi}),bC=Ti,TC=Object.assign(bh,{sync:Ti}),EC=Object.assign(Cn,{stream:bi,iterate:Ti}),Sh=Object.assign(yh,{glob:yh,globSync:Cn,sync:EC,globStream:wh,stream:wC,globStreamSync:bi,streamSync:SC,globIterate:bh,iterate:TC,globIterateSync:Ti,iterateSync:bC,Glob:Ct,hasMagic:Il,escape:hn,unescape:bt});Sh.glob=Sh;import OC from"os";import ur,{dirname as Ch}from"path";import{cwd as Ml}from"process";import vh from"yaml";import{z as me}from"zod";import Th from"fs";import Ei from"path";import CC from"yaml";import{z as Pl}from"zod";var Lo=[`**/*.${Bt.TEST}`,`**/*.${Bt.MODULE}`],Ol=Pl.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Ll=50,vC=Pl.object({fileType:Pl.nativeEnum(ne)});function vt(r,e){let t={project:r,tests:{},modules:{}},n=r.config.include??Lo,o=Array.from(r.config.exclude??[]).concat(Nd),s=Cn(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Ll,nodir:!0});for(let i of s)AC(r.rootDir,i,t,e);return t}function AC(r,e,t,n){let o=Ei.join(r,e),s;try{s=Th.readFileSync(o,"utf-8")}catch(d){n.warn(`Could not read possible Momentic file at ${o}, skipping: ${d}`);return}let i;try{if(i=CC.parse(s),typeof i!="object"||i===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(d){n.warn(`Could not parse possible Momentic file at ${o}, skipping: ${d}`);return}let a=vC.safeParse(i);if(a.error){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${a.error}`);return}let l=a.data.fileType,c;try{c=Th.statSync(o)}catch(d){n.warn(`Skipping path '${o}' because it could not be stat, skipping: ${d}`);return}let u={relativePath:e,fullFilePath:o,platformSep:Ei.sep,fullPathSegments:o.split(Ei.sep),fileName:Ei.basename(o),lastModified:c.mtime,createdAt:c.ctime};switch(l){case ne.TEST:try{let d=Ne.parse(i);t.tests[d.id]={type:ne.TEST,name:d.name,id:d.id,...u};return}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case ne.MODULE:try{let d=st.parse(i);t.modules[d.moduleId]={type:ne.MODULE,name:d.name,id:d.moduleId,...u};return}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}default:n.warn(`Unsupported file type ${l}, skipping...`);return}}var vn="momentic.config.yaml",Eh="momentic.workspace.yaml",LC=me.object({projects:me.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),MC=me.union([me.string(),me.object({fromFile:me.string(),json:me.boolean().optional()})]),NC=me.object({name:Ol,baseUrl:me.string(),envFile:me.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:me.record(me.string(),MC).optional(),inheritFromShell:me.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:la.optional().transform(r=>r&&(r.localChromeExtensionPaths&&(r.localChromeExtensionPaths=r.localChromeExtensionPaths.map(e=>e.startsWith("~")?ur.join(OC.homedir(),e.slice(1)):e)),r))}),_C=me.object({name:Ol,include:me.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:me.string().array().optional().describe("opposite of include, takes precedence over include"),moduleCreationDir:me.string().optional(),testCreationDir:me.string().optional(),environments:me.array(NC).optional()});function Ah(r,e){let t;try{t=RC(r,"utf-8")}catch(o){T.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=vh.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){T.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Nl(r){let e=Ah(r,"project configuration");if(e!==void 0)try{return _C.parse(e)}catch(t){T.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function kC(r){let e=Ah(r,"workspace configuration");if(e!==void 0)try{return LC.parse(e)}catch(t){T.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function DC(){let r=[],e=Ml(),t=ur.parse(e).root,n=15,o=0;for(;o<n;){o++;let s=ur.basename(e);if(to.includes(s))return T.warn(`Stopping search for Momentic projects since the current directory name (${s}) is likely a system artifact folder.`),r;for(let i of IC(e))if(i.endsWith(vn)){let a=ur.join(e,i),l=Nl(a);l&&r.push({configFilePath:a,config:l,rootDir:Ch(a)})}if(r.length)return r;if(e=ur.dirname(e),e===t)break}return r}function Lr(r={}){let{configFilePath:e,nameFilter:t}=r,n=_l(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
|
|
1981
|
-
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return n[0]}function FC(r){let e=kC(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(s=>(s.endsWith("/")||(s+="/"),`${s}*${vn}`)),n=Cn(t,{absolute:!1,cwd:Ml(),dotRelative:!1,maxDepth:Ll,nodir:!0}),o=[];for(let s of n){let i=ur.join(Ml(),s),a=Nl(i);a&&o.push({configFilePath:i,config:a,rootDir:Ch(i)})}return o}function _l(r){if(r){r=ur.resolve(r);let t=Nl(r);if(!t)throw new Error("No valid Momentic project file available.");return[{config:t,configFilePath:r,rootDir:ur.dirname(r)}]}if(xC(Eh)){let t=FC(Eh);if(t)return t}return DC()}function An(r,e){let t=vh.stringify(r);PC(e,t)}var Dl="https://api.momentic.ai",xh,Rh=r=>{Dl=r},Mo=()=>Dl,Ih=r=>{xh=r},Te=()=>xh,xn,kl,Ph=async r=>{if(xn)return xn;let e=new Be({baseUrl:Dl,apiKey:r});try{return xn=await e.getOrgId(),kl=r,xn}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Ci=()=>{if(!xn)throw new Error("Your organization ID appears invalid. Please contact Momentic support.");return xn},Oh=()=>{if(!kl)throw new Error("Your API key appears invalid. Please contact Momentic support.");return kl};import Lh,{multistream as UC}from"pino";import $C from"pino-pretty";var Fl=new Map,BC=!0,Ul=class r{consoleLogger;ddClientToken;hostname;bindingAttributes;excludeAttributesInConsoleLogs;excludeTimestamps;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:n,excludeAttributesInConsoleLogs:o,excludeTimestamps:s,disableConsoleLogs:i}){this.ddClientToken=t,this.hostname=n,this.excludeAttributesInConsoleLogs=o,this.excludeTimestamps=s,this.disableConsoleLogs=i,this.bindingAttributes={...e,env:"production"};let a={base:o?{}:this.bindingAttributes,errorKey:"err",level:"debug",timestamp:!s};this.consoleLogger=BC?Lh(a):Lh(a,UC([{stream:$C({colorize:!0})}]))}child(e){return new r({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,excludeAttributesInConsoleLogs:this.excludeAttributesInConsoleLogs,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,n,...o){if(t&&n===void 0&&(n=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},n,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let i={};for(let a of Object.getOwnPropertyNames(t.err))i[a]=t.err[a];i.name=t.err.name,t.err=i}let s=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(s.args=o),(async()=>{try{let i=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,hostname:this.hostname??"vercel",service:"momentic",message:{message:n||"",...s,level:e}}])});if(!i.ok)throw new Error(`Failed to log to Datadog: ${i.statusText})}`)}catch(i){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:n,args:o,err:i},"Failed to log to Datadog")}})()}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},vi=({app:r,clientToken:e,hostname:t,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return Fl.has(r)||Fl.set(r,new Ul({bindings:{app:r},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})),Fl.get(r)};import{hostname as zC}from"os";var pe=vi({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:zC(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0}),Mh=r=>{pe.addBinding("version",r)};function Ae(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Nh=WC();Nh.get("/",Ae((r,e)=>{let t=Cp(Te(),pe);e.status(200).json(t)}));var _h=Nh;import{Router as jC}from"express";import kh from"fs";import Dh from"path";var Ai=jC();Ai.get("/",Ae(async(r,e)=>{let t=vt(Te(),T),o=(await bp(t,pe)).filter(s=>s.enabled??!0);e.status(200).json(o)}));Ai.post("/",Ae(async(r,e)=>{let t;try{t=Od.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}try{qn(t.name)}catch(i){e.status(400).json({error:`Invalid module name: ${i}`});return}let n=Te(),o=Dh.join(n.rootDir,n.config.moduleCreationDir??Dh.dirname(t.testFilePath));if(!kh.existsSync(o)||!kh.statSync(o).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${o}' does not exist.`});return}let s=await wp({...t,folder:o});e.status(201).json(s)}));Ai.get("/:moduleId",Ae(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=vt(Te(),T),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await al(n,t,T);e.json(o)}catch(o){e.status(400).json({err:o})}}));var Fh=Ai;import{Router as HC}from"express";var xi=HC();xi.get("/",Ae((r,e)=>{let t=_l().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));xi.get("/current",Ae((r,e)=>{let t=Te(),n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));xi.post("/set",Ae((r,e)=>{let t;try{t=Md.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Lr({configFilePath:t.configFilePath});Ih(n)}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var Uh=xi;import{Router as GC}from"express";import $l from"path";import{v4 as VC}from"uuid";var Mr=GC();Mr.get("/",Ae((r,e)=>{let t=Te(),n=vt(t,T),o=Array.from(Object.values(n.tests));e.status(200).json(o)}));Mr.post("/",Ae(async(r,e)=>{let t;try{t=Pd.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{qn(t.name)}catch(c){e.status(400).json({error:c.message});return}let o={id:VC(),name:t.name,baseUrl:t.baseUrl,schemaVersion:ct,advanced:{disableAICaching:!1,browserType:t.browserType??"Chromium",viewport:t.viewport??Ut},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let s=Te(),i=$l.join(s.rootDir,s.config.testCreationDir??""),a=await Tp({test:o,name:t.name,folder:i}),l={...o,relativeFilePath:$l.relative(s.rootDir,a)};e.status(201).json(l)}));Mr.get("/:testPath",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=Te(),o=vt(n,T),s;try{s=await ni($l.join(n.rootDir,t),pe,o),e.status(200).json(s)}catch(i){e.status(400).send({error:i.message});return}(async()=>{try{let{stepsToSave:i,moduleUpdates:a}=await gt({steps:s.steps});a.forEach(l=>{il(l.moduleId,{...l,schemaVersion:ct},o)}),po(t,{schemaVersion:ct,steps:i},n)}catch(i){pe.error({err:i},"Failed to save migrated test to disk after initial fetch")}})()}));Mr.patch("/:testPath/metadata",Ae(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Id.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}po(r.params.testPath,t,Te()),e.status(201).json({message:"ok"})}));Mr.patch("/:testPath",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Rd.parse(r.body)}catch(d){e.status(400).json({error:`Invalid request body: ${d}`});return}let o=Te(),s=vt(o,T),i;try{i=ri(t,o)}catch(d){e.status(400).json({error:`Existing test file on disk is invalid: ${d}`});return}let{stepsToSave:a,moduleUpdates:l,cachesToSave:c}=await gt({steps:n.steps,cacheCreationParams:{testId:i.id,orgId:Ci()}});await new Be({apiKey:Oh(),baseUrl:Mo()}).updateStepCaches({entries:c,testId:i.id}),l.forEach(d=>{il(d.moduleId,{...d,schemaVersion:n.schemaVersion},s)}),po(t,{steps:a,schemaVersion:n.schemaVersion},o),e.status(201).json({message:"ok"})}));Mr.patch("/:testPath/environments",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Ld.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}po(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},Te()),e.status(201).json({message:"ok"})}));var $h=Mr;var Ri=class extends en{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async getOrgId(t){return this.orgId}async fetchTestMetadata(t,n,o){let s=Te(),a=vt(s,o).tests[t];if(a)return ri(a.relativePath,s)}async fetchEnvironment(t,n,o){let s=Te();return ho(n,s,o)}};async function jh(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,appPort:o,staticDir:s,devicePixelRatio:i,version:a}=r;Mh(a),e&&Rh(e),pe.debug(r,"Initializing desktop server");let l=await Ph(t);pe.debug({orgId:l},"Checking API key successful");let u=`http://localhost:${n}`;o&&(u=`http://localhost:${o}`);let d=ZC(s);await new Promise(y=>{d.listen(n,()=>{pe.info(`Server is running at http://localhost:${n}`),y()})});let p=new mn({baseURL:Mo(),apiKey:t}),h={type:"API_KEY",baseUrl:Mo(),apiKey:t},f=new Be(h),g=new Ri(f,Ci());Sp({baseServer:d,generator:p,storage:g,logger:pe,devicePixelRatio:i,authorization:h}),await JC(u)}var Wh="25mb";function ZC(r){let e=zh();e.use(qC()),e.use(Bh.json({limit:Wh})),e.use(Bh.urlencoded({extended:!1,limit:Wh}));let t=YC();if(t.use("/tests",$h),t.use("/modules",Fh),t.use("/environments",_h),t.use("/projects",Uh),e.use("/api",t),e.use((o,s,i)=>{o.path!=="/healthcheck"&&pe.debug({url:o.url,path:o.path,query:o.query,method:o.method,body:o.body,headers:o.rawHeaders,client:o.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&pe.error({url:o.url,method:o.method,statusCode:s.statusCode},"Request completed in error")}),i()}),e.use((o,s,i,a)=>{if(o instanceof Error&&o.message.includes("BadRequestError: request aborted")){i.status(400).send("Client disconnected");return}pe.error({stack:o.stack,msg:o.message,err:o,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),T.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${o.message}`),i.status(500).send("Internal Server Error")}),r){let o=zh.static(r);e.use("/",o),e.use("*",o)}return XC.createServer(e)}KC.setMaxListeners(50);process.on("warning",r=>{pe.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{pe.error({err:r},"Uncaught exception leading to exit on desktop-server")});process.on("unhandledRejection",(r,e)=>{pe.error({reason:`${r}`,promise:`${e}`,stack:r?.stack},"Uncaught exception leading to exit on desktop-server (promise rejection)")});import Kv from"events";import kf from"fs";import ji from"path";import{fileURLToPath as Yv}from"url";import{existsSync as mv,mkdirSync as pv,statSync as hv}from"fs";import{dirname as fv}from"path";import Yh from"readline/promises";import{execSync as QC}from"child_process";import{platform as ev}from"os";function Bl(){return Hh()?(T.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),T.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),T.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(T.info("Setting device pixel ratio to 1."),T.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),T.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function Hh(){return ev()==="darwin"&&QC("system_profiler SPDisplaysDataType").toString().includes("Retina")}function zl(r){Hh()&&r===1&&(T.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),T.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import tv from"@actions/exec";import rv from"@actions/io";import nv from"quote";import ov from"string-argv";async function Gh(r,e=!0){let t=ov(r),n=await rv.which(t[0],!0),o=t.slice(1),s=tv.exec(nv(n),o,{delay:100});if(e)return s}import{existsSync as sv,statSync as iv}from"fs";var Vh=!!process.env.CI||!process.stdout.isTTY;function No(r){try{return sv(r)&&iv(r).isDirectory()}catch(e){return T.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import av from"csv-parser";import{createReadStream as lv}from"fs";function Wl(r){return new Promise((e,t)=>{let n=[];lv(r).pipe(av()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import Ii from"semver";import{z as Pi}from"zod";var _o="1.0.21",cv="https://registry.npmjs.org/momentic",dv=Pi.object({versions:Pi.record(Pi.string(),Pi.unknown()).optional()});async function qh(r){if(!_o){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await J(fetch(cv),{milliseconds:2e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let s=await o.json();e=dv.parse(s).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))Ii.valid(n)&&(!t||Ii.gt(n,t))&&Ii.gt(n,_o)&&Ii.lt(n,"2.0.0")&&(t=n);t&&(T.warn(`Update available: v${_o} -> v${t}`),T.warn("This version may be missing critical fixes, features, and security updates."),T.warn(`Run "npx momentic@${t} -V" to update`))}import{hostname as uv}from"os";var $=vi({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:uv(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0}).child({version:"1.0.21"});var jl=!1,gv=(()=>{try{return hv("/.dockerenv"),!0}catch{return!1}})();async function tt(r,e){if(Vh||jl||gv)return!0;$.flush(),await new Promise(i=>setTimeout(i,500));let t=Yh.createInterface({input:process.stdin,output:process.stdout}),n=r.split("."),o;if(n.length===1)o=r;else{let i=`${n.slice(0,n.length-1).join(".").trim()}.`;e?T.warn(i):T.log(i),o=n[n.length-1].trim()}let s=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),s==="A"?(jl=!0,setTimeout(()=>{jl=!1},3e3),!0):s.toLowerCase()==="y"}async function Hl(r){let e=fv(r);return No(e)?mv(r)?tt(`File '${Kh(r)}' already exists. Overwrite existing content?`,!0):!0:await tt(`Directory '${Kh(e)}' doesn't exist. Create it now?`,!0)?(pv(e,{recursive:!0}),!0):!1}function Kh(r){return r.replace(/(\s+)/g,"\\$1")}async function Xh(r){let e=Yh.createInterface({input:process.stdin,output:process.stdout}),t=await e.question(`${r} `);return e.close(),t.trim()}import{cloneDeep as yv}from"lodash-es";async function Oi({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=yv(t.config);o.environments||(o.environments=[]);for(let s of n){let i=o.environments?.find(a=>a.name===s.name);if(i)!e&&!await tt(`Environment ${s.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),i.baseUrl=s.variables[oe],delete s.variables[oe],i.envVariables=s.variables;else{let a=s.variables[oe];delete s.variables[oe],o.environments.push({name:s.name,baseUrl:a,envVariables:s.variables})}}An(o,t.configFilePath),T.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as Jh}from"crypto";import Zh from"fs";async function ef({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:s}=await e.getTestYAMLExport({paths:r,all:t}),i=0;for(let[l,c]of Object.entries(o)){let u=Qh(l,ne.TEST);!n&&!await Hl(u)||(i+=1,Zh.writeFileSync(u,c,"utf-8"),$.info({checksum:Jh("md5").update(c).digest("hex")},`Wrote '${u}'`))}let a=0;for(let[l,c]of Object.entries(s)){let u=Qh(l,ne.MODULE);!n&&!await Hl(u)||(a+=1,Zh.writeFileSync(u,c,"utf-8"),$.info({checksum:Jh("md5").update(c).digest("hex")},`Wrote '${u}'`))}i===0?T.success("Pulled 0 tests."):T.success(`Pulled ${i} test${i>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function Qh(r,e){switch(e){case ne.TEST:return`${ge(r)}.${Bt.TEST}`;case ne.MODULE:return`${ge(r)}.${Bt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function tf(r){let{project:e,client:t,skipPrompts:n}=r;T.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),T.info("Importing environments from Momentic Cloud."),T.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await tt("Are you sure you want to proceed?",!0)||(T.info("Aborting..."),process.exit(1)),await Oi({client:t,project:e,skipPrompts:n}),T.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.`),T.info("Importing tests and modules from Momentic Cloud."),await ef({testsToFetch:[],client:t,all:!0,yes:n}),T.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 rt from"fs";import Nr from"path";import Sv from"yaml";function rf(){No("momentic")||(T.error(`The migration command should be ran from the v0 root Momentic directory, which should contain a folder called 'momentic'. No folder named 'momentic' was found in the current working directory (${process.cwd()}).`),process.exit(1));let r={name:"default",include:Lo,environments:[]};T.info("Migrating environments");let e=nf(["momentic/environments"],wv);for(let n of e){let o=Sv.parse(rt.readFileSync(n,"utf-8"));try{let s=Xo.parse(o),i=s.variables[oe]??"";delete s.variables[oe],r.environments?.push({name:s.name,baseUrl:i,envVariables:s.variables})}catch(s){T.error(`${n} failed to parse as a valid environment file.`),T.error(s),process.exit(1)}}T.info("Migrating tests");let t=ll("./momentic",T);for(let n of t){let o=Nr.join(...n.fullPathSegments),s=Nr.join(Nr.dirname(o),`${n.fileName.slice(0,-5)}.test.yaml`);T.debug(`Moving test ${o} to ${s}`),rt.renameSync(o,s)}if(No("momentic/modules")){T.info("Migrating modules");for(let n of rt.readdirSync("./momentic/modules")){if(!n.endsWith(".yaml"))continue;let o=Nr.resolve(Nr.join("./momentic/modules",n));if(!rt.readFileSync(o,"utf-8").includes("schemaVersion")){T.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let i=`${o.slice(0,-5)}.module.yaml`;T.debug(`Moving module ${o} to ${i}`),rt.renameSync(o,i)}}return T.debug("Writing new project configuration file"),An(r,"momentic.config.yaml"),rt.rmSync("./momentic/environments",{recursive:!0,force:!0}),rt.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),T.success("Migration succeeded!"),T.info("Going forward:"),T.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),T.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),r}function nf(r,e,t=new Set){for(let n of r){let o=Nr.resolve(n),s=!1;try{s=rt.existsSync(o)&&rt.statSync(o).isDirectory()}catch(i){T.error({err:i},`Error reading path ${o} during collect paths`)}if(o&&s){let i=rt.readdirSync(o).map(a=>Nr.join(o,a));nf(i,e,t);continue}if(o.endsWith(".yaml")){try{if(!rt.existsSync(o)||!rt.statSync(o).isFile()){T.warn(`File not found or unreadable: ${o}`);continue}}catch(i){T.error({err:i},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function wv(r){return r.endsWith(".yaml")?rt.readFileSync(r,"utf8").includes("momentic/environment")?!0:(T.warn(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}import{Argument as Li,Option as le}from"@commander-js/extra-typings";import{validateHeaderValue as bv}from"http";import{cpus as of}from"os";import{parse as Tv}from"yaml";import{z as _}from"zod";var Mi=58888,Vl=30*60*1e3,_r=new le("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),Rn=new le("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),kr=new le("-y, --yes","Skip all confirmation prompts."),ql=new le("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),Kl=new le("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${Vl/1e3} seconds.`),Ni=new le("--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."),Yl=new le("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),sf=new le("--reporter <reporter>","Output report files in a standardized format to a local directory. See the --reporter-dir flag for information on the output directory.").choices(Object.values(ps)),af=new le("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml. Defaults to 'reports' if unset."),lf=new le("--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."),cf=new le("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Xl=new le("--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."),df=new le("--port <port>",`Port to run the app on. Defaults to ${Mi}.`),Jl=new le("--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."),_i=new le("--env <env>","Name of the environment to use when running tests."),ki=new le("--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."),uf=new le("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),ko=new le("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),mf=new le("-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."),pf=new le("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),hf=new Li("<tests...>",`One or more test paths to queue on Momentic Cloud.
|
|
1981
|
+
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return n[0]}function FC(r){let e=kC(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(s=>(s.endsWith("/")||(s+="/"),`${s}*${vn}`)),n=Cn(t,{absolute:!1,cwd:Ml(),dotRelative:!1,maxDepth:Ll,nodir:!0}),o=[];for(let s of n){let i=ur.join(Ml(),s),a=Nl(i);a&&o.push({configFilePath:i,config:a,rootDir:Ch(i)})}return o}function _l(r){if(r){r=ur.resolve(r);let t=Nl(r);if(!t)throw new Error("No valid Momentic project file available.");return[{config:t,configFilePath:r,rootDir:ur.dirname(r)}]}if(xC(Eh)){let t=FC(Eh);if(t)return t}return DC()}function An(r,e){let t=vh.stringify(r);PC(e,t)}var Dl="https://api.momentic.ai",xh,Rh=r=>{Dl=r},Mo=()=>Dl,Ih=r=>{xh=r},Te=()=>xh,xn,kl,Ph=async r=>{if(xn)return xn;let e=new Be({baseUrl:Dl,apiKey:r});try{return xn=await e.getOrgId(),kl=r,xn}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Ci=()=>{if(!xn)throw new Error("Your organization ID appears invalid. Please contact Momentic support.");return xn},Oh=()=>{if(!kl)throw new Error("Your API key appears invalid. Please contact Momentic support.");return kl};import Lh,{multistream as UC}from"pino";import $C from"pino-pretty";var Fl=new Map,BC=!0,Ul=class r{consoleLogger;ddClientToken;hostname;bindingAttributes;excludeAttributesInConsoleLogs;excludeTimestamps;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:n,excludeAttributesInConsoleLogs:o,excludeTimestamps:s,disableConsoleLogs:i}){this.ddClientToken=t,this.hostname=n,this.excludeAttributesInConsoleLogs=o,this.excludeTimestamps=s,this.disableConsoleLogs=i,this.bindingAttributes={...e,env:"production"};let a={base:o?{}:this.bindingAttributes,errorKey:"err",level:"debug",timestamp:!s};this.consoleLogger=BC?Lh(a):Lh(a,UC([{stream:$C({colorize:!0})}]))}child(e){return new r({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,excludeAttributesInConsoleLogs:this.excludeAttributesInConsoleLogs,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,n,...o){if(t&&n===void 0&&(n=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},n,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let i={};for(let a of Object.getOwnPropertyNames(t.err))i[a]=t.err[a];i.name=t.err.name,t.err=i}let s=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(s.args=o),(async()=>{try{let i=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,hostname:this.hostname??"vercel",service:"momentic",message:{message:n||"",...s,level:e}}])});if(!i.ok)throw new Error(`Failed to log to Datadog: ${i.statusText})}`)}catch(i){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:n,args:o,err:i},"Failed to log to Datadog")}})()}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},vi=({app:r,clientToken:e,hostname:t,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return Fl.has(r)||Fl.set(r,new Ul({bindings:{app:r},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})),Fl.get(r)};import{hostname as zC}from"os";var pe=vi({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:zC(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0}),Mh=r=>{pe.addBinding("version",r)};function Ae(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Nh=WC();Nh.get("/",Ae((r,e)=>{let t=Cp(Te(),pe);e.status(200).json(t)}));var _h=Nh;import{Router as jC}from"express";import kh from"fs";import Dh from"path";var Ai=jC();Ai.get("/",Ae(async(r,e)=>{let t=vt(Te(),T),o=(await bp(t,pe)).filter(s=>s.enabled??!0);e.status(200).json(o)}));Ai.post("/",Ae(async(r,e)=>{let t;try{t=Od.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}try{qn(t.name)}catch(i){e.status(400).json({error:`Invalid module name: ${i}`});return}let n=Te(),o=Dh.join(n.rootDir,n.config.moduleCreationDir??Dh.dirname(t.testFilePath));if(!kh.existsSync(o)||!kh.statSync(o).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${o}' does not exist.`});return}let s=await wp({...t,folder:o});e.status(201).json(s)}));Ai.get("/:moduleId",Ae(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=vt(Te(),T),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await al(n,t,T);e.json(o)}catch(o){e.status(400).json({err:o})}}));var Fh=Ai;import{Router as HC}from"express";var xi=HC();xi.get("/",Ae((r,e)=>{let t=_l().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));xi.get("/current",Ae((r,e)=>{let t=Te(),n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));xi.post("/set",Ae((r,e)=>{let t;try{t=Md.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Lr({configFilePath:t.configFilePath});Ih(n)}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var Uh=xi;import{Router as GC}from"express";import $l from"path";import{v4 as VC}from"uuid";var Mr=GC();Mr.get("/",Ae((r,e)=>{let t=Te(),n=vt(t,T),o=Array.from(Object.values(n.tests));e.status(200).json(o)}));Mr.post("/",Ae(async(r,e)=>{let t;try{t=Pd.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{qn(t.name)}catch(c){e.status(400).json({error:c.message});return}let o={id:VC(),name:t.name,baseUrl:t.baseUrl,schemaVersion:ct,advanced:{disableAICaching:!1,browserType:t.browserType??"Chromium",viewport:t.viewport??Ut},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let s=Te(),i=$l.join(s.rootDir,s.config.testCreationDir??""),a=await Tp({test:o,name:t.name,folder:i}),l={...o,relativeFilePath:$l.relative(s.rootDir,a)};e.status(201).json(l)}));Mr.get("/:testPath",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=Te(),o=vt(n,T),s;try{s=await ni($l.join(n.rootDir,t),pe,o),e.status(200).json(s)}catch(i){e.status(400).send({error:i.message});return}(async()=>{try{let{stepsToSave:i,moduleUpdates:a}=await gt({steps:s.steps});a.forEach(l=>{il(l.moduleId,{...l,schemaVersion:ct},o)}),po(t,{schemaVersion:ct,steps:i},n)}catch(i){pe.error({err:i},"Failed to save migrated test to disk after initial fetch")}})()}));Mr.patch("/:testPath/metadata",Ae(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Id.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}po(r.params.testPath,t,Te()),e.status(201).json({message:"ok"})}));Mr.patch("/:testPath",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Rd.parse(r.body)}catch(d){e.status(400).json({error:`Invalid request body: ${d}`});return}let o=Te(),s=vt(o,T),i;try{i=ri(t,o)}catch(d){e.status(400).json({error:`Existing test file on disk is invalid: ${d}`});return}let{stepsToSave:a,moduleUpdates:l,cachesToSave:c}=await gt({steps:n.steps,cacheCreationParams:{testId:i.id,orgId:Ci()}});await new Be({apiKey:Oh(),baseUrl:Mo()}).updateStepCaches({entries:c,testId:i.id}),l.forEach(d=>{il(d.moduleId,{...d,schemaVersion:n.schemaVersion},s)}),po(t,{steps:a,schemaVersion:n.schemaVersion},o),e.status(201).json({message:"ok"})}));Mr.patch("/:testPath/environments",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Ld.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}po(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},Te()),e.status(201).json({message:"ok"})}));var $h=Mr;var Ri=class extends en{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async getOrgId(t){return this.orgId}async fetchTestMetadata(t,n,o){let s=Te(),a=vt(s,o).tests[t];if(a)return ri(a.relativePath,s)}async fetchEnvironment(t,n,o){let s=Te();return ho(n,s,o)}};async function jh(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,appPort:o,staticDir:s,devicePixelRatio:i,version:a}=r;Mh(a),e&&Rh(e),pe.debug(r,"Initializing desktop server");let l=await Ph(t);pe.debug({orgId:l},"Checking API key successful");let u=`http://localhost:${n}`;o&&(u=`http://localhost:${o}`);let d=ZC(s);await new Promise(y=>{d.listen(n,()=>{pe.info(`Server is running at http://localhost:${n}`),y()})});let p=new mn({baseURL:Mo(),apiKey:t}),h={type:"API_KEY",baseUrl:Mo(),apiKey:t},f=new Be(h),g=new Ri(f,Ci());Sp({baseServer:d,generator:p,storage:g,logger:pe,devicePixelRatio:i,authorization:h}),await JC(u)}var Wh="25mb";function ZC(r){let e=zh();e.use(qC()),e.use(Bh.json({limit:Wh})),e.use(Bh.urlencoded({extended:!1,limit:Wh}));let t=YC();if(t.use("/tests",$h),t.use("/modules",Fh),t.use("/environments",_h),t.use("/projects",Uh),e.use("/api",t),e.use((o,s,i)=>{o.path!=="/healthcheck"&&pe.debug({url:o.url,path:o.path,query:o.query,method:o.method,body:o.body,headers:o.rawHeaders,client:o.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&pe.error({url:o.url,method:o.method,statusCode:s.statusCode},"Request completed in error")}),i()}),e.use((o,s,i,a)=>{if(o instanceof Error&&o.message.includes("BadRequestError: request aborted")){i.status(400).send("Client disconnected");return}pe.error({stack:o.stack,msg:o.message,err:o,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),T.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${o.message}`),i.status(500).send("Internal Server Error")}),r){let o=zh.static(r);e.use("/",o),e.use("*",o)}return XC.createServer(e)}KC.setMaxListeners(50);process.on("warning",r=>{pe.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{pe.error({err:r},"Uncaught exception leading to exit on desktop-server")});process.on("unhandledRejection",(r,e)=>{pe.error({reason:`${r}`,promise:`${e}`,stack:r?.stack},"Uncaught exception leading to exit on desktop-server (promise rejection)")});import Kv from"events";import kf from"fs";import ji from"path";import{fileURLToPath as Yv}from"url";import{existsSync as mv,mkdirSync as pv,statSync as hv}from"fs";import{dirname as fv}from"path";import Yh from"readline/promises";import{execSync as QC}from"child_process";import{platform as ev}from"os";function Bl(){return Hh()?(T.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),T.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),T.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(T.info("Setting device pixel ratio to 1."),T.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),T.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function Hh(){return ev()==="darwin"&&QC("system_profiler SPDisplaysDataType").toString().includes("Retina")}function zl(r){Hh()&&r===1&&(T.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),T.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import tv from"@actions/exec";import rv from"@actions/io";import nv from"quote";import ov from"string-argv";async function Gh(r,e=!0){let t=ov(r),n=await rv.which(t[0],!0),o=t.slice(1),s=tv.exec(nv(n),o,{delay:100});if(e)return s}import{existsSync as sv,statSync as iv}from"fs";var Vh=!!process.env.CI||!process.stdout.isTTY;function No(r){try{return sv(r)&&iv(r).isDirectory()}catch(e){return T.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import av from"csv-parser";import{createReadStream as lv}from"fs";function Wl(r){return new Promise((e,t)=>{let n=[];lv(r).pipe(av()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import Ii from"semver";import{z as Pi}from"zod";var _o="1.0.22",cv="https://registry.npmjs.org/momentic",dv=Pi.object({versions:Pi.record(Pi.string(),Pi.unknown()).optional()});async function qh(r){if(!_o){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await J(fetch(cv),{milliseconds:2e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let s=await o.json();e=dv.parse(s).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))Ii.valid(n)&&(!t||Ii.gt(n,t))&&Ii.gt(n,_o)&&Ii.lt(n,"2.0.0")&&(t=n);t&&(T.warn(`Update available: v${_o} -> v${t}`),T.warn("This version may be missing critical fixes, features, and security updates."),T.warn(`Run "npx momentic@${t} -V" to update`))}import{hostname as uv}from"os";var $=vi({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:uv(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0}).child({version:"1.0.22"});var jl=!1,gv=(()=>{try{return hv("/.dockerenv"),!0}catch{return!1}})();async function tt(r,e){if(Vh||jl||gv)return!0;$.flush(),await new Promise(i=>setTimeout(i,500));let t=Yh.createInterface({input:process.stdin,output:process.stdout}),n=r.split("."),o;if(n.length===1)o=r;else{let i=`${n.slice(0,n.length-1).join(".").trim()}.`;e?T.warn(i):T.log(i),o=n[n.length-1].trim()}let s=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),s==="A"?(jl=!0,setTimeout(()=>{jl=!1},3e3),!0):s.toLowerCase()==="y"}async function Hl(r){let e=fv(r);return No(e)?mv(r)?tt(`File '${Kh(r)}' already exists. Overwrite existing content?`,!0):!0:await tt(`Directory '${Kh(e)}' doesn't exist. Create it now?`,!0)?(pv(e,{recursive:!0}),!0):!1}function Kh(r){return r.replace(/(\s+)/g,"\\$1")}async function Xh(r){let e=Yh.createInterface({input:process.stdin,output:process.stdout}),t=await e.question(`${r} `);return e.close(),t.trim()}import{cloneDeep as yv}from"lodash-es";async function Oi({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=yv(t.config);o.environments||(o.environments=[]);for(let s of n){let i=o.environments?.find(a=>a.name===s.name);if(i)!e&&!await tt(`Environment ${s.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),i.baseUrl=s.variables[oe],delete s.variables[oe],i.envVariables=s.variables;else{let a=s.variables[oe];delete s.variables[oe],o.environments.push({name:s.name,baseUrl:a,envVariables:s.variables})}}An(o,t.configFilePath),T.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as Jh}from"crypto";import Zh from"fs";async function ef({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:s}=await e.getTestYAMLExport({paths:r,all:t}),i=0;for(let[l,c]of Object.entries(o)){let u=Qh(l,ne.TEST);!n&&!await Hl(u)||(i+=1,Zh.writeFileSync(u,c,"utf-8"),$.info({checksum:Jh("md5").update(c).digest("hex")},`Wrote '${u}'`))}let a=0;for(let[l,c]of Object.entries(s)){let u=Qh(l,ne.MODULE);!n&&!await Hl(u)||(a+=1,Zh.writeFileSync(u,c,"utf-8"),$.info({checksum:Jh("md5").update(c).digest("hex")},`Wrote '${u}'`))}i===0?T.success("Pulled 0 tests."):T.success(`Pulled ${i} test${i>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function Qh(r,e){switch(e){case ne.TEST:return`${ge(r)}.${Bt.TEST}`;case ne.MODULE:return`${ge(r)}.${Bt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function tf(r){let{project:e,client:t,skipPrompts:n}=r;T.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),T.info("Importing environments from Momentic Cloud."),T.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await tt("Are you sure you want to proceed?",!0)||(T.info("Aborting..."),process.exit(1)),await Oi({client:t,project:e,skipPrompts:n}),T.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.`),T.info("Importing tests and modules from Momentic Cloud."),await ef({testsToFetch:[],client:t,all:!0,yes:n}),T.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 rt from"fs";import Nr from"path";import Sv from"yaml";function rf(){No("momentic")||(T.error(`The migration command should be ran from the v0 root Momentic directory, which should contain a folder called 'momentic'. No folder named 'momentic' was found in the current working directory (${process.cwd()}).`),process.exit(1));let r={name:"default",include:Lo,environments:[]};T.info("Migrating environments");let e=nf(["momentic/environments"],wv);for(let n of e){let o=Sv.parse(rt.readFileSync(n,"utf-8"));try{let s=Xo.parse(o),i=s.variables[oe]??"";delete s.variables[oe],r.environments?.push({name:s.name,baseUrl:i,envVariables:s.variables})}catch(s){T.error(`${n} failed to parse as a valid environment file.`),T.error(s),process.exit(1)}}T.info("Migrating tests");let t=ll("./momentic",T);for(let n of t){let o=Nr.join(...n.fullPathSegments),s=Nr.join(Nr.dirname(o),`${n.fileName.slice(0,-5)}.test.yaml`);T.debug(`Moving test ${o} to ${s}`),rt.renameSync(o,s)}if(No("momentic/modules")){T.info("Migrating modules");for(let n of rt.readdirSync("./momentic/modules")){if(!n.endsWith(".yaml"))continue;let o=Nr.resolve(Nr.join("./momentic/modules",n));if(!rt.readFileSync(o,"utf-8").includes("schemaVersion")){T.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let i=`${o.slice(0,-5)}.module.yaml`;T.debug(`Moving module ${o} to ${i}`),rt.renameSync(o,i)}}return T.debug("Writing new project configuration file"),An(r,"momentic.config.yaml"),rt.rmSync("./momentic/environments",{recursive:!0,force:!0}),rt.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),T.success("Migration succeeded!"),T.info("Going forward:"),T.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),T.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),r}function nf(r,e,t=new Set){for(let n of r){let o=Nr.resolve(n),s=!1;try{s=rt.existsSync(o)&&rt.statSync(o).isDirectory()}catch(i){T.error({err:i},`Error reading path ${o} during collect paths`)}if(o&&s){let i=rt.readdirSync(o).map(a=>Nr.join(o,a));nf(i,e,t);continue}if(o.endsWith(".yaml")){try{if(!rt.existsSync(o)||!rt.statSync(o).isFile()){T.warn(`File not found or unreadable: ${o}`);continue}}catch(i){T.error({err:i},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function wv(r){return r.endsWith(".yaml")?rt.readFileSync(r,"utf8").includes("momentic/environment")?!0:(T.warn(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}import{Argument as Li,Option as le}from"@commander-js/extra-typings";import{validateHeaderValue as bv}from"http";import{cpus as of}from"os";import{parse as Tv}from"yaml";import{z as _}from"zod";var Mi=58888,Vl=30*60*1e3,_r=new le("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),Rn=new le("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),kr=new le("-y, --yes","Skip all confirmation prompts."),ql=new le("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),Kl=new le("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${Vl/1e3} seconds.`),Ni=new le("--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."),Yl=new le("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),sf=new le("--reporter <reporter>","Output report files in a standardized format to a local directory. See the --reporter-dir flag for information on the output directory.").choices(Object.values(ps)),af=new le("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml. Defaults to 'reports' if unset."),lf=new le("--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."),cf=new le("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Xl=new le("--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."),df=new le("--port <port>",`Port to run the app on. Defaults to ${Mi}.`),Jl=new le("--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."),_i=new le("--env <env>","Name of the environment to use when running tests."),ki=new le("--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."),uf=new le("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),ko=new le("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),mf=new le("-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."),pf=new le("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),hf=new Li("<tests...>",`One or more test paths to queue on Momentic Cloud.
|
|
1982
1982
|
|
|
1983
1983
|
A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic@latest pull hello-world'.`),ff=new Li("<tests...>","One or more test file path or folders that exist on the local machine: 'npx momentic@latest run hello-world.test.yaml'.").argOptional(),gf=new Li("<suites...>",`One or more suite paths that exist on Momentic Cloud.
|
|
1984
1984
|
|
|
@@ -1994,4 +1994,4 @@ ${r.map(c=>` - ${c}`).join(`
|
|
|
1994
1994
|
`)}`),Object.values(e.tests).forEach(c=>{r.some(u=>c.relativePath.includes(u))&&i.add(c.fullFilePath)}))}else{!n&&!await tt("No test paths or substrings were provided. Do you want to run all tests?")&&(T.error("Cancelled by user."),process.exit(1));let a=Object.values(e.tests);T.info(`Reading all ${a.length} tests in the project from local disk.`),a.forEach(l=>{i.add(l.fullFilePath)})}for(let a of i){let l=Pf.relative(t.rootDir,a);o&&!o.some(c=>new RegExp(c).test(l))&&i.delete(a),s&&s.some(c=>new RegExp(c).test(l))&&i.delete(a)}return i}import{diff as Uv}from"deep-object-diff";import{cloneDeep as Lf}from"lodash-es";import $v from"semver";import{debounce as Bv}from"ts-debounce";import{v4 as Mf}from"uuid";var Wi=class extends ue{async runTemplateMatching(e){let t=await this.sendRequest(`/${ue.API_VERSION}/web-agent/template-matching`,e);return fs.parse(t)}};async function Nf(r){let e=new Date,{fullFilePath:t,momenticFiles:n}=r,o;try{o=await ni(t,$,n)}catch(s){T.error(`Failed to read and resolve test at '${t}': ${s}`),process.exit(1)}$v.gt(o.schemaVersion,ct)&&T.warn(`Test ${t} has schema version ${o.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`);try{return await zv(o,r)}catch(s){return T.error(`Fatal error running test: ${s.message}`),{parameters:r,failureReason:"UnknownError",failureDetails:{errorMessage:s.message,errorStack:s.stack},status:"FAILED",attempts:0,test:o,filePath:t,startedAt:e,finishedAt:new Date}}}async function zv(r,{fullFilePath:e,project:t,apiClient:n,generator:o,orgId:s,retriesOverride:i,noReport:a,envName:l,urlOverride:c,devicePixelRatio:u,customHeaders:d,testInputs:m}){let p=new Date,h={envName:l,urlOverride:c,customHeaders:d,testInputs:m},f=new en(n,s);try{await f.resolveStepCacheEntries({organizationId:s,testId:r.id,steps:r.steps,schemaVersion:r.schemaVersion,logger:$})}catch(x){throw $.error({err:x},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is an error, please contact Momentic Support with the following error: ${x}`)}if(!l){for(let x of r.envs??[])if(x.default){l=x.name;break}}let g,y={};if(l){try{g=ho(l,t,$)}catch(x){let j=`Failed to resolve environment ${l} for test ${r.name}: ${x}`;throw new Error(j)}y=g.variables}let S=r.baseUrl;if(c)S=c;else if(!S){let x=y[oe];typeof x=="string"&&(S=x)}if(!S){let x=`Cannot run test with no base URL and no ${oe} variable defined in its environment`;throw new Error(x)}let w;if(a)w=Mf();else try{w=(await n.createRun({testId:r.id,testName:r.name,trigger:"CLI",resolvedBaseUrl:S,schemaVersion:r.schemaVersion})).id}catch(x){throw $.error({err:x,testId:r.id},"Error creating run on Momentic Cloud"),new Error(`Error creating run on Momentic Cloud. Please ensure Momentic is accessible from your environment.
|
|
1995
1995
|
If you believe this is an error, please contact Momentic Support with the following error message: ${x}`)}let E=$.child({testId:r.id,runId:w}),C=async x=>{if(!a)try{await n.updateRun(w,x)}catch(j){E.warn({err:j},`Failed to update run status for test ${w}. You may see stale data on the Momentic Cloud Server.`)}},A,I=Math.max(i??r.retries,0),O=[];for(let x=0;x<=I;x++){let j=Mf();if(!a)try{j=(await n.createRunAttempt(w)).id}catch(P){throw $.error({err:P,testId:r.id,runId:w},"Error creating run attempt on Momentic Cloud"),new Error("Error creating run attempt on Momentic Cloud. Please ensure Momentic is accessible from your environment or pass the --no-report flag.")}let H=async P=>{if(!a)try{await n.updateRunAttempt(w,j,P)}catch(xe){E.warn({err:xe},`Failed to update run attempt for attempt ${j}. You may see stale data on the Momentic Cloud Server.`)}};try{await C({status:"RUNNING",attempts:x+1});let{controller:P,context:xe}=await Wv({baseUrl:S,envName:l,apiClient:n,devicePixelRatio:u,logger:E,storageClient:f,test:r,generator:o,orgId:s,variables:y,customHeaders:d,testInputs:m,localBrowserConfigFromEnv:g?.browser});if(A=await jv({logger:E,storageClient:f,apiClient:n,test:r,orgId:s,runId:w,context:xe,controller:P,noReport:a}),await H({status:A.status,finishedAt:new Date}),O.unshift(A.status),A.status!=="FAILED")return await C({status:A.status,finishedAt:new Date,flake:sd(O)}),{...A,parameters:h,runId:w,test:r,filePath:e,startedAt:p,finishedAt:new Date,attempts:x+1,baseUrl:S};let Re=A.failedStepResult,Dt=Re?.message||"Unknown failure";if(x<I){E.warn({errResult:Re},`Test '${r.name}' failed attempt ${x+1} of ${I+1}, retrying...`);continue}E.error({errResult:Re},`Test '${r.name}' failed after all exhausting ${I+1} attempts: ${Dt}
|
|
1996
1996
|
`),await C({status:"FAILED",failureReason:Re?.failureReason,finishedAt:new Date});let pr={errorMessage:Dt},L=Re?.failureReason??ud(Dt)??"UnknownError";return await C({status:"FAILED",finishedAt:new Date,failureDetails:pr,failureReason:L}),{...A,parameters:h,runId:w,failureDetails:pr,failureReason:L,test:r,filePath:e,startedAt:p,finishedAt:new Date,attempts:x+1,baseUrl:S}}catch(P){E.error({err:P},`Encountered fatal platform error while running test '${r.name}': ${P}`);let xe={errorMessage:P.message,errStack:P.stack},Re={status:"FAILED",failureDetails:xe,failureReason:"UnknownError",finishedAt:new Date};return await Promise.all([H(Re),C(Re)]),{...Re,parameters:h,runId:w,test:r,filePath:e,startedAt:p,finishedAt:new Date,attempts:x+1,baseUrl:S}}}throw new Error("This code should not be reachable")}async function Wv({baseUrl:r,envName:e,devicePixelRatio:t,apiClient:n,test:o,storageClient:s,generator:i,orgId:a,variables:l,logger:c,customHeaders:u,testInputs:d,localBrowserConfigFromEnv:m}){let p={...m,...Kn.parse(o.advanced)};u&&(p.extraHeaders={...p.extraHeaders??{},...u});let h=await Gt.init({baseUrl:r,logger:c,userBrowserSettings:p,storage:s,enricher:new Wi({baseURL:n.baseUrl,apiKey:n.apiKey}),timeout:p.pageLoadTimeoutMs,contextArgs:{viewport:o.advanced.viewport??Ut,deviceScaleFactor:t}}),f=new yt({httpClient:new Ze({baseUrl:n.baseUrl,apiKey:n.apiKey})}),g=new un({browser:h,generator:i,config:Zs,logger:c,orgId:a,storage:s,flagStore:await an.init(a),localCodeEvalTools:f}),y=new Ve({baseUrl:r,currentUrl:g.browser.url(),variablesFromEnvironment:l,envName:e});return o.parameters&&await Promise.all(o.parameters.map(async S=>{let{name:w,defaultValue:E,required:C}=S,A=d?.[w];C&&A===void 0&&(T.error(`Required parameter '${w}' is required by test '${o.name}' but not provided`),process.exit(1));let I=await St({orgId:a,s:A??E,localTools:f,logger:c,context:Ve.dummyContext(y.getEnvName())});y.setMomenticSystemVariable(w,I)})),{controller:g,context:y}}async function jv({storageClient:r,apiClient:e,test:t,orgId:n,runId:o,context:s,controller:i,noReport:a,logger:l}){$.info(`Running test '${t.name}' locally${a?"":` and reporting results to https://app.momentic.ai/runs/${o}`}`);let c=Lf(t.steps),u=async w=>{try{if(w.results){let E=Lf(w.results);Cs(E,$),w.results=E}await e.updateRun(o,w)}catch(E){l.warn({err:E},"Failed to update run data. You may see stale data on the Momentic Cloud Server.")}},d,m=Bv(async w=>{a||await u(w)},1e4,{maxWait:3e4}),p=new yt({httpClient:new Ze({baseUrl:e.baseUrl,apiKey:e.apiKey})}),h={controller:i,storage:r,context:s,logger:l,codeEvalTools:p},f={orgId:n,runId:o,testMetadata:t,steps:t.steps},S=await Ds({fixtures:h,inputs:f,options:{takeScreenshots:!0,consumeDebuggingData:!0,reinitializeBrowser:!0},callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()},onSaveScreenshot:async w=>{if(a)return"";let{key:E}=await e.uploadScreenshot({screenshot:w.toString("base64")});return E},onUpdateRun:w=>{d=Promise.resolve(m(w))},onProposedTestSteps:async w=>e.uploadProposedSteps(w,l),onTestSuccess:async w=>{let E=Uv(c,w);if(Object.keys(E).length===0){l.debug("No changes to test steps after success");return}l.debug({changes:E},"Updating steps post-run success in worker");try{let{cachesToSave:C}=await gt({steps:w,cacheCreationParams:{testId:t.id,orgId:n}});await e.updateStepCaches({testId:t.id,entries:C})}catch(C){l.error({err:C},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}}});return d&&(l.info("Waiting for last run update to finish"),await Promise.resolve(d)),S}async function _f(r){let{tests:e,yes:t,start:n,waitOn:o,client:s,project:i,report:a,retriesOverride:l,urlOverride:c,envName:u,orgId:d,devicePixelRatio:m,customHeaders:p,testInputMatrix:h,reporter:f,include:g,exclude:y,reporterDir:S="reports",waitOnTimeout:w=60,parallel:E=1,shardIndex:C=1,shardCount:A=1}=r;n&&($.info({orgId:d},`Executing start command: ${n}`),await Gh(n,!1)),o&&($.info({orgId:d},`Waiting for url: ${o} with timeout: ${w} seconds.`),await Hv({resources:[o],interval:2500,timeout:w*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let I=new mn({baseURL:s.baseUrl,apiKey:s.apiKey}),O=vt(i,T),x=await Of({tests:e,momenticFiles:O,yes:t,project:i,include:g,exclude:y}),j=Array.from(x),H=[];j.forEach((L,Fe)=>{h?h.forEach((Ft,Fr)=>{H.push({path:L,testIndex:Fe,inputs:Ft,inputIndex:Fr})}):H.push({path:L,testIndex:Fe,inputs:void 0,inputIndex:void 0})}),A&&A>1&&(H=Gv(H,C,A)),$.info({allTestsToRunWithInputs:H,shardCount:A,shardIndex:C,orgId:d},`Running ${H.length} tests with ${E} workers`),T.dimmed(`Running ${H.length} tests with ${E} workers:`),H.forEach(L=>{T.dimmed(` ${L.path}${typeof L.inputIndex=="number"?` with input set ${L.inputIndex}`:""}`)}),T.log("");let P=[],xe=Date.now(),Re=new Set;for(let L=0;L<H.length;L+=E){let Fe=await Promise.all(H.slice(L,L+E).map(async({path:Ft,inputs:Fr})=>{Re.add({path:Ft,inputs:Fr});let k=()=>{T.log(`${Re.size}/${H.length} ${Ft}`)};k();let Ff=setInterval(k,60*1e3);try{return await Nf({fullFilePath:Ft,momenticFiles:O,project:i,testInputs:Fr,orgId:d,devicePixelRatio:m,apiClient:s,generator:I,retriesOverride:l,urlOverride:c,envName:u,noReport:!a,customHeaders:p})}finally{clearInterval(Ff)}}));P.push(...Fe)}let Dt=s.getAppUrl(),pr=In({results:P,startTime:xe,onFailed:L=>{Bi(L,L.filePath)},getDisplayLine:L=>{let Fe=` ${L.filePath}`;return a&&L.runId&&(Fe+=` (${Dt}/runs/${L.runId})`),Fe},entity:"test"});return f&&await If(f,{suiteName:`on-demand-suite-${xe}`,startedAt:new Date(xe),finishedAt:new Date,runs:P},S??"reports"),pr}function Gv(r,e,t){if(t>r.length&&(T.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.toSorted().filter((s,i)=>i>=n&&i<o)}await qh($);var ht=new Vv;ht.name("momentic").description("Momentic CLI").version(_o||"unknown");ht.command("install-browsers").action(async()=>{await Fi()});ht.addOption(new mr("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{$.setMinLevel(r.toLowerCase()),T.setMinLevel(r.toLowerCase())});ht.addOption(new mr("--verbose","enable verbose logging")).on("option:verbose",()=>{$.enableConsoleLogs()});ht.command("check-config").addOption(ko).action(async r=>{Lr({configFilePath:r.config})});var Xv=ht.command("migrate").description("Migrate and upgrade tooling");Xv.command("v0-v1").addOption(kr).addOption(_r).action(async r=>{let e=await Dr(r);if(!e.yes&&!await tt("This command will migrate and then delete your previous Momentic files. All members of your team should transition to the V1 CLI at the same time. Please backup your local directory for safety before proceeding. Continue?",!0)&&process.exit(1),!rf().environments?.length&&await tt("In the V1 CLI, all environment configuration should be committed to a central `momentic.config.yaml` file, which you should commit to your source control repository. Sensitive data can be managed through `.env` files or by injecting the secret into the environment and then referencing them in `envVariables` with ${VAR} syntax. Would you like to pull the latest environments from Momentic Cloud into your `momentic.config.yaml` file?",!0)){let{apiKey:n,server:o}=e,s=Lr({}),i=new Be({baseUrl:o,apiKey:n,logger:$});await Oi({client:i,project:s,skipPrompts:e.yes}),T.success("Successfully imported environments from Momentic Cloud.")}});ht.command("import-from-cloud").addOption(_r).addOption(Rn).addOption(ko).addOption(kr).action(async r=>{let e=await Dr(r),{apiKey:t,server:n,config:o,yes:s}=e,i=Lr({configFilePath:o}),a=new Be({baseUrl:n,apiKey:t,logger:$});await tf({client:a,project:i,skipPrompts:s}),process.exit(0)});ht.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new mr("--name <name>","Name of the project")).action(async r=>{T.info(`Welcome to the Momentic project setup wizard! \u{1F680}
|
|
1997
|
-
`),T.info("This wizard will help you bootstrap a new Momentic project. If need to import existing assets from Momentic Cloud, you can call the 'import-from-cloud' command after initialization."),kf.existsSync(vn)&&(T.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:r.name??(await Xh("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):")||"app"),include:Lo};An(t,vn),T.success(`Initialized Momentic project file at ${ji.resolve(vn)}`)});ht.command("app").addOption(_r).addOption(Rn).addOption(kr).addOption(Xl).addOption(df).addOption(ko).action(async r=>{let e=await Dr(r),{apiKey:t,port:n=Mi,yes:o,server:s,pixelRatio:i}=e,a=new Be({baseUrl:s,apiKey:t,logger:$}),l=await Ql({client:a,skipPrompts:o,installBrowsers:!0});ln.capture({event:"local app started",distinctId:l,properties:{organizationId:l}});let c=Yv(import.meta.url),u=ji.dirname(c),d=ji.resolve(u,"..","static"),m=ji.resolve(u,"..","assets"),p=i??Bl();zl(p),await jh({momenticServerUrl:s,apiKey:t,serverPort:n,appPort:n,staticDir:d,assetsDir:m,devicePixelRatio:p,version:"1.0.
|
|
1997
|
+
`),T.info("This wizard will help you bootstrap a new Momentic project. If need to import existing assets from Momentic Cloud, you can call the 'import-from-cloud' command after initialization."),kf.existsSync(vn)&&(T.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:r.name??(await Xh("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):")||"app"),include:Lo};An(t,vn),T.success(`Initialized Momentic project file at ${ji.resolve(vn)}`)});ht.command("app").addOption(_r).addOption(Rn).addOption(kr).addOption(Xl).addOption(df).addOption(ko).action(async r=>{let e=await Dr(r),{apiKey:t,port:n=Mi,yes:o,server:s,pixelRatio:i}=e,a=new Be({baseUrl:s,apiKey:t,logger:$}),l=await Ql({client:a,skipPrompts:o,installBrowsers:!0});ln.capture({event:"local app started",distinctId:l,properties:{organizationId:l}});let c=Yv(import.meta.url),u=ji.dirname(c),d=ji.resolve(u,"..","static"),m=ji.resolve(u,"..","assets"),p=i??Bl();zl(p),await jh({momenticServerUrl:s,apiKey:t,serverPort:n,appPort:n,staticDir:d,assetsDir:m,devicePixelRatio:p,version:"1.0.22"})});var Df=ht.command("queue").description("Queue tests or suites to run on Momentic Cloud");Df.command("suites").description("Run one or more suites on Momentic Cloud").addOption(_r).addOption(Rn).addOption(ql).addOption(Kl).addOption(kr).addArgument(gf).addOption(ki).addOption(_i).addOption(Ni).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeout:s,env:i,urlOverride:a,customHeaders:l}=await Dr(e),c=new Be({baseUrl:n,apiKey:t,logger:$});(!r||!Array.isArray(r)||!r.length)&&(T.error("Must pass at least one suite to run."),process.exit(1));let u=await c.getOrgId();ln.capture({event:"queue suites remotely",distinctId:u,properties:{organizationId:u,numSuites:r.length}}),await Tf({client:c,orgId:u,wait:o,suitePaths:r,waitTimeout:s,env:i,urlOverride:a,customHeaders:Di(l)})});Df.command("tests").description("Run one or more tests on Momentic Cloud").addOption(_r).addOption(Rn).addOption(kr).addOption(Ni).addOption(Jl).addOption(ki).addOption(_i).addOption(ql).addOption(Kl).addArgument(hf).action(async(r,e)=>{let t=await Dr(e),{all:n,apiKey:o,customHeaders:s,env:i,server:a,inputCsv:l,urlOverride:c,wait:u,waitTimeout:d,yes:m}=t,p=Di(s);for(let y of r)(y.endsWith(".yaml")||kf.existsSync(y))&&T.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let h=new Be({baseUrl:a,apiKey:o,logger:$}),f=await h.getOrgId();ln.capture({event:"queue tests remotely",distinctId:f,properties:{organizationId:f,numTests:r.length}});let g;l&&(g=await Wl(l)),await Ef({client:h,orgId:f,tests:r,all:n,customHeaders:p,env:i,urlOverride:c,wait:u,waitTimeout:d,testInputMatrix:g,yes:m}),process.exit(0)});var Jv=ht.command("run").alias("test").description("Run tests on the local machine");Jv.addOption(_r).addOption(Rn).addOption(ko).addOption(mf).addOption(kr).addOption(Ni).addOption(Jl).addOption(_i).addOption(ki).addOption(Yl).addOption(Xl).addOption(new mr("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new mr("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new mr("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new mr("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new mr("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(Yl).addOption(sf).addOption(af).addOption(uf).addOption(pf).addOption(lf).addOption(cf).addArgument(ff).action(async(r,e)=>{let t=await Dr(e),n=Di(t.customHeaders),o=Lr({configFilePath:t.config,nameFilter:t.filter}),s=new Be({baseUrl:t.server,apiKey:t.apiKey,logger:$}),i;t.inputCsv&&(i=await Wl(t.inputCsv));let a=await Ql({client:s,skipPrompts:t.yes,installBrowsers:!0});ln.capture({event:"run tests locally",distinctId:a,properties:{organizationId:a}});let l=t.pixelRatio??Bl();zl(l);try{(await _f({...t,retriesOverride:t.retries,devicePixelRatio:l,tests:r,project:o,client:s,customHeaders:n,envName:t.env,orgId:a,testInputMatrix:i})).failed>0?process.exit(1):process.exit(0)}catch(c){T.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),T.error(c),process.exit(1)}});async function Zv(){try{await ht.parseAsync(process.argv)}catch(r){let e={};try{e.playwrightVersion=qv("npx playwright --version").toString()}catch(t){$.error({err:t},"Error fetching debug information")}$.error({err:r,debugInfo:e},"Uncaught error in CLI"),$.flush(),T.error(r),process.exit(1)}}Kv.setMaxListeners(50);process.on("warning",r=>{$.warn({err:r},`Node warning received on CLI: ${r.message}`)});Zv();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "momentic",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.22",
|
|
4
4
|
"bin": {
|
|
5
5
|
"momentic": "./bin/cli.js"
|
|
6
6
|
},
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"@actions/exec": "^1.1.1",
|
|
12
12
|
"@actions/io": "^1.1.3",
|
|
13
13
|
"@commander-js/extra-typings": "^11.1.0",
|
|
14
|
-
"@dotenvx/dotenvx": "
|
|
14
|
+
"@dotenvx/dotenvx": "1.14.2",
|
|
15
15
|
"@exodus/schemasafe": "^1.3.0",
|
|
16
16
|
"@faker-js/faker": "^8.4.1",
|
|
17
17
|
"@octokit/auth-app": "^7.1.0",
|