@easbot/codebase 0.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +187 -0
- package/README.md +187 -0
- package/dist/index.cjs +111 -0
- package/dist/index.d.cts +542 -0
- package/dist/index.d.ts +542 -0
- package/dist/index.mjs +111 -0
- package/package.json +109 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import Jt,{win32,posix}from'path';import {fileURLToPath}from'url';import {xdgData}from'xdg-basedir';import {getDefaultDatabasePath,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import*as An from'fs';import An__default,{realpathSync,createWriteStream,readlinkSync,readdirSync,readdir as readdir$1,lstatSync}from'fs';import qi,{realpath,readlink,readdir,lstat}from'fs/promises';import Ko from'zod';import {EventEmitter}from'events';import on from'stream';import {StringDecoder}from'string_decoder';import Zo from'better-sqlite3';import {Filesystem}from'@easbot/utils';import {createHash}from'crypto';import ch from'fast-glob';var Xn=Object.defineProperty;var Qi=s=>{throw TypeError(s)};var Qn=(s,e,t)=>e in s?Xn(s,e,{enumerable:true,configurable:true,writable:true,value:t}):s[e]=t;var u=(s,e,t)=>Qn(s,typeof e!="symbol"?e+"":e,t),mi=(s,e,t)=>e.has(s)||Qi("Cannot "+t);var n=(s,e,t)=>(mi(s,e,"read from private field"),t?t.call(s):e.get(s)),E=(s,e,t)=>e.has(s)?Qi("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),g=(s,e,t,i)=>(mi(s,e,"write to private field"),e.set(s,t),t),m=(s,e,t)=>(mi(s,e,"access private method"),t);var zs=(s,e,t,i)=>({set _(r){g(s,e,r);},get _(){return n(s,e,i)}});var Kn=()=>fileURLToPath(import.meta.url),Jn=()=>Jt.dirname(Kn()),oe=Jn();var Vi={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var At=class s extends Error{constructor(t,i,r){super(t);u(this,"name","ParserError");u(this,"filePath");u(this,"cause");this.filePath=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},ut=class s extends Error{constructor(t,i,r){super(t);u(this,"name","DatabaseError");u(this,"operation");u(this,"cause");this.operation=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},js=class s extends Error{constructor(t,i,r){super(t);u(this,"name","FileSystemError");u(this,"filePath");u(this,"cause");this.filePath=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},$s=class s extends Error{constructor(t,i){super(t);u(this,"name","SchemaError");u(this,"missing");this.missing=i,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},Zt=class s extends Error{constructor(t,i){super(t);u(this,"name","ConfigError");u(this,"field");this.field=i,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},Bs=class s extends Error{constructor(t,i,r){super(t);u(this,"name","IndexError");u(this,"filePath");u(this,"cause");this.filePath=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},es=class s extends Error{constructor(t,i,r){super(t);u(this,"name","QueryError");u(this,"params");u(this,"cause");this.params=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",i=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${i}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},Us=class s extends Error{constructor(t,i){super(`Unsupported language: ${t}`);u(this,"name","UnsupportedLanguageError");u(this,"extension");u(this,"filePath");this.extension=t,this.filePath=i,Object.setPrototypeOf(this,s.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var Br=(s,e,t)=>{let i=s instanceof RegExp?Yi(s,t):s,r=e instanceof RegExp?Yi(e,t):e,a=i!==null&&r!=null&&Zn(i,r,t);return a&&{start:a[0],end:a[1],pre:t.slice(0,a[0]),body:t.slice(a[0]+i.length,a[1]),post:t.slice(a[1]+r.length)}},Yi=(s,e)=>{let t=e.match(s);return t?t[0]:null},Zn=(s,e,t)=>{let i,r,a,o,h,l=t.indexOf(s),c=t.indexOf(e,l+1),p=l;if(l>=0&&c>0){if(s===e)return [l,c];for(i=[],a=t.length;p>=0&&!h;){if(p===l)i.push(p),l=t.indexOf(s,p+1);else if(i.length===1){let d=i.pop();d!==void 0&&(h=[d,c]);}else r=i.pop(),r!==void 0&&r<a&&(a=r,o=c),c=t.indexOf(e,p+1);p=l<c&&l>=0?l:c;}i.length&&o!==void 0&&(h=[a,o]);}return h},Ur="\0SLASH"+Math.random()+"\0",Gr="\0OPEN"+Math.random()+"\0",zi="\0CLOSE"+Math.random()+"\0",qr="\0COMMA"+Math.random()+"\0",Hr="\0PERIOD"+Math.random()+"\0",ea=new RegExp(Ur,"g"),ta=new RegExp(Gr,"g"),sa=new RegExp(zi,"g"),ia=new RegExp(qr,"g"),ra=new RegExp(Hr,"g"),na=/\\\\/g,aa=/\\{/g,oa=/\\}/g,ha=/\\,/g,la=/\\./g,ca=1e5;function yi(s){return isNaN(s)?s.charCodeAt(0):parseInt(s,10)}function da(s){return s.replace(na,Ur).replace(aa,Gr).replace(oa,zi).replace(ha,qr).replace(la,Hr)}function ua(s){return s.replace(ea,"\\").replace(ta,"{").replace(sa,"}").replace(ia,",").replace(ra,".")}function Xr(s){if(!s)return [""];let e=[],t=Br("{","}",s);if(!t)return s.split(",");let{pre:i,body:r,post:a}=t,o=i.split(",");o[o.length-1]+="{"+r+"}";let h=Xr(a);return a.length&&(o[o.length-1]+=h.shift(),o.push.apply(o,h)),e.push.apply(e,o),e}function pa(s,e={}){if(!s)return [];let{max:t=ca}=e;return s.slice(0,2)==="{}"&&(s="\\{\\}"+s.slice(2)),os(da(s),t,true).map(ua)}function ga(s){return "{"+s+"}"}function fa(s){return /^-?0\d/.test(s)}function ma(s,e){return s<=e}function ya(s,e){return s>=e}function os(s,e,t){let i=[],r=Br("{","}",s);if(!r)return [s];let a=r.pre,o=r.post.length?os(r.post,e,false):[""];if(/\$$/.test(r.pre))for(let h=0;h<o.length&&h<e;h++){let l=a+"{"+r.body+"}"+o[h];i.push(l);}else {let h=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),c=h||l,p=r.body.indexOf(",")>=0;if(!c&&!p)return r.post.match(/,(?!,).*\}/)?(s=r.pre+"{"+r.body+zi+r.post,os(s,e,true)):[s];let d;if(c)d=r.body.split(/\.\./);else if(d=Xr(r.body),d.length===1&&d[0]!==void 0&&(d=os(d[0],e,false).map(ga),d.length===1))return o.map(S=>r.pre+d[0]+S);let f;if(c&&d[0]!==void 0&&d[1]!==void 0){let S=yi(d[0]),w=yi(d[1]),x=Math.max(d[0].length,d[1].length),b=d.length===3&&d[2]!==void 0?Math.abs(yi(d[2])):1,y=ma;w<S&&(b*=-1,y=ya);let _=d.some(fa);f=[];for(let N=S;y(N,w);N+=b){let P;if(l)P=String.fromCharCode(N),P==="\\"&&(P="");else if(P=String(N),_){let T=x-P.length;if(T>0){let O=new Array(T+1).join("0");N<0?P="-"+O+P.slice(1):P=O+P;}}f.push(P);}}else {f=[];for(let S=0;S<d.length;S++)f.push.apply(f,os(d[S],e,false));}for(let S=0;S<f.length;S++)for(let w=0;w<o.length&&i.length<e;w++){let x=a+f[S]+o[w];(!t||c||x)&&i.push(x);}}return i}var ai=s=>{if(typeof s!="string")throw new TypeError("invalid pattern");if(s.length>65536)throw new TypeError("pattern is too long")},ba={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},ts=s=>s.replace(/[[\]\\-]/g,"\\$&"),wa=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ki=s=>s.join(""),Ea=(s,e)=>{let t=e;if(s.charAt(t)!=="[")throw new Error("not in a brace expression");let i=[],r=[],a=t+1,o=false,h=false,l=false,c=false,p=t,d="";e:for(;a<s.length;){let w=s.charAt(a);if((w==="!"||w==="^")&&a===t+1){c=true,a++;continue}if(w==="]"&&o&&!l){p=a+1;break}if(o=true,w==="\\"&&!l){l=true,a++;continue}if(w==="["&&!l){for(let[x,[b,y,_]]of Object.entries(ba))if(s.startsWith(x,a)){if(d)return ["$.",false,s.length-t,true];a+=x.length,_?r.push(b):i.push(b),h=h||y;continue e}}if(l=false,d){w>d?i.push(ts(d)+"-"+ts(w)):w===d&&i.push(ts(w)),d="",a++;continue}if(s.startsWith("-]",a+1)){i.push(ts(w+"-")),a+=2;continue}if(s.startsWith("-",a+1)){d=w,a+=2;continue}i.push(ts(w)),a++;}if(p<a)return ["",false,0,false];if(!i.length&&!r.length)return ["$.",false,s.length-t,true];if(r.length===0&&i.length===1&&/^\\?.$/.test(i[0])&&!c){let w=i[0].length===2?i[0].slice(-1):i[0];return [wa(w),false,p-t,false]}let f="["+(c?"^":"")+Ki(i)+"]",S="["+(c?"":"^")+Ki(r)+"]";return [i.length&&r.length?"("+f+"|"+S+")":i.length?f:S,h,p-t,true]},Dt=(s,{windowsPathsNoEscape:e=false,magicalBraces:t=true}={})=>t?e?s.replace(/\[([^\/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?s.replace(/\[([^\/\\{}])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),Sa=new Set(["!","?","+","*","@"]),Ji=s=>Sa.has(s),xa="(?!(?:^|/)\\.\\.?(?:$|/))",Gs="(?!\\.)",va=new Set(["[","."]),_a=new Set(["..","."]),Na=new Set("().*{}+?[]^$\\!"),Ta=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ji="[^/]",Zi=ji+"*?",er=ji+"+?",j,Q,Be,I,W,st,mt,it,ke,yt,gs,Tt,Vr,lt,K,Js,Ni,Yr,Qr=(K=class{constructor(e,t,i={}){E(this,Tt);u(this,"type");E(this,j);E(this,Q);E(this,Be,false);E(this,I,[]);E(this,W);E(this,st);E(this,mt);E(this,it,false);E(this,ke);E(this,yt);E(this,gs,false);this.type=e,e&&g(this,Q,true),g(this,W,t),g(this,j,n(this,W)?n(n(this,W),j):this),g(this,ke,n(this,j)===this?i:n(n(this,j),ke)),g(this,mt,n(this,j)===this?[]:n(n(this,j),mt)),e==="!"&&!n(n(this,j),it)&&n(this,mt).push(this),g(this,st,n(this,W)?n(n(this,W),I).length:0);}get hasMagic(){if(n(this,Q)!==void 0)return n(this,Q);for(let e of n(this,I))if(typeof e!="string"&&(e.type||e.hasMagic))return g(this,Q,true);return n(this,Q)}toString(){return n(this,yt)!==void 0?n(this,yt):this.type?g(this,yt,this.type+"("+n(this,I).map(e=>String(e)).join("|")+")"):g(this,yt,n(this,I).map(e=>String(e)).join(""))}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof K&&n(t,W)===this))throw new Error("invalid part: "+t);n(this,I).push(t);}}toJSON(){let e=this.type===null?n(this,I).slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...n(this,I).map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===n(this,j)||n(n(this,j),it)&&n(this,W)?.type==="!")&&e.push({}),e}isStart(){if(n(this,j)===this)return true;if(!n(this,W)?.isStart())return false;if(n(this,st)===0)return true;let e=n(this,W);for(let t=0;t<n(this,st);t++){let i=n(e,I)[t];if(!(i instanceof K&&i.type==="!"))return false}return true}isEnd(){if(n(this,j)===this||n(this,W)?.type==="!")return true;if(!n(this,W)?.isEnd())return false;if(!this.type)return n(this,W)?.isEnd();let e=n(this,W)?n(n(this,W),I).length:0;return n(this,st)===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this));}clone(e){let t=new K(this.type,e);for(let i of n(this,I))t.copyIn(i);return t}static fromGlob(e,t={}){var r;let i=new K(null,void 0,t);return m(r=K,lt,Js).call(r,e,i,0,t),i}toMMPattern(){if(this!==n(this,j))return n(this,j).toMMPattern();let e=this.toString(),[t,i,r,a]=this.toRegExpSource();if(!(r||n(this,Q)||n(this,ke).nocase&&!n(this,ke).nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return i;let o=(n(this,ke).nocase?"i":"")+(a?"u":"");return Object.assign(new RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return n(this,ke)}toRegExpSource(e){let t=e??!!n(this,ke).dot;if(n(this,j)===this&&m(this,Tt,Vr).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!n(this,I).some(f=>typeof f!="string"),c=n(this,I).map(f=>{var y;let[S,w,x,b]=typeof f=="string"?m(y=K,lt,Yr).call(y,f,n(this,Q),l):f.toRegExpSource(e);return g(this,Q,n(this,Q)||x),g(this,Be,n(this,Be)||b),S}).join(""),p="";if(this.isStart()&&typeof n(this,I)[0]=="string"&&!(n(this,I).length===1&&_a.has(n(this,I)[0]))){let f=va,S=t&&f.has(c.charAt(0))||c.startsWith("\\.")&&f.has(c.charAt(2))||c.startsWith("\\.\\.")&&f.has(c.charAt(4)),w=!t&&!e&&f.has(c.charAt(0));p=S?xa:w?Gs:"";}let d="";return this.isEnd()&&n(n(this,j),it)&&n(this,W)?.type==="!"&&(d="(?:$|\\/)"),[p+c+d,Dt(c),g(this,Q,!!n(this,Q)),n(this,Be)]}let i=this.type==="*"||this.type==="+",r=this.type==="!"?"(?:(?!(?:":"(?:",a=m(this,Tt,Ni).call(this,t);if(this.isStart()&&this.isEnd()&&!a&&this.type!=="!"){let l=this.toString();return g(this,I,[l]),this.type=null,g(this,Q,void 0),[l,Dt(this.toString()),false,false]}let o=!i||e||t||!Gs?"":m(this,Tt,Ni).call(this,true);o===a&&(o=""),o&&(a=`(?:${a})(?:${o})*?`);let h="";if(this.type==="!"&&n(this,gs))h=(this.isStart()&&!t?Gs:"")+er;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?Gs:"")+Zi+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;h=r+a+l;}return [h,Dt(a),g(this,Q,!!n(this,Q)),n(this,Be)]}},j=new WeakMap,Q=new WeakMap,Be=new WeakMap,I=new WeakMap,W=new WeakMap,st=new WeakMap,mt=new WeakMap,it=new WeakMap,ke=new WeakMap,yt=new WeakMap,gs=new WeakMap,Tt=new WeakSet,Vr=function(){if(this!==n(this,j))throw new Error("should only call on root");if(n(this,it))return this;this.toString(),g(this,it,true);let e;for(;e=n(this,mt).pop();){if(e.type!=="!")continue;let t=e,i=n(t,W);for(;i;){for(let r=n(t,st)+1;!i.type&&r<n(i,I).length;r++)for(let a of n(e,I)){if(typeof a=="string")throw new Error("string part in extglob AST??");a.copyIn(n(i,I)[r]);}t=i,i=n(t,W);}}return this},lt=new WeakSet,Js=function(e,t,i,r){var S,w;let a=false,o=false,h=-1,l=false;if(t.type===null){let x=i,b="";for(;x<e.length;){let y=e.charAt(x++);if(a||y==="\\"){a=!a,b+=y;continue}if(o){x===h+1?(y==="^"||y==="!")&&(l=true):y==="]"&&!(x===h+2&&l)&&(o=false),b+=y;continue}else if(y==="["){o=true,h=x,l=false,b+=y;continue}if(!r.noext&&Ji(y)&&e.charAt(x)==="("){t.push(b),b="";let _=new K(y,t);x=m(S=K,lt,Js).call(S,e,_,x,r),t.push(_);continue}b+=y;}return t.push(b),x}let c=i+1,p=new K(null,t),d=[],f="";for(;c<e.length;){let x=e.charAt(c++);if(a||x==="\\"){a=!a,f+=x;continue}if(o){c===h+1?(x==="^"||x==="!")&&(l=true):x==="]"&&!(c===h+2&&l)&&(o=false),f+=x;continue}else if(x==="["){o=true,h=c,l=false,f+=x;continue}if(Ji(x)&&e.charAt(c)==="("){p.push(f),f="";let b=new K(x,p);p.push(b),c=m(w=K,lt,Js).call(w,e,b,c,r);continue}if(x==="|"){p.push(f),f="",d.push(p),p=new K(null,t);continue}if(x===")")return f===""&&n(t,I).length===0&&g(t,gs,true),p.push(f),f="",t.push(...d,p),c;f+=x;}return t.type=null,g(t,Q,void 0),g(t,I,[e.substring(i-1)]),c},Ni=function(e){return n(this,I).map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[i,r,a,o]=t.toRegExpSource(e);return g(this,Be,n(this,Be)||o),i}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")},Yr=function(e,t,i=false){let r=false,a="",o=false,h=false;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(r){r=false,a+=(Na.has(c)?"\\":"")+c;continue}if(c==="*"){if(h)continue;h=true,a+=i&&/^[*]+$/.test(e)?er:Zi,t=true;continue}else h=false;if(c==="\\"){l===e.length-1?a+="\\\\":r=true;continue}if(c==="["){let[p,d,f,S]=Ea(e,l);if(f){a+=p,o=o||d,l+=f-1,t=t||S;continue}}if(c==="?"){a+=ji,t=true;continue}a+=Ta(c);}return [a,Dt(e),!!t,o]},E(K,lt),K),Kr=(s,{windowsPathsNoEscape:e=false,magicalBraces:t=false}={})=>t?e?s.replace(/[?*()[\]{}]/g,"[$&]"):s.replace(/[?*()[\]\\{}]/g,"\\$&"):e?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&"),ae=(s,e,t={})=>(ai(e),!t.nocomment&&e.charAt(0)==="#"?false:new ct(e,t).match(s)),Ca=/^\*+([^+@!?\*\[\(]*)$/,Ra=s=>e=>!e.startsWith(".")&&e.endsWith(s),Fa=s=>e=>e.endsWith(s),Pa=s=>(s=s.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(s)),Oa=s=>(s=s.toLowerCase(),e=>e.toLowerCase().endsWith(s)),La=/^\*+\.\*+$/,Ia=s=>!s.startsWith(".")&&s.includes("."),Aa=s=>s!=="."&&s!==".."&&s.includes("."),Ma=/^\.\*+$/,ka=s=>s!=="."&&s!==".."&&s.startsWith("."),Da=/^\*+$/,Wa=s=>s.length!==0&&!s.startsWith("."),za=s=>s.length!==0&&s!=="."&&s!=="..",ja=/^\?+([^+@!?\*\[\(]*)?$/,$a=([s,e=""])=>{let t=Jr([s]);return e?(e=e.toLowerCase(),i=>t(i)&&i.toLowerCase().endsWith(e)):t},Ba=([s,e=""])=>{let t=Zr([s]);return e?(e=e.toLowerCase(),i=>t(i)&&i.toLowerCase().endsWith(e)):t},Ua=([s,e=""])=>{let t=Zr([s]);return e?i=>t(i)&&i.endsWith(e):t},Ga=([s,e=""])=>{let t=Jr([s]);return e?i=>t(i)&&i.endsWith(e):t},Jr=([s])=>{let e=s.length;return t=>t.length===e&&!t.startsWith(".")},Zr=([s])=>{let e=s.length;return t=>t.length===e&&t!=="."&&t!==".."},en=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",tr={win32:{sep:"\\"},posix:{sep:"/"}},qa=en==="win32"?tr.win32.sep:tr.posix.sep;ae.sep=qa;var ne=Symbol("globstar **");ae.GLOBSTAR=ne;var Ha="[^/]",Xa=Ha+"*?",Qa="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Va="(?:(?!(?:\\/|^)\\.).)*?",Ya=(s,e={})=>t=>ae(t,s,e);ae.filter=Ya;var me=(s,e={})=>Object.assign({},s,e),Ka=s=>{if(!s||typeof s!="object"||!Object.keys(s).length)return ae;let e=ae;return Object.assign((t,i,r={})=>e(t,i,me(s,r)),{Minimatch:class extends e.Minimatch{constructor(t,i={}){super(t,me(s,i));}static defaults(t){return e.defaults(me(s,t)).Minimatch}},AST:class extends e.AST{constructor(t,i,r={}){super(t,i,me(s,r));}static fromGlob(t,i={}){return e.AST.fromGlob(t,me(s,i))}},unescape:(t,i={})=>e.unescape(t,me(s,i)),escape:(t,i={})=>e.escape(t,me(s,i)),filter:(t,i={})=>e.filter(t,me(s,i)),defaults:t=>e.defaults(me(s,t)),makeRe:(t,i={})=>e.makeRe(t,me(s,i)),braceExpand:(t,i={})=>e.braceExpand(t,me(s,i)),match:(t,i,r={})=>e.match(t,i,me(s,r)),sep:e.sep,GLOBSTAR:ne})};ae.defaults=Ka;var tn=(s,e={})=>(ai(s),e.nobrace||!/\{(?:(?!\{).)*\}/.test(s)?[s]:pa(s,{max:e.braceExpandMax}));ae.braceExpand=tn;var Ja=(s,e={})=>new ct(s,e).makeRe();ae.makeRe=Ja;var Za=(s,e,t={})=>{let i=new ct(e,t);return s=s.filter(r=>i.match(r)),i.options.nonull&&!s.length&&s.push(e),s};ae.match=Za;var sr=/[?*]|[+@!]\(.*?\)|\[|\]/,eo=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ct=class{constructor(s,e={}){u(this,"options");u(this,"set");u(this,"pattern");u(this,"windowsPathsNoEscape");u(this,"nonegate");u(this,"negate");u(this,"comment");u(this,"empty");u(this,"preserveMultipleSlashes");u(this,"partial");u(this,"globSet");u(this,"globParts");u(this,"nocase");u(this,"isWindows");u(this,"platform");u(this,"windowsNoMagicRoot");u(this,"regexp");ai(s),e=e||{},this.options=e,this.pattern=s,this.platform=e.platform||en,this.isWindows=this.platform==="win32";let t="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[t]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!e.nonegate,this.comment=false,this.empty=false,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 true;for(let s of this.set)for(let e of s)if(typeof e!="string")return true;return false}debug(...s){}make(){let s=this.pattern,e=this.options;if(!e.nocomment&&s.charAt(0)==="#"){this.comment=true;return}if(!s){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let t=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(t),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,a,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let h=r[0]===""&&r[1]===""&&(r[2]==="?"||!sr.test(r[2]))&&!sr.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(h)return [...r.slice(0,4),...r.slice(4).map(c=>this.parse(c))];if(l)return [r[0],...r.slice(1).map(c=>this.parse(c))]}return r.map(h=>this.parse(h))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(false)===-1),this.isWindows)for(let r=0;r<this.set.length;r++){let a=this.set[r];a[0]===""&&a[1]===""&&this.globParts[r][2]==="?"&&typeof a[3]=="string"&&/^[a-z]:$/i.test(a[3])&&(a[2]="?");}this.debug(this.pattern,this.set);}preprocess(s){if(this.options.noglobstar)for(let t=0;t<s.length;t++)for(let i=0;i<s[t].length;i++)s[t][i]==="**"&&(s[t][i]="*");let{optimizationLevel:e=1}=this.options;return e>=2?(s=this.firstPhasePreProcess(s),s=this.secondPhasePreProcess(s)):e>=1?s=this.levelOneOptimize(s):s=this.adjascentGlobstarOptimize(s),s}adjascentGlobstarOptimize(s){return s.map(e=>{let t=-1;for(;(t=e.indexOf("**",t+1))!==-1;){let i=t;for(;e[i+1]==="**";)i++;i!==t&&e.splice(t,i-t);}return e})}levelOneOptimize(s){return s.map(e=>(e=e.reduce((t,i)=>{let r=t[t.length-1];return i==="**"&&r==="**"?t:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(t.pop(),t):(t.push(i),t)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(s){Array.isArray(s)||(s=this.slashSplit(s));let e=false;do{if(e=false,!this.preserveMultipleSlashes){for(let i=1;i<s.length-1;i++){let r=s[i];i===1&&r===""&&s[0]===""||(r==="."||r==="")&&(e=true,s.splice(i,1),i--);}s[0]==="."&&s.length===2&&(s[1]==="."||s[1]==="")&&(e=true,s.pop());}let t=0;for(;(t=s.indexOf("..",t+1))!==-1;){let i=s[t-1];i&&i!=="."&&i!==".."&&i!=="**"&&(e=true,s.splice(t-1,2),t-=2);}}while(e);return s.length===0?[""]:s}firstPhasePreProcess(s){let e=false;do{e=false;for(let t of s){let i=-1;for(;(i=t.indexOf("**",i+1))!==-1;){let a=i;for(;t[a+1]==="**";)a++;a>i&&t.splice(i+1,a-i);let o=t[i+1],h=t[i+2],l=t[i+3];if(o!==".."||!h||h==="."||h===".."||!l||l==="."||l==="..")continue;e=true,t.splice(i,1);let c=t.slice(0);c[i]="**",s.push(c),i--;}if(!this.preserveMultipleSlashes){for(let a=1;a<t.length-1;a++){let o=t[a];a===1&&o===""&&t[0]===""||(o==="."||o==="")&&(e=true,t.splice(a,1),a--);}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=true,t.pop());}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let a=t[r-1];if(a&&a!=="."&&a!==".."&&a!=="**"){e=true;let o=r===1&&t[r+1]==="**"?["."]:[];t.splice(r-1,2,...o),t.length===0&&t.push(""),r-=2;}}}}while(e);return s}secondPhasePreProcess(s){for(let e=0;e<s.length-1;e++)for(let t=e+1;t<s.length;t++){let i=this.partsMatch(s[e],s[t],!this.preserveMultipleSlashes);if(i){s[e]=[],s[t]=i;break}}return s.filter(e=>e.length)}partsMatch(s,e,t=false){let i=0,r=0,a=[],o="";for(;i<s.length&&r<e.length;)if(s[i]===e[r])a.push(o==="b"?e[r]:s[i]),i++,r++;else if(t&&s[i]==="**"&&e[r]===s[i+1])a.push(s[i]),i++;else if(t&&e[r]==="**"&&s[i]===e[r+1])a.push(e[r]),r++;else if(s[i]==="*"&&e[r]&&(this.options.dot||!e[r].startsWith("."))&&e[r]!=="**"){if(o==="b")return false;o="a",a.push(s[i]),i++,r++;}else if(e[r]==="*"&&s[i]&&(this.options.dot||!s[i].startsWith("."))&&s[i]!=="**"){if(o==="a")return false;o="b",a.push(e[r]),i++,r++;}else return false;return s.length===e.length&&a}parseNegate(){if(this.nonegate)return;let s=this.pattern,e=false,t=0;for(let i=0;i<s.length&&s.charAt(i)==="!";i++)e=!e,t++;t&&(this.pattern=s.slice(t)),this.negate=e;}matchOne(s,e,t=false){let i=this.options;if(this.isWindows){let w=typeof s[0]=="string"&&/^[a-z]:$/i.test(s[0]),x=!w&&s[0]===""&&s[1]===""&&s[2]==="?"&&/^[a-z]:$/i.test(s[3]),b=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),y=!b&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),_=x?3:w?0:void 0,N=y?3:b?0:void 0;if(typeof _=="number"&&typeof N=="number"){let[P,T]=[s[_],e[N]];P.toLowerCase()===T.toLowerCase()&&(e[N]=P,N>_?e=e.slice(N):_>N&&(s=s.slice(_)));}}let{optimizationLevel:r=1}=this.options;r>=2&&(s=this.levelTwoFileOptimize(s)),this.debug("matchOne",this,{file:s,pattern:e}),this.debug("matchOne",s.length,e.length);for(var a=0,o=0,h=s.length,l=e.length;a<h&&o<l;a++,o++){this.debug("matchOne loop");var c=e[o],p=s[a];if(this.debug(e,c,p),c===false)return false;if(c===ne){this.debug("GLOBSTAR",[e,c,p]);var d=a,f=o+1;if(f===l){for(this.debug("** at the end");a<h;a++)if(s[a]==="."||s[a]===".."||!i.dot&&s[a].charAt(0)===".")return false;return true}for(;d<h;){var S=s[d];if(this.debug(`
|
|
2
|
+
globstar while`,s,d,e,f,S),this.matchOne(s.slice(d),e.slice(f),t))return this.debug("globstar found match!",d,h,S),true;if(S==="."||S===".."||!i.dot&&S.charAt(0)==="."){this.debug("dot detected!",s,d,e,f);break}this.debug("globstar swallow a segment, and continue"),d++;}return !!(t&&(this.debug(`
|
|
3
|
+
>>> no match, partial?`,s,d,e,f),d===h))}let w;if(typeof c=="string"?(w=p===c,this.debug("string match",c,p,w)):(w=c.test(p),this.debug("pattern match",c,p,w)),!w)return false}if(a===h&&o===l)return true;if(a===h)return t;if(o===l)return a===h-1&&s[a]==="";throw new Error("wtf?")}braceExpand(){return tn(this.pattern,this.options)}parse(s){ai(s);let e=this.options;if(s==="**")return ne;if(s==="")return "";let t,i=null;(t=s.match(Da))?i=e.dot?za:Wa:(t=s.match(Ca))?i=(e.nocase?e.dot?Oa:Pa:e.dot?Fa:Ra)(t[1]):(t=s.match(ja))?i=(e.nocase?e.dot?Ba:$a:e.dot?Ua:Ga)(t):(t=s.match(La))?i=e.dot?Aa:Ia:(t=s.match(Ma))&&(i=ka);let r=Qr.fromGlob(s,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let s=this.set;if(!s.length)return this.regexp=false,this.regexp;let e=this.options,t=e.noglobstar?Xa:e.dot?Qa:Va,i=new Set(e.nocase?["i"]:[]),r=s.map(h=>{let l=h.map(p=>{if(p instanceof RegExp)for(let d of p.flags.split(""))i.add(d);return typeof p=="string"?eo(p):p===ne?ne:p._src});l.forEach((p,d)=>{let f=l[d+1],S=l[d-1];p!==ne||S===ne||(S===void 0?f!==void 0&&f!==ne?l[d+1]="(?:\\/|"+t+"\\/)?"+f:l[d]=t:f===void 0?l[d-1]=S+"(?:\\/|\\/"+t+")?":f!==ne&&(l[d-1]=S+"(?:\\/|\\/"+t+"\\/)"+f,l[d+1]=ne));});let c=l.filter(p=>p!==ne);if(this.partial&&c.length>=1){let p=[];for(let d=1;d<=c.length;d++)p.push(c.slice(0,d).join("/"));return "(?:"+p.join("|")+")"}return c.join("/")}).join("|"),[a,o]=s.length>1?["(?:",")"]:["",""];r="^"+a+r+o+"$",this.partial&&(r="^(?:\\/|"+a+r.slice(1,-1)+o+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(s){return this.preserveMultipleSlashes?s.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(s)?["",...s.split(/\/+/)]:s.split(/\/+/)}match(s,e=this.partial){if(this.debug("match",s,this.pattern),this.comment)return false;if(this.empty)return s==="";if(s==="/"&&e)return true;let t=this.options;this.isWindows&&(s=s.split("\\").join("/"));let i=this.slashSplit(s);this.debug(this.pattern,"split",i);let r=this.set;this.debug(this.pattern,"set",r);let a=i[i.length-1];if(!a)for(let o=i.length-2;!a&&o>=0;o--)a=i[o];for(let o=0;o<r.length;o++){let h=r[o],l=i;if(t.matchBase&&h.length===1&&(l=[a]),this.matchOne(l,h,e))return t.flipNegate?true:!this.negate}return t.flipNegate?false:this.negate}static defaults(s){return ae.defaults(s).Minimatch}};ae.AST=Qr;ae.Minimatch=ct;ae.escape=Kr;ae.unescape=Dt;var so=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,sn=new Set,Ti=typeof process=="object"&&process?process:{},rn=(s,e,t,i)=>{typeof Ti.emitWarning=="function"?Ti.emitWarning(s,e,t,i):console.error(`[${t}] ${e}: ${s}`);},oi=globalThis.AbortController,ir=globalThis.AbortSignal;if(typeof oi>"u"){ir=class{constructor(){u(this,"onabort");u(this,"_onabort",[]);u(this,"reason");u(this,"aborted",false);}addEventListener(t,i){this._onabort.push(i);}},oi=class{constructor(){u(this,"signal",new ir);e();}abort(t){if(!this.signal.aborted){this.signal.reason=t,this.signal.aborted=true;for(let i of this.signal._onabort)i(t);this.signal.onabort?.(t);}}};let s=Ti.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{s&&(s=false,rn("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e));};}var io=s=>!sn.has(s),Je=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),nn=s=>Je(s)?s<=Math.pow(2,8)?Uint8Array:s<=Math.pow(2,16)?Uint16Array:s<=Math.pow(2,32)?Uint32Array:s<=Number.MAX_SAFE_INTEGER?Zs:null:null,Zs=class extends Array{constructor(s){super(s),this.fill(0);}},ze,Wt,ro=(ze=class{constructor(e,t){u(this,"heap");u(this,"length");if(!n(ze,Wt))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0;}static create(e){let t=nn(e);if(!t)return [];g(ze,Wt,true);let i=new ze(e,t);return g(ze,Wt,false),i}push(e){this.heap[this.length++]=e;}pop(){return this.heap[--this.length]}},Wt=new WeakMap,E(ze,Wt,false),ze),br,wr,be,de,Ne,bt,Te,zt,jt,Ce,$,Re,z,A,F,se,ue,ee,V,Fe,Y,Pe,Oe,pe,ge,Le,rt,ie,$t,v,Ci,wt,Ue,fs,fe,an,Et,Bt,ms,Ze,et,Ri,ei,ti,L,Fi,hs,tt,Pi,Ut,ci=(Ut=class{constructor(e){E(this,v);E(this,be);E(this,de);E(this,Ne);E(this,bt);E(this,Te);E(this,zt);E(this,jt);E(this,Ce);u(this,"ttl");u(this,"ttlResolution");u(this,"ttlAutopurge");u(this,"updateAgeOnGet");u(this,"updateAgeOnHas");u(this,"allowStale");u(this,"noDisposeOnSet");u(this,"noUpdateTTL");u(this,"maxEntrySize");u(this,"sizeCalculation");u(this,"noDeleteOnFetchRejection");u(this,"noDeleteOnStaleGet");u(this,"allowStaleOnFetchAbort");u(this,"allowStaleOnFetchRejection");u(this,"ignoreFetchAbort");E(this,$);E(this,Re);E(this,z);E(this,A);E(this,F);E(this,se);E(this,ue);E(this,ee);E(this,V);E(this,Fe);E(this,Y);E(this,Pe);E(this,Oe);E(this,pe);E(this,ge);E(this,Le);E(this,rt);E(this,ie);E(this,$t);E(this,wt,()=>{});E(this,Ue,()=>{});E(this,fs,()=>{});E(this,fe,()=>false);E(this,Et,e=>{});E(this,Bt,(e,t,i)=>{});E(this,ms,(e,t,i,r)=>{if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});u(this,br,"LRUCache");let{max:t=0,ttl:i,ttlResolution:r=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:h,allowStale:l,dispose:c,onInsert:p,disposeAfter:d,noDisposeOnSet:f,noUpdateTTL:S,maxSize:w=0,maxEntrySize:x=0,sizeCalculation:b,fetchMethod:y,memoMethod:_,noDeleteOnFetchRejection:N,noDeleteOnStaleGet:P,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:O,ignoreFetchAbort:k,perf:J}=e;if(J!==void 0&&typeof J?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(g(this,Ce,J??so),t!==0&&!Je(t))throw new TypeError("max option must be a nonnegative integer");let M=t?nn(t):Array;if(!M)throw new Error("invalid max value: "+t);if(g(this,be,t),g(this,de,w),this.maxEntrySize=x||n(this,de),this.sizeCalculation=b,this.sizeCalculation){if(!n(this,de)&&!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(_!==void 0&&typeof _!="function")throw new TypeError("memoMethod must be a function if defined");if(g(this,jt,_),y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(g(this,zt,y),g(this,rt,!!y),g(this,z,new Map),g(this,A,new Array(t).fill(void 0)),g(this,F,new Array(t).fill(void 0)),g(this,se,new M(t)),g(this,ue,new M(t)),g(this,ee,0),g(this,V,0),g(this,Fe,ro.create(t)),g(this,$,0),g(this,Re,0),typeof c=="function"&&g(this,Ne,c),typeof p=="function"&&g(this,bt,p),typeof d=="function"?(g(this,Te,d),g(this,Y,[])):(g(this,Te,void 0),g(this,Y,void 0)),g(this,Le,!!n(this,Ne)),g(this,$t,!!n(this,bt)),g(this,ie,!!n(this,Te)),this.noDisposeOnSet=!!f,this.noUpdateTTL=!!S,this.noDeleteOnFetchRejection=!!N,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!O,this.ignoreFetchAbort=!!k,this.maxEntrySize!==0){if(n(this,de)!==0&&!Je(n(this,de)))throw new TypeError("maxSize must be a positive integer if specified");if(!Je(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");m(this,v,an).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!P,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!h,this.ttlResolution=Je(r)||r===0?r:1,this.ttlAutopurge=!!a,this.ttl=i||0,this.ttl){if(!Je(this.ttl))throw new TypeError("ttl must be a positive integer if specified");m(this,v,Ci).call(this);}if(n(this,be)===0&&this.ttl===0&&n(this,de)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!n(this,be)&&!n(this,de)){let G="LRU_CACHE_UNBOUNDED";io(G)&&(sn.add(G),rn("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",G,Ut));}}get perf(){return n(this,Ce)}static unsafeExposeInternals(e){return {starts:n(e,Oe),ttls:n(e,pe),autopurgeTimers:n(e,ge),sizes:n(e,Pe),keyMap:n(e,z),keyList:n(e,A),valList:n(e,F),next:n(e,se),prev:n(e,ue),get head(){return n(e,ee)},get tail(){return n(e,V)},free:n(e,Fe),isBackgroundFetch:t=>{var i;return m(i=e,v,L).call(i,t)},backgroundFetch:(t,i,r,a)=>{var o;return m(o=e,v,ti).call(o,t,i,r,a)},moveToTail:t=>{var i;return m(i=e,v,hs).call(i,t)},indexes:t=>{var i;return m(i=e,v,Ze).call(i,t)},rindexes:t=>{var i;return m(i=e,v,et).call(i,t)},isStale:t=>{var i;return n(i=e,fe).call(i,t)}}}get max(){return n(this,be)}get maxSize(){return n(this,de)}get calculatedSize(){return n(this,Re)}get size(){return n(this,$)}get fetchMethod(){return n(this,zt)}get memoMethod(){return n(this,jt)}get dispose(){return n(this,Ne)}get onInsert(){return n(this,bt)}get disposeAfter(){return n(this,Te)}getRemainingTTL(e){return n(this,z).has(e)?1/0:0}*entries(){for(let e of m(this,v,Ze).call(this))n(this,F)[e]!==void 0&&n(this,A)[e]!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield [n(this,A)[e],n(this,F)[e]]);}*rentries(){for(let e of m(this,v,et).call(this))n(this,F)[e]!==void 0&&n(this,A)[e]!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield [n(this,A)[e],n(this,F)[e]]);}*keys(){for(let e of m(this,v,Ze).call(this)){let t=n(this,A)[e];t!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield t);}}*rkeys(){for(let e of m(this,v,et).call(this)){let t=n(this,A)[e];t!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield t);}}*values(){for(let e of m(this,v,Ze).call(this))n(this,F)[e]!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield n(this,F)[e]);}*rvalues(){for(let e of m(this,v,et).call(this))n(this,F)[e]!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield n(this,F)[e]);}[(wr=Symbol.iterator,br=Symbol.toStringTag,wr)](){return this.entries()}find(e,t={}){for(let i of m(this,v,Ze).call(this)){let r=n(this,F)[i],a=m(this,v,L).call(this,r)?r.__staleWhileFetching:r;if(a!==void 0&&e(a,n(this,A)[i],this))return this.get(n(this,A)[i],t)}}forEach(e,t=this){for(let i of m(this,v,Ze).call(this)){let r=n(this,F)[i],a=m(this,v,L).call(this,r)?r.__staleWhileFetching:r;a!==void 0&&e.call(t,a,n(this,A)[i],this);}}rforEach(e,t=this){for(let i of m(this,v,et).call(this)){let r=n(this,F)[i],a=m(this,v,L).call(this,r)?r.__staleWhileFetching:r;a!==void 0&&e.call(t,a,n(this,A)[i],this);}}purgeStale(){let e=false;for(let t of m(this,v,et).call(this,{allowStale:true}))n(this,fe).call(this,t)&&(m(this,v,tt).call(this,n(this,A)[t],"expire"),e=true);return e}info(e){let t=n(this,z).get(e);if(t===void 0)return;let i=n(this,F)[t],r=m(this,v,L).call(this,i)?i.__staleWhileFetching:i;if(r===void 0)return;let a={value:r};if(n(this,pe)&&n(this,Oe)){let o=n(this,pe)[t],h=n(this,Oe)[t];if(o&&h){let l=o-(n(this,Ce).now()-h);a.ttl=l,a.start=Date.now();}}return n(this,Pe)&&(a.size=n(this,Pe)[t]),a}dump(){let e=[];for(let t of m(this,v,Ze).call(this,{allowStale:true})){let i=n(this,A)[t],r=n(this,F)[t],a=m(this,v,L).call(this,r)?r.__staleWhileFetching:r;if(a===void 0||i===void 0)continue;let o={value:a};if(n(this,pe)&&n(this,Oe)){o.ttl=n(this,pe)[t];let h=n(this,Ce).now()-n(this,Oe)[t];o.start=Math.floor(Date.now()-h);}n(this,Pe)&&(o.size=n(this,Pe)[t]),e.unshift([i,o]);}return e}load(e){this.clear();for(let[t,i]of e){if(i.start){let r=Date.now()-i.start;i.start=n(this,Ce).now()-r;}this.set(t,i.value,i);}}set(e,t,i={}){var f,S,w,x;if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:l}=i,{noUpdateTTL:c=this.noUpdateTTL}=i,p=n(this,ms).call(this,e,t,i.size||0,h);if(this.maxEntrySize&&p>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),m(this,v,tt).call(this,e,"set"),this;let d=n(this,$)===0?void 0:n(this,z).get(e);if(d===void 0)d=n(this,$)===0?n(this,V):n(this,Fe).length!==0?n(this,Fe).pop():n(this,$)===n(this,be)?m(this,v,ei).call(this,false):n(this,$),n(this,A)[d]=e,n(this,F)[d]=t,n(this,z).set(e,d),n(this,se)[n(this,V)]=d,n(this,ue)[d]=n(this,V),g(this,V,d),zs(this,$)._++,n(this,Bt).call(this,d,p,l),l&&(l.set="add"),c=false,n(this,$t)&&((f=n(this,bt))==null||f.call(this,t,e,"add"));else {m(this,v,hs).call(this,d);let b=n(this,F)[d];if(t!==b){if(n(this,rt)&&m(this,v,L).call(this,b)){b.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:y}=b;y!==void 0&&!o&&(n(this,Le)&&((S=n(this,Ne))==null||S.call(this,y,e,"set")),n(this,ie)&&n(this,Y)?.push([y,e,"set"]));}else o||(n(this,Le)&&((w=n(this,Ne))==null||w.call(this,b,e,"set")),n(this,ie)&&n(this,Y)?.push([b,e,"set"]));if(n(this,Et).call(this,d),n(this,Bt).call(this,d,p,l),n(this,F)[d]=t,l){l.set="replace";let y=b&&m(this,v,L).call(this,b)?b.__staleWhileFetching:b;y!==void 0&&(l.oldValue=y);}}else l&&(l.set="update");n(this,$t)&&this.onInsert?.(t,e,t===b?"update":"replace");}if(r!==0&&!n(this,pe)&&m(this,v,Ci).call(this),n(this,pe)&&(c||n(this,fs).call(this,d,r,a),l&&n(this,Ue).call(this,l,d)),!o&&n(this,ie)&&n(this,Y)){let b=n(this,Y),y;for(;y=b?.shift();)(x=n(this,Te))==null||x.call(this,...y);}return this}pop(){var e;try{for(;n(this,$);){let t=n(this,F)[n(this,ee)];if(m(this,v,ei).call(this,!0),m(this,v,L).call(this,t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(n(this,ie)&&n(this,Y)){let t=n(this,Y),i;for(;i=t?.shift();)(e=n(this,Te))==null||e.call(this,...i);}}}has(e,t={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:r}=t,a=n(this,z).get(e);if(a!==void 0){let o=n(this,F)[a];if(m(this,v,L).call(this,o)&&o.__staleWhileFetching===void 0)return false;if(n(this,fe).call(this,a))r&&(r.has="stale",n(this,Ue).call(this,r,a));else return i&&n(this,wt).call(this,a),r&&(r.has="hit",n(this,Ue).call(this,r,a)),true}else r&&(r.has="miss");return false}peek(e,t={}){let{allowStale:i=this.allowStale}=t,r=n(this,z).get(e);if(r===void 0||!i&&n(this,fe).call(this,r))return;let a=n(this,F)[r];return m(this,v,L).call(this,a)?a.__staleWhileFetching:a}async fetch(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:p=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:S=this.ignoreFetchAbort,allowStaleOnFetchAbort:w=this.allowStaleOnFetchAbort,context:x,forceRefresh:b=false,status:y,signal:_}=t;if(!n(this,rt))return y&&(y.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:a,status:y});let N={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:h,size:l,sizeCalculation:c,noUpdateTTL:p,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:w,ignoreFetchAbort:S,status:y,signal:_},P=n(this,z).get(e);if(P===void 0){y&&(y.fetch="miss");let T=m(this,v,ti).call(this,e,P,N,x);return T.__returned=T}else {let T=n(this,F)[P];if(m(this,v,L).call(this,T)){let M=i&&T.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",M&&(y.returnedStale=true)),M?T.__staleWhileFetching:T.__returned=T}let O=n(this,fe).call(this,P);if(!b&&!O)return y&&(y.fetch="hit"),m(this,v,hs).call(this,P),r&&n(this,wt).call(this,P),y&&n(this,Ue).call(this,y,P),T;let k=m(this,v,ti).call(this,e,P,N,x),J=k.__staleWhileFetching!==void 0&&i;return y&&(y.fetch=O?"stale":"refresh",J&&O&&(y.returnedStale=true)),J?k.__staleWhileFetching:k.__returned=k}}async forceFetch(e,t={}){let i=await this.fetch(e,t);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(e,t={}){let i=n(this,jt);if(!i)throw new Error("no memoMethod provided to constructor");let{context:r,forceRefresh:a,...o}=t,h=this.get(e,o);if(!a&&h!==void 0)return h;let l=i(e,h,{options:o,context:r});return this.set(e,l,o),l}get(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=t,h=n(this,z).get(e);if(h!==void 0){let l=n(this,F)[h],c=m(this,v,L).call(this,l);return o&&n(this,Ue).call(this,o,h),n(this,fe).call(this,h)?(o&&(o.get="stale"),c?(o&&i&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),i?l.__staleWhileFetching:void 0):(a||m(this,v,tt).call(this,e,"expire"),o&&i&&(o.returnedStale=true),i?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(m(this,v,hs).call(this,h),r&&n(this,wt).call(this,h),l))}else o&&(o.get="miss");}delete(e){return m(this,v,tt).call(this,e,"delete")}clear(){return m(this,v,Pi).call(this,"delete")}},be=new WeakMap,de=new WeakMap,Ne=new WeakMap,bt=new WeakMap,Te=new WeakMap,zt=new WeakMap,jt=new WeakMap,Ce=new WeakMap,$=new WeakMap,Re=new WeakMap,z=new WeakMap,A=new WeakMap,F=new WeakMap,se=new WeakMap,ue=new WeakMap,ee=new WeakMap,V=new WeakMap,Fe=new WeakMap,Y=new WeakMap,Pe=new WeakMap,Oe=new WeakMap,pe=new WeakMap,ge=new WeakMap,Le=new WeakMap,rt=new WeakMap,ie=new WeakMap,$t=new WeakMap,v=new WeakSet,Ci=function(){let e=new Zs(n(this,be)),t=new Zs(n(this,be));g(this,pe,e),g(this,Oe,t);let i=this.ttlAutopurge?new Array(n(this,be)):void 0;g(this,ge,i),g(this,fs,(o,h,l=n(this,Ce).now())=>{if(t[o]=h!==0?l:0,e[o]=h,i?.[o]&&(clearTimeout(i[o]),i[o]=void 0),h!==0&&i){let c=setTimeout(()=>{n(this,fe).call(this,o)&&m(this,v,tt).call(this,n(this,A)[o],"expire");},h+1);c.unref&&c.unref(),i[o]=c;}}),g(this,wt,o=>{t[o]=e[o]!==0?n(this,Ce).now():0;}),g(this,Ue,(o,h)=>{if(e[h]){let l=e[h],c=t[h];if(!l||!c)return;o.ttl=l,o.start=c,o.now=r||a();let p=o.now-c;o.remainingTTL=l-p;}});let r=0,a=()=>{let o=n(this,Ce).now();if(this.ttlResolution>0){r=o;let h=setTimeout(()=>r=0,this.ttlResolution);h.unref&&h.unref();}return o};this.getRemainingTTL=o=>{let h=n(this,z).get(o);if(h===void 0)return 0;let l=e[h],c=t[h];if(!l||!c)return 1/0;let p=(r||a())-c;return l-p},g(this,fe,o=>{let h=t[o],l=e[o];return !!l&&!!h&&(r||a())-h>l});},wt=new WeakMap,Ue=new WeakMap,fs=new WeakMap,fe=new WeakMap,an=function(){let e=new Zs(n(this,be));g(this,Re,0),g(this,Pe,e),g(this,Et,t=>{g(this,Re,n(this,Re)-e[t]),e[t]=0;}),g(this,ms,(t,i,r,a)=>{if(m(this,v,L).call(this,i))return 0;if(!Je(r))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(r=a(i,t),!Je(r))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 r}),g(this,Bt,(t,i,r)=>{if(e[t]=i,n(this,de)){let a=n(this,de)-e[t];for(;n(this,Re)>a;)m(this,v,ei).call(this,true);}g(this,Re,n(this,Re)+e[t]),r&&(r.entrySize=i,r.totalCalculatedSize=n(this,Re));});},Et=new WeakMap,Bt=new WeakMap,ms=new WeakMap,Ze=function*({allowStale:e=this.allowStale}={}){if(n(this,$))for(let t=n(this,V);!(!m(this,v,Ri).call(this,t)||((e||!n(this,fe).call(this,t))&&(yield t),t===n(this,ee)));)t=n(this,ue)[t];},et=function*({allowStale:e=this.allowStale}={}){if(n(this,$))for(let t=n(this,ee);!(!m(this,v,Ri).call(this,t)||((e||!n(this,fe).call(this,t))&&(yield t),t===n(this,V)));)t=n(this,se)[t];},Ri=function(e){return e!==void 0&&n(this,z).get(n(this,A)[e])===e},ei=function(e){var a;let t=n(this,ee),i=n(this,A)[t],r=n(this,F)[t];return n(this,rt)&&m(this,v,L).call(this,r)?r.__abortController.abort(new Error("evicted")):(n(this,Le)||n(this,ie))&&(n(this,Le)&&((a=n(this,Ne))==null||a.call(this,r,i,"evict")),n(this,ie)&&n(this,Y)?.push([r,i,"evict"])),n(this,Et).call(this,t),n(this,ge)?.[t]&&(clearTimeout(n(this,ge)[t]),n(this,ge)[t]=void 0),e&&(n(this,A)[t]=void 0,n(this,F)[t]=void 0,n(this,Fe).push(t)),n(this,$)===1?(g(this,ee,g(this,V,0)),n(this,Fe).length=0):g(this,ee,n(this,se)[t]),n(this,z).delete(i),zs(this,$)._--,t},ti=function(e,t,i,r){let a=t===void 0?void 0:n(this,F)[t];if(m(this,v,L).call(this,a))return a;let o=new oi,{signal:h}=i;h?.addEventListener("abort",()=>o.abort(h.reason),{signal:o.signal});let l={signal:o.signal,options:i,context:r},c=(x,b=false)=>{let{aborted:y}=o.signal,_=i.ignoreFetchAbort&&x!==void 0,N=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&x!==void 0);if(i.status&&(y&&!b?(i.status.fetchAborted=true,i.status.fetchError=o.signal.reason,_&&(i.status.fetchAbortIgnored=true)):i.status.fetchResolved=true),y&&!_&&!b)return d(o.signal.reason,N);let P=S,T=n(this,F)[t];return (T===S||_&&b&&T===void 0)&&(x===void 0?P.__staleWhileFetching!==void 0?n(this,F)[t]=P.__staleWhileFetching:m(this,v,tt).call(this,e,"fetch"):(i.status&&(i.status.fetchUpdated=true),this.set(e,x,l.options))),x},p=x=>(i.status&&(i.status.fetchRejected=true,i.status.fetchError=x),d(x,false)),d=(x,b)=>{let{aborted:y}=o.signal,_=y&&i.allowStaleOnFetchAbort,N=_||i.allowStaleOnFetchRejection,P=N||i.noDeleteOnFetchRejection,T=S;if(n(this,F)[t]===S&&(!P||!b&&T.__staleWhileFetching===void 0?m(this,v,tt).call(this,e,"fetch"):_||(n(this,F)[t]=T.__staleWhileFetching)),N)return i.status&&T.__staleWhileFetching!==void 0&&(i.status.returnedStale=true),T.__staleWhileFetching;if(T.__returned===T)throw x},f=(x,b)=>{var _;let y=(_=n(this,zt))==null?void 0:_.call(this,e,a,l);y&&y instanceof Promise&&y.then(N=>x(N===void 0?void 0:N),b),o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(x(void 0),i.allowStaleOnFetchAbort&&(x=N=>c(N,true)));});};i.status&&(i.status.fetchDispatched=true);let S=new Promise(f).then(c,p),w=Object.assign(S,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return t===void 0?(this.set(e,w,{...l.options,status:void 0}),t=n(this,z).get(e)):n(this,F)[t]=w,w},L=function(e){if(!n(this,rt))return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof oi},Fi=function(e,t){n(this,ue)[t]=e,n(this,se)[e]=t;},hs=function(e){e!==n(this,V)&&(e===n(this,ee)?g(this,ee,n(this,se)[e]):m(this,v,Fi).call(this,n(this,ue)[e],n(this,se)[e]),m(this,v,Fi).call(this,n(this,V),e),g(this,V,e));},tt=function(e,t){var r,a;let i=false;if(n(this,$)!==0){let o=n(this,z).get(e);if(o!==void 0)if(n(this,ge)?.[o]&&(clearTimeout(n(this,ge)?.[o]),n(this,ge)[o]=void 0),i=true,n(this,$)===1)m(this,v,Pi).call(this,t);else {n(this,Et).call(this,o);let h=n(this,F)[o];if(m(this,v,L).call(this,h)?h.__abortController.abort(new Error("deleted")):(n(this,Le)||n(this,ie))&&(n(this,Le)&&((r=n(this,Ne))==null||r.call(this,h,e,t)),n(this,ie)&&n(this,Y)?.push([h,e,t])),n(this,z).delete(e),n(this,A)[o]=void 0,n(this,F)[o]=void 0,o===n(this,V))g(this,V,n(this,ue)[o]);else if(o===n(this,ee))g(this,ee,n(this,se)[o]);else {let l=n(this,ue)[o];n(this,se)[l]=n(this,se)[o];let c=n(this,se)[o];n(this,ue)[c]=n(this,ue)[o];}zs(this,$)._--,n(this,Fe).push(o);}}if(n(this,ie)&&n(this,Y)?.length){let o=n(this,Y),h;for(;h=o?.shift();)(a=n(this,Te))==null||a.call(this,...h);}return i},Pi=function(e){var t,i;for(let r of m(this,v,et).call(this,{allowStale:true})){let a=n(this,F)[r];if(m(this,v,L).call(this,a))a.__abortController.abort(new Error("deleted"));else {let o=n(this,A)[r];n(this,Le)&&((t=n(this,Ne))==null||t.call(this,a,o,e)),n(this,ie)&&n(this,Y)?.push([a,o,e]);}}if(n(this,z).clear(),n(this,F).fill(void 0),n(this,A).fill(void 0),n(this,pe)&&n(this,Oe)){n(this,pe).fill(0),n(this,Oe).fill(0);for(let r of n(this,ge)??[])r!==void 0&&clearTimeout(r);n(this,ge)?.fill(void 0);}if(n(this,Pe)&&n(this,Pe).fill(0),g(this,ee,0),g(this,V,0),n(this,Fe).length=0,g(this,Re,0),g(this,$,0),n(this,ie)&&n(this,Y)){let r=n(this,Y),a;for(;a=r?.shift();)(i=n(this,Te))==null||i.call(this,...a);}},Ut),rr=typeof process=="object"&&process?process:{stdout:null,stderr:null},wo=s=>!!s&&typeof s=="object"&&(s instanceof hi||s instanceof on||Eo(s)||So(s)),Eo=s=>!!s&&typeof s=="object"&&s instanceof EventEmitter&&typeof s.pipe=="function"&&s.pipe!==on.Writable.prototype.pipe,So=s=>!!s&&typeof s=="object"&&s instanceof EventEmitter&&typeof s.write=="function"&&typeof s.end=="function",je=Symbol("EOF"),$e=Symbol("maybeEmitEnd"),Ke=Symbol("emittedEnd"),qs=Symbol("emittingEnd"),ss=Symbol("emittedError"),Hs=Symbol("closed"),nr=Symbol("read"),Xs=Symbol("flush"),ar=Symbol("flushChunk"),ve=Symbol("encoding"),Mt=Symbol("decoder"),q=Symbol("flowing"),is=Symbol("paused"),kt=Symbol("resume"),H=Symbol("buffer"),te=Symbol("pipes"),X=Symbol("bufferLength"),bi=Symbol("bufferPush"),Qs=Symbol("bufferShift"),Z=Symbol("objectMode"),D=Symbol("destroyed"),wi=Symbol("error"),Ei=Symbol("emitData"),or=Symbol("emitEnd"),Si=Symbol("emitEnd2"),Ae=Symbol("async"),xi=Symbol("abort"),Vs=Symbol("aborted"),rs=Symbol("signal"),pt=Symbol("dataListeners"),ce=Symbol("discarded"),ns=s=>Promise.resolve().then(s),xo=s=>s(),vo=s=>s==="end"||s==="finish"||s==="prefinish",_o=s=>s instanceof ArrayBuffer||!!s&&typeof s=="object"&&s.constructor&&s.constructor.name==="ArrayBuffer"&&s.byteLength>=0,No=s=>!Buffer.isBuffer(s)&&ArrayBuffer.isView(s),hn=class{constructor(s,e,t){u(this,"src");u(this,"dest");u(this,"opts");u(this,"ondrain");this.src=s,this.dest=e,this.opts=t,this.ondrain=()=>s[kt](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(s){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},To=class extends hn{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(s,e,t){super(s,e,t),this.proxyErrors=i=>this.dest.emit("error",i),s.on("error",this.proxyErrors);}},Co=s=>!!s.objectMode,Ro=s=>!s.objectMode&&!!s.encoding&&s.encoding!=="buffer",Er,Sr,xr,vr,_r,Nr,Tr,Cr,Rr,Fr,Pr,Or,Lr,Ir,Ar,Mr,kr,Dr,Wr,hi=class extends EventEmitter{constructor(...e){let t=e[0]||{};super();u(this,Wr,false);u(this,Dr,false);u(this,kr,[]);u(this,Mr,[]);u(this,Ar);u(this,Ir);u(this,Lr);u(this,Or);u(this,Pr,false);u(this,Fr,false);u(this,Rr,false);u(this,Cr,false);u(this,Tr,null);u(this,Nr,0);u(this,_r,false);u(this,vr);u(this,xr,false);u(this,Sr,0);u(this,Er,false);u(this,"writable",true);u(this,"readable",true);if(t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Co(t)?(this[Z]=true,this[ve]=null):Ro(t)?(this[ve]=t.encoding,this[Z]=false):(this[Z]=false,this[ve]=null),this[Ae]=!!t.async,this[Mt]=this[ve]?new StringDecoder(this[ve]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[H]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[te]});let{signal:i}=t;i&&(this[rs]=i,i.aborted?this[xi]():i.addEventListener("abort",()=>this[xi]()));}get bufferLength(){return this[X]}get encoding(){return this[ve]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Z]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Ae]}set async(e){this[Ae]=this[Ae]||!!e;}[(Wr=q,Dr=is,kr=te,Mr=H,Ar=Z,Ir=ve,Lr=Ae,Or=Mt,Pr=je,Fr=Ke,Rr=qs,Cr=Hs,Tr=ss,Nr=X,_r=D,vr=rs,xr=Vs,Sr=pt,Er=ce,xi)](){this[Vs]=true,this.emit("abort",this[rs]?.reason),this.destroy(this[rs]?.reason);}get aborted(){return this[Vs]}set aborted(e){}write(e,t,i){if(this[Vs])return false;if(this[je])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"})),true;typeof t=="function"&&(i=t,t="utf8"),t||(t="utf8");let r=this[Ae]?ns:xo;if(!this[Z]&&!Buffer.isBuffer(e)){if(No(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(_o(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Z]?(this[q]&&this[X]!==0&&this[Xs](true),this[q]?this.emit("data",e):this[bi](e),this[X]!==0&&this.emit("readable"),i&&r(i),this[q]):e.length?(typeof e=="string"&&!(t===this[ve]&&!this[Mt]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[ve]&&(e=this[Mt].write(e)),this[q]&&this[X]!==0&&this[Xs](true),this[q]?this.emit("data",e):this[bi](e),this[X]!==0&&this.emit("readable"),i&&r(i),this[q]):(this[X]!==0&&this.emit("readable"),i&&r(i),this[q])}read(e){if(this[D])return null;if(this[ce]=false,this[X]===0||e===0||e&&e>this[X])return this[$e](),null;this[Z]&&(e=null),this[H].length>1&&!this[Z]&&(this[H]=[this[ve]?this[H].join(""):Buffer.concat(this[H],this[X])]);let t=this[nr](e||null,this[H][0]);return this[$e](),t}[nr](e,t){if(this[Z])this[Qs]();else {let i=t;e===i.length||e===null?this[Qs]():typeof i=="string"?(this[H][0]=i.slice(e),t=i.slice(0,e),this[X]-=e):(this[H][0]=i.subarray(e),t=i.subarray(0,e),this[X]-=e);}return this.emit("data",t),!this[H].length&&!this[je]&&this.emit("drain"),t}end(e,t,i){return typeof e=="function"&&(i=e,e=void 0),typeof t=="function"&&(i=t,t="utf8"),e!==void 0&&this.write(e,t),i&&this.once("end",i),this[je]=true,this.writable=false,(this[q]||!this[is])&&this[$e](),this}[kt](){this[D]||(!this[pt]&&!this[te].length&&(this[ce]=true),this[is]=false,this[q]=true,this.emit("resume"),this[H].length?this[Xs]():this[je]?this[$e]():this.emit("drain"));}resume(){return this[kt]()}pause(){this[q]=false,this[is]=true,this[ce]=false;}get destroyed(){return this[D]}get flowing(){return this[q]}get paused(){return this[is]}[bi](e){this[Z]?this[X]+=1:this[X]+=e.length,this[H].push(e);}[Qs](){return this[Z]?this[X]-=1:this[X]-=this[H][0].length,this[H].shift()}[Xs](e=false){do;while(this[ar](this[Qs]())&&this[H].length);!e&&!this[H].length&&!this[je]&&this.emit("drain");}[ar](e){return this.emit("data",e),this[q]}pipe(e,t){if(this[D])return e;this[ce]=false;let i=this[Ke];return t=t||{},e===rr.stdout||e===rr.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,i?t.end&&e.end():(this[te].push(t.proxyErrors?new To(this,e,t):new hn(this,e,t)),this[Ae]?ns(()=>this[kt]()):this[kt]()),e}unpipe(e){let t=this[te].find(i=>i.dest===e);t&&(this[te].length===1?(this[q]&&this[pt]===0&&(this[q]=false),this[te]=[]):this[te].splice(this[te].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let i=super.on(e,t);if(e==="data")this[ce]=false,this[pt]++,!this[te].length&&!this[q]&&this[kt]();else if(e==="readable"&&this[X]!==0)super.emit("readable");else if(vo(e)&&this[Ke])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[ss]){let r=t;this[Ae]?ns(()=>r.call(this,this[ss])):r.call(this,this[ss]);}return i}removeListener(e,t){return this.off(e,t)}off(e,t){let i=super.off(e,t);return e==="data"&&(this[pt]=this.listeners("data").length,this[pt]===0&&!this[ce]&&!this[te].length&&(this[q]=false)),i}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[pt]=0,!this[ce]&&!this[te].length&&(this[q]=false)),t}get emittedEnd(){return this[Ke]}[$e](){!this[qs]&&!this[Ke]&&!this[D]&&this[H].length===0&&this[je]&&(this[qs]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Hs]&&this.emit("close"),this[qs]=false);}emit(e,...t){let i=t[0];if(e!=="error"&&e!=="close"&&e!==D&&this[D])return false;if(e==="data")return !this[Z]&&!i?false:this[Ae]?(ns(()=>this[Ei](i)),true):this[Ei](i);if(e==="end")return this[or]();if(e==="close"){if(this[Hs]=true,!this[Ke]&&!this[D])return false;let a=super.emit("close");return this.removeAllListeners("close"),a}else if(e==="error"){this[ss]=i,super.emit(wi,i);let a=!this[rs]||this.listeners("error").length?super.emit("error",i):false;return this[$e](),a}else if(e==="resume"){let a=super.emit("resume");return this[$e](),a}else if(e==="finish"||e==="prefinish"){let a=super.emit(e);return this.removeAllListeners(e),a}let r=super.emit(e,...t);return this[$e](),r}[Ei](e){for(let i of this[te])i.dest.write(e)===false&&this.pause();let t=this[ce]?false:super.emit("data",e);return this[$e](),t}[or](){return this[Ke]?false:(this[Ke]=true,this.readable=false,this[Ae]?(ns(()=>this[Si]()),true):this[Si]())}[Si](){if(this[Mt]){let t=this[Mt].end();if(t){for(let i of this[te])i.dest.write(t);this[ce]||super.emit("data",t);}}for(let t of this[te])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[Z]||(e.dataLength=0);let t=this.promise();return this.on("data",i=>{e.push(i),this[Z]||(e.dataLength+=i.length);}),await t,e}async concat(){if(this[Z])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[ve]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(D,()=>t(new Error("stream destroyed"))),this.on("error",i=>t(i)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[ce]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let i=this.read();if(i!==null)return Promise.resolve({done:false,value:i});if(this[je])return t();let r,a,o=p=>{this.off("data",h),this.off("end",l),this.off(D,c),t(),a(p);},h=p=>{this.off("error",o),this.off("end",l),this.off(D,c),this.pause(),r({value:p,done:!!this[je]});},l=()=>{this.off("error",o),this.off("data",h),this.off(D,c),t(),r({done:true,value:void 0});},c=()=>o(new Error("stream destroyed"));return new Promise((p,d)=>{a=d,r=p,this.once(D,c),this.once("error",o),this.once("end",l),this.once("data",h);})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ce]=false;let e=false,t=()=>(this.pause(),this.off(wi,t),this.off(D,t),this.off("end",t),e=true,{done:true,value:void 0}),i=()=>{if(e)return t();let r=this.read();return r===null?t():{done:false,value:r}};return this.once("end",t),this.once(wi,t),this.once(D,t),{next:i,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[D])return e?this.emit("error",e):this.emit(D),this;this[D]=true,this[ce]=true,this[H].length=0,this[X]=0;let t=this;return typeof t.close=="function"&&!this[Hs]&&t.close(),e?this.emit("error",e):this.emit(D),this}static get isStream(){return wo}},Fo=realpathSync.native,ls={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Fo,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},ln=s=>!s||s===ls||s===An?ls:{...ls,...s,promises:{...ls.promises,...s.promises||{}}},cn=/^\\\\\?\\([a-z]:)\\?$/i,Po=s=>s.replace(/\//g,"\\").replace(cn,"$1\\"),Oo=/[\\\/]/,we=0,dn=1,un=2,Me=4,pn=6,gn=8,gt=10,fn=12,ye=15,as=~ye,vi=16,hr=32,cs=64,_e=128,Ys=256,si=512,lr=cs|_e|si,Lo=1023,_i=s=>s.isFile()?gn:s.isDirectory()?Me:s.isSymbolicLink()?gt:s.isCharacterDevice()?un:s.isBlockDevice()?pn:s.isSocket()?fn:s.isFIFO()?dn:we,cr=new ci({max:2**12}),ds=s=>{let e=cr.get(s);if(e)return e;let t=s.normalize("NFKD");return cr.set(s,t),t},dr=new ci({max:2**12}),Ks=s=>{let e=dr.get(s);if(e)return e;let t=ds(s.toLowerCase());return dr.set(s,t),t},ur=class extends ci{constructor(){super({max:256});}},Io=class extends ci{constructor(s=16*1024){super({maxSize:s,sizeCalculation:e=>e.length+1});}},mn=Symbol("PathScurry setAsCwd"),re,ys,bs,ws,Es,Ss,xs,vs,_s,Ns,Ts,Cs,Rs,Fs,Ps,Os,Ls,Is,As,nt,St,De,Ge,qe,He,R,xt,Xe,We,C,Li,ii,us,Ii,Ai,ps,ri,Mi,ki,ni,yn,bn,wn,Di,Gt,qt,En,vt,zr,he=(zr=class{constructor(s,e=we,t,i,r,a,o){E(this,C);u(this,"name");u(this,"root");u(this,"roots");u(this,"parent");u(this,"nocase");u(this,"isCWD",false);E(this,re);E(this,ys);E(this,bs);E(this,ws);E(this,Es);E(this,Ss);E(this,xs);E(this,vs);E(this,_s);E(this,Ns);E(this,Ts);E(this,Cs);E(this,Rs);E(this,Fs);E(this,Ps);E(this,Os);E(this,Ls);E(this,Is);E(this,As);E(this,nt);E(this,St);E(this,De);E(this,Ge);E(this,qe);E(this,He);E(this,R);E(this,xt);E(this,Xe);E(this,We);E(this,Gt,[]);E(this,qt,false);E(this,vt);this.name=s,g(this,nt,r?Ks(s):ds(s)),g(this,R,e&Lo),this.nocase=r,this.roots=i,this.root=t||this,g(this,xt,a),g(this,De,o.fullpath),g(this,qe,o.relative),g(this,He,o.relativePosix),this.parent=o.parent,this.parent?g(this,re,n(this.parent,re)):g(this,re,ln(o.fs));}get dev(){return n(this,ys)}get mode(){return n(this,bs)}get nlink(){return n(this,ws)}get uid(){return n(this,Es)}get gid(){return n(this,Ss)}get rdev(){return n(this,xs)}get blksize(){return n(this,vs)}get ino(){return n(this,_s)}get size(){return n(this,Ns)}get blocks(){return n(this,Ts)}get atimeMs(){return n(this,Cs)}get mtimeMs(){return n(this,Rs)}get ctimeMs(){return n(this,Fs)}get birthtimeMs(){return n(this,Ps)}get atime(){return n(this,Os)}get mtime(){return n(this,Ls)}get ctime(){return n(this,Is)}get birthtime(){return n(this,As)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return n(this,St)!==void 0?n(this,St):this.parent?g(this,St,this.parent.depth()+1):g(this,St,0)}childrenCache(){return n(this,xt)}resolve(s){var i;if(!s)return this;let e=this.getRootString(s),t=s.substring(e.length).split(this.splitSep);return e?m(i=this.getRoot(e),C,Li).call(i,t):m(this,C,Li).call(this,t)}children(){let s=n(this,xt).get(this);if(s)return s;let e=Object.assign([],{provisional:0});return n(this,xt).set(this,e),g(this,R,n(this,R)&~vi),e}child(s,e){if(s===""||s===".")return this;if(s==="..")return this.parent||this;let t=this.children(),i=this.nocase?Ks(s):ds(s);for(let h of t)if(n(h,nt)===i)return h;let r=this.parent?this.sep:"",a=n(this,De)?n(this,De)+r+s:void 0,o=this.newChild(s,we,{...e,parent:this,fullpath:a});return this.canReaddir()||g(o,R,n(o,R)|_e),t.push(o),o}relative(){if(this.isCWD)return "";if(n(this,qe)!==void 0)return n(this,qe);let s=this.name,e=this.parent;if(!e)return g(this,qe,this.name);let t=e.relative();return t+(!t||!e.parent?"":this.sep)+s}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(n(this,He)!==void 0)return n(this,He);let s=this.name,e=this.parent;if(!e)return g(this,He,this.fullpathPosix());let t=e.relativePosix();return t+(!t||!e.parent?"":"/")+s}fullpath(){if(n(this,De)!==void 0)return n(this,De);let s=this.name,e=this.parent;if(!e)return g(this,De,this.name);let t=e.fullpath()+(e.parent?this.sep:"")+s;return g(this,De,t)}fullpathPosix(){if(n(this,Ge)!==void 0)return n(this,Ge);if(this.sep==="/")return g(this,Ge,this.fullpath());if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(i)?g(this,Ge,`//?/${i}`):g(this,Ge,i)}let s=this.parent,e=s.fullpathPosix(),t=e+(!e||!s.parent?"":"/")+this.name;return g(this,Ge,t)}isUnknown(){return (n(this,R)&ye)===we}isType(s){return this[`is${s}`]()}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 (n(this,R)&ye)===gn}isDirectory(){return (n(this,R)&ye)===Me}isCharacterDevice(){return (n(this,R)&ye)===un}isBlockDevice(){return (n(this,R)&ye)===pn}isFIFO(){return (n(this,R)&ye)===dn}isSocket(){return (n(this,R)&ye)===fn}isSymbolicLink(){return (n(this,R)>)===gt}lstatCached(){return n(this,R)&hr?this:void 0}readlinkCached(){return n(this,Xe)}realpathCached(){return n(this,We)}readdirCached(){let s=this.children();return s.slice(0,s.provisional)}canReadlink(){if(n(this,Xe))return true;if(!this.parent)return false;let s=n(this,R)&ye;return !(s!==we&&s!==gt||n(this,R)&Ys||n(this,R)&_e)}calledReaddir(){return !!(n(this,R)&vi)}isENOENT(){return !!(n(this,R)&_e)}isNamed(s){return this.nocase?n(this,nt)===Ks(s):n(this,nt)===ds(s)}async readlink(){let s=n(this,Xe);if(s)return s;if(this.canReadlink()&&this.parent)try{let e=await n(this,re).promises.readlink(this.fullpath()),t=(await this.parent.realpath())?.resolve(e);if(t)return g(this,Xe,t)}catch(e){m(this,C,ki).call(this,e.code);return}}readlinkSync(){let s=n(this,Xe);if(s)return s;if(this.canReadlink()&&this.parent)try{let e=n(this,re).readlinkSync(this.fullpath()),t=this.parent.realpathSync()?.resolve(e);if(t)return g(this,Xe,t)}catch(e){m(this,C,ki).call(this,e.code);return}}async lstat(){if((n(this,R)&_e)===0)try{return m(this,C,Di).call(this,await n(this,re).promises.lstat(this.fullpath())),this}catch(s){m(this,C,Mi).call(this,s.code);}}lstatSync(){if((n(this,R)&_e)===0)try{return m(this,C,Di).call(this,n(this,re).lstatSync(this.fullpath())),this}catch(s){m(this,C,Mi).call(this,s.code);}}readdirCB(s,e=false){if(!this.canReaddir()){e?s(null,[]):queueMicrotask(()=>s(null,[]));return}let t=this.children();if(this.calledReaddir()){let r=t.slice(0,t.provisional);e?s(null,r):queueMicrotask(()=>s(null,r));return}if(n(this,Gt).push(s),n(this,qt))return;g(this,qt,true);let i=this.fullpath();n(this,re).readdir(i,{withFileTypes:true},(r,a)=>{if(r)m(this,C,ri).call(this,r.code),t.provisional=0;else {for(let o of a)m(this,C,ni).call(this,o,t);m(this,C,ii).call(this,t);}m(this,C,En).call(this,t.slice(0,t.provisional));});}async readdir(){if(!this.canReaddir())return [];let s=this.children();if(this.calledReaddir())return s.slice(0,s.provisional);let e=this.fullpath();if(n(this,vt))await n(this,vt);else {let t=()=>{};g(this,vt,new Promise(i=>t=i));try{for(let i of await n(this,re).promises.readdir(e,{withFileTypes:!0}))m(this,C,ni).call(this,i,s);m(this,C,ii).call(this,s);}catch(i){m(this,C,ri).call(this,i.code),s.provisional=0;}g(this,vt,void 0),t();}return s.slice(0,s.provisional)}readdirSync(){if(!this.canReaddir())return [];let s=this.children();if(this.calledReaddir())return s.slice(0,s.provisional);let e=this.fullpath();try{for(let t of n(this,re).readdirSync(e,{withFileTypes:!0}))m(this,C,ni).call(this,t,s);m(this,C,ii).call(this,s);}catch(t){m(this,C,ri).call(this,t.code),s.provisional=0;}return s.slice(0,s.provisional)}canReaddir(){if(n(this,R)&lr)return false;let s=ye&n(this,R);return s===we||s===Me||s===gt}shouldWalk(s,e){return (n(this,R)&Me)===Me&&!(n(this,R)&lr)&&!s.has(this)&&(!e||e(this))}async realpath(){if(n(this,We))return n(this,We);if(!((si|Ys|_e)&n(this,R)))try{let s=await n(this,re).promises.realpath(this.fullpath());return g(this,We,this.resolve(s))}catch{m(this,C,Ai).call(this);}}realpathSync(){if(n(this,We))return n(this,We);if(!((si|Ys|_e)&n(this,R)))try{let s=n(this,re).realpathSync(this.fullpath());return g(this,We,this.resolve(s))}catch{m(this,C,Ai).call(this);}}[mn](s){if(s===this)return;s.isCWD=false,this.isCWD=true;let e=new Set([]),t=[],i=this;for(;i&&i.parent;)e.add(i),g(i,qe,t.join(this.sep)),g(i,He,t.join("/")),i=i.parent,t.push("..");for(i=s;i&&i.parent&&!e.has(i);)g(i,qe,void 0),g(i,He,void 0),i=i.parent;}},re=new WeakMap,ys=new WeakMap,bs=new WeakMap,ws=new WeakMap,Es=new WeakMap,Ss=new WeakMap,xs=new WeakMap,vs=new WeakMap,_s=new WeakMap,Ns=new WeakMap,Ts=new WeakMap,Cs=new WeakMap,Rs=new WeakMap,Fs=new WeakMap,Ps=new WeakMap,Os=new WeakMap,Ls=new WeakMap,Is=new WeakMap,As=new WeakMap,nt=new WeakMap,St=new WeakMap,De=new WeakMap,Ge=new WeakMap,qe=new WeakMap,He=new WeakMap,R=new WeakMap,xt=new WeakMap,Xe=new WeakMap,We=new WeakMap,C=new WeakSet,Li=function(s){let e=this;for(let t of s)e=e.child(t);return e},ii=function(s){var e;g(this,R,n(this,R)|vi);for(let t=s.provisional;t<s.length;t++){let i=s[t];i&&m(e=i,C,us).call(e);}},us=function(){n(this,R)&_e||(g(this,R,(n(this,R)|_e)&as),m(this,C,Ii).call(this));},Ii=function(){var e;let s=this.children();s.provisional=0;for(let t of s)m(e=t,C,us).call(e);},Ai=function(){g(this,R,n(this,R)|si),m(this,C,ps).call(this);},ps=function(){if(n(this,R)&cs)return;let s=n(this,R);(s&ye)===Me&&(s&=as),g(this,R,s|cs),m(this,C,Ii).call(this);},ri=function(s=""){s==="ENOTDIR"||s==="EPERM"?m(this,C,ps).call(this):s==="ENOENT"?m(this,C,us).call(this):this.children().provisional=0;},Mi=function(s=""){var e;s==="ENOTDIR"?m(e=this.parent,C,ps).call(e):s==="ENOENT"&&m(this,C,us).call(this);},ki=function(s=""){var t;let e=n(this,R);e|=Ys,s==="ENOENT"&&(e|=_e),(s==="EINVAL"||s==="UNKNOWN")&&(e&=as),g(this,R,e),s==="ENOTDIR"&&this.parent&&m(t=this.parent,C,ps).call(t);},ni=function(s,e){return m(this,C,bn).call(this,s,e)||m(this,C,yn).call(this,s,e)},yn=function(s,e){let t=_i(s),i=this.newChild(s.name,t,{parent:this}),r=n(i,R)&ye;return r!==Me&&r!==gt&&r!==we&&g(i,R,n(i,R)|cs),e.unshift(i),e.provisional++,i},bn=function(s,e){for(let t=e.provisional;t<e.length;t++){let i=e[t];if((this.nocase?Ks(s.name):ds(s.name))===n(i,nt))return m(this,C,wn).call(this,s,i,t,e)}},wn=function(s,e,t,i){let r=e.name;return g(e,R,n(e,R)&as|_i(s)),r!==s.name&&(e.name=s.name),t!==i.provisional&&(t===i.length-1?i.pop():i.splice(t,1),i.unshift(e)),i.provisional++,e},Di=function(s){let{atime:e,atimeMs:t,birthtime:i,birthtimeMs:r,blksize:a,blocks:o,ctime:h,ctimeMs:l,dev:c,gid:p,ino:d,mode:f,mtime:S,mtimeMs:w,nlink:x,rdev:b,size:y,uid:_}=s;g(this,Os,e),g(this,Cs,t),g(this,As,i),g(this,Ps,r),g(this,vs,a),g(this,Ts,o),g(this,Is,h),g(this,Fs,l),g(this,ys,c),g(this,Ss,p),g(this,_s,d),g(this,bs,f),g(this,Ls,S),g(this,Rs,w),g(this,ws,x),g(this,xs,b),g(this,Ns,y),g(this,Es,_);let N=_i(s);g(this,R,n(this,R)&as|N|hr),N!==we&&N!==Me&&N!==gt&&g(this,R,n(this,R)|cs);},Gt=new WeakMap,qt=new WeakMap,En=function(s){g(this,qt,false);let e=n(this,Gt).slice();n(this,Gt).length=0,e.forEach(t=>t(null,s));},vt=new WeakMap,zr),Sn=class xn extends he{constructor(t,i=we,r,a,o,h,l){super(t,i,r,a,o,h,l);u(this,"sep","\\");u(this,"splitSep",Oo);}newChild(t,i=we,r={}){return new xn(t,i,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(t){return win32.parse(t).root}getRoot(t){if(t=Po(t.toUpperCase()),t===this.root.name)return this.root;for(let[i,r]of Object.entries(this.roots))if(this.sameRoot(t,i))return this.roots[t]=r;return this.roots[t]=new Bi(t,this).root}sameRoot(t,i=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(cn,"$1\\"),t===i}},vn=class _n extends he{constructor(t,i=we,r,a,o,h,l){super(t,i,r,a,o,h,l);u(this,"splitSep","/");u(this,"sep","/");}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,i=we,r={}){return new _n(t,i,this.root,this.roots,this.nocase,this.childrenCache(),r)}},Ht,Xt,Ms,ks,jr,Nn=(jr=class{constructor(s=process.cwd(),e,t,{nocase:i,childrenCacheSize:r=16*1024,fs:a=ls}={}){u(this,"root");u(this,"rootPath");u(this,"roots");u(this,"cwd");E(this,Ht);E(this,Xt);E(this,Ms);u(this,"nocase");E(this,ks);g(this,ks,ln(a)),(s instanceof URL||s.startsWith("file://"))&&(s=fileURLToPath(s));let o=e.resolve(s);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),g(this,Ht,new ur),g(this,Xt,new ur),g(this,Ms,new Io(r));let h=o.substring(this.rootPath.length).split(t);if(h.length===1&&!h[0]&&h.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(n(this,ks)),this.roots[this.rootPath]=this.root;let l=this.root,c=h.length-1,p=e.sep,d=this.rootPath,f=false;for(let S of h){let w=c--;l=l.child(S,{relative:new Array(w).fill("..").join(p),relativePosix:new Array(w).fill("..").join("/"),fullpath:d+=(f?"":p)+S}),f=true;}this.cwd=l;}depth(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.depth()}childrenCache(){return n(this,Ms)}resolve(...s){let e="";for(let r=s.length-1;r>=0;r--){let a=s[r];if(!(!a||a===".")&&(e=e?`${a}/${e}`:a,this.isAbsolute(a)))break}let t=n(this,Ht).get(e);if(t!==void 0)return t;let i=this.cwd.resolve(e).fullpath();return n(this,Ht).set(e,i),i}resolvePosix(...s){let e="";for(let r=s.length-1;r>=0;r--){let a=s[r];if(!(!a||a===".")&&(e=e?`${a}/${e}`:a,this.isAbsolute(a)))break}let t=n(this,Xt).get(e);if(t!==void 0)return t;let i=this.cwd.resolve(e).fullpathPosix();return n(this,Xt).set(e,i),i}relative(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.relative()}relativePosix(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.relativePosix()}basename(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.name}dirname(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),(s.parent||s).fullpath()}async readdir(s=this.cwd,e={withFileTypes:true}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t}=e;if(s.canReaddir()){let i=await s.readdir();return t?i:i.map(r=>r.name)}else return []}readdirSync(s=this.cwd,e={withFileTypes:true}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true}=e;return s.canReaddir()?t?s.readdirSync():s.readdirSync().map(i=>i.name):[]}async lstat(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.lstat()}lstatSync(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.lstatSync()}async readlink(s=this.cwd,{withFileTypes:e}={withFileTypes:false}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s.withFileTypes,s=this.cwd);let t=await s.readlink();return e?t:t?.fullpath()}readlinkSync(s=this.cwd,{withFileTypes:e}={withFileTypes:false}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s.withFileTypes,s=this.cwd);let t=s.readlinkSync();return e?t:t?.fullpath()}async realpath(s=this.cwd,{withFileTypes:e}={withFileTypes:false}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s.withFileTypes,s=this.cwd);let t=await s.realpath();return e?t:t?.fullpath()}realpathSync(s=this.cwd,{withFileTypes:e}={withFileTypes:false}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s.withFileTypes,s=this.cwd);let t=s.realpathSync();return e?t:t?.fullpath()}async walk(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e,o=[];(!r||r(s))&&o.push(t?s:s.fullpath());let h=new Set,l=(p,d)=>{h.add(p),p.readdirCB((f,S)=>{if(f)return d(f);let w=S.length;if(!w)return d();let x=()=>{--w===0&&d();};for(let b of S)(!r||r(b))&&o.push(t?b:b.fullpath()),i&&b.isSymbolicLink()?b.realpath().then(y=>y?.isUnknown()?y.lstat():y).then(y=>y?.shouldWalk(h,a)?l(y,x):x()):b.shouldWalk(h,a)?l(b,x):x();},true);},c=s;return new Promise((p,d)=>{l(c,f=>{if(f)return d(f);p(o);});})}walkSync(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e,o=[];(!r||r(s))&&o.push(t?s:s.fullpath());let h=new Set([s]);for(let l of h){let c=l.readdirSync();for(let p of c){(!r||r(p))&&o.push(t?p:p.fullpath());let d=p;if(p.isSymbolicLink()){if(!(i&&(d=p.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(h,a)&&h.add(d);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(s=this.cwd,e={}){return typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd),this.stream(s,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e;(!r||r(s))&&(yield t?s:s.fullpath());let o=new Set([s]);for(let h of o){let l=h.readdirSync();for(let c of l){(!r||r(c))&&(yield t?c:c.fullpath());let p=c;if(c.isSymbolicLink()){if(!(i&&(p=c.realpathSync())))continue;p.isUnknown()&&p.lstatSync();}p.shouldWalk(o,a)&&o.add(p);}}}stream(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e,o=new hi({objectMode:true});(!r||r(s))&&o.write(t?s:s.fullpath());let h=new Set,l=[s],c=0,p=()=>{let d=false;for(;!d;){let f=l.shift();if(!f){c===0&&o.end();return}c++,h.add(f);let S=(x,b,y=false)=>{if(x)return o.emit("error",x);if(i&&!y){let _=[];for(let N of b)N.isSymbolicLink()&&_.push(N.realpath().then(P=>P?.isUnknown()?P.lstat():P));if(_.length){Promise.all(_).then(()=>S(null,b,true));return}}for(let _ of b)_&&(!r||r(_))&&(o.write(t?_:_.fullpath())||(d=true));c--;for(let _ of b){let N=_.realpathCached()||_;N.shouldWalk(h,a)&&l.push(N);}d&&!o.flowing?o.once("drain",p):w||p();},w=true;f.readdirCB(S,true),w=false;}};return p(),o}streamSync(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e,o=new hi({objectMode:true}),h=new Set;(!r||r(s))&&o.write(t?s:s.fullpath());let l=[s],c=0,p=()=>{let d=false;for(;!d;){let f=l.shift();if(!f){c===0&&o.end();return}c++,h.add(f);let S=f.readdirSync();for(let w of S)(!r||r(w))&&(o.write(t?w:w.fullpath())||(d=true));c--;for(let w of S){let x=w;if(w.isSymbolicLink()){if(!(i&&(x=w.realpathSync())))continue;x.isUnknown()&&x.lstatSync();}x.shouldWalk(h,a)&&l.push(x);}}d&&!o.flowing&&o.once("drain",p);};return p(),o}chdir(s=this.cwd){let e=this.cwd;this.cwd=typeof s=="string"?this.cwd.resolve(s):s,this.cwd[mn](e);}},Ht=new WeakMap,Xt=new WeakMap,Ms=new WeakMap,ks=new WeakMap,jr),Bi=class extends Nn{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,win32,"\\",{...t,nocase:i});u(this,"sep","\\");this.nocase=i;for(let r=this.cwd;r;r=r.parent)r.nocase=this.nocase;}parseRootPath(e){return win32.parse(e).root.toUpperCase()}newRoot(e){return new Sn(this.rootPath,Me,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Ui=class extends Nn{constructor(e=process.cwd(),t={}){let{nocase:i=false}=t;super(e,posix,"/",{...t,nocase:i});u(this,"sep","/");this.nocase=i;}parseRootPath(e){return "/"}newRoot(e){return new vn(this.rootPath,Me,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Tn=class extends Ui{constructor(s=process.cwd(),e={}){let{nocase:t=true}=e;super(s,{...e,nocase:t});}};process.platform==="win32"?Sn:vn;var Ao=process.platform==="win32"?Bi:process.platform==="darwin"?Tn:Ui,Mo=s=>s.length>=1,ko=s=>s.length>=1,Do=Symbol.for("nodejs.util.inspect.custom"),B,le,U,_t,Ie,Ds,at,ot,ht,Qt,Vt,Cn=(Vt=class{constructor(e,t,i,r){E(this,B);E(this,le);E(this,U);u(this,"length");E(this,_t);E(this,Ie);E(this,Ds);E(this,at);E(this,ot);E(this,ht);E(this,Qt,true);if(!Mo(e))throw new TypeError("empty pattern list");if(!ko(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,i<0||i>=this.length)throw new TypeError("index out of range");if(g(this,B,e),g(this,le,t),g(this,U,i),g(this,_t,r),n(this,U)===0){if(this.isUNC()){let[a,o,h,l,...c]=n(this,B),[p,d,f,S,...w]=n(this,le);c[0]===""&&(c.shift(),w.shift());let x=[a,o,h,l,""].join("/"),b=[p,d,f,S,""].join("/");g(this,B,[x,...c]),g(this,le,[b,...w]),this.length=n(this,B).length;}else if(this.isDrive()||this.isAbsolute()){let[a,...o]=n(this,B),[h,...l]=n(this,le);o[0]===""&&(o.shift(),l.shift());let c=a+"/",p=h+"/";g(this,B,[c,...o]),g(this,le,[p,...l]),this.length=n(this,B).length;}}}[Do](){return "Pattern <"+n(this,le).slice(n(this,U)).join("/")+">"}pattern(){return n(this,B)[n(this,U)]}isString(){return typeof n(this,B)[n(this,U)]=="string"}isGlobstar(){return n(this,B)[n(this,U)]===ne}isRegExp(){return n(this,B)[n(this,U)]instanceof RegExp}globString(){return g(this,Ds,n(this,Ds)||(n(this,U)===0?this.isAbsolute()?n(this,le)[0]+n(this,le).slice(1).join("/"):n(this,le).join("/"):n(this,le).slice(n(this,U)).join("/")))}hasMore(){return this.length>n(this,U)+1}rest(){return n(this,Ie)!==void 0?n(this,Ie):this.hasMore()?(g(this,Ie,new Vt(n(this,B),n(this,le),n(this,U)+1,n(this,_t))),g(n(this,Ie),ht,n(this,ht)),g(n(this,Ie),ot,n(this,ot)),g(n(this,Ie),at,n(this,at)),n(this,Ie)):g(this,Ie,null)}isUNC(){let e=n(this,B);return n(this,ot)!==void 0?n(this,ot):g(this,ot,n(this,_t)==="win32"&&n(this,U)===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3])}isDrive(){let e=n(this,B);return n(this,at)!==void 0?n(this,at):g(this,at,n(this,_t)==="win32"&&n(this,U)===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]))}isAbsolute(){let e=n(this,B);return n(this,ht)!==void 0?n(this,ht):g(this,ht,e[0]===""&&e.length>1||this.isDrive()||this.isUNC())}root(){let e=n(this,B)[0];return typeof e=="string"&&this.isAbsolute()&&n(this,U)===0?e:""}checkFollowGlobstar(){return !(n(this,U)===0||!this.isGlobstar()||!n(this,Qt))}markFollowGlobstar(){return n(this,U)===0||!this.isGlobstar()||!n(this,Qt)?false:(g(this,Qt,false),true)}},B=new WeakMap,le=new WeakMap,U=new WeakMap,_t=new WeakMap,Ie=new WeakMap,Ds=new WeakMap,at=new WeakMap,ot=new WeakMap,ht=new WeakMap,Qt=new WeakMap,Vt),Wo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",pr=class{constructor(s,{nobrace:e,nocase:t,noext:i,noglobstar:r,platform:a=Wo}){u(this,"relative");u(this,"relativeChildren");u(this,"absolute");u(this,"absoluteChildren");u(this,"platform");u(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=a,this.mmopts={dot:true,nobrace:e,nocase:t,noext:i,noglobstar:r,optimizationLevel:2,platform:a,nocomment:true,nonegate:true};for(let o of s)this.add(o);}add(s){let e=new ct(s,this.mmopts);for(let t=0;t<e.set.length;t++){let i=e.set[t],r=e.globParts[t];if(!i||!r)throw new Error("invalid pattern object");for(;i[0]==="."&&r[0]===".";)i.shift(),r.shift();let a=new Cn(i,r,0,this.platform),o=new ct(a.globString(),this.mmopts),h=r[r.length-1]==="**",l=a.isAbsolute();l?this.absolute.push(o):this.relative.push(o),h&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(s){let e=s.fullpath(),t=`${e}/`,i=s.relative()||".",r=`${i}/`;for(let a of this.relative)if(a.match(i)||a.match(r))return true;for(let a of this.absolute)if(a.match(e)||a.match(t))return true;return false}childrenIgnored(s){let e=s.fullpath()+"/",t=(s.relative()||".")+"/";for(let i of this.relativeChildren)if(i.match(t))return true;for(let i of this.absoluteChildren)if(i.match(e))return true;return false}},zo=class Rn{constructor(e=new Map){u(this,"store");this.store=e;}copy(){return new Rn(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let i=e.fullpath(),r=this.store.get(i);r?r.add(t.globString()):this.store.set(i,new Set([t.globString()]));}},jo=class{constructor(){u(this,"store",new Map);}add(s,e,t){let i=(e?2:0)|(t?1:0),r=this.store.get(s);this.store.set(s,r===void 0?i:i&r);}entries(){return [...this.store.entries()].map(([s,e])=>[s,!!(e&2),!!(e&1)])}},$o=class{constructor(){u(this,"store",new Map);}add(s,e){if(!s.canReaddir())return;let t=this.store.get(s);t?t.find(i=>i.globString()===e.globString())||t.push(e):this.store.set(s,[e]);}get(s){let e=this.store.get(s);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(s=>[s,this.store.get(s)])}keys(){return [...this.store.keys()].filter(s=>s.canReaddir())}},gr=class Fn{constructor(e,t){u(this,"hasWalkedCache");u(this,"matches",new jo);u(this,"subwalks",new $o);u(this,"patterns");u(this,"follow");u(this,"dot");u(this,"opts");this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new zo;}processPatterns(e,t){this.patterns=t;let i=t.map(r=>[e,r]);for(let[r,a]of i){this.hasWalkedCache.storeWalked(r,a);let o=a.root(),h=a.isAbsolute()&&this.opts.absolute!==false;if(o){r=r.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let d=a.rest();if(d)a=d;else {this.matches.add(r,true,false);continue}}if(r.isENOENT())continue;let l,c,p=false;for(;typeof(l=a.pattern())=="string"&&(c=a.rest());)r=r.resolve(l),a=c,p=true;if(l=a.pattern(),c=a.rest(),p){if(this.hasWalkedCache.hasWalked(r,a))continue;this.hasWalkedCache.storeWalked(r,a);}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(r.resolve(l),h,d);continue}else if(l===ne){(!r.isSymbolicLink()||this.follow||a.checkFollowGlobstar())&&this.subwalks.add(r,a);let d=c?.pattern(),f=c?.rest();if(!c||(d===""||d===".")&&!f)this.matches.add(r,h,d===""||d===".");else if(d===".."){let S=r.parent||r;f?this.hasWalkedCache.hasWalked(S,f)||this.subwalks.add(S,f):this.matches.add(S,h,true);}}else l instanceof RegExp&&this.subwalks.add(r,a);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new Fn(this.opts,this.hasWalkedCache)}filterEntries(e,t){let i=this.subwalks.get(e),r=this.child();for(let a of t)for(let o of i){let h=o.isAbsolute(),l=o.pattern(),c=o.rest();l===ne?r.testGlobstar(a,o,c,h):l instanceof RegExp?r.testRegExp(a,l,c,h):r.testString(a,l,c,h);}return r}testGlobstar(e,t,i,r){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,r,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(i&&t.checkFollowGlobstar()?this.subwalks.add(e,i):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),i){let a=i.pattern();if(typeof a=="string"&&a!==".."&&a!==""&&a!==".")this.testString(e,a,i.rest(),r);else if(a===".."){let o=e.parent||e;this.subwalks.add(o,i);}else a instanceof RegExp&&this.testRegExp(e,a,i.rest(),r);}}testRegExp(e,t,i,r){t.test(e.name)&&(i?this.subwalks.add(e,i):this.matches.add(e,r,false));}testString(e,t,i,r){e.isNamed(t)&&(i?this.subwalks.add(e,i):this.matches.add(e,r,false));}},Bo=(s,e)=>typeof s=="string"?new pr([s],e):Array.isArray(s)?new pr(s,e):s,Yt,Qe,Nt,Ee,ft,Wi,$r,Pn=($r=class{constructor(s,e,t){E(this,Ee);u(this,"path");u(this,"patterns");u(this,"opts");u(this,"seen",new Set);u(this,"paused",false);u(this,"aborted",false);E(this,Yt,[]);E(this,Qe);E(this,Nt);u(this,"signal");u(this,"maxDepth");u(this,"includeChildMatches");if(this.patterns=s,this.path=e,this.opts=t,g(this,Nt,!t.posix&&t.platform==="win32"?"\\":"/"),this.includeChildMatches=t.includeChildMatches!==false,(t.ignore||!this.includeChildMatches)&&(g(this,Qe,Bo(t.ignore??[],t)),!this.includeChildMatches&&typeof n(this,Qe).add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=t.maxDepth||1/0,t.signal&&(this.signal=t.signal,this.signal.addEventListener("abort",()=>{n(this,Yt).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let s;for(;!this.paused&&(s=n(this,Yt).shift());)s();}onResume(s){this.signal?.aborted||(this.paused?n(this,Yt).push(s):s());}async matchCheck(s,e){if(e&&this.opts.nodir)return;let t;if(this.opts.realpath){if(t=s.realpathCached()||await s.realpath(),!t)return;s=t;}let i=s.isUnknown()||this.opts.stat?await s.lstat():s;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let r=await i.realpath();r&&(r.isUnknown()||this.opts.stat)&&await r.lstat();}return this.matchCheckTest(i,e)}matchCheckTest(s,e){return s&&(this.maxDepth===1/0||s.depth()<=this.maxDepth)&&(!e||s.canReaddir())&&(!this.opts.nodir||!s.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!s.isSymbolicLink()||!s.realpathCached()?.isDirectory())&&!m(this,Ee,ft).call(this,s)?s:void 0}matchCheckSync(s,e){if(e&&this.opts.nodir)return;let t;if(this.opts.realpath){if(t=s.realpathCached()||s.realpathSync(),!t)return;s=t;}let i=s.isUnknown()||this.opts.stat?s.lstatSync():s;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let r=i.realpathSync();r&&(r?.isUnknown()||this.opts.stat)&&r.lstatSync();}return this.matchCheckTest(i,e)}matchFinish(s,e){if(m(this,Ee,ft).call(this,s))return;if(!this.includeChildMatches&&n(this,Qe)?.add){let r=`${s.relativePosix()}/**`;n(this,Qe).add(r);}let t=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(s);let i=this.opts.mark&&s.isDirectory()?n(this,Nt):"";if(this.opts.withFileTypes)this.matchEmit(s);else if(t){let r=this.opts.posix?s.fullpathPosix():s.fullpath();this.matchEmit(r+i);}else {let r=this.opts.posix?s.relativePosix():s.relative(),a=this.opts.dotRelative&&!r.startsWith(".."+n(this,Nt))?"."+n(this,Nt):"";this.matchEmit(r?a+r+i:"."+i);}}async match(s,e,t){let i=await this.matchCheck(s,t);i&&this.matchFinish(i,e);}matchSync(s,e,t){let i=this.matchCheckSync(s,t);i&&this.matchFinish(i,e);}walkCB(s,e,t){this.signal?.aborted&&t(),this.walkCB2(s,e,new gr(this.opts),t);}walkCB2(s,e,t,i){if(m(this,Ee,Wi).call(this,s))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(s,e,t,i));return}t.processPatterns(s,e);let r=1,a=()=>{--r===0&&i();};for(let[o,h,l]of t.matches.entries())m(this,Ee,ft).call(this,o)||(r++,this.match(o,h,l).then(()=>a()));for(let o of t.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let h=o.readdirCached();o.calledReaddir()?this.walkCB3(o,h,t,a):o.readdirCB((l,c)=>this.walkCB3(o,c,t,a),true);}a();}walkCB3(s,e,t,i){t=t.filterEntries(s,e);let r=1,a=()=>{--r===0&&i();};for(let[o,h,l]of t.matches.entries())m(this,Ee,ft).call(this,o)||(r++,this.match(o,h,l).then(()=>a()));for(let[o,h]of t.subwalks.entries())r++,this.walkCB2(o,h,t.child(),a);a();}walkCBSync(s,e,t){this.signal?.aborted&&t(),this.walkCB2Sync(s,e,new gr(this.opts),t);}walkCB2Sync(s,e,t,i){if(m(this,Ee,Wi).call(this,s))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(s,e,t,i));return}t.processPatterns(s,e);let r=1,a=()=>{--r===0&&i();};for(let[o,h,l]of t.matches.entries())m(this,Ee,ft).call(this,o)||this.matchSync(o,h,l);for(let o of t.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let h=o.readdirSync();this.walkCB3Sync(o,h,t,a);}a();}walkCB3Sync(s,e,t,i){t=t.filterEntries(s,e);let r=1,a=()=>{--r===0&&i();};for(let[o,h,l]of t.matches.entries())m(this,Ee,ft).call(this,o)||this.matchSync(o,h,l);for(let[o,h]of t.subwalks.entries())r++,this.walkCB2Sync(o,h,t.child(),a);a();}},Yt=new WeakMap,Qe=new WeakMap,Nt=new WeakMap,Ee=new WeakSet,ft=function(s){return this.seen.has(s)||!!n(this,Qe)?.ignored?.(s)},Wi=function(s){return !!n(this,Qe)?.childrenIgnored?.(s)},$r),fr=class extends Pn{constructor(e,t,i){super(e,t,i);u(this,"matches",new Set);}matchEmit(e){this.matches.add(e);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},mr=class extends Pn{constructor(e,t,i){super(e,t,i);u(this,"results");this.results=new hi({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(e){this.results.write(e),this.results.flowing||this.pause();}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end());}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},Uo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ct=class{constructor(s,e){u(this,"absolute");u(this,"cwd");u(this,"root");u(this,"dot");u(this,"dotRelative");u(this,"follow");u(this,"ignore");u(this,"magicalBraces");u(this,"mark");u(this,"matchBase");u(this,"maxDepth");u(this,"nobrace");u(this,"nocase");u(this,"nodir");u(this,"noext");u(this,"noglobstar");u(this,"pattern");u(this,"platform");u(this,"realpath");u(this,"scurry");u(this,"stat");u(this,"signal");u(this,"windowsPathsNoEscape");u(this,"withFileTypes");u(this,"includeChildMatches");u(this,"opts");u(this,"patterns");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=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!==false,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 s=="string"&&(s=[s]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===false,this.windowsPathsNoEscape&&(s=s.map(h=>h.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");s=s.map(h=>h.includes("/")?h:`./**/${h}`);}if(this.pattern=s,this.platform=e.platform||Uo,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 h=e.platform==="win32"?Bi:e.platform==="darwin"?Tn:e.platform?Ui:Ao;this.scurry=new h(this.cwd,{nocase:e.nocase,fs:e.fs});}this.nocase=this.scurry.nocase;let t=this.platform==="darwin"||this.platform==="win32",i={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:t,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(h=>new ct(h,i)),[a,o]=r.reduce((h,l)=>(h[0].push(...l.set),h[1].push(...l.globParts),h),[[],[]]);this.patterns=a.map((h,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new Cn(h,c,0,this.platform)});}async walk(){return [...await new fr(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 fr(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 mr(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 mr(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()}},Go=(s,e={})=>{Array.isArray(s)||(s=[s]);for(let t of s)if(new ct(t,e).hasMagic())return true;return false};function di(s,e={}){return new Ct(s,e).streamSync()}function On(s,e={}){return new Ct(s,e).stream()}function Ln(s,e={}){return new Ct(s,e).walkSync()}async function yr(s,e={}){return new Ct(s,e).walk()}function ui(s,e={}){return new Ct(s,e).iterateSync()}function In(s,e={}){return new Ct(s,e).iterate()}var qo=di,Ho=Object.assign(On,{sync:di}),Xo=ui,Qo=Object.assign(In,{sync:ui}),Vo=Object.assign(Ln,{stream:di,iterate:ui}),li=Object.assign(yr,{glob:yr,globSync:Ln,sync:Vo,globStream:On,stream:Ho,globStreamSync:di,streamSync:qo,globIterate:In,iterate:Qo,globIterateSync:ui,iterateSync:Xo,Glob:Ct,hasMagic:Go,escape:Kr,unescape:Dt});li.glob=li;var Ve;(P=>{P.Level=Ko.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let e={DEBUG:0,INFO:1,WARN:2,ERROR:3},t="INFO";function i(T){return e[T]>=e[t]}function r(){return t}P.getLevel=r;let a=new Map;P.Default=N({service:"default"});let h="";function l(){return h}P.file=l;let c,p,d=false,f=()=>{},S=false;async function w(T){if(d)return;if(T.print){d=true;return}T.level&&(t=T.level);let O=T.logDir||Jt.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");T.logFile?h=Jt.join(O,T.logFile??"codebase.log"):h=Jt.join(O,"codebase.log");try{await qi.mkdir(O,{recursive:!0}),c=await qi.open(h,"a"),p=createWriteStream("",{fd:c.fd,autoClose:!1}),f=k=>{if(!(S||!p||p.destroyed))try{if(!p.writable)return;p.write(k,J=>{J&&!S&&(S=!0,setTimeout(()=>{S=!1;},1e3));});}catch{S||(S=!0,setTimeout(()=>{S=!1;},1e3));}},d=!0;}catch{f=k=>{try{process.stderr.write(k);}catch{}},d=true;}}P.init=w;async function x(){d&&(p&&!p.destroyed&&(await new Promise((T,O)=>{p.end(k=>{k?O(k):T();});}).catch(()=>{}),p=void 0),c&&(await c.close().catch(()=>{}),c=void 0),f=T=>{try{process.stderr.write(T);}catch{}},d=false);}P.close=x;function y(T,O=0){let k=T.message;return T.cause instanceof Error&&O<10?k+" Caused by: "+y(T.cause,O+1):k}let _=Date.now();function N(T){T=T||{};let O=T.service;if(O&&typeof O=="string"){let M=a.get(O);if(M)return M}function k(M,G){let gi=Object.entries({...T,...G}).filter(([Xi,Ye])=>Ye!=null).map(([Xi,Ye])=>{let fi=`${Xi}=`;return Ye instanceof Error?fi+y(Ye):typeof Ye=="object"?fi+JSON.stringify(Ye):fi+Ye}).join(" "),Se=new Date,Hn=Se.getTime()-_;return _=Se.getTime(),[Se.getFullYear()+"-"+String(Se.getMonth()+1).padStart(2,"0")+"-"+String(Se.getDate()).padStart(2,"0")+"T"+String(Se.getHours()).padStart(2,"0")+":"+String(Se.getMinutes()).padStart(2,"0")+":"+String(Se.getSeconds()).padStart(2,"0"),"+"+Hn+"ms",gi,M].filter(Boolean).join(" ")+`
|
|
4
|
+
`}let J={debug(M,G){i("DEBUG")&&f("DEBUG "+k(M,G));},info(M,G){i("INFO")&&f("INFO "+k(M,G));},error(M,G){i("ERROR")&&f("ERROR "+k(M,G));},warn(M,G){i("WARN")&&f("WARN "+k(M,G));},tag(M,G){return T&&(T[M]=G),J},clone(){return P.create({...T})},time(M,G){let gi=Date.now();J.info(M,{status:"started",...G});function Se(){J.info(M,{status:"completed",duration:Date.now()-gi,...G});}return {stop:Se,[Symbol.dispose](){Se();}}}};return O&&typeof O=="string"&&a.set(O,J),J}P.create=N;})(Ve||(Ve={}));var dt=Filesystem.toUnixPath,Ws=Ve.create({service:"codebase-database"}),Kt=class{constructor(e){u(this,"db");u(this,"dbPath");u(this,"closed",false);u(this,"ftsAvailable",false);this.dbPath=Filesystem.toUnixPath(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=Jt.dirname(this.dbPath);An__default.existsSync(e)||An__default.mkdirSync(e,{recursive:true});let t=new Zo(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
|
|
5
|
+
CREATE TABLE IF NOT EXISTS nodes (
|
|
6
|
+
id TEXT PRIMARY KEY,
|
|
7
|
+
name TEXT NOT NULL,
|
|
8
|
+
ast_type TEXT NOT NULL,
|
|
9
|
+
language TEXT NOT NULL,
|
|
10
|
+
file_path TEXT NOT NULL,
|
|
11
|
+
start_line INTEGER,
|
|
12
|
+
start_col INTEGER,
|
|
13
|
+
end_line INTEGER,
|
|
14
|
+
end_col INTEGER,
|
|
15
|
+
text TEXT,
|
|
16
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
17
|
+
)
|
|
18
|
+
`),e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)"),e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_ast_type ON nodes(ast_type)"),e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_language ON nodes(language)"),e.exec(`
|
|
19
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
20
|
+
id TEXT PRIMARY KEY,
|
|
21
|
+
source TEXT NOT NULL,
|
|
22
|
+
target TEXT NOT NULL,
|
|
23
|
+
relation TEXT NOT NULL,
|
|
24
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
25
|
+
FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
|
|
26
|
+
FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
|
|
27
|
+
)
|
|
28
|
+
`),e.exec("CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)"),e.exec("CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"),e.exec("CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)"),e.exec(`
|
|
29
|
+
CREATE TABLE IF NOT EXISTS file_hashes (
|
|
30
|
+
file_path TEXT PRIMARY KEY,
|
|
31
|
+
content_hash TEXT NOT NULL,
|
|
32
|
+
last_modified DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
33
|
+
)
|
|
34
|
+
`),e.exec(`
|
|
35
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
|
|
36
|
+
id,
|
|
37
|
+
name,
|
|
38
|
+
ast_type,
|
|
39
|
+
language,
|
|
40
|
+
file_path,
|
|
41
|
+
text,
|
|
42
|
+
tokenize='unicode61'
|
|
43
|
+
)
|
|
44
|
+
`),e.exec(`
|
|
45
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
46
|
+
key TEXT PRIMARY KEY,
|
|
47
|
+
value TEXT
|
|
48
|
+
)
|
|
49
|
+
`),e.exec(`
|
|
50
|
+
CREATE TABLE IF NOT EXISTS embedding_cache (
|
|
51
|
+
content_hash TEXT PRIMARY KEY,
|
|
52
|
+
embedding BLOB NOT NULL
|
|
53
|
+
)
|
|
54
|
+
`),e.exec(`
|
|
55
|
+
CREATE TABLE IF NOT EXISTS node_embeddings (
|
|
56
|
+
node_id TEXT PRIMARY KEY,
|
|
57
|
+
embedding_text TEXT NOT NULL,
|
|
58
|
+
embedding BLOB NOT NULL,
|
|
59
|
+
FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
60
|
+
)
|
|
61
|
+
`);}catch(t){throw new $s("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:dt(e.file_path)};this.db.prepare(`
|
|
62
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
63
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
64
|
+
`).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(a=>({...a,file_path:dt(a.file_path)})),i=this.db.prepare(`
|
|
65
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
66
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
67
|
+
`);this.db.transaction(a=>{for(let o of a)i.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.start_line,o.start_col,o.end_line,o.end_col,o.text,o.created_at);})(t),this.ftsAvailable&&this.updateFtsNodes(t);}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){Ws.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),i=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(o=>{for(let h of o)try{let l=i.get(h.id);l&&t.run(l.rowid),r.run(h.id,h.name,h.ast_type,h.language,h.file_path,h.text);}catch(l){Ws.warn("FTS update failed for node",{nodeId:h.id,error:String(l)});}})(e);}insertEdge(e){this.db.prepare(`
|
|
68
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
69
|
+
VALUES (?, ?, ?, ?, ?)
|
|
70
|
+
`).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
|
|
71
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
72
|
+
VALUES (?, ?, ?, ?, ?)
|
|
73
|
+
`);this.db.transaction(r=>{for(let a of r)t.run(a.id,a.source,a.target,a.relation,a.created_at);})(e);}queryNodes(e){let t=[],i=[];e.filePath&&(t.push("file_path LIKE ?"),i.push(`%${dt(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),i.push(e.astType)),e.name&&(t.push("name LIKE ?"),i.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),i.push(e.language));let r="SELECT * FROM nodes";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY file_path, start_line",e.limit&&(r+=" LIMIT ?",i.push(e.limit)),e.offset&&(r+=" OFFSET ?",i.push(e.offset));try{return this.db.prepare(r).all(...i)}catch(a){throw new ut("Failed to query nodes","queryNodes",a instanceof Error?a:new Error(String(a)))}}queryEdges(e){let t=[],i=[];e.source&&(t.push("source = ?"),i.push(e.source)),e.target&&(t.push("target = ?"),i.push(e.target)),e.relation&&(t.push("relation = ?"),i.push(e.relation));let r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",i.push(e.limit)),e.offset&&(r+=" OFFSET ?",i.push(e.offset));try{return this.db.prepare(r).all(...i)}catch(a){throw new ut("Failed to query edges","queryEdges",a instanceof Error?a:new Error(String(a)))}}queryAll(e,t){try{let i=this.db.prepare(e);return t?i.all(...t):i.all()}catch(i){throw new ut("Failed to execute query","queryAll",i instanceof Error?i:new Error(String(i)))}}searchNodesFts(e,t=20){if(!this.ftsAvailable)return [];try{let i=e.split(/\s+/).map(o=>`${o}*`).join(" ");return this.db.prepare(`
|
|
74
|
+
SELECT
|
|
75
|
+
f.id,
|
|
76
|
+
f.name,
|
|
77
|
+
f.ast_type,
|
|
78
|
+
f.language,
|
|
79
|
+
f.file_path,
|
|
80
|
+
f.text,
|
|
81
|
+
n.start_line,
|
|
82
|
+
n.start_col,
|
|
83
|
+
n.end_line,
|
|
84
|
+
n.end_col,
|
|
85
|
+
-bm25(nodes_fts, 0, 1.0, 0.5, 0.3, 0.2, 1.5) as score
|
|
86
|
+
FROM nodes_fts f
|
|
87
|
+
JOIN nodes n ON n.id = f.id
|
|
88
|
+
WHERE nodes_fts MATCH ?
|
|
89
|
+
ORDER BY score DESC
|
|
90
|
+
LIMIT ?
|
|
91
|
+
`).all(i,t)}catch{return []}}deleteNodesByFile(e){let t=dt(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let a of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(a.rowid);}catch(r){Ws.warn("FTS delete failed for file",{filePath:t,error:String(r)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=dt(e);return this.db.prepare(`
|
|
92
|
+
DELETE FROM edges
|
|
93
|
+
WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
94
|
+
OR target IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
95
|
+
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(dt(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
|
|
96
|
+
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
97
|
+
VALUES (?, ?, datetime('now'))
|
|
98
|
+
`).run(dt(e),t);}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(dt(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),i=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),r=this.db.prepare("SELECT value FROM meta WHERE key = 'lastSync'").get();return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:i?.c??0,dbPath:this.dbPath,workspaceDir:"",lastSync:r?.value??null}}setLastSync(){this.db.prepare(`
|
|
99
|
+
INSERT OR REPLACE INTO meta (key, value)
|
|
100
|
+
VALUES ('lastSync', datetime('now'))
|
|
101
|
+
`).run();}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache"),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let i=this.db.prepare(`
|
|
102
|
+
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
103
|
+
`).get(e);return i?new Float32Array(i.embedding.buffer,i.embedding.byteOffset,i.embedding.length/4):null}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.db.prepare(`
|
|
104
|
+
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
105
|
+
VALUES (?, ?)
|
|
106
|
+
`).run(e,t);}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;let t=this.db.prepare(`
|
|
107
|
+
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
108
|
+
VALUES (?, ?, ?)
|
|
109
|
+
`);this.db.transaction(r=>{for(let a of r)try{t.run(a.nodeId,a.embeddingText,a.embedding);}catch(o){Ws.warn("Failed to store embedding for node",{nodeId:a.nodeId,error:String(o)});}})(e);}initialize(){if(this.closed)throw new ut("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){Ws.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}};var kn=Ve.create({service:"codebase-parser"}),sh={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"}};function ih(){return typeof import.meta<"u"&&import.meta.url?Jt.dirname(fileURLToPath(import.meta.url)):typeof oe<"u"?oe:process.cwd()}function rh(s,e){let t=ih(),i=t;for(let r=0;r<10;r++){let a=Jt.join(i,"node_modules",s,e);if(Filesystem.stat(a)!==void 0)return a;let o=Jt.dirname(i);if(o===i)break;i=o;}return Jt.join(t,"node_modules",s,e)}var Ft=class{constructor(){u(this,"parsers",new Map);u(this,"initialized",false);u(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,i=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof i!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof i}`);let r=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],a=await Promise.allSettled(r.map(async o=>{try{let h=sh[o];if(!h)return kn.warn("No WASM config for language",{lang:o}),null;let l=rh(h.package,h.wasmFile),c=await i.load(l),p=new t;return p.setLanguage(c),{lang:o,parser:p,language:c}}catch(h){return kn.warn("Failed to load parser",{lang:o,error:String(h)}),null}}));for(let o of a)if(o.status==="fulfilled"&&o.value){let{lang:h,parser:l,language:c}=o.value;this.parsers.set(h,{parser:l,language:c});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=Jt.extname(e).toLowerCase();return Vi[t]??null}parse(e,t){if(!this.initialized)throw new At("Parser not initialized","");let i=this.parsers.get(t);if(!i)throw new At(`No parser available for language: ${t}`,"");try{return i.parser.parse(e)}catch(r){throw new At("Failed to parse code","",r instanceof Error?r:new Error(String(r)))}}parseFile(e,t){let i=this.detectLanguage(e);if(!i)throw new Us(Jt.extname(e),e);return this.parse(t,i)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let i of t)e[i]=this.parsers.has(i);return e}dispose(){this.parsers.clear(),this.initialized=false;}},Rt=null;async function Dn(){return Rt||(Rt=new Ft,await Rt.initialize()),Rt}function Wn(){Rt&&(Rt.dispose(),Rt=null);}var nh={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},ah=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),Pt=class{extractNodes(e,t,i,r){let a=[],o=t.split(`
|
|
110
|
+
`);return this.walkTree(e.rootNode,a,i,r,o),a}walkTree(e,t,i,r,a,o){if(ah.has(e.type)){let h=this.extractNode(e,i,r,a,o);h&&(t.push(h),o=h.name?this.generateNodeId(h):o);}for(let h=0;h<e.childCount;h++){let l=e.children[h];l&&this.walkTree(l,t,i,r,a,o);}}extractNode(e,t,i,r,a){let o=this.getNodeName(e);if(!o)return null;let h=e.startPosition,l=e.endPosition,c=this.getNodeText(e,r);return {name:o,ast_type:this.normalizeAstType(e.type),language:t,file_path:i,start_line:h.row,start_col:h.column,end_line:l.row,end_col:l.column,text:c,parent_id:a}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let i of t){let r=e.childForFieldName?.(i);if(r?.text)return r.text}for(let i of e.children)if(i.type==="identifier"||i.type==="type_identifier"||i.type==="property_identifier"||i.type==="field_identifier"||i.type==="name")return i.text;return null}findNameInGrandchildren(e,t,i){for(let r of e.children)if(t.includes(r.type)){let a=this.findNameInChildren(r,i);if(a)return a}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"){let i=t.text;return (i.startsWith('"')||i.startsWith("'"))&&(i=i.slice(1,-1)),i}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,i]of Object.entries(nh))if(i.includes(e))return t;return e}getNodeText(e,t){let i=e.startPosition.row,r=e.endPosition.row;return i===r?t[i]?.trim()??"":t.slice(i,r+1).join(`
|
|
111
|
+
`)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function zn(){return new Pt}var Ot=class{extractEdges(e,t,i,r){let a=[],o=new Map;for(let h of t){let l=this.generateNodeId(h);o.set(l,h);}return this.extractContainsEdges(t,a),this.extractCallEdges(e.rootNode,t,a,i,r,o),this.extractInheritanceEdges(e.rootNode,t,a,i,r,o),this.extractImportEdges(e.rootNode,t,a,i,r),a}extractContainsEdges(e,t){for(let i of e)i.parent_id&&t.push({source:i.parent_id,target:this.generateNodeId(i),relation:"CONTAINS"});}extractCallEdges(e,t,i,r,a,o){let h=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,l=>{if(h.includes(l.type)){let c=this.findEnclosingFunction(l,t),p=this.extractCalleeName(l);if(c&&p){let d=`${r}:${a}:function_declaration:${p}`;i.push({source:c.id,target:d,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,i,r,a,o){let h=["class_declaration","class_definition","class_specifier"];this.walkTree(e,l=>{if(h.includes(l.type)){let c=this.findNameInChildren(l);if(!c)return;let p=`${r}:${a}:class_declaration:${c}`,d=this.findDescendantByType(l,["class_heritage","extends_clause","superclass"]);if(d){let w=this.findChildByType(d,["extends_clause","superclass"])??d,x=this.extractIdentifier(w);if(x&&x!==c){let b=`${r}:${a}:class_declaration:${x}`;i.push({source:p,target:b,relation:"INHERITS_FROM"});}}let f=this.findDescendantByType(l,["implements_clause","interface_list","implements"]);if(f){let S=this.extractIdentifiers(f);for(let w of S){let x=`${r}:${a}:interface_declaration:${w}`;i.push({source:p,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,i,r,a){let o=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,h=>{if(o.includes(h.type)){let l=this.extractImportPath(h);if(l){let c=`${r}:${a}:module:file`;i.push({source:c,target:l,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let i of e.children)this.walkTree(i,t);}findEnclosingFunction(e,t){let i=e;for(;i;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(i.type)){let a=this.findNameInChildren(i);if(a){let o=t.find(d=>d.name===a);if(o)return {id:this.generateNodeId(o),name:a};i.startPosition;let l=t[0],c=l?.language??"ts",p=l?.file_path??"";return {id:`${c}:${p}:function_declaration:${a}`,name:a}}}i=i.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let i=t.childForFieldName?.("property");if(i)return i.text;let r=t.children[t.children.length-1];if(r)return r.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let i of e.children)if(t.includes(i.type))return i;return null}findDescendantByType(e,t){for(let i of e.children){if(t.includes(i.type))return i;if(!["class_declaration","class_definition"].includes(i.type)){let a=this.findDescendantByType(i,t);if(a)return a}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let i of e.children)(i.type==="identifier"||i.type==="type_identifier")&&t.push(i.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let i=t.text;return (i.startsWith('"')||i.startsWith("'"))&&(i=i.slice(1,-1)),i}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function jn(){return new Ot}var Lt=class{constructor(e,t,i){u(this,"db");u(this,"parserManager");u(this,"nodeExtractor");u(this,"edgeExtractor");u(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new Pt,this.edgeExtractor=new Ot,this.config=i;}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),i=this.db.getCachedEmbedding?.(t);if(i)return new Float32Array(i.buffer,i.byteOffset,i.length/4);let a=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(a){let o=new Float32Array(a);return this.db.cacheEmbedding?.(t,o),o}return null}catch{return null}}async indexFile(e,t){let i=Date.now(),r=[],a=0,o=0;try{let h=this.parserManager.detectLanguage(e);if(!h)throw new Bs("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let l=await this.readFile(e),c=this.computeHash(l);if(this.config.incremental&&this.db.getFileHash(e)===c)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-i};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let p=this.parserManager.parse(l,h),d=this.nodeExtractor.extractNodes(p,l,h,e);a=d.length;let f=this.edgeExtractor.extractEdges(p,d,h,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(d);let S=this.getValidEdgeCount(f,d);this.storeEdges(f,d),o=S,this.config.embedding&&d.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(d)),this.db.setFileHash(e,c),p.delete();}catch(h){let l=h instanceof Error?h.message:String(h);r.push({filePath:e,error:l});}return {success:r.length===0,filesProcessed:1,nodesCreated:a,edgesCreated:o,errors:r,duration:Date.now()-i}}async indexDirectory(e,t){let i=Date.now(),r=e??this.config.workspaceDir,a=[],o=0,h=0,l=0;try{let c=await this.scanFiles(r),p=c.length;for(let d=0;d<c.length;d+=this.config.batchSize){let f=c.slice(d,d+this.config.batchSize);for(let S of f){let w=await this.indexFile(S.filePath,t);o++,h+=w.nodesCreated,l+=w.edgesCreated,!w.success&&w.errors.length>0&&a.push(...w.errors);}}}catch(c){let p=c instanceof Error?c.message:String(c);a.push({filePath:r,error:p});}return this.db.setLastSync(),{success:a.length===0,filesProcessed:o,nodesCreated:h,edgesCreated:l,errors:a,duration:Date.now()-i}}async sync(e){let t=Date.now(),i=[],r=0,a=0,o=0,h=0,l=0,c=0;try{let p=await this.scanFiles(this.config.workspaceDir),d=new Set(p.map(w=>w.filePath)),f=this.db.getAllFileHashes(),S=new Set(f.map(w=>w.file_path));for(let w of f)d.has(w.file_path)||(this.db.deleteNodesByFile(w.file_path),this.db.deleteEdgesByFile(w.file_path),this.db.deleteFileHash(w.file_path),o++);for(let w of p){let x=this.db.getFileHash(w.filePath);if(x)if(x!==w.contentHash){let b=await this.indexFile(w.filePath,e);b.success?(a++,l+=b.nodesCreated,c+=b.edgesCreated):i.push(...b.errors);}else h++;else {let b=await this.indexFile(w.filePath,e);b.success?(r++,l+=b.nodesCreated,c+=b.edgesCreated):i.push(...b.errors);}}}catch(p){let d=p instanceof Error?p.message:String(p);i.push({filePath:this.config.workspaceDir,error:d});}return this.db.setLastSync(),{success:i.length===0,filesAdded:r,filesUpdated:a,filesDeleted:o,filesSkipped:h,nodesCreated:l,edgesCreated:c,errors:i,duration:Date.now()-t}}async scanFiles(e){let t=[],r=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(p=>`**/*${p}`),a=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],o=this.config.ignorePatterns.map(p=>p.includes("/")||p.includes("*")?p:`**/${p}/**`),h=[...a,...o],l=e.replace(/\\/g,"/"),c=await ch(r,{cwd:l,absolute:true,ignore:h,onlyFiles:true});for(let p of c){let d=Filesystem.toUnixPath(Jt.normalize(p)),f=this.parserManager.detectLanguage(d);if(f)try{let S=await this.readFile(d),w=this.computeHash(S);t.push({filePath:d,language:f,contentHash:w,content:S});}catch{}}return t}async readFile(e){try{return await qi.readFile(e,"utf-8")}catch(t){throw new js("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(i=>({id:this.nodeExtractor.generateNodeId(i),name:i.name,ast_type:i.ast_type,language:i.language,file_path:i.file_path,start_line:i.start_line,start_col:i.start_col,end_line:i.end_line,end_col:i.end_col,text:i.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let i=new Set(t.map(a=>this.nodeExtractor.generateNodeId(a))),r=e.filter(a=>i.has(a.source)&&i.has(a.target)).map((a,o)=>({id:`${a.source}:${a.relation}:${a.target}:${o}`,source:a.source,target:a.target,relation:a.relation,created_at:new Date().toISOString()}));r.length>0&&this.db.insertEdges(r);}getValidEdgeCount(e,t){let i=new Set(t.map(r=>this.nodeExtractor.generateNodeId(r)));return e.filter(r=>i.has(r.source)&&i.has(r.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,i=this.chunkArray(e,t),r=[];for(let a of i){let o=a.map(h=>this.generateNodeEmbeddingText(h));try{let h=await this.config.embedding.doEmbed({values:o});for(let l=0;l<a.length;l++){let c=a[l];if(!c)continue;let p=h.embeddings[l];if(p){let d=new Float32Array(p),f=this.computeHash(this.generateNodeEmbeddingText(c));this.db.cacheEmbedding?.(f,d),r.push({nodeId:this.nodeExtractor.generateNodeId(c),embeddingText:o[l]||"",embedding:d});}}}catch{for(let l of a){if(!l)continue;let c=this.generateNodeEmbeddingText(l),p=await this.embedText(c);p&&r.push({nodeId:this.nodeExtractor.generateNodeId(l),embeddingText:c,embedding:p});}}}r.length>0&&this.db.storeNodeEmbeddings?.(r);}chunkArray(e,t){let i=[];for(let r=0;r<e.length;r+=t)i.push(e.slice(r,r+t));return i}};function $n(s,e,t){return new Lt(s,e,t)}var Bn=Filesystem.toUnixPath,It=class{constructor(e,t){u(this,"db");u(this,"embedding");this.db=e,this.embedding=t;}async search(e,t={}){let{maxResults:i=20,minScore:r=.1,language:a,filePath:o,astType:h,enableFts:l=true,includeEdges:c=true,edgesLimit:p=100,vectorWeight:d=.7,textWeight:f=.3}=t,S=[];if(this.embedding){let b=await this.vectorSearchNodes(e,i*2,r);for(let y of b)S.push({...y,source:"vector",vectorScore:y.score,hybridScore:y.score*d});}if(l&&this.db.isFtsAvailable()){let b=this.db.searchNodesFts(e,i*2);for(let y of b){if(a&&y.language!==a||o&&!y.file_path.includes(Bn(o))||h&&y.ast_type!==h)continue;let _=this.normalizeScore(y.score),N=S.find(P=>P.id===y.id);N?(N.ftsScore=_,N.hybridScore=N.vectorScore*d+_*f):S.push({id:y.id,name:y.name,astType:y.ast_type,language:y.language,filePath:y.file_path,text:y.text,snippet:y.text.slice(0,200),startLine:y.start_line,startCol:y.start_col,endLine:y.end_line,endCol:y.end_col,score:_,source:"fts",ftsScore:_,hybridScore:_*f});}}if(!l||!this.db.isFtsAvailable()||S.length===0)try{let b=this.db.queryNodes({limit:i,astType:h,language:a,filePath:o}),y=new Set(S.map(_=>_.id));for(let _ of b){if(y.has(_.id)||o&&!_.file_path.includes(Bn(o)))continue;let N=_.name.toLowerCase().includes(e.toLowerCase()),P=_.text.toLowerCase().includes(e.toLowerCase());if(N||P){let T=N?.9:.5;S.push({id:_.id,name:_.name,astType:_.ast_type,language:_.language,filePath:_.file_path,text:_.text,snippet:_.text.slice(0,200),startLine:_.start_line,startCol:_.start_col,endLine:_.end_line,endCol:_.end_col,score:T,source:"basic",hybridScore:T});}}}catch{}let x=S.filter(b=>b.hybridScore>=r).sort((b,y)=>y.hybridScore-b.hybridScore).slice(0,i).map(b=>({id:b.id,name:b.name,ast_type:b.astType,language:b.language,file_path:b.filePath,start_line:b.startLine,start_col:b.startCol,end_line:b.endLine,end_col:b.endCol,text:b.text,created_at:new Date().toISOString()}));if(c&&x.length>0){let b=x.map(N=>N.id),y=this.db.queryEdges({sourceOrTarget:b}),_=new Map;for(let N of y)N.source!==N.target&&(_.has(N.source)||_.set(N.source,[]),_.get(N.source).push(N));return x.map(N=>{let P=_.get(N.id)||[];return {...N,edges:P.slice(0,p)}})}return x.map(b=>({...b,edges:[]}))}async vectorSearchNodes(e,t,i,r){if(!this.embedding)return [];let a=await this.embedText(e);if(!a)return [];let o=new Float32Array(a),h;if(r&&r.length>0){let f=r.map(()=>"?").join(",");h=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${f})`,r);}else h=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);let l=[];for(let f of h){let S=new Float32Array(f.embedding.buffer,f.embedding.byteOffset,f.embedding.length/4),w=this.cosineSimilarity(o,S);w>=i&&l.push({nodeId:f.node_id,score:w});}l.sort((f,S)=>S.score-f.score);let c=l.slice(0,t).map(f=>f.nodeId),p=this.db.queryNodes({ids:c}),d=new Map(l.slice(0,t).map(f=>[f.nodeId,f.score]));return p.map(f=>({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text??"",snippet:(f.text??"").slice(0,200),startLine:f.start_line??0,startCol:f.start_col??0,endLine:f.end_line??0,endCol:f.end_col??0,score:d.get(f.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let i=this.db.queryEdges({source:e.id,target:e.id,limit:t});return {...e,edges:i}}async embedText(e){if(!this.embedding)return null;try{let i=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return i?new Float32Array(i):null}catch{return null}}cosineSimilarity(e,t){let i=0,r=0,a=0;for(let o=0;o<e.length;o++){let h=e[o],l=t[o];i+=h*l,r+=h*h,a+=l*l;}return r===0||a===0?0:i/(Math.sqrt(r)*Math.sqrt(a))}structuralSearch(e,t){let i=[],r=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let a of r){let o=this.calculateNameSimilarity(e,a.name);i.push({id:a.id,name:a.name,astType:a.ast_type,language:a.language,filePath:a.file_path,text:a.text??"",snippet:(a.text??"").slice(0,200),startLine:a.start_line??0,startCol:a.start_col??0,endLine:a.end_line??0,endCol:a.end_col??0,score:o,source:"structural"});}return i}calculateNameSimilarity(e,t){let i=e.toLowerCase(),r=t.toLowerCase();if(i===r)return 1;if(r.startsWith(i))return .9;if(r.includes(i))return .7;let a=new Set(i.split("")),o=new Set(r.split("")),h=0;for(let l of a)o.has(l)&&h++;return h/a.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new es("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new es("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),i=[];for(let r of t){let a=this.db.getNodeById(r.source),o=this.db.getNodeById(r.target);a&&o&&i.push({edge:r,sourceNode:a,targetNode:o});}return i}queryNeighbors(e,t={}){let{relationTypes:i,direction:r="both",limit:a=100}=t,o=[],h=[],l=new Set;if(r==="outgoing"||r==="both"){let c=this.db.queryEdges({source:e,relation:i?.[0],limit:a});for(let p of c){if(i&&!i.includes(p.relation))continue;o.push(p);let d=this.db.getNodeById(p.target);d&&!l.has(d.id)&&(h.push(d),l.add(d.id));}}if(r==="incoming"||r==="both"){let c=this.db.queryEdges({target:e,relation:i?.[0],limit:a});for(let p of c){if(i&&!i.includes(p.relation))continue;o.push(p);let d=this.db.getNodeById(p.source);d&&!l.has(d.id)&&(h.push(d),l.add(d.id));}}return {nodes:h.slice(0,a),edges:o.slice(0,a)}}queryCallGraph(e,t=2){let i=new Map,r=new Set,a=(o,h)=>{if(h>t||r.has(o))return;r.add(o);let l=[],c=[],p=this.db.queryEdges({target:o,relation:"CALLS"});for(let f of p)l.push(f.source),a(f.source,h+1);let d=this.db.queryEdges({source:o,relation:"CALLS"});for(let f of d)c.push(f.target),a(f.target,h+1);i.set(o,{callers:l,callees:c});};return a(e,0),i}queryInheritance(e){let t=[],i=[],r=new Set,a=new Set,o=l=>{if(r.has(l))return;r.add(l);let c=this.db.queryEdges({source:l,relation:"INHERITS_FROM"}),p=this.db.queryEdges({source:l,relation:"IMPLEMENTS"});for(let d of [...c,...p]){let f=this.db.getNodeById(d.target);f&&(t.push(f),o(d.target));}},h=l=>{if(a.has(l))return;a.add(l);let c=this.db.queryEdges({target:l,relation:"INHERITS_FROM"}),p=this.db.queryEdges({target:l,relation:"IMPLEMENTS"});for(let d of [...c,...p]){let f=this.db.getNodeById(d.source);f&&(i.push(f),h(d.source));}};return o(e),h(e),{ancestors:t,descendants:i}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function Un(s){return new It(s)}var yh=Ve.create({service:"codebase"}),bh={database:{path:getDefaultDatabasePath(xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true}},pi=class{constructor(e={}){u(this,"config");u(this,"db");u(this,"parserManager");u(this,"indexer");u(this,"queryInterface");u(this,"initialized",false);this.config={...bh,...e};let t=e.workspaceDir??process.cwd(),i=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:i,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let r=this.resolveDbPath();this.db=new Kt(r),this.parserManager=new Ft;let a={workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm};this.indexer=new Lt(this.db,this.parserManager,a),this.queryInterface=new It(this.db,this.config.embeddingLlm);}async initialize(){this.initialized||(this.db.initialize(),await Ve.init({logDir:this.config.logDir||Jt.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),await this.parserManager.initialize(),this.initialized=true);}validateConfig(){if(!this.config.workspaceDir)throw new Zt("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new Zt("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return Jt.isAbsolute(e)?e:Jt.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){return await this.ensureInitialized(),this.indexer.sync(e)}async search(e,t){return await this.ensureInitialized(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){return {...this.db.getStatus(),workspaceDir:this.config.workspaceDir}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(){this.db.clearAll();}async close(){this.initialized&&(this.db.close(),this.parserManager.dispose(),this.initialized=false,yh.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function wh(s){let e=new pi(s);return await e.initialize(),e}export{pi as CodeBase,Zt as ConfigError,ut as DatabaseError,Kt as DatabaseManager,Ot as EdgeExtractor,Vi as FILE_EXTENSION_MAP,js as FileSystemError,Bs as IndexError,Lt as Indexer,Pt as NodeExtractor,At as ParserError,Ft as ParserManager,es as QueryError,It as QueryInterface,$s as SchemaError,Us as UnsupportedLanguageError,wh as createCodebase,jn as createEdgeExtractor,$n as createIndexer,zn as createNodeExtractor,Un as createQueryInterface,Dn as getParserManager,Wn as resetParserManager};
|
package/package.json
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@easbot/codebase",
|
|
3
|
+
"version": "0.1.11",
|
|
4
|
+
"description": "Code Knowledge Graph SDK for EASBot - Property Graph model for code indexing and querying with Tree-sitter parsing, FTS hybrid search, and incremental updates",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.cjs",
|
|
7
|
+
"module": "dist/index.mjs",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.mjs",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"dev": "tsup --watch --env.NODE_ENV development",
|
|
19
|
+
"build": "tsup --env.NODE_ENV production",
|
|
20
|
+
"test": "vitest",
|
|
21
|
+
"test:run": "vitest run",
|
|
22
|
+
"lint": "biome check .",
|
|
23
|
+
"lint:fix": "biome check --write .",
|
|
24
|
+
"lint:report": "biome check --reporter=summary .",
|
|
25
|
+
"format": "biome format .",
|
|
26
|
+
"format:fix": "biome format --write .",
|
|
27
|
+
"type-check": "tsc --noEmit",
|
|
28
|
+
"clean": "npx rimraf dist node_modules",
|
|
29
|
+
"prepare": "echo norun",
|
|
30
|
+
"prepublishOnly": "pnpm build",
|
|
31
|
+
"publish:npm": "bash scripts/publish.sh",
|
|
32
|
+
"publish:npm:win": "powershell -ExecutionPolicy Bypass -File scripts/publish.ps1"
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"easbot",
|
|
36
|
+
"code-knowledge-graph",
|
|
37
|
+
"code-indexing",
|
|
38
|
+
"tree-sitter",
|
|
39
|
+
"ast",
|
|
40
|
+
"property-graph",
|
|
41
|
+
"code-search",
|
|
42
|
+
"fts",
|
|
43
|
+
"sqlite",
|
|
44
|
+
"code-analysis",
|
|
45
|
+
"semantic-search",
|
|
46
|
+
"incremental-indexing"
|
|
47
|
+
],
|
|
48
|
+
"author": "houjallen",
|
|
49
|
+
"license": "MIT",
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "https://github.com/houjallen/easbot.git",
|
|
53
|
+
"directory": "packages/codebase"
|
|
54
|
+
},
|
|
55
|
+
"homepage": "https://github.com/houjallen/easbot/tree/main/packages/codebase#readme",
|
|
56
|
+
"bugs": {
|
|
57
|
+
"url": "https://github.com/houjallen/easbot/issues"
|
|
58
|
+
},
|
|
59
|
+
"files": [
|
|
60
|
+
"dist",
|
|
61
|
+
"README.md",
|
|
62
|
+
"README.en.md",
|
|
63
|
+
"LICENSE"
|
|
64
|
+
],
|
|
65
|
+
"dependencies": {
|
|
66
|
+
"@ai-sdk/provider": "^3.0.8",
|
|
67
|
+
"@ai-sdk/provider-utils": "^4.0.21",
|
|
68
|
+
"@easbot/local-model-sdk": "workspace:*",
|
|
69
|
+
"@easbot/types": "workspace:*",
|
|
70
|
+
"@easbot/utils": "workspace:*",
|
|
71
|
+
"@tree-sitter-grammars/tree-sitter-zig": "^1.1.2",
|
|
72
|
+
"@tursodatabase/database": "0.5.1",
|
|
73
|
+
"ai": "^6.0.136",
|
|
74
|
+
"better-sqlite3": "^12.9.0",
|
|
75
|
+
"commander": "^14.0.3",
|
|
76
|
+
"fast-glob": "^3.3.3",
|
|
77
|
+
"tree-sitter-c": "^0.24.1",
|
|
78
|
+
"tree-sitter-c-sharp": "^0.23.1",
|
|
79
|
+
"tree-sitter-cpp": "^0.23.4",
|
|
80
|
+
"tree-sitter-go": "^0.25.0",
|
|
81
|
+
"tree-sitter-java": "^0.23.5",
|
|
82
|
+
"tree-sitter-javascript": "^0.25.0",
|
|
83
|
+
"tree-sitter-php": "^0.24.2",
|
|
84
|
+
"tree-sitter-python": "^0.25.0",
|
|
85
|
+
"tree-sitter-ruby": "^0.23.1",
|
|
86
|
+
"tree-sitter-rust": "^0.24.0",
|
|
87
|
+
"tree-sitter-scala": "^0.24.0",
|
|
88
|
+
"tree-sitter-typescript": "^0.23.2",
|
|
89
|
+
"web-tree-sitter": "^0.26.7",
|
|
90
|
+
"xdg-basedir": "^5.1.0",
|
|
91
|
+
"zod": "^4.3.6"
|
|
92
|
+
},
|
|
93
|
+
"devDependencies": {
|
|
94
|
+
"@biomejs/biome": "^2.4.8",
|
|
95
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
96
|
+
"@types/node": "^22.17.0",
|
|
97
|
+
"@vitest/coverage-v8": "^4.1.1",
|
|
98
|
+
"dotenv": "^17.3.1",
|
|
99
|
+
"tsup": "^8.5.1",
|
|
100
|
+
"typescript": "^6.0.2",
|
|
101
|
+
"vitest": "^4.1.1"
|
|
102
|
+
},
|
|
103
|
+
"engines": {
|
|
104
|
+
"node": ">=22.17.0"
|
|
105
|
+
},
|
|
106
|
+
"publishConfig": {
|
|
107
|
+
"access": "public"
|
|
108
|
+
}
|
|
109
|
+
}
|