From 02b973517fb0a6691312162a30c9a4be31fa0a51 Mon Sep 17 00:00:00 2001 From: Nathan Randall Date: Tue, 15 Jul 2025 15:11:38 -0600 Subject: [PATCH 01/11] Setup CDS extractor esbuild JS bundle Changes the build process for the CDS extractor to produce `dist/cds-extractor.bundle.js` and `dist/cds-extractor.bundle.js.map` files instead of a pair of `.js` and `.js.map` files for every compiled `.ts` file. Allows for pre-build of the JavaScript code used to run the CDS extractor while committing the bare minimum number of files for the "distribution" of the build. --- extractors/cds/tools/.gitignore | 4 + .../cds/tools/dist/cds-extractor.bundle.js | 23 + .../tools/dist/cds-extractor.bundle.js.map | 7 + extractors/cds/tools/esbuild.config.mjs | 80 ++++ extractors/cds/tools/eslint.config.mjs | 12 +- extractors/cds/tools/index-files.cmd | 68 +-- extractors/cds/tools/index-files.sh | 67 +-- extractors/cds/tools/package-lock.json | 431 ++++++++++++++++++ extractors/cds/tools/package.json | 9 +- extractors/cds/tools/tsconfig.json | 3 + extractors/cds/tools/validate-bundle.js | 75 +++ 11 files changed, 669 insertions(+), 110 deletions(-) create mode 100644 extractors/cds/tools/.gitignore create mode 100644 extractors/cds/tools/dist/cds-extractor.bundle.js create mode 100644 extractors/cds/tools/dist/cds-extractor.bundle.js.map create mode 100644 extractors/cds/tools/esbuild.config.mjs create mode 100644 extractors/cds/tools/validate-bundle.js diff --git a/extractors/cds/tools/.gitignore b/extractors/cds/tools/.gitignore new file mode 100644 index 000000000..d01d6ca0c --- /dev/null +++ b/extractors/cds/tools/.gitignore @@ -0,0 +1,4 @@ +# Override .gitignore configs from parent directories in order to +# include the bundled JS code for the CDS extractor. +!dist/ + diff --git a/extractors/cds/tools/dist/cds-extractor.bundle.js b/extractors/cds/tools/dist/cds-extractor.bundle.js new file mode 100644 index 000000000..434af625b --- /dev/null +++ b/extractors/cds/tools/dist/cds-extractor.bundle.js @@ -0,0 +1,23 @@ +#!/usr/bin/env node +"use strict";var or=Object.create;var As=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var cr=Object.getOwnPropertyNames;var lr=Object.getPrototypeOf,hr=Object.prototype.hasOwnProperty;var Re=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports);var fr=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of cr(t))!hr.call(r,i)&&i!==e&&As(r,i,{get:()=>t[i],enumerable:!(s=ar(t,i))||s.enumerable});return r};var ie=(r,t,e)=>(e=r!=null?or(lr(r)):{},fr(t||!r||!r.__esModule?As(e,"default",{value:r,enumerable:!0}):e,r));var xi=Re((Da,Ei)=>{"use strict";Ei.exports=function(t){return t.map(function(e){return e===""?"''":e&&typeof e=="object"?e.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(e)&&!/'/.test(e)?"'"+e.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(e)?'"'+e.replace(/(["\\$`!])/g,"\\$1")+'"':String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var Fi=Re((Ta,Ai)=>{"use strict";var $i="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",vi=new RegExp("^"+$i+"$"),Di="|&;()<> \\t",Mn='"((\\\\"|[^"])*?)"',Ln="'((\\\\'|[^'])*?)'",In=/^#$/,Ti="'",ki='"',es="$",wt="",Nn=4294967296;for(ss=0;ss<4;ss++)wt+=(Nn*Math.random()).toString(16);var ss,Wn=new RegExp("^"+wt);function zn(r,t){for(var e=t.lastIndex,s=[],i;i=t.exec(r);)s.push(i),t.lastIndex===i.index&&(t.lastIndex+=1);return t.lastIndex=e,s}function Bn(r,t,e){var s=typeof r=="function"?r(e):r[e];return typeof s>"u"&&e!=""?s="":typeof s>"u"&&(s="$"),typeof s=="object"?t+wt+JSON.stringify(s)+wt:t+s}function Vn(r,t,e){e||(e={});var s=e.escape||"\\",i="(\\"+s+`['"`+Di+`]|[^\\s'"`+Di+"])+",n=new RegExp(["("+$i+")","("+i+"|"+Mn+"|"+Ln+")+"].join("|"),"g"),o=zn(r,n);if(o.length===0)return[];t||(t={});var a=!1;return o.map(function(c){var l=c[0];if(!l||a)return;if(vi.test(l))return{op:l};var h=!1,f=!1,d="",p=!1,g;function m(){g+=1;var b,y,C=l.charAt(g);if(C==="{"){if(g+=1,l.charAt(g)==="}")throw new Error("Bad substitution: "+l.slice(g-2,g+1));if(b=l.indexOf("}",g),b<0)throw new Error("Bad substitution: "+l.slice(g));y=l.slice(g,b),g=b}else if(/[*@#?$!_-]/.test(C))y=C,g+=1;else{var x=l.slice(g);b=x.match(/[^\w\d_]/),b?(y=x.slice(0,b.index),g+=b.index-1):(y=x,g=l.length)}return Bn(t,"",y)}for(g=0;g"u"?c:c.concat(l)},[])}Ai.exports=function(t,e,s){var i=Vn(t,e,s);return typeof e!="function"?i:i.reduce(function(n,o){if(typeof o=="object")return n.concat(o);var a=o.split(RegExp("("+wt+".*?"+wt+")","g"));return a.length===1?n.concat(a[0]):n.concat(a.filter(Boolean).map(function(c){return Wn.test(c)?JSON.parse(c.split(wt)[1]):c}))},[])}});var rs=Re(is=>{"use strict";is.quote=xi();is.parse=Fi()});var rr=require("path");var Pe=(r,t,e)=>{let s=r instanceof RegExp?Fs(r,e):r,i=t instanceof RegExp?Fs(t,e):t,n=s!==null&&i!=null&&ur(s,i,e);return n&&{start:n[0],end:n[1],pre:e.slice(0,n[0]),body:e.slice(n[0]+s.length,n[1]),post:e.slice(n[1]+i.length)}},Fs=(r,t)=>{let e=t.match(r);return e?e[0]:null},ur=(r,t,e)=>{let s,i,n,o,a,c=e.indexOf(r),l=e.indexOf(t,c+1),h=c;if(c>=0&&l>0){if(r===t)return[c,l];for(s=[],n=e.length;h>=0&&!a;){if(h===c)s.push(h),c=e.indexOf(r,h+1);else if(s.length===1){let f=s.pop();f!==void 0&&(a=[f,l])}else i=s.pop(),i!==void 0&&i=0?c:l}s.length&&o!==void 0&&(a=[n,o])}return a};var _s="\0SLASH"+Math.random()+"\0",js="\0OPEN"+Math.random()+"\0",Le="\0CLOSE"+Math.random()+"\0",Os="\0COMMA"+Math.random()+"\0",Rs="\0PERIOD"+Math.random()+"\0",dr=new RegExp(_s,"g"),pr=new RegExp(js,"g"),mr=new RegExp(Le,"g"),gr=new RegExp(Os,"g"),wr=new RegExp(Rs,"g"),Sr=/\\\\/g,Cr=/\\{/g,yr=/\\}/g,br=/\\,/g,Er=/\\./g;function Me(r){return isNaN(r)?r.charCodeAt(0):parseInt(r,10)}function xr(r){return r.replace(Sr,_s).replace(Cr,js).replace(yr,Le).replace(br,Os).replace(Er,Rs)}function vr(r){return r.replace(dr,"\\").replace(pr,"{").replace(mr,"}").replace(gr,",").replace(wr,".")}function Ps(r){if(!r)return[""];let t=[],e=Pe("{","}",r);if(!e)return r.split(",");let{pre:s,body:i,post:n}=e,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=Ps(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Ms(r){return r?(r.slice(0,2)==="{}"&&(r="\\{\\}"+r.slice(2)),Nt(xr(r),!0).map(vr)):[]}function Dr(r){return"{"+r+"}"}function Tr(r){return/^-?0\d/.test(r)}function kr(r,t){return r<=t}function $r(r,t){return r>=t}function Nt(r,t){let e=[],s=Pe("{","}",r);if(!s)return[r];let i=s.pre,n=s.post.length?Nt(s.post,!1):[""];if(/\$$/.test(s.pre))for(let o=0;o=0;if(!c&&!l)return s.post.match(/,(?!,).*\}/)?(r=s.pre+"{"+s.body+Le+s.post,Nt(r)):[r];let h;if(c)h=s.body.split(/\.\./);else if(h=Ps(s.body),h.length===1&&h[0]!==void 0&&(h=Nt(h[0],!1).map(Dr),h.length===1))return n.map(d=>s.pre+h[0]+d);let f;if(c&&h[0]!==void 0&&h[1]!==void 0){let d=Me(h[0]),p=Me(h[1]),g=Math.max(h[0].length,h[1].length),m=h.length===3&&h[2]!==void 0?Math.abs(Me(h[2])):1,w=kr;p0){let I=new Array(x+1).join("0");y<0?C="-"+I+C.slice(1):C=I+C}}f.push(C)}}else{f=[];for(let d=0;d{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var Ar={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},zt=r=>r.replace(/[[\]\\-]/g,"\\$&"),Fr=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ls=r=>r.join(""),Is=(r,t)=>{let e=t;if(r.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=e+1,o=!1,a=!1,c=!1,l=!1,h=e,f="";t:for(;nf?s.push(zt(f)+"-"+zt(m)):m===f&&s.push(zt(m)),f="",n++;continue}if(r.startsWith("-]",n+1)){s.push(zt(m+"-")),n+=2;continue}if(r.startsWith("-",n+1)){f=m,n+=2;continue}s.push(zt(m)),n++}if(ht?r.replace(/\[([^\/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var _r=new Set(["!","?","+","*","@"]),Ns=r=>_r.has(r),jr="(?!(?:^|/)\\.\\.?(?:$|/))",re="(?!\\.)",Or=new Set(["[","."]),Rr=new Set(["..","."]),Pr=new Set("().*{}+?[]^$\\!"),Mr=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ie="[^/]",Ws=Ie+"*?",zs=Ie+"+?",bt=class r{type;#t;#e;#n=!1;#r=[];#o;#y;#w;#a=!1;#f;#c;#l=!1;constructor(t,e,s={}){this.type=t,t&&(this.#e=!0),this.#o=e,this.#t=this.#o?this.#o.#t:this,this.#f=this.#t===this?s:this.#t.#f,this.#w=this.#t===this?[]:this.#t.#w,t==="!"&&!this.#t.#a&&this.#w.push(this),this.#y=this.#o?this.#o.#r.length:0}get hasMagic(){if(this.#e!==void 0)return this.#e;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#e=!0;return this.#e}toString(){return this.#c!==void 0?this.#c:this.type?this.#c=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#c=this.#r.map(t=>String(t)).join("")}#s(){if(this!==this.#t)throw new Error("should only call on root");if(this.#a)return this;this.toString(),this.#a=!0;let t;for(;t=this.#w.pop();){if(t.type!=="!")continue;let e=t,s=e.#o;for(;s;){for(let i=e.#y+1;!s.type&&itypeof e=="string"?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#a&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#o?.isStart())return!1;if(this.#y===0)return!0;let t=this.#o;for(let e=0;e{let[g,m,w,S]=typeof p=="string"?r.#p(p,this.#e,c):p.toRegExpSource(t);return this.#e=this.#e||w,this.#n=this.#n||S,g}).join(""),h="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&Rr.has(this.#r[0]))){let g=Or,m=e&&g.has(l.charAt(0))||l.startsWith("\\.")&&g.has(l.charAt(2))||l.startsWith("\\.\\.")&&g.has(l.charAt(4)),w=!e&&!t&&g.has(l.charAt(0));h=m?jr:w?re:""}let f="";return this.isEnd()&&this.#t.#a&&this.#o?.type==="!"&&(f="(?:$|\\/)"),[h+l+f,U(l),this.#e=!!this.#e,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#S(e);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let c=this.toString();return this.#r=[c],this.type=null,this.#e=void 0,[c,U(this.toString()),!1,!1]}let o=!s||t||e||!re?"":this.#S(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#l)a=(this.isStart()&&!e?re:"")+zs;else{let c=this.type==="!"?"))"+(this.isStart()&&!e&&!t?re:"")+Ws+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+c}return[a,U(n),this.#e=!!this.#e,this.#n]}#S(t){return this.#r.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=e.toRegExpSource(t);return this.#n=this.#n||o,s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#p(t,e,s=!1){let i=!1,n="",o=!1;for(let a=0;at?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var R=(r,t,e={})=>(Wt(t),!e.nocomment&&t.charAt(0)==="#"?!1:new N(t,e).match(r)),Lr=/^\*+([^+@!?\*\[\(]*)$/,Ir=r=>t=>!t.startsWith(".")&&t.endsWith(r),Nr=r=>t=>t.endsWith(r),Wr=r=>(r=r.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(r)),zr=r=>(r=r.toLowerCase(),t=>t.toLowerCase().endsWith(r)),Br=/^\*+\.\*+$/,Vr=r=>!r.startsWith(".")&&r.includes("."),Jr=r=>r!=="."&&r!==".."&&r.includes("."),Ur=/^\.\*+$/,Gr=r=>r!=="."&&r!==".."&&r.startsWith("."),Qr=/^\*+$/,Hr=r=>r.length!==0&&!r.startsWith("."),qr=r=>r.length!==0&&r!=="."&&r!=="..",Xr=/^\?+([^+@!?\*\[\(]*)?$/,Kr=([r,t=""])=>{let e=Js([r]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Yr=([r,t=""])=>{let e=Us([r]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Zr=([r,t=""])=>{let e=Us([r]);return t?s=>e(s)&&s.endsWith(t):e},tn=([r,t=""])=>{let e=Js([r]);return t?s=>e(s)&&s.endsWith(t):e},Js=([r])=>{let t=r.length;return e=>e.length===t&&!e.startsWith(".")},Us=([r])=>{let t=r.length;return e=>e.length===t&&e!=="."&&e!==".."},Gs=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Bs={win32:{sep:"\\"},posix:{sep:"/"}},en=Gs==="win32"?Bs.win32.sep:Bs.posix.sep;R.sep=en;var _=Symbol("globstar **");R.GLOBSTAR=_;var sn="[^/]",rn=sn+"*?",nn="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",on="(?:(?!(?:\\/|^)\\.).)*?",an=(r,t={})=>e=>R(e,r,t);R.filter=an;var z=(r,t={})=>Object.assign({},r,t),cn=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return R;let t=R;return Object.assign((s,i,n={})=>t(s,i,z(r,n)),{Minimatch:class extends t.Minimatch{constructor(i,n={}){super(i,z(r,n))}static defaults(i){return t.defaults(z(r,i)).Minimatch}},AST:class extends t.AST{constructor(i,n,o={}){super(i,n,z(r,o))}static fromGlob(i,n={}){return t.AST.fromGlob(i,z(r,n))}},unescape:(s,i={})=>t.unescape(s,z(r,i)),escape:(s,i={})=>t.escape(s,z(r,i)),filter:(s,i={})=>t.filter(s,z(r,i)),defaults:s=>t.defaults(z(r,s)),makeRe:(s,i={})=>t.makeRe(s,z(r,i)),braceExpand:(s,i={})=>t.braceExpand(s,z(r,i)),match:(s,i,n={})=>t.match(s,i,z(r,n)),sep:t.sep,GLOBSTAR:_})};R.defaults=cn;var Qs=(r,t={})=>(Wt(r),t.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:Ms(r));R.braceExpand=Qs;var ln=(r,t={})=>new N(r,t).makeRe();R.makeRe=ln;var hn=(r,t,e={})=>{let s=new N(t,e);return r=r.filter(i=>s.match(i)),s.options.nonull&&!r.length&&r.push(t),r};R.match=hn;var Vs=/[?*]|[+@!]\(.*?\)|\[|\]/,fn=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),N=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){Wt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Gs,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.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 t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...n)=>console.error(...n)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(n=>this.slashSplit(n));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let i=this.globParts.map((n,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let c=n[0]===""&&n[1]===""&&(n[2]==="?"||!Vs.test(n[2]))&&!Vs.test(n[3]),l=/^[a-z]:/i.test(n[0]);if(c)return[...n.slice(0,4),...n.slice(4).map(h=>this.parse(h))];if(l)return[n[0],...n.slice(1).map(h=>this.parse(h))]}return n.map(c=>this.parse(c))});if(this.debug(this.pattern,i),this.set=i.filter(n=>n.indexOf(!1)===-1),this.isWindows)for(let n=0;n=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,i)=>{let n=s[s.length-1];return i==="**"&&n==="**"?s:i===".."&&n&&n!==".."&&n!=="."&&n!=="**"?(s.pop(),s):(s.push(i),s)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&s.splice(i+1,o-i);let a=s[i+1],c=s[i+2],l=s[i+3];if(a!==".."||!c||c==="."||c===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(i,1);let h=s.slice(0);h[i]="**",t.push(h),i--}if(!this.preserveMultipleSlashes){for(let o=1;oe.length)}partsMatch(t,e,s=!1){let i=0,n=0,o=[],a="";for(;iy?e=e.slice(C):y>C&&(t=t.slice(y)))}}let{optimizationLevel:n=1}=this.options;n>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var o=0,a=0,c=t.length,l=e.length;o>> no match, partial?`,t,d,e,p),d===c))}let m;if(typeof h=="string"?(m=f===h,this.debug("string match",h,f,m)):(m=h.test(f),this.debug("pattern match",h,f,m)),!m)return!1}if(o===c&&a===l)return!0;if(o===c)return s;if(a===l)return o===c-1&&t[o]==="";throw new Error("wtf?")}braceExpand(){return Qs(this.pattern,this.options)}parse(t){Wt(t);let e=this.options;if(t==="**")return _;if(t==="")return"";let s,i=null;(s=t.match(Qr))?i=e.dot?qr:Hr:(s=t.match(Lr))?i=(e.nocase?e.dot?zr:Wr:e.dot?Nr:Ir)(s[1]):(s=t.match(Xr))?i=(e.nocase?e.dot?Yr:Kr:e.dot?Zr:tn)(s):(s=t.match(Br))?i=e.dot?Jr:Vr:(s=t.match(Ur))&&(i=Gr);let n=bt.fromGlob(t,this.options).toMMPattern();return i&&typeof n=="object"&&Reflect.defineProperty(n,"test",{value:i}),n}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,s=e.noglobstar?rn:e.dot?nn:on,i=new Set(e.nocase?["i"]:[]),n=t.map(c=>{let l=c.map(h=>{if(h instanceof RegExp)for(let f of h.flags.split(""))i.add(f);return typeof h=="string"?fn(h):h===_?_:h._src});return l.forEach((h,f)=>{let d=l[f+1],p=l[f-1];h!==_||p===_||(p===void 0?d!==void 0&&d!==_?l[f+1]="(?:\\/|"+s+"\\/)?"+d:l[f]=s:d===void 0?l[f-1]=p+"(?:\\/|"+s+")?":d!==_&&(l[f-1]=p+"(?:\\/|\\/"+s+"\\/)"+d,l[f+1]=_))}),l.filter(h=>h!==_).join("/")}).join("|"),[o,a]=t.length>1?["(?:",")"]:["",""];n="^"+o+n+a+"$",this.negate&&(n="^(?!"+n+").+$");try{this.regexp=new RegExp(n,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let s=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let n=this.set;this.debug(this.pattern,"set",n);let o=i[i.length-1];if(!o)for(let a=i.length-2;!o&&a>=0;a--)o=i[a];for(let a=0;a{typeof Ne.emitWarning=="function"?Ne.emitWarning(r,t,e,s):console.error(`[${e}] ${t}: ${r}`)},ne=globalThis.AbortController,Hs=globalThis.AbortSignal;if(typeof ne>"u"){Hs=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(s,i){this._onabort.push(i)}},ne=class{constructor(){t()}signal=new Hs;abort(s){if(!this.signal.aborted){this.signal.reason=s,this.signal.aborted=!0;for(let i of this.signal._onabort)i(s);this.signal.onabort?.(s)}}};let r=Ne.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{r&&(r=!1,Xs("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",t))}}var un=r=>!qs.has(r),Go=Symbol("type"),lt=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Ks=r=>lt(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?vt:null:null,vt=class extends Array{constructor(t){super(t),this.fill(0)}},We=class r{heap;length;static#t=!1;static create(t){let e=Ks(t);if(!e)return[];r.#t=!0;let s=new r(t,e);return r.#t=!1,s}constructor(t,e){if(!r.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Bt=class r{#t;#e;#n;#r;#o;#y;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#f;#c;#l;#s;#u;#S;#p;#m;#k;#g;#$;#E;#b;#C;#D;#d;#F;static unsafeExposeInternals(t){return{starts:t.#E,ttls:t.#b,sizes:t.#$,keyMap:t.#c,keyList:t.#l,valList:t.#s,next:t.#u,prev:t.#S,get head(){return t.#p},get tail(){return t.#m},free:t.#k,isBackgroundFetch:e=>t.#h(e),backgroundFetch:(e,s,i,n)=>t.#P(e,s,i,n),moveToTail:e=>t.#I(e),indexes:e=>t.#T(e),rindexes:e=>t.#A(e),isStale:e=>t.#v(e)}}get max(){return this.#t}get maxSize(){return this.#e}get calculatedSize(){return this.#f}get size(){return this.#a}get fetchMethod(){return this.#y}get memoMethod(){return this.#w}get dispose(){return this.#n}get onInsert(){return this.#r}get disposeAfter(){return this.#o}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:c,dispose:l,onInsert:h,disposeAfter:f,noDisposeOnSet:d,noUpdateTTL:p,maxSize:g=0,maxEntrySize:m=0,sizeCalculation:w,fetchMethod:S,memoMethod:b,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:C,allowStaleOnFetchRejection:x,allowStaleOnFetchAbort:I,ignoreFetchAbort:at}=t;if(e!==0&&!lt(e))throw new TypeError("max option must be a nonnegative integer");let yt=e?Ks(e):Array;if(!yt)throw new Error("invalid max value: "+e);if(this.#t=e,this.#e=g,this.maxEntrySize=m||this.#e,this.sizeCalculation=w,this.sizeCalculation){if(!this.#e&&!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(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=b,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#y=S,this.#D=!!S,this.#c=new Map,this.#l=new Array(e).fill(void 0),this.#s=new Array(e).fill(void 0),this.#u=new yt(e),this.#S=new yt(e),this.#p=0,this.#m=0,this.#k=We.create(e),this.#a=0,this.#f=0,typeof l=="function"&&(this.#n=l),typeof h=="function"&&(this.#r=h),typeof f=="function"?(this.#o=f,this.#g=[]):(this.#o=void 0,this.#g=void 0),this.#C=!!this.#n,this.#F=!!this.#r,this.#d=!!this.#o,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!x,this.allowStaleOnFetchAbort=!!I,this.ignoreFetchAbort=!!at,this.maxEntrySize!==0){if(this.#e!==0&&!lt(this.#e))throw new TypeError("maxSize must be a positive integer if specified");if(!lt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#W()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!C,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=lt(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!lt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#i()}if(this.#t===0&&this.ttl===0&&this.#e===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#e){let ct="LRU_CACHE_UNBOUNDED";un(ct)&&(qs.add(ct),Xs("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",ct,r))}}getRemainingTTL(t){return this.#c.has(t)?1/0:0}#i(){let t=new vt(this.#t),e=new vt(this.#t);this.#b=t,this.#E=e,this.#_=(n,o,a=xt.now())=>{if(e[n]=o!==0?a:0,t[n]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#v(n)&&this.#j(this.#l[n],"expire")},o+1);c.unref&&c.unref()}},this.#O=n=>{e[n]=t[n]!==0?xt.now():0},this.#x=(n,o)=>{if(t[o]){let a=t[o],c=e[o];if(!a||!c)return;n.ttl=a,n.start=c,n.now=s||i();let l=n.now-c;n.remainingTTL=a-l}};let s=0,i=()=>{let n=xt.now();if(this.ttlResolution>0){s=n;let o=setTimeout(()=>s=0,this.ttlResolution);o.unref&&o.unref()}return n};this.getRemainingTTL=n=>{let o=this.#c.get(n);if(o===void 0)return 0;let a=t[o],c=e[o];if(!a||!c)return 1/0;let l=(s||i())-c;return a-l},this.#v=n=>{let o=e[n],a=t[n];return!!a&&!!o&&(s||i())-o>a}}#O=()=>{};#x=()=>{};#_=()=>{};#v=()=>!1;#W(){let t=new vt(this.#t);this.#f=0,this.#$=t,this.#R=e=>{this.#f-=t[e],t[e]=0},this.#z=(e,s,i,n)=>{if(this.#h(s))return 0;if(!lt(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,e),!lt(i))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 i},this.#M=(e,s,i)=>{if(t[e]=s,this.#e){let n=this.#e-t[e];for(;this.#f>n;)this.#L(!0)}this.#f+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#f)}}#R=t=>{};#M=(t,e,s)=>{};#z=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:t=this.allowStale}={}){if(this.#a)for(let e=this.#m;!(!this.#B(e)||((t||!this.#v(e))&&(yield e),e===this.#p));)e=this.#S[e]}*#A({allowStale:t=this.allowStale}={}){if(this.#a)for(let e=this.#p;!(!this.#B(e)||((t||!this.#v(e))&&(yield e),e===this.#m));)e=this.#u[e]}#B(t){return t!==void 0&&this.#c.get(this.#l[t])===t}*entries(){for(let t of this.#T())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#h(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*rentries(){for(let t of this.#A())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#h(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*keys(){for(let t of this.#T()){let e=this.#l[t];e!==void 0&&!this.#h(this.#s[t])&&(yield e)}}*rkeys(){for(let t of this.#A()){let e=this.#l[t];e!==void 0&&!this.#h(this.#s[t])&&(yield e)}}*values(){for(let t of this.#T())this.#s[t]!==void 0&&!this.#h(this.#s[t])&&(yield this.#s[t])}*rvalues(){for(let t of this.#A())this.#s[t]!==void 0&&!this.#h(this.#s[t])&&(yield this.#s[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#T()){let i=this.#s[s],n=this.#h(i)?i.__staleWhileFetching:i;if(n!==void 0&&t(n,this.#l[s],this))return this.get(this.#l[s],e)}}forEach(t,e=this){for(let s of this.#T()){let i=this.#s[s],n=this.#h(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(e,n,this.#l[s],this)}}rforEach(t,e=this){for(let s of this.#A()){let i=this.#s[s],n=this.#h(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(e,n,this.#l[s],this)}}purgeStale(){let t=!1;for(let e of this.#A({allowStale:!0}))this.#v(e)&&(this.#j(this.#l[e],"expire"),t=!0);return t}info(t){let e=this.#c.get(t);if(e===void 0)return;let s=this.#s[e],i=this.#h(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#b&&this.#E){let o=this.#b[e],a=this.#E[e];if(o&&a){let c=o-(xt.now()-a);n.ttl=c,n.start=Date.now()}}return this.#$&&(n.size=this.#$[e]),n}dump(){let t=[];for(let e of this.#T({allowStale:!0})){let s=this.#l[e],i=this.#s[e],n=this.#h(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#b&&this.#E){o.ttl=this.#b[e];let a=xt.now()-this.#E[e];o.start=Math.floor(Date.now()-a)}this.#$&&(o.size=this.#$[e]),t.unshift([s,o])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=xt.now()-i}this.set(e,s.value,s)}}set(t,e,s={}){if(e===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=s,{noUpdateTTL:l=this.noUpdateTTL}=s,h=this.#z(t,e,s.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#j(t,"set"),this;let f=this.#a===0?void 0:this.#c.get(t);if(f===void 0)f=this.#a===0?this.#m:this.#k.length!==0?this.#k.pop():this.#a===this.#t?this.#L(!1):this.#a,this.#l[f]=t,this.#s[f]=e,this.#c.set(t,f),this.#u[this.#m]=f,this.#S[f]=this.#m,this.#m=f,this.#a++,this.#M(f,h,c),c&&(c.set="add"),l=!1,this.#F&&this.#r?.(e,t,"add");else{this.#I(f);let d=this.#s[f];if(e!==d){if(this.#D&&this.#h(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:p}=d;p!==void 0&&!o&&(this.#C&&this.#n?.(p,t,"set"),this.#d&&this.#g?.push([p,t,"set"]))}else o||(this.#C&&this.#n?.(d,t,"set"),this.#d&&this.#g?.push([d,t,"set"]));if(this.#R(f),this.#M(f,h,c),this.#s[f]=e,c){c.set="replace";let p=d&&this.#h(d)?d.__staleWhileFetching:d;p!==void 0&&(c.oldValue=p)}}else c&&(c.set="update");this.#F&&this.onInsert?.(e,t,e===d?"update":"replace")}if(i!==0&&!this.#b&&this.#i(),this.#b&&(l||this.#_(f,i,n),c&&this.#x(c,f)),!o&&this.#d&&this.#g){let d=this.#g,p;for(;p=d?.shift();)this.#o?.(...p)}return this}pop(){try{for(;this.#a;){let t=this.#s[this.#p];if(this.#L(!0),this.#h(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#d&&this.#g){let t=this.#g,e;for(;e=t?.shift();)this.#o?.(...e)}}}#L(t){let e=this.#p,s=this.#l[e],i=this.#s[e];return this.#D&&this.#h(i)?i.__abortController.abort(new Error("evicted")):(this.#C||this.#d)&&(this.#C&&this.#n?.(i,s,"evict"),this.#d&&this.#g?.push([i,s,"evict"])),this.#R(e),t&&(this.#l[e]=void 0,this.#s[e]=void 0,this.#k.push(e)),this.#a===1?(this.#p=this.#m=0,this.#k.length=0):this.#p=this.#u[e],this.#c.delete(s),this.#a--,e}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,n=this.#c.get(t);if(n!==void 0){let o=this.#s[n];if(this.#h(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#v(n))i&&(i.has="stale",this.#x(i,n));else return s&&this.#O(n),i&&(i.has="hit",this.#x(i,n)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{allowStale:s=this.allowStale}=e,i=this.#c.get(t);if(i===void 0||!s&&this.#v(i))return;let n=this.#s[i];return this.#h(n)?n.__staleWhileFetching:n}#P(t,e,s,i){let n=e===void 0?void 0:this.#s[e];if(this.#h(n))return n;let o=new ne,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let c={signal:o.signal,options:s,context:i},l=(m,w=!1)=>{let{aborted:S}=o.signal,b=s.ignoreFetchAbort&&m!==void 0;if(s.status&&(S&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,b&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),S&&!b&&!w)return f(o.signal.reason);let y=p;return this.#s[e]===p&&(m===void 0?y.__staleWhileFetching?this.#s[e]=y.__staleWhileFetching:this.#j(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,m,c.options))),m},h=m=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=m),f(m)),f=m=>{let{aborted:w}=o.signal,S=w&&s.allowStaleOnFetchAbort,b=S||s.allowStaleOnFetchRejection,y=b||s.noDeleteOnFetchRejection,C=p;if(this.#s[e]===p&&(!y||C.__staleWhileFetching===void 0?this.#j(t,"fetch"):S||(this.#s[e]=C.__staleWhileFetching)),b)return s.status&&C.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),C.__staleWhileFetching;if(C.__returned===C)throw m},d=(m,w)=>{let S=this.#y?.(t,n,c);S&&S instanceof Promise&&S.then(b=>m(b===void 0?void 0:b),w),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(m(void 0),s.allowStaleOnFetchAbort&&(m=b=>l(b,!0)))})};s.status&&(s.status.fetchDispatched=!0);let p=new Promise(d).then(l,h),g=Object.assign(p,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.set(t,g,{...c.options,status:void 0}),e=this.#c.get(t)):this.#s[e]=g,g}#h(t){if(!this.#D)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof ne}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:m,forceRefresh:w=!1,status:S,signal:b}=e;if(!this.#D)return S&&(S.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:S});let y={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:h,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:g,ignoreFetchAbort:p,status:S,signal:b},C=this.#c.get(t);if(C===void 0){S&&(S.fetch="miss");let x=this.#P(t,C,y,m);return x.__returned=x}else{let x=this.#s[C];if(this.#h(x)){let It=s&&x.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",It&&(S.returnedStale=!0)),It?x.__staleWhileFetching:x.__returned=x}let I=this.#v(C);if(!w&&!I)return S&&(S.fetch="hit"),this.#I(C),i&&this.#O(C),S&&this.#x(S,C),x;let at=this.#P(t,C,y,m),ct=at.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=I?"stale":"refresh",ct&&I&&(S.returnedStale=!0)),ct?at.__staleWhileFetching:at.__returned=at}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:n,...o}=e,a=this.get(t,o);if(!n&&a!==void 0)return a;let c=s(t,a,{options:o,context:i});return this.set(t,c,o),c}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=e,a=this.#c.get(t);if(a!==void 0){let c=this.#s[a],l=this.#h(c);return o&&this.#x(o,a),this.#v(a)?(o&&(o.get="stale"),l?(o&&s&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?c.__staleWhileFetching:void 0):(n||this.#j(t,"expire"),o&&s&&(o.returnedStale=!0),s?c:void 0)):(o&&(o.get="hit"),l?c.__staleWhileFetching:(this.#I(a),i&&this.#O(a),c))}else o&&(o.get="miss")}#V(t,e){this.#S[e]=t,this.#u[t]=e}#I(t){t!==this.#m&&(t===this.#p?this.#p=this.#u[t]:this.#V(this.#S[t],this.#u[t]),this.#V(this.#m,t),this.#m=t)}delete(t){return this.#j(t,"delete")}#j(t,e){let s=!1;if(this.#a!==0){let i=this.#c.get(t);if(i!==void 0)if(s=!0,this.#a===1)this.#N(e);else{this.#R(i);let n=this.#s[i];if(this.#h(n)?n.__abortController.abort(new Error("deleted")):(this.#C||this.#d)&&(this.#C&&this.#n?.(n,t,e),this.#d&&this.#g?.push([n,t,e])),this.#c.delete(t),this.#l[i]=void 0,this.#s[i]=void 0,i===this.#m)this.#m=this.#S[i];else if(i===this.#p)this.#p=this.#u[i];else{let o=this.#S[i];this.#u[o]=this.#u[i];let a=this.#u[i];this.#S[a]=this.#S[i]}this.#a--,this.#k.push(i)}}if(this.#d&&this.#g?.length){let i=this.#g,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#N("delete")}#N(t){for(let e of this.#A({allowStale:!0})){let s=this.#s[e];if(this.#h(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#l[e];this.#C&&this.#n?.(s,i,t),this.#d&&this.#g?.push([s,i,t])}}if(this.#c.clear(),this.#s.fill(void 0),this.#l.fill(void 0),this.#b&&this.#E&&(this.#b.fill(0),this.#E.fill(0)),this.#$&&this.#$.fill(0),this.#p=0,this.#m=0,this.#k.length=0,this.#f=0,this.#a=0,this.#d&&this.#g){let e=this.#g,s;for(;s=e?.shift();)this.#o?.(...s)}}};var kt=require("node:path"),ai=require("node:url"),K=require("fs"),En=ie(require("node:fs"),1),ut=require("node:fs/promises");var ue=require("node:events"),Qe=ie(require("node:stream"),1),si=require("node:string_decoder"),Ys=typeof process=="object"&&process?process:{stdout:null,stderr:null},dn=r=>!!r&&typeof r=="object"&&(r instanceof ft||r instanceof Qe.default||pn(r)||mn(r)),pn=r=>!!r&&typeof r=="object"&&r instanceof ue.EventEmitter&&typeof r.pipe=="function"&&r.pipe!==Qe.default.Writable.prototype.pipe,mn=r=>!!r&&typeof r=="object"&&r instanceof ue.EventEmitter&&typeof r.write=="function"&&typeof r.end=="function",st=Symbol("EOF"),it=Symbol("maybeEmitEnd"),ht=Symbol("emittedEnd"),oe=Symbol("emittingEnd"),Vt=Symbol("emittedError"),ae=Symbol("closed"),Zs=Symbol("read"),ce=Symbol("flush"),ti=Symbol("flushChunk"),G=Symbol("encoding"),Dt=Symbol("decoder"),$=Symbol("flowing"),Jt=Symbol("paused"),Tt=Symbol("resume"),A=Symbol("buffer"),P=Symbol("pipes"),F=Symbol("bufferLength"),ze=Symbol("bufferPush"),le=Symbol("bufferShift"),j=Symbol("objectMode"),D=Symbol("destroyed"),Be=Symbol("error"),Ve=Symbol("emitData"),ei=Symbol("emitEnd"),Je=Symbol("emitEnd2"),q=Symbol("async"),Ue=Symbol("abort"),he=Symbol("aborted"),Ut=Symbol("signal"),mt=Symbol("dataListeners"),W=Symbol("discarded"),Gt=r=>Promise.resolve().then(r),gn=r=>r(),wn=r=>r==="end"||r==="finish"||r==="prefinish",Sn=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,Cn=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),fe=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[Tt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ge=class extends fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>e.emit("error",i),t.on("error",this.proxyErrors)}},yn=r=>!!r.objectMode,bn=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",ft=class extends ue.EventEmitter{[$]=!1;[Jt]=!1;[P]=[];[A]=[];[j];[G];[q];[Dt];[st]=!1;[ht]=!1;[oe]=!1;[ae]=!1;[Vt]=null;[F]=0;[D]=!1;[Ut];[he]=!1;[mt]=0;[W]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");yn(e)?(this[j]=!0,this[G]=null):bn(e)?(this[G]=e.encoding,this[j]=!1):(this[j]=!1,this[G]=null),this[q]=!!e.async,this[Dt]=this[G]?new si.StringDecoder(this[G]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[A]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[P]});let{signal:s}=e;s&&(this[Ut]=s,s.aborted?this[Ue]():s.addEventListener("abort",()=>this[Ue]()))}get bufferLength(){return this[F]}get encoding(){return this[G]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[j]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[q]}set async(t){this[q]=this[q]||!!t}[Ue](){this[he]=!0,this.emit("abort",this[Ut]?.reason),this.destroy(this[Ut]?.reason)}get aborted(){return this[he]}set aborted(t){}write(t,e,s){if(this[he])return!1;if(this[st])throw new Error("write after end");if(this[D])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[q]?Gt:gn;if(!this[j]&&!Buffer.isBuffer(t)){if(Cn(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Sn(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[j]?(this[$]&&this[F]!==0&&this[ce](!0),this[$]?this.emit("data",t):this[ze](t),this[F]!==0&&this.emit("readable"),s&&i(s),this[$]):t.length?(typeof t=="string"&&!(e===this[G]&&!this[Dt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[G]&&(t=this[Dt].write(t)),this[$]&&this[F]!==0&&this[ce](!0),this[$]?this.emit("data",t):this[ze](t),this[F]!==0&&this.emit("readable"),s&&i(s),this[$]):(this[F]!==0&&this.emit("readable"),s&&i(s),this[$])}read(t){if(this[D])return null;if(this[W]=!1,this[F]===0||t===0||t&&t>this[F])return this[it](),null;this[j]&&(t=null),this[A].length>1&&!this[j]&&(this[A]=[this[G]?this[A].join(""):Buffer.concat(this[A],this[F])]);let e=this[Zs](t||null,this[A][0]);return this[it](),e}[Zs](t,e){if(this[j])this[le]();else{let s=e;t===s.length||t===null?this[le]():typeof s=="string"?(this[A][0]=s.slice(t),e=s.slice(0,t),this[F]-=t):(this[A][0]=s.subarray(t),e=s.subarray(0,t),this[F]-=t)}return this.emit("data",e),!this[A].length&&!this[st]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[st]=!0,this.writable=!1,(this[$]||!this[Jt])&&this[it](),this}[Tt](){this[D]||(!this[mt]&&!this[P].length&&(this[W]=!0),this[Jt]=!1,this[$]=!0,this.emit("resume"),this[A].length?this[ce]():this[st]?this[it]():this.emit("drain"))}resume(){return this[Tt]()}pause(){this[$]=!1,this[Jt]=!0,this[W]=!1}get destroyed(){return this[D]}get flowing(){return this[$]}get paused(){return this[Jt]}[ze](t){this[j]?this[F]+=1:this[F]+=t.length,this[A].push(t)}[le](){return this[j]?this[F]-=1:this[F]-=this[A][0].length,this[A].shift()}[ce](t=!1){do;while(this[ti](this[le]())&&this[A].length);!t&&!this[A].length&&!this[st]&&this.emit("drain")}[ti](t){return this.emit("data",t),this[$]}pipe(t,e){if(this[D])return t;this[W]=!1;let s=this[ht];return e=e||{},t===Ys.stdout||t===Ys.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[P].push(e.proxyErrors?new Ge(this,t,e):new fe(this,t,e)),this[q]?Gt(()=>this[Tt]()):this[Tt]()),t}unpipe(t){let e=this[P].find(s=>s.dest===t);e&&(this[P].length===1?(this[$]&&this[mt]===0&&(this[$]=!1),this[P]=[]):this[P].splice(this[P].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[W]=!1,this[mt]++,!this[P].length&&!this[$]&&this[Tt]();else if(t==="readable"&&this[F]!==0)super.emit("readable");else if(wn(t)&&this[ht])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Vt]){let i=e;this[q]?Gt(()=>i.call(this,this[Vt])):i.call(this,this[Vt])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[mt]=this.listeners("data").length,this[mt]===0&&!this[W]&&!this[P].length&&(this[$]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[mt]=0,!this[W]&&!this[P].length&&(this[$]=!1)),e}get emittedEnd(){return this[ht]}[it](){!this[oe]&&!this[ht]&&!this[D]&&this[A].length===0&&this[st]&&(this[oe]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ae]&&this.emit("close"),this[oe]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==D&&this[D])return!1;if(t==="data")return!this[j]&&!s?!1:this[q]?(Gt(()=>this[Ve](s)),!0):this[Ve](s);if(t==="end")return this[ei]();if(t==="close"){if(this[ae]=!0,!this[ht]&&!this[D])return!1;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[Vt]=s,super.emit(Be,s);let n=!this[Ut]||this.listeners("error").length?super.emit("error",s):!1;return this[it](),n}else if(t==="resume"){let n=super.emit("resume");return this[it](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let i=super.emit(t,...e);return this[it](),i}[Ve](t){for(let s of this[P])s.dest.write(t)===!1&&this.pause();let e=this[W]?!1:super.emit("data",t);return this[it](),e}[ei](){return this[ht]?!1:(this[ht]=!0,this.readable=!1,this[q]?(Gt(()=>this[Je]()),!0):this[Je]())}[Je](){if(this[Dt]){let e=this[Dt].end();if(e){for(let s of this[P])s.dest.write(e);this[W]||super.emit("data",e)}}for(let e of this[P])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[j]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[j]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[j])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[G]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(D,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[W]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[st])return e();let n,o,a=f=>{this.off("data",c),this.off("end",l),this.off(D,h),e(),o(f)},c=f=>{this.off("error",a),this.off("end",l),this.off(D,h),this.pause(),n({value:f,done:!!this[st]})},l=()=>{this.off("error",a),this.off("data",c),this.off(D,h),e(),n({done:!0,value:void 0})},h=()=>a(new Error("stream destroyed"));return new Promise((f,d)=>{o=d,n=f,this.once(D,h),this.once("error",a),this.once("end",l),this.once("data",c)})},throw:e,return:e,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[W]=!1;let t=!1,e=()=>(this.pause(),this.off(Be,e),this.off(D,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Be,e),this.once(D,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this}}}destroy(t){if(this[D])return t?this.emit("error",t):this.emit(D),this;this[D]=!0,this[W]=!0,this[A].length=0,this[F]=0;let e=this;return typeof e.close=="function"&&!this[ae]&&e.close(),t?this.emit("error",t):this.emit(D),this}static get isStream(){return dn}};var xn=K.realpathSync.native,Ht={lstatSync:K.lstatSync,readdir:K.readdir,readdirSync:K.readdirSync,readlinkSync:K.readlinkSync,realpathSync:xn,promises:{lstat:ut.lstat,readdir:ut.readdir,readlink:ut.readlink,realpath:ut.realpath}},ci=r=>!r||r===Ht||r===En?Ht:{...Ht,...r,promises:{...Ht.promises,...r.promises||{}}},li=/^\\\\\?\\([a-z]:)\\?$/i,vn=r=>r.replace(/\//g,"\\").replace(li,"$1\\"),Dn=/[\\\/]/,V=0,hi=1,fi=2,X=4,ui=6,di=8,gt=10,pi=12,B=15,Qt=~B,He=16,ii=32,qt=64,Q=128,de=256,me=512,ri=qt|Q|me,Tn=1023,qe=r=>r.isFile()?di:r.isDirectory()?X:r.isSymbolicLink()?gt:r.isCharacterDevice()?fi:r.isBlockDevice()?ui:r.isSocket()?pi:r.isFIFO()?hi:V,ni=new Map,Xt=r=>{let t=ni.get(r);if(t)return t;let e=r.normalize("NFKD");return ni.set(r,e),e},oi=new Map,pe=r=>{let t=oi.get(r);if(t)return t;let e=Xt(r.toLowerCase());return oi.set(r,e),e},ge=class extends Bt{constructor(){super({max:256})}},Xe=class extends Bt{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},mi=Symbol("PathScurry setAsCwd"),O=class{name;root;roots;parent;nocase;isCWD=!1;#t;#e;get dev(){return this.#e}#n;get mode(){return this.#n}#r;get nlink(){return this.#r}#o;get uid(){return this.#o}#y;get gid(){return this.#y}#w;get rdev(){return this.#w}#a;get blksize(){return this.#a}#f;get ino(){return this.#f}#c;get size(){return this.#c}#l;get blocks(){return this.#l}#s;get atimeMs(){return this.#s}#u;get mtimeMs(){return this.#u}#S;get ctimeMs(){return this.#S}#p;get birthtimeMs(){return this.#p}#m;get atime(){return this.#m}#k;get mtime(){return this.#k}#g;get ctime(){return this.#g}#$;get birthtime(){return this.#$}#E;#b;#C;#D;#d;#F;#i;#O;#x;#_;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=V,s,i,n,o,a){this.name=t,this.#E=n?pe(t):Xt(t),this.#i=e&Tn,this.nocase=n,this.roots=i,this.root=s||this,this.#O=o,this.#C=a.fullpath,this.#d=a.relative,this.#F=a.relativePosix,this.parent=a.parent,this.parent?this.#t=this.parent.#t:this.#t=ci(a.fs)}depth(){return this.#b!==void 0?this.#b:this.parent?this.#b=this.parent.depth()+1:this.#b=0}childrenCache(){return this.#O}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#v(i):this.#v(i)}#v(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#O.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#O.set(this,e),this.#i&=~He,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?pe(t):Xt(t);for(let c of s)if(c.#E===i)return c;let n=this.parent?this.sep:"",o=this.#C?this.#C+n+t:void 0,a=this.newChild(t,V,{...e,parent:this,fullpath:o});return this.canReaddir()||(a.#i|=Q),s.push(a),a}relative(){if(this.isCWD)return"";if(this.#d!==void 0)return this.#d;let t=this.name,e=this.parent;if(!e)return this.#d=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#F!==void 0)return this.#F;let t=this.name,e=this.parent;if(!e)return this.#F=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#C!==void 0)return this.#C;let t=this.name,e=this.parent;if(!e)return this.#C=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#C=i}fullpathPosix(){if(this.#D!==void 0)return this.#D;if(this.sep==="/")return this.#D=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#D=`//?/${i}`:this.#D=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#D=s}isUnknown(){return(this.#i&B)===V}isType(t){return this[`is${t}`]()}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.#i&B)===di}isDirectory(){return(this.#i&B)===X}isCharacterDevice(){return(this.#i&B)===fi}isBlockDevice(){return(this.#i&B)===ui}isFIFO(){return(this.#i&B)===hi}isSocket(){return(this.#i&B)===pi}isSymbolicLink(){return(this.#i>)===gt}lstatCached(){return this.#i&ii?this:void 0}readlinkCached(){return this.#x}realpathCached(){return this.#_}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#x)return!0;if(!this.parent)return!1;let t=this.#i&B;return!(t!==V&&t!==gt||this.#i&de||this.#i&Q)}calledReaddir(){return!!(this.#i&He)}isENOENT(){return!!(this.#i&Q)}isNamed(t){return this.nocase?this.#E===pe(t):this.#E===Xt(t)}async readlink(){let t=this.#x;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#x=s}catch(e){this.#L(e.code);return}}readlinkSync(){let t=this.#x;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#x=s}catch(e){this.#L(e.code);return}}#W(t){this.#i|=He;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let n=s.slice(0,s.provisional);e?t(null,n):queueMicrotask(()=>t(null,n));return}if(this.#N.push(t),this.#U)return;this.#U=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(n,o)=>{if(n)this.#A(n.code),s.provisional=0;else{for(let a of o)this.#P(a,s);this.#W(s)}this.#G(s.slice(0,s.provisional))})}#J;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#J)await this.#J;else{let s=()=>{};this.#J=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#P(i,t);this.#W(t)}catch(i){this.#A(i.code),t.provisional=0}this.#J=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#P(s,t);this.#W(t)}catch(s){this.#A(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#i&ri)return!1;let t=B&this.#i;return t===V||t===X||t===gt}shouldWalk(t,e){return(this.#i&X)===X&&!(this.#i&ri)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#_)return this.#_;if(!((me|de|Q)&this.#i))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#_=this.resolve(t)}catch{this.#z()}}realpathSync(){if(this.#_)return this.#_;if(!((me|de|Q)&this.#i))try{let t=this.#t.realpathSync(this.fullpath());return this.#_=this.resolve(t)}catch{this.#z()}}[mi](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#d=s.join(this.sep),i.#F=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#d=void 0,i.#F=void 0,i=i.parent}},we=class r extends O{sep="\\";splitSep=Dn;constructor(t,e=V,s,i,n,o,a){super(t,e,s,i,n,o,a)}newChild(t,e=V,s={}){return new r(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return kt.win32.parse(t).root}getRoot(t){if(t=vn(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new $t(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(li,"$1\\"),t===e}},Se=class r extends O{splitSep="/";sep="/";constructor(t,e=V,s,i,n,o,a){super(t,e,s,i,n,o,a)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=V,s={}){return new r(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Ce=class{root;rootPath;roots;cwd;#t;#e;#n;nocase;#r;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:n=16*1024,fs:o=Ht}={}){this.#r=ci(o),(t instanceof URL||t.startsWith("file://"))&&(t=(0,ai.fileURLToPath)(t));let a=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#t=new ge,this.#e=new ge,this.#n=new Xe(n);let c=a.substring(this.rootPath.length).split(s);if(c.length===1&&!c[0]&&c.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let l=this.root,h=c.length-1,f=e.sep,d=this.rootPath,p=!1;for(let g of c){let m=h--;l=l.child(g,{relative:new Array(m).fill("..").join(f),relativePosix:new Array(m).fill("..").join("/"),fullpath:d+=(p?"":f)+g}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let n=t.length-1;n>=0;n--){let o=t[n];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let n=t.length-1;n>=0;n--){let o=t[n];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#e.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#e.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(n=>n.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,a=[];(!n||n(t))&&a.push(s?t:t.fullpath());let c=new Set,l=(f,d)=>{c.add(f),f.readdirCB((p,g)=>{if(p)return d(p);let m=g.length;if(!m)return d();let w=()=>{--m===0&&d()};for(let S of g)(!n||n(S))&&a.push(s?S:S.fullpath()),i&&S.isSymbolicLink()?S.realpath().then(b=>b?.isUnknown()?b.lstat():b).then(b=>b?.shouldWalk(c,o)?l(b,w):w()):S.shouldWalk(c,o)?l(S,w):w()},!0)},h=t;return new Promise((f,d)=>{l(h,p=>{if(p)return d(p);f(a)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,a=[];(!n||n(t))&&a.push(s?t:t.fullpath());let c=new Set([t]);for(let l of c){let h=l.readdirSync();for(let f of h){(!n||n(f))&&a.push(s?f:f.fullpath());let d=f;if(f.isSymbolicLink()){if(!(i&&(d=f.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(c,o)&&c.add(d)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e;(!n||n(t))&&(yield s?t:t.fullpath());let a=new Set([t]);for(let c of a){let l=c.readdirSync();for(let h of l){(!n||n(h))&&(yield s?h:h.fullpath());let f=h;if(h.isSymbolicLink()){if(!(i&&(f=h.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(a,o)&&a.add(f)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,a=new ft({objectMode:!0});(!n||n(t))&&a.write(s?t:t.fullpath());let c=new Set,l=[t],h=0,f=()=>{let d=!1;for(;!d;){let p=l.shift();if(!p){h===0&&a.end();return}h++,c.add(p);let g=(w,S,b=!1)=>{if(w)return a.emit("error",w);if(i&&!b){let y=[];for(let C of S)C.isSymbolicLink()&&y.push(C.realpath().then(x=>x?.isUnknown()?x.lstat():x));if(y.length){Promise.all(y).then(()=>g(null,S,!0));return}}for(let y of S)y&&(!n||n(y))&&(a.write(s?y:y.fullpath())||(d=!0));h--;for(let y of S){let C=y.realpathCached()||y;C.shouldWalk(c,o)&&l.push(C)}d&&!a.flowing?a.once("drain",f):m||f()},m=!0;p.readdirCB(g,!0),m=!1}};return f(),a}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,a=new ft({objectMode:!0}),c=new Set;(!n||n(t))&&a.write(s?t:t.fullpath());let l=[t],h=0,f=()=>{let d=!1;for(;!d;){let p=l.shift();if(!p){h===0&&a.end();return}h++,c.add(p);let g=p.readdirSync();for(let m of g)(!n||n(m))&&(a.write(s?m:m.fullpath())||(d=!0));h--;for(let m of g){let w=m;if(m.isSymbolicLink()){if(!(i&&(w=m.realpathSync())))continue;w.isUnknown()&&w.lstatSync()}w.shouldWalk(c,o)&&l.push(w)}}d&&!a.flowing&&a.once("drain",f)};return f(),a}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[mi](e)}},$t=class extends Ce{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,kt.win32,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return kt.win32.parse(t).root.toUpperCase()}newRoot(t){return new we(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},At=class extends Ce{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,kt.posix,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new Se(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Kt=class extends At{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}},Ko=process.platform==="win32"?we:Se,gi=process.platform==="win32"?$t:process.platform==="darwin"?Kt:At;var kn=r=>r.length>=1,$n=r=>r.length>=1,Ft=class r{#t;#e;#n;length;#r;#o;#y;#w;#a;#f;#c=!0;constructor(t,e,s,i){if(!kn(t))throw new TypeError("empty pattern list");if(!$n(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#e=e,this.#n=s,this.#r=i,this.#n===0){if(this.isUNC()){let[n,o,a,c,...l]=this.#t,[h,f,d,p,...g]=this.#e;l[0]===""&&(l.shift(),g.shift());let m=[n,o,a,c,""].join("/"),w=[h,f,d,p,""].join("/");this.#t=[m,...l],this.#e=[w,...g],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#t,[a,...c]=this.#e;o[0]===""&&(o.shift(),c.shift());let l=n+"/",h=a+"/";this.#t=[l,...o],this.#e=[h,...c],this.length=this.#t.length}}}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===_}isRegExp(){return this.#t[this.#n]instanceof RegExp}globString(){return this.#y=this.#y||(this.#n===0?this.isAbsolute()?this.#e[0]+this.#e.slice(1).join("/"):this.#e.join("/"):this.#e.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new r(this.#t,this.#e,this.#n+1,this.#r),this.#o.#f=this.#f,this.#o.#a=this.#a,this.#o.#w=this.#w,this.#o):this.#o=null}isUNC(){let t=this.#t;return this.#a!==void 0?this.#a:this.#a=this.#r==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#w!==void 0?this.#w:this.#w=this.#r==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#f!==void 0?this.#f:this.#f=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#c)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#c?!1:(this.#c=!1,!0)}};var An=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",_t=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:n,platform:o=An}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:n,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(let a of t)this.add(a)}add(t){let e=new N(t,this.mmopts);for(let s=0;s[t,!!(e&2),!!(e&1)])}},Ze=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},Yt=class r{hasWalkedCache;matches=new Ye;subwalks=new Ze;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new Ke}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=n.rest();if(f)n=f;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let c,l,h=!1;for(;typeof(c=n.pattern())=="string"&&(l=n.rest());)i=i.resolve(c),n=l,h=!0;if(c=n.pattern(),l=n.rest(),h){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof c=="string"){let f=c===".."||c===""||c===".";this.matches.add(i.resolve(c),a,f);continue}else if(c===_){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let f=l?.pattern(),d=l?.rest();if(!l||(f===""||f===".")&&!d)this.matches.add(i,a,f===""||f===".");else if(f===".."){let p=i.parent||i;d?this.hasWalkedCache.hasWalked(p,d)||this.subwalks.add(p,d):this.matches.add(p,a,!0)}}else c instanceof RegExp&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let n of e)for(let o of s){let a=o.isAbsolute(),c=o.pattern(),l=o.rest();c===_?i.testGlobstar(n,o,l,a):c instanceof RegExp?i.testRegExp(n,c,l,a):i.testString(n,c,l,a)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),i);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),i)}}testRegExp(t,e,s,i){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};var Fn=(r,t)=>typeof r=="string"?new _t([r],t):Array.isArray(r)?new _t(r,t):r,ye=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#e;#n;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#n=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#e=Fn(s.ignore??[],s),!this.includeChildMatches&&typeof this.#e.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#r(t){return this.seen.has(t)||!!this.#e?.ignored?.(t)}#o(t){return!!this.#e?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;t=s}let n=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&n?.isSymbolicLink()){let o=await n.realpath();o&&(o.isUnknown()||this.opts.stat)&&await o.lstat()}return this.matchCheckTest(n,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#r(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;t=s}let n=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&n?.isSymbolicLink()){let o=n.realpathSync();o&&(o?.isUnknown()||this.opts.stat)&&o.lstatSync()}return this.matchCheckTest(n,e)}matchFinish(t,e){if(this.#r(t))return;if(!this.includeChildMatches&&this.#e?.add){let n=`${t.relativePosix()}/**`;this.#e.add(n)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let n=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(n+i)}else{let n=this.opts.posix?t.relativePosix():t.relative(),o=this.opts.dotRelative&&!n.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(n?o+n+i:"."+i)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.matchFinish(i,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Yt(this.opts),s)}walkCB2(t,e,s,i){if(this.#o(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let n=1,o=()=>{--n===0&&i()};for(let[a,c,l]of s.matches.entries())this.#r(a)||(n++,this.match(a,c,l).then(()=>o()));for(let a of s.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;n++;let c=a.readdirCached();a.calledReaddir()?this.walkCB3(a,c,s,o):a.readdirCB((l,h)=>this.walkCB3(a,h,s,o),!0)}o()}walkCB3(t,e,s,i){s=s.filterEntries(t,e);let n=1,o=()=>{--n===0&&i()};for(let[a,c,l]of s.matches.entries())this.#r(a)||(n++,this.match(a,c,l).then(()=>o()));for(let[a,c]of s.subwalks.entries())n++,this.walkCB2(a,c,s.child(),o);o()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Yt(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#o(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let n=1,o=()=>{--n===0&&i()};for(let[a,c,l]of s.matches.entries())this.#r(a)||this.matchSync(a,c,l);for(let a of s.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;n++;let c=a.readdirSync();this.walkCB3Sync(a,c,s,o)}o()}walkCB3Sync(t,e,s,i){s=s.filterEntries(t,e);let n=1,o=()=>{--n===0&&i()};for(let[a,c,l]of s.matches.entries())this.#r(a)||this.matchSync(a,c,l);for(let[a,c]of s.subwalks.entries())n++,this.walkCB2Sync(a,c,s.child(),o);o()}},Zt=class extends ye{matches=new Set;constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(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}},te=class extends ye{results;constructor(t,e,s){super(t,e,s),this.results=new ft({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,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 _n=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",H=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(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,wi.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(c=>c.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(c=>c.includes("/")?c:`./**/${c}`)}if(this.pattern=t,this.platform=e.platform||_n,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let c=e.platform==="win32"?$t:e.platform==="darwin"?Kt:e.platform?At:gi;this.scurry=new c(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",i={...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},n=this.pattern.map(c=>new N(c,i)),[o,a]=n.reduce((c,l)=>(c[0].push(...l.set),c[1].push(...l.globParts),c),[[],[]]);this.patterns=o.map((c,l)=>{let h=a[l];if(!h)throw new Error("invalid pattern object");return new Ft(c,h,0,this.platform)})}async walk(){return[...await new Zt(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 Zt(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 te(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 te(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 ts=(r,t={})=>{Array.isArray(r)||(r=[r]);for(let e of r)if(new N(e,t).hasMagic())return!0;return!1};function be(r,t={}){return new H(r,t).streamSync()}function yi(r,t={}){return new H(r,t).stream()}function ee(r,t={}){return new H(r,t).walkSync()}async function Si(r,t={}){return new H(r,t).walk()}function Ee(r,t={}){return new H(r,t).iterateSync()}function bi(r,t={}){return new H(r,t).iterate()}var jn=be,On=Object.assign(yi,{sync:be}),Rn=Ee,Pn=Object.assign(bi,{sync:Ee}),rt=Object.assign(ee,{stream:be,iterate:Ee}),Ci=Object.assign(Si,{glob:Si,globSync:ee,sync:rt,globStream:yi,stream:On,globStreamSync:be,streamSync:jn,globIterate:bi,iterate:Pn,globIterateSync:Ee,iterateSync:Rn,Glob:H,hasMagic:ts,escape:Et,unescape:U});Ci.glob=Ci;var fs=require("child_process"),Te=require("fs"),Ot=require("path"),ji=ie(rs());var Y=require("fs"),jt=require("path");var _i,os=Date.now().toString(),as=Date.now(),ns=new Map;function u(r,t,...e){if(!_i)throw new Error("Source root directory is not set. Call setSourceRootDirectory() first.");let i=Date.now()-as,n=`[CDS-${os} ${i}] ${r.toUpperCase()}: `;switch(r){case"debug":case"info":typeof t=="string"?console.log(n+t,...e):console.log(n,t,...e);break;case"warn":typeof t=="string"?console.warn(n+t,...e):console.warn(n,t,...e);break;case"error":typeof t=="string"?console.error(n+t,...e):console.error(n,t,...e);break;default:throw new Error(`Invalid log level: ${String(r)}`)}}function cs(r,t=Date.now()){let e=t-r;if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(2)}s`;{let s=Math.floor(e/6e4),i=(e%6e4/1e3).toFixed(2);return`${s}m ${i}s`}}function ls(r){u("info",`=== CDS EXTRACTOR START [${os}] ===`),u("info",`Source Root: ${r}`)}function dt(r=!0,t){let e=Date.now(),s=cs(as,e),i=r?"SUCCESS":"FAILURE";t&&u("info",t),u("info",`=== CDS EXTRACTOR END [${os}] - ${i} ===`),u("info",`Total Duration: ${s}`)}function xe(r,t){let e=Date.now(),s=cs(as,e),i=t?` - ${t}`:"";u("info",`MILESTONE: ${r} (after ${s})${i}`)}function St(r){ns.set(r,Date.now()),u("debug",`Started: ${r}`)}function pt(r){let t=ns.get(r);if(t){let e=cs(t);ns.delete(r),u("info",`Completed: ${r} (took ${e})`)}else u("warn",`No start time found for operation: ${r}`)}function hs(r){_i=r}function se(r){let t=r.statusSummary,e=[];if(e.push("=".repeat(80)),e.push("CDS EXTRACTOR STATUS REPORT"),e.push("=".repeat(80)),e.push(""),e.push("OVERALL SUMMARY:"),e.push(` Status: ${t.overallSuccess?"SUCCESS":"FAILED"}`),e.push(` Current Phase: ${r.currentPhase.toUpperCase()}`),e.push(` Projects: ${t.totalProjects}`),e.push(` CDS Files: ${t.totalCdsFiles}`),e.push(` JSON Files Generated: ${t.jsonFilesGenerated}`),e.push(""),e.push("COMPILATION SUMMARY:"),e.push(` Total Tasks: ${t.totalCompilationTasks}`),e.push(` Successful: ${t.successfulCompilations}`),e.push(` Failed: ${t.failedCompilations}`),e.push(` Skipped: ${t.skippedCompilations}`),e.push(""),e.push("PERFORMANCE:"),e.push(` Total Duration: ${t.performance.totalDurationMs}ms`),e.push(` Parsing: ${t.performance.parsingDurationMs}ms`),e.push(` Compilation: ${t.performance.compilationDurationMs}ms`),e.push(` Extraction: ${t.performance.extractionDurationMs}ms`),t.performance.totalDurationMs>0){let s=Math.round(t.performance.parsingDurationMs/t.performance.totalDurationMs*100),i=Math.round(t.performance.compilationDurationMs/t.performance.totalDurationMs*100),n=Math.round(t.performance.extractionDurationMs/t.performance.totalDurationMs*100);e.push(" Breakdown:"),e.push(` Parsing: ${s}%`),e.push(` Compilation: ${i}%`),e.push(` Extraction: ${n}%`)}if(e.push(""),t.criticalErrors.length>0){e.push("CRITICAL ERRORS:");for(let s of t.criticalErrors)e.push(` - ${s}`);e.push("")}if(t.warnings.length>0){e.push("WARNINGS:");for(let s of t.warnings)e.push(` - ${s}`);e.push("")}return e.push("=".repeat(80)),e.join(` +`)}function nt(r){return(0,Y.existsSync)(r)&&(0,Y.statSync)(r).isDirectory()}function Ct(r){return(0,Y.existsSync)(r)&&(0,Y.statSync)(r).isFile()}function ve(r){if(!nt(r)){u("info",`Directory not found: ${r}`);return}u("info",`Processing JSON files in directory: ${r}`);let t=(0,Y.readdirSync)(r,{withFileTypes:!0});for(let e of t){let s=(0,jt.join)(r,e.name);if(e.isDirectory())ve(s);else if(e.isFile()&&e.name.endsWith(".json")&&!e.name.endsWith(".cds.json")){let i=(0,jt.format)({...(0,jt.parse)(s),base:"",ext:".cds.json"});(0,Y.renameSync)(s,i),u("info",`Renamed CDS output file from ${s} to ${i}`)}}}var J={commandResults:new Map,availableCacheDirs:[],initialized:!1};function us(r,t){try{return Un(r,t)}catch(e){let s=`Failed to determine CDS command: ${String(e)}`;throw u("error",s),new Error(s)}}function Jn(r){if(J.availableCacheDirs.length>0)return J.availableCacheDirs;let t=(0,Ot.join)(r,".cds-extractor-cache"),e=[];try{if((0,Te.existsSync)(t)){let s=(0,Te.readdirSync)(t,{withFileTypes:!0});for(let i of s)if(i.isDirectory()&&i.name.startsWith("cds-")){let n=(0,Ot.join)(t,i.name),o=(0,Ot.join)(n,"node_modules",".bin","cds");Ct(o)&&e.push(n)}}}catch(s){u("debug",`Failed to discover cache directories: ${String(s)}`)}return J.availableCacheDirs=e,e}function Un(r,t){if(Gn(t),r){let s=(0,Ot.join)(r,"node_modules",".bin","cds");if(Ct(s)&&De(s,t,!0).works)return s}for(let s of J.availableCacheDirs){let i=(0,Ot.join)(s,"node_modules",".bin","cds");if(De(i,t,!0).works)return i}if(J.globalCommand)return J.globalCommand;let e=["npx -y --package @sap/cds cds","npx --yes @sap/cds-dk cds"];for(let s of e)if(De(s,t,!0).works)return s;return"npx -y --package @sap/cds-dk cds"}function Gn(r){if(J.initialized)return;u("info","Initializing CDS command cache...");let t=["cds","npx -y --package @sap/cds-dk cds"];for(let s of t){let i=De(s,r,!0);if(i.works){J.globalCommand=s,u("info",`Found working global CDS command: ${s} (v${i.version??"unknown"})`);break}}let e=Jn(r);e.length>0&&u("info",`Discovered ${e.length} CDS cache director${e.length===1?"y":"ies"}`),J.initialized=!0}function De(r,t,e=!1){let s=J.commandResults.get(r);if(s)return s;try{let i,n={...process.env,CODEQL_EXTRACTOR_CDS_WIP_DATABASE:void 0,CODEQL_RUNNER:void 0};if(r.includes("node ")){let l=r.split(" "),h=l[0],f=l[1].replace(/"/g,"");i=(0,fs.execFileSync)(h,[f,"--version"],{encoding:"utf8",stdio:"pipe",timeout:5e3,cwd:t,env:n}).toString()}else{let l=(0,ji.quote)([r,"--version"]);i=(0,fs.execFileSync)("sh",["-c",l],{encoding:"utf8",stdio:"pipe",timeout:5e3,cwd:t,env:n}).toString()}let o=i.match(/(\d+\.\d+\.\d+)/),c={works:!0,version:o?o[1]:void 0};return J.commandResults.set(r,c),c}catch(i){let n=String(i);e||u("debug",`CDS command test failed for '${r}': ${n}`);let o={works:!1,error:n};return J.commandResults.set(r,o),o}}var ps=require("child_process"),k=require("path");var Oi=require("child_process"),Rt=require("path");function ds(r,t){try{let e={shell:!0,stdio:"pipe",env:{...process.env}};if(t){let i=(0,Rt.join)(t,"node_modules");e.env={...process.env,NODE_PATH:`${i}${Rt.delimiter}${process.env.NODE_PATH??""}`,PATH:`${(0,Rt.join)(i,".bin")}${Rt.delimiter}${process.env.PATH}`,npm_config_prefix:t}}let s=(0,Oi.spawnSync)(r,["--version"],e);if(s.status===0&&s.stdout){let i=s.stdout.toString().trim(),n=i.match(/@sap\/cds[^0-9]*([0-9]+\.[0-9]+\.[0-9]+)/);return n?.[1]?n[1]:i}return}catch{return}}function ms(r,t,e,s,i,n){try{let o=(0,k.resolve)(r);if(!Ct(o))throw new Error(`Expected CDS file '${o}' does not exist.`);let a=ds(e,s),c=a?`with CDS v${a}`:"",l=qn(t,e,s);if(!i||!n||!i.has(n))throw new Error(`Project directory '${n}' not found in projectMap. Ensure the project is properly initialized.`);let h=i.get(n),f=(0,k.relative)(t,o);return Kn(h)?Qn(o,t,n,e,l,c):Xn(h,f)?(u("info",`${o} identified as a root CDS file - using project-aware compilation for root file ${c}...`),Hn(o,t,n,e,l,c)):(u("info",`${o} is imported by other files - will be compiled as part of a project ${c}...`),{success:!0,outputPath:`${o}.json`,compiledAsProject:!0,message:"File was compiled as part of a project-based compilation"})}catch(o){return{success:!1,message:String(o)}}}function Qn(r,t,e,s,i,n){u("info",`${r} is part of a CAP project - using project-aware compilation ${n}...`);let o=(0,k.join)(t,e),a=["db","srv","app"],c=[];for(let w of a){let S=(0,k.join)(o,w);nt(S)&&c.push(w)}let l=ee((0,k.join)(o,"**/*.cds"),{nodir:!0,ignore:["**/node_modules/**"]});if(l.length===0)throw new Error(`Project directory '${e}' does not contain any CDS files and cannot be compiled`);if(c.length===0)if(ee((0,k.join)(o,"*.cds")).length>0)c.push(".");else{let S=new Set(l.map(b=>{let y=(0,k.relative)(o,b),C=y.split("/")[0];return C===y?".":C}));c.push(...Array.from(S))}let h=(0,k.join)(e,"model.cds.json"),f=(0,k.join)(t,h),d={...i,cwd:t},g=["compile",...c.map(w=>w==="."?e:(0,k.join)(e,w)),"--to","json","--dest",(0,k.join)(e,"model.cds.json"),"--locations","--log-level","warn"];u("info",`Compiling CAP project directories: ${c.join(", ")}`),u("info",`Executing CDS command in directory ${o}: command='${s}' args='${JSON.stringify(g)}'`);let m=(0,ps.spawnSync)(s,g,d);if(m.error)throw u("error",`SpawnSync error: ${m.error.message}`),new Error(`Error executing CDS compiler: ${m.error.message}`);if(m.stderr&&m.stderr.length>0&&u("warn",`CDS stderr output: ${m.stderr.toString()}`),m.status!==0)throw u("error",`CDS command failed with status ${m.status}`),u("error",`Command: ${s} ${g.map(w=>w.includes(" ")?`"${w}"`:w).join(" ")}`),u("error",`Stdout: ${m.stdout?.toString()||"No stdout"}`),u("error",`Stderr: ${m.stderr?.toString()||"No stderr"}`),new Error(`Could not compile the CAP project ${e}. +Reported error(s): +\`\`\` +${m.stderr?.toString()||"Unknown error"} +\`\`\``);if(!Ct(f)&&!nt(f))throw new Error(`CAP project '${e}' was not compiled to JSON. This is likely because the project structure is invalid.`);return nt(f)?(u("info",`CDS compiler generated JSON to output directory: ${f}`),ve(f)):u("info",`CDS compiler generated JSON to file: ${f}`),{success:!0,outputPath:f,compiledAsProject:!0,message:"Project was compiled using project-aware compilation"}}function Hn(r,t,e,s,i,n){let o=(0,k.relative)(t,r),a=`${r}.json`,c=["compile",o,"--to","json","--dest",`${o}.json`,"--locations","--log-level","warn"];u("info",`Compiling root CDS file using project-aware approach: ${o}`),u("info",`Executing CDS command: command='${s}' args='${JSON.stringify(c)}'`);let l=(0,ps.spawnSync)(s,c,i);if(l.error)throw u("error",`SpawnSync error: ${l.error.message}`),new Error(`Error executing CDS compiler: ${l.error.message}`);if(l.stderr&&l.stderr.length>0&&u("warn",`CDS stderr output: ${l.stderr.toString()}`),l.status!==0)throw u("error",`CDS command failed with status ${l.status}`),u("error",`Command: ${s} ${c.map(h=>h.includes(" ")?`"${h}"`:h).join(" ")}`),u("error",`Stdout: ${l.stdout?.toString()||"No stdout"}`),u("error",`Stderr: ${l.stderr?.toString()||"No stderr"}`),new Error(`Could not compile the root CDS file ${o}. +Reported error(s): +\`\`\` +${l.stderr?.toString()||"Unknown error"} +\`\`\``);if(!Ct(a)&&!nt(a))throw new Error(`Root CDS file '${o}' was not compiled to JSON. Expected output: ${a}`);return nt(a)?(u("info",`CDS compiler generated JSON to output directory: ${a}`),ve(a)):u("info",`CDS compiler generated JSON to file: ${a}`),{success:!0,outputPath:a,compiledAsProject:!0,message:"Root file compiled using project-aware compilation"}}function qn(r,t,e){let s={cwd:r,shell:!1,stdio:"pipe",env:{...process.env}},i=t.includes("node_modules/.bin/");if(e&&!i){let n=(0,k.join)(e,"node_modules");s.env={...process.env,NODE_PATH:`${n}${k.delimiter}${process.env.NODE_PATH??""}`,PATH:`${(0,k.join)(n,".bin")}${k.delimiter}${process.env.PATH}`,npm_config_prefix:e,npm_config_global:"false",CDS_HOME:e}}else if(i){let n={...process.env};delete n.NODE_PATH,delete n.npm_config_prefix,delete n.npm_config_global,delete n.CDS_HOME,s.env=n}return s}function Xn(r,t){return r?.cdsFilesToCompile?.includes(t)??!0}function Kn(r){return r?.cdsFilesToCompile?.includes("__PROJECT_LEVEL_COMPILATION__")??!1}var Ri=require("child_process"),Pi=require("path"),Mi=ie(rs());function Li(r,t,e,s,i,n,o){try{let a=(0,Mi.quote)([t]);return(0,Ri.execFileSync)(e,["database","add-diagnostic","--extractor-name=cds","--ready-for-status-page",`--source-id=${s}`,`--source-name=${i}`,`--severity=${n}`,`--markdown-message=${a.slice(1,-1)}`,`--file-path=${(0,Pi.resolve)(r)}`,"--",`${process.env.CODEQL_EXTRACTOR_CDS_WIP_DATABASE??""}`]),u("info",`Added ${n} diagnostic for ${o}: ${r}`),!0}catch(a){return u("error",`Failed to add ${n} diagnostic for ${o}=${r} : ${String(a)}`),!1}}function ke(r,t,e){return Li(r,t,e,"cds/compilation-failure","Failure to compile one or more SAP CAP CDS files","error","source file")}function gs(r,t,e){return Li(r,t,e,"cds/js-extractor-failure","Failure in JavaScript extractor for SAP CAP CDS files","error","extraction file")}function Yn(r,t,e,s){let i=`${r.id}_${Date.now()}_${Math.random().toString(36).substr(2,5)}`,n=new Date,o={id:i,cdsCommand:t,cacheDir:e,timestamp:n,result:{success:!1,timestamp:n}};try{let a=r.sourceFiles[0],c=ms(a,s.sourceRootDir,t,e,new Map(Array.from(s.projects.entries()).map(([h,f])=>[h,{cdsFiles:f.cdsFiles,cdsFilesToCompile:f.cdsFilesToCompile,expectedOutputFiles:f.expectedOutputFiles,projectDir:f.projectDir,dependencies:f.dependencies,imports:f.imports,packageJson:f.packageJson,compilationConfig:f.compilationConfig}])),r.projectDir),l=new Date;o.result={...c,timestamp:l,durationMs:l.getTime()-n.getTime(),commandUsed:t,cacheDir:e},c.success&&c.outputPath&&s.statusSummary.jsonFilesGenerated++}catch(a){let c=new Date;o.error={message:String(a),stack:a instanceof Error?a.stack:void 0},o.result.timestamp=c,o.result.durationMs=c.getTime()-n.getTime()}return r.attempts.push(o),o}function Ii(r,t,e,s,i){return{id:`${r}_${s}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:r,status:"pending",sourceFiles:t,expectedOutputFiles:e,projectDir:s,attempts:[],useProjectLevelCompilation:i,dependencies:[]}}function Zn(r,t,e){return{cdsCommand:r,cacheDir:t,useProjectLevelCompilation:e,versionCompatibility:{isCompatible:!0},maxRetryAttempts:3}}function to(r,t,e,s){r.status="in_progress";let i=t.enhancedCompilationConfig;if(!i)throw new Error(`No compilation configuration found for project ${t.projectDir}`);let n=Yn(r,i.cdsCommand,i.cacheDir,e);if(n.result.success){r.status="success",e.statusSummary.successfulCompilations++;return}let o=n.error?new Error(n.error.message):new Error("Compilation failed");r.status="failed",r.errorSummary=o?.message||"Compilation failed",e.statusSummary.failedCompilations++;for(let a of r.sourceFiles)ke(a,r.errorSummary,s);u("error",`Compilation failed for task ${r.id}: ${r.errorSummary}`)}function eo(r,t){u("info","Starting compilation execution for all projects..."),r.currentPhase="compiling";let e=new Date,s=[];for(let n of r.projects.values())for(let o of n.compilationTasks)s.push({task:o,project:n});u("info",`Executing ${s.length} compilation task(s)...`);for(let{task:n,project:o}of s)try{to(n,o,r,t)}catch(a){let c=`Failed to execute compilation task ${n.id}: ${String(a)}`;u("error",c),r.errors.critical.push({phase:"compiling",message:c,timestamp:new Date,stack:a instanceof Error?a.stack:void 0}),n.status="failed",n.errorSummary=c,r.statusSummary.failedCompilations++}for(let n of r.projects.values())if(n.compilationTasks.every(a=>a.status==="success"||a.status==="failed")){let a=n.compilationTasks.some(c=>c.status==="failed");n.status=a?"failed":"completed",n.timestamps.compilationCompleted=new Date}let i=new Date;r.statusSummary.performance.compilationDurationMs=i.getTime()-e.getTime(),u("info",`Compilation execution completed. Success: ${r.statusSummary.successfulCompilations}, Failed: ${r.statusSummary.failedCompilations}`)}function ws(r,t,e){try{so(r,t),eo(r,e);let s=r.statusSummary.failedCompilations>0||r.errors.critical.length>0;r.statusSummary.overallSuccess=!s,r.currentPhase=s?"failed":"completed";let i=se(r);u("info",`CDS Extractor Status Report : Post-Compilation... +`+i)}catch(s){let i=`Compilation orchestration failed: ${String(s)}`;throw u("error",i),r.errors.critical.push({phase:"compiling",message:i,timestamp:new Date,stack:s instanceof Error?s.stack:void 0}),r.currentPhase="failed",r.statusSummary.overallSuccess=!1,s}}function so(r,t){u("info","Planning compilation tasks for all projects..."),r.currentPhase="compilation_planning";for(let[s,i]of r.projects.entries())try{let n=t.get(s),o=us(n,r.sourceRootDir),a=Zn(o,n,i.cdsFilesToCompile.includes("__PROJECT_LEVEL_COMPILATION__"));if(i.enhancedCompilationConfig=a,i.cdsFilesToCompile.includes("__PROJECT_LEVEL_COMPILATION__")){let c=Ii("project",i.cdsFiles,i.expectedOutputFiles,s,!0);i.compilationTasks=[c]}else{let c=[];for(let l of i.cdsFilesToCompile){let h=`${l}.json`,f=Ii("file",[l],[h],s,!1);c.push(f)}i.compilationTasks=c}i.status="compilation_planned",i.timestamps.compilationStarted=new Date,u("info",`Planned ${i.compilationTasks.length} compilation task(s) for project ${s}`)}catch(n){let o=`Failed to plan compilation for project ${s}: ${String(n)}`;u("error",o),r.errors.critical.push({phase:"compilation_planning",message:o,timestamp:new Date,stack:n instanceof Error?n.stack:void 0}),i.status="failed"}let e=Array.from(r.projects.values()).reduce((s,i)=>s+i.compilationTasks.length,0);r.statusSummary.totalCompilationTasks=e,u("info",`Compilation planning completed. Total tasks: ${e}`)}var io=require("path");var M=require("path");var v=require("fs"),E=require("path");function Ni(r,t){if(!r||!t)throw new Error(`Unable to determine CDS files for project dir '${t}'; both sourceRootDir and projectDir must be provided.`);let e=r.replace(/[/\\]+$/,""),s=t.replace(/[/\\]+$/,"");if(!s.startsWith(e)&&s!==e)throw new Error("projectDir must be a subdirectory of sourceRootDir or equal to sourceRootDir.");try{return rt((0,E.join)(t,"**/*.cds"),{nodir:!0,ignore:["**/node_modules/**","**/*.testproj/**"]}).map(n=>(0,E.relative)(r,n))}catch(i){return u("error",`Error finding CDS files in ${t}: ${String(i)}`),[]}}function Wi(r){if(!r||!(0,v.existsSync)(r))throw new Error(`Source root directory '${r}' does not exist.`);let t=new Set,e=rt((0,E.join)(r,"**/package.json"),{nodir:!0,ignore:["**/node_modules/**","**/*.testproj/**"]}),s=rt((0,E.join)(r,"**/*.cds"),{nodir:!0,ignore:["**/node_modules/**","**/*.testproj/**"]}),i=new Set;for(let n of e)i.add((0,E.dirname)(n));for(let n of s){let o=(0,E.dirname)(n),a=ro(o,r);a?i.add(a):i.add(o)}for(let n of i)if($e(n)){let a=(0,E.relative)(r,n)||".",c=!0,l=Array.from(t);for(let h of l){let f=(0,E.join)(r,h);if(n.startsWith(f+E.sep)){let d=(0,E.join)(f,"package.json"),p=Mt(d);p?.workspaces&&Array.isArray(p.workspaces)&&p.workspaces.length>0&&(Bi(f)||Vi(f))?c=!0:c=!1;break}if(f.startsWith(n+E.sep)){let d=(0,E.join)(n,"package.json"),p=Mt(d);p?.workspaces&&Array.isArray(p.workspaces)&&p.workspaces.length>0&&$e(f)||t.delete(h)}}c&&t.add(a)}return Array.from(t).sort()}function zi(r){if(!(0,v.existsSync)(r))throw new Error(`File does not exist: ${r}`);let t=(0,v.readFileSync)(r,"utf8"),e=[],s=/using\s+(?:{[^}]+}|[\w.]+(?:\s+as\s+[\w.]+)?)\s+from\s+['"`]([^'"`]+)['"`]\s*;/g,i;for(;(i=s.exec(t))!==null;){let n=i[1];e.push({statement:i[0],path:n,isRelative:n.startsWith("./")||n.startsWith("../"),isModule:!n.startsWith("./")&&!n.startsWith("../")&&!n.startsWith("/")})}return e}function ro(r,t){if(r.includes("node_modules")||r.includes(".testproj"))return null;let e=r;for(;e.startsWith(t);){if($e(e)){let a=(0,E.basename)(e);if(["srv","db","app"].includes(a)){let h=(0,E.dirname)(e);if(h!==e&&h.startsWith(t)&&!h.includes("node_modules")&&!h.includes(".testproj")&&$e(h))return h}let l=(0,E.dirname)(e);if(l!==e&&l.startsWith(t)&&!l.includes("node_modules")&&!l.includes(".testproj")){let h=(0,v.existsSync)((0,E.join)(l,"db"))&&(0,v.statSync)((0,E.join)(l,"db")).isDirectory(),f=(0,v.existsSync)((0,E.join)(l,"srv"))&&(0,v.statSync)((0,E.join)(l,"srv")).isDirectory(),d=(0,v.existsSync)((0,E.join)(l,"app"))&&(0,v.statSync)((0,E.join)(l,"app")).isDirectory();if(h&&f||f&&d)return l}return e}let s=(0,v.existsSync)((0,E.join)(e,"db"))&&(0,v.statSync)((0,E.join)(e,"db")).isDirectory(),i=(0,v.existsSync)((0,E.join)(e,"srv"))&&(0,v.statSync)((0,E.join)(e,"srv")).isDirectory(),n=(0,v.existsSync)((0,E.join)(e,"app"))&&(0,v.statSync)((0,E.join)(e,"app")).isDirectory();if(s&&i||i&&n)return e;let o=(0,E.dirname)(e);if(o===e)break;e=o}return r}function $e(r){try{if(r.includes("node_modules")||r.includes(".testproj"))return!1;let t=Bi(r),e=Vi(r),s=t||e;if(Ui(r)){if(!s)return!1;let n=(0,E.join)(r,"package.json"),o=Mt(n);return!(o?.workspaces&&Array.isArray(o.workspaces)&&o.workspaces.length>0&&!s)}return s}catch(t){return u("error",`Error checking directory ${r}: ${String(t)}`),!1}}function Bi(r){let t=[(0,E.join)(r,"db"),(0,E.join)(r,"srv"),(0,E.join)(r,"app")];for(let e of t)if((0,v.existsSync)(e)&&(0,v.statSync)(e).isDirectory()&&rt((0,E.join)(e,"**/*.cds"),{nodir:!0}).length>0)return!0;return!1}function Vi(r){return rt((0,E.join)(r,"*.cds")).length>0}function Mt(r){if((0,v.existsSync)(r))try{let t=(0,v.readFileSync)(r,"utf8");return JSON.parse(t)}catch(t){u("warn",`Error parsing package.json at ${r}: ${String(t)}`);return}}function Ji(r,t){if(!t.cdsFiles||t.cdsFiles.length===0)return{filesToCompile:[],expectedOutputFiles:[]};if(t.cdsFiles.length===1){let n=[...t.cdsFiles];return{filesToCompile:n,expectedOutputFiles:Pt(n,t.projectDir)}}let e=(0,E.join)(r,t.projectDir),s=no(t.cdsFiles),i=Ui(e);if(t.cdsFiles.length>1&&(s||i)){let n=["__PROJECT_LEVEL_COMPILATION__"];return{filesToCompile:n,expectedOutputFiles:Pt(n,t.projectDir)}}if(!t.imports||t.imports.size===0){let n=[...t.cdsFiles];return{filesToCompile:n,expectedOutputFiles:Pt(n,t.projectDir)}}try{let n=new Map;for(let a of t.cdsFiles)try{let c=(0,E.join)(r,a);if((0,v.existsSync)(c)){let l=t.imports.get(a)??[];for(let h of l)h.resolvedPath&&n.set(h.resolvedPath,!0)}}catch(c){u("warn",`Error processing imports for ${a}: ${String(c)}`)}let o=[];for(let a of t.cdsFiles){let c=(0,E.relative)(r,(0,E.join)(r,a));n.has(c)||o.push(a)}if(o.length===0){u("warn",`No root CDS files identified in project ${t.projectDir}, will compile all files`);let a=[...t.cdsFiles];return{filesToCompile:a,expectedOutputFiles:Pt(a,t.projectDir)}}return{filesToCompile:o,expectedOutputFiles:Pt(o,t.projectDir)}}catch(n){u("warn",`Error determining files to compile for project ${t.projectDir}: ${String(n)}`);let o=[...t.cdsFiles];return{filesToCompile:o,expectedOutputFiles:Pt(o,t.projectDir)}}}function Pt(r,t){let e=[],s=r.includes("__PROJECT_LEVEL_COMPILATION__");if(s&&r.length!==1)throw new Error(`Invalid compilation configuration: '__PROJECT_LEVEL_COMPILATION__' must be the only element in filesToCompile array, but found ${r.length} elements: ${r.join(", ")}`);if(s){let i=(0,E.join)(t,"model.cds.json");e.push(i)}else for(let i of r)e.push(`${i}.json`);return e}function no(r){let t=r.some(i=>i.includes("db/")||i.includes("database/")),e=r.some(i=>i.includes("srv/")||i.includes("service/"));return t&&e?!0:new Set(r.map(i=>(0,E.dirname)(i)).filter(i=>i!=="."&&i!=="")).size>=2}function Ui(r){try{let t=(0,E.join)(r,"package.json"),e=Mt(t);if(e){let s={...e.dependencies??{},...e.devDependencies??{}};return!!(s["@sap/cds"]||s["@sap/cds-dk"])}return!1}catch{return!1}}function oo(r){u("info","Detecting CDS projects...");let t=Wi(r);if(t.length===0)return u("info","No CDS projects found."),new Map;u("info",`Found ${t.length} CDS project(s) under source directory.`);let e=new Map;for(let s of t){let i=(0,M.join)(r,s),n=Ni(r,i),o=(0,M.join)(i,"package.json"),a=Mt(o);e.set(s,{projectDir:s,cdsFiles:n,cdsFilesToCompile:[],expectedOutputFiles:[],packageJson:a,dependencies:[],imports:new Map})}u("info","Analyzing dependencies between CDS projects...");for(let[s,i]of e.entries())for(let n of i.cdsFiles){let o=(0,M.join)(r,n);try{let a=zi(o),c=[];for(let l of a){let h={...l};if(l.isRelative){let f=(0,M.resolve)((0,M.dirname)(o),l.path),d=f.endsWith(".cds")?f:`${f}.cds`;try{let p=(0,M.dirname)(n),g=(0,M.resolve)((0,M.join)(r,p),l.path),m=g.endsWith(".cds")?g:`${g}.cds`;m.startsWith(r)&&(h.resolvedPath=m.substring(r.length).replace(/^[/\\]/,""))}catch(p){u("warn",`Could not resolve import path for ${l.path} in ${n}: ${String(p)}`)}for(let[p,g]of e.entries()){if(p===s)continue;let m=(0,M.join)(r,p);g.cdsFiles.some(S=>(0,M.join)(r,S)===d||d.startsWith(m+M.sep))&&(i.dependencies??=[],i.dependencies.includes(g)||i.dependencies.push(g))}}else if(l.isModule&&i.packageJson){let f={...i.packageJson.dependencies??{},...i.packageJson.devDependencies??{}},d=l.path.split("/")[0].startsWith("@")?l.path.split("/").slice(0,2).join("/"):l.path.split("/")[0];f[d]}c.push(h)}i.imports?.set(n,c)}catch(a){u("warn",`Error processing imports in ${o}: ${String(a)}`)}}u("info","Determining CDS files to compile and expected output files for each project...");for(let[,s]of e.entries())try{let i=Ji(r,s);s.cdsFilesToCompile=i.filesToCompile,s.expectedOutputFiles=i.expectedOutputFiles,i.filesToCompile.includes("__PROJECT_LEVEL_COMPILATION__")?u("info",`Project ${s.projectDir}: using project-level compilation for all ${s.cdsFiles.length} CDS files, expecting ${i.expectedOutputFiles.length} output files`):u("info",`Project ${s.projectDir}: ${i.filesToCompile.length} files to compile out of ${s.cdsFiles.length} total CDS files, expecting ${i.expectedOutputFiles.length} output files`)}catch(i){u("warn",`Error determining files to compile for project ${s.projectDir}: ${String(i)}`),s.cdsFilesToCompile=[...s.cdsFiles],s.expectedOutputFiles=[]}return e}function Ss(r){let t=new Date,e={id:`cds_graph_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sourceRootDir:r,projects:new Map,debugInfo:{extractor:{runMode:"autobuild",sourceRootDir:r,startTime:t,environment:{nodeVersion:process.version,platform:process.platform,cwd:process.cwd(),argv:process.argv}},parser:{projectsDetected:0,cdsFilesFound:0,dependencyResolutionSuccess:!0,parsingErrors:[],parsingWarnings:[]},compiler:{availableCommands:[],selectedCommand:"",cacheDirectories:[],cacheInitialized:!1}},currentPhase:"parsing",statusSummary:{overallSuccess:!1,totalProjects:0,totalCdsFiles:0,totalCompilationTasks:0,successfulCompilations:0,failedCompilations:0,skippedCompilations:0,jsonFilesGenerated:0,criticalErrors:[],warnings:[],performance:{totalDurationMs:0,parsingDurationMs:0,compilationDurationMs:0,extractionDurationMs:0}},config:{maxRetryAttempts:3,enableDetailedLogging:!1,generateDebugOutput:!1,compilationTimeoutMs:3e4},errors:{critical:[],warnings:[]}};try{let s=oo(r);for(let[n,o]of s.entries()){let a={...o,id:`project_${n.replace(/[^a-zA-Z0-9]/g,"_")}_${Date.now()}`,enhancedCompilationConfig:void 0,compilationTasks:[],parserDebugInfo:{dependenciesResolved:[],importErrors:[],parseErrors:new Map},status:"discovered",timestamps:{discovered:new Date}};e.projects.set(n,a)}e.statusSummary.totalProjects=e.projects.size,e.statusSummary.totalCdsFiles=Array.from(e.projects.values()).reduce((n,o)=>n+o.cdsFiles.length,0),e.debugInfo.parser.projectsDetected=e.projects.size,e.debugInfo.parser.cdsFilesFound=e.statusSummary.totalCdsFiles,e.currentPhase="dependency_resolution";let i=new Date;return e.debugInfo.extractor.endTime=i,e.debugInfo.extractor.durationMs=i.getTime()-t.getTime(),e.statusSummary.performance.parsingDurationMs=e.debugInfo.extractor.durationMs,u("info",`CDS dependency graph created with ${e.projects.size} projects and ${e.statusSummary.totalCdsFiles} CDS files`),e}catch(s){let i=`Failed to build CDS dependency graph: ${String(s)}`;return u("error",i),e.errors.critical.push({phase:"parsing",message:i,timestamp:new Date,stack:s instanceof Error?s.stack:void 0}),e.currentPhase="failed",e}}var Gi=require("child_process");function Qi(r,t,e){u("info",`Extracting the .cds.json files by running the 'javascript' extractor autobuild script: + ${t}`);let s=(0,Gi.spawnSync)(t,[],{cwd:r,env:process.env,shell:!0,stdio:"inherit"});if(s.error){let i=`Error running JavaScript extractor: ${s.error.message}`;return e&&gs(r,i,e),{success:!1,error:i}}if(s.status!==0){let i=`JavaScript extractor failed with exit code ${String(s.status)}`;return e&&gs(r,i,e),{success:!1,error:i}}return{success:!0}}var ys=require("child_process"),Cs=require("fs"),Ae=require("os"),L=require("path");function bs(){let r=(0,Ae.platform)(),t=(0,Ae.arch)(),e=r==="win32";return{platform:r,arch:t,isWindows:e,exeExtension:e?".exe":""}}function ao(){let t=bs().isWindows?"codeql.exe":"codeql",e=process.env.CODEQL_DIST;if(e){let s=(0,L.resolve)((0,L.join)(e,t));if((0,Cs.existsSync)(s))return u("info",`Using CodeQL executable from CODEQL_DIST: ${s}`),s;u("error",`CODEQL_DIST is set to '${e}', but CodeQL executable was not found at '${s}'. Please ensure this path is correct. Falling back to PATH-based discovery.`)}u("info",'CODEQL_DIST environment variable not set or invalid. Attempting to find CodeQL executable via system PATH using "codeql version --format=json".');try{let s=(0,ys.execFileSync)(t,["version","--format=json"],{encoding:"utf8",timeout:5e3,stdio:"pipe"});try{let i=JSON.parse(s);if(i&&typeof i.unpackedLocation=="string"&&i.unpackedLocation){let n=(0,L.resolve)((0,L.join)(i.unpackedLocation,t));if((0,Cs.existsSync)(n))return u("info",`CodeQL executable found via 'codeql version --format=json' at: ${n}`),n;u("warn",`'codeql version --format=json' provided unpackedLocation '${i.unpackedLocation}', but executable not found at '${n}'.`)}else u("warn","Could not determine CodeQL executable path from 'codeql version --format=json' output. 'unpackedLocation' field missing, empty, or invalid.")}catch(i){u("warn",`Failed to parse 'codeql version --format=json' output: ${String(i)}. Output was: ${s}`)}}catch(s){let i=`INFO: Failed to find CodeQL executable via 'codeql version --format=json'. Error: ${String(s)}`;s&&typeof s=="object"&&"code"in s&&s.code==="ENOENT"&&(i+=` +INFO: The command '${t}' was not found in your system PATH.`),u("info",i)}return u("error",'Failed to determine CodeQL executable path. Please ensure the CODEQL_DIST environment variable is set and points to a valid CodeQL distribution, or that the CodeQL CLI (codeql) is available in your system PATH and "codeql version --format=json" can provide its location.'),""}function co(r){let t=process.env.CODEQL_EXTRACTOR_JAVASCRIPT_ROOT??"";if(t)return u("info",`Using JavaScript extractor root from environment variable CODEQL_EXTRACTOR_JAVASCRIPT_ROOT: ${t}`),t;if(!r)return u("warn","Cannot resolve JavaScript extractor root because the CodeQL executable path was not provided or found."),"";try{t=(0,ys.execFileSync)(r,["resolve","extractor","--language=javascript"],{stdio:"pipe"}).toString().trim(),t?u("info",`JavaScript extractor root resolved to: ${t}`):u("warn",`'codeql resolve extractor --language=javascript' using '${r}' returned an empty path.`)}catch(e){u("error",`Error resolving JavaScript extractor root using '${r}': ${String(e)}`),t=""}return t}function lo(){process.env.CODEQL_EXTRACTOR_JAVASCRIPT_WIP_DATABASE=process.env.CODEQL_EXTRACTOR_CDS_WIP_DATABASE,process.env.CODEQL_EXTRACTOR_JAVASCRIPT_DIAGNOSTIC_DIR=process.env.CODEQL_EXTRACTOR_CDS_DIAGNOSTIC_DIR,process.env.CODEQL_EXTRACTOR_JAVASCRIPT_LOG_DIR=process.env.CODEQL_EXTRACTOR_CDS_LOG_DIR,process.env.CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR=process.env.CODEQL_EXTRACTOR_CDS_SCRATCH_DIR,process.env.CODEQL_EXTRACTOR_JAVASCRIPT_TRAP_DIR=process.env.CODEQL_EXTRACTOR_CDS_TRAP_DIR,process.env.CODEQL_EXTRACTOR_JAVASCRIPT_SOURCE_ARCHIVE_DIR=process.env.CODEQL_EXTRACTOR_CDS_SOURCE_ARCHIVE_DIR}function ho(r){if(!r)return"";let e=bs().isWindows?"autobuild.cmd":"autobuild.sh";return(0,L.resolve)((0,L.join)(r,"tools",e))}function Hi(){let r="";if(process.env.LGTM_INDEX_FILTERS){u("info",`Found $LGTM_INDEX_FILTERS already set to: +${process.env.LGTM_INDEX_FILTERS}`);let e=[(0,L.join)("exclude:**","*"),(0,L.join)("exclude:**","*.*")];r=` +`+process.env.LGTM_INDEX_FILTERS.split(` +`).filter(s=>s.startsWith("exclude")&&!e.some(i=>s.includes(i))).join(` +`)}let t=[(0,L.join)("exclude:**","*.*"),(0,L.join)("include:**","*.cds.json"),(0,L.join)("include:**","*.cds"),(0,L.join)("exclude:**","node_modules","**","*.*")].join(` +`);process.env.LGTM_INDEX_FILTERS=t+r,process.env.LGTM_INDEX_TYPESCRIPT="NONE",process.env.LGTM_INDEX_FILETYPES=".cds:JSON"}function qi(r){let t=[],e=bs(),s=ao();s||t.push("Failed to find CodeQL executable. Ensure CODEQL_DIST is set and valid, or CodeQL CLI is in PATH."),nt(r)||t.push(`Project root directory '${r}' does not exist.`);let i=co(s);i||(s?t.push("Failed to determine JavaScript extractor root using the found CodeQL executable."):t.push("Cannot determine JavaScript extractor root because CodeQL executable was not found.")),i&&(process.env.CODEQL_EXTRACTOR_JAVASCRIPT_ROOT=i,lo());let n=i?ho(i):"";return{success:t.length===0,errorMessages:t,codeqlExePath:s,jsExtractorRoot:i,autobuildScriptPath:n,platformInfo:e}}var Ds=require("child_process"),sr=require("crypto"),et=require("fs"),tt=require("path");var Yi=require("child_process");var Fe=new Map,Xi={hits:0,misses:0,get hitRate(){let r=this.hits+this.misses;return r>0?(this.hits/r*100).toFixed(1):"0.0"}};function Zi(r,t){if(r==="latest"||t==="latest")return{isCompatible:!0};let e=Lt(r),s=Lt(t);if(!e||!s)return{isCompatible:!1,warning:"Unable to parse version numbers for compatibility check"};let i=e.major===s.major,n=e.minor===s.minor;return i?n?{isCompatible:!0}:{isCompatible:!0,warning:`Minor version difference: @sap/cds ${r} and @sap/cds-dk ${t} - consider aligning versions for best compatibility`}:{isCompatible:!1,warning:`Major version mismatch: @sap/cds ${r} and @sap/cds-dk ${t} may not be compatible`}}function Z(r,t){return r.major!==t.major?r.major-t.major:r.minor!==t.minor?r.minor-t.minor:r.patch!==t.patch?r.patch-t.patch:r.prerelease&&!t.prerelease?-1:!r.prerelease&&t.prerelease?1:r.prerelease&&t.prerelease?r.prerelease.localeCompare(t.prerelease):0}function Es(r,t){let e=r.map(i=>Lt(i)).filter(i=>i!==null);if(e.length===0)return null;let s=e.filter(i=>vs(i,t));return s.length>0?(s.sort((i,n)=>Z(n,i)),s[0].original):(e.sort((i,n)=>Z(n,i)),e[0].original)}function xs(r){if(Fe.has(r))return Xi.hits++,Fe.get(r);Xi.misses++;try{let t=(0,Yi.execSync)(`npm view ${r} versions --json`,{encoding:"utf8",timeout:3e4}),e=JSON.parse(t),s=[];return Array.isArray(e)?s=e.filter(i=>typeof i=="string"):typeof e=="string"&&(s=[e]),Fe.set(r,s),s}catch(t){return u("warn",`Failed to fetch versions for ${r}: ${String(t)}`),Fe.set(r,[]),[]}}function Lt(r){if(r==="latest")return{major:999,minor:999,patch:999,original:r};let t=r.replace(/^[\^~>=<]+/,""),e=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,s=t.match(e);return s?{major:parseInt(s[1],10),minor:parseInt(s[2],10),patch:parseInt(s[3],10),prerelease:s[4],build:s[5],original:r}:null}function Ki(r,t){if(r===t||t==="latest")return!0;let e=Lt(r);return e?vs(e,t):!1}function _e(r,t){let e=xs("@sap/cds"),s=xs("@sap/cds-dk"),i=Es(e,r),n=Es(s,t),o=i===r||r==="latest"&&i!==null,a=n===t||t==="latest"&&n!==null,c=i?Ki(i,r):!1,l=n?Ki(n,t):!1,h=!c||!l,f;if(i&&n){let d=Zi(i,n),p=h||!o||!a||d.warning&&!d.isCompatible;d.warning&&p&&(f=d.warning)}return{resolvedCdsVersion:i,resolvedCdsDkVersion:n,cdsExactMatch:o,cdsDkExactMatch:a,warning:f,isFallback:h}}function vs(r,t){if(t==="latest")return!0;let e=Lt(t);return e?t.startsWith("^")?r.major===e.major&&Z(r,e)>=0:t.startsWith("~")?r.major===e.major&&r.minor===e.minor&&Z(r,e)>=0:t.startsWith(">=")?Z(r,e)>=0:t.startsWith(">")?Z(r,e)>0:t.startsWith("<=")?Z(r,e)<=0:t.startsWith("<")?Z(r,e)<0:Z(r,e)===0:!1}var tr=".cds-extractor-cache";function er(r,t,e){try{return(0,Ds.execFileSync)(e,["database","add-diagnostic","--extractor-name=cds","--ready-for-status-page","--source-id=cds/dependency-version-fallback","--source-name=Using fallback versions for SAP CAP CDS dependencies","--severity=warning",`--markdown-message=${t}`,`--file-path=${(0,tt.resolve)(r)}`,"--",`${process.env.CODEQL_EXTRACTOR_CDS_WIP_DATABASE??""}`]),u("info",`Added warning diagnostic for dependency fallback: ${r}`),!0}catch(s){return u("error",`Failed to add warning diagnostic for ${r}: ${String(s)}`),!1}}function fo(r){let t=new Map;for(let e of Array.from(r.values())){if(!e.packageJson)continue;let s=e.packageJson.dependencies?.["@sap/cds"]??"latest",i=e.packageJson.devDependencies?.["@sap/cds-dk"]??s;u("info",`Resolving available dependency versions for project '${e.projectDir}' with dependencies: [@sap/cds@${s}, @sap/cds-dk@${i}]`);let n=_e(s,i),{resolvedCdsVersion:o,resolvedCdsDkVersion:a,...c}=n;if(o&&a){let d;n.cdsExactMatch&&n.cdsDkExactMatch?d=" (exact match)":n.isFallback?d=" (using fallback versions)":d=" (compatible versions)",u("info",`Resolved to: @sap/cds@${o}, @sap/cds-dk@${a}${d}`)}else u("error",`Failed to resolve CDS dependencies: @sap/cds@${s}, @sap/cds-dk@${i}`);let l=o??s,h=a??i,f=(0,sr.createHash)("sha256").update(`${l}|${h}`).digest("hex");t.has(f)||t.set(f,{cdsVersion:s,cdsDkVersion:i,hash:f,resolvedCdsVersion:o??void 0,resolvedCdsDkVersion:a??void 0,...c})}return Array.from(t.values())}function Ts(r,t,e){if(r.projects.size===0)return u("info","No CDS projects found for dependency installation."),u("info","This is expected if the source contains no CAP/CDS projects and should be handled by the caller."),new Map;let s=fo(r.projects);if(s.length===0)return u("error","No CDS dependencies found in any project. This means projects were detected but lack proper @sap/cds dependencies."),u("info","Will attempt to use system-installed CDS tools if available, but compilation may fail."),new Map;u("info",`Found ${s.length} unique CDS dependency combination(s).`);for(let a of s){let{cdsVersion:c,cdsDkVersion:l,hash:h,resolvedCdsVersion:f,resolvedCdsDkVersion:d,isFallback:p}=a,g=f??c,m=d??l,w=p?" (using fallback versions)":"";u("info",`Dependency combination ${h.substring(0,8)}: @sap/cds@${g}, @sap/cds-dk@${m}${w}`)}let i=(0,tt.join)(t,tr);if(u("info",`Using cache directory '${tr}' within source root directory '${i}'`),(0,et.existsSync)(i))u("info",`Cache directory already exists: ${i}`);else try{(0,et.mkdirSync)(i,{recursive:!0}),u("info",`Created cache directory: ${i}`)}catch(a){return u("warn",`Failed to create cache directory: ${a instanceof Error?a.message:String(a)}`),u("info","Skipping dependency installation due to cache directory failure."),new Map}let n=new Map,o=0;for(let a of s){let{cdsVersion:c,cdsDkVersion:l,hash:h}=a,{resolvedCdsVersion:f,resolvedCdsDkVersion:d}=a,p=`cds-${h}`,g=(0,tt.join)(i,p);if(u("info",`Processing dependency combination ${h.substring(0,8)} in cache directory: ${p}`),!(0,et.existsSync)(g)){try{(0,et.mkdirSync)(g,{recursive:!0}),u("info",`Created cache subdirectory: ${p}`)}catch(x){u("error",`Failed to create cache directory for combination ${h.substring(0,8)} (${p}): ${x instanceof Error?x.message:String(x)}`);continue}let b=f??c,y=d??l,C={name:`cds-extractor-cache-${h}`,version:"1.0.0",private:!0,dependencies:{"@sap/cds":b,"@sap/cds-dk":y}};try{(0,et.writeFileSync)((0,tt.join)(g,"package.json"),JSON.stringify(C,null,2)),u("info",`Created package.json in cache subdirectory: ${p}`)}catch(x){u("error",`Failed to create package.json in cache directory ${p}: ${x instanceof Error?x.message:String(x)}`);continue}}let m=Array.from(r.projects.values()).find(b=>b.packageJson)?.projectDir,w=m?(0,tt.join)(t,m,"package.json"):void 0;if(!uo(g,a,p,w,e)){u("warn",`Skipping failed dependency combination ${h.substring(0,8)} (cache directory: ${p})`);continue}o++;for(let[b,y]of Array.from(r.projects.entries())){if(!y.packageJson)continue;let C=y.packageJson.dependencies?.["@sap/cds"]??"latest",x=y.packageJson.devDependencies?.["@sap/cds-dk"]??C,I=_e(C,x),at=I.resolvedCdsVersion??C,yt=I.resolvedCdsDkVersion??x,ct=a.resolvedCdsVersion??a.cdsVersion,It=a.resolvedCdsDkVersion??a.cdsDkVersion;at===ct&&yt===It&&n.set(b,g)}}if(o===0?(u("error","Failed to install any dependency combinations."),s.length>0&&u("error",`All ${s.length} dependency combination(s) failed to install. This will likely cause compilation failures.`)):o0){u("info","Project to cache directory mappings:");for(let[a,c]of Array.from(n.entries())){let l=(0,tt.join)(c).split("/").pop()??"unknown";u("info",` ${a} \u2192 ${l}`)}}else u("warn","No project to cache directory mappings created. Projects may not have compatible dependencies installed.");return n}function uo(r,t,e,s,i){let{resolvedCdsVersion:n,resolvedCdsDkVersion:o,isFallback:a,warning:c}=t;if((0,et.existsSync)((0,tt.join)(r,"node_modules","@sap","cds"))&&(0,et.existsSync)((0,tt.join)(r,"node_modules","@sap","cds-dk")))return u("info",`Using cached dependencies for @sap/cds@${n} and @sap/cds-dk@${o} from ${e}`),a&&c&&s&&i&&er(s,c,i),!0;if(!n||!o)return u("error","Cannot install dependencies: no compatible versions found"),!1;u("info",`Installing @sap/cds@${n} and @sap/cds-dk@${o} in cache directory: ${e}`),a&&c&&u("warn",c);try{return(0,Ds.execFileSync)("npm",["install","--quiet","--no-audit","--no-fund"],{cwd:r,stdio:"inherit"}),a&&c&&s&&i&&er(s,c,i),!0}catch(h){let f=`Failed to install resolved dependencies in cache directory ${r}: ${h instanceof Error?h.message:String(h)}`;return u("error",f),!1}}var po=" Usage: node