@easbot/gateway 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.
@@ -0,0 +1,9 @@
1
+ import {a}from'./chunk-SJNPXLNN.mjs';import {g,e,h,f as f$1,i,j}from'./chunk-TY6W6O7O.mjs';import ys,{win32,posix}from'path';import qs,{realpath,readlink,readdir,lstat}from'fs/promises';import*as pa from'fs';import {realpathSync,createWriteStream,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,existsSync}from'fs';import f from'zod';import {fileURLToPath}from'url';import {EventEmitter}from'events';import fn from'stream';import {StringDecoder}from'string_decoder';import {initLog}from'@easbot/utils';a();a();var Kr=(e,t,i)=>{let s=e instanceof RegExp?tr(e,i):e,n=t instanceof RegExp?tr(t,i):t,o=s!==null&&n!=null&&Xn(s,n,i);return o&&{start:o[0],end:o[1],pre:i.slice(0,o[0]),body:i.slice(o[0]+s.length,o[1]),post:i.slice(o[1]+n.length)}},tr=(e,t)=>{let i=t.match(e);return i?i[0]:null},Xn=(e,t,i)=>{let s,n,o,a,h,l=i.indexOf(e),u=i.indexOf(t,l+1),g=l;if(l>=0&&u>0){if(e===t)return [l,u];for(s=[],o=i.length;g>=0&&!h;){if(g===l)s.push(g),l=i.indexOf(e,g+1);else if(s.length===1){let d=s.pop();d!==void 0&&(h=[d,u]);}else n=s.pop(),n!==void 0&&n<o&&(o=n,a=u),u=i.indexOf(t,g+1);g=l<u&&l>=0?l:u;}s.length&&a!==void 0&&(h=[o,a]);}return h},Qr="\0SLASH"+Math.random()+"\0",qr="\0OPEN"+Math.random()+"\0",Bs="\0CLOSE"+Math.random()+"\0",Jr="\0COMMA"+Math.random()+"\0",Vr="\0PERIOD"+Math.random()+"\0",to=new RegExp(Qr,"g"),eo=new RegExp(qr,"g"),io=new RegExp(Bs,"g"),so=new RegExp(Jr,"g"),ro=new RegExp(Vr,"g"),no=/\\\\/g,oo=/\\{/g,ao=/\\}/g,ho=/\\,/g,lo=/\\./g,co=1e5;function Cs(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function fo(e){return e.replace(no,Qr).replace(oo,qr).replace(ao,Bs).replace(ho,Jr).replace(lo,Vr)}function uo(e){return e.replace(to,"\\").replace(eo,"{").replace(io,"}").replace(so,",").replace(ro,".")}function Yr(e){if(!e)return [""];let t=[],i=Kr("{","}",e);if(!i)return e.split(",");let{pre:s,body:n,post:o}=i,a=s.split(",");a[a.length-1]+="{"+n+"}";let h=Yr(o);return o.length&&(a[a.length-1]+=h.shift(),a.push.apply(a,h)),t.push.apply(t,a),t}function po(e,t={}){if(!e)return [];let{max:i=co}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Ze(fo(e),i,true).map(uo)}function go(e){return "{"+e+"}"}function mo(e){return /^-?0\d/.test(e)}function yo(e,t){return e<=t}function wo(e,t){return e>=t}function Ze(e,t,i){let s=[],n=Kr("{","}",e);if(!n)return [e];let o=n.pre,a=n.post.length?Ze(n.post,t,false):[""];if(/\$$/.test(n.pre))for(let h=0;h<a.length&&h<t;h++){let l=o+"{"+n.body+"}"+a[h];s.push(l);}else {let h=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),u=h||l,g=n.body.indexOf(",")>=0;if(!u&&!g)return n.post.match(/,(?!,).*\}/)?(e=n.pre+"{"+n.body+Bs+n.post,Ze(e,t,true)):[e];let d;if(u)d=n.body.split(/\.\./);else if(d=Yr(n.body),d.length===1&&d[0]!==void 0&&(d=Ze(d[0],t,false).map(go),d.length===1))return a.map(S=>n.pre+d[0]+S);let w;if(u&&d[0]!==void 0&&d[1]!==void 0){let S=Cs(d[0]),x=Cs(d[1]),C=Math.max(d[0].length,d[1].length),E=d.length===3&&d[2]!==void 0?Math.abs(Cs(d[2])):1,v=yo;x<S&&(E*=-1,v=wo);let T=d.some(mo);w=[];for(let F=S;v(F,x);F+=E){let P;if(l)P=String.fromCharCode(F),P==="\\"&&(P="");else if(P=String(F),T){let A=C-P.length;if(A>0){let L=new Array(A+1).join("0");F<0?P="-"+L+P.slice(1):P=L+P;}}w.push(P);}}else {w=[];for(let S=0;S<d.length;S++)w.push.apply(w,Ze(d[S],t,false));}for(let S=0;S<w.length;S++)for(let x=0;x<a.length&&s.length<t;x++){let C=o+w[S]+a[x];(!i||u||C)&&s.push(C);}}return s}var Ji=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},bo={"[: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]},Ke=e=>e.replace(/[[\]\\-]/g,"\\$&"),Co=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),er=e=>e.join(""),So=(e,t)=>{let i=t;if(e.charAt(i)!=="[")throw new Error("not in a brace expression");let s=[],n=[],o=i+1,a=false,h=false,l=false,u=false,g=i,d="";t:for(;o<e.length;){let x=e.charAt(o);if((x==="!"||x==="^")&&o===i+1){u=true,o++;continue}if(x==="]"&&a&&!l){g=o+1;break}if(a=true,x==="\\"&&!l){l=true,o++;continue}if(x==="["&&!l){for(let[C,[E,v,T]]of Object.entries(bo))if(e.startsWith(C,o)){if(d)return ["$.",false,e.length-i,true];o+=C.length,T?n.push(E):s.push(E),h=h||v;continue t}}if(l=false,d){x>d?s.push(Ke(d)+"-"+Ke(x)):x===d&&s.push(Ke(x)),d="",o++;continue}if(e.startsWith("-]",o+1)){s.push(Ke(x+"-")),o+=2;continue}if(e.startsWith("-",o+1)){d=x,o+=2;continue}s.push(Ke(x)),o++;}if(g<o)return ["",false,0,false];if(!s.length&&!n.length)return ["$.",false,e.length-i,true];if(n.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!u){let x=s[0].length===2?s[0].slice(-1):s[0];return [Co(x),false,g-i,false]}let w="["+(u?"^":"")+er(s)+"]",S="["+(u?"":"^")+er(n)+"]";return [s.length&&n.length?"("+w+"|"+S+")":s.length?w:S,h,g-i,true]},Pe=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=true}={})=>i?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),vo=new Set(["!","?","+","*","@"]),ir=e=>vo.has(e),xo="(?!(?:^|/)\\.\\.?(?:$|/))",Ni="(?!\\.)",Eo=new Set(["[","."]),Ao=new Set(["..","."]),ko=new Set("().*{}+?[]^$\\!"),To=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Us="[^/]",sr=Us+"*?",rr=Us+"+?",B,V,Ut,G,I,re,ye,ne,Wt,we,ni,Te,Xr,fe,X,zi,Rs,tn,Zr=(X=class{constructor(t,i,s={}){g(this,Te);e(this,"type");g(this,B);g(this,V);g(this,Ut,false);g(this,G,[]);g(this,I);g(this,re);g(this,ye);g(this,ne,false);g(this,Wt);g(this,we);g(this,ni,false);this.type=t,t&&h(this,V,true),h(this,I,i),h(this,B,f$1(this,I)?f$1(f$1(this,I),B):this),h(this,Wt,f$1(this,B)===this?s:f$1(f$1(this,B),Wt)),h(this,ye,f$1(this,B)===this?[]:f$1(f$1(this,B),ye)),t==="!"&&!f$1(f$1(this,B),ne)&&f$1(this,ye).push(this),h(this,re,f$1(this,I)?f$1(f$1(this,I),G).length:0);}get hasMagic(){if(f$1(this,V)!==void 0)return f$1(this,V);for(let t of f$1(this,G))if(typeof t!="string"&&(t.type||t.hasMagic))return h(this,V,true);return f$1(this,V)}toString(){return f$1(this,we)!==void 0?f$1(this,we):this.type?h(this,we,this.type+"("+f$1(this,G).map(t=>String(t)).join("|")+")"):h(this,we,f$1(this,G).map(t=>String(t)).join(""))}push(...t){for(let i of t)if(i!==""){if(typeof i!="string"&&!(i instanceof X&&f$1(i,I)===this))throw new Error("invalid part: "+i);f$1(this,G).push(i);}}toJSON(){let t=this.type===null?f$1(this,G).slice().map(i=>typeof i=="string"?i:i.toJSON()):[this.type,...f$1(this,G).map(i=>i.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===f$1(this,B)||f$1(f$1(this,B),ne)&&f$1(this,I)?.type==="!")&&t.push({}),t}isStart(){if(f$1(this,B)===this)return true;if(!f$1(this,I)?.isStart())return false;if(f$1(this,re)===0)return true;let t=f$1(this,I);for(let i=0;i<f$1(this,re);i++){let s=f$1(t,G)[i];if(!(s instanceof X&&s.type==="!"))return false}return true}isEnd(){if(f$1(this,B)===this||f$1(this,I)?.type==="!")return true;if(!f$1(this,I)?.isEnd())return false;if(!this.type)return f$1(this,I)?.isEnd();let t=f$1(this,I)?f$1(f$1(this,I),G).length:0;return f$1(this,re)===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this));}clone(t){let i=new X(this.type,t);for(let s of f$1(this,G))i.copyIn(s);return i}static fromGlob(t,i$1={}){var n;let s=new X(null,void 0,i$1);return i(n=X,fe,zi).call(n,t,s,0,i$1),s}toMMPattern(){if(this!==f$1(this,B))return f$1(this,B).toMMPattern();let t=this.toString(),[i,s,n,o]=this.toRegExpSource();if(!(n||f$1(this,V)||f$1(this,Wt).nocase&&!f$1(this,Wt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let a=(f$1(this,Wt).nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${i}$`,a),{_src:i,_glob:t})}get options(){return f$1(this,Wt)}toRegExpSource(t){let i$1=t??!!f$1(this,Wt).dot;if(f$1(this,B)===this&&i(this,Te,Xr).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!f$1(this,G).some(w=>typeof w!="string"),u=f$1(this,G).map(w=>{var v;let[S,x,C,E]=typeof w=="string"?i(v=X,fe,tn).call(v,w,f$1(this,V),l):w.toRegExpSource(t);return h(this,V,f$1(this,V)||C),h(this,Ut,f$1(this,Ut)||E),S}).join(""),g="";if(this.isStart()&&typeof f$1(this,G)[0]=="string"&&!(f$1(this,G).length===1&&Ao.has(f$1(this,G)[0]))){let w=Eo,S=i$1&&w.has(u.charAt(0))||u.startsWith("\\.")&&w.has(u.charAt(2))||u.startsWith("\\.\\.")&&w.has(u.charAt(4)),x=!i$1&&!t&&w.has(u.charAt(0));g=S?xo:x?Ni:"";}let d="";return this.isEnd()&&f$1(f$1(this,B),ne)&&f$1(this,I)?.type==="!"&&(d="(?:$|\\/)"),[g+u+d,Pe(u),h(this,V,!!f$1(this,V)),f$1(this,Ut)]}let s=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",o=i(this,Te,Rs).call(this,i$1);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let l=this.toString();return h(this,G,[l]),this.type=null,h(this,V,void 0),[l,Pe(this.toString()),false,false]}let a=!s||t||i$1||!Ni?"":i(this,Te,Rs).call(this,true);a===o&&(a=""),a&&(o=`(?:${o})(?:${a})*?`);let h$1="";if(this.type==="!"&&f$1(this,ni))h$1=(this.isStart()&&!i$1?Ni:"")+rr;else {let l=this.type==="!"?"))"+(this.isStart()&&!i$1&&!t?Ni:"")+sr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;h$1=n+o+l;}return [h$1,Pe(o),h(this,V,!!f$1(this,V)),f$1(this,Ut)]}},B=new WeakMap,V=new WeakMap,Ut=new WeakMap,G=new WeakMap,I=new WeakMap,re=new WeakMap,ye=new WeakMap,ne=new WeakMap,Wt=new WeakMap,we=new WeakMap,ni=new WeakMap,Te=new WeakSet,Xr=function(){if(this!==f$1(this,B))throw new Error("should only call on root");if(f$1(this,ne))return this;this.toString(),h(this,ne,true);let t;for(;t=f$1(this,ye).pop();){if(t.type!=="!")continue;let i=t,s=f$1(i,I);for(;s;){for(let n=f$1(i,re)+1;!s.type&&n<f$1(s,G).length;n++)for(let o of f$1(t,G)){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(f$1(s,G)[n]);}i=s,s=f$1(i,I);}}return this},fe=new WeakSet,zi=function(t,i$1,s,n){var S,x;let o=false,a=false,h$1=-1,l=false;if(i$1.type===null){let C=s,E="";for(;C<t.length;){let v=t.charAt(C++);if(o||v==="\\"){o=!o,E+=v;continue}if(a){C===h$1+1?(v==="^"||v==="!")&&(l=true):v==="]"&&!(C===h$1+2&&l)&&(a=false),E+=v;continue}else if(v==="["){a=true,h$1=C,l=false,E+=v;continue}if(!n.noext&&ir(v)&&t.charAt(C)==="("){i$1.push(E),E="";let T=new X(v,i$1);C=i(S=X,fe,zi).call(S,t,T,C,n),i$1.push(T);continue}E+=v;}return i$1.push(E),C}let u=s+1,g=new X(null,i$1),d=[],w="";for(;u<t.length;){let C=t.charAt(u++);if(o||C==="\\"){o=!o,w+=C;continue}if(a){u===h$1+1?(C==="^"||C==="!")&&(l=true):C==="]"&&!(u===h$1+2&&l)&&(a=false),w+=C;continue}else if(C==="["){a=true,h$1=u,l=false,w+=C;continue}if(ir(C)&&t.charAt(u)==="("){g.push(w),w="";let E=new X(C,g);g.push(E),u=i(x=X,fe,zi).call(x,t,E,u,n);continue}if(C==="|"){g.push(w),w="",d.push(g),g=new X(null,i$1);continue}if(C===")")return w===""&&f$1(i$1,G).length===0&&h(i$1,ni,true),g.push(w),w="",i$1.push(...d,g),u;w+=C;}return i$1.type=null,h(i$1,V,void 0),h(i$1,G,[t.substring(s-1)]),u},Rs=function(t){return f$1(this,G).map(i=>{if(typeof i=="string")throw new Error("string type in extglob ast??");let[s,n,o,a]=i.toRegExpSource(t);return h(this,Ut,f$1(this,Ut)||a),s}).filter(i=>!(this.isStart()&&this.isEnd())||!!i).join("|")},tn=function(t,i,s=false){let n=false,o="",a=false,h=false;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(n){n=false,o+=(ko.has(u)?"\\":"")+u;continue}if(u==="*"){if(h)continue;h=true,o+=s&&/^[*]+$/.test(t)?rr:sr,i=true;continue}else h=false;if(u==="\\"){l===t.length-1?o+="\\\\":n=true;continue}if(u==="["){let[g,d,w,S]=So(t,l);if(w){o+=g,a=a||d,l+=w-1,i=i||S;continue}}if(u==="?"){o+=Us,i=true;continue}o+=To(u);}return [o,Pe(t),!!i,a]},g(X,fe),X),en=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=false}={})=>i?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),at=(e,t,i={})=>(Ji(t),!i.nocomment&&t.charAt(0)==="#"?false:new ue(t,i).match(e)),Ro=/^\*+([^+@!?\*\[\(]*)$/,Oo=e=>t=>!t.startsWith(".")&&t.endsWith(e),Fo=e=>t=>t.endsWith(e),Po=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),Lo=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),No=/^\*+\.\*+$/,Go=e=>!e.startsWith(".")&&e.includes("."),Do=e=>e!=="."&&e!==".."&&e.includes("."),Mo=/^\.\*+$/,Wo=e=>e!=="."&&e!==".."&&e.startsWith("."),_o=/^\*+$/,jo=e=>e.length!==0&&!e.startsWith("."),Io=e=>e.length!==0&&e!=="."&&e!=="..",zo=/^\?+([^+@!?\*\[\(]*)?$/,Bo=([e,t=""])=>{let i=sn([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},Uo=([e,t=""])=>{let i=rn([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},$o=([e,t=""])=>{let i=rn([e]);return t?s=>i(s)&&s.endsWith(t):i},Ho=([e,t=""])=>{let i=sn([e]);return t?s=>i(s)&&s.endsWith(t):i},sn=([e])=>{let t=e.length;return i=>i.length===t&&!i.startsWith(".")},rn=([e])=>{let t=e.length;return i=>i.length===t&&i!=="."&&i!==".."},nn=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",nr={win32:{sep:"\\"},posix:{sep:"/"}},Ko=nn==="win32"?nr.win32.sep:nr.posix.sep;at.sep=Ko;var ot=Symbol("globstar **");at.GLOBSTAR=ot;var Qo="[^/]",qo=Qo+"*?",Jo="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Vo="(?:(?!(?:\\/|^)\\.).)*?",Yo=(e,t={})=>i=>at(i,e,t);at.filter=Yo;var wt=(e,t={})=>Object.assign({},e,t),Zo=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return at;let t=at;return Object.assign((i,s,n={})=>t(i,s,wt(e,n)),{Minimatch:class extends t.Minimatch{constructor(i,s={}){super(i,wt(e,s));}static defaults(i){return t.defaults(wt(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,s,n={}){super(i,s,wt(e,n));}static fromGlob(i,s={}){return t.AST.fromGlob(i,wt(e,s))}},unescape:(i,s={})=>t.unescape(i,wt(e,s)),escape:(i,s={})=>t.escape(i,wt(e,s)),filter:(i,s={})=>t.filter(i,wt(e,s)),defaults:i=>t.defaults(wt(e,i)),makeRe:(i,s={})=>t.makeRe(i,wt(e,s)),braceExpand:(i,s={})=>t.braceExpand(i,wt(e,s)),match:(i,s,n={})=>t.match(i,s,wt(e,n)),sep:t.sep,GLOBSTAR:ot})};at.defaults=Zo;var on=(e,t={})=>(Ji(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:po(e,{max:t.braceExpandMax}));at.braceExpand=on;var Xo=(e,t={})=>new ue(e,t).makeRe();at.makeRe=Xo;var ta=(e,t,i={})=>{let s=new ue(t,i);return e=e.filter(n=>s.match(n)),s.options.nonull&&!e.length&&e.push(t),e};at.match=ta;var or=/[?*]|[+@!]\(.*?\)|\[|\]/,ea=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ue=class{constructor(e$1,t={}){e(this,"options");e(this,"set");e(this,"pattern");e(this,"windowsPathsNoEscape");e(this,"nonegate");e(this,"negate");e(this,"comment");e(this,"empty");e(this,"preserveMultipleSlashes");e(this,"partial");e(this,"globSet");e(this,"globParts");e(this,"nocase");e(this,"isWindows");e(this,"platform");e(this,"windowsNoMagicRoot");e(this,"regexp");Ji(e$1),t=t||{},this.options=t,this.pattern=e$1,this.platform=t.platform||nn,this.isWindows=this.platform==="win32";let i="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[i]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...n)=>console.error(...n)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(n=>this.slashSplit(n));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let s=this.globParts.map((n,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let h=n[0]===""&&n[1]===""&&(n[2]==="?"||!or.test(n[2]))&&!or.test(n[3]),l=/^[a-z]:/i.test(n[0]);if(h)return [...n.slice(0,4),...n.slice(4).map(u=>this.parse(u))];if(l)return [n[0],...n.slice(1).map(u=>this.parse(u))]}return n.map(h=>this.parse(h))});if(this.debug(this.pattern,s),this.set=s.filter(n=>n.indexOf(false)===-1),this.isWindows)for(let n=0;n<this.set.length;n++){let o=this.set[n];o[0]===""&&o[1]===""&&this.globParts[n][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let i=0;i<e.length;i++)for(let s=0;s<e[i].length;s++)e[i][s]==="**"&&(e[i][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let i=-1;for(;(i=t.indexOf("**",i+1))!==-1;){let s=i;for(;t[s+1]==="**";)s++;s!==i&&t.splice(i,s-i);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((i,s)=>{let n=i[i.length-1];return s==="**"&&n==="**"?i:s===".."&&n&&n!==".."&&n!=="."&&n!=="**"?(i.pop(),i):(i.push(s),i)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let n=e[s];s===1&&n===""&&e[0]===""||(n==="."||n==="")&&(t=true,e.splice(s,1),s--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let i=0;for(;(i=e.indexOf("..",i+1))!==-1;){let s=e[i-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,e.splice(i-1,2),i-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let i of e){let s=-1;for(;(s=i.indexOf("**",s+1))!==-1;){let o=s;for(;i[o+1]==="**";)o++;o>s&&i.splice(s+1,o-s);let a=i[s+1],h=i[s+2],l=i[s+3];if(a!==".."||!h||h==="."||h===".."||!l||l==="."||l==="..")continue;t=true,i.splice(s,1);let u=i.slice(0);u[s]="**",e.push(u),s--;}if(!this.preserveMultipleSlashes){for(let o=1;o<i.length-1;o++){let a=i[o];o===1&&a===""&&i[0]===""||(a==="."||a==="")&&(t=true,i.splice(o,1),o--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let n=0;for(;(n=i.indexOf("..",n+1))!==-1;){let o=i[n-1];if(o&&o!=="."&&o!==".."&&o!=="**"){t=true;let a=n===1&&i[n+1]==="**"?["."]:[];i.splice(n-1,2,...a),i.length===0&&i.push(""),n-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let i=t+1;i<e.length;i++){let s=this.partsMatch(e[t],e[i],!this.preserveMultipleSlashes);if(s){e[t]=[],e[i]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,i=false){let s=0,n=0,o=[],a="";for(;s<e.length&&n<t.length;)if(e[s]===t[n])o.push(a==="b"?t[n]:e[s]),s++,n++;else if(i&&e[s]==="**"&&t[n]===e[s+1])o.push(e[s]),s++;else if(i&&t[n]==="**"&&e[s]===t[n+1])o.push(t[n]),n++;else if(e[s]==="*"&&t[n]&&(this.options.dot||!t[n].startsWith("."))&&t[n]!=="**"){if(a==="b")return false;a="a",o.push(e[s]),s++,n++;}else if(t[n]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(a==="a")return false;a="b",o.push(t[n]),s++,n++;}else return false;return e.length===t.length&&o}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,i=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,i++;i&&(this.pattern=e.slice(i)),this.negate=t;}matchOne(e,t,i=false){let s=this.options;if(this.isWindows){let x=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),C=!x&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),E=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),v=!E&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),T=C?3:x?0:void 0,F=v?3:E?0:void 0;if(typeof T=="number"&&typeof F=="number"){let[P,A]=[e[T],t[F]];P.toLowerCase()===A.toLowerCase()&&(t[F]=P,F>T?t=t.slice(F):T>F&&(e=e.slice(T)));}}let{optimizationLevel:n=1}=this.options;n>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var o=0,a=0,h=e.length,l=t.length;o<h&&a<l;o++,a++){this.debug("matchOne loop");var u=t[a],g=e[o];if(this.debug(t,u,g),u===false)return false;if(u===ot){this.debug("GLOBSTAR",[t,u,g]);var d=o,w=a+1;if(w===l){for(this.debug("** at the end");o<h;o++)if(e[o]==="."||e[o]===".."||!s.dot&&e[o].charAt(0)===".")return false;return true}for(;d<h;){var S=e[d];if(this.debug(`
2
+ globstar while`,e,d,t,w,S),this.matchOne(e.slice(d),t.slice(w),i))return this.debug("globstar found match!",d,h,S),true;if(S==="."||S===".."||!s.dot&&S.charAt(0)==="."){this.debug("dot detected!",e,d,t,w);break}this.debug("globstar swallow a segment, and continue"),d++;}return !!(i&&(this.debug(`
3
+ >>> no match, partial?`,e,d,t,w),d===h))}let x;if(typeof u=="string"?(x=g===u,this.debug("string match",u,g,x)):(x=u.test(g),this.debug("pattern match",u,g,x)),!x)return false}if(o===h&&a===l)return true;if(o===h)return i;if(a===l)return o===h-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return on(this.pattern,this.options)}parse(e){Ji(e);let t=this.options;if(e==="**")return ot;if(e==="")return "";let i,s=null;(i=e.match(_o))?s=t.dot?Io:jo:(i=e.match(Ro))?s=(t.nocase?t.dot?Lo:Po:t.dot?Fo:Oo)(i[1]):(i=e.match(zo))?s=(t.nocase?t.dot?Uo:Bo:t.dot?$o:Ho)(i):(i=e.match(No))?s=t.dot?Do:Go:(i=e.match(Mo))&&(s=Wo);let n=Zr.fromGlob(e,this.options).toMMPattern();return s&&typeof n=="object"&&Reflect.defineProperty(n,"test",{value:s}),n}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,i=t.noglobstar?qo:t.dot?Jo:Vo,s=new Set(t.nocase?["i"]:[]),n=e.map(h=>{let l=h.map(g=>{if(g instanceof RegExp)for(let d of g.flags.split(""))s.add(d);return typeof g=="string"?ea(g):g===ot?ot:g._src});l.forEach((g,d)=>{let w=l[d+1],S=l[d-1];g!==ot||S===ot||(S===void 0?w!==void 0&&w!==ot?l[d+1]="(?:\\/|"+i+"\\/)?"+w:l[d]=i:w===void 0?l[d-1]=S+"(?:\\/|\\/"+i+")?":w!==ot&&(l[d-1]=S+"(?:\\/|\\/"+i+"\\/)"+w,l[d+1]=ot));});let u=l.filter(g=>g!==ot);if(this.partial&&u.length>=1){let g=[];for(let d=1;d<=u.length;d++)g.push(u.slice(0,d).join("/"));return "(?:"+g.join("|")+")"}return u.join("/")}).join("|"),[o,a]=e.length>1?["(?:",")"]:["",""];n="^"+o+n+a+"$",this.partial&&(n="^(?:\\/|"+o+n.slice(1,-1)+a+")$"),this.negate&&(n="^(?!"+n+").+$");try{this.regexp=new RegExp(n,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let i=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let n=this.set;this.debug(this.pattern,"set",n);let o=s[s.length-1];if(!o)for(let a=s.length-2;!o&&a>=0;a--)o=s[a];for(let a=0;a<n.length;a++){let h=n[a],l=s;if(i.matchBase&&h.length===1&&(l=[o]),this.matchOne(l,h,t))return i.flipNegate?true:!this.negate}return i.flipNegate?false:this.negate}static defaults(e){return at.defaults(e).Minimatch}};at.AST=Zr;at.Minimatch=ue;at.escape=en;at.unescape=Pe;var sa=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,an=new Set,Os=typeof process=="object"&&process?process:{},hn=(e,t,i,s)=>{typeof Os.emitWarning=="function"?Os.emitWarning(e,t,i,s):console.error(`[${i}] ${t}: ${e}`);},Vi=globalThis.AbortController,ar=globalThis.AbortSignal;if(typeof Vi>"u"){ar=class{constructor(){e(this,"onabort");e(this,"_onabort",[]);e(this,"reason");e(this,"aborted",false);}addEventListener(i,s){this._onabort.push(s);}},Vi=class{constructor(){e(this,"signal",new ar);t();}abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=true;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i);}}};let e$1=Os.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e$1&&(e$1=false,hn("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var ra=e=>!an.has(e),te=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),ln=e=>te(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Bi:null:null,Bi=class extends Array{constructor(e){super(e),this.fill(0);}},It,Le,na=(It=class{constructor(t,i){e(this,"heap");e(this,"length");if(!f$1(It,Le))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(t),this.length=0;}static create(t){let i=ln(t);if(!i)return [];h(It,Le,true);let s=new It(t,i);return h(It,Le,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Le=new WeakMap,g(It,Le,false),It),vr,xr,Ct,ft,kt,be,Tt,Ne,Ge,Rt,U,Ot,z,D,O,st,ut,et,Y,Ft,Z,Pt,Lt,pt,dt,Nt,oe,rt,De,b,Fs,Ce,$t,oi,gt,cn,Se,Me,ai,ee,ie,Ps,Ui,$i,N,Ls,Xe,se,Ns,We,Xi=(We=class{constructor(t){g(this,b);g(this,Ct);g(this,ft);g(this,kt);g(this,be);g(this,Tt);g(this,Ne);g(this,Ge);g(this,Rt);e(this,"ttl");e(this,"ttlResolution");e(this,"ttlAutopurge");e(this,"updateAgeOnGet");e(this,"updateAgeOnHas");e(this,"allowStale");e(this,"noDisposeOnSet");e(this,"noUpdateTTL");e(this,"maxEntrySize");e(this,"sizeCalculation");e(this,"noDeleteOnFetchRejection");e(this,"noDeleteOnStaleGet");e(this,"allowStaleOnFetchAbort");e(this,"allowStaleOnFetchRejection");e(this,"ignoreFetchAbort");g(this,U);g(this,Ot);g(this,z);g(this,D);g(this,O);g(this,st);g(this,ut);g(this,et);g(this,Y);g(this,Ft);g(this,Z);g(this,Pt);g(this,Lt);g(this,pt);g(this,dt);g(this,Nt);g(this,oe);g(this,rt);g(this,De);g(this,Ce,()=>{});g(this,$t,()=>{});g(this,oi,()=>{});g(this,gt,()=>false);g(this,Se,t=>{});g(this,Me,(t,i,s)=>{});g(this,ai,(t,i,s,n)=>{if(s||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});e(this,vr,"LRUCache");let{max:i$1=0,ttl:s,ttlResolution:n=1,ttlAutopurge:o,updateAgeOnGet:a,updateAgeOnHas:h$1,allowStale:l,dispose:u,onInsert:g$1,disposeAfter:d,noDisposeOnSet:w,noUpdateTTL:S,maxSize:x=0,maxEntrySize:C=0,sizeCalculation:E,fetchMethod:v,memoMethod:T,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:P,allowStaleOnFetchRejection:A,allowStaleOnFetchAbort:L,ignoreFetchAbort:W,perf:j}=t;if(j!==void 0&&typeof j?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(h(this,Rt,j??sa),i$1!==0&&!te(i$1))throw new TypeError("max option must be a nonnegative integer");let M=i$1?ln(i$1):Array;if(!M)throw new Error("invalid max value: "+i$1);if(h(this,Ct,i$1),h(this,ft,x),this.maxEntrySize=C||f$1(this,ft),this.sizeCalculation=E,this.sizeCalculation){if(!f$1(this,ft)&&!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(T!==void 0&&typeof T!="function")throw new TypeError("memoMethod must be a function if defined");if(h(this,Ge,T),v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(h(this,Ne,v),h(this,oe,!!v),h(this,z,new Map),h(this,D,new Array(i$1).fill(void 0)),h(this,O,new Array(i$1).fill(void 0)),h(this,st,new M(i$1)),h(this,ut,new M(i$1)),h(this,et,0),h(this,Y,0),h(this,Ft,na.create(i$1)),h(this,U,0),h(this,Ot,0),typeof u=="function"&&h(this,kt,u),typeof g$1=="function"&&h(this,be,g$1),typeof d=="function"?(h(this,Tt,d),h(this,Z,[])):(h(this,Tt,void 0),h(this,Z,void 0)),h(this,Nt,!!f$1(this,kt)),h(this,De,!!f$1(this,be)),h(this,rt,!!f$1(this,Tt)),this.noDisposeOnSet=!!w,this.noUpdateTTL=!!S,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!A,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!W,this.maxEntrySize!==0){if(f$1(this,ft)!==0&&!te(f$1(this,ft)))throw new TypeError("maxSize must be a positive integer if specified");if(!te(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");i(this,b,cn).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!P,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!h$1,this.ttlResolution=te(n)||n===0?n:1,this.ttlAutopurge=!!o,this.ttl=s||0,this.ttl){if(!te(this.ttl))throw new TypeError("ttl must be a positive integer if specified");i(this,b,Fs).call(this);}if(f$1(this,Ct)===0&&this.ttl===0&&f$1(this,ft)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!f$1(this,Ct)&&!f$1(this,ft)){let K="LRU_CACHE_UNBOUNDED";ra(K)&&(an.add(K),hn("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",K,We));}}get perf(){return f$1(this,Rt)}static unsafeExposeInternals(t){return {starts:f$1(t,Lt),ttls:f$1(t,pt),autopurgeTimers:f$1(t,dt),sizes:f$1(t,Pt),keyMap:f$1(t,z),keyList:f$1(t,D),valList:f$1(t,O),next:f$1(t,st),prev:f$1(t,ut),get head(){return f$1(t,et)},get tail(){return f$1(t,Y)},free:f$1(t,Ft),isBackgroundFetch:i$1=>{var s;return i(s=t,b,N).call(s,i$1)},backgroundFetch:(i$1,s,n,o)=>{var a;return i(a=t,b,$i).call(a,i$1,s,n,o)},moveToTail:i$1=>{var s;return i(s=t,b,Xe).call(s,i$1)},indexes:i$1=>{var s;return i(s=t,b,ee).call(s,i$1)},rindexes:i$1=>{var s;return i(s=t,b,ie).call(s,i$1)},isStale:i=>{var s;return f$1(s=t,gt).call(s,i)}}}get max(){return f$1(this,Ct)}get maxSize(){return f$1(this,ft)}get calculatedSize(){return f$1(this,Ot)}get size(){return f$1(this,U)}get fetchMethod(){return f$1(this,Ne)}get memoMethod(){return f$1(this,Ge)}get dispose(){return f$1(this,kt)}get onInsert(){return f$1(this,be)}get disposeAfter(){return f$1(this,Tt)}getRemainingTTL(t){return f$1(this,z).has(t)?1/0:0}*entries(){for(let t of i(this,b,ee).call(this))f$1(this,O)[t]!==void 0&&f$1(this,D)[t]!==void 0&&!i(this,b,N).call(this,f$1(this,O)[t])&&(yield [f$1(this,D)[t],f$1(this,O)[t]]);}*rentries(){for(let t of i(this,b,ie).call(this))f$1(this,O)[t]!==void 0&&f$1(this,D)[t]!==void 0&&!i(this,b,N).call(this,f$1(this,O)[t])&&(yield [f$1(this,D)[t],f$1(this,O)[t]]);}*keys(){for(let t of i(this,b,ee).call(this)){let i$1=f$1(this,D)[t];i$1!==void 0&&!i(this,b,N).call(this,f$1(this,O)[t])&&(yield i$1);}}*rkeys(){for(let t of i(this,b,ie).call(this)){let i$1=f$1(this,D)[t];i$1!==void 0&&!i(this,b,N).call(this,f$1(this,O)[t])&&(yield i$1);}}*values(){for(let t of i(this,b,ee).call(this))f$1(this,O)[t]!==void 0&&!i(this,b,N).call(this,f$1(this,O)[t])&&(yield f$1(this,O)[t]);}*rvalues(){for(let t of i(this,b,ie).call(this))f$1(this,O)[t]!==void 0&&!i(this,b,N).call(this,f$1(this,O)[t])&&(yield f$1(this,O)[t]);}[(xr=Symbol.iterator,vr=Symbol.toStringTag,xr)](){return this.entries()}find(t,i$1={}){for(let s of i(this,b,ee).call(this)){let n=f$1(this,O)[s],o=i(this,b,N).call(this,n)?n.__staleWhileFetching:n;if(o!==void 0&&t(o,f$1(this,D)[s],this))return this.get(f$1(this,D)[s],i$1)}}forEach(t,i$1=this){for(let s of i(this,b,ee).call(this)){let n=f$1(this,O)[s],o=i(this,b,N).call(this,n)?n.__staleWhileFetching:n;o!==void 0&&t.call(i$1,o,f$1(this,D)[s],this);}}rforEach(t,i$1=this){for(let s of i(this,b,ie).call(this)){let n=f$1(this,O)[s],o=i(this,b,N).call(this,n)?n.__staleWhileFetching:n;o!==void 0&&t.call(i$1,o,f$1(this,D)[s],this);}}purgeStale(){let t=false;for(let i$1 of i(this,b,ie).call(this,{allowStale:true}))f$1(this,gt).call(this,i$1)&&(i(this,b,se).call(this,f$1(this,D)[i$1],"expire"),t=true);return t}info(t){let i$1=f$1(this,z).get(t);if(i$1===void 0)return;let s=f$1(this,O)[i$1],n=i(this,b,N).call(this,s)?s.__staleWhileFetching:s;if(n===void 0)return;let o={value:n};if(f$1(this,pt)&&f$1(this,Lt)){let a=f$1(this,pt)[i$1],h=f$1(this,Lt)[i$1];if(a&&h){let l=a-(f$1(this,Rt).now()-h);o.ttl=l,o.start=Date.now();}}return f$1(this,Pt)&&(o.size=f$1(this,Pt)[i$1]),o}dump(){let t=[];for(let i$1 of i(this,b,ee).call(this,{allowStale:true})){let s=f$1(this,D)[i$1],n=f$1(this,O)[i$1],o=i(this,b,N).call(this,n)?n.__staleWhileFetching:n;if(o===void 0||s===void 0)continue;let a={value:o};if(f$1(this,pt)&&f$1(this,Lt)){a.ttl=f$1(this,pt)[i$1];let h=f$1(this,Rt).now()-f$1(this,Lt)[i$1];a.start=Math.floor(Date.now()-h);}f$1(this,Pt)&&(a.size=f$1(this,Pt)[i$1]),t.unshift([s,a]);}return t}load(t){this.clear();for(let[i,s]of t){if(s.start){let n=Date.now()-s.start;s.start=f$1(this,Rt).now()-n;}this.set(i,s.value,s);}}set(t,i$1,s={}){var w,S,x,C;if(i$1===void 0)return this.delete(t),this;let{ttl:n=this.ttl,start:o,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:h$1=this.sizeCalculation,status:l}=s,{noUpdateTTL:u=this.noUpdateTTL}=s,g=f$1(this,ai).call(this,t,i$1,s.size||0,h$1);if(this.maxEntrySize&&g>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),i(this,b,se).call(this,t,"set"),this;let d=f$1(this,U)===0?void 0:f$1(this,z).get(t);if(d===void 0)d=f$1(this,U)===0?f$1(this,Y):f$1(this,Ft).length!==0?f$1(this,Ft).pop():f$1(this,U)===f$1(this,Ct)?i(this,b,Ui).call(this,false):f$1(this,U),f$1(this,D)[d]=t,f$1(this,O)[d]=i$1,f$1(this,z).set(t,d),f$1(this,st)[f$1(this,Y)]=d,f$1(this,ut)[d]=f$1(this,Y),h(this,Y,d),j(this,U)._++,f$1(this,Me).call(this,d,g,l),l&&(l.set="add"),u=false,f$1(this,De)&&((w=f$1(this,be))==null||w.call(this,i$1,t,"add"));else {i(this,b,Xe).call(this,d);let E=f$1(this,O)[d];if(i$1!==E){if(f$1(this,oe)&&i(this,b,N).call(this,E)){E.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:v}=E;v!==void 0&&!a&&(f$1(this,Nt)&&((S=f$1(this,kt))==null||S.call(this,v,t,"set")),f$1(this,rt)&&f$1(this,Z)?.push([v,t,"set"]));}else a||(f$1(this,Nt)&&((x=f$1(this,kt))==null||x.call(this,E,t,"set")),f$1(this,rt)&&f$1(this,Z)?.push([E,t,"set"]));if(f$1(this,Se).call(this,d),f$1(this,Me).call(this,d,g,l),f$1(this,O)[d]=i$1,l){l.set="replace";let v=E&&i(this,b,N).call(this,E)?E.__staleWhileFetching:E;v!==void 0&&(l.oldValue=v);}}else l&&(l.set="update");f$1(this,De)&&this.onInsert?.(i$1,t,i$1===E?"update":"replace");}if(n!==0&&!f$1(this,pt)&&i(this,b,Fs).call(this),f$1(this,pt)&&(u||f$1(this,oi).call(this,d,n,o),l&&f$1(this,$t).call(this,l,d)),!a&&f$1(this,rt)&&f$1(this,Z)){let E=f$1(this,Z),v;for(;v=E?.shift();)(C=f$1(this,Tt))==null||C.call(this,...v);}return this}pop(){var t;try{for(;f$1(this,U);){let i$1=f$1(this,O)[f$1(this,et)];if(i(this,b,Ui).call(this,!0),i(this,b,N).call(this,i$1)){if(i$1.__staleWhileFetching)return i$1.__staleWhileFetching}else if(i$1!==void 0)return i$1}}finally{if(f$1(this,rt)&&f$1(this,Z)){let i=f$1(this,Z),s;for(;s=i?.shift();)(t=f$1(this,Tt))==null||t.call(this,...s);}}}has(t,i$1={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:n}=i$1,o=f$1(this,z).get(t);if(o!==void 0){let a=f$1(this,O)[o];if(i(this,b,N).call(this,a)&&a.__staleWhileFetching===void 0)return false;if(f$1(this,gt).call(this,o))n&&(n.has="stale",f$1(this,$t).call(this,n,o));else return s&&f$1(this,Ce).call(this,o),n&&(n.has="hit",f$1(this,$t).call(this,n,o)),true}else n&&(n.has="miss");return false}peek(t,i$1={}){let{allowStale:s=this.allowStale}=i$1,n=f$1(this,z).get(t);if(n===void 0||!s&&f$1(this,gt).call(this,n))return;let o=f$1(this,O)[n];return i(this,b,N).call(this,o)?o.__staleWhileFetching:o}async fetch(t,i$1={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:g=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:w=this.allowStaleOnFetchRejection,ignoreFetchAbort:S=this.ignoreFetchAbort,allowStaleOnFetchAbort:x=this.allowStaleOnFetchAbort,context:C,forceRefresh:E=false,status:v,signal:T}=i$1;if(!f$1(this,oe))return v&&(v.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:v});let F={allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:a,noDisposeOnSet:h,size:l,sizeCalculation:u,noUpdateTTL:g,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:x,ignoreFetchAbort:S,status:v,signal:T},P=f$1(this,z).get(t);if(P===void 0){v&&(v.fetch="miss");let A=i(this,b,$i).call(this,t,P,F,C);return A.__returned=A}else {let A=f$1(this,O)[P];if(i(this,b,N).call(this,A)){let M=s&&A.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",M&&(v.returnedStale=true)),M?A.__staleWhileFetching:A.__returned=A}let L=f$1(this,gt).call(this,P);if(!E&&!L)return v&&(v.fetch="hit"),i(this,b,Xe).call(this,P),n&&f$1(this,Ce).call(this,P),v&&f$1(this,$t).call(this,v,P),A;let W=i(this,b,$i).call(this,t,P,F,C),j=W.__staleWhileFetching!==void 0&&s;return v&&(v.fetch=L?"stale":"refresh",j&&L&&(v.returnedStale=true)),j?W.__staleWhileFetching:W.__returned=W}}async forceFetch(t,i={}){let s=await this.fetch(t,i);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,i={}){let s=f$1(this,Ge);if(!s)throw new Error("no memoMethod provided to constructor");let{context:n,forceRefresh:o,...a}=i,h=this.get(t,a);if(!o&&h!==void 0)return h;let l=s(t,h,{options:a,context:n});return this.set(t,l,a),l}get(t,i$1={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:a}=i$1,h=f$1(this,z).get(t);if(h!==void 0){let l=f$1(this,O)[h],u=i(this,b,N).call(this,l);return a&&f$1(this,$t).call(this,a,h),f$1(this,gt).call(this,h)?(a&&(a.get="stale"),u?(a&&s&&l.__staleWhileFetching!==void 0&&(a.returnedStale=true),s?l.__staleWhileFetching:void 0):(o||i(this,b,se).call(this,t,"expire"),a&&s&&(a.returnedStale=true),s?l:void 0)):(a&&(a.get="hit"),u?l.__staleWhileFetching:(i(this,b,Xe).call(this,h),n&&f$1(this,Ce).call(this,h),l))}else a&&(a.get="miss");}delete(t){return i(this,b,se).call(this,t,"delete")}clear(){return i(this,b,Ns).call(this,"delete")}},Ct=new WeakMap,ft=new WeakMap,kt=new WeakMap,be=new WeakMap,Tt=new WeakMap,Ne=new WeakMap,Ge=new WeakMap,Rt=new WeakMap,U=new WeakMap,Ot=new WeakMap,z=new WeakMap,D=new WeakMap,O=new WeakMap,st=new WeakMap,ut=new WeakMap,et=new WeakMap,Y=new WeakMap,Ft=new WeakMap,Z=new WeakMap,Pt=new WeakMap,Lt=new WeakMap,pt=new WeakMap,dt=new WeakMap,Nt=new WeakMap,oe=new WeakMap,rt=new WeakMap,De=new WeakMap,b=new WeakSet,Fs=function(){let t=new Bi(f$1(this,Ct)),i$1=new Bi(f$1(this,Ct));h(this,pt,t),h(this,Lt,i$1);let s=this.ttlAutopurge?new Array(f$1(this,Ct)):void 0;h(this,dt,s),h(this,oi,(a,h,l=f$1(this,Rt).now())=>{if(i$1[a]=h!==0?l:0,t[a]=h,s?.[a]&&(clearTimeout(s[a]),s[a]=void 0),h!==0&&s){let u=setTimeout(()=>{f$1(this,gt).call(this,a)&&i(this,b,se).call(this,f$1(this,D)[a],"expire");},h+1);u.unref&&u.unref(),s[a]=u;}}),h(this,Ce,a=>{i$1[a]=t[a]!==0?f$1(this,Rt).now():0;}),h(this,$t,(a,h)=>{if(t[h]){let l=t[h],u=i$1[h];if(!l||!u)return;a.ttl=l,a.start=u,a.now=n||o();let g=a.now-u;a.remainingTTL=l-g;}});let n=0,o=()=>{let a=f$1(this,Rt).now();if(this.ttlResolution>0){n=a;let h=setTimeout(()=>n=0,this.ttlResolution);h.unref&&h.unref();}return a};this.getRemainingTTL=a=>{let h=f$1(this,z).get(a);if(h===void 0)return 0;let l=t[h],u=i$1[h];if(!l||!u)return 1/0;let g=(n||o())-u;return l-g},h(this,gt,a=>{let h=i$1[a],l=t[a];return !!l&&!!h&&(n||o())-h>l});},Ce=new WeakMap,$t=new WeakMap,oi=new WeakMap,gt=new WeakMap,cn=function(){let t=new Bi(f$1(this,Ct));h(this,Ot,0),h(this,Pt,t),h(this,Se,i=>{h(this,Ot,f$1(this,Ot)-t[i]),t[i]=0;}),h(this,ai,(i$1,s,n,o)=>{if(i(this,b,N).call(this,s))return 0;if(!te(n))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(n=o(s,i$1),!te(n))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 n}),h(this,Me,(i$1,s,n)=>{if(t[i$1]=s,f$1(this,ft)){let o=f$1(this,ft)-t[i$1];for(;f$1(this,Ot)>o;)i(this,b,Ui).call(this,true);}h(this,Ot,f$1(this,Ot)+t[i$1]),n&&(n.entrySize=s,n.totalCalculatedSize=f$1(this,Ot));});},Se=new WeakMap,Me=new WeakMap,ai=new WeakMap,ee=function*({allowStale:t=this.allowStale}={}){if(f$1(this,U))for(let i$1=f$1(this,Y);!(!i(this,b,Ps).call(this,i$1)||((t||!f$1(this,gt).call(this,i$1))&&(yield i$1),i$1===f$1(this,et)));)i$1=f$1(this,ut)[i$1];},ie=function*({allowStale:t=this.allowStale}={}){if(f$1(this,U))for(let i$1=f$1(this,et);!(!i(this,b,Ps).call(this,i$1)||((t||!f$1(this,gt).call(this,i$1))&&(yield i$1),i$1===f$1(this,Y)));)i$1=f$1(this,st)[i$1];},Ps=function(t){return t!==void 0&&f$1(this,z).get(f$1(this,D)[t])===t},Ui=function(t){var o;let i$1=f$1(this,et),s=f$1(this,D)[i$1],n=f$1(this,O)[i$1];return f$1(this,oe)&&i(this,b,N).call(this,n)?n.__abortController.abort(new Error("evicted")):(f$1(this,Nt)||f$1(this,rt))&&(f$1(this,Nt)&&((o=f$1(this,kt))==null||o.call(this,n,s,"evict")),f$1(this,rt)&&f$1(this,Z)?.push([n,s,"evict"])),f$1(this,Se).call(this,i$1),f$1(this,dt)?.[i$1]&&(clearTimeout(f$1(this,dt)[i$1]),f$1(this,dt)[i$1]=void 0),t&&(f$1(this,D)[i$1]=void 0,f$1(this,O)[i$1]=void 0,f$1(this,Ft).push(i$1)),f$1(this,U)===1?(h(this,et,h(this,Y,0)),f$1(this,Ft).length=0):h(this,et,f$1(this,st)[i$1]),f$1(this,z).delete(s),j(this,U)._--,i$1},$i=function(t,i$1,s,n){let o=i$1===void 0?void 0:f$1(this,O)[i$1];if(i(this,b,N).call(this,o))return o;let a=new Vi,{signal:h}=s;h?.addEventListener("abort",()=>a.abort(h.reason),{signal:a.signal});let l={signal:a.signal,options:s,context:n},u=(C,E=false)=>{let{aborted:v}=a.signal,T=s.ignoreFetchAbort&&C!==void 0,F=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&C!==void 0);if(s.status&&(v&&!E?(s.status.fetchAborted=true,s.status.fetchError=a.signal.reason,T&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),v&&!T&&!E)return d(a.signal.reason,F);let P=S,A=f$1(this,O)[i$1];return (A===S||T&&E&&A===void 0)&&(C===void 0?P.__staleWhileFetching!==void 0?f$1(this,O)[i$1]=P.__staleWhileFetching:i(this,b,se).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,C,l.options))),C},g=C=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=C),d(C,false)),d=(C,E)=>{let{aborted:v}=a.signal,T=v&&s.allowStaleOnFetchAbort,F=T||s.allowStaleOnFetchRejection,P=F||s.noDeleteOnFetchRejection,A=S;if(f$1(this,O)[i$1]===S&&(!P||!E&&A.__staleWhileFetching===void 0?i(this,b,se).call(this,t,"fetch"):T||(f$1(this,O)[i$1]=A.__staleWhileFetching)),F)return s.status&&A.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),A.__staleWhileFetching;if(A.__returned===A)throw C},w=(C,E)=>{var T;let v=(T=f$1(this,Ne))==null?void 0:T.call(this,t,o,l);v&&v instanceof Promise&&v.then(F=>C(F===void 0?void 0:F),E),a.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(C(void 0),s.allowStaleOnFetchAbort&&(C=F=>u(F,true)));});};s.status&&(s.status.fetchDispatched=true);let S=new Promise(w).then(u,g),x=Object.assign(S,{__abortController:a,__staleWhileFetching:o,__returned:void 0});return i$1===void 0?(this.set(t,x,{...l.options,status:void 0}),i$1=f$1(this,z).get(t)):f$1(this,O)[i$1]=x,x},N=function(t){if(!f$1(this,oe))return false;let i=t;return !!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof Vi},Ls=function(t,i){f$1(this,ut)[i]=t,f$1(this,st)[t]=i;},Xe=function(t){t!==f$1(this,Y)&&(t===f$1(this,et)?h(this,et,f$1(this,st)[t]):i(this,b,Ls).call(this,f$1(this,ut)[t],f$1(this,st)[t]),i(this,b,Ls).call(this,f$1(this,Y),t),h(this,Y,t));},se=function(t,i$1){var n,o;let s=false;if(f$1(this,U)!==0){let a=f$1(this,z).get(t);if(a!==void 0)if(f$1(this,dt)?.[a]&&(clearTimeout(f$1(this,dt)?.[a]),f$1(this,dt)[a]=void 0),s=true,f$1(this,U)===1)i(this,b,Ns).call(this,i$1);else {f$1(this,Se).call(this,a);let h$1=f$1(this,O)[a];if(i(this,b,N).call(this,h$1)?h$1.__abortController.abort(new Error("deleted")):(f$1(this,Nt)||f$1(this,rt))&&(f$1(this,Nt)&&((n=f$1(this,kt))==null||n.call(this,h$1,t,i$1)),f$1(this,rt)&&f$1(this,Z)?.push([h$1,t,i$1])),f$1(this,z).delete(t),f$1(this,D)[a]=void 0,f$1(this,O)[a]=void 0,a===f$1(this,Y))h(this,Y,f$1(this,ut)[a]);else if(a===f$1(this,et))h(this,et,f$1(this,st)[a]);else {let l=f$1(this,ut)[a];f$1(this,st)[l]=f$1(this,st)[a];let u=f$1(this,st)[a];f$1(this,ut)[u]=f$1(this,ut)[a];}j(this,U)._--,f$1(this,Ft).push(a);}}if(f$1(this,rt)&&f$1(this,Z)?.length){let a=f$1(this,Z),h;for(;h=a?.shift();)(o=f$1(this,Tt))==null||o.call(this,...h);}return s},Ns=function(t){var i$1,s;for(let n of i(this,b,ie).call(this,{allowStale:true})){let o=f$1(this,O)[n];if(i(this,b,N).call(this,o))o.__abortController.abort(new Error("deleted"));else {let a=f$1(this,D)[n];f$1(this,Nt)&&((i$1=f$1(this,kt))==null||i$1.call(this,o,a,t)),f$1(this,rt)&&f$1(this,Z)?.push([o,a,t]);}}if(f$1(this,z).clear(),f$1(this,O).fill(void 0),f$1(this,D).fill(void 0),f$1(this,pt)&&f$1(this,Lt)){f$1(this,pt).fill(0),f$1(this,Lt).fill(0);for(let n of f$1(this,dt)??[])n!==void 0&&clearTimeout(n);f$1(this,dt)?.fill(void 0);}if(f$1(this,Pt)&&f$1(this,Pt).fill(0),h(this,et,0),h(this,Y,0),f$1(this,Ft).length=0,h(this,Ot,0),h(this,U,0),f$1(this,rt)&&f$1(this,Z)){let n=f$1(this,Z),o;for(;o=n?.shift();)(s=f$1(this,Tt))==null||s.call(this,...o);}},We),hr=typeof process=="object"&&process?process:{stdout:null,stderr:null},ba=e=>!!e&&typeof e=="object"&&(e instanceof Yi||e instanceof fn||Ca(e)||Sa(e)),Ca=e=>!!e&&typeof e=="object"&&e instanceof EventEmitter&&typeof e.pipe=="function"&&e.pipe!==fn.Writable.prototype.pipe,Sa=e=>!!e&&typeof e=="object"&&e instanceof EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",zt=Symbol("EOF"),Bt=Symbol("maybeEmitEnd"),Xt=Symbol("emittedEnd"),Gi=Symbol("emittingEnd"),Qe=Symbol("emittedError"),Di=Symbol("closed"),lr=Symbol("read"),Mi=Symbol("flush"),cr=Symbol("flushChunk"),Et=Symbol("encoding"),Oe=Symbol("decoder"),Q=Symbol("flowing"),qe=Symbol("paused"),Fe=Symbol("resume"),q=Symbol("buffer"),it=Symbol("pipes"),J=Symbol("bufferLength"),Ss=Symbol("bufferPush"),Wi=Symbol("bufferShift"),tt=Symbol("objectMode"),_=Symbol("destroyed"),vs=Symbol("error"),xs=Symbol("emitData"),fr=Symbol("emitEnd"),Es=Symbol("emitEnd2"),Dt=Symbol("async"),As=Symbol("abort"),_i=Symbol("aborted"),Je=Symbol("signal"),de=Symbol("dataListeners"),ct=Symbol("discarded"),Ve=e=>Promise.resolve().then(e),va=e=>e(),xa=e=>e==="end"||e==="finish"||e==="prefinish",Ea=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,Aa=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),un=class{constructor(e$1,t,i){e(this,"src");e(this,"dest");e(this,"opts");e(this,"ondrain");this.src=e$1,this.dest=t,this.opts=i,this.ondrain=()=>e$1[Fe](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},ka=class extends un{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,i){super(e,t,i),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors);}},Ta=e=>!!e.objectMode,Ra=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Er,Ar,kr,Tr,Rr,Or,Fr,Pr,Lr,Nr,Gr,Dr,Mr,Wr,_r,jr,Ir,zr,Br,Yi=class extends EventEmitter{constructor(...t){let i=t[0]||{};super();e(this,Br,false);e(this,zr,false);e(this,Ir,[]);e(this,jr,[]);e(this,_r);e(this,Wr);e(this,Mr);e(this,Dr);e(this,Gr,false);e(this,Nr,false);e(this,Lr,false);e(this,Pr,false);e(this,Fr,null);e(this,Or,0);e(this,Rr,false);e(this,Tr);e(this,kr,false);e(this,Ar,0);e(this,Er,false);e(this,"writable",true);e(this,"readable",true);if(i.objectMode&&typeof i.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Ta(i)?(this[tt]=true,this[Et]=null):Ra(i)?(this[Et]=i.encoding,this[tt]=false):(this[tt]=false,this[Et]=null),this[Dt]=!!i.async,this[Oe]=this[Et]?new StringDecoder(this[Et]):null,i&&i.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[q]}),i&&i.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[it]});let{signal:s}=i;s&&(this[Je]=s,s.aborted?this[As]():s.addEventListener("abort",()=>this[As]()));}get bufferLength(){return this[J]}get encoding(){return this[Et]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[tt]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Dt]}set async(t){this[Dt]=this[Dt]||!!t;}[(Br=Q,zr=qe,Ir=it,jr=q,_r=tt,Wr=Et,Mr=Dt,Dr=Oe,Gr=zt,Nr=Xt,Lr=Gi,Pr=Di,Fr=Qe,Or=J,Rr=_,Tr=Je,kr=_i,Ar=de,Er=ct,As)](){this[_i]=true,this.emit("abort",this[Je]?.reason),this.destroy(this[Je]?.reason);}get aborted(){return this[_i]}set aborted(t){}write(t,i,s){if(this[_i])return false;if(this[zt])throw new Error("write after end");if(this[_])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof i=="function"&&(s=i,i="utf8"),i||(i="utf8");let n=this[Dt]?Ve:va;if(!this[tt]&&!Buffer.isBuffer(t)){if(Aa(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Ea(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[tt]?(this[Q]&&this[J]!==0&&this[Mi](true),this[Q]?this.emit("data",t):this[Ss](t),this[J]!==0&&this.emit("readable"),s&&n(s),this[Q]):t.length?(typeof t=="string"&&!(i===this[Et]&&!this[Oe]?.lastNeed)&&(t=Buffer.from(t,i)),Buffer.isBuffer(t)&&this[Et]&&(t=this[Oe].write(t)),this[Q]&&this[J]!==0&&this[Mi](true),this[Q]?this.emit("data",t):this[Ss](t),this[J]!==0&&this.emit("readable"),s&&n(s),this[Q]):(this[J]!==0&&this.emit("readable"),s&&n(s),this[Q])}read(t){if(this[_])return null;if(this[ct]=false,this[J]===0||t===0||t&&t>this[J])return this[Bt](),null;this[tt]&&(t=null),this[q].length>1&&!this[tt]&&(this[q]=[this[Et]?this[q].join(""):Buffer.concat(this[q],this[J])]);let i=this[lr](t||null,this[q][0]);return this[Bt](),i}[lr](t,i){if(this[tt])this[Wi]();else {let s=i;t===s.length||t===null?this[Wi]():typeof s=="string"?(this[q][0]=s.slice(t),i=s.slice(0,t),this[J]-=t):(this[q][0]=s.subarray(t),i=s.subarray(0,t),this[J]-=t);}return this.emit("data",i),!this[q].length&&!this[zt]&&this.emit("drain"),i}end(t,i,s){return typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i="utf8"),t!==void 0&&this.write(t,i),s&&this.once("end",s),this[zt]=true,this.writable=false,(this[Q]||!this[qe])&&this[Bt](),this}[Fe](){this[_]||(!this[de]&&!this[it].length&&(this[ct]=true),this[qe]=false,this[Q]=true,this.emit("resume"),this[q].length?this[Mi]():this[zt]?this[Bt]():this.emit("drain"));}resume(){return this[Fe]()}pause(){this[Q]=false,this[qe]=true,this[ct]=false;}get destroyed(){return this[_]}get flowing(){return this[Q]}get paused(){return this[qe]}[Ss](t){this[tt]?this[J]+=1:this[J]+=t.length,this[q].push(t);}[Wi](){return this[tt]?this[J]-=1:this[J]-=this[q][0].length,this[q].shift()}[Mi](t=false){do;while(this[cr](this[Wi]())&&this[q].length);!t&&!this[q].length&&!this[zt]&&this.emit("drain");}[cr](t){return this.emit("data",t),this[Q]}pipe(t,i){if(this[_])return t;this[ct]=false;let s=this[Xt];return i=i||{},t===hr.stdout||t===hr.stderr?i.end=false:i.end=i.end!==false,i.proxyErrors=!!i.proxyErrors,s?i.end&&t.end():(this[it].push(i.proxyErrors?new ka(this,t,i):new un(this,t,i)),this[Dt]?Ve(()=>this[Fe]()):this[Fe]()),t}unpipe(t){let i=this[it].find(s=>s.dest===t);i&&(this[it].length===1?(this[Q]&&this[de]===0&&(this[Q]=false),this[it]=[]):this[it].splice(this[it].indexOf(i),1),i.unpipe());}addListener(t,i){return this.on(t,i)}on(t,i){let s=super.on(t,i);if(t==="data")this[ct]=false,this[de]++,!this[it].length&&!this[Q]&&this[Fe]();else if(t==="readable"&&this[J]!==0)super.emit("readable");else if(xa(t)&&this[Xt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Qe]){let n=i;this[Dt]?Ve(()=>n.call(this,this[Qe])):n.call(this,this[Qe]);}return s}removeListener(t,i){return this.off(t,i)}off(t,i){let s=super.off(t,i);return t==="data"&&(this[de]=this.listeners("data").length,this[de]===0&&!this[ct]&&!this[it].length&&(this[Q]=false)),s}removeAllListeners(t){let i=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[de]=0,!this[ct]&&!this[it].length&&(this[Q]=false)),i}get emittedEnd(){return this[Xt]}[Bt](){!this[Gi]&&!this[Xt]&&!this[_]&&this[q].length===0&&this[zt]&&(this[Gi]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Di]&&this.emit("close"),this[Gi]=false);}emit(t,...i){let s=i[0];if(t!=="error"&&t!=="close"&&t!==_&&this[_])return false;if(t==="data")return !this[tt]&&!s?false:this[Dt]?(Ve(()=>this[xs](s)),true):this[xs](s);if(t==="end")return this[fr]();if(t==="close"){if(this[Di]=true,!this[Xt]&&!this[_])return false;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[Qe]=s,super.emit(vs,s);let o=!this[Je]||this.listeners("error").length?super.emit("error",s):false;return this[Bt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Bt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let n=super.emit(t,...i);return this[Bt](),n}[xs](t){for(let s of this[it])s.dest.write(t)===false&&this.pause();let i=this[ct]?false:super.emit("data",t);return this[Bt](),i}[fr](){return this[Xt]?false:(this[Xt]=true,this.readable=false,this[Dt]?(Ve(()=>this[Es]()),true):this[Es]())}[Es](){if(this[Oe]){let i=this[Oe].end();if(i){for(let s of this[it])s.dest.write(i);this[ct]||super.emit("data",i);}}for(let i of this[it])i.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[tt]||(t.dataLength=0);let i=this.promise();return this.on("data",s=>{t.push(s),this[tt]||(t.dataLength+=s.length);}),await i,t}async concat(){if(this[tt])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Et]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,i)=>{this.on(_,()=>i(new Error("stream destroyed"))),this.on("error",s=>i(s)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[ct]=false;let t=false,i=async()=>(this.pause(),t=true,{value:void 0,done:true});return {next:()=>{if(t)return i();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[zt])return i();let n,o,a=g=>{this.off("data",h),this.off("end",l),this.off(_,u),i(),o(g);},h=g=>{this.off("error",a),this.off("end",l),this.off(_,u),this.pause(),n({value:g,done:!!this[zt]});},l=()=>{this.off("error",a),this.off("data",h),this.off(_,u),i(),n({done:true,value:void 0});},u=()=>a(new Error("stream destroyed"));return new Promise((g,d)=>{o=d,n=g,this.once(_,u),this.once("error",a),this.once("end",l),this.once("data",h);})},throw:i,return:i,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ct]=false;let t=false,i=()=>(this.pause(),this.off(vs,i),this.off(_,i),this.off("end",i),t=true,{done:true,value:void 0}),s=()=>{if(t)return i();let n=this.read();return n===null?i():{done:false,value:n}};return this.once("end",i),this.once(vs,i),this.once(_,i),{next:s,throw:i,return:i,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[_])return t?this.emit("error",t):this.emit(_),this;this[_]=true,this[ct]=true,this[q].length=0,this[J]=0;let i=this;return typeof i.close=="function"&&!this[Di]&&i.close(),t?this.emit("error",t):this.emit(_),this}static get isStream(){return ba}},Oa=realpathSync.native,ti={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Oa,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},pn=e=>!e||e===ti||e===pa?ti:{...ti,...e,promises:{...ti.promises,...e.promises||{}}},dn=/^\\\\\?\\([a-z]:)\\?$/i,Fa=e=>e.replace(/\//g,"\\").replace(dn,"$1\\"),Pa=/[\\\/]/,St=0,gn=1,mn=2,Mt=4,yn=6,wn=8,ge=10,bn=12,bt=15,Ye=~bt,ks=16,ur=32,ei=64,At=128,ji=256,Hi=512,pr=ei|At|Hi,La=1023,Ts=e=>e.isFile()?wn:e.isDirectory()?Mt:e.isSymbolicLink()?ge:e.isCharacterDevice()?mn:e.isBlockDevice()?yn:e.isSocket()?bn:e.isFIFO()?gn:St,dr=new Xi({max:2**12}),ii=e=>{let t=dr.get(e);if(t)return t;let i=e.normalize("NFKD");return dr.set(e,i),i},gr=new Xi({max:2**12}),Ii=e=>{let t=gr.get(e);if(t)return t;let i=ii(e.toLowerCase());return gr.set(e,i),i},mr=class extends Xi{constructor(){super({max:256});}},Na=class extends Xi{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Cn=Symbol("PathScurry setAsCwd"),nt,hi,li,ci,fi,ui,pi,di,gi,mi,yi,wi,bi,Ci,Si,vi,xi,Ei,Ai,ae,ve,_t,Ht,Kt,Qt,R,xe,qt,jt,k,Ds,Ki,si,Ms,Ws,ri,Qi,_s,js,qi,Sn,vn,xn,Is,_e,je,En,Ee,Ur,ht=(Ur=class{constructor(e$1,t=St,i,s,n,o,a){g(this,k);e(this,"name");e(this,"root");e(this,"roots");e(this,"parent");e(this,"nocase");e(this,"isCWD",false);g(this,nt);g(this,hi);g(this,li);g(this,ci);g(this,fi);g(this,ui);g(this,pi);g(this,di);g(this,gi);g(this,mi);g(this,yi);g(this,wi);g(this,bi);g(this,Ci);g(this,Si);g(this,vi);g(this,xi);g(this,Ei);g(this,Ai);g(this,ae);g(this,ve);g(this,_t);g(this,Ht);g(this,Kt);g(this,Qt);g(this,R);g(this,xe);g(this,qt);g(this,jt);g(this,_e,[]);g(this,je,false);g(this,Ee);this.name=e$1,h(this,ae,n?Ii(e$1):ii(e$1)),h(this,R,t&La),this.nocase=n,this.roots=s,this.root=i||this,h(this,xe,o),h(this,_t,a.fullpath),h(this,Kt,a.relative),h(this,Qt,a.relativePosix),this.parent=a.parent,this.parent?h(this,nt,f$1(this.parent,nt)):h(this,nt,pn(a.fs));}get dev(){return f$1(this,hi)}get mode(){return f$1(this,li)}get nlink(){return f$1(this,ci)}get uid(){return f$1(this,fi)}get gid(){return f$1(this,ui)}get rdev(){return f$1(this,pi)}get blksize(){return f$1(this,di)}get ino(){return f$1(this,gi)}get size(){return f$1(this,mi)}get blocks(){return f$1(this,yi)}get atimeMs(){return f$1(this,wi)}get mtimeMs(){return f$1(this,bi)}get ctimeMs(){return f$1(this,Ci)}get birthtimeMs(){return f$1(this,Si)}get atime(){return f$1(this,vi)}get mtime(){return f$1(this,xi)}get ctime(){return f$1(this,Ei)}get birthtime(){return f$1(this,Ai)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return f$1(this,ve)!==void 0?f$1(this,ve):this.parent?h(this,ve,this.parent.depth()+1):h(this,ve,0)}childrenCache(){return f$1(this,xe)}resolve(e){var s;if(!e)return this;let t=this.getRootString(e),i$1=e.substring(t.length).split(this.splitSep);return t?i(s=this.getRoot(t),k,Ds).call(s,i$1):i(this,k,Ds).call(this,i$1)}children(){let e=f$1(this,xe).get(this);if(e)return e;let t=Object.assign([],{provisional:0});return f$1(this,xe).set(this,t),h(this,R,f$1(this,R)&~ks),t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let i=this.children(),s=this.nocase?Ii(e):ii(e);for(let h of i)if(f$1(h,ae)===s)return h;let n=this.parent?this.sep:"",o=f$1(this,_t)?f$1(this,_t)+n+e:void 0,a=this.newChild(e,St,{...t,parent:this,fullpath:o});return this.canReaddir()||h(a,R,f$1(a,R)|At),i.push(a),a}relative(){if(this.isCWD)return "";if(f$1(this,Kt)!==void 0)return f$1(this,Kt);let e=this.name,t=this.parent;if(!t)return h(this,Kt,this.name);let i=t.relative();return i+(!i||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(f$1(this,Qt)!==void 0)return f$1(this,Qt);let e=this.name,t=this.parent;if(!t)return h(this,Qt,this.fullpathPosix());let i=t.relativePosix();return i+(!i||!t.parent?"":"/")+e}fullpath(){if(f$1(this,_t)!==void 0)return f$1(this,_t);let e=this.name,t=this.parent;if(!t)return h(this,_t,this.name);let i=t.fullpath()+(t.parent?this.sep:"")+e;return h(this,_t,i)}fullpathPosix(){if(f$1(this,Ht)!==void 0)return f$1(this,Ht);if(this.sep==="/")return h(this,Ht,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?h(this,Ht,`//?/${s}`):h(this,Ht,s)}let e=this.parent,t=e.fullpathPosix(),i=t+(!t||!e.parent?"":"/")+this.name;return h(this,Ht,i)}isUnknown(){return (f$1(this,R)&bt)===St}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (f$1(this,R)&bt)===wn}isDirectory(){return (f$1(this,R)&bt)===Mt}isCharacterDevice(){return (f$1(this,R)&bt)===mn}isBlockDevice(){return (f$1(this,R)&bt)===yn}isFIFO(){return (f$1(this,R)&bt)===gn}isSocket(){return (f$1(this,R)&bt)===bn}isSymbolicLink(){return (f$1(this,R)&ge)===ge}lstatCached(){return f$1(this,R)&ur?this:void 0}readlinkCached(){return f$1(this,qt)}realpathCached(){return f$1(this,jt)}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(f$1(this,qt))return true;if(!this.parent)return false;let e=f$1(this,R)&bt;return !(e!==St&&e!==ge||f$1(this,R)&ji||f$1(this,R)&At)}calledReaddir(){return !!(f$1(this,R)&ks)}isENOENT(){return !!(f$1(this,R)&At)}isNamed(e){return this.nocase?f$1(this,ae)===Ii(e):f$1(this,ae)===ii(e)}async readlink(){let e=f$1(this,qt);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await f$1(this,nt).promises.readlink(this.fullpath()),i=(await this.parent.realpath())?.resolve(t);if(i)return h(this,qt,i)}catch(t){i(this,k,js).call(this,t.code);return}}readlinkSync(){let e=f$1(this,qt);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=f$1(this,nt).readlinkSync(this.fullpath()),i=this.parent.realpathSync()?.resolve(t);if(i)return h(this,qt,i)}catch(t){i(this,k,js).call(this,t.code);return}}async lstat(){if((f$1(this,R)&At)===0)try{return i(this,k,Is).call(this,await f$1(this,nt).promises.lstat(this.fullpath())),this}catch(e){i(this,k,_s).call(this,e.code);}}lstatSync(){if((f$1(this,R)&At)===0)try{return i(this,k,Is).call(this,f$1(this,nt).lstatSync(this.fullpath())),this}catch(e){i(this,k,_s).call(this,e.code);}}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let i$1=this.children();if(this.calledReaddir()){let n=i$1.slice(0,i$1.provisional);t?e(null,n):queueMicrotask(()=>e(null,n));return}if(f$1(this,_e).push(e),f$1(this,je))return;h(this,je,true);let s=this.fullpath();f$1(this,nt).readdir(s,{withFileTypes:true},(n,o)=>{if(n)i(this,k,Qi).call(this,n.code),i$1.provisional=0;else {for(let a of o)i(this,k,qi).call(this,a,i$1);i(this,k,Ki).call(this,i$1);}i(this,k,En).call(this,i$1.slice(0,i$1.provisional));});}async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(f$1(this,Ee))await f$1(this,Ee);else {let i$1=()=>{};h(this,Ee,new Promise(s=>i$1=s));try{for(let s of await f$1(this,nt).promises.readdir(t,{withFileTypes:!0}))i(this,k,qi).call(this,s,e);i(this,k,Ki).call(this,e);}catch(s){i(this,k,Qi).call(this,s.code),e.provisional=0;}h(this,Ee,void 0),i$1();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let i$1 of f$1(this,nt).readdirSync(t,{withFileTypes:!0}))i(this,k,qi).call(this,i$1,e);i(this,k,Ki).call(this,e);}catch(i$1){i(this,k,Qi).call(this,i$1.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(f$1(this,R)&pr)return false;let e=bt&f$1(this,R);return e===St||e===Mt||e===ge}shouldWalk(e,t){return (f$1(this,R)&Mt)===Mt&&!(f$1(this,R)&pr)&&!e.has(this)&&(!t||t(this))}async realpath(){if(f$1(this,jt))return f$1(this,jt);if(!((Hi|ji|At)&f$1(this,R)))try{let e=await f$1(this,nt).promises.realpath(this.fullpath());return h(this,jt,this.resolve(e))}catch{i(this,k,Ws).call(this);}}realpathSync(){if(f$1(this,jt))return f$1(this,jt);if(!((Hi|ji|At)&f$1(this,R)))try{let e=f$1(this,nt).realpathSync(this.fullpath());return h(this,jt,this.resolve(e))}catch{i(this,k,Ws).call(this);}}[Cn](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),i=[],s=this;for(;s&&s.parent;)t.add(s),h(s,Kt,i.join(this.sep)),h(s,Qt,i.join("/")),s=s.parent,i.push("..");for(s=e;s&&s.parent&&!t.has(s);)h(s,Kt,void 0),h(s,Qt,void 0),s=s.parent;}},nt=new WeakMap,hi=new WeakMap,li=new WeakMap,ci=new WeakMap,fi=new WeakMap,ui=new WeakMap,pi=new WeakMap,di=new WeakMap,gi=new WeakMap,mi=new WeakMap,yi=new WeakMap,wi=new WeakMap,bi=new WeakMap,Ci=new WeakMap,Si=new WeakMap,vi=new WeakMap,xi=new WeakMap,Ei=new WeakMap,Ai=new WeakMap,ae=new WeakMap,ve=new WeakMap,_t=new WeakMap,Ht=new WeakMap,Kt=new WeakMap,Qt=new WeakMap,R=new WeakMap,xe=new WeakMap,qt=new WeakMap,jt=new WeakMap,k=new WeakSet,Ds=function(e){let t=this;for(let i of e)t=t.child(i);return t},Ki=function(e){var t;h(this,R,f$1(this,R)|ks);for(let i$1=e.provisional;i$1<e.length;i$1++){let s=e[i$1];s&&i(t=s,k,si).call(t);}},si=function(){f$1(this,R)&At||(h(this,R,(f$1(this,R)|At)&Ye),i(this,k,Ms).call(this));},Ms=function(){var t;let e=this.children();e.provisional=0;for(let i$1 of e)i(t=i$1,k,si).call(t);},Ws=function(){h(this,R,f$1(this,R)|Hi),i(this,k,ri).call(this);},ri=function(){if(f$1(this,R)&ei)return;let e=f$1(this,R);(e&bt)===Mt&&(e&=Ye),h(this,R,e|ei),i(this,k,Ms).call(this);},Qi=function(e=""){e==="ENOTDIR"||e==="EPERM"?i(this,k,ri).call(this):e==="ENOENT"?i(this,k,si).call(this):this.children().provisional=0;},_s=function(e=""){var t;e==="ENOTDIR"?i(t=this.parent,k,ri).call(t):e==="ENOENT"&&i(this,k,si).call(this);},js=function(e=""){var i$1;let t=f$1(this,R);t|=ji,e==="ENOENT"&&(t|=At),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Ye),h(this,R,t),e==="ENOTDIR"&&this.parent&&i(i$1=this.parent,k,ri).call(i$1);},qi=function(e,t){return i(this,k,vn).call(this,e,t)||i(this,k,Sn).call(this,e,t)},Sn=function(e,t){let i=Ts(e),s=this.newChild(e.name,i,{parent:this}),n=f$1(s,R)&bt;return n!==Mt&&n!==ge&&n!==St&&h(s,R,f$1(s,R)|ei),t.unshift(s),t.provisional++,s},vn=function(e,t){for(let i$1=t.provisional;i$1<t.length;i$1++){let s=t[i$1];if((this.nocase?Ii(e.name):ii(e.name))===f$1(s,ae))return i(this,k,xn).call(this,e,s,i$1,t)}},xn=function(e,t,i,s){let n=t.name;return h(t,R,f$1(t,R)&Ye|Ts(e)),n!==e.name&&(t.name=e.name),i!==s.provisional&&(i===s.length-1?s.pop():s.splice(i,1),s.unshift(t)),s.provisional++,t},Is=function(e){let{atime:t,atimeMs:i,birthtime:s,birthtimeMs:n,blksize:o,blocks:a,ctime:h$1,ctimeMs:l,dev:u,gid:g,ino:d,mode:w,mtime:S,mtimeMs:x,nlink:C,rdev:E,size:v,uid:T}=e;h(this,vi,t),h(this,wi,i),h(this,Ai,s),h(this,Si,n),h(this,di,o),h(this,yi,a),h(this,Ei,h$1),h(this,Ci,l),h(this,hi,u),h(this,ui,g),h(this,gi,d),h(this,li,w),h(this,xi,S),h(this,bi,x),h(this,ci,C),h(this,pi,E),h(this,mi,v),h(this,fi,T);let F=Ts(e);h(this,R,f$1(this,R)&Ye|F|ur),F!==St&&F!==Mt&&F!==ge&&h(this,R,f$1(this,R)|ei);},_e=new WeakMap,je=new WeakMap,En=function(e){h(this,je,false);let t=f$1(this,_e).slice();f$1(this,_e).length=0,t.forEach(i=>i(null,e));},Ee=new WeakMap,Ur),An=class kn extends ht{constructor(i,s=St,n,o,a,h,l){super(i,s,n,o,a,h,l);e(this,"sep","\\");e(this,"splitSep",Pa);}newChild(i,s=St,n={}){return new kn(i,s,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(i){return win32.parse(i).root}getRoot(i){if(i=Fa(i.toUpperCase()),i===this.root.name)return this.root;for(let[s,n]of Object.entries(this.roots))if(this.sameRoot(i,s))return this.roots[i]=n;return this.roots[i]=new Hs(i,this).root}sameRoot(i,s=this.root.name){return i=i.toUpperCase().replace(/\//g,"\\").replace(dn,"$1\\"),i===s}},Tn=class Rn extends ht{constructor(i,s=St,n,o,a,h,l){super(i,s,n,o,a,h,l);e(this,"splitSep","/");e(this,"sep","/");}getRootString(i){return i.startsWith("/")?"/":""}getRoot(i){return this.root}newChild(i,s=St,n={}){return new Rn(i,s,this.root,this.roots,this.nocase,this.childrenCache(),n)}},Ie,ze,ki,Ti,$r,On=($r=class{constructor(e$1=process.cwd(),t,i,{nocase:s,childrenCacheSize:n=16*1024,fs:o=ti}={}){e(this,"root");e(this,"rootPath");e(this,"roots");e(this,"cwd");g(this,Ie);g(this,ze);g(this,ki);e(this,"nocase");g(this,Ti);h(this,Ti,pn(o)),(e$1 instanceof URL||e$1.startsWith("file://"))&&(e$1=fileURLToPath(e$1));let a=t.resolve(e$1);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),h(this,Ie,new mr),h(this,ze,new mr),h(this,ki,new Na(n));let h$1=a.substring(this.rootPath.length).split(i);if(h$1.length===1&&!h$1[0]&&h$1.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(f$1(this,Ti)),this.roots[this.rootPath]=this.root;let l=this.root,u=h$1.length-1,g$1=t.sep,d=this.rootPath,w=false;for(let S of h$1){let x=u--;l=l.child(S,{relative:new Array(x).fill("..").join(g$1),relativePosix:new Array(x).fill("..").join("/"),fullpath:d+=(w?"":g$1)+S}),w=true;}this.cwd=l;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return f$1(this,ki)}resolve(...e){let t="";for(let n=e.length-1;n>=0;n--){let o=e[n];if(!(!o||o===".")&&(t=t?`${o}/${t}`:o,this.isAbsolute(o)))break}let i=f$1(this,Ie).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpath();return f$1(this,Ie).set(t,s),s}resolvePosix(...e){let t="";for(let n=e.length-1;n>=0;n--){let o=e[n];if(!(!o||o===".")&&(t=t?`${o}/${t}`:o,this.isAbsolute(o)))break}let i=f$1(this,ze).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpathPosix();return f$1(this,ze).set(t,s),s}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:i}=t;if(e.canReaddir()){let s=await e.readdir();return i?s:s.map(n=>n.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:i=true}=t;return e.canReaddir()?i?e.readdirSync():e.readdirSync().map(s=>s.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let i=await e.readlink();return t?i:i?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let i=e.readlinkSync();return t?i:i?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let i=await e.realpath();return t?i:i?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let i=e.realpathSync();return t?i:i?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:n,walkFilter:o}=t,a=[];(!n||n(e))&&a.push(i?e:e.fullpath());let h=new Set,l=(g,d)=>{h.add(g),g.readdirCB((w,S)=>{if(w)return d(w);let x=S.length;if(!x)return d();let C=()=>{--x===0&&d();};for(let E of S)(!n||n(E))&&a.push(i?E:E.fullpath()),s&&E.isSymbolicLink()?E.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(h,o)?l(v,C):C()):E.shouldWalk(h,o)?l(E,C):C();},true);},u=e;return new Promise((g,d)=>{l(u,w=>{if(w)return d(w);g(a);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:n,walkFilter:o}=t,a=[];(!n||n(e))&&a.push(i?e:e.fullpath());let h=new Set([e]);for(let l of h){let u=l.readdirSync();for(let g of u){(!n||n(g))&&a.push(i?g:g.fullpath());let d=g;if(g.isSymbolicLink()){if(!(s&&(d=g.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(h,o)&&h.add(d);}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:n,walkFilter:o}=t;(!n||n(e))&&(yield i?e:e.fullpath());let a=new Set([e]);for(let h of a){let l=h.readdirSync();for(let u of l){(!n||n(u))&&(yield i?u:u.fullpath());let g=u;if(u.isSymbolicLink()){if(!(s&&(g=u.realpathSync())))continue;g.isUnknown()&&g.lstatSync();}g.shouldWalk(a,o)&&a.add(g);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:n,walkFilter:o}=t,a=new Yi({objectMode:true});(!n||n(e))&&a.write(i?e:e.fullpath());let h=new Set,l=[e],u=0,g=()=>{let d=false;for(;!d;){let w=l.shift();if(!w){u===0&&a.end();return}u++,h.add(w);let S=(C,E,v=false)=>{if(C)return a.emit("error",C);if(s&&!v){let T=[];for(let F of E)F.isSymbolicLink()&&T.push(F.realpath().then(P=>P?.isUnknown()?P.lstat():P));if(T.length){Promise.all(T).then(()=>S(null,E,true));return}}for(let T of E)T&&(!n||n(T))&&(a.write(i?T:T.fullpath())||(d=true));u--;for(let T of E){let F=T.realpathCached()||T;F.shouldWalk(h,o)&&l.push(F);}d&&!a.flowing?a.once("drain",g):x||g();},x=true;w.readdirCB(S,true),x=false;}};return g(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:n,walkFilter:o}=t,a=new Yi({objectMode:true}),h=new Set;(!n||n(e))&&a.write(i?e:e.fullpath());let l=[e],u=0,g=()=>{let d=false;for(;!d;){let w=l.shift();if(!w){u===0&&a.end();return}u++,h.add(w);let S=w.readdirSync();for(let x of S)(!n||n(x))&&(a.write(i?x:x.fullpath())||(d=true));u--;for(let x of S){let C=x;if(x.isSymbolicLink()){if(!(s&&(C=x.realpathSync())))continue;C.isUnknown()&&C.lstatSync();}C.shouldWalk(h,o)&&l.push(C);}}d&&!a.flowing&&a.once("drain",g);};return g(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Cn](t);}},Ie=new WeakMap,ze=new WeakMap,ki=new WeakMap,Ti=new WeakMap,$r),Hs=class extends On{constructor(t=process.cwd(),i={}){let{nocase:s=true}=i;super(t,win32,"\\",{...i,nocase:s});e(this,"sep","\\");this.nocase=s;for(let n=this.cwd;n;n=n.parent)n.nocase=this.nocase;}parseRootPath(t){return win32.parse(t).root.toUpperCase()}newRoot(t){return new An(this.rootPath,Mt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},Ks=class extends On{constructor(t=process.cwd(),i={}){let{nocase:s=false}=i;super(t,posix,"/",{...i,nocase:s});e(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Tn(this.rootPath,Mt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Fn=class extends Ks{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,{...t,nocase:i});}};process.platform==="win32"?An:Tn;var Ga=process.platform==="win32"?Hs:process.platform==="darwin"?Fn:Ks,Da=e=>e.length>=1,Ma=e=>e.length>=1,Wa=Symbol.for("nodejs.util.inspect.custom"),$,lt,H,Ae,Gt,Ri,he,le,ce,Be,Ue,Pn=(Ue=class{constructor(t,i,s,n){g(this,$);g(this,lt);g(this,H);e(this,"length");g(this,Ae);g(this,Gt);g(this,Ri);g(this,he);g(this,le);g(this,ce);g(this,Be,true);if(!Da(t))throw new TypeError("empty pattern list");if(!Ma(i))throw new TypeError("empty glob list");if(i.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(h(this,$,t),h(this,lt,i),h(this,H,s),h(this,Ae,n),f$1(this,H)===0){if(this.isUNC()){let[o,a,h$1,l,...u]=f$1(this,$),[g,d,w,S,...x]=f$1(this,lt);u[0]===""&&(u.shift(),x.shift());let C=[o,a,h$1,l,""].join("/"),E=[g,d,w,S,""].join("/");h(this,$,[C,...u]),h(this,lt,[E,...x]),this.length=f$1(this,$).length;}else if(this.isDrive()||this.isAbsolute()){let[o,...a]=f$1(this,$),[h$1,...l]=f$1(this,lt);a[0]===""&&(a.shift(),l.shift());let u=o+"/",g=h$1+"/";h(this,$,[u,...a]),h(this,lt,[g,...l]),this.length=f$1(this,$).length;}}}[Wa](){return "Pattern <"+f$1(this,lt).slice(f$1(this,H)).join("/")+">"}pattern(){return f$1(this,$)[f$1(this,H)]}isString(){return typeof f$1(this,$)[f$1(this,H)]=="string"}isGlobstar(){return f$1(this,$)[f$1(this,H)]===ot}isRegExp(){return f$1(this,$)[f$1(this,H)]instanceof RegExp}globString(){return h(this,Ri,f$1(this,Ri)||(f$1(this,H)===0?this.isAbsolute()?f$1(this,lt)[0]+f$1(this,lt).slice(1).join("/"):f$1(this,lt).join("/"):f$1(this,lt).slice(f$1(this,H)).join("/")))}hasMore(){return this.length>f$1(this,H)+1}rest(){return f$1(this,Gt)!==void 0?f$1(this,Gt):this.hasMore()?(h(this,Gt,new Ue(f$1(this,$),f$1(this,lt),f$1(this,H)+1,f$1(this,Ae))),h(f$1(this,Gt),ce,f$1(this,ce)),h(f$1(this,Gt),le,f$1(this,le)),h(f$1(this,Gt),he,f$1(this,he)),f$1(this,Gt)):h(this,Gt,null)}isUNC(){let t=f$1(this,$);return f$1(this,le)!==void 0?f$1(this,le):h(this,le,f$1(this,Ae)==="win32"&&f$1(this,H)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=f$1(this,$);return f$1(this,he)!==void 0?f$1(this,he):h(this,he,f$1(this,Ae)==="win32"&&f$1(this,H)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=f$1(this,$);return f$1(this,ce)!==void 0?f$1(this,ce):h(this,ce,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=f$1(this,$)[0];return typeof t=="string"&&this.isAbsolute()&&f$1(this,H)===0?t:""}checkFollowGlobstar(){return !(f$1(this,H)===0||!this.isGlobstar()||!f$1(this,Be))}markFollowGlobstar(){return f$1(this,H)===0||!this.isGlobstar()||!f$1(this,Be)?false:(h(this,Be,false),true)}},$=new WeakMap,lt=new WeakMap,H=new WeakMap,Ae=new WeakMap,Gt=new WeakMap,Ri=new WeakMap,he=new WeakMap,le=new WeakMap,ce=new WeakMap,Be=new WeakMap,Ue),_a=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",yr=class{constructor(e$1,{nobrace:t,nocase:i,noext:s,noglobstar:n,platform:o=_a}){e(this,"relative");e(this,"relativeChildren");e(this,"absolute");e(this,"absoluteChildren");e(this,"platform");e(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:true,nobrace:t,nocase:i,noext:s,noglobstar:n,optimizationLevel:2,platform:o,nocomment:true,nonegate:true};for(let a of e$1)this.add(a);}add(e){let t=new ue(e,this.mmopts);for(let i=0;i<t.set.length;i++){let s=t.set[i],n=t.globParts[i];if(!s||!n)throw new Error("invalid pattern object");for(;s[0]==="."&&n[0]===".";)s.shift(),n.shift();let o=new Pn(s,n,0,this.platform),a=new ue(o.globString(),this.mmopts),h=n[n.length-1]==="**",l=o.isAbsolute();l?this.absolute.push(a):this.relative.push(a),h&&(l?this.absoluteChildren.push(a):this.relativeChildren.push(a));}}ignored(e){let t=e.fullpath(),i=`${t}/`,s=e.relative()||".",n=`${s}/`;for(let o of this.relative)if(o.match(s)||o.match(n))return true;for(let o of this.absolute)if(o.match(t)||o.match(i))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",i=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(i))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}},ja=class Ln{constructor(t=new Map){e(this,"store");this.store=t;}copy(){return new Ln(new Map(this.store))}hasWalked(t,i){return this.store.get(t.fullpath())?.has(i.globString())}storeWalked(t,i){let s=t.fullpath(),n=this.store.get(s);n?n.add(i.globString()):this.store.set(s,new Set([i.globString()]));}},Ia=class{constructor(){e(this,"store",new Map);}add(e,t,i){let s=(t?2:0)|(i?1:0),n=this.store.get(e);this.store.set(e,n===void 0?s:s&n);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},za=class{constructor(){e(this,"store",new Map);}add(e,t){if(!e.canReaddir())return;let i=this.store.get(e);i?i.find(s=>s.globString()===t.globString())||i.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},wr=class Nn{constructor(t,i){e(this,"hasWalkedCache");e(this,"matches",new Ia);e(this,"subwalks",new za);e(this,"patterns");e(this,"follow");e(this,"dot");e(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=i?i.copy():new ja;}processPatterns(t,i){this.patterns=i;let s=i.map(n=>[t,n]);for(let[n,o]of s){this.hasWalkedCache.storeWalked(n,o);let a=o.root(),h=o.isAbsolute()&&this.opts.absolute!==false;if(a){n=n.resolve(a==="/"&&this.opts.root!==void 0?this.opts.root:a);let d=o.rest();if(d)o=d;else {this.matches.add(n,true,false);continue}}if(n.isENOENT())continue;let l,u,g=false;for(;typeof(l=o.pattern())=="string"&&(u=o.rest());)n=n.resolve(l),o=u,g=true;if(l=o.pattern(),u=o.rest(),g){if(this.hasWalkedCache.hasWalked(n,o))continue;this.hasWalkedCache.storeWalked(n,o);}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(n.resolve(l),h,d);continue}else if(l===ot){(!n.isSymbolicLink()||this.follow||o.checkFollowGlobstar())&&this.subwalks.add(n,o);let d=u?.pattern(),w=u?.rest();if(!u||(d===""||d===".")&&!w)this.matches.add(n,h,d===""||d===".");else if(d===".."){let S=n.parent||n;w?this.hasWalkedCache.hasWalked(S,w)||this.subwalks.add(S,w):this.matches.add(S,h,true);}}else l instanceof RegExp&&this.subwalks.add(n,o);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new Nn(this.opts,this.hasWalkedCache)}filterEntries(t,i){let s=this.subwalks.get(t),n=this.child();for(let o of i)for(let a of s){let h=a.isAbsolute(),l=a.pattern(),u=a.rest();l===ot?n.testGlobstar(o,a,u,h):l instanceof RegExp?n.testRegExp(o,l,u,h):n.testString(o,l,u,h);}return n}testGlobstar(t,i,s,n){if((this.dot||!t.name.startsWith("."))&&(i.hasMore()||this.matches.add(t,n,false),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,i):t.isSymbolicLink()&&(s&&i.checkFollowGlobstar()?this.subwalks.add(t,s):i.markFollowGlobstar()&&this.subwalks.add(t,i)))),s){let o=s.pattern();if(typeof o=="string"&&o!==".."&&o!==""&&o!==".")this.testString(t,o,s.rest(),n);else if(o===".."){let a=t.parent||t;this.subwalks.add(a,s);}else o instanceof RegExp&&this.testRegExp(t,o,s.rest(),n);}}testRegExp(t,i,s,n){i.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,n,false));}testString(t,i,s,n){t.isNamed(i)&&(s?this.subwalks.add(t,s):this.matches.add(t,n,false));}},Ba=(e,t)=>typeof e=="string"?new yr([e],t):Array.isArray(e)?new yr(e,t):e,$e,Jt,ke,vt,me,zs,Hr,Gn=(Hr=class{constructor(e$1,t,i){g(this,vt);e(this,"path");e(this,"patterns");e(this,"opts");e(this,"seen",new Set);e(this,"paused",false);e(this,"aborted",false);g(this,$e,[]);g(this,Jt);g(this,ke);e(this,"signal");e(this,"maxDepth");e(this,"includeChildMatches");if(this.patterns=e$1,this.path=t,this.opts=i,h(this,ke,!i.posix&&i.platform==="win32"?"\\":"/"),this.includeChildMatches=i.includeChildMatches!==false,(i.ignore||!this.includeChildMatches)&&(h(this,Jt,Ba(i.ignore??[],i)),!this.includeChildMatches&&typeof f$1(this,Jt).add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=i.maxDepth||1/0,i.signal&&(this.signal=i.signal,this.signal.addEventListener("abort",()=>{f$1(this,$e).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=f$1(this,$e).shift());)e();}onResume(e){this.signal?.aborted||(this.paused?f$1(this,$e).push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||await e.realpath(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let n=await s.realpath();n&&(n.isUnknown()||this.opts.stat)&&await n.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!i(this,vt,me).call(this,e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||e.realpathSync(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let n=s.realpathSync();n&&(n?.isUnknown()||this.opts.stat)&&n.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(e,t){if(i(this,vt,me).call(this,e))return;if(!this.includeChildMatches&&f$1(this,Jt)?.add){let n=`${e.relativePosix()}/**`;f$1(this,Jt).add(n);}let i$1=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?f$1(this,ke):"";if(this.opts.withFileTypes)this.matchEmit(e);else if(i$1){let n=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(n+s);}else {let n=this.opts.posix?e.relativePosix():e.relative(),o=this.opts.dotRelative&&!n.startsWith(".."+f$1(this,ke))?"."+f$1(this,ke):"";this.matchEmit(n?o+n+s:"."+s);}}async match(e,t,i){let s=await this.matchCheck(e,i);s&&this.matchFinish(s,t);}matchSync(e,t,i){let s=this.matchCheckSync(e,i);s&&this.matchFinish(s,t);}walkCB(e,t,i){this.signal?.aborted&&i(),this.walkCB2(e,t,new wr(this.opts),i);}walkCB2(e,t,i$1,s){if(i(this,vt,zs).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,i$1,s));return}i$1.processPatterns(e,t);let n=1,o=()=>{--n===0&&s();};for(let[a,h,l]of i$1.matches.entries())i(this,vt,me).call(this,a)||(n++,this.match(a,h,l).then(()=>o()));for(let a of i$1.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;n++;let h=a.readdirCached();a.calledReaddir()?this.walkCB3(a,h,i$1,o):a.readdirCB((l,u)=>this.walkCB3(a,u,i$1,o),true);}o();}walkCB3(e,t,i$1,s){i$1=i$1.filterEntries(e,t);let n=1,o=()=>{--n===0&&s();};for(let[a,h,l]of i$1.matches.entries())i(this,vt,me).call(this,a)||(n++,this.match(a,h,l).then(()=>o()));for(let[a,h]of i$1.subwalks.entries())n++,this.walkCB2(a,h,i$1.child(),o);o();}walkCBSync(e,t,i){this.signal?.aborted&&i(),this.walkCB2Sync(e,t,new wr(this.opts),i);}walkCB2Sync(e,t,i$1,s){if(i(this,vt,zs).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,i$1,s));return}i$1.processPatterns(e,t);let n=1,o=()=>{--n===0&&s();};for(let[a,h,l]of i$1.matches.entries())i(this,vt,me).call(this,a)||this.matchSync(a,h,l);for(let a of i$1.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;n++;let h=a.readdirSync();this.walkCB3Sync(a,h,i$1,o);}o();}walkCB3Sync(e,t,i$1,s){i$1=i$1.filterEntries(e,t);let n=1,o=()=>{--n===0&&s();};for(let[a,h,l]of i$1.matches.entries())i(this,vt,me).call(this,a)||this.matchSync(a,h,l);for(let[a,h]of i$1.subwalks.entries())n++,this.walkCB2Sync(a,h,i$1.child(),o);o();}},$e=new WeakMap,Jt=new WeakMap,ke=new WeakMap,vt=new WeakSet,me=function(e){return this.seen.has(e)||!!f$1(this,Jt)?.ignored?.(e)},zs=function(e){return !!f$1(this,Jt)?.childrenIgnored?.(e)},Hr),br=class extends Gn{constructor(t,i,s){super(t,i,s);e(this,"matches",new Set);}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,i)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?i(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Cr=class extends Gn{constructor(t,i,s){super(t,i,s);e(this,"results");this.results=new Yi({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},Ua=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Re=class{constructor(e$1,t){e(this,"absolute");e(this,"cwd");e(this,"root");e(this,"dot");e(this,"dotRelative");e(this,"follow");e(this,"ignore");e(this,"magicalBraces");e(this,"mark");e(this,"matchBase");e(this,"maxDepth");e(this,"nobrace");e(this,"nocase");e(this,"nodir");e(this,"noext");e(this,"noglobstar");e(this,"pattern");e(this,"platform");e(this,"realpath");e(this,"scurry");e(this,"stat");e(this,"signal");e(this,"windowsPathsNoEscape");e(this,"withFileTypes");e(this,"includeChildMatches");e(this,"opts");e(this,"patterns");if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e$1=="string"&&(e$1=[e$1]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e$1=e$1.map(h=>h.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e$1=e$1.map(h=>h.includes("/")?h:`./**/${h}`);}if(this.pattern=e$1,this.platform=t.platform||Ua,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let h=t.platform==="win32"?Hs:t.platform==="darwin"?Fn:t.platform?Ks:Ga;this.scurry=new h(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},n=this.pattern.map(h=>new ue(h,s)),[o,a]=n.reduce((h,l)=>(h[0].push(...l.set),h[1].push(...l.globParts),h),[[],[]]);this.patterns=o.map((h,l)=>{let u=a[l];if(!u)throw new Error("invalid pattern object");return new Pn(h,u,0,this.platform)});}async walk(){return [...await new br(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 br(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 Cr(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 Cr(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()}},$a=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let i of e)if(new ue(i,t).hasMagic())return true;return false};function ts(e,t={}){return new Re(e,t).streamSync()}function Dn(e,t={}){return new Re(e,t).stream()}function Mn(e,t={}){return new Re(e,t).walkSync()}async function Sr(e,t={}){return new Re(e,t).walk()}function es(e,t={}){return new Re(e,t).iterateSync()}function Wn(e,t={}){return new Re(e,t).iterate()}var Ha=ts,Ka=Object.assign(Dn,{sync:ts}),Qa=es,qa=Object.assign(Wn,{sync:es}),Ja=Object.assign(Mn,{stream:ts,iterate:es}),Zi=Object.assign(Sr,{glob:Sr,globSync:Mn,sync:Ja,globStream:Dn,stream:Ka,globStreamSync:ts,streamSync:Ha,globIterate:Wn,iterate:qa,globIterateSync:es,iterateSync:Qa,Glob:Re,hasMagic:$a,escape:en,unescape:Pe});Zi.glob=Zi;var pe;(P=>{P.Level=f.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let t={DEBUG:0,INFO:1,WARN:2,ERROR:3},i="INFO";function s(A){return t[A]>=t[i]}function n(){return i}P.getLevel=n;let o=new Map;P.Default=F({service:"default"});let h="";function l(){return h}P.file=l;let u,g,d=false,w=()=>{},S=false;async function x(A){if(d)return;if(A.print){d=true;return}A.level&&(i=A.level);let L=A.logDir||ys.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");await initLog(A),A.logFile?h=ys.join(L,A.logFile??"gateway.log"):h=ys.join(L,"gateway.log");try{await qs.mkdir(L,{recursive:!0}),u=await qs.open(h,"a"),g=createWriteStream("",{fd:u.fd,autoClose:!1}),w=W=>{if(!(S||!g||g.destroyed))try{if(!g.writable)return;g.write(W,j=>{j&&!S&&(S=!0,setTimeout(()=>{S=!1;},1e3));});}catch(j){S||(S=!0,process.stderr.write(`[LOG ERROR] Write failed: ${j}
4
+ `),setTimeout(()=>{S=!1;},1e3));}},d=!0;}catch(W){process.stderr.write(`[LOG ERROR] Failed to init log file: ${W}
5
+ `),w=j=>{try{process.stderr.write(j);}catch{}},d=true;}}P.init=x;async function C(){d&&(g&&!g.destroyed&&(await new Promise((A,L)=>{g.end(W=>{W?L(W):A();});}).catch(A=>{process.stderr.write(`[LOG ERROR] Failed to close log stream: ${A}
6
+ `);}),g=void 0),u&&(await u.close().catch(A=>{process.stderr.write(`[LOG ERROR] Failed to close log file: ${A}
7
+ `);}),u=void 0),w=A=>{try{process.stderr.write(A);}catch{}},d=false);}P.close=C;function v(A,L=0){let W=A.message;return A.cause instanceof Error&&L<10?W+" Caused by: "+v(A.cause,L+1):W}let T=Date.now();function F(A){A=A||{};let L=A.service;if(L&&typeof L=="string"){let M=o.get(L);if(M)return M}function W(M,K){let ws=Object.entries({...A,...K}).filter(([Xs,Zt])=>Zt!=null).map(([Xs,Zt])=>{let bs=`${Xs}=`;return Zt instanceof Error?bs+v(Zt):typeof Zt=="object"?bs+JSON.stringify(Zt):bs+Zt}).join(" "),xt=new Date,Zn=xt.getTime()-T;return T=xt.getTime(),[xt.getFullYear()+"-"+String(xt.getMonth()+1).padStart(2,"0")+"-"+String(xt.getDate()).padStart(2,"0")+"T"+String(xt.getHours()).padStart(2,"0")+":"+String(xt.getMinutes()).padStart(2,"0")+":"+String(xt.getSeconds()).padStart(2,"0"),"+"+Zn+"ms",ws,M].filter(Boolean).join(" ")+`
8
+ `}let j={debug(M,K){s("DEBUG")&&w("DEBUG "+W(M,K));},info(M,K){s("INFO")&&w("INFO "+W(M,K));},error(M,K){s("ERROR")&&w("ERROR "+W(M,K));},warn(M,K){s("WARN")&&w("WARN "+W(M,K));},tag(M,K){return A&&(A[M]=K),j},clone(){return P.create({...A})},time(M,K){let ws=Date.now();j.info(M,{status:"started",...K});function xt(){j.info(M,{status:"completed",duration:Date.now()-ws,...K});}return {stop:xt,[Symbol.dispose](){xt();}}}};return L&&typeof L=="string"&&o.set(L,j),j}P.create=F;})(pe||(pe={}));a();var Xa=pe.create({service:"gateway:config"});f.enum(["telegram","slack","feishu","wechat","webchat","signal","nostr"]);f.enum(["low","medium","high","critical"]);var ss=f.object({enabled:f.boolean().default(true),botToken:f.string().describe("Telegram Bot Token"),webhookUrl:f.string().optional().describe("Webhook URL for receiving updates"),maxConnections:f.number().int().positive().optional().default(100),timeout:f.number().int().positive().optional().default(3e4)}),rs=f.object({enabled:f.boolean().default(true),botToken:f.string().describe("Slack Bot Token (xoxb-*)"),appToken:f.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:f.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:f.number().int().positive().optional().default(100),timeout:f.number().int().positive().optional().default(3e4)}),ns=f.object({enabled:f.boolean().default(true),appId:f.string().describe("Feishu App ID"),appSecret:f.string().describe("Feishu App Secret"),encryptKey:f.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:f.string().optional().describe("Feishu Verification Token"),maxConnections:f.number().int().positive().optional().default(100),timeout:f.number().int().positive().optional().default(3e4)}),os=f.object({enabled:f.boolean().default(true),mode:f.enum(["official","wecom"]).default("official"),appId:f.string().describe("WeChat App ID"),appSecret:f.string().describe("WeChat App Secret"),token:f.string().optional().describe("WeChat Token for message verification"),encodingAESKey:f.string().optional().describe("WeChat Encoding AES Key"),agentId:f.string().optional().describe("WeCom Agent ID"),maxConnections:f.number().int().positive().optional().default(100),timeout:f.number().int().positive().optional().default(3e4)}),as=f.object({enabled:f.boolean().default(true),path:f.string().optional().default("/ws"),heartbeatInterval:f.number().int().positive().optional().default(3e4),connectionTimeout:f.number().int().positive().optional().default(6e4),maxConnections:f.number().int().positive().optional().default(1e3),cors:f.boolean().optional().default(true)}),hs=f.object({enabled:f.boolean().default(true),serviceUrl:f.string().optional().default("https://chat.signal.org"),phoneNumber:f.string().describe("Signal phone number"),password:f.string().optional().describe("Signal account password"),maxConnections:f.number().int().positive().optional().default(100),timeout:f.number().int().positive().optional().default(3e4)}),ls=f.object({enabled:f.boolean().default(true),relays:f.array(f.string()).min(1).describe("Nostr relay URLs"),privateKey:f.string().optional().describe("Nostr private key (hex)"),publicKey:f.string().optional().describe("Nostr public key (hex)"),maxConnections:f.number().int().positive().optional().default(100),timeout:f.number().int().positive().optional().default(3e4)}),_n=f.object({telegram:ss.optional(),slack:rs.optional(),feishu:ns.optional(),wechat:os.optional(),webchat:as.optional(),signal:hs.optional(),nostr:ls.optional()}),jn=f.object({enabled:f.boolean().default(false),cert:f.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:f.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:f.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:f.string().optional().describe("Path to SSL key file (alias of key)"),ca:f.string().optional().describe("Path to CA certificate file"),forceRedirect:f.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:f.number().int().positive().optional().default(80).describe("HTTP redirect port")}),th=f.object({name:f.string().describe("Token name/description"),value:f.string().describe("Token value"),permissions:f.array(f.string()).default(["*"]).describe("Associated permissions"),expiresAt:f.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:f.string().optional().describe("Token description")}),eh=f.object({enabled:f.boolean().default(true),tokens:f.array(th).default([]).describe("List of valid tokens"),onInvalid:f.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:f.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:f.array(f.string()).default([]).describe("Default permissions for anonymous users")}),ih=f.object({enabled:f.boolean().default(false),authorizationServer:f.string().describe("OAuth2 authorization server URL"),clientId:f.string().describe("OAuth2 client ID"),clientSecret:f.string().describe("OAuth2 client secret"),tokenValidationEndpoint:f.string().describe("OAuth2 token validation endpoint"),scope:f.array(f.string()).default([]).describe("OAuth2 scopes")}),In=f.object({type:f.enum(["token","oauth2"]).default("token"),token:eh.optional(),oauth2:ih.optional()}),zn=f.object({mode:f.enum(["pull","push","both"]).default("both"),interval:f.number().int().positive().default(3e4),pushEvents:f.array(f.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:f.enum(["latest","local","remote"]).default("latest")}),sh=f.object({id:f.string().describe("Gateway node ID"),address:f.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:f.boolean().default(true),metadata:f.record(f.string(),f.any()).optional()}),Bn=f.object({nodeId:f.string().describe("Current gateway node ID"),nodes:f.array(sh).default([]).describe("Other gateway nodes in the cluster"),sync:zn.optional()}),cs=f.object({maxConnectionsPerChannel:f.number().int().positive().default(100),idleTimeout:f.number().int().positive().default(3e5),reuseStrategy:f.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:f.number().int().positive().default(6e4),acquireTimeout:f.number().int().positive().default(5e3),warmupCount:f.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),fs=f.object({maxLength:f.number().int().positive().default(1e4),concurrency:f.number().int().positive().default(100),batchSize:f.number().int().positive().default(10),batchTimeout:f.number().int().positive().default(100),priorityLevels:f.number().int().positive().default(4)}),us=f.object({failureThreshold:f.number().int().positive().default(5),successThreshold:f.number().int().positive().default(3),timeout:f.number().int().positive().default(3e4),halfOpenDuration:f.number().int().positive().default(15e3)}),ps=f.object({heartbeatInterval:f.number().int().positive().default(3e4),heartbeatTimeout:f.number().int().positive().default(9e4),heartbeatCheckInterval:f.number().int().positive().default(1e4),autoDeregisterTimeout:f.number().int().positive().default(3e5),maxAgents:f.number().int().positive().default(100),persistenceFile:f.string().optional().describe("Path to persist agent registrations"),maxRegistrations:f.number().int().positive().default(1e3)}),ds=f.object({sessionTimeout:f.number().int().positive().default(18e5),resumeGracePeriod:f.number().int().positive().default(3e5),maxSessions:f.number().int().positive().default(1e4),persistenceFile:f.string().optional().describe("Path to persist sessions")}),gs=f.object({enabled:f.boolean().default(true),port:f.number().int().positive().default(8080),hostname:f.string().default("localhost"),path:f.string().optional().default("/ws"),maxConnections:f.number().int().positive().optional().default(1e3),connectionTimeout:f.number().int().positive().optional().default(6e4),heartbeatInterval:f.number().int().positive().optional().default(3e4),sessionExpireMs:f.number().int().positive().optional().default(3e5),https:jn.optional(),auth:In.optional(),cors:f.boolean().default(true),corsOrigins:f.array(f.string()).optional(),mdns:f.boolean().default(false),mdnsDomain:f.string().optional().default("gateway.easbot.local")}),is=f.object({server:gs.optional(),channels:_n.optional(),cluster:Bn.optional(),connectionPool:cs.optional(),messageQueue:fs.optional(),circuitBreaker:us.optional(),agentRegistry:ps.optional(),session:ds.optional(),defaultAgent:f.string().optional().describe("Default agent ID for routing"),logLevel:f.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(f.unknown());function ms(e){let t=is.safeParse(e);return t.success||Xa.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:is.parse({})}function rh(e){return is.parse(e)}a();a();a();pe.create({service:"gateway:interfaces"});var Vt;function Qn(){return Vt!==void 0}function qn(){throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");}var wh={Path:{data:".easbot"}},bh={directory:process.cwd()},Vs=class{async load(t){return Js(t)}},Ch=new Vs;function Ul(){return Ch}function Jn(){return wh}function Ys(){return bh}var Yt=pe.create({service:"gateway:config"}),Un={enabled:true,port:8080,hostname:"localhost",path:"/",maxConnections:1e3,connectionTimeout:6e4,heartbeatInterval:3e4,sessionExpireMs:3e5,cors:true,mdns:false,mdnsDomain:"gateway.easbot.local",https:{enabled:false,cert:"",key:"",certPath:void 0,keyPath:void 0,ca:void 0,forceRedirect:false,httpPort:80}},vh={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},xh={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},Eh={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},Ah={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3},kh={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e4},Th={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Rh={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Oh={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},Fh={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},Ph={enabled:true,path:"/ws",heartbeatInterval:3e4,connectionTimeout:6e4,maxConnections:1e3,cors:true},Lh={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},Nh={enabled:true,relays:[],maxConnections:100,timeout:3e4},Pi,He=null;async function Yn(e){try{if(!existsSync(e))return null;let i=(await qs.readFile(e,"utf-8")).replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").trim();return i?JSON.parse(i):null}catch(t){return Yt.debug("Failed to load config file",{file:e,error:String(t)}),null}}function Zs(e,t){let i={...e,...t};return (e.server||t.server)&&(i.server={...e.server,...t.server}),(e.channels||t.channels)&&(i.channels={...e.channels,...t.channels}),i}async function Gh(){let e=Jn(),t=Ys(),i=[],s=ys.join(e.Path.data,"config");i.push(s),i.push(t.directory);try{let{Filesystem:o}=await import('@easbot/utils'),a=await Array.fromAsync(o.up({targets:[".easbot"],start:t.directory}));i.push(...a);let h=process.env.HOME||process.env.USERPROFILE;if(h){let l=ys.join(h,".easbot");existsSync(l)&&i.push(l);}}catch{Yt.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(i.push(n),Yt.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(i)]}async function Dh(e){let t=["gateway.jsonc","gateway.json"],i={};for(let s of t){let n=ys.join(e,s),o=await Yn(n);o&&(i=Zs(i,o),Yt.debug("Loaded gateway config from file",{file:n}));}return i}async function Mh(e){let t=["easbot.jsonc","easbot.json"];for(let i of t){let s=ys.join(e,i),n=await Yn(s);if(n?.gateway)return Yt.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function Wh(){return Pi||(Pi=async()=>{let e=await Gh(),t={};for(let s of e){let n=await Dh(s);t=Zs(t,n);let o=await Mh(s);t=Zs(t,o);}let i=ms(t);return He=i,Yt.info("Gateway config loaded",{directories:e.length,port:i.server?.port,logLevel:i.logLevel}),{config:i,directories:e}}),Pi}async function mt(){return Wh()()}async function Js(e){return e&&(Pi=void 0,He=null),(await mt()).config}function $n(){return He}function Hn(){return He!==null}function nh(){Pi=void 0,He=null,Yt.debug("Config cache cleared");}function oh(){return Ys().directory}async function ah(){let{config:e}=await mt();return gs.parse({...Un,...e.server})}async function hh(e){let{config:t}=await mt(),i=t.channels?.[e],n={telegram:ss.parse(Th),slack:rs.parse(Rh),feishu:ns.parse(Oh),wechat:os.parse(Fh),webchat:as.parse(Ph),signal:hs.parse(Lh),nostr:ls.parse(Nh)}[e];if(!n)throw new Error(`Unknown channel type: ${e}`);return {...n,...i}}async function lh(){let{config:e}=await mt();return cs.parse({...vh,...e.connectionPool})}async function ch(){let{config:e}=await mt();return fs.parse({...xh,...e.messageQueue})}async function fh(){let{config:e}=await mt();return us.parse({...Eh,...e.circuitBreaker})}async function uh(){let{config:e}=await mt();return ps.parse({...Ah,...e.agentRegistry})}async function ph(){let{config:e}=await mt();return ds.parse({...kh,...e.session})}async function dh(){let{config:e}=await mt();return e.server?.https}async function gh(){let{config:e}=await mt();return e.server?.auth}async function mh(){let{config:e}=await mt();return e.cluster}async function yh(){let{config:e}=await mt();return e.defaultAgent}async function Kn(){let{config:e}=await mt();return e.logLevel??"INFO"}
9
+ export{nh as A,oh as B,ah as C,hh as D,lh as E,ch as F,fh as G,uh as H,ph as I,dh as J,gh as K,mh as L,yh as M,Kn as N,Qn as O,qn as P,Ul as Q,Jn as R,Ys as S,pe as a,ss as b,rs as c,ns as d,os as e,as as f,hs as g,ls as h,_n as i,jn as j,In as k,zn as l,Bn as m,cs as n,fs as o,us as p,ps as q,ds as r,gs as s,is as t,ms as u,rh as v,Un as w,Js as x,$n as y,Hn as z};
@@ -0,0 +1,2 @@
1
+ import {w as w$1,a as a$1,R as R$1,O,P as P$1}from'./chunk-UMFMKA5B.mjs';import {a}from'./chunk-SJNPXLNN.mjs';import {e}from'./chunk-TY6W6O7O.mjs';import*as m from'fs';import m__default from'fs';import*as z from'path';import {HookEvent}from'@easbot/plugin';import {createServer}from'@easbot/utils';import {WebSocketServer}from'ws';import V from'https';import K from'http';a();a();a();var x=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:lock"}));e(this,"config");e(this,"locks",new Map);e(this,"cleanupTimer",null);this.config={defaultTimeout:e$1.defaultTimeout??6e4,checkInterval:e$1.checkInterval??1e4};}tryAcquire(e,t,s,n){let r=this.locks.get(e);if(r)if(this.isLockExpired(r))this.log.warn("lock expired, releasing",{sessionId:e,oldHolder:r.holderId,newHolder:s}),this.locks.delete(e);else return this.log.debug("lock already held",{sessionId:e,holder:r.holderId,messageId:r.messageId}),false;let a={sessionId:e,messageId:t,holderId:s,acquiredAt:Date.now(),timeout:n??this.config.defaultTimeout};return this.locks.set(e,a),this.log.debug("lock acquired",{sessionId:e,messageId:t,subscriberId:s}),true}release(e,t){let s=this.locks.get(e);return s?s.holderId!==t?(this.log.warn("cannot release lock held by another",{sessionId:e,holder:s.holderId,requester:t}),false):(this.locks.delete(e),this.log.debug("lock released",{sessionId:e,subscriberId:t}),true):(this.log.debug("no lock to release",{sessionId:e}),false)}forceRelease(e){let t=this.locks.get(e);return t?(this.locks.delete(e),this.log.warn("lock force released",{sessionId:e,holder:t.holderId,messageId:t.messageId}),true):false}isLockExpired(e){return Date.now()-e.acquiredAt>e.timeout}getLock(e){return this.locks.get(e)}isLocked(e){let t=this.locks.get(e);return t?this.isLockExpired(t)?(this.locks.delete(e),false):true:false}getHolder(e){let t=this.locks.get(e);if(!(!t||this.isLockExpired(t)))return t.holderId}startCleanup(){this.cleanupTimer||(this.cleanupTimer=setInterval(()=>{this.cleanupExpired();},this.config.checkInterval),this.log.info("lock cleanup started",{interval:this.config.checkInterval}));}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.log.info("lock cleanup stopped"));}cleanupExpired(){let e=0;for(let[t,s]of this.locks)this.isLockExpired(s)&&(this.locks.delete(t),e++,this.log.warn("expired lock cleaned up",{sessionId:t,holder:s.holderId,messageId:s.messageId}));return e>0&&this.log.info("cleaned up expired locks",{count:e}),e}getAllLocks(){return [...this.locks.values()]}getLockCount(){return this.locks.size}};a();var k=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:retry"}));e(this,"policy");e(this,"retryQueue",new Map);e(this,"retryTimer",null);e(this,"handlers",new Map);this.policy={maxRetries:e$1.maxRetries??3,initialDelay:e$1.initialDelay??1e3,maxDelay:e$1.maxDelay??3e4,backoffMultiplier:e$1.backoffMultiplier??2};}registerHandler(e,t){this.handlers.set(e,t);}unregisterHandler(e){this.handlers.delete(e);}scheduleRetry(e,t){let s=e.id,n=this.retryQueue.get(s);if(n||(n={messageId:s,retryCount:0,nextRetryAt:0,errors:[]},this.retryQueue.set(s,n)),n.errors.push({error:t.message,timestamp:Date.now()}),n.retryCount>=this.policy.maxRetries)return this.log.error("max retries exceeded",{messageId:s,retryCount:n.retryCount,maxRetries:this.policy.maxRetries}),false;let r=Math.min(this.policy.initialDelay*this.policy.backoffMultiplier**n.retryCount,this.policy.maxDelay);return n.retryCount++,n.nextRetryAt=Date.now()+r,this.log.warn("retry scheduled",{messageId:s,retryCount:n.retryCount,delay:r,error:t.message}),true}getPendingRetries(){let e=Date.now(),t=[];for(let s of this.retryQueue.values())s.nextRetryAt<=e&&s.retryCount<=this.policy.maxRetries&&t.push(s);return t}async executeRetry(e){if(!this.handlers.get(e.messageId))return this.log.warn("no handler for retry",{messageId:e.messageId}),false;this.retryQueue.delete(e.messageId);try{return this.log.info("executing retry",{messageId:e.messageId,retryCount:e.retryCount}),!0}catch(s){return this.log.error("retry execution failed",{messageId:e.messageId,error:String(s)}),false}}clearRetry(e){this.retryQueue.delete(e),this.handlers.delete(e),this.log.debug("retry cleared",{messageId:e});}startProcessing(){this.retryTimer||(this.retryTimer=setInterval(async()=>{let e=this.getPendingRetries();for(let t of e)await this.executeRetry(t);},1e3),this.log.info("retry processing started"));}stopProcessing(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null,this.log.info("retry processing stopped"));}getStats(){let e=0;for(let t of this.retryQueue.values())e+=t.errors.length;return {pendingCount:this.retryQueue.size,totalErrors:e}}};a();a();function W(c,e,t,s){return {id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c,type:e,content:t,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function q(c,e,t,s){return W(c,e,[{type:"text",text:t}],s)}a();function E(c){let e=[c.platform,c.channelId];return c.chatId&&e.push(c.chatId),c.userId&&e.push(c.userId),e.join("_")}function D(){return {status:"active",messageCount:0,lastMessageAt:null}}a();function A(c,e){return `sub_${c}_${e}`}a();var _=w$1,v={maxConnections:w$1.maxConnections??1e3,connectionTimeout:w$1.connectionTimeout??6e4,sessionExpireMs:w$1.sessionExpireMs??3e5,heartbeatInterval:w$1.heartbeatInterval??3e4};a();var F={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};a();var U={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};a();var $={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};a();var j={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var P=class{constructor(){e(this,"log",a$1.create({service:"gateway:router"}));e(this,"subscribers",new Map);e(this,"subscriptions",new Map);e(this,"sessionSubscriptions",new Map);e(this,"channelPlugins",new Map);e(this,"lockManager");e(this,"retryManager");e(this,"cancelHandlers",new Set);this.lockManager=new x,this.retryManager=new k,this.lockManager.startCleanup();}onCancel(e){this.cancelHandlers.add(e);}offCancel(e){this.cancelHandlers.delete(e);}async emitCancel(e){for(let t of this.cancelHandlers)try{await t(e);}catch(s){this.log.error("cancel handler error",{error:String(s)});}}async route(e){this.log.debug("routing message",{id:e.id,sessionId:e.sessionId,type:e.type});let t=this.sessionSubscriptions.get(e.sessionId);if(!t||t.size===0)return this.log.debug("no subscribers for session",{sessionId:e.sessionId}),{success:true,broadcastCount:0,dispatchedToSubAgent:false};let s=0,n=null,r=[];for(let a of t){let g=this.subscriptions.get(a);if(!g)continue;let u=this.subscribers.get(g.subscriberId);if(u){if(e.type==="input"){if(!this.lockManager.tryAcquire(e.sessionId,e.id,u.id)){this.log.debug("skipping subscriber, lock held by another",{subscriberId:u.id,holder:this.lockManager.getHolder(e.sessionId)});continue}n=u.id;}try{await u.connection.send(e),s++,u.lastActiveAt=Date.now();}catch(f){this.log.warn("failed to send message to subscriber",{subscriberId:u.id,error:String(f)}),r.push(f instanceof Error?f:new Error(String(f))),n===u.id&&(this.lockManager.release(e.sessionId,u.id),n=null);}}}return this.log.debug("message routed",{id:e.id,broadcastCount:s,errorCount:r.length,processedBy:n}),{success:r.length===0,broadcastCount:s,dispatchedToSubAgent:false,error:r.length>0?r.map(a=>a.message).join("; "):void 0}}async completeMessage(e,t,s,n="completed"){this.lockManager.release(e,s),await this.emitCancel({sessionId:e,messageId:t,processedBy:s,reason:n,timestamp:Date.now()}),this.log.info("message completed",{sessionId:e,messageId:t,subscriberId:s,reason:n});}scheduleRetry(e,t){return this.retryManager.scheduleRetry(e,t)}async subscribe(e,t){let s=A(t.id,e);if(this.subscriptions.has(s))return this.log.debug("already subscribed",{subscriberId:t.id,sessionId:e}),this.subscriptions.get(s);let n={id:s,subscriberId:t.id,sessionId:e,createdAt:Date.now()};return this.subscribers.has(t.id)||this.subscribers.set(t.id,t),this.subscriptions.set(s,n),this.sessionSubscriptions.has(e)||this.sessionSubscriptions.set(e,new Set),this.sessionSubscriptions.get(e).add(s),t.sessions.add(e),this.log.info("subscribed to session",{subscriberId:t.id,sessionId:e,subscriptionId:s}),n}async unsubscribe(e){let t=this.subscriptions.get(e);if(!t){this.log.warn("subscription not found",{subscriptionId:e});return}this.subscriptions.delete(e);let s=this.sessionSubscriptions.get(t.sessionId);s&&(s.delete(e),s.size===0&&this.sessionSubscriptions.delete(t.sessionId));let n=this.subscribers.get(t.subscriberId);n&&n.sessions.delete(t.sessionId),this.log.info("unsubscribed from session",{subscriberId:t.subscriberId,sessionId:t.sessionId,subscriptionId:e});}async unsubscribeAll(e){let t=this.subscribers.get(e);if(!t)return;let s=[...t.sessions];for(let n of s){let r=A(e,n);await this.unsubscribe(r);}this.subscribers.delete(e),this.log.info("unsubscribed all sessions",{subscriberId:e});}async registerChannel(e){if(this.channelPlugins.has(e.id)){this.log.warn("channel plugin already registered",{id:e.id});return}this.channelPlugins.set(e.id,e),this.log.info("channel plugin registered",{id:e.id,platform:e.platform});}async unregisterChannel(e){let t=this.channelPlugins.get(e);if(!t){this.log.warn("channel plugin not found",{id:e});return}await t.stop(),this.channelPlugins.delete(e),this.log.info("channel plugin unregistered",{id:e});}getSubscriberCount(e){let t=this.sessionSubscriptions.get(e);return t?t.size:0}getAllSubscribers(){return [...this.subscribers.values()]}getChannelPlugin(e){return this.channelPlugins.get(e)}getAllChannelPlugins(){return [...this.channelPlugins.values()]}getLockManager(){return this.lockManager}getRetryManager(){return this.retryManager}async shutdown(){this.lockManager.stopCleanup(),this.retryManager.stopProcessing(),this.log.info("router shutdown");}};a();a();a();a();var C=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:message-store"}));e(this,"config");e(this,"messages",new Map);e(this,"sessionMessages",new Map);this.config={storagePath:e$1.storagePath??"./data/gateway-messages",maxRetentionDays:e$1.maxRetentionDays??30,maxRecords:e$1.maxRecords??1e5};}async store(e){let t={message:e,status:"pending",processedBy:null,processedAt:null,retryCount:0,error:null,createdAt:Date.now(),updatedAt:Date.now()};return this.messages.set(e.id,t),this.sessionMessages.has(e.sessionId)||this.sessionMessages.set(e.sessionId,new Set),this.sessionMessages.get(e.sessionId).add(e.id),this.log.debug("message stored",{id:e.id,sessionId:e.sessionId,type:e.type}),t}get(e){return this.messages.get(e)}async updateStatus(e,t,s={}){let n=this.messages.get(e);if(!n){this.log.warn("message not found for status update",{messageId:e});return}n.status=t,n.updatedAt=Date.now(),s.processedBy&&(n.processedBy=s.processedBy),(t==="completed"||t==="failed")&&(n.processedAt=Date.now()),s.error&&(n.error=s.error),this.log.debug("message status updated",{id:e,status:t,processedBy:s.processedBy});}incrementRetry(e){let t=this.messages.get(e);return t?(t.retryCount++,t.updatedAt=Date.now(),t.retryCount):0}isProcessed(e){let t=this.messages.get(e);return t?t.status==="completed"||t.status==="processing":false}getSessionHistory(e,t=100){let s=this.sessionMessages.get(e);if(!s)return [];let n=[];for(let r of s){let a=this.messages.get(r);a&&n.push(a);}return n.sort((r,a)=>r.createdAt-a.createdAt),n.slice(-t)}getPendingMessages(e){let t=[];for(let s of this.messages.values())s.status==="pending"&&(!e||s.message.sessionId===e)&&t.push(s);return t}getFailedMessages(e=3){let t=[];for(let s of this.messages.values())s.status==="failed"&&s.retryCount<e&&t.push(s);return t}async cleanup(){let e=Date.now(),t=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let[n,r]of this.messages)e-r.createdAt>t&&s.push(n);for(let n of s){let r=this.messages.get(n);if(r){let a=this.sessionMessages.get(r.message.sessionId);a&&a.delete(n),this.messages.delete(n);}}return s.length>0&&this.log.info("cleaned up expired messages",{count:s.length}),s.length}getStats(){let e={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0};for(let t of this.messages.values())e[t.status]++;return e}};a();var M=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:session-store"}));e(this,"config");e(this,"sessions",new Map);e(this,"channelSessions",new Map);e(this,"autoSaveTimer",null);e(this,"isDirty",false);this.config={storagePath:e$1.storagePath??"./data/gateway-sessions",autoSaveInterval:e$1.autoSaveInterval??6e4,maxRetentionDays:e$1.maxRetentionDays??7,enablePersistence:e$1.enablePersistence??true};}async initialize(){if(!this.config.enablePersistence){this.log.info("session persistence disabled");return}await this.ensureStorageDir(),await this.load(),this.startAutoSave(),this.log.info("session store initialized",{sessionCount:this.sessions.size,storagePath:this.config.storagePath});}async close(){this.stopAutoSave(),this.isDirty&&await this.save(),this.log.info("session store closed");}async set(e){this.sessions.set(e.id,e),this.channelSessions.has(e.channel.channelId)||this.channelSessions.set(e.channel.channelId,new Set),this.channelSessions.get(e.channel.channelId).add(e.id),this.markDirty();}get(e){return this.sessions.get(e)}async delete(e){let t=this.sessions.get(e);if(!t)return;this.sessions.delete(e);let s=this.channelSessions.get(t.channel.channelId);s&&(s.delete(e),s.size===0&&this.channelSessions.delete(t.channel.channelId)),this.markDirty();}getAll(){return [...this.sessions.values()]}getByChannel(e){let t=this.channelSessions.get(e);return t?[...t].map(s=>this.sessions.get(s)).filter(s=>s!==void 0):[]}size(){return this.sessions.size}markDirty(){this.isDirty=true;}async save(){if(!this.config.enablePersistence)return;let e=this.getSessionFilePath(),t=this.serializeAll();try{await this.ensureStorageDir(),await m.promises.writeFile(e,JSON.stringify(t,null,2),"utf-8"),this.isDirty=!1,this.log.debug("sessions saved",{count:t.length});}catch(s){throw this.log.error("failed to save sessions",{error:s}),s}}async load(){if(!this.config.enablePersistence)return;let e=this.getSessionFilePath();try{if(!m.existsSync(e)){this.log.debug("no saved sessions found");return}let t=await m.promises.readFile(e,"utf-8"),s=JSON.parse(t);this.sessions.clear(),this.channelSessions.clear();let n=Date.now(),r=this.config.maxRetentionDays*24*60*60*1e3;for(let a of s){if(n-a.lastActiveAt>r)continue;let g={id:a.id,channel:a.channel,backendSessionId:a.backendSessionId,subscribers:new Set(a.subscribers),state:a.state,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt};this.sessions.set(g.id,g),this.channelSessions.has(g.channel.channelId)||this.channelSessions.set(g.channel.channelId,new Set),this.channelSessions.get(g.channel.channelId).add(g.id);}this.log.info("sessions loaded",{loaded:this.sessions.size,skipped:s.length-this.sessions.size});}catch(t){this.log.error("failed to load sessions",{error:t});}}serializeAll(){let e=[];for(let t of this.sessions.values())e.push(this.serialize(t));return e}serialize(e){return {id:e.id,channel:e.channel,backendSessionId:e.backendSessionId,subscribers:[...e.subscribers],state:e.state,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt}}getSessionFilePath(){return z.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){m.existsSync(this.config.storagePath)||await m.promises.mkdir(this.config.storagePath,{recursive:true});}startAutoSave(){this.autoSaveTimer||(this.autoSaveTimer=setInterval(async()=>{this.isDirty&&await this.save();},this.config.autoSaveInterval));}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null);}async cleanup(){let e=Date.now(),t=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let n of this.sessions.values())e-n.lastActiveAt>t&&s.push(n.id);for(let n of s)await this.delete(n);return s.length>0&&(this.log.info("cleaned up expired sessions",{count:s.length}),await this.save()),s.length}getStats(){let e={total:this.sessions.size,byStatus:{active:0,idle:0,closed:0},byPlatform:{}};for(let t of this.sessions.values()){e.byStatus[t.state.status]++;let s=t.channel.platform;e.byPlatform[s]=(e.byPlatform[s]||0)+1;}return e}};var w=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:session"}));e(this,"sessionStore");e(this,"config");e(this,"initialized",false);this.config={enablePersistence:e$1.enablePersistence??true,storagePath:e$1.storagePath??"./data/gateway-sessions",autoSaveInterval:e$1.autoSaveInterval??6e4,maxRetentionDays:e$1.maxRetentionDays??7},this.sessionStore=new M({storagePath:this.config.storagePath,autoSaveInterval:this.config.autoSaveInterval,maxRetentionDays:this.config.maxRetentionDays,enablePersistence:this.config.enablePersistence});}async initialize(){this.initialized||(await this.sessionStore.initialize(),this.initialized=true,this.log.info("session manager initialized",{sessionCount:this.sessionStore.size(),persistenceEnabled:this.config.enablePersistence}));}async close(){await this.sessionStore.close(),this.log.info("session manager closed");}async getOrCreate(e,t={}){let s=E(e),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),this.log.debug("session found",{sessionId:s}),n):(n={id:s,channel:e,backendSessionId:null,subscribers:new Set,state:D(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),this.log.info("session created",{sessionId:s,platform:e.platform,channelId:e.channelId,chatId:e.chatId,userId:e.userId}),n)}get(e){return this.sessionStore.get(e)}async closeSession(e){let t=this.sessionStore.get(e);if(!t){this.log.warn("session not found",{sessionId:e});return}t.state.status="closed",await this.sessionStore.delete(e),this.log.info("session closed",{sessionId:e});}async closeById(e){return this.closeSession(e)}async bindBackendSession(e,t){let s=this.sessionStore.get(e);if(!s)throw new Error(`Session not found: ${e}`);s.backendSessionId=t,await this.sessionStore.set(s),this.log.info("backend session bound",{gatewaySessionId:e,backendSessionId:t});}async unbindBackendSession(e){let t=this.sessionStore.get(e);if(!t){this.log.warn("session not found",{sessionId:e});return}t.backendSessionId=null,await this.sessionStore.set(t),this.log.info("backend session unbound",{gatewaySessionId:e});}getState(e){return this.sessionStore.get(e)?.state}async incrementMessageCountOrCreate(e,t){let s=this.sessionStore.get(e);if(!s){let n=t??{platform:"api",channelId:"default"};s=await this.getOrCreate(n);}return s.state.messageCount++,s.state.lastMessageAt=Date.now(),s.lastActiveAt=Date.now(),await this.sessionStore.set(s),s}async incrementMessageCount(e){let t=this.sessionStore.get(e);t&&(t.state.messageCount++,t.state.lastMessageAt=Date.now(),t.lastActiveAt=Date.now(),await this.sessionStore.set(t));}async addSubscriber(e,t){let s=this.sessionStore.get(e);if(!s){this.log.warn("session not found",{sessionId:e});return}s.subscribers.add(t),await this.sessionStore.set(s),this.log.debug("subscriber added to session",{sessionId:e,subscriberId:t});}async removeSubscriber(e,t){let s=this.sessionStore.get(e);s&&(s.subscribers.delete(t),await this.sessionStore.set(s),this.log.debug("subscriber removed from session",{sessionId:e,subscriberId:t}));}query(e){let t=this.sessionStore.getAll();return e.platform&&(t=t.filter(s=>s.channel.platform===e.platform)),e.channelId&&(t=t.filter(s=>s.channel.channelId===e.channelId)),e.userId&&(t=t.filter(s=>s.channel.userId===e.userId)),e.status&&(t=t.filter(s=>s.state.status===e.status)),t}getSessionsByChannel(e){return this.sessionStore.getByChannel(e)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(e){let t=Date.now(),s=[];for(let n of this.sessionStore.getAll())n.state.status==="idle"&&t-n.lastActiveAt>e&&s.push(n.id);for(let n of s)await this.closeSession(n);return s.length>0&&this.log.info("cleaned up idle sessions",{count:s.length}),s.length}async save(){this.log.debug("session save triggered");}getStats(){return this.sessionStore.getStats()}};a();var I=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:plugin-loader"}));e(this,"plugins",new Map);e(this,"messageHandler",null);e(this,"healthCheckTimer",null);e(this,"config");this.config={pluginDir:e$1.pluginDir??"./plugins",autoDiscover:e$1.autoDiscover??false,healthCheckInterval:e$1.healthCheckInterval??6e4,healthCheckTimeout:e$1.healthCheckTimeout??5e3};}setMessageHandler(e){this.messageHandler=e;}async register(e,t){if(this.plugins.has(e.id)){this.log.warn("plugin already registered",{id:e.id});return}this.plugins.set(e.id,{plugin:e,config:t,started:false}),this.log.info("plugin registered",{id:e.id,platform:e.platform,name:e.name});}async unregister(e){let t=this.plugins.get(e);if(!t){this.log.warn("plugin not found",{id:e});return}t.started&&await this.stop(e),this.plugins.delete(e),this.log.info("plugin unregistered",{id:e});}async start(e){let t=this.plugins.get(e);if(!t)throw new Error(`Plugin not found: ${e}`);if(t.started){this.log.warn("plugin already started",{id:e});return}if(!this.messageHandler)throw new Error("Message handler not set");if(!t.config.enabled){this.log.warn("plugin is disabled",{id:e});return}this.log.info("starting plugin",{id:e});try{await t.plugin.start(t.config,this.messageHandler),t.started=!0,this.log.info("plugin started",{id:e});}catch(s){throw this.log.error("failed to start plugin",{id:e,error:String(s)}),s}}async stop(e){let t=this.plugins.get(e);if(!t){this.log.warn("plugin not found",{id:e});return}if(!t.started){this.log.warn("plugin not started",{id:e});return}this.log.info("stopping plugin",{id:e});try{await t.plugin.stop(),t.started=!1,this.log.info("plugin stopped",{id:e});}catch(s){throw this.log.error("failed to stop plugin",{id:e,error:String(s)}),s}}async startAll(){let e=[];for(let[t,s]of this.plugins){if(!s.config.enabled){this.log.debug("skipping disabled plugin",{id:t});continue}try{await this.start(t);}catch(n){e.push({id:t,error:n instanceof Error?n:new Error(String(n))});}}e.length>0&&this.log.warn("some plugins failed to start",{count:e.length,errors:e.map(t=>({id:t.id,error:t.error.message}))});}async stopAll(){let e=[];for(let[t,s]of this.plugins)if(s.started)try{await this.stop(t);}catch(n){e.push({id:t,error:n instanceof Error?n:new Error(String(n))});}e.length>0&&this.log.warn("some plugins failed to stop",{count:e.length,errors:e.map(t=>({id:t.id,error:t.error.message}))});}getPlugin(e){return this.plugins.get(e)?.plugin}getAllPlugins(){return [...this.plugins.values()].map(e=>e.plugin)}getRunningPlugins(){return [...this.plugins.values()].filter(e=>e.started).map(e=>e.plugin)}isRunning(e){return this.plugins.get(e)?.started??false}async healthCheck(e){let t=this.plugins.get(e);if(!t)return {healthy:false,lastCheck:Date.now(),error:"Plugin not found"};try{let s=await Promise.race([t.plugin.healthCheck(),new Promise((n,r)=>setTimeout(()=>r(new Error("Health check timeout")),this.config.healthCheckTimeout))]);return t.lastHealthCheck=s,s}catch(s){let n={healthy:false,lastCheck:Date.now(),error:s instanceof Error?s.message:String(s)};return t.lastHealthCheck=n,n}}async healthCheckAll(){let e=new Map;for(let[t]of this.plugins)e.set(t,await this.healthCheck(t));return e}startHealthCheckTimer(){if(this.healthCheckTimer){this.log.warn("health check timer already running");return}this.healthCheckTimer=setInterval(async()=>{let e=await this.healthCheckAll();for(let[t,s]of e)s.healthy||this.log.warn("plugin health check failed",{id:t,error:s.error});},this.config.healthCheckInterval),this.log.info("health check timer started",{interval:this.config.healthCheckInterval});}stopHealthCheckTimer(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null,this.log.info("health check timer stopped"));}async sendToPlugin(e,t){let s=this.plugins.get(e);if(!s)throw new Error(`Plugin not found: ${e}`);if(!s.started)throw new Error(`Plugin not started: ${e}`);return s.plugin.send(t)}};a();var l=a$1.create({service:"gateway:websocket-server"});function J(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function R(c,e){for(let[t,s]of e.entries())if(s===c)return t;return null}var G=class{constructor(e$1={}){e(this,"config");e(this,"server",null);e(this,"wss",null);e(this,"httpsServer",null);e(this,"httpRedirectServer",null);e(this,"connections",new Map);e(this,"subscriptions",new Map);e(this,"sessionSubscriptions",new Map);e(this,"sessionLastActivity",new Map);e(this,"cleanupInterval",null);e(this,"heartbeatInterval",null);e(this,"startTime",0);e(this,"running",false);this.config={..._,...e$1};}async start(){if(this.running){l.warn("WebSocket server is already running");return}l.info("Starting WebSocket server",{port:this.config.port,hostname:this.config.hostname,path:this.config.path,https:this.config.https?.enabled??false}),this.startTime=Date.now();let e={onOpen:(s,n)=>{this.handleConnection(n);},onMessage:async(s,n)=>{try{let r=JSON.parse(s.data.toString());await this.handleMessage(n,r);}catch(r){l.error("Error processing WebSocket message",{error:r.message}),this.sendError(n,r.message);}},onClose:(s,n)=>{this.handleDisconnection(n);},onError:(s,n)=>{l.error("WebSocket error",{error:s.type});}};this.config.https?.enabled?await this.startHTTPSServer(e):await this.startHTTPServer(e),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let t=this.config.https?.enabled?"wss":"ws";l.info("WebSocket server started",{url:`${t}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(e){this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let t=this.server.raw;t&&this.setupWebSocketUpgrade(t,e);}async startHTTPSServer(e){let t=this.config.https,s=this.loadSSLCertificates(t);if(!s){l.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(e);return}this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let n=this.server.raw;this.httpsServer=V.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,e),await new Promise(r=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{l.info("HTTPS server started",{port:this.config.port,hostname:this.config.hostname}),r();});}),t.forceRedirect&&t.httpPort&&this.startHTTPRedirectServer(t.httpPort);}loadSSLCertificates(e){try{return e.cert&&e.key?{cert:e.cert,key:e.key}:e.certPath&&e.keyPath?{cert:m__default.readFileSync(e.certPath),key:m__default.readFileSync(e.keyPath)}:null}catch(t){return l.error("Failed to load SSL certificates",{error:t.message}),null}}setupWebSocketUpgrade(e,t){this.wss=new WebSocketServer({noServer:true}),e.on("upgrade",(s,n,r)=>{try{let g=new URL(s.url||"/",`http://${s.headers.host}`).pathname;(g===this.config.path||this.config.path==="/"&&(g==="/"||g===""))&&this.wss.handleUpgrade(s,n,r,u=>{t.onOpen?.({type:"open"},u),u.on("message",f=>{t.onMessage?.({data:f},u);}),u.on("close",(f,L)=>{t.onClose?.({code:f,reason:L},u);}),u.on("error",f=>{t.onError?.({type:"error",message:f.message},u);});});}catch{}});}startHTTPRedirectServer(e){this.httpRedirectServer=K.createServer((t,s)=>{let r=`https://${t.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${t.url}`;l.debug("Redirecting HTTP to HTTPS",{from:t.url,to:r}),s.writeHead(301,{Location:r,"Content-Type":"text/plain"}),s.end(`Redirecting to ${r}`);}),this.httpRedirectServer.listen(e,this.config.hostname,()=>{l.info("HTTP redirect server started",{port:e,hostname:this.config.hostname});});}async stop(){if(!this.running){l.warn("WebSocket server is not running");return}l.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[e,t]of this.connections.entries())try{t.close(1e3,"Server shutting down");}catch(s){l.debug("Error closing connection",{clientId:e,error:String(s)});}this.connections.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.sessionLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(e=>{this.httpsServer.close(()=>e());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(e=>{this.httpRedirectServer.close(()=>e());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,l.info("WebSocket server stopped");}broadcastToSession(e,t){this.touchSession(e);let s=this.sessionSubscriptions.get(e);if(!s||s.size===0){l.debug("No clients subscribed to session",{sessionId:e});return}let n=t?.properties?.sessionID;if(typeof n=="string"&&n&&n!==e)return;let r=JSON.stringify({type:"event",sessionId:e,payload:t});for(let a of s){let g=this.subscriptions.get(a);if(g&&g.ws.readyState===g.ws.OPEN&&g.subscribedSessions.has(e)){if(g.subscribedEventTypes.size>0&&!g.subscribedEventTypes.has(t.type)){l.debug("Event type not subscribed, skipping",{clientId:a,sessionId:e,eventType:t.type,subscribedTypes:Array.from(g.subscribedEventTypes)});continue}g.ws.send(r),l.debug("Event pushed to client",{clientId:a,sessionId:e,eventType:t.type});}}}getConnectionCount(){return this.connections.size}getSubscriptionCount(){return this.sessionSubscriptions.size}getConnectionInfos(){let e=[];for(let[t,s]of this.subscriptions.entries())e.push({clientId:t,state:s.ws.readyState===s.ws.OPEN?"connected":"disconnected",connectedAt:s.connectedAt,lastActivityAt:s.lastActivityAt,authInfo:s.authInfo});return e}isRunning(){return this.running}handleConnection(e){if(this.connections.size>=(this.config.maxConnections??v.maxConnections)){l.warn("Maximum connections reached, rejecting new connection"),e.close(1013,"Maximum connections reached");return}let t=J();this.connections.set(t,e),this.subscriptions.set(t,{clientId:t,ws:e,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()}),l.info("WebSocket client connected",{clientId:t,totalConnections:this.connections.size}),this.sendMessage(e,{type:"connected",clientId:t,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}handleDisconnection(e){let t=R(e,this.connections);if(!t)return;this.connections.delete(t);let s=this.subscriptions.get(t);if(s){for(let n of s.subscribedSessions){let r=this.sessionSubscriptions.get(n);r&&(r.delete(t),r.size===0&&this.sessionSubscriptions.delete(n));}this.subscriptions.delete(t);}l.info("WebSocket client disconnected",{clientId:t,totalConnections:this.connections.size});}async handleMessage(e,t){let s=R(e,this.connections);if(!s){this.sendError(e,"Client not found");return}let n=this.subscriptions.get(s);switch(n&&(n.lastActivityAt=Date.now()),t.type){case "ping":this.sendMessage(e,{type:"pong"});break;case "initialize":await this.handleInitialize(e,t);break;case "subscribe":await this.handleSubscribe(e,t);break;case "unsubscribe":await this.handleUnsubscribe(e,t);break;case "message":await this.handleMessageRequest(e,t);break;case "interrupt":await this.handleInterrupt(e,t);break;case "releaseSubscription":await this.handleReleaseSubscription(e,t);break;default:this.sendError(e,`Unknown message type: ${t.type}`);}}async handleInitialize(e,t){this.sendMessage(e,{type:"initialize_response",success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleSubscribe(e,t){if(t.type!=="subscribe"||!t.sessionId){this.sendError(e,"Invalid subscribe request");return}let s=R(e,this.connections);if(!s){this.sendError(e,"Client not found");return}let n=this.subscriptions.get(s);if(!n){this.sendError(e,"Subscription not found");return}if(n.subscribedSessions.add(t.sessionId),this.sessionSubscriptions.has(t.sessionId)||this.sessionSubscriptions.set(t.sessionId,new Set),this.sessionSubscriptions.get(t.sessionId).add(s),this.touchSession(t.sessionId),t.payload?.eventTypes)for(let r of t.payload.eventTypes)n.subscribedEventTypes.add(r);l.info("Client subscribed to session",{clientId:s,sessionId:t.sessionId}),this.sendMessage(e,{type:"subscribed",sessionId:t.sessionId});}async handleUnsubscribe(e,t){if(t.type!=="unsubscribe"||!t.sessionId){this.sendError(e,"Invalid unsubscribe request");return}let s=R(e,this.connections);if(!s)return;let n=this.subscriptions.get(s);if(!n)return;n.subscribedSessions.delete(t.sessionId);let r=this.sessionSubscriptions.get(t.sessionId);r&&(r.delete(s),r.size===0&&this.sessionSubscriptions.delete(t.sessionId)),l.info("Client unsubscribed from session",{clientId:s,sessionId:t.sessionId}),this.sendMessage(e,{type:"unsubscribed",sessionId:t.sessionId});}async handleMessageRequest(e,t){if(t.type!=="message"||!t.sessionId||!t.payload){this.sendError(e,"Invalid message request");return}l.debug("Message received",{sessionId:t.sessionId}),this.sendMessage(e,{type:"response",sessionId:t.sessionId,success:true,result:{received:true}});}async handleInterrupt(e,t){if(t.type!=="interrupt"||!t.sessionId){this.sendError(e,"Invalid interrupt request");return}l.info("Interrupt requested via WebSocket",{sessionId:t.sessionId}),this.sendMessage(e,{type:"interrupted",sessionId:t.sessionId,success:true});}async handleReleaseSubscription(e,t){if(t.type!=="releaseSubscription"||!t.sessionId){this.sendError(e,"Invalid releaseSubscription request");return}l.info("Release subscription requested via WebSocket",{sessionId:t.sessionId}),this.releaseSessionResources(t.sessionId),this.sendMessage(e,{type:"subscriptionReleased",sessionId:t.sessionId});}touchSession(e){this.sessionLastActivity.set(e,Date.now());}checkConnectionTimeout(){let e=Date.now(),t=this.config.connectionTimeout??v.connectionTimeout,s=[];for(let[n,r]of this.subscriptions.entries())e-r.lastActivityAt>t&&s.push(n);for(let n of s){let r=this.subscriptions.get(n);if(r){l.info("Closing inactive connection",{clientId:n,lastActivityAt:r.lastActivityAt,timeoutMs:t});try{r.ws.close(1001,"Connection timeout");}catch(a){l.debug("Error closing timed out connection",{clientId:n,error:String(a)});}}}s.length>0&&l.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size-s.length});}cleanupExpiredSessions(){let e=Date.now(),t=[],s=this.config.sessionExpireMs??v.sessionExpireMs;for(let[n,r]of this.sessionLastActivity.entries())e-r>s&&t.push(n);for(let n of t)l.info("Session expired due to inactivity, releasing resources",{sessionId:n,lastActivity:this.sessionLastActivity.get(n),expireMs:s}),this.releaseSessionResources(n),this.sessionLastActivity.delete(n);t.length>0&&l.debug("Cleaned up expired sessions",{count:t.length,remainingActive:this.sessionLastActivity.size});}releaseSessionResources(e){let t=this.sessionSubscriptions.get(e);if(t){for(let s of t){let n=this.subscriptions.get(s);n&&n.ws.readyState===n.ws.OPEN&&this.sendMessage(n.ws,{type:"session_closed",sessionId:e,payload:{reason:"Session resources released due to expiration or explicit release"}});}for(let s of t){let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(e);}this.sessionSubscriptions.delete(e),l.info("Session resources released",{sessionId:e,clientCount:t.size});}}sendMessage(e,t){e.readyState===e.OPEN&&e.send(JSON.stringify(t));}sendError(e,t,s){this.sendMessage(e,{type:"error",message:t,code:s});}createRoutes(){return [{method:"get",path:"/health",handler:e=>{let t={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return e.json(t)}},{method:"get",path:"/status",handler:e=>{let t={status:this.running?"running":"stopped",connections:this.connections.size,sessions:this.sessionSubscriptions.size,subscriptions:this.subscriptions.size,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0"};return e.json(t)}},{method:"post",path:"/initialize",handler:async e=>{let t=await e.req.json().catch(()=>({}));return l.debug("ACP initialize request received",{body:t}),e.json({success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"],version:"1.0.0"}})}},{method:"post",path:"/session",handler:async e=>{await e.req.json().catch(()=>({}));let n={id:`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,createdAt:Date.now()};return e.json(n)}},{method:"post",path:"/session/:sessionId/prompt",handler:async e=>{let t=e.req.param("sessionId");await e.req.json().catch(()=>({}));if(!t)return e.json({error:"No sessionId provided"},400);let r={messageId:`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,sessionId:t,createdAt:Date.now()};return e.status(202),e.json(r)}},{method:"get",path:"/subscriptions",handler:e=>{let t=Array.from(this.sessionSubscriptions.entries()).map(([n,r])=>({sessionId:n,subscriberCount:r.size,subscribers:Array.from(r)})),s={subscriptions:t,total:t.length};return e.json(s)}}]}};function Y(c){let e={platform:c.channel?.platform??"api",channelId:c.channel?.channelId??"unknown",chatId:c.channel?.chatId,userId:c.channel?.userId};return {id:c.messageId??`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c.sessionId,type:c.type,content:Array.isArray(c.content)?c.content:[{type:"text",text:String(c.content??"")}],metadata:{channel:e,replyToMessageId:c.replyToMessageId},timestamp:c.timestamp??Date.now()}}var B=class{constructor(e$1){e(this,"log",a$1.create({service:"gateway:server"}));e(this,"config");e(this,"router");e(this,"sessionManager");e(this,"pluginLoader");e(this,"messageStore");e(this,"running",false);e(this,"connections",0);this.config=e$1,this.router=new P,this.sessionManager=new w,this.pluginLoader=new I({healthCheckInterval:6e4});let t=R$1(),s=O();this.messageStore=new C({storagePath:`${t.Path.data}/gateway-messages`}),s&&P$1().setMessageStorage({store:async r=>{let a=Y(r);await this.messageStore.store(a);},updateStatus:async(r,a,g)=>{await this.messageStore.updateStatus(r,a,g);}}),this.pluginLoader.setMessageHandler({onMessage:n=>this.onMessage(n),onEvent:n=>this.onEvent(n)});}async start(){if(this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),await this.sessionManager.initialize(),await this.pluginLoader.startAll(),this.pluginLoader.startHealthCheckTimer(),this.running=true,this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}this.log.info("stopping gateway server"),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),this.running=false,this.log.info("gateway server stopped");}getStatus(){return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections}}async onMessage(e){if(this.log.debug("message received",{id:e.id,sessionId:e.sessionId,type:e.type}),this.messageStore.isProcessed(e.id)){this.log.warn("message already processed, skipping",{id:e.id});return}await this.storeMessage(e),await this.sessionManager.incrementMessageCountOrCreate(e.sessionId,e.metadata.channel),(await this.router.route(e)).broadcastCount===0&&e.type==="input"&&this.log.debug("no subscribers, message pending",{id:e.id});}async storeMessage(e){if(await this.messageStore.store(e),O())try{let t=P$1(),s={name:HookEvent.GatewayMessageReceive,data:{messageId:e.id,sessionId:e.sessionId,type:e.type,content:e.content,channel:e.metadata.channel,replyToMessageId:e.metadata.replyToMessageId,timestamp:e.timestamp||Date.now()}};await t.hookRegistry.emit(s);}catch{this.log.debug("hook trigger skipped (no context)");}}async processMessage(e,t,s,n={}){if(await this.messageStore.updateStatus(t,"processing",{processedBy:s}),O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageProcess,data:{messageId:t,sessionId:e,processorId:s,processType:n.processType||"direct",agent:n.agent,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}}async completeMessage(e,t,s,n={}){let{success:r=true,error:a,responseMessageId:g,tokens:u,duration:f}=n;if(await this.messageStore.updateStatus(t,r?"completed":"failed",{processedBy:s,error:a}),O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageComplete,data:{messageId:t,sessionId:e,processorId:s,status:r?"completed":"failed",error:a,responseMessageId:g,tokens:u,duration:f,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}await this.router.completeMessage(e,t,s,r?"completed":"failed");}async onEvent(e){switch(this.log.debug("channel event",{type:e.type,channelId:e.channelId}),e.type){case "connected":this.connections++;break;case "disconnected":this.connections--;break;case "error":this.log.error("channel error",{channelId:e.channelId,data:e.data});break}}async registerChannel(e,t){let s=t??{enabled:true,platform:{},session:{autoCreate:true,resetPolicy:"onNewConversation"},routing:{broadcast:true,dispatchToSubAgent:false}};await this.pluginLoader.register(e,s),this.running&&await this.pluginLoader.start(e.id);}async unregisterChannel(e){await this.pluginLoader.unregister(e);}async subscribe(e,t){await this.router.subscribe(e,t),await this.sessionManager.addSubscriber(e,t.id);}async unsubscribe(e){await this.router.unsubscribe(e);}async send(e){await this.onMessage(e);}async sendToChannel(e,t,s={}){let{proactive:n=false,replyToMessageId:r}=s;if(O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageSend,data:{messageId:t.id,sessionId:t.sessionId,type:t.type,channel:t.metadata.channel,proactive:n,replyToMessageId:r,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}return this.pluginLoader.sendToPlugin(e,t)}async sendProactiveMessage(e,t,s,n){let r={id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:t,type:"output",content:s,metadata:{channel:n},timestamp:Date.now()};return this.sendToChannel(e,r,{proactive:true})}getSessionManager(){return this.sessionManager}getRouter(){return this.router}getPluginLoader(){return this.pluginLoader}getMessageStore(){return this.messageStore}async getMessageHistory(e,t){return this.messageStore.getSessionHistory(e,t)}};
2
+ export{x as a,k as b,W as c,q as d,E as e,D as f,A as g,_ as h,F as i,U as j,$ as k,j as l,P as m,C as n,M as o,w as p,I as q,G as r,B as s};
@@ -0,0 +1 @@
1
+ 'use strict';var i=Object.create;var f=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,m=Object.prototype.hasOwnProperty;var h=a=>{throw TypeError(a)};var n=(a,b,c)=>b in a?f(a,b,{enumerable:true,configurable:true,writable:true,value:c}):a[b]=c;var r=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var s=(a,b)=>()=>(a&&(b=a(a=0)),b);var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var o=(a,b,c,d)=>{if(b&&typeof b=="object"||typeof b=="function")for(let e of k(b))!m.call(a,e)&&e!==c&&f(a,e,{get:()=>b[e],enumerable:!(d=j(b,e))||d.enumerable});return a};var u=(a,b,c)=>(c=a!=null?i(l(a)):{},o(b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:true}):c,a));var v=(a,b,c)=>n(a,typeof b!="symbol"?b+"":b,c),g=(a,b,c)=>b.has(a)||h("Cannot "+c);var p=(a,b,c)=>(g(a,b,"read from private field"),c?c.call(a):b.get(a)),w=(a,b,c)=>b.has(a)?h("Cannot add the same private member more than once"):b instanceof WeakSet?b.add(a):b.set(a,c),q=(a,b,c,d)=>(g(a,b,"write to private field"),d?d.call(a,c):b.set(a,c),c),x=(a,b,c)=>(g(a,b,"access private method"),c);var y=(a,b,c,d)=>({set _(e){q(a,b,e,c);},get _(){return p(a,b,d)}});exports.a=r;exports.b=s;exports.c=t;exports.d=u;exports.e=v;exports.f=p;exports.g=w;exports.h=q;exports.i=x;exports.j=y;
@@ -0,0 +1 @@
1
+ 'use strict';var chunk7SIK6QBH_cjs=require('./chunk-7SIK6QBH.cjs'),chunkSIOB4FC7_cjs=require('./chunk-SIOB4FC7.cjs');require('./chunk-XQVVSJRM.cjs');var promises=require('fs/promises'),o=require('path'),xdgBasedir=require('xdg-basedir'),x=require('os');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var o__default=/*#__PURE__*/_interopDefault(o);var x__default=/*#__PURE__*/_interopDefault(x);chunkSIOB4FC7_cjs.a();var s="easbot",c=o__default.default.join(xdgBasedir.xdgData,s),H=o__default.default.join(xdgBasedir.xdgCache,s),N=o__default.default.join(xdgBasedir.xdgConfig,s),j=o__default.default.join(xdgBasedir.xdgState,s);exports.Global=void 0;(e=>{e.Path={get home(){return process.env.EASBOT_TEST_HOME||x__default.default.homedir()},data:c,bin:o__default.default.join(c,"bin"),log:o__default.default.join(c,"log"),cache:H,config:N,state:j};let t=null,n=null;async function A(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{let r=await import('./package-OFDLYJ3A.cjs');t=r.default?.version||r.version||"local";}catch{t="local";}return t||"local"}function E(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=chunk7SIK6QBH_cjs.a.version||"local";}catch{t="local";}return t||"local"}e.getVersion=E;function l(){if(n)return n;if(process.env.EASBOT_CHANNEL)return n=process.env.EASBOT_CHANNEL,n;let r=E();return r==="local"||r.includes("dev")?n="local":r.includes("beta")||r.includes("alpha")?n="preview":n="latest",n||"local"}e.getChannel=l;function C(){return l()==="local"}e.isLocal=C;function V(){return l()==="preview"}e.isPreview=V;let u=false,a=null;async function I(){if(!u)return a||(a=(async()=>{await A(),await Promise.all([promises.mkdir(e.Path.data,{recursive:true}),promises.mkdir(e.Path.config,{recursive:true}),promises.mkdir(e.Path.state,{recursive:true}),promises.mkdir(e.Path.log,{recursive:true}),promises.mkdir(e.Path.bin,{recursive:true}),promises.mkdir(e.Path.cache,{recursive:true})]).then(()=>{process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let r="1",h=o__default.default.join(e.Path.cache,"version");if(await promises.readFile(h,"utf-8").catch(()=>"0")!==r){try{let p=await promises.readdir(e.Path.cache);await Promise.all(p.map(g=>promises.rm(o__default.default.join(e.Path.cache,g),{recursive:!0,force:!0})));}catch{}await promises.writeFile(h,r);}u=true;})(),a)}e.init=I;})(exports.Global||(exports.Global={}));
@@ -0,0 +1 @@
1
+ import {a as a$1}from'./chunk-T4HRQGQB.mjs';import {a}from'./chunk-SJNPXLNN.mjs';import'./chunk-TY6W6O7O.mjs';import {mkdir,readFile,readdir,rm,writeFile}from'fs/promises';import o from'path';import {xdgData,xdgCache,xdgConfig,xdgState}from'xdg-basedir';import x from'os';a();var s="easbot",c=o.join(xdgData,s),H=o.join(xdgCache,s),N=o.join(xdgConfig,s),j=o.join(xdgState,s),P;(e=>{e.Path={get home(){return process.env.EASBOT_TEST_HOME||x.homedir()},data:c,bin:o.join(c,"bin"),log:o.join(c,"log"),cache:H,config:N,state:j};let t=null,n=null;async function A(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{let r=await import('./package-IPUQXPNH.mjs');t=r.default?.version||r.version||"local";}catch{t="local";}return t||"local"}function E(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=a$1.version||"local";}catch{t="local";}return t||"local"}e.getVersion=E;function l(){if(n)return n;if(process.env.EASBOT_CHANNEL)return n=process.env.EASBOT_CHANNEL,n;let r=E();return r==="local"||r.includes("dev")?n="local":r.includes("beta")||r.includes("alpha")?n="preview":n="latest",n||"local"}e.getChannel=l;function C(){return l()==="local"}e.isLocal=C;function V(){return l()==="preview"}e.isPreview=V;let u=false,a=null;async function I(){if(!u)return a||(a=(async()=>{await A(),await Promise.all([mkdir(e.Path.data,{recursive:true}),mkdir(e.Path.config,{recursive:true}),mkdir(e.Path.state,{recursive:true}),mkdir(e.Path.log,{recursive:true}),mkdir(e.Path.bin,{recursive:true}),mkdir(e.Path.cache,{recursive:true})]).then(()=>{process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let r="1",h=o.join(e.Path.cache,"version");if(await readFile(h,"utf-8").catch(()=>"0")!==r){try{let p=await readdir(e.Path.cache);await Promise.all(p.map(g=>rm(o.join(e.Path.cache,g),{recursive:!0,force:!0})));}catch{}await writeFile(h,r);}u=true;})(),a)}e.init=I;})(P||(P={}));export{P as Global};
@@ -0,0 +1 @@
1
+ export{a as default}from'./chunk-T4HRQGQB.mjs';import'./chunk-TY6W6O7O.mjs';
@@ -0,0 +1 @@
1
+ 'use strict';var chunk7SIK6QBH_cjs=require('./chunk-7SIK6QBH.cjs');require('./chunk-XQVVSJRM.cjs');module.exports=chunk7SIK6QBH_cjs.a;
@@ -0,0 +1 @@
1
+ export{q as ChannelPluginLoader,s as GatewayServer,r as GatewayWebSocketServer}from'./chunk-X7GOOL6H.mjs';import'./chunk-UMFMKA5B.mjs';import'./chunk-SJNPXLNN.mjs';import'./chunk-TY6W6O7O.mjs';
@@ -0,0 +1 @@
1
+ 'use strict';var chunk56QXYDMF_cjs=require('./chunk-56QXYDMF.cjs');require('./chunk-JJLKV5TO.cjs'),require('./chunk-SIOB4FC7.cjs'),require('./chunk-XQVVSJRM.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunk56QXYDMF_cjs.q}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunk56QXYDMF_cjs.s}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunk56QXYDMF_cjs.r}});