@easbot/gateway 0.2.23 → 0.2.25

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.
@@ -1,7 +0,0 @@
1
- import {c,a,d,b,e,f}from'./chunk-HAMGVOQD.mjs';import qi,{win32,posix}from'path';import oh,{realpath,readlink,readdir,lstat}from'fs/promises';import*as Cn from'fs';import {realpathSync,createWriteStream,readlinkSync,readdirSync,readdir as readdir$1,lstatSync}from'fs';import co from'zod';import {fileURLToPath}from'url';import {EventEmitter}from'events';import Pr from'stream';import {StringDecoder}from'string_decoder';import {initLog,formatLogTime}from'@easbot/utils';var mr=(e,t,i)=>{let s=e instanceof RegExp?ks(e,i):e,h=t instanceof RegExp?ks(t,i):t,n=s!==null&&h!=null&&ph(s,h,i);return n&&{start:n[0],end:n[1],pre:i.slice(0,n[0]),body:i.slice(n[0]+s.length,n[1]),post:i.slice(n[1]+h.length)}},ks=(e,t)=>{let i=t.match(e);return i?i[0]:null},ph=(e,t,i)=>{let s,h,n,o,a,l=i.indexOf(e),u=i.indexOf(t,l+1),d=l;if(l>=0&&u>0){if(e===t)return [l,u];for(s=[],n=i.length;d>=0&&!a;){if(d===l)s.push(d),l=i.indexOf(e,d+1);else if(s.length===1){let f=s.pop();f!==void 0&&(a=[f,u]);}else h=s.pop(),h!==void 0&&h<n&&(n=h,o=u),u=i.indexOf(t,d+1);d=l<u&&l>=0?l:u;}s.length&&o!==void 0&&(a=[n,o]);}return a},wr="\0SLASH"+Math.random()+"\0",yr="\0OPEN"+Math.random()+"\0",ys="\0CLOSE"+Math.random()+"\0",br="\0COMMA"+Math.random()+"\0",Sr="\0PERIOD"+Math.random()+"\0",fh=new RegExp(wr,"g"),dh=new RegExp(yr,"g"),gh=new RegExp(ys,"g"),mh=new RegExp(br,"g"),wh=new RegExp(Sr,"g"),yh=/\\\\/g,bh=/\\{/g,Sh=/\\}/g,vh=/\\,/g,Eh=/\\./g,xh=1e5;function Ki(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function kh(e){return e.replace(yh,wr).replace(bh,yr).replace(Sh,ys).replace(vh,br).replace(Eh,Sr)}function Rh(e){return e.replace(fh,"\\").replace(dh,"{").replace(gh,"}").replace(mh,",").replace(wh,".")}function vr(e){if(!e)return [""];let t=[],i=mr("{","}",e);if(!i)return e.split(",");let{pre:s,body:h,post:n}=i,o=s.split(",");o[o.length-1]+="{"+h+"}";let a=vr(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Ch(e,t={}){if(!e)return [];let{max:i=xh}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Je(kh(e),i,true).map(Rh)}function Oh(e){return "{"+e+"}"}function Ah(e){return /^-?0\d/.test(e)}function Fh(e,t){return e<=t}function Th(e,t){return e>=t}function Je(e,t,i){let s=[],h=mr("{","}",e);if(!h)return [e];let n=h.pre,o=h.post.length?Je(h.post,t,false):[""];if(/\$$/.test(h.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+h.body+"}"+o[a];s.push(l);}else {let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(h.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(h.body),u=a||l,d=h.body.indexOf(",")>=0;if(!u&&!d)return h.post.match(/,(?!,).*\}/)?(e=h.pre+"{"+h.body+ys+h.post,Je(e,t,true)):[e];let f;if(u)f=h.body.split(/\.\./);else if(f=vr(h.body),f.length===1&&f[0]!==void 0&&(f=Je(f[0],t,false).map(Oh),f.length===1))return o.map(S=>h.pre+f[0]+S);let w;if(u&&f[0]!==void 0&&f[1]!==void 0){let S=Ki(f[0]),E=Ki(f[1]),b=Math.max(f[0].length,f[1].length),x=f.length===3&&f[2]!==void 0?Math.abs(Ki(f[2])):1,v=Fh;E<S&&(x*=-1,v=Th);let R=f.some(Ah);w=[];for(let A=S;v(A,E);A+=x){let T;if(l)T=String.fromCharCode(A),T==="\\"&&(T="");else if(T=String(A),R){let L=b-T.length;if(L>0){let F=new Array(L+1).join("0");A<0?T="-"+F+T.slice(1):T=F+T;}}w.push(T);}}else {w=[];for(let S=0;S<f.length;S++)w.push.apply(w,Je(f[S],t,false));}for(let S=0;S<w.length;S++)for(let E=0;E<o.length&&s.length<t;E++){let b=n+w[S]+o[E];(!i||u||b)&&s.push(b);}}return s}var $i=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},Lh={"[: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]},$e=e=>e.replace(/[[\]\\-]/g,"\\$&"),Mh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Rs=e=>e.join(""),Wh=(e,t)=>{let i=t;if(e.charAt(i)!=="[")throw new Error("not in a brace expression");let s=[],h=[],n=i+1,o=false,a=false,l=false,u=false,d=i,f="";t:for(;n<e.length;){let E=e.charAt(n);if((E==="!"||E==="^")&&n===i+1){u=true,n++;continue}if(E==="]"&&o&&!l){d=n+1;break}if(o=true,E==="\\"&&!l){l=true,n++;continue}if(E==="["&&!l){for(let[b,[x,v,R]]of Object.entries(Lh))if(e.startsWith(b,n)){if(f)return ["$.",false,e.length-i,true];n+=b.length,R?h.push(x):s.push(x),a=a||v;continue t}}if(l=false,f){E>f?s.push($e(f)+"-"+$e(E)):E===f&&s.push($e(E)),f="",n++;continue}if(e.startsWith("-]",n+1)){s.push($e(E+"-")),n+=2;continue}if(e.startsWith("-",n+1)){f=E,n+=2;continue}s.push($e(E)),n++;}if(d<n)return ["",false,0,false];if(!s.length&&!h.length)return ["$.",false,e.length-i,true];if(h.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!u){let E=s[0].length===2?s[0].slice(-1):s[0];return [Mh(E),false,d-i,false]}let w="["+(u?"^":"")+Rs(s)+"]",S="["+(u?"":"^")+Rs(h)+"]";return [s.length&&h.length?"("+w+"|"+S+")":s.length?w:S,a,d-i,true]},Ce=(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"),Ph=new Set(["!","?","+","*","@"]),Cs=e=>Ph.has(e),Dh="(?!(?:^|/)\\.\\.?(?:$|/))",ki="(?!\\.)",jh=new Set(["[","."]),Nh=new Set(["..","."]),zh=new Set("().*{}+?[]^$\\!"),_h=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),bs="[^/]",Os=bs+"*?",As=bs+"+?",U,V,$t,P,_,Qt,ue,te,Pt,pe,Qe,ve,xr,ne,X,Mi,rs,kr,Er=(X=class{constructor(t,i,s={}){c(this,ve);a(this,"type");c(this,U);c(this,V);c(this,$t,false);c(this,P,[]);c(this,_);c(this,Qt);c(this,ue);c(this,te,false);c(this,Pt);c(this,pe);c(this,Qe,false);this.type=t,t&&d(this,V,true),d(this,_,i),d(this,U,b(this,_)?b(b(this,_),U):this),d(this,Pt,b(this,U)===this?s:b(b(this,U),Pt)),d(this,ue,b(this,U)===this?[]:b(b(this,U),ue)),t==="!"&&!b(b(this,U),te)&&b(this,ue).push(this),d(this,Qt,b(this,_)?b(b(this,_),P).length:0);}get hasMagic(){if(b(this,V)!==void 0)return b(this,V);for(let t of b(this,P))if(typeof t!="string"&&(t.type||t.hasMagic))return d(this,V,true);return b(this,V)}toString(){return b(this,pe)!==void 0?b(this,pe):this.type?d(this,pe,this.type+"("+b(this,P).map(t=>String(t)).join("|")+")"):d(this,pe,b(this,P).map(t=>String(t)).join(""))}push(...t){for(let i of t)if(i!==""){if(typeof i!="string"&&!(i instanceof X&&b(i,_)===this))throw new Error("invalid part: "+i);b(this,P).push(i);}}toJSON(){let t=this.type===null?b(this,P).slice().map(i=>typeof i=="string"?i:i.toJSON()):[this.type,...b(this,P).map(i=>i.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===b(this,U)||b(b(this,U),te)&&b(this,_)?.type==="!")&&t.push({}),t}isStart(){if(b(this,U)===this)return true;if(!b(this,_)?.isStart())return false;if(b(this,Qt)===0)return true;let t=b(this,_);for(let i=0;i<b(this,Qt);i++){let s=b(t,P)[i];if(!(s instanceof X&&s.type==="!"))return false}return true}isEnd(){if(b(this,U)===this||b(this,_)?.type==="!")return true;if(!b(this,_)?.isEnd())return false;if(!this.type)return b(this,_)?.isEnd();let t=b(this,_)?b(b(this,_),P).length:0;return b(this,Qt)===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 b(this,P))i.copyIn(s);return i}static fromGlob(t,i={}){var h;let s=new X(null,void 0,i);return e(h=X,ne,Mi).call(h,t,s,0,i),s}toMMPattern(){if(this!==b(this,U))return b(this,U).toMMPattern();let t=this.toString(),[i,s,h,n]=this.toRegExpSource();if(!(h||b(this,V)||b(this,Pt).nocase&&!b(this,Pt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let o=(b(this,Pt).nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${i}$`,o),{_src:i,_glob:t})}get options(){return b(this,Pt)}toRegExpSource(t){let i=t??!!b(this,Pt).dot;if(b(this,U)===this&&e(this,ve,xr).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!b(this,P).some(w=>typeof w!="string"),u=b(this,P).map(w=>{var v;let[S,E,b$1,x]=typeof w=="string"?e(v=X,ne,kr).call(v,w,b(this,V),l):w.toRegExpSource(t);return d(this,V,b(this,V)||b$1),d(this,$t,b(this,$t)||x),S}).join(""),d$1="";if(this.isStart()&&typeof b(this,P)[0]=="string"&&!(b(this,P).length===1&&Nh.has(b(this,P)[0]))){let w=jh,S=i&&w.has(u.charAt(0))||u.startsWith("\\.")&&w.has(u.charAt(2))||u.startsWith("\\.\\.")&&w.has(u.charAt(4)),E=!i&&!t&&w.has(u.charAt(0));d$1=S?Dh:E?ki:"";}let f="";return this.isEnd()&&b(b(this,U),te)&&b(this,_)?.type==="!"&&(f="(?:$|\\/)"),[d$1+u+f,Ce(u),d(this,V,!!b(this,V)),b(this,$t)]}let s=this.type==="*"||this.type==="+",h=this.type==="!"?"(?:(?!(?:":"(?:",n=e(this,ve,rs).call(this,i);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return d(this,P,[l]),this.type=null,d(this,V,void 0),[l,Ce(this.toString()),false,false]}let o=!s||t||i||!ki?"":e(this,ve,rs).call(this,true);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&b(this,Qe))a=(this.isStart()&&!i?ki:"")+As;else {let l=this.type==="!"?"))"+(this.isStart()&&!i&&!t?ki:"")+Os+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=h+n+l;}return [a,Ce(n),d(this,V,!!b(this,V)),b(this,$t)]}},U=new WeakMap,V=new WeakMap,$t=new WeakMap,P=new WeakMap,_=new WeakMap,Qt=new WeakMap,ue=new WeakMap,te=new WeakMap,Pt=new WeakMap,pe=new WeakMap,Qe=new WeakMap,ve=new WeakSet,xr=function(){if(this!==b(this,U))throw new Error("should only call on root");if(b(this,te))return this;this.toString(),d(this,te,true);let t;for(;t=b(this,ue).pop();){if(t.type!=="!")continue;let i=t,s=b(i,_);for(;s;){for(let h=b(i,Qt)+1;!s.type&&h<b(s,P).length;h++)for(let n of b(t,P)){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(b(s,P)[h]);}i=s,s=b(i,_);}}return this},ne=new WeakSet,Mi=function(t,i,s,h){var S,E;let n=false,o=false,a=-1,l=false;if(i.type===null){let b=s,x="";for(;b<t.length;){let v=t.charAt(b++);if(n||v==="\\"){n=!n,x+=v;continue}if(o){b===a+1?(v==="^"||v==="!")&&(l=true):v==="]"&&!(b===a+2&&l)&&(o=false),x+=v;continue}else if(v==="["){o=true,a=b,l=false,x+=v;continue}if(!h.noext&&Cs(v)&&t.charAt(b)==="("){i.push(x),x="";let R=new X(v,i);b=e(S=X,ne,Mi).call(S,t,R,b,h),i.push(R);continue}x+=v;}return i.push(x),b}let u=s+1,d$1=new X(null,i),f=[],w="";for(;u<t.length;){let b$1=t.charAt(u++);if(n||b$1==="\\"){n=!n,w+=b$1;continue}if(o){u===a+1?(b$1==="^"||b$1==="!")&&(l=true):b$1==="]"&&!(u===a+2&&l)&&(o=false),w+=b$1;continue}else if(b$1==="["){o=true,a=u,l=false,w+=b$1;continue}if(Cs(b$1)&&t.charAt(u)==="("){d$1.push(w),w="";let x=new X(b$1,d$1);d$1.push(x),u=e(E=X,ne,Mi).call(E,t,x,u,h);continue}if(b$1==="|"){d$1.push(w),w="",f.push(d$1),d$1=new X(null,i);continue}if(b$1===")")return w===""&&b(i,P).length===0&&d(i,Qe,true),d$1.push(w),w="",i.push(...f,d$1),u;w+=b$1;}return i.type=null,d(i,V,void 0),d(i,P,[t.substring(s-1)]),u},rs=function(t){return b(this,P).map(i=>{if(typeof i=="string")throw new Error("string type in extglob ast??");let[s,h,n,o]=i.toRegExpSource(t);return d(this,$t,b(this,$t)||o),s}).filter(i=>!(this.isStart()&&this.isEnd())||!!i).join("|")},kr=function(t,i,s=false){let h=false,n="",o=false,a=false;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(h){h=false,n+=(zh.has(u)?"\\":"")+u;continue}if(u==="*"){if(a)continue;a=true,n+=s&&/^[*]+$/.test(t)?As:Os,i=true;continue}else a=false;if(u==="\\"){l===t.length-1?n+="\\\\":h=true;continue}if(u==="["){let[d,f,w,S]=Wh(t,l);if(w){n+=d,o=o||f,l+=w-1,i=i||S;continue}}if(u==="?"){n+=bs,i=true;continue}n+=_h(u);}return [n,Ce(t),!!i,o]},c(X,ne),X),Rr=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=false}={})=>i?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),nt=(e,t,i={})=>($i(t),!i.nocomment&&t.charAt(0)==="#"?false:new oe(t,i).match(e)),$h=/^\*+([^+@!?\*\[\(]*)$/,Bh=e=>t=>!t.startsWith(".")&&t.endsWith(e),Uh=e=>t=>t.endsWith(e),Gh=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),Ih=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Hh=/^\*+\.\*+$/,Jh=e=>!e.startsWith(".")&&e.includes("."),qh=e=>e!=="."&&e!==".."&&e.includes("."),Zh=/^\.\*+$/,Vh=e=>e!=="."&&e!==".."&&e.startsWith("."),Kh=/^\*+$/,Yh=e=>e.length!==0&&!e.startsWith("."),Xh=e=>e.length!==0&&e!=="."&&e!=="..",Qh=/^\?+([^+@!?\*\[\(]*)?$/,tn=([e,t=""])=>{let i=Cr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},en=([e,t=""])=>{let i=Or([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},sn=([e,t=""])=>{let i=Or([e]);return t?s=>i(s)&&s.endsWith(t):i},rn=([e,t=""])=>{let i=Cr([e]);return t?s=>i(s)&&s.endsWith(t):i},Cr=([e])=>{let t=e.length;return i=>i.length===t&&!i.startsWith(".")},Or=([e])=>{let t=e.length;return i=>i.length===t&&i!=="."&&i!==".."},Ar=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Fs={win32:{sep:"\\"},posix:{sep:"/"}},hn=Ar==="win32"?Fs.win32.sep:Fs.posix.sep;nt.sep=hn;var ht=Symbol("globstar **");nt.GLOBSTAR=ht;var nn="[^/]",on=nn+"*?",an="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",ln="(?:(?!(?:\\/|^)\\.).)*?",cn=(e,t={})=>i=>nt(i,e,t);nt.filter=cn;var mt=(e,t={})=>Object.assign({},e,t),un=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return nt;let t=nt;return Object.assign((i,s,h={})=>t(i,s,mt(e,h)),{Minimatch:class extends t.Minimatch{constructor(i,s={}){super(i,mt(e,s));}static defaults(i){return t.defaults(mt(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,s,h={}){super(i,s,mt(e,h));}static fromGlob(i,s={}){return t.AST.fromGlob(i,mt(e,s))}},unescape:(i,s={})=>t.unescape(i,mt(e,s)),escape:(i,s={})=>t.escape(i,mt(e,s)),filter:(i,s={})=>t.filter(i,mt(e,s)),defaults:i=>t.defaults(mt(e,i)),makeRe:(i,s={})=>t.makeRe(i,mt(e,s)),braceExpand:(i,s={})=>t.braceExpand(i,mt(e,s)),match:(i,s,h={})=>t.match(i,s,mt(e,h)),sep:t.sep,GLOBSTAR:ht})};nt.defaults=un;var Fr=(e,t={})=>($i(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Ch(e,{max:t.braceExpandMax}));nt.braceExpand=Fr;var pn=(e,t={})=>new oe(e,t).makeRe();nt.makeRe=pn;var fn=(e,t,i={})=>{let s=new oe(t,i);return e=e.filter(h=>s.match(h)),s.options.nonull&&!e.length&&e.push(t),e};nt.match=fn;var Ts=/[?*]|[+@!]\(.*?\)|\[|\]/,dn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),oe=class{constructor(e,t={}){a(this,"options");a(this,"set");a(this,"pattern");a(this,"windowsPathsNoEscape");a(this,"nonegate");a(this,"negate");a(this,"comment");a(this,"empty");a(this,"preserveMultipleSlashes");a(this,"partial");a(this,"globSet");a(this,"globParts");a(this,"nocase");a(this,"isWindows");a(this,"platform");a(this,"windowsNoMagicRoot");a(this,"regexp");$i(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Ar,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=(...h)=>console.error(...h)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(h=>this.slashSplit(h));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let s=this.globParts.map((h,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=h[0]===""&&h[1]===""&&(h[2]==="?"||!Ts.test(h[2]))&&!Ts.test(h[3]),l=/^[a-z]:/i.test(h[0]);if(a)return [...h.slice(0,4),...h.slice(4).map(u=>this.parse(u))];if(l)return [h[0],...h.slice(1).map(u=>this.parse(u))]}return h.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(h=>h.indexOf(false)===-1),this.isWindows)for(let h=0;h<this.set.length;h++){let n=this.set[h];n[0]===""&&n[1]===""&&this.globParts[h][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[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 h=i[i.length-1];return s==="**"&&h==="**"?i:s===".."&&h&&h!==".."&&h!=="."&&h!=="**"?(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 h=e[s];s===1&&h===""&&e[0]===""||(h==="."||h==="")&&(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 n=s;for(;i[n+1]==="**";)n++;n>s&&i.splice(s+1,n-s);let o=i[s+1],a=i[s+2],l=i[s+3];if(o!==".."||!a||a==="."||a===".."||!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 n=1;n<i.length-1;n++){let o=i[n];n===1&&o===""&&i[0]===""||(o==="."||o==="")&&(t=true,i.splice(n,1),n--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let h=0;for(;(h=i.indexOf("..",h+1))!==-1;){let n=i[h-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=true;let o=h===1&&i[h+1]==="**"?["."]:[];i.splice(h-1,2,...o),i.length===0&&i.push(""),h-=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,h=0,n=[],o="";for(;s<e.length&&h<t.length;)if(e[s]===t[h])n.push(o==="b"?t[h]:e[s]),s++,h++;else if(i&&e[s]==="**"&&t[h]===e[s+1])n.push(e[s]),s++;else if(i&&t[h]==="**"&&e[s]===t[h+1])n.push(t[h]),h++;else if(e[s]==="*"&&t[h]&&(this.options.dot||!t[h].startsWith("."))&&t[h]!=="**"){if(o==="b")return false;o="a",n.push(e[s]),s++,h++;}else if(t[h]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return false;o="b",n.push(t[h]),s++,h++;}else return false;return e.length===t.length&&n}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 E=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),b=!E&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),x=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),v=!x&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),R=b?3:E?0:void 0,A=v?3:x?0:void 0;if(typeof R=="number"&&typeof A=="number"){let[T,L]=[e[R],t[A]];T.toLowerCase()===L.toLowerCase()&&(t[A]=T,A>R?t=t.slice(A):R>A&&(e=e.slice(R)));}}let{optimizationLevel:h=1}=this.options;h>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var u=t[o],d=e[n];if(this.debug(t,u,d),u===false)return false;if(u===ht){this.debug("GLOBSTAR",[t,u,d]);var f=n,w=o+1;if(w===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return false;return true}for(;f<a;){var S=e[f];if(this.debug(`
2
- globstar while`,e,f,t,w,S),this.matchOne(e.slice(f),t.slice(w),i))return this.debug("globstar found match!",f,a,S),true;if(S==="."||S===".."||!s.dot&&S.charAt(0)==="."){this.debug("dot detected!",e,f,t,w);break}this.debug("globstar swallow a segment, and continue"),f++;}return !!(i&&(this.debug(`
3
- >>> no match, partial?`,e,f,t,w),f===a))}let E;if(typeof u=="string"?(E=d===u,this.debug("string match",u,d,E)):(E=u.test(d),this.debug("pattern match",u,d,E)),!E)return false}if(n===a&&o===l)return true;if(n===a)return i;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Fr(this.pattern,this.options)}parse(e){$i(e);let t=this.options;if(e==="**")return ht;if(e==="")return "";let i,s=null;(i=e.match(Kh))?s=t.dot?Xh:Yh:(i=e.match($h))?s=(t.nocase?t.dot?Ih:Gh:t.dot?Uh:Bh)(i[1]):(i=e.match(Qh))?s=(t.nocase?t.dot?en:tn:t.dot?sn:rn)(i):(i=e.match(Hh))?s=t.dot?qh:Jh:(i=e.match(Zh))&&(s=Vh);let h=Er.fromGlob(e,this.options).toMMPattern();return s&&typeof h=="object"&&Reflect.defineProperty(h,"test",{value:s}),h}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?on:t.dot?an:ln,s=new Set(t.nocase?["i"]:[]),h=e.map(a=>{let l=a.map(d=>{if(d instanceof RegExp)for(let f of d.flags.split(""))s.add(f);return typeof d=="string"?dn(d):d===ht?ht:d._src});l.forEach((d,f)=>{let w=l[f+1],S=l[f-1];d!==ht||S===ht||(S===void 0?w!==void 0&&w!==ht?l[f+1]="(?:\\/|"+i+"\\/)?"+w:l[f]=i:w===void 0?l[f-1]=S+"(?:\\/|\\/"+i+")?":w!==ht&&(l[f-1]=S+"(?:\\/|\\/"+i+"\\/)"+w,l[f+1]=ht));});let u=l.filter(d=>d!==ht);if(this.partial&&u.length>=1){let d=[];for(let f=1;f<=u.length;f++)d.push(u.slice(0,f).join("/"));return "(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];h="^"+n+h+o+"$",this.partial&&(h="^(?:\\/|"+n+h.slice(1,-1)+o+")$"),this.negate&&(h="^(?!"+h+").+$");try{this.regexp=new RegExp(h,[...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 h=this.set;this.debug(this.pattern,"set",h);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<h.length;o++){let a=h[o],l=s;if(i.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return i.flipNegate?true:!this.negate}return i.flipNegate?false:this.negate}static defaults(e){return nt.defaults(e).Minimatch}};nt.AST=Er;nt.Minimatch=oe;nt.escape=Rr;nt.unescape=Ce;var mn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Tr=new Set,hs=typeof process=="object"&&process?process:{},Lr=(e,t,i,s)=>{typeof hs.emitWarning=="function"?hs.emitWarning(e,t,i,s):console.error(`[${i}] ${t}: ${e}`);},Bi=globalThis.AbortController,Ls=globalThis.AbortSignal;if(typeof Bi>"u"){Ls=class{constructor(){a(this,"onabort");a(this,"_onabort",[]);a(this,"reason");a(this,"aborted",false);}addEventListener(i,s){this._onabort.push(s);}},Bi=class{constructor(){a(this,"signal",new Ls);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=hs.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=false,Lr("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 wn=e=>!Tr.has(e),Vt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Mr=e=>Vt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Wi:null:null,Wi=class extends Array{constructor(e){super(e),this.fill(0);}},Nt,Oe,yn=(Nt=class{constructor(t,i){a(this,"heap");a(this,"length");if(!b(Nt,Oe))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(t),this.length=0;}static create(t){let i=Mr(t);if(!i)return [];d(Nt,Oe,true);let s=new Nt(t,i);return d(Nt,Oe,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Oe=new WeakMap,c(Nt,Oe,false),Nt),Js,qs,yt,ut,xt,fe,kt,Ae,Fe,Rt,G,Ct,$,D,O,it,pt,tt,K,Ot,Y,At,Ft,ft,dt,Tt,ee,st,Te,y,ns,de,Bt,ti,gt,Wr,ge,Le,ei,Kt,Yt,os,Pi,Di,W,as,qe,Xt,ls,Me,Ii=(Me=class{constructor(t){c(this,y);c(this,yt);c(this,ut);c(this,xt);c(this,fe);c(this,kt);c(this,Ae);c(this,Fe);c(this,Rt);a(this,"ttl");a(this,"ttlResolution");a(this,"ttlAutopurge");a(this,"updateAgeOnGet");a(this,"updateAgeOnHas");a(this,"allowStale");a(this,"noDisposeOnSet");a(this,"noUpdateTTL");a(this,"maxEntrySize");a(this,"sizeCalculation");a(this,"noDeleteOnFetchRejection");a(this,"noDeleteOnStaleGet");a(this,"allowStaleOnFetchAbort");a(this,"allowStaleOnFetchRejection");a(this,"ignoreFetchAbort");c(this,G);c(this,Ct);c(this,$);c(this,D);c(this,O);c(this,it);c(this,pt);c(this,tt);c(this,K);c(this,Ot);c(this,Y);c(this,At);c(this,Ft);c(this,ft);c(this,dt);c(this,Tt);c(this,ee);c(this,st);c(this,Te);c(this,de,()=>{});c(this,Bt,()=>{});c(this,ti,()=>{});c(this,gt,()=>false);c(this,ge,t=>{});c(this,Le,(t,i,s)=>{});c(this,ei,(t,i,s,h)=>{if(s||h)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});a(this,Js,"LRUCache");let{max:i=0,ttl:s,ttlResolution:h=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a$1,allowStale:l,dispose:u,onInsert:d$1,disposeAfter:f,noDisposeOnSet:w,noUpdateTTL:S,maxSize:E=0,maxEntrySize:b$1=0,sizeCalculation:x,fetchMethod:v,memoMethod:R,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:T,allowStaleOnFetchRejection:L,allowStaleOnFetchAbort:F,ignoreFetchAbort:j,perf:N}=t;if(N!==void 0&&typeof N?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(d(this,Rt,N??mn),i!==0&&!Vt(i))throw new TypeError("max option must be a nonnegative integer");let B=i?Mr(i):Array;if(!B)throw new Error("invalid max value: "+i);if(d(this,yt,i),d(this,ut,E),this.maxEntrySize=b$1||b(this,ut),this.sizeCalculation=x,this.sizeCalculation){if(!b(this,ut)&&!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(R!==void 0&&typeof R!="function")throw new TypeError("memoMethod must be a function if defined");if(d(this,Fe,R),v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(d(this,Ae,v),d(this,ee,!!v),d(this,$,new Map),d(this,D,new Array(i).fill(void 0)),d(this,O,new Array(i).fill(void 0)),d(this,it,new B(i)),d(this,pt,new B(i)),d(this,tt,0),d(this,K,0),d(this,Ot,yn.create(i)),d(this,G,0),d(this,Ct,0),typeof u=="function"&&d(this,xt,u),typeof d$1=="function"&&d(this,fe,d$1),typeof f=="function"?(d(this,kt,f),d(this,Y,[])):(d(this,kt,void 0),d(this,Y,void 0)),d(this,Tt,!!b(this,xt)),d(this,Te,!!b(this,fe)),d(this,st,!!b(this,kt)),this.noDisposeOnSet=!!w,this.noUpdateTTL=!!S,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!L,this.allowStaleOnFetchAbort=!!F,this.ignoreFetchAbort=!!j,this.maxEntrySize!==0){if(b(this,ut)!==0&&!Vt(b(this,ut)))throw new TypeError("maxSize must be a positive integer if specified");if(!Vt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");e(this,y,Wr).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!T,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a$1,this.ttlResolution=Vt(h)||h===0?h:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!Vt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");e(this,y,ns).call(this);}if(b(this,yt)===0&&this.ttl===0&&b(this,ut)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!b(this,yt)&&!b(this,ut)){let M="LRU_CACHE_UNBOUNDED";wn(M)&&(Tr.add(M),Lr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",M,Me));}}get perf(){return b(this,Rt)}static unsafeExposeInternals(t){return {starts:b(t,Ft),ttls:b(t,ft),autopurgeTimers:b(t,dt),sizes:b(t,At),keyMap:b(t,$),keyList:b(t,D),valList:b(t,O),next:b(t,it),prev:b(t,pt),get head(){return b(t,tt)},get tail(){return b(t,K)},free:b(t,Ot),isBackgroundFetch:i=>{var s;return e(s=t,y,W).call(s,i)},backgroundFetch:(i,s,h,n)=>{var o;return e(o=t,y,Di).call(o,i,s,h,n)},moveToTail:i=>{var s;return e(s=t,y,qe).call(s,i)},indexes:i=>{var s;return e(s=t,y,Kt).call(s,i)},rindexes:i=>{var s;return e(s=t,y,Yt).call(s,i)},isStale:i=>{var s;return b(s=t,gt).call(s,i)}}}get max(){return b(this,yt)}get maxSize(){return b(this,ut)}get calculatedSize(){return b(this,Ct)}get size(){return b(this,G)}get fetchMethod(){return b(this,Ae)}get memoMethod(){return b(this,Fe)}get dispose(){return b(this,xt)}get onInsert(){return b(this,fe)}get disposeAfter(){return b(this,kt)}getRemainingTTL(t){return b(this,$).has(t)?1/0:0}*entries(){for(let t of e(this,y,Kt).call(this))b(this,O)[t]!==void 0&&b(this,D)[t]!==void 0&&!e(this,y,W).call(this,b(this,O)[t])&&(yield [b(this,D)[t],b(this,O)[t]]);}*rentries(){for(let t of e(this,y,Yt).call(this))b(this,O)[t]!==void 0&&b(this,D)[t]!==void 0&&!e(this,y,W).call(this,b(this,O)[t])&&(yield [b(this,D)[t],b(this,O)[t]]);}*keys(){for(let t of e(this,y,Kt).call(this)){let i=b(this,D)[t];i!==void 0&&!e(this,y,W).call(this,b(this,O)[t])&&(yield i);}}*rkeys(){for(let t of e(this,y,Yt).call(this)){let i=b(this,D)[t];i!==void 0&&!e(this,y,W).call(this,b(this,O)[t])&&(yield i);}}*values(){for(let t of e(this,y,Kt).call(this))b(this,O)[t]!==void 0&&!e(this,y,W).call(this,b(this,O)[t])&&(yield b(this,O)[t]);}*rvalues(){for(let t of e(this,y,Yt).call(this))b(this,O)[t]!==void 0&&!e(this,y,W).call(this,b(this,O)[t])&&(yield b(this,O)[t]);}[(qs=Symbol.iterator,Js=Symbol.toStringTag,qs)](){return this.entries()}find(t,i={}){for(let s of e(this,y,Kt).call(this)){let h=b(this,O)[s],n=e(this,y,W).call(this,h)?h.__staleWhileFetching:h;if(n!==void 0&&t(n,b(this,D)[s],this))return this.get(b(this,D)[s],i)}}forEach(t,i=this){for(let s of e(this,y,Kt).call(this)){let h=b(this,O)[s],n=e(this,y,W).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,b(this,D)[s],this);}}rforEach(t,i=this){for(let s of e(this,y,Yt).call(this)){let h=b(this,O)[s],n=e(this,y,W).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,b(this,D)[s],this);}}purgeStale(){let t=false;for(let i of e(this,y,Yt).call(this,{allowStale:true}))b(this,gt).call(this,i)&&(e(this,y,Xt).call(this,b(this,D)[i],"expire"),t=true);return t}info(t){let i=b(this,$).get(t);if(i===void 0)return;let s=b(this,O)[i],h=e(this,y,W).call(this,s)?s.__staleWhileFetching:s;if(h===void 0)return;let n={value:h};if(b(this,ft)&&b(this,Ft)){let o=b(this,ft)[i],a=b(this,Ft)[i];if(o&&a){let l=o-(b(this,Rt).now()-a);n.ttl=l,n.start=Date.now();}}return b(this,At)&&(n.size=b(this,At)[i]),n}dump(){let t=[];for(let i of e(this,y,Kt).call(this,{allowStale:true})){let s=b(this,D)[i],h=b(this,O)[i],n=e(this,y,W).call(this,h)?h.__staleWhileFetching:h;if(n===void 0||s===void 0)continue;let o={value:n};if(b(this,ft)&&b(this,Ft)){o.ttl=b(this,ft)[i];let a=b(this,Rt).now()-b(this,Ft)[i];o.start=Math.floor(Date.now()-a);}b(this,At)&&(o.size=b(this,At)[i]),t.unshift([s,o]);}return t}load(t){this.clear();for(let[i,s]of t){if(s.start){let h=Date.now()-s.start;s.start=b(this,Rt).now()-h;}this.set(i,s.value,s);}}set(t,i,s={}){var w,S,E,b$1;if(i===void 0)return this.delete(t),this;let{ttl:h=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:u=this.noUpdateTTL}=s,d$1=b(this,ei).call(this,t,i,s.size||0,a);if(this.maxEntrySize&&d$1>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),e(this,y,Xt).call(this,t,"set"),this;let f$1=b(this,G)===0?void 0:b(this,$).get(t);if(f$1===void 0)f$1=b(this,G)===0?b(this,K):b(this,Ot).length!==0?b(this,Ot).pop():b(this,G)===b(this,yt)?e(this,y,Pi).call(this,false):b(this,G),b(this,D)[f$1]=t,b(this,O)[f$1]=i,b(this,$).set(t,f$1),b(this,it)[b(this,K)]=f$1,b(this,pt)[f$1]=b(this,K),d(this,K,f$1),f(this,G)._++,b(this,Le).call(this,f$1,d$1,l),l&&(l.set="add"),u=false,b(this,Te)&&((w=b(this,fe))==null||w.call(this,i,t,"add"));else {e(this,y,qe).call(this,f$1);let x=b(this,O)[f$1];if(i!==x){if(b(this,ee)&&e(this,y,W).call(this,x)){x.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:v}=x;v!==void 0&&!o&&(b(this,Tt)&&((S=b(this,xt))==null||S.call(this,v,t,"set")),b(this,st)&&b(this,Y)?.push([v,t,"set"]));}else o||(b(this,Tt)&&((E=b(this,xt))==null||E.call(this,x,t,"set")),b(this,st)&&b(this,Y)?.push([x,t,"set"]));if(b(this,ge).call(this,f$1),b(this,Le).call(this,f$1,d$1,l),b(this,O)[f$1]=i,l){l.set="replace";let v=x&&e(this,y,W).call(this,x)?x.__staleWhileFetching:x;v!==void 0&&(l.oldValue=v);}}else l&&(l.set="update");b(this,Te)&&this.onInsert?.(i,t,i===x?"update":"replace");}if(h!==0&&!b(this,ft)&&e(this,y,ns).call(this),b(this,ft)&&(u||b(this,ti).call(this,f$1,h,n),l&&b(this,Bt).call(this,l,f$1)),!o&&b(this,st)&&b(this,Y)){let x=b(this,Y),v;for(;v=x?.shift();)(b$1=b(this,kt))==null||b$1.call(this,...v);}return this}pop(){var t;try{for(;b(this,G);){let i=b(this,O)[b(this,tt)];if(e(this,y,Pi).call(this,!0),e(this,y,W).call(this,i)){if(i.__staleWhileFetching)return i.__staleWhileFetching}else if(i!==void 0)return i}}finally{if(b(this,st)&&b(this,Y)){let i=b(this,Y),s;for(;s=i?.shift();)(t=b(this,kt))==null||t.call(this,...s);}}}has(t,i={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:h}=i,n=b(this,$).get(t);if(n!==void 0){let o=b(this,O)[n];if(e(this,y,W).call(this,o)&&o.__staleWhileFetching===void 0)return false;if(b(this,gt).call(this,n))h&&(h.has="stale",b(this,Bt).call(this,h,n));else return s&&b(this,de).call(this,n),h&&(h.has="hit",b(this,Bt).call(this,h,n)),true}else h&&(h.has="miss");return false}peek(t,i={}){let{allowStale:s=this.allowStale}=i,h=b(this,$).get(t);if(h===void 0||!s&&b(this,gt).call(this,h))return;let n=b(this,O)[h];return e(this,y,W).call(this,n)?n.__staleWhileFetching:n}async fetch(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:w=this.allowStaleOnFetchRejection,ignoreFetchAbort:S=this.ignoreFetchAbort,allowStaleOnFetchAbort:E=this.allowStaleOnFetchAbort,context:b$1,forceRefresh:x=false,status:v,signal:R}=i;if(!b(this,ee))return v&&(v.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,status:v});let A={allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:E,ignoreFetchAbort:S,status:v,signal:R},T=b(this,$).get(t);if(T===void 0){v&&(v.fetch="miss");let L=e(this,y,Di).call(this,t,T,A,b$1);return L.__returned=L}else {let L=b(this,O)[T];if(e(this,y,W).call(this,L)){let B=s&&L.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",B&&(v.returnedStale=true)),B?L.__staleWhileFetching:L.__returned=L}let F=b(this,gt).call(this,T);if(!x&&!F)return v&&(v.fetch="hit"),e(this,y,qe).call(this,T),h&&b(this,de).call(this,T),v&&b(this,Bt).call(this,v,T),L;let j=e(this,y,Di).call(this,t,T,A,b$1),N=j.__staleWhileFetching!==void 0&&s;return v&&(v.fetch=F?"stale":"refresh",N&&F&&(v.returnedStale=true)),N?j.__staleWhileFetching:j.__returned=j}}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=b(this,Fe);if(!s)throw new Error("no memoMethod provided to constructor");let{context:h,forceRefresh:n,...o}=i,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:h});return this.set(t,l,o),l}get(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=i,a=b(this,$).get(t);if(a!==void 0){let l=b(this,O)[a],u=e(this,y,W).call(this,l);return o&&b(this,Bt).call(this,o,a),b(this,gt).call(this,a)?(o&&(o.get="stale"),u?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),s?l.__staleWhileFetching:void 0):(n||e(this,y,Xt).call(this,t,"expire"),o&&s&&(o.returnedStale=true),s?l:void 0)):(o&&(o.get="hit"),u?l.__staleWhileFetching:(e(this,y,qe).call(this,a),h&&b(this,de).call(this,a),l))}else o&&(o.get="miss");}delete(t){return e(this,y,Xt).call(this,t,"delete")}clear(){return e(this,y,ls).call(this,"delete")}},yt=new WeakMap,ut=new WeakMap,xt=new WeakMap,fe=new WeakMap,kt=new WeakMap,Ae=new WeakMap,Fe=new WeakMap,Rt=new WeakMap,G=new WeakMap,Ct=new WeakMap,$=new WeakMap,D=new WeakMap,O=new WeakMap,it=new WeakMap,pt=new WeakMap,tt=new WeakMap,K=new WeakMap,Ot=new WeakMap,Y=new WeakMap,At=new WeakMap,Ft=new WeakMap,ft=new WeakMap,dt=new WeakMap,Tt=new WeakMap,ee=new WeakMap,st=new WeakMap,Te=new WeakMap,y=new WeakSet,ns=function(){let t=new Wi(b(this,yt)),i=new Wi(b(this,yt));d(this,ft,t),d(this,Ft,i);let s=this.ttlAutopurge?new Array(b(this,yt)):void 0;d(this,dt,s),d(this,ti,(o,a,l=b(this,Rt).now())=>{if(i[o]=a!==0?l:0,t[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let u=setTimeout(()=>{b(this,gt).call(this,o)&&e(this,y,Xt).call(this,b(this,D)[o],"expire");},a+1);u.unref&&u.unref(),s[o]=u;}}),d(this,de,o=>{i[o]=t[o]!==0?b(this,Rt).now():0;}),d(this,Bt,(o,a)=>{if(t[a]){let l=t[a],u=i[a];if(!l||!u)return;o.ttl=l,o.start=u,o.now=h||n();let d=o.now-u;o.remainingTTL=l-d;}});let h=0,n=()=>{let o=b(this,Rt).now();if(this.ttlResolution>0){h=o;let a=setTimeout(()=>h=0,this.ttlResolution);a.unref&&a.unref();}return o};this.getRemainingTTL=o=>{let a=b(this,$).get(o);if(a===void 0)return 0;let l=t[a],u=i[a];if(!l||!u)return 1/0;let d=(h||n())-u;return l-d},d(this,gt,o=>{let a=i[o],l=t[o];return !!l&&!!a&&(h||n())-a>l});},de=new WeakMap,Bt=new WeakMap,ti=new WeakMap,gt=new WeakMap,Wr=function(){let t=new Wi(b(this,yt));d(this,Ct,0),d(this,At,t),d(this,ge,i=>{d(this,Ct,b(this,Ct)-t[i]),t[i]=0;}),d(this,ei,(i,s,h,n)=>{if(e(this,y,W).call(this,s))return 0;if(!Vt(h))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(h=n(s,i),!Vt(h))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 h}),d(this,Le,(i,s,h)=>{if(t[i]=s,b(this,ut)){let n=b(this,ut)-t[i];for(;b(this,Ct)>n;)e(this,y,Pi).call(this,true);}d(this,Ct,b(this,Ct)+t[i]),h&&(h.entrySize=s,h.totalCalculatedSize=b(this,Ct));});},ge=new WeakMap,Le=new WeakMap,ei=new WeakMap,Kt=function*({allowStale:t=this.allowStale}={}){if(b(this,G))for(let i=b(this,K);!(!e(this,y,os).call(this,i)||((t||!b(this,gt).call(this,i))&&(yield i),i===b(this,tt)));)i=b(this,pt)[i];},Yt=function*({allowStale:t=this.allowStale}={}){if(b(this,G))for(let i=b(this,tt);!(!e(this,y,os).call(this,i)||((t||!b(this,gt).call(this,i))&&(yield i),i===b(this,K)));)i=b(this,it)[i];},os=function(t){return t!==void 0&&b(this,$).get(b(this,D)[t])===t},Pi=function(t){var n;let i=b(this,tt),s=b(this,D)[i],h=b(this,O)[i];return b(this,ee)&&e(this,y,W).call(this,h)?h.__abortController.abort(new Error("evicted")):(b(this,Tt)||b(this,st))&&(b(this,Tt)&&((n=b(this,xt))==null||n.call(this,h,s,"evict")),b(this,st)&&b(this,Y)?.push([h,s,"evict"])),b(this,ge).call(this,i),b(this,dt)?.[i]&&(clearTimeout(b(this,dt)[i]),b(this,dt)[i]=void 0),t&&(b(this,D)[i]=void 0,b(this,O)[i]=void 0,b(this,Ot).push(i)),b(this,G)===1?(d(this,tt,d(this,K,0)),b(this,Ot).length=0):d(this,tt,b(this,it)[i]),b(this,$).delete(s),f(this,G)._--,i},Di=function(t,i,s,h){let n=i===void 0?void 0:b(this,O)[i];if(e(this,y,W).call(this,n))return n;let o=new Bi,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:h},u=(b$1,x=false)=>{let{aborted:v}=o.signal,R=s.ignoreFetchAbort&&b$1!==void 0,A=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&b$1!==void 0);if(s.status&&(v&&!x?(s.status.fetchAborted=true,s.status.fetchError=o.signal.reason,R&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),v&&!R&&!x)return f(o.signal.reason,A);let T=S,L=b(this,O)[i];return (L===S||R&&x&&L===void 0)&&(b$1===void 0?T.__staleWhileFetching!==void 0?b(this,O)[i]=T.__staleWhileFetching:e(this,y,Xt).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,b$1,l.options))),b$1},d=b=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=b),f(b,false)),f=(b$1,x)=>{let{aborted:v}=o.signal,R=v&&s.allowStaleOnFetchAbort,A=R||s.allowStaleOnFetchRejection,T=A||s.noDeleteOnFetchRejection,L=S;if(b(this,O)[i]===S&&(!T||!x&&L.__staleWhileFetching===void 0?e(this,y,Xt).call(this,t,"fetch"):R||(b(this,O)[i]=L.__staleWhileFetching)),A)return s.status&&L.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),L.__staleWhileFetching;if(L.__returned===L)throw b$1},w=(b$1,x)=>{var R;let v=(R=b(this,Ae))==null?void 0:R.call(this,t,n,l);v&&v instanceof Promise&&v.then(A=>b$1(A===void 0?void 0:A),x),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(b$1(void 0),s.allowStaleOnFetchAbort&&(b$1=A=>u(A,true)));});};s.status&&(s.status.fetchDispatched=true);let S=new Promise(w).then(u,d),E=Object.assign(S,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return i===void 0?(this.set(t,E,{...l.options,status:void 0}),i=b(this,$).get(t)):b(this,O)[i]=E,E},W=function(t){if(!b(this,ee))return false;let i=t;return !!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof Bi},as=function(t,i){b(this,pt)[i]=t,b(this,it)[t]=i;},qe=function(t){t!==b(this,K)&&(t===b(this,tt)?d(this,tt,b(this,it)[t]):e(this,y,as).call(this,b(this,pt)[t],b(this,it)[t]),e(this,y,as).call(this,b(this,K),t),d(this,K,t));},Xt=function(t,i){var h,n;let s=false;if(b(this,G)!==0){let o=b(this,$).get(t);if(o!==void 0)if(b(this,dt)?.[o]&&(clearTimeout(b(this,dt)?.[o]),b(this,dt)[o]=void 0),s=true,b(this,G)===1)e(this,y,ls).call(this,i);else {b(this,ge).call(this,o);let a=b(this,O)[o];if(e(this,y,W).call(this,a)?a.__abortController.abort(new Error("deleted")):(b(this,Tt)||b(this,st))&&(b(this,Tt)&&((h=b(this,xt))==null||h.call(this,a,t,i)),b(this,st)&&b(this,Y)?.push([a,t,i])),b(this,$).delete(t),b(this,D)[o]=void 0,b(this,O)[o]=void 0,o===b(this,K))d(this,K,b(this,pt)[o]);else if(o===b(this,tt))d(this,tt,b(this,it)[o]);else {let l=b(this,pt)[o];b(this,it)[l]=b(this,it)[o];let u=b(this,it)[o];b(this,pt)[u]=b(this,pt)[o];}f(this,G)._--,b(this,Ot).push(o);}}if(b(this,st)&&b(this,Y)?.length){let o=b(this,Y),a;for(;a=o?.shift();)(n=b(this,kt))==null||n.call(this,...a);}return s},ls=function(t){var i,s;for(let h of e(this,y,Yt).call(this,{allowStale:true})){let n=b(this,O)[h];if(e(this,y,W).call(this,n))n.__abortController.abort(new Error("deleted"));else {let o=b(this,D)[h];b(this,Tt)&&((i=b(this,xt))==null||i.call(this,n,o,t)),b(this,st)&&b(this,Y)?.push([n,o,t]);}}if(b(this,$).clear(),b(this,O).fill(void 0),b(this,D).fill(void 0),b(this,ft)&&b(this,Ft)){b(this,ft).fill(0),b(this,Ft).fill(0);for(let h of b(this,dt)??[])h!==void 0&&clearTimeout(h);b(this,dt)?.fill(void 0);}if(b(this,At)&&b(this,At).fill(0),d(this,tt,0),d(this,K,0),b(this,Ot).length=0,d(this,Ct,0),d(this,G,0),b(this,st)&&b(this,Y)){let h=b(this,Y),n;for(;n=h?.shift();)(s=b(this,kt))==null||s.call(this,...n);}},Me),Ms=typeof process=="object"&&process?process:{stdout:null,stderr:null},Mn=e=>!!e&&typeof e=="object"&&(e instanceof Ui||e instanceof Pr||Wn(e)||Pn(e)),Wn=e=>!!e&&typeof e=="object"&&e instanceof EventEmitter&&typeof e.pipe=="function"&&e.pipe!==Pr.Writable.prototype.pipe,Pn=e=>!!e&&typeof e=="object"&&e instanceof EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",zt=Symbol("EOF"),_t=Symbol("maybeEmitEnd"),Zt=Symbol("emittedEnd"),Ri=Symbol("emittingEnd"),Be=Symbol("emittedError"),Ci=Symbol("closed"),Ws=Symbol("read"),Oi=Symbol("flush"),Ps=Symbol("flushChunk"),vt=Symbol("encoding"),ke=Symbol("decoder"),J=Symbol("flowing"),Ue=Symbol("paused"),Re=Symbol("resume"),q=Symbol("buffer"),et=Symbol("pipes"),Z=Symbol("bufferLength"),Yi=Symbol("bufferPush"),Ai=Symbol("bufferShift"),Q=Symbol("objectMode"),z=Symbol("destroyed"),Xi=Symbol("error"),Qi=Symbol("emitData"),Ds=Symbol("emitEnd"),ts=Symbol("emitEnd2"),Mt=Symbol("async"),es=Symbol("abort"),Fi=Symbol("aborted"),Ge=Symbol("signal"),ae=Symbol("dataListeners"),ct=Symbol("discarded"),Ie=e=>Promise.resolve().then(e),Dn=e=>e(),jn=e=>e==="end"||e==="finish"||e==="prefinish",Nn=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,zn=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),Dr=class{constructor(e,t,i){a(this,"src");a(this,"dest");a(this,"opts");a(this,"ondrain");this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[Re](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},_n=class extends Dr{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);}},$n=e=>!!e.objectMode,Bn=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Zs,Vs,Ks,Ys,Xs,Qs,tr,er,ir,sr,rr,hr,nr,or,ar,lr,cr,ur,pr,Ui=class extends EventEmitter{constructor(...t){let i=t[0]||{};super();a(this,pr,false);a(this,ur,false);a(this,cr,[]);a(this,lr,[]);a(this,ar);a(this,or);a(this,nr);a(this,hr);a(this,rr,false);a(this,sr,false);a(this,ir,false);a(this,er,false);a(this,tr,null);a(this,Qs,0);a(this,Xs,false);a(this,Ys);a(this,Ks,false);a(this,Vs,0);a(this,Zs,false);a(this,"writable",true);a(this,"readable",true);if(i.objectMode&&typeof i.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");$n(i)?(this[Q]=true,this[vt]=null):Bn(i)?(this[vt]=i.encoding,this[Q]=false):(this[Q]=false,this[vt]=null),this[Mt]=!!i.async,this[ke]=this[vt]?new StringDecoder(this[vt]):null,i&&i.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[q]}),i&&i.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:s}=i;s&&(this[Ge]=s,s.aborted?this[es]():s.addEventListener("abort",()=>this[es]()));}get bufferLength(){return this[Z]}get encoding(){return this[vt]}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[Q]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Mt]}set async(t){this[Mt]=this[Mt]||!!t;}[(pr=J,ur=Ue,cr=et,lr=q,ar=Q,or=vt,nr=Mt,hr=ke,rr=zt,sr=Zt,ir=Ri,er=Ci,tr=Be,Qs=Z,Xs=z,Ys=Ge,Ks=Fi,Vs=ae,Zs=ct,es)](){this[Fi]=true,this.emit("abort",this[Ge]?.reason),this.destroy(this[Ge]?.reason);}get aborted(){return this[Fi]}set aborted(t){}write(t,i,s){if(this[Fi])return false;if(this[zt])throw new Error("write after end");if(this[z])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 h=this[Mt]?Ie:Dn;if(!this[Q]&&!Buffer.isBuffer(t)){if(zn(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Nn(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Q]?(this[J]&&this[Z]!==0&&this[Oi](true),this[J]?this.emit("data",t):this[Yi](t),this[Z]!==0&&this.emit("readable"),s&&h(s),this[J]):t.length?(typeof t=="string"&&!(i===this[vt]&&!this[ke]?.lastNeed)&&(t=Buffer.from(t,i)),Buffer.isBuffer(t)&&this[vt]&&(t=this[ke].write(t)),this[J]&&this[Z]!==0&&this[Oi](true),this[J]?this.emit("data",t):this[Yi](t),this[Z]!==0&&this.emit("readable"),s&&h(s),this[J]):(this[Z]!==0&&this.emit("readable"),s&&h(s),this[J])}read(t){if(this[z])return null;if(this[ct]=false,this[Z]===0||t===0||t&&t>this[Z])return this[_t](),null;this[Q]&&(t=null),this[q].length>1&&!this[Q]&&(this[q]=[this[vt]?this[q].join(""):Buffer.concat(this[q],this[Z])]);let i=this[Ws](t||null,this[q][0]);return this[_t](),i}[Ws](t,i){if(this[Q])this[Ai]();else {let s=i;t===s.length||t===null?this[Ai]():typeof s=="string"?(this[q][0]=s.slice(t),i=s.slice(0,t),this[Z]-=t):(this[q][0]=s.subarray(t),i=s.subarray(0,t),this[Z]-=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[J]||!this[Ue])&&this[_t](),this}[Re](){this[z]||(!this[ae]&&!this[et].length&&(this[ct]=true),this[Ue]=false,this[J]=true,this.emit("resume"),this[q].length?this[Oi]():this[zt]?this[_t]():this.emit("drain"));}resume(){return this[Re]()}pause(){this[J]=false,this[Ue]=true,this[ct]=false;}get destroyed(){return this[z]}get flowing(){return this[J]}get paused(){return this[Ue]}[Yi](t){this[Q]?this[Z]+=1:this[Z]+=t.length,this[q].push(t);}[Ai](){return this[Q]?this[Z]-=1:this[Z]-=this[q][0].length,this[q].shift()}[Oi](t=false){do;while(this[Ps](this[Ai]())&&this[q].length);!t&&!this[q].length&&!this[zt]&&this.emit("drain");}[Ps](t){return this.emit("data",t),this[J]}pipe(t,i){if(this[z])return t;this[ct]=false;let s=this[Zt];return i=i||{},t===Ms.stdout||t===Ms.stderr?i.end=false:i.end=i.end!==false,i.proxyErrors=!!i.proxyErrors,s?i.end&&t.end():(this[et].push(i.proxyErrors?new _n(this,t,i):new Dr(this,t,i)),this[Mt]?Ie(()=>this[Re]()):this[Re]()),t}unpipe(t){let i=this[et].find(s=>s.dest===t);i&&(this[et].length===1?(this[J]&&this[ae]===0&&(this[J]=false),this[et]=[]):this[et].splice(this[et].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[ae]++,!this[et].length&&!this[J]&&this[Re]();else if(t==="readable"&&this[Z]!==0)super.emit("readable");else if(jn(t)&&this[Zt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Be]){let h=i;this[Mt]?Ie(()=>h.call(this,this[Be])):h.call(this,this[Be]);}return s}removeListener(t,i){return this.off(t,i)}off(t,i){let s=super.off(t,i);return t==="data"&&(this[ae]=this.listeners("data").length,this[ae]===0&&!this[ct]&&!this[et].length&&(this[J]=false)),s}removeAllListeners(t){let i=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[ae]=0,!this[ct]&&!this[et].length&&(this[J]=false)),i}get emittedEnd(){return this[Zt]}[_t](){!this[Ri]&&!this[Zt]&&!this[z]&&this[q].length===0&&this[zt]&&(this[Ri]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ci]&&this.emit("close"),this[Ri]=false);}emit(t,...i){let s=i[0];if(t!=="error"&&t!=="close"&&t!==z&&this[z])return false;if(t==="data")return !this[Q]&&!s?false:this[Mt]?(Ie(()=>this[Qi](s)),true):this[Qi](s);if(t==="end")return this[Ds]();if(t==="close"){if(this[Ci]=true,!this[Zt]&&!this[z])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[Be]=s,super.emit(Xi,s);let n=!this[Ge]||this.listeners("error").length?super.emit("error",s):false;return this[_t](),n}else if(t==="resume"){let n=super.emit("resume");return this[_t](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let h=super.emit(t,...i);return this[_t](),h}[Qi](t){for(let s of this[et])s.dest.write(t)===false&&this.pause();let i=this[ct]?false:super.emit("data",t);return this[_t](),i}[Ds](){return this[Zt]?false:(this[Zt]=true,this.readable=false,this[Mt]?(Ie(()=>this[ts]()),true):this[ts]())}[ts](){if(this[ke]){let i=this[ke].end();if(i){for(let s of this[et])s.dest.write(i);this[ct]||super.emit("data",i);}}for(let i of this[et])i.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Q]||(t.dataLength=0);let i=this.promise();return this.on("data",s=>{t.push(s),this[Q]||(t.dataLength+=s.length);}),await i,t}async concat(){if(this[Q])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[vt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,i)=>{this.on(z,()=>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 h,n,o=d=>{this.off("data",a),this.off("end",l),this.off(z,u),i(),n(d);},a=d=>{this.off("error",o),this.off("end",l),this.off(z,u),this.pause(),h({value:d,done:!!this[zt]});},l=()=>{this.off("error",o),this.off("data",a),this.off(z,u),i(),h({done:true,value:void 0});},u=()=>o(new Error("stream destroyed"));return new Promise((d,f)=>{n=f,h=d,this.once(z,u),this.once("error",o),this.once("end",l),this.once("data",a);})},throw:i,return:i,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ct]=false;let t=false,i=()=>(this.pause(),this.off(Xi,i),this.off(z,i),this.off("end",i),t=true,{done:true,value:void 0}),s=()=>{if(t)return i();let h=this.read();return h===null?i():{done:false,value:h}};return this.once("end",i),this.once(Xi,i),this.once(z,i),{next:s,throw:i,return:i,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[z])return t?this.emit("error",t):this.emit(z),this;this[z]=true,this[ct]=true,this[q].length=0,this[Z]=0;let i=this;return typeof i.close=="function"&&!this[Ci]&&i.close(),t?this.emit("error",t):this.emit(z),this}static get isStream(){return Mn}},Un=realpathSync.native,Ze={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Un,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},jr=e=>!e||e===Ze||e===Cn?Ze:{...Ze,...e,promises:{...Ze.promises,...e.promises||{}}},Nr=/^\\\\\?\\([a-z]:)\\?$/i,Gn=e=>e.replace(/\//g,"\\").replace(Nr,"$1\\"),In=/[\\\/]/,bt=0,zr=1,_r=2,Wt=4,$r=6,Br=8,le=10,Ur=12,wt=15,He=~wt,is=16,js=32,Ve=64,Et=128,Ti=256,ji=512,Ns=Ve|Et|ji,Hn=1023,ss=e=>e.isFile()?Br:e.isDirectory()?Wt:e.isSymbolicLink()?le:e.isCharacterDevice()?_r:e.isBlockDevice()?$r:e.isSocket()?Ur:e.isFIFO()?zr:bt,zs=new Ii({max:2**12}),Ke=e=>{let t=zs.get(e);if(t)return t;let i=e.normalize("NFKD");return zs.set(e,i),i},_s=new Ii({max:2**12}),Li=e=>{let t=_s.get(e);if(t)return t;let i=Ke(e.toLowerCase());return _s.set(e,i),i},$s=class extends Ii{constructor(){super({max:256});}},Jn=class extends Ii{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Gr=Symbol("PathScurry setAsCwd"),rt,ii,si,ri,hi,ni,oi,ai,li,ci,ui,pi,fi,di,gi,mi,wi,yi,bi,ie,me,Dt,Ut,Gt,It,C,we,Ht,jt,k,us,Ni,Ye,ps,fs,Xe,zi,ds,gs,_i,Ir,Hr,Jr,ms,We,Pe,qr,ye,fr,at=(fr=class{constructor(e,t=bt,i,s,h,n,o){c(this,k);a(this,"name");a(this,"root");a(this,"roots");a(this,"parent");a(this,"nocase");a(this,"isCWD",false);c(this,rt);c(this,ii);c(this,si);c(this,ri);c(this,hi);c(this,ni);c(this,oi);c(this,ai);c(this,li);c(this,ci);c(this,ui);c(this,pi);c(this,fi);c(this,di);c(this,gi);c(this,mi);c(this,wi);c(this,yi);c(this,bi);c(this,ie);c(this,me);c(this,Dt);c(this,Ut);c(this,Gt);c(this,It);c(this,C);c(this,we);c(this,Ht);c(this,jt);c(this,We,[]);c(this,Pe,false);c(this,ye);this.name=e,d(this,ie,h?Li(e):Ke(e)),d(this,C,t&Hn),this.nocase=h,this.roots=s,this.root=i||this,d(this,we,n),d(this,Dt,o.fullpath),d(this,Gt,o.relative),d(this,It,o.relativePosix),this.parent=o.parent,this.parent?d(this,rt,b(this.parent,rt)):d(this,rt,jr(o.fs));}get dev(){return b(this,ii)}get mode(){return b(this,si)}get nlink(){return b(this,ri)}get uid(){return b(this,hi)}get gid(){return b(this,ni)}get rdev(){return b(this,oi)}get blksize(){return b(this,ai)}get ino(){return b(this,li)}get size(){return b(this,ci)}get blocks(){return b(this,ui)}get atimeMs(){return b(this,pi)}get mtimeMs(){return b(this,fi)}get ctimeMs(){return b(this,di)}get birthtimeMs(){return b(this,gi)}get atime(){return b(this,mi)}get mtime(){return b(this,wi)}get ctime(){return b(this,yi)}get birthtime(){return b(this,bi)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return b(this,me)!==void 0?b(this,me):this.parent?d(this,me,this.parent.depth()+1):d(this,me,0)}childrenCache(){return b(this,we)}resolve(e$1){var s;if(!e$1)return this;let t=this.getRootString(e$1),i=e$1.substring(t.length).split(this.splitSep);return t?e(s=this.getRoot(t),k,us).call(s,i):e(this,k,us).call(this,i)}children(){let e=b(this,we).get(this);if(e)return e;let t=Object.assign([],{provisional:0});return b(this,we).set(this,t),d(this,C,b(this,C)&~is),t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let i=this.children(),s=this.nocase?Li(e):Ke(e);for(let a of i)if(b(a,ie)===s)return a;let h=this.parent?this.sep:"",n=b(this,Dt)?b(this,Dt)+h+e:void 0,o=this.newChild(e,bt,{...t,parent:this,fullpath:n});return this.canReaddir()||d(o,C,b(o,C)|Et),i.push(o),o}relative(){if(this.isCWD)return "";if(b(this,Gt)!==void 0)return b(this,Gt);let e=this.name,t=this.parent;if(!t)return d(this,Gt,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(b(this,It)!==void 0)return b(this,It);let e=this.name,t=this.parent;if(!t)return d(this,It,this.fullpathPosix());let i=t.relativePosix();return i+(!i||!t.parent?"":"/")+e}fullpath(){if(b(this,Dt)!==void 0)return b(this,Dt);let e=this.name,t=this.parent;if(!t)return d(this,Dt,this.name);let i=t.fullpath()+(t.parent?this.sep:"")+e;return d(this,Dt,i)}fullpathPosix(){if(b(this,Ut)!==void 0)return b(this,Ut);if(this.sep==="/")return d(this,Ut,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?d(this,Ut,`//?/${s}`):d(this,Ut,s)}let e=this.parent,t=e.fullpathPosix(),i=t+(!t||!e.parent?"":"/")+this.name;return d(this,Ut,i)}isUnknown(){return (b(this,C)&wt)===bt}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 (b(this,C)&wt)===Br}isDirectory(){return (b(this,C)&wt)===Wt}isCharacterDevice(){return (b(this,C)&wt)===_r}isBlockDevice(){return (b(this,C)&wt)===$r}isFIFO(){return (b(this,C)&wt)===zr}isSocket(){return (b(this,C)&wt)===Ur}isSymbolicLink(){return (b(this,C)&le)===le}lstatCached(){return b(this,C)&js?this:void 0}readlinkCached(){return b(this,Ht)}realpathCached(){return b(this,jt)}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(b(this,Ht))return true;if(!this.parent)return false;let e=b(this,C)&wt;return !(e!==bt&&e!==le||b(this,C)&Ti||b(this,C)&Et)}calledReaddir(){return !!(b(this,C)&is)}isENOENT(){return !!(b(this,C)&Et)}isNamed(e){return this.nocase?b(this,ie)===Li(e):b(this,ie)===Ke(e)}async readlink(){let e$1=b(this,Ht);if(e$1)return e$1;if(this.canReadlink()&&this.parent)try{let t=await b(this,rt).promises.readlink(this.fullpath()),i=(await this.parent.realpath())?.resolve(t);if(i)return d(this,Ht,i)}catch(t){e(this,k,gs).call(this,t.code);return}}readlinkSync(){let e$1=b(this,Ht);if(e$1)return e$1;if(this.canReadlink()&&this.parent)try{let t=b(this,rt).readlinkSync(this.fullpath()),i=this.parent.realpathSync()?.resolve(t);if(i)return d(this,Ht,i)}catch(t){e(this,k,gs).call(this,t.code);return}}async lstat(){if((b(this,C)&Et)===0)try{return e(this,k,ms).call(this,await b(this,rt).promises.lstat(this.fullpath())),this}catch(e$1){e(this,k,ds).call(this,e$1.code);}}lstatSync(){if((b(this,C)&Et)===0)try{return e(this,k,ms).call(this,b(this,rt).lstatSync(this.fullpath())),this}catch(e$1){e(this,k,ds).call(this,e$1.code);}}readdirCB(e$1,t=false){if(!this.canReaddir()){t?e$1(null,[]):queueMicrotask(()=>e$1(null,[]));return}let i=this.children();if(this.calledReaddir()){let h=i.slice(0,i.provisional);t?e$1(null,h):queueMicrotask(()=>e$1(null,h));return}if(b(this,We).push(e$1),b(this,Pe))return;d(this,Pe,true);let s=this.fullpath();b(this,rt).readdir(s,{withFileTypes:true},(h,n)=>{if(h)e(this,k,zi).call(this,h.code),i.provisional=0;else {for(let o of n)e(this,k,_i).call(this,o,i);e(this,k,Ni).call(this,i);}e(this,k,qr).call(this,i.slice(0,i.provisional));});}async readdir(){if(!this.canReaddir())return [];let e$1=this.children();if(this.calledReaddir())return e$1.slice(0,e$1.provisional);let t=this.fullpath();if(b(this,ye))await b(this,ye);else {let i=()=>{};d(this,ye,new Promise(s=>i=s));try{for(let s of await b(this,rt).promises.readdir(t,{withFileTypes:!0}))e(this,k,_i).call(this,s,e$1);e(this,k,Ni).call(this,e$1);}catch(s){e(this,k,zi).call(this,s.code),e$1.provisional=0;}d(this,ye,void 0),i();}return e$1.slice(0,e$1.provisional)}readdirSync(){if(!this.canReaddir())return [];let e$1=this.children();if(this.calledReaddir())return e$1.slice(0,e$1.provisional);let t=this.fullpath();try{for(let i of b(this,rt).readdirSync(t,{withFileTypes:!0}))e(this,k,_i).call(this,i,e$1);e(this,k,Ni).call(this,e$1);}catch(i){e(this,k,zi).call(this,i.code),e$1.provisional=0;}return e$1.slice(0,e$1.provisional)}canReaddir(){if(b(this,C)&Ns)return false;let e=wt&b(this,C);return e===bt||e===Wt||e===le}shouldWalk(e,t){return (b(this,C)&Wt)===Wt&&!(b(this,C)&Ns)&&!e.has(this)&&(!t||t(this))}async realpath(){if(b(this,jt))return b(this,jt);if(!((ji|Ti|Et)&b(this,C)))try{let e=await b(this,rt).promises.realpath(this.fullpath());return d(this,jt,this.resolve(e))}catch{e(this,k,fs).call(this);}}realpathSync(){if(b(this,jt))return b(this,jt);if(!((ji|Ti|Et)&b(this,C)))try{let e=b(this,rt).realpathSync(this.fullpath());return d(this,jt,this.resolve(e))}catch{e(this,k,fs).call(this);}}[Gr](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),d(s,Gt,i.join(this.sep)),d(s,It,i.join("/")),s=s.parent,i.push("..");for(s=e;s&&s.parent&&!t.has(s);)d(s,Gt,void 0),d(s,It,void 0),s=s.parent;}},rt=new WeakMap,ii=new WeakMap,si=new WeakMap,ri=new WeakMap,hi=new WeakMap,ni=new WeakMap,oi=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap,ui=new WeakMap,pi=new WeakMap,fi=new WeakMap,di=new WeakMap,gi=new WeakMap,mi=new WeakMap,wi=new WeakMap,yi=new WeakMap,bi=new WeakMap,ie=new WeakMap,me=new WeakMap,Dt=new WeakMap,Ut=new WeakMap,Gt=new WeakMap,It=new WeakMap,C=new WeakMap,we=new WeakMap,Ht=new WeakMap,jt=new WeakMap,k=new WeakSet,us=function(e){let t=this;for(let i of e)t=t.child(i);return t},Ni=function(e$1){var t;d(this,C,b(this,C)|is);for(let i=e$1.provisional;i<e$1.length;i++){let s=e$1[i];s&&e(t=s,k,Ye).call(t);}},Ye=function(){b(this,C)&Et||(d(this,C,(b(this,C)|Et)&He),e(this,k,ps).call(this));},ps=function(){var t;let e$1=this.children();e$1.provisional=0;for(let i of e$1)e(t=i,k,Ye).call(t);},fs=function(){d(this,C,b(this,C)|ji),e(this,k,Xe).call(this);},Xe=function(){if(b(this,C)&Ve)return;let e$1=b(this,C);(e$1&wt)===Wt&&(e$1&=He),d(this,C,e$1|Ve),e(this,k,ps).call(this);},zi=function(e$1=""){e$1==="ENOTDIR"||e$1==="EPERM"?e(this,k,Xe).call(this):e$1==="ENOENT"?e(this,k,Ye).call(this):this.children().provisional=0;},ds=function(e$1=""){var t;e$1==="ENOTDIR"?e(t=this.parent,k,Xe).call(t):e$1==="ENOENT"&&e(this,k,Ye).call(this);},gs=function(e$1=""){var i;let t=b(this,C);t|=Ti,e$1==="ENOENT"&&(t|=Et),(e$1==="EINVAL"||e$1==="UNKNOWN")&&(t&=He),d(this,C,t),e$1==="ENOTDIR"&&this.parent&&e(i=this.parent,k,Xe).call(i);},_i=function(e$1,t){return e(this,k,Hr).call(this,e$1,t)||e(this,k,Ir).call(this,e$1,t)},Ir=function(e,t){let i=ss(e),s=this.newChild(e.name,i,{parent:this}),h=b(s,C)&wt;return h!==Wt&&h!==le&&h!==bt&&d(s,C,b(s,C)|Ve),t.unshift(s),t.provisional++,s},Hr=function(e$1,t){for(let i=t.provisional;i<t.length;i++){let s=t[i];if((this.nocase?Li(e$1.name):Ke(e$1.name))===b(s,ie))return e(this,k,Jr).call(this,e$1,s,i,t)}},Jr=function(e,t,i,s){let h=t.name;return d(t,C,b(t,C)&He|ss(e)),h!==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},ms=function(e){let{atime:t,atimeMs:i,birthtime:s,birthtimeMs:h,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:u,gid:d$1,ino:f,mode:w,mtime:S,mtimeMs:E,nlink:b$1,rdev:x,size:v,uid:R}=e;d(this,mi,t),d(this,pi,i),d(this,bi,s),d(this,gi,h),d(this,ai,n),d(this,ui,o),d(this,yi,a),d(this,di,l),d(this,ii,u),d(this,ni,d$1),d(this,li,f),d(this,si,w),d(this,wi,S),d(this,fi,E),d(this,ri,b$1),d(this,oi,x),d(this,ci,v),d(this,hi,R);let A=ss(e);d(this,C,b(this,C)&He|A|js),A!==bt&&A!==Wt&&A!==le&&d(this,C,b(this,C)|Ve);},We=new WeakMap,Pe=new WeakMap,qr=function(e){d(this,Pe,false);let t=b(this,We).slice();b(this,We).length=0,t.forEach(i=>i(null,e));},ye=new WeakMap,fr),Zr=class Vr extends at{constructor(i,s=bt,h,n,o,a$1,l){super(i,s,h,n,o,a$1,l);a(this,"sep","\\");a(this,"splitSep",In);}newChild(i,s=bt,h={}){return new Vr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}getRootString(i){return win32.parse(i).root}getRoot(i){if(i=Gn(i.toUpperCase()),i===this.root.name)return this.root;for(let[s,h]of Object.entries(this.roots))if(this.sameRoot(i,s))return this.roots[i]=h;return this.roots[i]=new vs(i,this).root}sameRoot(i,s=this.root.name){return i=i.toUpperCase().replace(/\//g,"\\").replace(Nr,"$1\\"),i===s}},Kr=class Yr extends at{constructor(i,s=bt,h,n,o,a$1,l){super(i,s,h,n,o,a$1,l);a(this,"splitSep","/");a(this,"sep","/");}getRootString(i){return i.startsWith("/")?"/":""}getRoot(i){return this.root}newChild(i,s=bt,h={}){return new Yr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}},De,je,Si,vi,dr,Xr=(dr=class{constructor(e=process.cwd(),t,i,{nocase:s,childrenCacheSize:h=16*1024,fs:n=Ze}={}){a(this,"root");a(this,"rootPath");a(this,"roots");a(this,"cwd");c(this,De);c(this,je);c(this,Si);a(this,"nocase");c(this,vi);d(this,vi,jr(n)),(e instanceof URL||e.startsWith("file://"))&&(e=fileURLToPath(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),d(this,De,new $s),d(this,je,new $s),d(this,Si,new Jn(h));let a$1=o.substring(this.rootPath.length).split(i);if(a$1.length===1&&!a$1[0]&&a$1.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(b(this,vi)),this.roots[this.rootPath]=this.root;let l=this.root,u=a$1.length-1,d$1=t.sep,f=this.rootPath,w=false;for(let S of a$1){let E=u--;l=l.child(S,{relative:new Array(E).fill("..").join(d$1),relativePosix:new Array(E).fill("..").join("/"),fullpath:f+=(w?"":d$1)+S}),w=true;}this.cwd=l;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return b(this,Si)}resolve(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=b(this,De).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpath();return b(this,De).set(t,s),s}resolvePosix(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=b(this,je).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpathPosix();return b(this,je).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 at||(t=e,e=this.cwd);let{withFileTypes:i}=t;if(e.canReaddir()){let s=await e.readdir();return i?s:s.map(h=>h.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(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 at||(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 at||(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 at||(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 at||(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 at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set,l=(d,f)=>{a.add(d),d.readdirCB((w,S)=>{if(w)return f(w);let E=S.length;if(!E)return f();let b=()=>{--E===0&&f();};for(let x of S)(!h||h(x))&&o.push(i?x:x.fullpath()),s&&x.isSymbolicLink()?x.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(a,n)?l(v,b):b()):x.shouldWalk(a,n)?l(x,b):b();},true);},u=e;return new Promise((d,f)=>{l(u,w=>{if(w)return f(w);d(o);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set([e]);for(let l of a){let u=l.readdirSync();for(let d of u){(!h||h(d))&&o.push(i?d:d.fullpath());let f=d;if(d.isSymbolicLink()){if(!(s&&(f=d.realpathSync())))continue;f.isUnknown()&&f.lstatSync();}f.shouldWalk(a,n)&&a.add(f);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(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 at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t;(!h||h(e))&&(yield i?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let u of l){(!h||h(u))&&(yield i?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(o,n)&&o.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ui({objectMode:true});(!h||h(e))&&o.write(i?e:e.fullpath());let a=new Set,l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let S=(b,x,v=false)=>{if(b)return o.emit("error",b);if(s&&!v){let R=[];for(let A of x)A.isSymbolicLink()&&R.push(A.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(R.length){Promise.all(R).then(()=>S(null,x,true));return}}for(let R of x)R&&(!h||h(R))&&(o.write(i?R:R.fullpath())||(f=true));u--;for(let R of x){let A=R.realpathCached()||R;A.shouldWalk(a,n)&&l.push(A);}f&&!o.flowing?o.once("drain",d):E||d();},E=true;w.readdirCB(S,true),E=false;}};return d(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ui({objectMode:true}),a=new Set;(!h||h(e))&&o.write(i?e:e.fullpath());let l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let S=w.readdirSync();for(let E of S)(!h||h(E))&&(o.write(i?E:E.fullpath())||(f=true));u--;for(let E of S){let b=E;if(E.isSymbolicLink()){if(!(s&&(b=E.realpathSync())))continue;b.isUnknown()&&b.lstatSync();}b.shouldWalk(a,n)&&l.push(b);}}f&&!o.flowing&&o.once("drain",d);};return d(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Gr](t);}},De=new WeakMap,je=new WeakMap,Si=new WeakMap,vi=new WeakMap,dr),vs=class extends Xr{constructor(t=process.cwd(),i={}){let{nocase:s=true}=i;super(t,win32,"\\",{...i,nocase:s});a(this,"sep","\\");this.nocase=s;for(let h=this.cwd;h;h=h.parent)h.nocase=this.nocase;}parseRootPath(t){return win32.parse(t).root.toUpperCase()}newRoot(t){return new Zr(this.rootPath,Wt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},Es=class extends Xr{constructor(t=process.cwd(),i={}){let{nocase:s=false}=i;super(t,posix,"/",{...i,nocase:s});a(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Kr(this.rootPath,Wt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Qr=class extends Es{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,{...t,nocase:i});}};process.platform==="win32"?Zr:Kr;var qn=process.platform==="win32"?vs:process.platform==="darwin"?Qr:Es,Zn=e=>e.length>=1,Vn=e=>e.length>=1,Kn=Symbol.for("nodejs.util.inspect.custom"),I,lt,H,be,Lt,Ei,se,re,he,Ne,ze,th=(ze=class{constructor(t,i,s,h){c(this,I);c(this,lt);c(this,H);a(this,"length");c(this,be);c(this,Lt);c(this,Ei);c(this,se);c(this,re);c(this,he);c(this,Ne,true);if(!Zn(t))throw new TypeError("empty pattern list");if(!Vn(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(d(this,I,t),d(this,lt,i),d(this,H,s),d(this,be,h),b(this,H)===0){if(this.isUNC()){let[n,o,a,l,...u]=b(this,I),[d$1,f,w,S,...E]=b(this,lt);u[0]===""&&(u.shift(),E.shift());let b$1=[n,o,a,l,""].join("/"),x=[d$1,f,w,S,""].join("/");d(this,I,[b$1,...u]),d(this,lt,[x,...E]),this.length=b(this,I).length;}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=b(this,I),[a,...l]=b(this,lt);o[0]===""&&(o.shift(),l.shift());let u=n+"/",d$1=a+"/";d(this,I,[u,...o]),d(this,lt,[d$1,...l]),this.length=b(this,I).length;}}}[Kn](){return "Pattern <"+b(this,lt).slice(b(this,H)).join("/")+">"}pattern(){return b(this,I)[b(this,H)]}isString(){return typeof b(this,I)[b(this,H)]=="string"}isGlobstar(){return b(this,I)[b(this,H)]===ht}isRegExp(){return b(this,I)[b(this,H)]instanceof RegExp}globString(){return d(this,Ei,b(this,Ei)||(b(this,H)===0?this.isAbsolute()?b(this,lt)[0]+b(this,lt).slice(1).join("/"):b(this,lt).join("/"):b(this,lt).slice(b(this,H)).join("/")))}hasMore(){return this.length>b(this,H)+1}rest(){return b(this,Lt)!==void 0?b(this,Lt):this.hasMore()?(d(this,Lt,new ze(b(this,I),b(this,lt),b(this,H)+1,b(this,be))),d(b(this,Lt),he,b(this,he)),d(b(this,Lt),re,b(this,re)),d(b(this,Lt),se,b(this,se)),b(this,Lt)):d(this,Lt,null)}isUNC(){let t=b(this,I);return b(this,re)!==void 0?b(this,re):d(this,re,b(this,be)==="win32"&&b(this,H)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=b(this,I);return b(this,se)!==void 0?b(this,se):d(this,se,b(this,be)==="win32"&&b(this,H)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=b(this,I);return b(this,he)!==void 0?b(this,he):d(this,he,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=b(this,I)[0];return typeof t=="string"&&this.isAbsolute()&&b(this,H)===0?t:""}checkFollowGlobstar(){return !(b(this,H)===0||!this.isGlobstar()||!b(this,Ne))}markFollowGlobstar(){return b(this,H)===0||!this.isGlobstar()||!b(this,Ne)?false:(d(this,Ne,false),true)}},I=new WeakMap,lt=new WeakMap,H=new WeakMap,be=new WeakMap,Lt=new WeakMap,Ei=new WeakMap,se=new WeakMap,re=new WeakMap,he=new WeakMap,Ne=new WeakMap,ze),Yn=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Bs=class{constructor(e,{nobrace:t,nocase:i,noext:s,noglobstar:h,platform:n=Yn}){a(this,"relative");a(this,"relativeChildren");a(this,"absolute");a(this,"absoluteChildren");a(this,"platform");a(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:true,nobrace:t,nocase:i,noext:s,noglobstar:h,optimizationLevel:2,platform:n,nocomment:true,nonegate:true};for(let o of e)this.add(o);}add(e){let t=new oe(e,this.mmopts);for(let i=0;i<t.set.length;i++){let s=t.set[i],h=t.globParts[i];if(!s||!h)throw new Error("invalid pattern object");for(;s[0]==="."&&h[0]===".";)s.shift(),h.shift();let n=new th(s,h,0,this.platform),o=new oe(n.globString(),this.mmopts),a=h[h.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(e){let t=e.fullpath(),i=`${t}/`,s=e.relative()||".",h=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(h))return true;for(let n of this.absolute)if(n.match(t)||n.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}},Xn=class eh{constructor(t=new Map){a(this,"store");this.store=t;}copy(){return new eh(new Map(this.store))}hasWalked(t,i){return this.store.get(t.fullpath())?.has(i.globString())}storeWalked(t,i){let s=t.fullpath(),h=this.store.get(s);h?h.add(i.globString()):this.store.set(s,new Set([i.globString()]));}},Qn=class{constructor(){a(this,"store",new Map);}add(e,t,i){let s=(t?2:0)|(i?1:0),h=this.store.get(e);this.store.set(e,h===void 0?s:s&h);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},to=class{constructor(){a(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())}},Us=class ih{constructor(t,i){a(this,"hasWalkedCache");a(this,"matches",new Qn);a(this,"subwalks",new to);a(this,"patterns");a(this,"follow");a(this,"dot");a(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=i?i.copy():new Xn;}processPatterns(t,i){this.patterns=i;let s=i.map(h=>[t,h]);for(let[h,n]of s){this.hasWalkedCache.storeWalked(h,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==false;if(o){h=h.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=n.rest();if(f)n=f;else {this.matches.add(h,true,false);continue}}if(h.isENOENT())continue;let l,u,d=false;for(;typeof(l=n.pattern())=="string"&&(u=n.rest());)h=h.resolve(l),n=u,d=true;if(l=n.pattern(),u=n.rest(),d){if(this.hasWalkedCache.hasWalked(h,n))continue;this.hasWalkedCache.storeWalked(h,n);}if(typeof l=="string"){let f=l===".."||l===""||l===".";this.matches.add(h.resolve(l),a,f);continue}else if(l===ht){(!h.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(h,n);let f=u?.pattern(),w=u?.rest();if(!u||(f===""||f===".")&&!w)this.matches.add(h,a,f===""||f===".");else if(f===".."){let S=h.parent||h;w?this.hasWalkedCache.hasWalked(S,w)||this.subwalks.add(S,w):this.matches.add(S,a,true);}}else l instanceof RegExp&&this.subwalks.add(h,n);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new ih(this.opts,this.hasWalkedCache)}filterEntries(t,i){let s=this.subwalks.get(t),h=this.child();for(let n of i)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),u=o.rest();l===ht?h.testGlobstar(n,o,u,a):l instanceof RegExp?h.testRegExp(n,l,u,a):h.testString(n,l,u,a);}return h}testGlobstar(t,i,s,h){if((this.dot||!t.name.startsWith("."))&&(i.hasMore()||this.matches.add(t,h,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 n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),h);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s);}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),h);}}testRegExp(t,i,s,h){i.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}testString(t,i,s,h){t.isNamed(i)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}},eo=(e,t)=>typeof e=="string"?new Bs([e],t):Array.isArray(e)?new Bs(e,t):e,_e,Jt,Se,St,ce,ws,gr,sh=(gr=class{constructor(e,t,i){c(this,St);a(this,"path");a(this,"patterns");a(this,"opts");a(this,"seen",new Set);a(this,"paused",false);a(this,"aborted",false);c(this,_e,[]);c(this,Jt);c(this,Se);a(this,"signal");a(this,"maxDepth");a(this,"includeChildMatches");if(this.patterns=e,this.path=t,this.opts=i,d(this,Se,!i.posix&&i.platform==="win32"?"\\":"/"),this.includeChildMatches=i.includeChildMatches!==false,(i.ignore||!this.includeChildMatches)&&(d(this,Jt,eo(i.ignore??[],i)),!this.includeChildMatches&&typeof b(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",()=>{b(this,_e).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=b(this,_e).shift());)e();}onResume(e){this.signal?.aborted||(this.paused?b(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 h=await s.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(e$1,t){return e$1&&(this.maxDepth===1/0||e$1.depth()<=this.maxDepth)&&(!t||e$1.canReaddir())&&(!this.opts.nodir||!e$1.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e$1.isSymbolicLink()||!e$1.realpathCached()?.isDirectory())&&!e(this,St,ce).call(this,e$1)?e$1: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 h=s.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(e$1,t){if(e(this,St,ce).call(this,e$1))return;if(!this.includeChildMatches&&b(this,Jt)?.add){let h=`${e$1.relativePosix()}/**`;b(this,Jt).add(h);}let i=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e$1);let s=this.opts.mark&&e$1.isDirectory()?b(this,Se):"";if(this.opts.withFileTypes)this.matchEmit(e$1);else if(i){let h=this.opts.posix?e$1.fullpathPosix():e$1.fullpath();this.matchEmit(h+s);}else {let h=this.opts.posix?e$1.relativePosix():e$1.relative(),n=this.opts.dotRelative&&!h.startsWith(".."+b(this,Se))?"."+b(this,Se):"";this.matchEmit(h?n+h+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 Us(this.opts),i);}walkCB2(e$1,t,i,s){if(e(this,St,ws).call(this,e$1))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e$1,t,i,s));return}i.processPatterns(e$1,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())e(this,St,ce).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,i,n):o.readdirCB((l,u)=>this.walkCB3(o,u,i,n),true);}n();}walkCB3(e$1,t,i,s){i=i.filterEntries(e$1,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())e(this,St,ce).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let[o,a]of i.subwalks.entries())h++,this.walkCB2(o,a,i.child(),n);n();}walkCBSync(e,t,i){this.signal?.aborted&&i(),this.walkCB2Sync(e,t,new Us(this.opts),i);}walkCB2Sync(e$1,t,i,s){if(e(this,St,ws).call(this,e$1))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e$1,t,i,s));return}i.processPatterns(e$1,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())e(this,St,ce).call(this,o)||this.matchSync(o,a,l);for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirSync();this.walkCB3Sync(o,a,i,n);}n();}walkCB3Sync(e$1,t,i,s){i=i.filterEntries(e$1,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())e(this,St,ce).call(this,o)||this.matchSync(o,a,l);for(let[o,a]of i.subwalks.entries())h++,this.walkCB2Sync(o,a,i.child(),n);n();}},_e=new WeakMap,Jt=new WeakMap,Se=new WeakMap,St=new WeakSet,ce=function(e){return this.seen.has(e)||!!b(this,Jt)?.ignored?.(e)},ws=function(e){return !!b(this,Jt)?.childrenIgnored?.(e)},gr),Gs=class extends sh{constructor(t,i,s){super(t,i,s);a(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}},Is=class extends sh{constructor(t,i,s){super(t,i,s);a(this,"results");this.results=new Ui({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}},io=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ee=class{constructor(e,t){a(this,"absolute");a(this,"cwd");a(this,"root");a(this,"dot");a(this,"dotRelative");a(this,"follow");a(this,"ignore");a(this,"magicalBraces");a(this,"mark");a(this,"matchBase");a(this,"maxDepth");a(this,"nobrace");a(this,"nocase");a(this,"nodir");a(this,"noext");a(this,"noglobstar");a(this,"pattern");a(this,"platform");a(this,"realpath");a(this,"scurry");a(this,"stat");a(this,"signal");a(this,"windowsPathsNoEscape");a(this,"withFileTypes");a(this,"includeChildMatches");a(this,"opts");a(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=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`);}if(this.pattern=e,this.platform=t.platform||io,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 a=t.platform==="win32"?vs:t.platform==="darwin"?Qr:t.platform?Es:qn;this.scurry=new a(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},h=this.pattern.map(a=>new oe(a,s)),[n,o]=h.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let u=o[l];if(!u)throw new Error("invalid pattern object");return new th(a,u,0,this.platform)});}async walk(){return [...await new Gs(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 Gs(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 Is(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 Is(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()}},so=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let i of e)if(new oe(i,t).hasMagic())return true;return false};function Hi(e,t={}){return new Ee(e,t).streamSync()}function rh(e,t={}){return new Ee(e,t).stream()}function hh(e,t={}){return new Ee(e,t).walkSync()}async function Hs(e,t={}){return new Ee(e,t).walk()}function Ji(e,t={}){return new Ee(e,t).iterateSync()}function nh(e,t={}){return new Ee(e,t).iterate()}var ro=Hi,ho=Object.assign(rh,{sync:Hi}),no=Ji,oo=Object.assign(nh,{sync:Ji}),ao=Object.assign(hh,{stream:Hi,iterate:Ji}),Gi=Object.assign(Hs,{glob:Hs,globSync:hh,sync:ao,globStream:rh,stream:ho,globStreamSync:Hi,streamSync:ro,globIterate:nh,iterate:oo,globIterateSync:Ji,iterateSync:no,Glob:Ee,hasMagic:so,escape:Rr,unescape:Ce});Gi.glob=Gi;var ah;(L=>{L.Level=co.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(F){return t[F]>=t[i]}function h(){return i}L.getLevel=h;let n=new Map;L.Default=T({service:"default"});let a="";function l(){return a}L.file=l;let u,d,f=false,w=()=>{},S=false,E=false;async function b(F){if(f)return;if(F.print){f=true;return}F.level&&(i=F.level);let j=F.logDir||qi.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");await initLog(F),F.logFile?a=qi.join(j,F.logFile??"gateway.log"):a=qi.join(j,"gateway.log");try{await oh.mkdir(j,{recursive:!0}),u=await oh.open(a,"a"),d=createWriteStream("",{fd:u.fd,autoClose:!1}),w=N=>{if(!(S||E||!d||d.destroyed))try{if(!d.writable)return;d.write(N,B=>{if(B&&!S){let M=B;if(M.code==="EPIPE"||M.code==="EIO"){E=!0,d?.destroy();return}S=!0,setTimeout(()=>{S=!1;},1e3);}});}catch(B){let M=B;if(M.code==="EPIPE"||M.code==="EIO"){E=!0,d?.destroy();return}S||(S=!0,setTimeout(()=>{S=!1;},1e3));}},f=!0;}catch(N){process.stderr.write(`[LOG ERROR] Failed to init log file: ${N}
4
- `),w=B=>{try{process.stderr.write(B);}catch{}},f=true;}}L.init=b;async function x(){f&&(d&&!d.destroyed&&(await new Promise((F,j)=>{d.end(N=>{N?j(N):F();});}).catch(F=>{process.stderr.write(`[LOG ERROR] Failed to close log stream: ${F}
5
- `);}),d=void 0),u&&(await u.close().catch(F=>{process.stderr.write(`[LOG ERROR] Failed to close log file: ${F}
6
- `);}),u=void 0),w=F=>{try{process.stderr.write(F);}catch{}},f=false);}L.close=x;function R(F,j=0){let N=F.message;return F.cause instanceof Error&&j<10?N+" Caused by: "+R(F.cause,j+1):N}let A=Date.now();function T(F){F=F||{};let j=F.service;if(j&&typeof j=="string"){let M=n.get(j);if(M)return M}function N(M,ot){let Zi=Object.entries({...F,...ot}).filter(([xs,qt])=>qt!=null).map(([xs,qt])=>{let Vi=`${xs}=`;return qt instanceof Error?Vi+R(qt):typeof qt=="object"?Vi+JSON.stringify(qt):Vi+qt}).join(" "),xe=new Date,lh=xe.getTime()-A;return A=xe.getTime(),[formatLogTime(xe),"+"+lh+"ms",Zi,M].filter(Boolean).join(" ")+`
7
- `}let B={debug(M,ot){s("DEBUG")&&w("DEBUG "+N(M,ot));},info(M,ot){s("INFO")&&w("INFO "+N(M,ot));},error(M,ot){s("ERROR")&&w("ERROR "+N(M,ot));},warn(M,ot){s("WARN")&&w("WARN "+N(M,ot));},tag(M,ot){return F&&(F[M]=ot),B},clone(){return L.create({...F})},time(M,ot){let Zi=Date.now();B.info(M,{status:"started",...ot});function xe(){B.info(M,{status:"completed",duration:Date.now()-Zi,...ot});}return {stop:xe,[Symbol.dispose](){xe();}}}};return j&&typeof j=="string"&&n.set(j,B),B}L.create=T;})(ah||(ah={}));export{ah as a};
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-6TRL3CVJ.mjs';import e from'zod';import R from'path';import {existsSync}from'fs';import de from'fs/promises';var V=a.create({service:"gateway:config"});e.enum(["telegram","slack","feishu","wechat","webchat","signal","nostr"]);e.enum(["low","medium","high","critical"]);var m=e.object({enabled:e.boolean().default(true),botToken:e.string().describe("Telegram Bot Token"),webhookUrl:e.string().optional().describe("Webhook URL for receiving updates"),maxConnections:e.number().int().positive().optional().default(100),timeout:e.number().int().positive().optional().default(3e4)}),y=e.object({enabled:e.boolean().default(true),botToken:e.string().describe("Slack Bot Token (xoxb-*)"),appToken:e.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:e.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:e.number().int().positive().optional().default(100),timeout:e.number().int().positive().optional().default(3e4)}),b=e.object({enabled:e.boolean().default(true),appId:e.string().describe("Feishu App ID"),appSecret:e.string().describe("Feishu App Secret"),encryptKey:e.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:e.string().optional().describe("Feishu Verification Token"),maxConnections:e.number().int().positive().optional().default(100),timeout:e.number().int().positive().optional().default(3e4)}),S=e.object({enabled:e.boolean().default(true),mode:e.enum(["official","wecom"]).default("official"),appId:e.string().describe("WeChat App ID"),appSecret:e.string().describe("WeChat App Secret"),token:e.string().optional().describe("WeChat Token for message verification"),encodingAESKey:e.string().optional().describe("WeChat Encoding AES Key"),agentId:e.string().optional().describe("WeCom Agent ID"),maxConnections:e.number().int().positive().optional().default(100),timeout:e.number().int().positive().optional().default(3e4)}),w=e.object({enabled:e.boolean().default(true),path:e.string().optional().default("/"),heartbeatInterval:e.number().int().positive().optional().default(3e4),connectionTimeout:e.number().int().positive().optional().default(6e4),maxConnections:e.number().int().positive().optional().default(1e3),cors:e.boolean().optional().default(true)}),A=e.object({enabled:e.boolean().default(true),serviceUrl:e.string().optional().default("https://chat.signal.org"),phoneNumber:e.string().describe("Signal phone number"),password:e.string().optional().describe("Signal account password"),maxConnections:e.number().int().positive().optional().default(100),timeout:e.number().int().positive().optional().default(3e4)}),x=e.object({enabled:e.boolean().default(true),relays:e.array(e.string()).min(1).describe("Nostr relay URLs"),privateKey:e.string().optional().describe("Nostr private key (hex)"),publicKey:e.string().optional().describe("Nostr public key (hex)"),maxConnections:e.number().int().positive().optional().default(100),timeout:e.number().int().positive().optional().default(3e4)}),_=e.object({telegram:m.optional(),slack:y.optional(),feishu:b.optional(),wechat:S.optional(),webchat:w.optional(),signal:A.optional(),nostr:x.optional()}),O=e.object({enabled:e.boolean().default(false),cert:e.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:e.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:e.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:e.string().optional().describe("Path to SSL key file (alias of key)"),ca:e.string().optional().describe("Path to CA certificate file"),forceRedirect:e.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:e.number().int().positive().optional().default(80).describe("HTTP redirect port")}),q=e.object({name:e.string().describe("Token name/description"),value:e.string().describe("Token value"),permissions:e.array(e.string()).default(["*"]).describe("Associated permissions"),expiresAt:e.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:e.string().optional().describe("Token description")}),Y=e.object({enabled:e.boolean().default(true),tokens:e.array(q).default([]).describe("List of valid tokens"),onInvalid:e.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:e.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:e.array(e.string()).default([]).describe("Default permissions for anonymous users")}),J=e.object({enabled:e.boolean().default(false),authorizationServer:e.string().describe("OAuth2 authorization server URL"),clientId:e.string().describe("OAuth2 client ID"),clientSecret:e.string().describe("OAuth2 client secret"),tokenValidationEndpoint:e.string().describe("OAuth2 token validation endpoint"),scope:e.array(e.string()).default([]).describe("OAuth2 scopes")}),D=e.object({type:e.enum(["token","oauth2"]).default("token"),token:Y.optional(),oauth2:J.optional()}),j=e.object({mode:e.enum(["pull","push","both"]).default("both"),interval:e.number().int().positive().default(3e4),pushEvents:e.array(e.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:e.enum(["latest","local","remote"]).default("latest")}),$=e.object({id:e.string().describe("Gateway node ID"),address:e.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:e.boolean().default(true),metadata:e.record(e.string(),e.any()).optional()}),z=e.object({nodeId:e.string().describe("Current gateway node ID"),nodes:e.array($).default([]).describe("Other gateway nodes in the cluster"),sync:j.optional()}),v=e.object({maxConnectionsPerChannel:e.number().int().positive().default(100),idleTimeout:e.number().int().positive().default(3e5),reuseStrategy:e.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:e.number().int().positive().default(6e4),acquireTimeout:e.number().int().positive().default(5e3),warmupCount:e.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),T=e.object({maxLength:e.number().int().positive().default(1e4),concurrency:e.number().int().positive().default(100),batchSize:e.number().int().positive().default(10),batchTimeout:e.number().int().positive().default(100),priorityLevels:e.number().int().positive().default(4)}),G=e.object({failureThreshold:e.number().int().positive().default(5),successThreshold:e.number().int().positive().default(3),timeout:e.number().int().positive().default(3e4),halfOpenDuration:e.number().int().positive().default(15e3)}),P=e.object({heartbeatInterval:e.number().int().positive().default(3e4),heartbeatTimeout:e.number().int().positive().default(9e4),heartbeatCheckInterval:e.number().int().positive().default(1e4),autoDeregisterTimeout:e.number().int().positive().default(3e5),maxAgents:e.number().int().positive().default(100),persistenceFile:e.string().optional().describe("Path to persist agent registrations"),maxRegistrations:e.number().int().positive().default(1e3)}),k=e.object({sessionTimeout:e.number().int().positive().default(18e5),resumeGracePeriod:e.number().int().positive().default(3e5),maxSessions:e.number().int().positive().default(1e4),persistenceFile:e.string().optional().describe("Path to persist sessions")}),I=e.object({enabled:e.boolean().default(true),port:e.number().int().positive().default(8080),hostname:e.string().default("localhost"),path:e.string().optional().default("/"),maxConnections:e.number().int().positive().optional().default(1e3),connectionTimeout:e.number().int().positive().optional().default(6e4),heartbeatInterval:e.number().int().positive().optional().default(3e4),sessionExpireMs:e.number().int().positive().optional().default(3e5),https:O.optional(),auth:D.optional(),cors:e.boolean().default(true),corsOrigins:e.array(e.string()).optional(),mdns:e.boolean().default(false),mdnsDomain:e.string().optional().default("gateway.easbot.local")}),d=e.object({server:I.optional(),channels:_.optional(),cluster:z.optional(),connectionPool:v.optional(),messageQueue:T.optional(),circuitBreaker:G.optional(),agentRegistry:P.optional(),session:k.optional(),defaultAgent:e.string().optional().describe("Default agent ID for routing"),logLevel:e.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(e.unknown());function F(t){let n=d.safeParse(t);return n.success||V.warn("Invalid gateway config",{issues:n.error.issues}),n.success?n.data:d.parse({})}function X(t){return d.parse(t)}var ue=a.create({service:"gateway:interfaces"}),f;function qe(t){f=t,ue.debug("Agent adapter registered",{hasSubAgentRunner:!!t.subAgentRunner});}function Ye(){return f}function Je(){return f!==void 0}function $e(){if(!f)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return f}var pe={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},Ce={directory:process.cwd(),worktree:process.cwd()};function Q(){return f?f.global:pe}function L(){return f?f.instance:Ce}var g=a.create({service:"gateway:config"}),U={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}},me={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},ye={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},be={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},Se={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3},we={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e4},Ae={enabled:true,botToken:"",maxConnections:100,timeout:3e4},xe={enabled:true,botToken:"",maxConnections:100,timeout:3e4},ve={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},Te={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},Ge={enabled:true,path:"/ws",heartbeatInterval:3e4,connectionTimeout:6e4,maxConnections:1e3,cors:true},Pe={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},ke={enabled:true,relays:[],maxConnections:100,timeout:3e4},p,h=null;async function K(t){try{if(!existsSync(t))return null;let n=await de.readFile(t,"utf-8"),o=n,s=!1,a=!1,r=[];for(let i=0;i<n.length;i++){let l=n[i];if(a){r.push(l),a=!1;continue}if(l==="\\"){r.push(l),a=!0;continue}if(l==='"'){s=!s,r.push(l);continue}if(!s&&l==="/"&&n[i+1]==="/"){for(;i<n.length&&n[i]!==`
2
- `&&n[i]!=="\r";)i++;continue}if(!s&&l==="/"&&n[i+1]==="*"){for(i+=2;i<n.length-1;){if(n[i]==="*"&&n[i+1]==="/"){i+=2;break}i++;}continue}r.push(l);}return o=r.join("").trim(),o?JSON.parse(o):null}catch(n){return g.debug("Failed to load config file",{file:t,error:String(n)}),null}}function C(t,n){let o={...t,...n};return (t.server||n.server)&&(o.server={...t.server,...n.server}),(t.channels||n.channels)&&(o.channels={...t.channels,...n.channels}),o}async function Ie(){let t=Q(),n=L(),o=[],s=R.join(t.Path.config);o.push(s),o.push(n.directory);try{let{Filesystem:r}=await import('@easbot/utils'),i=await Array.fromAsync(r.up({targets:[".easbot"],start:n.directory,stop:n.worktree}));o.push(...i);}catch{g.debug("Filesystem utils not available, using basic directories");}let a=process.env.EASBOT_CONFIG_DIR;return a&&(o.push(a),g.debug("Using EASBOT_CONFIG_DIR",{path:a})),[...new Set(o)]}async function Ne(t){let n=["gateway.json"],o={};for(let s of n){let a=R.join(t,s),r=await K(a);if(r)if("gateway"in r&&r.gateway){let i=r.gateway;"server"in i||"channels"in i||"cluster"in i?o=C(o,i):o=C(o,{server:i}),g.debug("Loaded gateway config from file (nested format)",{file:a});}else "gateway"in r||(o=C(o,r),g.debug("Loaded gateway config from file (direct format)",{file:a}));}return o}async function Ee(t){let n=["easbot.json"];for(let o of n){let s=R.join(t,o),a=await K(s);if(a?.gateway)return g.debug("Loaded gateway config from easbot.json",{file:s}),a.gateway}return {}}function Fe(){return p||(p=async()=>{let t=await Ie(),n={};for(let s of t){let a=await Ne(s);n=C(n,a);let r=await Ee(s);n=C(n,r);}let o=F(n);return h=o,g.info("Gateway config loaded",{directories:t.length,port:o.server?.port,logLevel:o.logLevel}),{config:o,directories:t}}),p}async function c(){return Fe()()}async function W(t){return t&&(p=void 0,h=null),(await c()).config}function H(){return h}function B(){return h!==null}function Z(){p=void 0,h=null,g.debug("Config cache cleared");}function ee(){return L().directory}async function te(){let{config:t}=await c();return I.parse({...U,...t.server})}async function ne(t){let{config:n}=await c(),o=n.channels?.[t],a={telegram:m.parse(Ae),slack:y.parse(xe),feishu:b.parse(ve),wechat:S.parse(Te),webchat:w.parse(Ge),signal:A.parse(Pe),nostr:x.parse(ke)}[t];if(!a)throw new Error(`Unknown channel type: ${t}`);return {...a,...o}}async function oe(){let{config:t}=await c();return v.parse({...me,...t.connectionPool})}async function ie(){let{config:t}=await c();return T.parse({...ye,...t.messageQueue})}async function ae(){let{config:t}=await c();return G.parse({...be,...t.circuitBreaker})}async function re(){let{config:t}=await c();return P.parse({...Se,...t.agentRegistry})}async function se(){let{config:t}=await c();return k.parse({...we,...t.session})}async function ce(){let{config:t}=await c();return t.server?.https}async function le(){let{config:t}=await c();return t.server?.auth}async function fe(){let{config:t}=await c();return t.cluster}async function ge(){let{config:t}=await c();return t.defaultAgent}async function M(){let{config:t}=await c();return t.logLevel??"INFO"}export{ee as A,te as B,ne as C,oe as D,ie as E,ae as F,re as G,se as H,ce as I,le as J,fe as K,ge as L,M,qe as N,Ye as O,Je as P,$e as Q,Q as R,L as S,m as a,y as b,b as c,S as d,w as e,A as f,x as g,_ as h,O as i,D as j,j as k,z as l,v as m,T as n,G as o,P as p,k as q,I as r,d as s,F as t,X as u,U as v,W as w,H as x,B as y,Z as z};
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkRR6UFR5U_cjs=require('./chunk-RR6UFR5U.cjs'),chunk5ETPYYQR_cjs=require('./chunk-5ETPYYQR.cjs'),chunkGY3SWWW3_cjs=require('./chunk-GY3SWWW3.cjs'),p=require('fs'),H=require('path'),utils=require('@easbot/utils'),ws=require('ws'),j=require('https'),Q=require('http'),plugin=require('@easbot/plugin');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var p__namespace=/*#__PURE__*/_interopNamespace(p);var H__namespace=/*#__PURE__*/_interopNamespace(H);var j__default=/*#__PURE__*/_interopDefault(j);var Q__default=/*#__PURE__*/_interopDefault(Q);var M=class{constructor(e={}){chunkGY3SWWW3_cjs.a(this,"log",chunk5ETPYYQR_cjs.a.create({service:"gateway:lock"}));chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"locks",new Map);chunkGY3SWWW3_cjs.a(this,"cleanupTimer",null);this.config={defaultTimeout:e.defaultTimeout??6e4,checkInterval:e.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}};var I=class{constructor(e={}){chunkGY3SWWW3_cjs.a(this,"log",chunk5ETPYYQR_cjs.a.create({service:"gateway:retry"}));chunkGY3SWWW3_cjs.a(this,"policy");chunkGY3SWWW3_cjs.a(this,"retryQueue",new Map);chunkGY3SWWW3_cjs.a(this,"retryTimer",null);chunkGY3SWWW3_cjs.a(this,"handlers",new Map);this.policy={maxRetries:e.maxRetries??3,initialDelay:e.initialDelay??1e3,maxDelay:e.maxDelay??3e4,backoffMultiplier:e.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}}};function _(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 N(c,e,t,s){return _(c,e,[{type:"text",text:t}],s)}function T(c){let e=[c.platform,c.channelId];return c.chatId&&e.push(c.chatId),c.userId&&e.push(c.userId),e.join("_")}function R(){return {status:"active",messageCount:0,lastMessageAt:null}}function k(c,e){return `sub_${c}_${e}`}var E=chunkRR6UFR5U_cjs.v,m={maxConnections:1e3,connectionTimeout:6e4,sessionExpireMs:3e5};var B={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var q={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};var F={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var U={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var x=class{constructor(){chunkGY3SWWW3_cjs.a(this,"log",chunk5ETPYYQR_cjs.a.create({service:"gateway:router"}));chunkGY3SWWW3_cjs.a(this,"subscribers",new Map);chunkGY3SWWW3_cjs.a(this,"subscriptions",new Map);chunkGY3SWWW3_cjs.a(this,"sessionSubscriptions",new Map);chunkGY3SWWW3_cjs.a(this,"channelPlugins",new Map);chunkGY3SWWW3_cjs.a(this,"lockManager");chunkGY3SWWW3_cjs.a(this,"retryManager");chunkGY3SWWW3_cjs.a(this,"cancelHandlers",new Set);this.lockManager=new M,this.retryManager=new I,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 l=this.subscribers.get(g.subscriberId);if(l){if(e.type==="input"){if(!this.lockManager.tryAcquire(e.sessionId,e.id,l.id)){this.log.debug("skipping subscriber, lock held by another",{subscriberId:l.id,holder:this.lockManager.getHolder(e.sessionId)});continue}n=l.id;}try{await l.connection.send(e),s++,l.lastActiveAt=Date.now();}catch(h){this.log.warn("failed to send message to subscriber",{subscriberId:l.id,error:String(h)}),r.push(h instanceof Error?h:new Error(String(h))),n===l.id&&(this.lockManager.release(e.sessionId,l.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=k(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=k(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");}};var S=class{constructor(e={}){chunkGY3SWWW3_cjs.a(this,"log",chunk5ETPYYQR_cjs.a.create({service:"gateway:message-store"}));chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"messages",new Map);chunkGY3SWWW3_cjs.a(this,"sessionMessages",new Map);this.config={storagePath:e.storagePath??"./data/gateway-messages",maxRetentionDays:e.maxRetentionDays??30,maxRecords:e.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}};var b=class{constructor(e={}){chunkGY3SWWW3_cjs.a(this,"log",chunk5ETPYYQR_cjs.a.create({service:"gateway:session-store"}));chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"sessions",new Map);chunkGY3SWWW3_cjs.a(this,"channelSessions",new Map);chunkGY3SWWW3_cjs.a(this,"autoSaveTimer",null);chunkGY3SWWW3_cjs.a(this,"isDirty",false);this.config={storagePath:e.storagePath??"./data/gateway-sessions",autoSaveInterval:e.autoSaveInterval??6e4,maxRetentionDays:e.maxRetentionDays??7,enablePersistence:e.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 p__namespace.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(!p__namespace.existsSync(e)){this.log.debug("no saved sessions found");return}let t=await p__namespace.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 H__namespace.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){p__namespace.existsSync(this.config.storagePath)||await p__namespace.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 v=class{constructor(e={}){chunkGY3SWWW3_cjs.a(this,"log",chunk5ETPYYQR_cjs.a.create({service:"gateway:session"}));chunkGY3SWWW3_cjs.a(this,"sessionStore");chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"initialized",false);this.config={enablePersistence:e.enablePersistence??true,storagePath:e.storagePath??"./data/gateway-sessions",autoSaveInterval:e.autoSaveInterval??6e4,maxRetentionDays:e.maxRetentionDays??7},this.sessionStore=new b({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=T(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:R(),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()}};var C=class{constructor(e={}){chunkGY3SWWW3_cjs.a(this,"log",chunk5ETPYYQR_cjs.a.create({service:"gateway:plugin-loader"}));chunkGY3SWWW3_cjs.a(this,"plugins",new Map);chunkGY3SWWW3_cjs.a(this,"messageHandler",null);chunkGY3SWWW3_cjs.a(this,"healthCheckTimer",null);chunkGY3SWWW3_cjs.a(this,"config");this.config={pluginDir:e.pluginDir??"./plugins",autoDiscover:e.autoDiscover??false,healthCheckInterval:e.healthCheckInterval??6e4,healthCheckTimeout:e.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)}};var o=chunk5ETPYYQR_cjs.a.create({service:"gateway:websocket-server"});function V(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function A(c,e){for(let[t,s]of e.entries())if(s===c)return t;return null}var w=class{constructor(e={}){chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"server",null);chunkGY3SWWW3_cjs.a(this,"wss",null);chunkGY3SWWW3_cjs.a(this,"httpsServer",null);chunkGY3SWWW3_cjs.a(this,"httpRedirectServer",null);chunkGY3SWWW3_cjs.a(this,"connections",new Map);chunkGY3SWWW3_cjs.a(this,"subscriptions",new Map);chunkGY3SWWW3_cjs.a(this,"sessionSubscriptions",new Map);chunkGY3SWWW3_cjs.a(this,"sessionLastActivity",new Map);chunkGY3SWWW3_cjs.a(this,"cleanupInterval",null);chunkGY3SWWW3_cjs.a(this,"heartbeatInterval",null);chunkGY3SWWW3_cjs.a(this,"startTime",0);chunkGY3SWWW3_cjs.a(this,"running",false);this.config={...E,...e};}async start(){if(this.running){o.warn("WebSocket server is already running");return}o.debug("WebSocket server start: checking configuration",{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:(n,r)=>{this.handleConnection(r);},onMessage:async(n,r)=>{try{let a=JSON.parse(n.data.toString());await this.handleMessage(r,a);}catch(a){o.error("Error processing WebSocket message",{error:a.message}),this.sendError(r,a.message);}},onClose:(n,r)=>{this.handleDisconnection(r);},onError:(n,r)=>{o.error("WebSocket error",{error:n.type});}},t=this.config.https?.enabled??false;o.debug("WebSocket server start: choosing server type",{https:t});try{t?(o.debug("WebSocket server start: starting HTTPS server"),await this.startHTTPSServer(e)):(o.debug("WebSocket server start: starting HTTP server"),await this.startHTTPServer(e)),o.debug("WebSocket server start: HTTP/HTTPS server started successfully");}catch(n){throw o.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}o.debug("WebSocket server start: server initialization complete"),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=t?"wss":"ws";o.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(e){o.debug("HTTP server start: creating server",{port:this.config.port,hostname:this.config.hostname}),this.server=utils.createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true}),o.debug("HTTP server start: server created, checking raw server");let t=this.server.raw;t?(o.debug("HTTP server start: raw server available, setting up WebSocket upgrade"),this.setupWebSocketUpgrade(t,e),o.debug("HTTP server start: WebSocket upgrade configured")):o.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(e){let t=this.config.https,s=this.loadSSLCertificates(t);if(!s){o.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(e);return}this.server=utils.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=j__default.default.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,e),await new Promise(r=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{o.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:p__namespace.default.readFileSync(e.certPath),key:p__namespace.default.readFileSync(e.keyPath)}:null}catch(t){return o.error("Failed to load SSL certificates",{error:t.message}),null}}setupWebSocketUpgrade(e,t){this.wss=new ws.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,l=>{t.onOpen?.({type:"open"},l),l.on("message",h=>{t.onMessage?.({data:h},l);}),l.on("close",(h,G)=>{t.onClose?.({code:h,reason:G},l);}),l.on("error",h=>{t.onError?.({type:"error",message:h.message},l);});});}catch{}});}startHTTPRedirectServer(e){this.httpRedirectServer=Q__default.default.createServer((t,s)=>{let r=`https://${t.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${t.url}`;o.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,()=>{o.info("HTTP redirect server started",{port:e,hostname:this.config.hostname});});}async stop(){if(!this.running){o.warn("WebSocket server is not running");return}o.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){o.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,o.info("WebSocket server stopped");}broadcastToSession(e,t){this.touchSession(e);let s=this.sessionSubscriptions.get(e);if(!s||s.size===0){o.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)){o.debug("Event type not subscribed, skipping",{clientId:a,sessionId:e,eventType:t.type,subscribedTypes:Array.from(g.subscribedEventTypes)});continue}g.ws.send(r),o.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??m.maxConnections)){o.warn("Maximum connections reached, rejecting new connection"),e.close(1013,"Maximum connections reached");return}let t=V();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()}),o.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=A(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);}o.info("WebSocket client disconnected",{clientId:t,totalConnections:this.connections.size});}async handleMessage(e,t){let s=A(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=A(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);o.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=A(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)),o.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}o.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}o.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}o.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??m.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){o.info("Closing inactive connection",{clientId:n,lastActivityAt:r.lastActivityAt,timeoutMs:t});try{r.ws.close(1001,"Connection timeout");}catch(a){o.debug("Error closing timed out connection",{clientId:n,error:String(a)});}}}s.length>0&&o.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size-s.length});}cleanupExpiredSessions(){let e=Date.now(),t=[],s=this.config.sessionExpireMs??m.sessionExpireMs;for(let[n,r]of this.sessionLastActivity.entries())e-r>s&&t.push(n);for(let n of t)o.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&&o.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),o.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 o.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 K(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 O=class{constructor(e){chunkGY3SWWW3_cjs.a(this,"log",chunk5ETPYYQR_cjs.a.create({service:"gateway:server"}));chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"router");chunkGY3SWWW3_cjs.a(this,"sessionManager");chunkGY3SWWW3_cjs.a(this,"pluginLoader");chunkGY3SWWW3_cjs.a(this,"messageStore");chunkGY3SWWW3_cjs.a(this,"wsServer",null);chunkGY3SWWW3_cjs.a(this,"running",false);chunkGY3SWWW3_cjs.a(this,"connections",0);this.log.debug("GatewayServer.constructor: starting"),this.config=e,this.log.debug("GatewayServer.constructor: creating MessageRouter"),this.router=new x,this.log.debug("GatewayServer.constructor: creating GatewaySessionManager"),this.sessionManager=new v,this.log.debug("GatewayServer.constructor: creating ChannelPluginLoader"),this.pluginLoader=new C({healthCheckInterval:6e4}),this.log.debug("GatewayServer.constructor: pluginLoader created");let t=chunkRR6UFR5U_cjs.R(),s=chunkRR6UFR5U_cjs.P();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:s}),this.messageStore=new S({storagePath:`${t.Path.data}/gateway-messages`}),s&&(this.log.debug("GatewayServer.constructor: adapter exists, setting message storage"),chunkRR6UFR5U_cjs.Q().setMessageStorage({store:async r=>{let a=K(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)}),this.log.debug("GatewayServer.constructor: completed");}async start(){if(this.log.debug("GatewayServer.start: called"),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}),this.log.debug("GatewayServer.start: initializing sessionManager"),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),this.log.debug("GatewayServer.start: creating WebSocket server"),this.wsServer=new w({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),this.log.debug("GatewayServer.start: calling wsServer.start()"),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),this.log.debug("GatewayServer.start: calling pluginLoader.startAll()"),await this.pluginLoader.startAll(),this.log.debug("GatewayServer.start: pluginLoader started"),this.log.debug("GatewayServer.start: starting health check timer"),this.pluginLoader.startHealthCheckTimer(),this.running=true,this.log.debug("GatewayServer.start: completed"),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.wsServer&&(this.log.debug("stopping WebSocket server"),await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),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),chunkRR6UFR5U_cjs.P())try{let t=chunkRR6UFR5U_cjs.Q(),s={name:plugin.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}),chunkRR6UFR5U_cjs.P())try{await chunkRR6UFR5U_cjs.Q().hookRegistry.emit({name:plugin.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:l,duration:h}=n;if(await this.messageStore.updateStatus(t,r?"completed":"failed",{processedBy:s,error:a}),chunkRR6UFR5U_cjs.P())try{await chunkRR6UFR5U_cjs.Q().hookRegistry.emit({name:plugin.HookEvent.GatewayMessageComplete,data:{messageId:t,sessionId:e,processorId:s,status:r?"completed":"failed",error:a,responseMessageId:g,tokens:l,duration:h,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(chunkRR6UFR5U_cjs.P())try{await chunkRR6UFR5U_cjs.Q().hookRegistry.emit({name:plugin.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
- exports.a=M;exports.b=I;exports.c=_;exports.d=N;exports.e=T;exports.f=R;exports.g=k;exports.h=E;exports.i=B;exports.j=q;exports.k=F;exports.l=U;exports.m=x;exports.n=S;exports.o=b;exports.p=v;exports.q=C;exports.r=w;exports.s=O;
@@ -1,2 +0,0 @@
1
- import {v as v$1,R as R$1,P as P$1,Q as Q$1}from'./chunk-77F43CRD.mjs';import {a}from'./chunk-6TRL3CVJ.mjs';import {a as a$1}from'./chunk-HAMGVOQD.mjs';import*as f from'fs';import f__default from'fs';import*as W from'path';import {createServer}from'@easbot/utils';import {WebSocketServer}from'ws';import Q from'https';import V from'http';import {HookEvent}from'@easbot/plugin';var I=class{constructor(e={}){a$1(this,"log",a.create({service:"gateway:lock"}));a$1(this,"config");a$1(this,"locks",new Map);a$1(this,"cleanupTimer",null);this.config={defaultTimeout:e.defaultTimeout??6e4,checkInterval:e.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}};var k=class{constructor(e={}){a$1(this,"log",a.create({service:"gateway:retry"}));a$1(this,"policy");a$1(this,"retryQueue",new Map);a$1(this,"retryTimer",null);a$1(this,"handlers",new Map);this.policy={maxRetries:e.maxRetries??3,initialDelay:e.initialDelay??1e3,maxDelay:e.maxDelay??3e4,backoffMultiplier:e.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}}};function H(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 B(c,e,t,s){return H(c,e,[{type:"text",text:t}],s)}function R(c){let e=[c.platform,c.channelId];return c.chatId&&e.push(c.chatId),c.userId&&e.push(c.userId),e.join("_")}function E(){return {status:"active",messageCount:0,lastMessageAt:null}}function x(c,e){return `sub_${c}_${e}`}var G=v$1,S={maxConnections:1e3,connectionTimeout:6e4,sessionExpireMs:3e5};var q={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var F={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};var U={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var $={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var A=class{constructor(){a$1(this,"log",a.create({service:"gateway:router"}));a$1(this,"subscribers",new Map);a$1(this,"subscriptions",new Map);a$1(this,"sessionSubscriptions",new Map);a$1(this,"channelPlugins",new Map);a$1(this,"lockManager");a$1(this,"retryManager");a$1(this,"cancelHandlers",new Set);this.lockManager=new I,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 l=this.subscribers.get(g.subscriberId);if(l){if(e.type==="input"){if(!this.lockManager.tryAcquire(e.sessionId,e.id,l.id)){this.log.debug("skipping subscriber, lock held by another",{subscriberId:l.id,holder:this.lockManager.getHolder(e.sessionId)});continue}n=l.id;}try{await l.connection.send(e),s++,l.lastActiveAt=Date.now();}catch(p){this.log.warn("failed to send message to subscriber",{subscriberId:l.id,error:String(p)}),r.push(p instanceof Error?p:new Error(String(p))),n===l.id&&(this.lockManager.release(e.sessionId,l.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=x(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=x(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");}};var b=class{constructor(e={}){a$1(this,"log",a.create({service:"gateway:message-store"}));a$1(this,"config");a$1(this,"messages",new Map);a$1(this,"sessionMessages",new Map);this.config={storagePath:e.storagePath??"./data/gateway-messages",maxRetentionDays:e.maxRetentionDays??30,maxRecords:e.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}};var v=class{constructor(e={}){a$1(this,"log",a.create({service:"gateway:session-store"}));a$1(this,"config");a$1(this,"sessions",new Map);a$1(this,"channelSessions",new Map);a$1(this,"autoSaveTimer",null);a$1(this,"isDirty",false);this.config={storagePath:e.storagePath??"./data/gateway-sessions",autoSaveInterval:e.autoSaveInterval??6e4,maxRetentionDays:e.maxRetentionDays??7,enablePersistence:e.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 f.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(!f.existsSync(e)){this.log.debug("no saved sessions found");return}let t=await f.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 W.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){f.existsSync(this.config.storagePath)||await f.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 C=class{constructor(e={}){a$1(this,"log",a.create({service:"gateway:session"}));a$1(this,"sessionStore");a$1(this,"config");a$1(this,"initialized",false);this.config={enablePersistence:e.enablePersistence??true,storagePath:e.storagePath??"./data/gateway-sessions",autoSaveInterval:e.autoSaveInterval??6e4,maxRetentionDays:e.maxRetentionDays??7},this.sessionStore=new v({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=R(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:E(),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()}};var w=class{constructor(e={}){a$1(this,"log",a.create({service:"gateway:plugin-loader"}));a$1(this,"plugins",new Map);a$1(this,"messageHandler",null);a$1(this,"healthCheckTimer",null);a$1(this,"config");this.config={pluginDir:e.pluginDir??"./plugins",autoDiscover:e.autoDiscover??false,healthCheckInterval:e.healthCheckInterval??6e4,healthCheckTimeout:e.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)}};var o=a.create({service:"gateway:websocket-server"});function K(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function P(c,e){for(let[t,s]of e.entries())if(s===c)return t;return null}var M=class{constructor(e={}){a$1(this,"config");a$1(this,"server",null);a$1(this,"wss",null);a$1(this,"httpsServer",null);a$1(this,"httpRedirectServer",null);a$1(this,"connections",new Map);a$1(this,"subscriptions",new Map);a$1(this,"sessionSubscriptions",new Map);a$1(this,"sessionLastActivity",new Map);a$1(this,"cleanupInterval",null);a$1(this,"heartbeatInterval",null);a$1(this,"startTime",0);a$1(this,"running",false);this.config={...G,...e};}async start(){if(this.running){o.warn("WebSocket server is already running");return}o.debug("WebSocket server start: checking configuration",{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:(n,r)=>{this.handleConnection(r);},onMessage:async(n,r)=>{try{let a=JSON.parse(n.data.toString());await this.handleMessage(r,a);}catch(a){o.error("Error processing WebSocket message",{error:a.message}),this.sendError(r,a.message);}},onClose:(n,r)=>{this.handleDisconnection(r);},onError:(n,r)=>{o.error("WebSocket error",{error:n.type});}},t=this.config.https?.enabled??false;o.debug("WebSocket server start: choosing server type",{https:t});try{t?(o.debug("WebSocket server start: starting HTTPS server"),await this.startHTTPSServer(e)):(o.debug("WebSocket server start: starting HTTP server"),await this.startHTTPServer(e)),o.debug("WebSocket server start: HTTP/HTTPS server started successfully");}catch(n){throw o.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}o.debug("WebSocket server start: server initialization complete"),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=t?"wss":"ws";o.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(e){o.debug("HTTP server start: creating server",{port:this.config.port,hostname:this.config.hostname}),this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true}),o.debug("HTTP server start: server created, checking raw server");let t=this.server.raw;t?(o.debug("HTTP server start: raw server available, setting up WebSocket upgrade"),this.setupWebSocketUpgrade(t,e),o.debug("HTTP server start: WebSocket upgrade configured")):o.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(e){let t=this.config.https,s=this.loadSSLCertificates(t);if(!s){o.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=Q.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,e),await new Promise(r=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{o.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:f__default.readFileSync(e.certPath),key:f__default.readFileSync(e.keyPath)}:null}catch(t){return o.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,l=>{t.onOpen?.({type:"open"},l),l.on("message",p=>{t.onMessage?.({data:p},l);}),l.on("close",(p,D)=>{t.onClose?.({code:p,reason:D},l);}),l.on("error",p=>{t.onError?.({type:"error",message:p.message},l);});});}catch{}});}startHTTPRedirectServer(e){this.httpRedirectServer=V.createServer((t,s)=>{let r=`https://${t.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${t.url}`;o.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,()=>{o.info("HTTP redirect server started",{port:e,hostname:this.config.hostname});});}async stop(){if(!this.running){o.warn("WebSocket server is not running");return}o.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){o.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,o.info("WebSocket server stopped");}broadcastToSession(e,t){this.touchSession(e);let s=this.sessionSubscriptions.get(e);if(!s||s.size===0){o.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)){o.debug("Event type not subscribed, skipping",{clientId:a,sessionId:e,eventType:t.type,subscribedTypes:Array.from(g.subscribedEventTypes)});continue}g.ws.send(r),o.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??S.maxConnections)){o.warn("Maximum connections reached, rejecting new connection"),e.close(1013,"Maximum connections reached");return}let t=K();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()}),o.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=P(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);}o.info("WebSocket client disconnected",{clientId:t,totalConnections:this.connections.size});}async handleMessage(e,t){let s=P(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=P(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);o.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=P(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)),o.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}o.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}o.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}o.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??S.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){o.info("Closing inactive connection",{clientId:n,lastActivityAt:r.lastActivityAt,timeoutMs:t});try{r.ws.close(1001,"Connection timeout");}catch(a){o.debug("Error closing timed out connection",{clientId:n,error:String(a)});}}}s.length>0&&o.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size-s.length});}cleanupExpiredSessions(){let e=Date.now(),t=[],s=this.config.sessionExpireMs??S.sessionExpireMs;for(let[n,r]of this.sessionLastActivity.entries())e-r>s&&t.push(n);for(let n of t)o.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&&o.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),o.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 o.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 J(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 N=class{constructor(e){a$1(this,"log",a.create({service:"gateway:server"}));a$1(this,"config");a$1(this,"router");a$1(this,"sessionManager");a$1(this,"pluginLoader");a$1(this,"messageStore");a$1(this,"wsServer",null);a$1(this,"running",false);a$1(this,"connections",0);this.log.debug("GatewayServer.constructor: starting"),this.config=e,this.log.debug("GatewayServer.constructor: creating MessageRouter"),this.router=new A,this.log.debug("GatewayServer.constructor: creating GatewaySessionManager"),this.sessionManager=new C,this.log.debug("GatewayServer.constructor: creating ChannelPluginLoader"),this.pluginLoader=new w({healthCheckInterval:6e4}),this.log.debug("GatewayServer.constructor: pluginLoader created");let t=R$1(),s=P$1();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:s}),this.messageStore=new b({storagePath:`${t.Path.data}/gateway-messages`}),s&&(this.log.debug("GatewayServer.constructor: adapter exists, setting message storage"),Q$1().setMessageStorage({store:async r=>{let a=J(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)}),this.log.debug("GatewayServer.constructor: completed");}async start(){if(this.log.debug("GatewayServer.start: called"),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}),this.log.debug("GatewayServer.start: initializing sessionManager"),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),this.log.debug("GatewayServer.start: creating WebSocket server"),this.wsServer=new M({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),this.log.debug("GatewayServer.start: calling wsServer.start()"),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),this.log.debug("GatewayServer.start: calling pluginLoader.startAll()"),await this.pluginLoader.startAll(),this.log.debug("GatewayServer.start: pluginLoader started"),this.log.debug("GatewayServer.start: starting health check timer"),this.pluginLoader.startHealthCheckTimer(),this.running=true,this.log.debug("GatewayServer.start: completed"),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.wsServer&&(this.log.debug("stopping WebSocket server"),await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),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),P$1())try{let t=Q$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}),P$1())try{await Q$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:l,duration:p}=n;if(await this.messageStore.updateStatus(t,r?"completed":"failed",{processedBy:s,error:a}),P$1())try{await Q$1().hookRegistry.emit({name:HookEvent.GatewayMessageComplete,data:{messageId:t,sessionId:e,processorId:s,status:r?"completed":"failed",error:a,responseMessageId:g,tokens:l,duration:p,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(P$1())try{await Q$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{I as a,k as b,H as c,B as d,R as e,E as f,x as g,G as h,q as i,F as j,U as k,$ as l,A as m,b as n,v as o,C as p,w as q,M as r,N as s};
@@ -1,2 +0,0 @@
1
- 'use strict';var chunk5ETPYYQR_cjs=require('./chunk-5ETPYYQR.cjs'),e=require('zod'),L=require('path'),fs=require('fs'),he=require('fs/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var e__default=/*#__PURE__*/_interopDefault(e);var L__default=/*#__PURE__*/_interopDefault(L);var he__default=/*#__PURE__*/_interopDefault(he);var K=chunk5ETPYYQR_cjs.a.create({service:"gateway:config"});e__default.default.enum(["telegram","slack","feishu","wechat","webchat","signal","nostr"]);e__default.default.enum(["low","medium","high","critical"]);var m=e__default.default.object({enabled:e__default.default.boolean().default(true),botToken:e__default.default.string().describe("Telegram Bot Token"),webhookUrl:e__default.default.string().optional().describe("Webhook URL for receiving updates"),maxConnections:e__default.default.number().int().positive().optional().default(100),timeout:e__default.default.number().int().positive().optional().default(3e4)}),y=e__default.default.object({enabled:e__default.default.boolean().default(true),botToken:e__default.default.string().describe("Slack Bot Token (xoxb-*)"),appToken:e__default.default.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:e__default.default.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:e__default.default.number().int().positive().optional().default(100),timeout:e__default.default.number().int().positive().optional().default(3e4)}),b=e__default.default.object({enabled:e__default.default.boolean().default(true),appId:e__default.default.string().describe("Feishu App ID"),appSecret:e__default.default.string().describe("Feishu App Secret"),encryptKey:e__default.default.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:e__default.default.string().optional().describe("Feishu Verification Token"),maxConnections:e__default.default.number().int().positive().optional().default(100),timeout:e__default.default.number().int().positive().optional().default(3e4)}),S=e__default.default.object({enabled:e__default.default.boolean().default(true),mode:e__default.default.enum(["official","wecom"]).default("official"),appId:e__default.default.string().describe("WeChat App ID"),appSecret:e__default.default.string().describe("WeChat App Secret"),token:e__default.default.string().optional().describe("WeChat Token for message verification"),encodingAESKey:e__default.default.string().optional().describe("WeChat Encoding AES Key"),agentId:e__default.default.string().optional().describe("WeCom Agent ID"),maxConnections:e__default.default.number().int().positive().optional().default(100),timeout:e__default.default.number().int().positive().optional().default(3e4)}),w=e__default.default.object({enabled:e__default.default.boolean().default(true),path:e__default.default.string().optional().default("/"),heartbeatInterval:e__default.default.number().int().positive().optional().default(3e4),connectionTimeout:e__default.default.number().int().positive().optional().default(6e4),maxConnections:e__default.default.number().int().positive().optional().default(1e3),cors:e__default.default.boolean().optional().default(true)}),A=e__default.default.object({enabled:e__default.default.boolean().default(true),serviceUrl:e__default.default.string().optional().default("https://chat.signal.org"),phoneNumber:e__default.default.string().describe("Signal phone number"),password:e__default.default.string().optional().describe("Signal account password"),maxConnections:e__default.default.number().int().positive().optional().default(100),timeout:e__default.default.number().int().positive().optional().default(3e4)}),x=e__default.default.object({enabled:e__default.default.boolean().default(true),relays:e__default.default.array(e__default.default.string()).min(1).describe("Nostr relay URLs"),privateKey:e__default.default.string().optional().describe("Nostr private key (hex)"),publicKey:e__default.default.string().optional().describe("Nostr public key (hex)"),maxConnections:e__default.default.number().int().positive().optional().default(100),timeout:e__default.default.number().int().positive().optional().default(3e4)}),R=e__default.default.object({telegram:m.optional(),slack:y.optional(),feishu:b.optional(),wechat:S.optional(),webchat:w.optional(),signal:A.optional(),nostr:x.optional()}),_=e__default.default.object({enabled:e__default.default.boolean().default(false),cert:e__default.default.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:e__default.default.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:e__default.default.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:e__default.default.string().optional().describe("Path to SSL key file (alias of key)"),ca:e__default.default.string().optional().describe("Path to CA certificate file"),forceRedirect:e__default.default.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:e__default.default.number().int().positive().optional().default(80).describe("HTTP redirect port")}),V=e__default.default.object({name:e__default.default.string().describe("Token name/description"),value:e__default.default.string().describe("Token value"),permissions:e__default.default.array(e__default.default.string()).default(["*"]).describe("Associated permissions"),expiresAt:e__default.default.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:e__default.default.string().optional().describe("Token description")}),q=e__default.default.object({enabled:e__default.default.boolean().default(true),tokens:e__default.default.array(V).default([]).describe("List of valid tokens"),onInvalid:e__default.default.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:e__default.default.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:e__default.default.array(e__default.default.string()).default([]).describe("Default permissions for anonymous users")}),Y=e__default.default.object({enabled:e__default.default.boolean().default(false),authorizationServer:e__default.default.string().describe("OAuth2 authorization server URL"),clientId:e__default.default.string().describe("OAuth2 client ID"),clientSecret:e__default.default.string().describe("OAuth2 client secret"),tokenValidationEndpoint:e__default.default.string().describe("OAuth2 token validation endpoint"),scope:e__default.default.array(e__default.default.string()).default([]).describe("OAuth2 scopes")}),O=e__default.default.object({type:e__default.default.enum(["token","oauth2"]).default("token"),token:q.optional(),oauth2:Y.optional()}),D=e__default.default.object({mode:e__default.default.enum(["pull","push","both"]).default("both"),interval:e__default.default.number().int().positive().default(3e4),pushEvents:e__default.default.array(e__default.default.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:e__default.default.enum(["latest","local","remote"]).default("latest")}),J=e__default.default.object({id:e__default.default.string().describe("Gateway node ID"),address:e__default.default.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:e__default.default.boolean().default(true),metadata:e__default.default.record(e__default.default.string(),e__default.default.any()).optional()}),j=e__default.default.object({nodeId:e__default.default.string().describe("Current gateway node ID"),nodes:e__default.default.array(J).default([]).describe("Other gateway nodes in the cluster"),sync:D.optional()}),v=e__default.default.object({maxConnectionsPerChannel:e__default.default.number().int().positive().default(100),idleTimeout:e__default.default.number().int().positive().default(3e5),reuseStrategy:e__default.default.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:e__default.default.number().int().positive().default(6e4),acquireTimeout:e__default.default.number().int().positive().default(5e3),warmupCount:e__default.default.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),T=e__default.default.object({maxLength:e__default.default.number().int().positive().default(1e4),concurrency:e__default.default.number().int().positive().default(100),batchSize:e__default.default.number().int().positive().default(10),batchTimeout:e__default.default.number().int().positive().default(100),priorityLevels:e__default.default.number().int().positive().default(4)}),G=e__default.default.object({failureThreshold:e__default.default.number().int().positive().default(5),successThreshold:e__default.default.number().int().positive().default(3),timeout:e__default.default.number().int().positive().default(3e4),halfOpenDuration:e__default.default.number().int().positive().default(15e3)}),P=e__default.default.object({heartbeatInterval:e__default.default.number().int().positive().default(3e4),heartbeatTimeout:e__default.default.number().int().positive().default(9e4),heartbeatCheckInterval:e__default.default.number().int().positive().default(1e4),autoDeregisterTimeout:e__default.default.number().int().positive().default(3e5),maxAgents:e__default.default.number().int().positive().default(100),persistenceFile:e__default.default.string().optional().describe("Path to persist agent registrations"),maxRegistrations:e__default.default.number().int().positive().default(1e3)}),k=e__default.default.object({sessionTimeout:e__default.default.number().int().positive().default(18e5),resumeGracePeriod:e__default.default.number().int().positive().default(3e5),maxSessions:e__default.default.number().int().positive().default(1e4),persistenceFile:e__default.default.string().optional().describe("Path to persist sessions")}),I=e__default.default.object({enabled:e__default.default.boolean().default(true),port:e__default.default.number().int().positive().default(8080),hostname:e__default.default.string().default("localhost"),path:e__default.default.string().optional().default("/"),maxConnections:e__default.default.number().int().positive().optional().default(1e3),connectionTimeout:e__default.default.number().int().positive().optional().default(6e4),heartbeatInterval:e__default.default.number().int().positive().optional().default(3e4),sessionExpireMs:e__default.default.number().int().positive().optional().default(3e5),https:_.optional(),auth:O.optional(),cors:e__default.default.boolean().default(true),corsOrigins:e__default.default.array(e__default.default.string()).optional(),mdns:e__default.default.boolean().default(false),mdnsDomain:e__default.default.string().optional().default("gateway.easbot.local")}),d=e__default.default.object({server:I.optional(),channels:R.optional(),cluster:j.optional(),connectionPool:v.optional(),messageQueue:T.optional(),circuitBreaker:G.optional(),agentRegistry:P.optional(),session:k.optional(),defaultAgent:e__default.default.string().optional().describe("Default agent ID for routing"),logLevel:e__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(e__default.default.unknown());function E(t){let n=d.safeParse(t);return n.success||K.warn("Invalid gateway config",{issues:n.error.issues}),n.success?n.data:d.parse({})}function $(t){return d.parse(t)}var ge=chunk5ETPYYQR_cjs.a.create({service:"gateway:interfaces"}),f;function Ve(t){f=t,ge.debug("Agent adapter registered",{hasSubAgentRunner:!!t.subAgentRunner});}function qe(){return f}function Ye(){return f!==void 0}function Je(){if(!f)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return f}var ue={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},pe={directory:process.cwd(),worktree:process.cwd()};function M(){return f?f.global:ue}function F(){return f?f.instance:pe}var g=chunk5ETPYYQR_cjs.a.create({service:"gateway:config"}),z={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}},de={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},me={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},ye={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},be={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3},Se={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e4},we={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Ae={enabled:true,botToken:"",maxConnections:100,timeout:3e4},xe={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},ve={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},Te={enabled:true,path:"/ws",heartbeatInterval:3e4,connectionTimeout:6e4,maxConnections:1e3,cors:true},Ge={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},Pe={enabled:true,relays:[],maxConnections:100,timeout:3e4},p,h=null;async function Q(t){try{if(!fs.existsSync(t))return null;let n=await he__default.default.readFile(t,"utf-8"),o=n,s=!1,a=!1,r=[];for(let i=0;i<n.length;i++){let l=n[i];if(a){r.push(l),a=!1;continue}if(l==="\\"){r.push(l),a=!0;continue}if(l==='"'){s=!s,r.push(l);continue}if(!s&&l==="/"&&n[i+1]==="/"){for(;i<n.length&&n[i]!==`
2
- `&&n[i]!=="\r";)i++;continue}if(!s&&l==="/"&&n[i+1]==="*"){for(i+=2;i<n.length-1;){if(n[i]==="*"&&n[i+1]==="/"){i+=2;break}i++;}continue}r.push(l);}return o=r.join("").trim(),o?JSON.parse(o):null}catch(n){return g.debug("Failed to load config file",{file:t,error:String(n)}),null}}function C(t,n){let o={...t,...n};return (t.server||n.server)&&(o.server={...t.server,...n.server}),(t.channels||n.channels)&&(o.channels={...t.channels,...n.channels}),o}async function ke(){let t=M(),n=F(),o=[],s=L__default.default.join(t.Path.config);o.push(s),o.push(n.directory);try{let{Filesystem:r}=await import('@easbot/utils'),i=await Array.fromAsync(r.up({targets:[".easbot"],start:n.directory,stop:n.worktree}));o.push(...i);}catch{g.debug("Filesystem utils not available, using basic directories");}let a=process.env.EASBOT_CONFIG_DIR;return a&&(o.push(a),g.debug("Using EASBOT_CONFIG_DIR",{path:a})),[...new Set(o)]}async function Ie(t){let n=["gateway.json"],o={};for(let s of n){let a=L__default.default.join(t,s),r=await Q(a);if(r)if("gateway"in r&&r.gateway){let i=r.gateway;"server"in i||"channels"in i||"cluster"in i?o=C(o,i):o=C(o,{server:i}),g.debug("Loaded gateway config from file (nested format)",{file:a});}else "gateway"in r||(o=C(o,r),g.debug("Loaded gateway config from file (direct format)",{file:a}));}return o}async function Ne(t){let n=["easbot.json"];for(let o of n){let s=L__default.default.join(t,o),a=await Q(s);if(a?.gateway)return g.debug("Loaded gateway config from easbot.json",{file:s}),a.gateway}return {}}function Ee(){return p||(p=async()=>{let t=await ke(),n={};for(let s of t){let a=await Ie(s);n=C(n,a);let r=await Ne(s);n=C(n,r);}let o=E(n);return h=o,g.info("Gateway config loaded",{directories:t.length,port:o.server?.port,logLevel:o.logLevel}),{config:o,directories:t}}),p}async function c(){return Ee()()}async function U(t){return t&&(p=void 0,h=null),(await c()).config}function W(){return h}function H(){return h!==null}function X(){p=void 0,h=null,g.debug("Config cache cleared");}function Z(){return F().directory}async function ee(){let{config:t}=await c();return I.parse({...z,...t.server})}async function te(t){let{config:n}=await c(),o=n.channels?.[t],a={telegram:m.parse(we),slack:y.parse(Ae),feishu:b.parse(xe),wechat:S.parse(ve),webchat:w.parse(Te),signal:A.parse(Ge),nostr:x.parse(Pe)}[t];if(!a)throw new Error(`Unknown channel type: ${t}`);return {...a,...o}}async function ne(){let{config:t}=await c();return v.parse({...de,...t.connectionPool})}async function oe(){let{config:t}=await c();return T.parse({...me,...t.messageQueue})}async function ie(){let{config:t}=await c();return G.parse({...ye,...t.circuitBreaker})}async function ae(){let{config:t}=await c();return P.parse({...be,...t.agentRegistry})}async function re(){let{config:t}=await c();return k.parse({...Se,...t.session})}async function se(){let{config:t}=await c();return t.server?.https}async function ce(){let{config:t}=await c();return t.server?.auth}async function le(){let{config:t}=await c();return t.cluster}async function fe(){let{config:t}=await c();return t.defaultAgent}async function B(){let{config:t}=await c();return t.logLevel??"INFO"}exports.A=Z;exports.B=ee;exports.C=te;exports.D=ne;exports.E=oe;exports.F=ie;exports.G=ae;exports.H=re;exports.I=se;exports.J=ce;exports.K=le;exports.L=fe;exports.M=B;exports.N=Ve;exports.O=qe;exports.P=Ye;exports.Q=Je;exports.R=M;exports.S=F;exports.a=m;exports.b=y;exports.c=b;exports.d=S;exports.e=w;exports.f=A;exports.g=x;exports.h=R;exports.i=_;exports.j=O;exports.k=D;exports.l=j;exports.m=v;exports.n=T;exports.o=G;exports.p=P;exports.q=k;exports.r=I;exports.s=d;exports.t=E;exports.u=$;exports.v=z;exports.w=U;exports.x=W;exports.y=H;exports.z=X;