@naarang/ccc 2.0.0-alpha.1 → 2.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +54 -54
- package/package.json +2 -2
- package/dist/ngrok.win32-x64-msvc-zjj4rz8c.node +0 -0
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var ZX=Object.create;var{getPrototypeOf:zX,defineProperty:lU,getOwnPropertyNames:HS}=Object;var $S=Object.prototype.hasOwnProperty;var dH=(H,$,A)=>{A=H!=null?ZX(zX(H)):{};let L=$||!H||!H.__esModule?lU(A,"default",{value:H,enumerable:!0}):A;for(let D of HS(H))if(!$S.call(L,D))lU(L,D,{get:()=>H[D],enumerable:!0});return L};var p=(H,$)=>()=>($||H(($={exports:{}}).exports,$),$.exports);var B=import.meta.require;var eU=p((d6,wU)=>{wU.exports=pS;var _S=Object.prototype.hasOwnProperty;function pS(){var H={};for(var $=0;$<arguments.length;$++){var A=arguments[$];for(var L in A)if(_S.call(A,L))H[L]=A[L]}return H}});var qf=p((a6,jU)=>{function VS(H){var $=new H,A=$;function L(){var f=$;if(f.next)$=f.next;else $=new H,A=$;return f.next=null,f}function D(f){A.next=f,A=f}return{get:L,release:D}}jU.exports=VS});var zE=p((l6,QU)=>{var WS=eU(),JU=qf(),uS={released:iA,results:!0};function xS(H){H=WS(uS,H);var $=H.released,A=JU(H.results?XS:hS),L=JU(cS),D=H.results?U:t,f=H.results?T:M;return E;function E(_,x,V,h){var W=A.get();if(h=h||iA,x.length===0)h.call(_),$(W);else{if(W._callback=h,W._callThat=_,W._release=I,typeof x==="function")f(_,x,V,W);else D(_,x,V,W);if(W._count===0)W.release()}}function I(_){A.release(_),$(_)}function P(_){L.release(_)}function T(_,x,V,h){var W=null;h._count=V.length,h._results=Array(h._count);for(var c=0;c<V.length;c++)if(W=L.get(),W._release=P,W.parent=h,W.pos=c,_)x.call(_,V[c],W.release);else x(V[c],W.release)}function U(_,x,V,h){var W=null,c=iA;h._count=x.length,h._results=Array(h._count);for(var r=0;r<x.length;r++)if(W=L.get(),W._release=P,W.parent=h,W.pos=r,c=x[r],_)if(c.length===1)c.call(_,W.release);else c.call(_,V,W.release);else if(c.length===1)c(W.release);else c(V,W.release)}function M(_,x,V,h){h._count=V.length;for(var W=0;W<V.length;W++)if(_)x.call(_,V[W],h.release);else x(V[W],h.release)}function t(_,x,V,h){var W=null;h._count=x.length;for(var c=0;c<x.length;c++)if(W=x[c],_)if(W.length===1)W.call(_,h.release);else W.call(_,V,h.release);else if(W.length===1)W(h.release);else W(V,h.release)}}function hS(){this._count=-1,this._callback=iA,this._callThat=null,this._release=null,this.next=null;var H=this,$=0;this.release=function(){var A=H._callback;if(++$===H._count||H._count===0){if(H._callThat)A.call(H._callThat);else A();H._callback=iA,H._callThat=null,$=0,H._release(H)}}}function cS(){this.pos=-1,this._release=iA,this.parent=null,this.next=null;var H=this;this.release=function($,A){H.parent.release($,H.pos,A),H.pos=-1,H.parent=null,H._release(H)}}function XS(){this._count=-1,this._callback=iA,this._results=null,this._err=null,this._callThat=null,this._release=iA,this.next=null;var H=this,$=0;this.release=function(A,L,D){if(H._err=H._err||A,L>=0)H._results[L]=D;var f=H._callback;if(++$===H._count||H._count===0){if(H._callThat)f.call(H._callThat,H._err,H._results);else f(H._err,H._results);H._callback=iA,H._results=null,H._err=null,H._callThat=null,$=0,H._release(H)}}}function iA(){}QU.exports=xS});var vU=p((y6,gU)=>{var SS={results:!0};function rS(H){H=Object.assign({},SS,H);var $,A;if(H.results)$=oS,A=FS;else $=BS,A=nS;return L;function L(D,f,E,I){if(I=(I||sS).bind(D),f.length===0)I.call(D);else if(f.bind){if(D)f=f.bind(D);$(f,E,I)}else{var P;if(D){var T=f.length;P=Array(T);for(var U=0;U<T;U++)P[U]=f[U].bind(D)}else P=f;A(P,E,I)}}}function BS(H,$,A){var L=0,D=$.length;f();function f(){if(L<D)Zf(H,$[L++],f);else A()}}function nS(H,$,A){var L=0,D=H.length,f;if(H[0].length===1)f=KU;else f=Zf;E();function E(){if(L<D)f(H[L++],$,E);else A()}}function oS(H,$,A){var L=0,D=$.length,f=Array(D);E(null,null);function E(I,P){if(I){A(I);return}if(L>0)f[L-1]=P;if(L<D)Zf(H,$[L++],E);else A(null,f)}}function FS(H,$,A){var L=0,D=H.length,f;if(H[0].length===1)f=KU;else f=Zf;var E=Array(D);I(null,null);function I(P,T){if(P){A(P);return}if(L>0)E[L-1]=T;if(L<D)f(H[L++],$,I);else A(null,E)}}function KU(H,$,A){H(A)}function Zf(H,$,A){H($,A)}function sS(){}gU.exports=rS});var ZU=p((YU)=>{Object.defineProperty(YU,"__esModule",{value:!0});YU.default=void 0;var b6=YU.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var $M=p((zU)=>{Object.defineProperty(zU,"__esModule",{value:!0});zU.default=void 0;var k6=zU.default="00000000-0000-0000-0000-000000000000"});var DM=p((AM)=>{Object.defineProperty(AM,"__esModule",{value:!0});AM.default=void 0;var O6=AM.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var bD=p((fM)=>{Object.defineProperty(fM,"__esModule",{value:!0});fM.default=void 0;var CS=iS(DM());function iS(H){return H&&H.__esModule?H:{default:H}}function GS(H){return typeof H==="string"&&CS.default.test(H)}var w6=fM.default=GS});var ND=p((IM)=>{Object.defineProperty(IM,"__esModule",{value:!0});IM.default=void 0;var dS=aS(bD());function aS(H){return H&&H.__esModule?H:{default:H}}function lS(H){if(!(0,dS.default)(H))throw TypeError("Invalid UUID");let $,A=new Uint8Array(16);return A[0]=($=parseInt(H.slice(0,8),16))>>>24,A[1]=$>>>16&255,A[2]=$>>>8&255,A[3]=$&255,A[4]=($=parseInt(H.slice(9,13),16))>>>8,A[5]=$&255,A[6]=($=parseInt(H.slice(14,18),16))>>>8,A[7]=$&255,A[8]=($=parseInt(H.slice(19,23),16))>>>8,A[9]=$&255,A[10]=($=parseInt(H.slice(24,36),16))/1099511627776&255,A[11]=$/4294967296&255,A[12]=$>>>24&255,A[13]=$>>>16&255,A[14]=$>>>8&255,A[15]=$&255,A}var j6=IM.default=lS});var GA=p((UM)=>{Object.defineProperty(UM,"__esModule",{value:!0});UM.default=void 0;UM.unsafeStringify=TM;var yS=bS(bD());function bS(H){return H&&H.__esModule?H:{default:H}}var jH=[];for(let H=0;H<256;++H)jH.push((H+256).toString(16).slice(1));function TM(H,$=0){return(jH[H[$+0]]+jH[H[$+1]]+jH[H[$+2]]+jH[H[$+3]]+"-"+jH[H[$+4]]+jH[H[$+5]]+"-"+jH[H[$+6]]+jH[H[$+7]]+"-"+jH[H[$+8]]+jH[H[$+9]]+"-"+jH[H[$+10]]+jH[H[$+11]]+jH[H[$+12]]+jH[H[$+13]]+jH[H[$+14]]+jH[H[$+15]]).toLowerCase()}function NS(H,$=0){let A=TM(H,$);if(!(0,yS.default)(A))throw TypeError("Stringified UUID is invalid");return A}var Q6=UM.default=NS});var $0=p((tM)=>{Object.defineProperty(tM,"__esModule",{value:!0});tM.default=mS;var RS=OS(B("crypto"));function OS(H){return H&&H.__esModule?H:{default:H}}var H0=new Uint8Array(256),zf=H0.length;function mS(){if(zf>H0.length-16)RS.default.randomFillSync(H0),zf=0;return H0.slice(zf,zf+=16)}});var LI=p((_M)=>{Object.defineProperty(_M,"__esModule",{value:!0});_M.default=void 0;var eS=JS($0()),jS=GA();function JS(H){return H&&H.__esModule?H:{default:H}}var HI,A0,$I=0,AI=0;function QS(H,$,A){let L=$&&A||0,D=$||Array(16);H=H||{};let{node:f,clockseq:E}=H;if(!H._v6){if(!f)f=HI;if(E==null)E=A0}if(f==null||E==null){let t=H.random||(H.rng||eS.default)();if(f==null){if(f=[t[0],t[1],t[2],t[3],t[4],t[5]],!HI&&!H._v6)f[0]|=1,HI=f}if(E==null){if(E=(t[6]<<8|t[7])&16383,A0===void 0&&!H._v6)A0=E}}let I=H.msecs!==void 0?H.msecs:Date.now(),P=H.nsecs!==void 0?H.nsecs:AI+1,T=I-$I+(P-AI)/1e4;if(T<0&&H.clockseq===void 0)E=E+1&16383;if((T<0||I>$I)&&H.nsecs===void 0)P=0;if(P>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");$I=I,AI=P,A0=E,I+=12219292800000;let U=((I&268435455)*1e4+P)%4294967296;D[L++]=U>>>24&255,D[L++]=U>>>16&255,D[L++]=U>>>8&255,D[L++]=U&255;let M=I/4294967296*1e4&268435455;D[L++]=M>>>8&255,D[L++]=M&255,D[L++]=M>>>24&15|16,D[L++]=M>>>16&255,D[L++]=E>>>8|128,D[L++]=E&255;for(let t=0;t<6;++t)D[L+t]=f[t];return $||(0,jS.unsafeStringify)(D)}var v6=_M.default=QS});var DI=p((VM)=>{Object.defineProperty(VM,"__esModule",{value:!0});VM.default=YS;var KS=vS(ND()),gS=GA();function vS(H){return H&&H.__esModule?H:{default:H}}function YS(H){let $=typeof H==="string"?(0,KS.default)(H):H,A=qS($);return typeof H==="string"?(0,gS.unsafeStringify)(A):A}function qS(H,$=!1){return Uint8Array.of((H[6]&15)<<4|H[7]>>4&15,(H[7]&15)<<4|(H[4]&240)>>4,(H[4]&15)<<4|(H[5]&240)>>4,(H[5]&15)<<4|(H[0]&240)>>4,(H[0]&15)<<4|(H[1]&240)>>4,(H[1]&15)<<4|(H[2]&240)>>4,96|H[2]&15,H[3],H[8],H[9],H[10],H[11],H[12],H[13],H[14],H[15])}});var fI=p((WM)=>{Object.defineProperty(WM,"__esModule",{value:!0});WM.URL=WM.DNS=void 0;WM.default=fr;var zS=GA(),Hr=$r(ND());function $r(H){return H&&H.__esModule?H:{default:H}}function Ar(H){H=unescape(encodeURIComponent(H));let $=[];for(let A=0;A<H.length;++A)$.push(H.charCodeAt(A));return $}var Lr=WM.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Dr=WM.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function fr(H,$,A){function L(D,f,E,I){var P;if(typeof D==="string")D=Ar(D);if(typeof f==="string")f=(0,Hr.default)(f);if(((P=f)===null||P===void 0?void 0:P.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let T=new Uint8Array(16+D.length);if(T.set(f),T.set(D,f.length),T=A(T),T[6]=T[6]&15|$,T[8]=T[8]&63|128,E){I=I||0;for(let U=0;U<16;++U)E[I+U]=T[U];return E}return(0,zS.unsafeStringify)(T)}try{L.name=H}catch(D){}return L.DNS=Lr,L.URL=Dr,L}});var cM=p((xM)=>{Object.defineProperty(xM,"__esModule",{value:!0});xM.default=void 0;var Pr=Tr(B("crypto"));function Tr(H){return H&&H.__esModule?H:{default:H}}function Ur(H){if(Array.isArray(H))H=Buffer.from(H);else if(typeof H==="string")H=Buffer.from(H,"utf8");return Pr.default.createHash("md5").update(H).digest()}var z6=xM.default=Ur});var BM=p((SM)=>{Object.defineProperty(SM,"__esModule",{value:!0});SM.default=void 0;var Mr=XM(fI()),tr=XM(cM());function XM(H){return H&&H.__esModule?H:{default:H}}var _r=(0,Mr.default)("v3",48,tr.default),$k=SM.default=_r});var FM=p((nM)=>{Object.defineProperty(nM,"__esModule",{value:!0});nM.default=void 0;var pr=Vr(B("crypto"));function Vr(H){return H&&H.__esModule?H:{default:H}}var Lk=nM.default={randomUUID:pr.default.randomUUID}});var dM=p((iM)=>{Object.defineProperty(iM,"__esModule",{value:!0});iM.default=void 0;var sM=CM(FM()),Wr=CM($0()),ur=GA();function CM(H){return H&&H.__esModule?H:{default:H}}function xr(H,$,A){if(sM.default.randomUUID&&!$&&!H)return sM.default.randomUUID();H=H||{};let L=H.random||(H.rng||Wr.default)();if(L[6]=L[6]&15|64,L[8]=L[8]&63|128,$){A=A||0;for(let D=0;D<16;++D)$[A+D]=L[D];return $}return(0,ur.unsafeStringify)(L)}var fk=iM.default=xr});var yM=p((aM)=>{Object.defineProperty(aM,"__esModule",{value:!0});aM.default=void 0;var hr=cr(B("crypto"));function cr(H){return H&&H.__esModule?H:{default:H}}function Xr(H){if(Array.isArray(H))H=Buffer.from(H);else if(typeof H==="string")H=Buffer.from(H,"utf8");return hr.default.createHash("sha1").update(H).digest()}var Ik=aM.default=Xr});var RM=p((NM)=>{Object.defineProperty(NM,"__esModule",{value:!0});NM.default=void 0;var Sr=bM(fI()),rr=bM(yM());function bM(H){return H&&H.__esModule?H:{default:H}}var Br=(0,Sr.default)("v5",80,rr.default),Tk=NM.default=Br});var wM=p((mM)=>{Object.defineProperty(mM,"__esModule",{value:!0});mM.default=sr;var nr=GA(),or=OM(LI()),Fr=OM(DI());function OM(H){return H&&H.__esModule?H:{default:H}}function sr(H={},$,A=0){let L=(0,or.default)({...H,_v6:!0},new Uint8Array(16));if(L=(0,Fr.default)(L),$){for(let D=0;D<16;D++)$[A+D]=L[D];return $}return(0,nr.unsafeStringify)(L)}});var jM=p((eM)=>{Object.defineProperty(eM,"__esModule",{value:!0});eM.default=ar;var ir=dr(ND()),Gr=GA();function dr(H){return H&&H.__esModule?H:{default:H}}function ar(H){let $=typeof H==="string"?(0,ir.default)(H):H,A=lr($);return typeof H==="string"?(0,Gr.unsafeStringify)(A):A}function lr(H){return Uint8Array.of((H[3]&15)<<4|H[4]>>4&15,(H[4]&15)<<4|(H[5]&240)>>4,(H[5]&15)<<4|H[6]&15,H[7],(H[1]&15)<<4|(H[2]&240)>>4,(H[2]&15)<<4|(H[3]&240)>>4,16|(H[0]&240)>>4,(H[0]&15)<<4|(H[1]&240)>>4,H[8],H[9],H[10],H[11],H[12],H[13],H[14],H[15])}});var vM=p((KM)=>{Object.defineProperty(KM,"__esModule",{value:!0});KM.default=void 0;var br=kr($0()),Nr=GA();function kr(H){return H&&H.__esModule?H:{default:H}}var JM=null,QM=null,m$=0;function Rr(H,$,A){H=H||{};let L=$&&A||0,D=$||new Uint8Array(16),f=H.random||(H.rng||br.default)(),E=H.msecs!==void 0?H.msecs:Date.now(),I=H.seq!==void 0?H.seq:null,P=QM,T=JM;if(E>m$&&H.msecs===void 0){if(m$=E,I!==null)P=null,T=null}if(I!==null){if(I>2147483647)I=2147483647;P=I>>>19&4095,T=I&524287}if(P===null||T===null)P=f[6]&127,P=P<<8|f[7],T=f[8]&63,T=T<<8|f[9],T=T<<5|f[10]>>>3;if(E+1e4>m$&&I===null){if(++T>524287){if(T=0,++P>4095)P=0,m$++}}else m$=E;return QM=P,JM=T,D[L++]=m$/1099511627776&255,D[L++]=m$/4294967296&255,D[L++]=m$/16777216&255,D[L++]=m$/65536&255,D[L++]=m$/256&255,D[L++]=m$&255,D[L++]=P>>>4&15|112,D[L++]=P&255,D[L++]=T>>>13&63|128,D[L++]=T>>>5&255,D[L++]=T<<3&255|f[10]&7,D[L++]=f[11],D[L++]=f[12],D[L++]=f[13],D[L++]=f[14],D[L++]=f[15],$||(0,Nr.unsafeStringify)(D)}var _k=KM.default=Rr});var ZM=p((YM)=>{Object.defineProperty(YM,"__esModule",{value:!0});YM.default=void 0;var Or=mr(bD());function mr(H){return H&&H.__esModule?H:{default:H}}function wr(H){if(!(0,Or.default)(H))throw TypeError("Invalid UUID");return parseInt(H.slice(14,15),16)}var Vk=YM.default=wr});var zM=p((YH)=>{Object.defineProperty(YH,"__esModule",{value:!0});Object.defineProperty(YH,"MAX",{enumerable:!0,get:function(){return er.default}});Object.defineProperty(YH,"NIL",{enumerable:!0,get:function(){return jr.default}});Object.defineProperty(YH,"parse",{enumerable:!0,get:function(){return Jr.default}});Object.defineProperty(YH,"stringify",{enumerable:!0,get:function(){return Qr.default}});Object.defineProperty(YH,"v1",{enumerable:!0,get:function(){return Kr.default}});Object.defineProperty(YH,"v1ToV6",{enumerable:!0,get:function(){return gr.default}});Object.defineProperty(YH,"v3",{enumerable:!0,get:function(){return vr.default}});Object.defineProperty(YH,"v4",{enumerable:!0,get:function(){return Yr.default}});Object.defineProperty(YH,"v5",{enumerable:!0,get:function(){return qr.default}});Object.defineProperty(YH,"v6",{enumerable:!0,get:function(){return Zr.default}});Object.defineProperty(YH,"v6ToV1",{enumerable:!0,get:function(){return zr.default}});Object.defineProperty(YH,"v7",{enumerable:!0,get:function(){return HB.default}});Object.defineProperty(YH,"validate",{enumerable:!0,get:function(){return $B.default}});Object.defineProperty(YH,"version",{enumerable:!0,get:function(){return AB.default}});var er=M$(ZU()),jr=M$($M()),Jr=M$(ND()),Qr=M$(GA()),Kr=M$(LI()),gr=M$(DI()),vr=M$(BM()),Yr=M$(dM()),qr=M$(RM()),Zr=M$(wM()),zr=M$(jM()),HB=M$(vM()),$B=M$(bD()),AB=M$(ZM());function M$(H){return H&&H.__esModule?H:{default:H}}});var vL=p((xk,Ht)=>{function LB(H,$){if(Object.prototype.hasOwnProperty.call(H,"clientId"))this.clientId=H.clientId;if(Object.prototype.hasOwnProperty.call(H,"nl"))this.nl=H.nl;if(this.cmd=H.cmd||"publish",this.brokerId=H.brokerId||$&&$.id,this.brokerCounter=H.brokerCounter||($?++$.counter:0),this.topic=H.topic,this.payload=H.payload||Buffer.alloc(0),this.qos=H.qos||0,this.retain=H.retain||!1,this.dup=H.dup||!1,this.qos>0||this.cmd!=="publish")this.messageId=void 0}Ht.exports=LB});var EI=p((hk,$t)=>{var w$=B("util");$t.exports=function(H,$){class A extends H{constructor(L){super(L);this.addP=w$.promisify(this.add_async),this.removeP=w$.promisify(this.remove_async),this.matchP=w$.promisify(this.match_async),this.testP=w$.promisify(this.test_async),this.clearP=w$.promisify(this.clear_async),this._get_visitorP=w$.promisify(this.get_visitor_async),this._visit_nextP=w$.promisify(this.visit_next_async),this._get_restorerP=w$.promisify(this.get_restorer_async),this._restore_nextP=w$.promisify(this.restore_next_async),this._match_iterP=w$.promisify(this.match_iter_async),this._match_nextP=w$.promisify(this.match_next_async)}*visit(){let L=this.get_visitor();while(!0){let D=this.visit_next(L);if(D===void 0)break;yield D}}async*visitP(){let L=await this._get_visitorP();while(!0){let D=await this._visit_nextP(L);if(D===void 0)break;yield D}}*match_iter(L,D){let f=super.match_iter(L,D);while(!0){let E=this.match_next(f);if(E===void 0)break;yield E.value}}async*match_iterP(L,D){let f=await this._match_iterP(L,D);while(!0){let E=await this._match_nextP(f);if(E===void 0)break;yield E.value}}get_trie(){let L=new $(this.options),D=L.get_restorer();for(let f of this.visit())D(f);return L.get_trie()}get_restorer(L){let D=super.get_restorer(L);return(f)=>{super.restore_next(D,f)}}async get_restorerP(L){let D=await this._get_restorerP(L);return async(f)=>{await this._restore_nextP(D,f)}}}return A.is_native=!0,A.nonNative=$,A}});var TI=p((Lt)=>{var L0=B("util");function EH(H){if(H=H||{},this._separator=H.separator||".",this._wildcard_one=H.wildcard_one||"*",this._wildcard_some=H.wildcard_some||"#",this._max_words=H.max_words||100,this._max_wildcard_somes=H.max_wildcard_somes||3,this._match_empty_levels=H.match_empty_levels,this._trie=new Map,H.cache_adds instanceof Map)this._shortcuts=H.cache_adds;else if(H.cache_adds)this._shortcuts=new Map;if(H.cache_splits>0)this._cache_splits=H.cache_splits,this._split_cache=new Map}EH.prototype._initial_value=function(H){return[H]};EH.prototype._add_value=function(H,$){H[H.length]=$};EH.prototype._add_values=function(H,$){var A,L=H.length,D=$.length;for(A=0;A<D;A+=1)H[L+A]=$[A]};EH.prototype._iter_values=function(H,$){return H[Symbol.iterator]($)};EH.prototype._remove_value=function(H,$){if($===void 0)return!0;var A=H.lastIndexOf($);if(A>=0)H.splice(A,1);return H.length===0};EH.prototype._add=function(H,$,A,L){var D,f;if($===A.length){if(D=L.get(this._separator),D)this._add_value(D,H);else D=this._initial_value(H),L.set(this._separator,D);return D}if(f=A[$],D=L.get(f),!D)D=new Map,L.set(f,D);return this._add(H,$+1,A,D)};EH.prototype._remove=function(H,$,A,L){var D,f,E;if($===A.length){if(D=L.get(this._separator),D&&this._remove_value(D,H))return L.delete(this._separator),!0;return!1}if(f=A[$],D=L.get(f),!D)return!1;if(E=this._remove(H,$+1,A,D),D.size===0)L.delete(f);return E};EH.prototype._match_some=function(H,$,A,L,D){var f,E;for(E of L.keys())if(E!==this._separator){for(f=$;f<A.length;f+=1)H=this._match(H,f,A,L,D);break}return H};EH.prototype._match=function(H,$,A,L,D){var f,E;if(E=L.get(this._wildcard_some),E)H=this._match_some(H,$,A,E,D),H=this._match(H,A.length,A,E,D);if($===A.length){if(E=L.get(this._separator),E)if(H.dest)this._add_values(H.dest,H.source,D),this._add_values(H.dest,E,D),H=H.dest;else if(H.source)H.dest=H.source,H.source=E;else this._add_values(H,E,D)}else{if(f=A[$],f!==this._wildcard_one&&f!==this._wildcard_some){if(E=L.get(f),E)H=this._match(H,$+1,A,E,D)}if(f||this._match_empty_levels){if(E=L.get(this._wildcard_one),E)H=this._match(H,$+1,A,E,D)}}return H};EH.prototype._match2=function(H,$,A){var L=this._match({source:H},0,this._split($,!1),this._trie,A);return L.source||L};EH.prototype._test_some=function(H,$,A,L){var D,f;for(f of L.keys())if(f!==this._separator){for(D=$;D<A.length;D+=1)if(this._test(H,D,A,L))return!0;break}return!1};EH.prototype._test=function(H,$,A,L){var D,f;if(f=L.get(this._wildcard_some),f){if(this._test_some(H,$,A,f)||this._test(H,A.length,A,f))return!0}if($===A.length){if(f=L.get(this._separator),f&&this.test_values(f,H))return!0}else{if(D=A[$],D!==this._wildcard_one&&D!==this._wildcard_some){if(f=L.get(D),f&&this._test(H,$+1,A,f))return!0}if(D||this._match_empty_levels){if(f=L.get(this._wildcard_one),f&&this._test(H,$+1,A,f))return!0}}return!1};EH.prototype._match_some_iter=function*(H,$,A,L){var D,f;for(f of A.keys())if(f!==this._separator){for(D=H;D<$.length;D+=1)yield*this._match_iter(D,$,A,L);break}};EH.prototype._match_iter=function*(H,$,A,L){var D,f;if(f=A.get(this._wildcard_some),f)yield*this._match_some_iter(H,$,f,L),yield*this._match_iter($.length,$,f,L);if(H===$.length){if(f=A.get(this._separator),f)yield*this._iter_values(f,L)}else{if(D=$[H],D!==this._wildcard_one&&D!==this._wildcard_some){if(f=A.get(D),f)yield*this._match_iter(H+1,$,f,L)}if(D||this._match_empty_levels){if(f=A.get(this._wildcard_one),f)yield*this._match_iter(H+1,$,f,L)}}};EH.prototype._split_words=function(H){let $=H.split(this._separator);if($.length>this._max_words)throw Error("too many words");return $};EH.prototype._split=function(H,$){let A;if(this._split_cache){if(A=this._split_cache.get(H),A===void 0){if(A=this._split_words(H),this._split_cache.set(H,A),this._split_cache.size>this._cache_splits)for(let L of this._split_cache.keys()){this._split_cache.delete(L);break}}}else A=this._split_words(H);if($&&A.reduce((L,D)=>L+(D===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return A};EH.prototype.add=function(H,$){var A=this._shortcuts&&this._shortcuts.get(H);if(A)this._add_value(A,$);else if(A=this._add($,0,this._split(H,!0),this._trie),this._shortcuts)this._shortcuts.set(H,A);return this};EH.prototype.remove=function(H,$){if(this._remove($,0,this._split(H,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(H);return this};EH.prototype.match=function(H,$){return this._match2([],H,$)};EH.prototype.match_iter=function(H,$){return this._match_iter(0,this._split(H,!1),this._trie,$)};EH.prototype.test=function(H,$){return this._test($,0,this._split(H,!1),this._trie)};EH.prototype.test_values=function(H,$){return H.indexOf($)>=0};EH.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};EH.prototype.get_trie=function(){return this._trie};EH.prototype.visit=function*(){let H=[],$=this._trie.entries(),A=0;while(!0){if(A===0)yield{type:"start_entries"};let L=$.next();if(L.done){yield{type:"end_entries"};let E=H.pop();if(E===void 0)return;[$,A]=E;continue}let[D,f]=L.value;if(yield{type:"entry",key:D},++A,D===this._separator){if(yield{type:"start_values"},f[Symbol.iterator])for(let E of f)yield{type:"value",value:E};else yield{type:"value",value:f};yield{type:"end_values"};continue}H.push([$,A]),$=f.entries(),A=0}};EH.prototype.get_restorer=function(H){H=H||{};let $=[],A=this._trie,L="";return(D)=>{switch(D.type){case"entry":if(A=A||new Map,$.push([A,D.key,L]),A=A.get(D.key),H.cache_adds){if(L)L+=this._separator;L+=D.key}break;case"value":if(A)this._add_value(A,D.value);else A=this._initial_value(D.value);break;case"end_entries":if(A&&A.size===0)A=void 0;case"end_values":let f=$.pop();if(f===void 0)A=void 0,L="";else{let[E,I,P]=f;if(A){if(H.cache_adds&&this._shortcuts&&D.type==="end_values")this._shortcuts.set(P,A);E.set(I,A)}A=E,L=P}break}}};function r$(H){EH.call(this,H)}L0.inherits(r$,EH);r$.prototype._initial_value=function(H){return new Set().add(H)};r$.prototype._add_value=function(H,$){H.add($)};r$.prototype._add_values=function(H,$){$.forEach(function(A){H.add(A)})};r$.prototype._remove_value=function(H,$){if($===void 0)return!0;return H.delete($),H.size===0};r$.prototype.test_values=function(H,$){return H.has($)};r$.prototype.match=function(H,$){return this._match2(new Set,H,$)};function LA(H){EH.call(this,H)}L0.inherits(LA,EH);LA.prototype._initial_value=function(){return!0};LA.prototype._add_value=function(){};LA.prototype._remove_value=function(){return!0};LA.prototype._iter_values=function*(){yield!0};LA.prototype.test_values=function(){return!0};LA.prototype.match=function(H,$){return this.test(H,$)};var D0=B("stream");function II(H){D0.Readable.call(this,{objectMode:!0}),this._iterator=H.visit()}L0.inherits(II,D0.Readable);II.prototype._read=function(){while(!0){let{done:H,value:$}=this._iterator.next();if(H){this.push(null);break}if(!this.push($))break}};function PI(H){D0.Writable.call(this,{objectMode:!0}),this._restorer=H.get_restorer()}L0.inherits(PI,D0.Writable);PI.prototype._write=function(H,$,A){this._restorer(H),A()};var At=null;function DB(H){if(H!==At){let $=EI();EH.nativeString=$(H.QlobberString,EH),EH.nativeNumber=$(H.QlobberNumber,EH),r$.nativeString=$(H.QlobberDedupString,r$),r$.nativeNumber=$(H.QlobberDedupNumber,r$),LA.native=$(H.QlobberTrue,LA),At=H}return Lt}Lt.Qlobber=EH;Lt.QlobberDedup=r$;Lt.QlobberTrue=LA;Lt.VisitorStream=II;Lt.RestorerStream=PI;Lt.set_native=DB});var Dt=p((Xk,MI)=>{var MB=B("util"),tB=TI(),UI=tB.Qlobber;function B$(H){UI.call(this,H),this.subscriptionsCount=0}MB.inherits(B$,UI);B$.prototype._initial_value=function(H){this.subscriptionsCount+=1;let $={topic:H.topic,clientMap:new Map().set(H.clientId,{qos:H.qos,rh:H.rh,rap:H.rap,nl:H.nl})};return $[Symbol.iterator]=function*(A){if(A===void 0)for(let[L,D]of $.clientMap)yield{topic:$.topic,clientId:L,...D};else if($.topic===A)for(let[L,D]of $.clientMap)yield{clientId:L,...D}},$};B$.prototype._add_value=function(H,$){var A=H.clientMap,L=A.size;if(A.set($.clientId,{qos:$.qos,rh:$.rh,rap:$.rap,nl:$.nl}),A.size>L)this.subscriptionsCount+=1};B$.prototype._add_values=function(H,$,A){if(A===void 0)for(let[L,D]of $.clientMap)H.push({clientId:L,topic:$.topic,...D});else if($.topic===A)for(let[L,D]of $.clientMap)H.push({clientId:L,...D})};B$.prototype._remove_value=function(H,$){var A=H.clientMap,L=A.size;A.delete($.clientId);var D=A.size;if(D<L)this.subscriptionsCount-=1;return D===0};B$.prototype.test_values=function(H,$){var A=H.clientMap;return H.topic===$.topic&&A.size===1&&A.has($.clientId)};B$.prototype.match=function(H,$){return this._match([],0,H.split(this._separator),this._trie,$)};B$.prototype.clear=function(){return this.subscriptionsCount=0,UI.prototype.clear.call(this)};B$.set_native=function(H){let $=EI();return B$.native=$(H.QlobberSub,B$),MI.exports};MI.exports=B$});var Pt=p((Sk,_I)=>{var{Readable:kD}=B("stream"),_B=Dt(),{QlobberTrue:pB}=TI(),tI=vL(),Et={wildcard_one:"+",wildcard_some:"#",separator:"/"};function*VB(H){for(let $ of H)yield*$}function*ft(H,$){let A=new pB(Et);A.add($);for(let[L,D]of H)if(A.test(L))yield D}function*WB(H,$){for(let A of H.values())if(!$[A.brokerId])yield A}function*uB(H,$){for(let[A,L]of H)if(L.has($))yield A}class It{#f;#D;#T;#U;#V;#h;#A;constructor(){this.#f=new Map,this.#D=new Map,this.#T=new Map,this.#U=new Map,this.#V=new Map,this.#h=0,this.#A=new _B(Et)}storeRetained(H,$){let A=Object.assign({},H);if(A.payload.length===0)this.#f.delete(A.topic);else this.#f.set(A.topic,A);$(null)}createRetainedStreamCombi(H){let $=H.map((A)=>{return ft(this.#f,A)});return kD.from(VB($))}createRetainedStream(H){return kD.from(ft(this.#f,H))}addSubscriptions(H,$,A){let L=this.#D.get(H.id),D=this.#A;if(!L)L=new Map,this.#D.set(H.id,L),this.#h++;for(let f of $){let E=L.get(f.topic);if(f.qos>0)D.add(f.topic,{clientId:H.id,topic:f.topic,qos:f.qos,rh:f.rh,rap:f.rap,nl:f.nl});else if(E?.qos>0)D.remove(f.topic,{clientId:H.id,topic:f.topic});L.set(f.topic,{qos:f.qos,rh:f.rh,rap:f.rap,nl:f.nl})}A(null,H)}removeSubscriptions(H,$,A){let L=this.#D.get(H.id),D=this.#A;if(L){for(let f of $){let E=L.get(f);if(E!==void 0){if(E.qos>0)D.remove(f,{clientId:H.id,topic:f});L.delete(f)}}if(L.size===0)this.#h--,this.#D.delete(H.id)}A(null,H)}subscriptionsByClient(H,$){let A=null,L=this.#D.get(H.id);if(L){A=[];for(let[D,f]of L)A.push({topic:D,...f})}$(null,A,H)}countOffline(H){return H(null,this.#A.subscriptionsCount,this.#h)}subscriptionsByTopic(H,$){$(null,this.#A.match(H))}cleanSubscriptions(H,$){let A=this.#A,L=this.#D.get(H.id);if(L){for(let[D,f]of L)if(f.qos>0)A.remove(D,{clientId:H.id,topic:D});this.#h--,this.#D.delete(H.id)}$(null,H)}#p(H,$){let A=H.clientId,L=VL(this.#T,A,[],!0);L[L.length]=new tI($)}outgoingEnqueue(H,$,A){this.#p(H,$),process.nextTick(A)}outgoingEnqueueCombi(H,$,A){for(let L=0;L<H.length;L++)this.#p(H[L],$);process.nextTick(A)}outgoingUpdate(H,$,A){let L=VL(this.#T,H.id,[],!0),D;for(let f=0;f<L.length;f++)if(D=L[f],D.brokerId===$.brokerId){if(D.brokerCounter===$.brokerCounter)return D.messageId=$.messageId,A(null,H,$)}else if(D.messageId===$.messageId)return L[f]=$,A(null,H,$);A(Error("no such packet"),H,$)}outgoingClearMessageId(H,$,A){let L=VL(this.#T,H.id,[],!0),D;for(let f=0;f<L.length;f++)if(D=L[f],D.messageId===$.messageId)return L.splice(f,1),A(null,D);A()}outgoingStream(H){let $=[].concat(VL(this.#T,H.id,[]));return kD.from($)}incomingStorePacket(H,$,A){let L=H.id,D=VL(this.#U,L,{},!0);D[$.messageId]=new tI($),D[$.messageId].messageId=$.messageId,A(null)}incomingGetPacket(H,$,A){let L=H.id,D=VL(this.#U,L,{}),f=null;if(this.#U.set(L,D),!D[$.messageId])f=Error("no such packet");A(f,D[$.messageId])}incomingDelPacket(H,$,A){let L=H.id,D=VL(this.#U,L,{}),f=D[$.messageId],E=null;if(!f)E=Error("no such packet");else delete D[$.messageId];A(E)}putWill(H,$,A){$.brokerId=this.broker.id,$.clientId=H.id,this.#V.set(H.id,$),A(null,H)}getWill(H,$){$(null,this.#V.get(H.id),H)}delWill(H,$){let A=this.#V.get(H.id);this.#V.delete(H.id),$(null,A,H)}streamWill(H={}){return kD.from(WB(this.#V,H))}getClientList(H){return kD.from(uB(this.#D,H))}destroy(H){if(this.#f=null,H)H(null)}}function VL(H,$,A,L=!1){let D=H.get($);if(D===void 0&&L)H.set($,A);return D||A}_I.exports=()=>{return new It};_I.exports.Packet=tI});var Ut=p((rk,Tt)=>{var e$=B("util");Tt.exports=function(H,$){class A extends H{constructor(L){super(L);this.addP=e$.promisify(this.add_async),this.removeP=e$.promisify(this.remove_async),this.matchP=e$.promisify(this.match_async),this.testP=e$.promisify(this.test_async),this.clearP=e$.promisify(this.clear_async),this._get_visitorP=e$.promisify(this.get_visitor_async),this._visit_nextP=e$.promisify(this.visit_next_async),this._get_restorerP=e$.promisify(this.get_restorer_async),this._restore_nextP=e$.promisify(this.restore_next_async),this._match_iterP=e$.promisify(this.match_iter_async),this._match_nextP=e$.promisify(this.match_next_async)}*visit(){let L=this.get_visitor();while(!0){let D=this.visit_next(L);if(D===void 0)break;yield D}}async*visitP(){let L=await this._get_visitorP();while(!0){let D=await this._visit_nextP(L);if(D===void 0)break;yield D}}*match_iter(L,D){let f=super.match_iter(L,D);while(!0){let E=this.match_next(f);if(E===void 0)break;yield E.value}}async*match_iterP(L,D){let f=await this._match_iterP(L,D);while(!0){let E=await this._match_nextP(f);if(E===void 0)break;yield E.value}}get_trie(){let L=new $(this.options),D=L.get_restorer();for(let f of this.visit())D(f);return L.get_trie()}get_restorer(L){let D=super.get_restorer(L);return(f)=>{super.restore_next(D,f)}}async get_restorerP(L){let D=await this._get_restorerP(L);return async(f)=>{await this._restore_nextP(D,f)}}}return A.is_native=!0,A.nonNative=$,A}});var _t=p((tt)=>{var f0=B("util");function IH(H){if(H=H||{},this._separator=H.separator||".",this._wildcard_one=H.wildcard_one||"*",this._wildcard_some=H.wildcard_some||"#",this._max_words=H.max_words||100,this._max_wildcard_somes=H.max_wildcard_somes||3,this._match_empty_levels=H.match_empty_levels,this._trie=new Map,H.cache_adds instanceof Map)this._shortcuts=H.cache_adds;else if(H.cache_adds)this._shortcuts=new Map;if(H.cache_splits>0)this._cache_splits=H.cache_splits,this._split_cache=new Map}IH.prototype._initial_value=function(H){return[H]};IH.prototype._add_value=function(H,$){H[H.length]=$};IH.prototype._add_values=function(H,$){var A,L=H.length,D=$.length;for(A=0;A<D;A+=1)H[L+A]=$[A]};IH.prototype._iter_values=function(H,$){return H[Symbol.iterator]($)};IH.prototype._remove_value=function(H,$){if($===void 0)return!0;var A=H.lastIndexOf($);if(A>=0)H.splice(A,1);return H.length===0};IH.prototype._add=function(H,$,A,L){var D,f;if($===A.length){if(D=L.get(this._separator),D)this._add_value(D,H);else D=this._initial_value(H),L.set(this._separator,D);return D}if(f=A[$],D=L.get(f),!D)D=new Map,L.set(f,D);return this._add(H,$+1,A,D)};IH.prototype._remove=function(H,$,A,L){var D,f,E;if($===A.length){if(D=L.get(this._separator),D&&this._remove_value(D,H))return L.delete(this._separator),!0;return!1}if(f=A[$],D=L.get(f),!D)return!1;if(E=this._remove(H,$+1,A,D),D.size===0)L.delete(f);return E};IH.prototype._match_some=function(H,$,A,L,D){var f,E;for(E of L.keys())if(E!==this._separator){for(f=$;f<A.length;f+=1)H=this._match(H,f,A,L,D);break}return H};IH.prototype._match=function(H,$,A,L,D){var f,E;if(E=L.get(this._wildcard_some),E)H=this._match_some(H,$,A,E,D),H=this._match(H,A.length,A,E,D);if($===A.length){if(E=L.get(this._separator),E)if(H.dest)this._add_values(H.dest,H.source,D),this._add_values(H.dest,E,D),H=H.dest;else if(H.source)H.dest=H.source,H.source=E;else this._add_values(H,E,D)}else{if(f=A[$],f!==this._wildcard_one&&f!==this._wildcard_some){if(E=L.get(f),E)H=this._match(H,$+1,A,E,D)}if(f||this._match_empty_levels){if(E=L.get(this._wildcard_one),E)H=this._match(H,$+1,A,E,D)}}return H};IH.prototype._match2=function(H,$,A){var L=this._match({source:H},0,this._split($,!1),this._trie,A);return L.source||L};IH.prototype._test_some=function(H,$,A,L){var D,f;for(f of L.keys())if(f!==this._separator){for(D=$;D<A.length;D+=1)if(this._test(H,D,A,L))return!0;break}return!1};IH.prototype._test=function(H,$,A,L){var D,f;if(f=L.get(this._wildcard_some),f){if(this._test_some(H,$,A,f)||this._test(H,A.length,A,f))return!0}if($===A.length){if(f=L.get(this._separator),f&&this.test_values(f,H))return!0}else{if(D=A[$],D!==this._wildcard_one&&D!==this._wildcard_some){if(f=L.get(D),f&&this._test(H,$+1,A,f))return!0}if(D||this._match_empty_levels){if(f=L.get(this._wildcard_one),f&&this._test(H,$+1,A,f))return!0}}return!1};IH.prototype._match_some_iter=function*(H,$,A,L){var D,f;for(f of A.keys())if(f!==this._separator){for(D=H;D<$.length;D+=1)yield*this._match_iter(D,$,A,L);break}};IH.prototype._match_iter=function*(H,$,A,L){var D,f;if(f=A.get(this._wildcard_some),f)yield*this._match_some_iter(H,$,f,L),yield*this._match_iter($.length,$,f,L);if(H===$.length){if(f=A.get(this._separator),f)yield*this._iter_values(f,L)}else{if(D=$[H],D!==this._wildcard_one&&D!==this._wildcard_some){if(f=A.get(D),f)yield*this._match_iter(H+1,$,f,L)}if(D||this._match_empty_levels){if(f=A.get(this._wildcard_one),f)yield*this._match_iter(H+1,$,f,L)}}};IH.prototype._split_words=function(H){let $=H.split(this._separator);if($.length>this._max_words)throw Error("too many words");return $};IH.prototype._split=function(H,$){let A;if(this._split_cache){if(A=this._split_cache.get(H),A===void 0){if(A=this._split_words(H),this._split_cache.set(H,A),this._split_cache.size>this._cache_splits)for(let L of this._split_cache.keys()){this._split_cache.delete(L);break}}}else A=this._split_words(H);if($&&A.reduce((L,D)=>L+(D===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return A};IH.prototype.add=function(H,$){var A=this._shortcuts&&this._shortcuts.get(H);if(A)this._add_value(A,$);else if(A=this._add($,0,this._split(H,!0),this._trie),this._shortcuts)this._shortcuts.set(H,A);return this};IH.prototype.remove=function(H,$){if(this._remove($,0,this._split(H,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(H);return this};IH.prototype.match=function(H,$){return this._match2([],H,$)};IH.prototype.match_iter=function(H,$){return this._match_iter(0,this._split(H,!1),this._trie,$)};IH.prototype.test=function(H,$){return this._test($,0,this._split(H,!1),this._trie)};IH.prototype.test_values=function(H,$){return H.indexOf($)>=0};IH.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};IH.prototype.get_trie=function(){return this._trie};IH.prototype.visit=function*(){let H=[],$=this._trie.entries(),A=0;while(!0){if(A===0)yield{type:"start_entries"};let L=$.next();if(L.done){yield{type:"end_entries"};let E=H.pop();if(E===void 0)return;[$,A]=E;continue}let[D,f]=L.value;if(yield{type:"entry",key:D},++A,D===this._separator){if(yield{type:"start_values"},f[Symbol.iterator])for(let E of f)yield{type:"value",value:E};else yield{type:"value",value:f};yield{type:"end_values"};continue}H.push([$,A]),$=f.entries(),A=0}};IH.prototype.get_restorer=function(H){H=H||{};let $=[],A=this._trie,L="";return(D)=>{switch(D.type){case"entry":if(A=A||new Map,$.push([A,D.key,L]),A=A.get(D.key),H.cache_adds){if(L)L+=this._separator;L+=D.key}break;case"value":if(A)this._add_value(A,D.value);else A=this._initial_value(D.value);break;case"end_entries":if(A&&A.size===0)A=void 0;case"end_values":let f=$.pop();if(f===void 0)A=void 0,L="";else{let[E,I,P]=f;if(A){if(H.cache_adds&&this._shortcuts&&D.type==="end_values")this._shortcuts.set(P,A);E.set(I,A)}A=E,L=P}break}}};function n$(H){IH.call(this,H)}f0.inherits(n$,IH);n$.prototype._initial_value=function(H){return new Set().add(H)};n$.prototype._add_value=function(H,$){H.add($)};n$.prototype._add_values=function(H,$){$.forEach(function(A){H.add(A)})};n$.prototype._remove_value=function(H,$){if($===void 0)return!0;return H.delete($),H.size===0};n$.prototype.test_values=function(H,$){return H.has($)};n$.prototype.match=function(H,$){return this._match2(new Set,H,$)};function DA(H){IH.call(this,H)}f0.inherits(DA,IH);DA.prototype._initial_value=function(){return!0};DA.prototype._add_value=function(){};DA.prototype._remove_value=function(){return!0};DA.prototype._iter_values=function*(){yield!0};DA.prototype.test_values=function(){return!0};DA.prototype.match=function(H,$){return this.test(H,$)};var E0=B("stream");function pI(H){E0.Readable.call(this,{objectMode:!0}),this._iterator=H.visit()}f0.inherits(pI,E0.Readable);pI.prototype._read=function(){while(!0){let{done:H,value:$}=this._iterator.next();if(H){this.push(null);break}if(!this.push($))break}};function VI(H){E0.Writable.call(this,{objectMode:!0}),this._restorer=H.get_restorer()}f0.inherits(VI,E0.Writable);VI.prototype._write=function(H,$,A){this._restorer(H),A()};var Mt=null;function xB(H){if(H!==Mt){let $=Ut();IH.nativeString=$(H.QlobberString,IH),IH.nativeNumber=$(H.QlobberNumber,IH),n$.nativeString=$(H.QlobberDedupString,n$),n$.nativeNumber=$(H.QlobberDedupNumber,n$),DA.native=$(H.QlobberTrue,DA),Mt=H}return tt}tt.Qlobber=IH;tt.QlobberDedup=n$;tt.QlobberTrue=DA;tt.VisitorStream=pI;tt.RestorerStream=VI;tt.set_native=xB});var Vt=p((nk,pt)=>{var{Qlobber:nB}=_t(),YL=B("assert"),oB=zE();function fA(H){if(!(this instanceof fA))return new fA(H);let $=this;H=H||{},H.matchEmptyLevels=H.matchEmptyLevels===void 0?!0:!!H.matchEmptyLevels,H.separator=H.separator||"/",H.wildcardOne=H.wildcardOne||"+",H.wildcardSome=H.wildcardSome||"#",this._messageQueue=[],this._messageCallbacks=[],this._parallel=oB({results:!1,released:A}),this.concurrency=H.concurrency||0,this.current=0,this._doing=!1,this._matcher=new nB({match_empty_levels:H.matchEmptyLevels,separator:H.separator,wildcard_one:H.wildcardOne,wildcard_some:H.wildcardSome}),this.closed=!1,this._released=A;function A(){$.current--;let L=$._messageQueue.shift(),D=$._messageCallbacks.shift();if(L)$._do(L,D);else $._doing=!1}}Object.defineProperty(fA.prototype,"length",{get:function(){return this._messageQueue.length},enumerable:!0});fA.prototype.on=function($,A,L){if(YL($),YL(A),this._matcher.add($,A),L)setImmediate(L);return this};fA.prototype.removeListener=function($,A,L){YL($),YL(A);let D=this;return setImmediate(function(){if(D._matcher.remove($,A),L)L()}),this};fA.prototype.removeAllListeners=function($,A){if(YL($),this._matcher.remove($),A)setImmediate(A);return this};fA.prototype.emit=function($,A){if(YL($),A=A||FB,this.closed)return A(Error("mqemitter is closed"));if(this.concurrency>0&&this.current>=this.concurrency){if(this._messageQueue.push($),this._messageCallbacks.push(A),!this._doing)process.emitWarning("MqEmitter leak detected",{detail:"For more info check: https://github.com/mcollina/mqemitter/pull/94"}),this._released()}else this._do($,A);return this};fA.prototype.close=function($){return this.closed=!0,setImmediate($),this};fA.prototype._do=function(H,$){this._doing=!0;let A=this._matcher.match(H.topic);return this.current++,this._parallel(this,A,H,$),this};function FB(){}pt.exports=fA});var XH=p((ok,ut)=>{class Wt extends Error{constructor(H){if(!Array.isArray(H))throw TypeError(`Expected input to be an Array, got ${typeof H}`);let $="";for(let A=0;A<H.length;A++)$+=` ${H[A].stack}
|
|
3
|
-
`;super($);this.name="AggregateError",this.errors=H}}ut.exports={AggregateError:Wt,ArrayIsArray(H){return Array.isArray(H)},ArrayPrototypeIncludes(H,$){return H.includes($)},ArrayPrototypeIndexOf(H,$){return H.indexOf($)},ArrayPrototypeJoin(H,$){return H.join($)},ArrayPrototypeMap(H,$){return H.map($)},ArrayPrototypePop(H,$){return H.pop($)},ArrayPrototypePush(H,$){return H.push($)},ArrayPrototypeSlice(H,$,A){return H.slice($,A)},Error,FunctionPrototypeCall(H,$,...A){return H.call($,...A)},FunctionPrototypeSymbolHasInstance(H,$){return Function.prototype[Symbol.hasInstance].call(H,$)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(H,$){return Object.defineProperties(H,$)},ObjectDefineProperty(H,$,A){return Object.defineProperty(H,$,A)},ObjectGetOwnPropertyDescriptor(H,$){return Object.getOwnPropertyDescriptor(H,$)},ObjectKeys(H){return Object.keys(H)},ObjectSetPrototypeOf(H,$){return Object.setPrototypeOf(H,$)},Promise,PromisePrototypeCatch(H,$){return H.catch($)},PromisePrototypeThen(H,$,A){return H.then($,A)},PromiseReject(H){return Promise.reject(H)},PromiseResolve(H){return Promise.resolve(H)},ReflectApply:Reflect.apply,RegExpPrototypeTest(H,$){return H.test($)},SafeSet:Set,String,StringPrototypeSlice(H,$,A){return H.slice($,A)},StringPrototypeToLowerCase(H){return H.toLowerCase()},StringPrototypeToUpperCase(H){return H.toUpperCase()},StringPrototypeTrim(H){return H.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(H,$,A){return H.set($,A)},Boolean,Uint8Array}});var WI=p((Fk,xt)=>{xt.exports={format(H,...$){return H.replace(/%([sdifj])/g,function(...[A,L]){let D=$.shift();if(L==="f")return D.toFixed(6);else if(L==="j")return JSON.stringify(D);else if(L==="s"&&typeof D==="object")return`${D.constructor!==Object?D.constructor.name:""} {}`.trim();else return D.toString()})},inspect(H){switch(typeof H){case"string":if(H.includes("'")){if(!H.includes('"'))return`"${H}"`;else if(!H.includes("`")&&!H.includes("${"))return`\`${H}\``}return`'${H}'`;case"number":if(isNaN(H))return"NaN";else if(Object.is(H,-0))return String(H);return H;case"bigint":return`${String(H)}n`;case"boolean":case"undefined":return String(H);case"object":return"{}"}}}});var qH=p((sk,St)=>{var{format:sB,inspect:I0}=WI(),{AggregateError:CB}=XH(),iB=globalThis.AggregateError||CB,GB=Symbol("kIsNodeError"),dB=["string","function","number","object","Function","Object","boolean","bigint","symbol"],aB=/^([A-Z][a-z0-9]*)+$/,P0={};function WL(H,$){if(!H)throw new P0.ERR_INTERNAL_ASSERTION($)}function ht(H){let $="",A=H.length,L=H[0]==="-"?1:0;for(;A>=L+4;A-=3)$=`_${H.slice(A-3,A)}${$}`;return`${H.slice(0,A)}${$}`}function lB(H,$,A){if(typeof $==="function")return WL($.length<=A.length,`Code: ${H}; The provided arguments length (${A.length}) does not match the required ones (${$.length}).`),$(...A);let L=($.match(/%[dfijoOs]/g)||[]).length;if(WL(L===A.length,`Code: ${H}; The provided arguments length (${A.length}) does not match the required ones (${L}).`),A.length===0)return $;return sB($,...A)}function JH(H,$,A){if(!A)A=Error;class L extends A{constructor(...D){super(lB(H,$,D))}toString(){return`${this.name} [${H}]: ${this.message}`}}Object.defineProperties(L.prototype,{name:{value:A.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${H}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),L.prototype.code=H,L.prototype[GB]=!0,P0[H]=L}function ct(H){let $="__node_internal_"+H.name;return Object.defineProperty(H,"name",{value:$}),H}function yB(H,$){if(H&&$&&H!==$){if(Array.isArray($.errors))return $.errors.push(H),$;let A=new iB([$,H],$.message);return A.code=$.code,A}return H||$}class Xt extends Error{constructor(H="The operation was aborted",$=void 0){if($!==void 0&&typeof $!=="object")throw new P0.ERR_INVALID_ARG_TYPE("options","Object",$);super(H,$);this.code="ABORT_ERR",this.name="AbortError"}}JH("ERR_ASSERTION","%s",Error);JH("ERR_INVALID_ARG_TYPE",(H,$,A)=>{if(WL(typeof H==="string","'name' must be a string"),!Array.isArray($))$=[$];let L="The ";if(H.endsWith(" argument"))L+=`${H} `;else L+=`"${H}" ${H.includes(".")?"property":"argument"} `;L+="must be ";let D=[],f=[],E=[];for(let P of $)if(WL(typeof P==="string","All expected entries have to be of type string"),dB.includes(P))D.push(P.toLowerCase());else if(aB.test(P))f.push(P);else WL(P!=="object",'The value "object" should be written as "Object"'),E.push(P);if(f.length>0){let P=D.indexOf("object");if(P!==-1)D.splice(D,P,1),f.push("Object")}if(D.length>0){switch(D.length){case 1:L+=`of type ${D[0]}`;break;case 2:L+=`one of type ${D[0]} or ${D[1]}`;break;default:{let P=D.pop();L+=`one of type ${D.join(", ")}, or ${P}`}}if(f.length>0||E.length>0)L+=" or "}if(f.length>0){switch(f.length){case 1:L+=`an instance of ${f[0]}`;break;case 2:L+=`an instance of ${f[0]} or ${f[1]}`;break;default:{let P=f.pop();L+=`an instance of ${f.join(", ")}, or ${P}`}}if(E.length>0)L+=" or "}switch(E.length){case 0:break;case 1:if(E[0].toLowerCase()!==E[0])L+="an ";L+=`${E[0]}`;break;case 2:L+=`one of ${E[0]} or ${E[1]}`;break;default:{let P=E.pop();L+=`one of ${E.join(", ")}, or ${P}`}}if(A==null)L+=`. Received ${A}`;else if(typeof A==="function"&&A.name)L+=`. Received function ${A.name}`;else if(typeof A==="object"){var I;if((I=A.constructor)!==null&&I!==void 0&&I.name)L+=`. Received an instance of ${A.constructor.name}`;else{let P=I0(A,{depth:-1});L+=`. Received ${P}`}}else{let P=I0(A,{colors:!1});if(P.length>25)P=`${P.slice(0,25)}...`;L+=`. Received type ${typeof A} (${P})`}return L},TypeError);JH("ERR_INVALID_ARG_VALUE",(H,$,A="is invalid")=>{let L=I0($);if(L.length>128)L=L.slice(0,128)+"...";return`The ${H.includes(".")?"property":"argument"} '${H}' ${A}. Received ${L}`},TypeError);JH("ERR_INVALID_RETURN_VALUE",(H,$,A)=>{var L;let D=A!==null&&A!==void 0&&(L=A.constructor)!==null&&L!==void 0&&L.name?`instance of ${A.constructor.name}`:`type ${typeof A}`;return`Expected ${H} to be returned from the "${$}" function but got ${D}.`},TypeError);JH("ERR_MISSING_ARGS",(...H)=>{WL(H.length>0,"At least one arg needs to be specified");let $,A=H.length;switch(H=(Array.isArray(H)?H:[H]).map((L)=>`"${L}"`).join(" or "),A){case 1:$+=`The ${H[0]} argument`;break;case 2:$+=`The ${H[0]} and ${H[1]} arguments`;break;default:{let L=H.pop();$+=`The ${H.join(", ")}, and ${L} arguments`}break}return`${$} must be specified`},TypeError);JH("ERR_OUT_OF_RANGE",(H,$,A)=>{WL($,'Missing "range" argument');let L;if(Number.isInteger(A)&&Math.abs(A)>4294967296)L=ht(String(A));else if(typeof A==="bigint"){L=String(A);let D=BigInt(2)**BigInt(32);if(A>D||A<-D)L=ht(L);L+="n"}else L=I0(A);return`The value of "${H}" is out of range. It must be ${$}. Received ${L}`},RangeError);JH("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);JH("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);JH("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);JH("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);JH("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);JH("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);JH("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);JH("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);JH("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);JH("ERR_STREAM_WRITE_AFTER_END","write after end",Error);JH("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);St.exports={AbortError:Xt,aggregateTwoErrors:ct(yB),hideStackFrames:ct,codes:P0}});var L$=p((Ck,xI)=>{var bB=B("buffer"),{format:NB,inspect:kB}=WI(),{codes:{ERR_INVALID_ARG_TYPE:uI}}=qH(),{kResistStopPropagation:RB,AggregateError:OB,SymbolDispose:mB}=XH(),wB=globalThis.AbortSignal||B("abort-controller").AbortSignal,eB=globalThis.AbortController||B("abort-controller").AbortController,jB=Object.getPrototypeOf(async function(){}).constructor,rt=globalThis.Blob||bB.Blob,JB=typeof rt<"u"?function($){return $ instanceof rt}:function($){return!1},Bt=(H,$)=>{if(H!==void 0&&(H===null||typeof H!=="object"||!("aborted"in H)))throw new uI($,"AbortSignal",H)},QB=(H,$)=>{if(typeof H!=="function")throw new uI($,"Function",H)};xI.exports={AggregateError:OB,kEmptyObject:Object.freeze({}),once(H){let $=!1;return function(...A){if($)return;$=!0,H.apply(this,A)}},createDeferredPromise:function(){let H,$;return{promise:new Promise((L,D)=>{H=L,$=D}),resolve:H,reject:$}},promisify(H){return new Promise(($,A)=>{H((L,...D)=>{if(L)return A(L);return $(...D)})})},debuglog(){return function(){}},format:NB,inspect:kB,types:{isAsyncFunction(H){return H instanceof jB},isArrayBufferView(H){return ArrayBuffer.isView(H)}},isBlob:JB,deprecate(H,$){return H},addAbortListener:B("events").addAbortListener||function($,A){if($===void 0)throw new uI("signal","AbortSignal",$);Bt($,"signal"),QB(A,"listener");let L;if($.aborted)queueMicrotask(()=>A());else $.addEventListener("abort",A,{__proto__:null,once:!0,[RB]:!0}),L=()=>{$.removeEventListener("abort",A)};return{__proto__:null,[mB](){var D;(D=L)===null||D===void 0||D()}}},AbortSignalAny:wB.any||function($){if($.length===1)return $[0];let A=new eB,L=()=>A.abort();return $.forEach((D)=>{Bt(D,"signals"),D.addEventListener("abort",L,{once:!0})}),A.signal.addEventListener("abort",()=>{$.forEach((D)=>D.removeEventListener("abort",L))},{once:!0}),A.signal}};xI.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var ZL=p((ik,lt)=>{var{ArrayIsArray:cI,ArrayPrototypeIncludes:st,ArrayPrototypeJoin:Ct,ArrayPrototypeMap:KB,NumberIsInteger:XI,NumberIsNaN:gB,NumberMAX_SAFE_INTEGER:vB,NumberMIN_SAFE_INTEGER:YB,NumberParseInt:qB,ObjectPrototypeHasOwnProperty:ZB,RegExpPrototypeExec:it,String:zB,StringPrototypeToUpperCase:Hn,StringPrototypeTrim:$n}=XH(),{hideStackFrames:o$,codes:{ERR_SOCKET_BAD_PORT:An,ERR_INVALID_ARG_TYPE:ZH,ERR_INVALID_ARG_VALUE:qL,ERR_OUT_OF_RANGE:uL,ERR_UNKNOWN_SIGNAL:nt}}=qH(),{normalizeEncoding:Ln}=L$(),{isAsyncFunction:Dn,isArrayBufferView:fn}=L$().types,ot={};function En(H){return H===(H|0)}function In(H){return H===H>>>0}var Pn=/^[0-7]+$/,Tn="must be a 32-bit unsigned integer or an octal string";function Un(H,$,A){if(typeof H>"u")H=A;if(typeof H==="string"){if(it(Pn,H)===null)throw new qL($,H,Tn);H=qB(H,8)}return Gt(H,$),H}var Mn=o$((H,$,A=YB,L=vB)=>{if(typeof H!=="number")throw new ZH($,"number",H);if(!XI(H))throw new uL($,"an integer",H);if(H<A||H>L)throw new uL($,`>= ${A} && <= ${L}`,H)}),tn=o$((H,$,A=-2147483648,L=2147483647)=>{if(typeof H!=="number")throw new ZH($,"number",H);if(!XI(H))throw new uL($,"an integer",H);if(H<A||H>L)throw new uL($,`>= ${A} && <= ${L}`,H)}),Gt=o$((H,$,A=!1)=>{if(typeof H!=="number")throw new ZH($,"number",H);if(!XI(H))throw new uL($,"an integer",H);let L=A?1:0,D=4294967295;if(H<L||H>D)throw new uL($,`>= ${L} && <= ${D}`,H)});function SI(H,$){if(typeof H!=="string")throw new ZH($,"string",H)}function _n(H,$,A=void 0,L){if(typeof H!=="number")throw new ZH($,"number",H);if(A!=null&&H<A||L!=null&&H>L||(A!=null||L!=null)&&gB(H))throw new uL($,`${A!=null?`>= ${A}`:""}${A!=null&&L!=null?" && ":""}${L!=null?`<= ${L}`:""}`,H)}var pn=o$((H,$,A)=>{if(!st(A,H)){let D="must be one of: "+Ct(KB(A,(f)=>typeof f==="string"?`'${f}'`:zB(f)),", ");throw new qL($,H,D)}});function dt(H,$){if(typeof H!=="boolean")throw new ZH($,"boolean",H)}function hI(H,$,A){return H==null||!ZB(H,$)?A:H[$]}var Vn=o$((H,$,A=null)=>{let L=hI(A,"allowArray",!1),D=hI(A,"allowFunction",!1);if(!hI(A,"nullable",!1)&&H===null||!L&&cI(H)||typeof H!=="object"&&(!D||typeof H!=="function"))throw new ZH($,"Object",H)}),Wn=o$((H,$)=>{if(H!=null&&typeof H!=="object"&&typeof H!=="function")throw new ZH($,"a dictionary",H)}),T0=o$((H,$,A=0)=>{if(!cI(H))throw new ZH($,"Array",H);if(H.length<A){let L=`must be longer than ${A}`;throw new qL($,H,L)}});function un(H,$){T0(H,$);for(let A=0;A<H.length;A++)SI(H[A],`${$}[${A}]`)}function xn(H,$){T0(H,$);for(let A=0;A<H.length;A++)dt(H[A],`${$}[${A}]`)}function hn(H,$){T0(H,$);for(let A=0;A<H.length;A++){let L=H[A],D=`${$}[${A}]`;if(L==null)throw new ZH(D,"AbortSignal",L);at(L,D)}}function cn(H,$="signal"){if(SI(H,$),ot[H]===void 0){if(ot[Hn(H)]!==void 0)throw new nt(H+" (signals must use all capital letters)");throw new nt(H)}}var Xn=o$((H,$="buffer")=>{if(!fn(H))throw new ZH($,["Buffer","TypedArray","DataView"],H)});function Sn(H,$){let A=Ln($),L=H.length;if(A==="hex"&&L%2!==0)throw new qL("encoding",$,`is invalid for data of length ${L}`)}function rn(H,$="Port",A=!0){if(typeof H!=="number"&&typeof H!=="string"||typeof H==="string"&&$n(H).length===0||+H!==+H>>>0||H>65535||H===0&&!A)throw new An($,H,A);return H|0}var at=o$((H,$)=>{if(H!==void 0&&(H===null||typeof H!=="object"||!("aborted"in H)))throw new ZH($,"AbortSignal",H)}),Bn=o$((H,$)=>{if(typeof H!=="function")throw new ZH($,"Function",H)}),nn=o$((H,$)=>{if(typeof H!=="function"||Dn(H))throw new ZH($,"Function",H)}),on=o$((H,$)=>{if(H!==void 0)throw new ZH($,"undefined",H)});function Fn(H,$,A){if(!st(A,H))throw new ZH($,`('${Ct(A,"|")}')`,H)}var sn=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function Ft(H,$){if(typeof H>"u"||!it(sn,H))throw new qL($,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function Cn(H){if(typeof H==="string")return Ft(H,"hints"),H;else if(cI(H)){let $=H.length,A="";if($===0)return A;for(let L=0;L<$;L++){let D=H[L];if(Ft(D,"hints"),A+=D,L!==$-1)A+=", "}return A}throw new qL("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}lt.exports={isInt32:En,isUint32:In,parseFileMode:Un,validateArray:T0,validateStringArray:un,validateBooleanArray:xn,validateAbortSignalArray:hn,validateBoolean:dt,validateBuffer:Xn,validateDictionary:Wn,validateEncoding:Sn,validateFunction:Bn,validateInt32:tn,validateInteger:Mn,validateNumber:_n,validateObject:Vn,validateOneOf:pn,validatePlainFunction:nn,validatePort:rn,validateSignalName:cn,validateString:SI,validateUint32:Gt,validateUndefined:on,validateUnion:Fn,validateAbortSignal:at,validateLinkHeaderValue:Cn}});var qA=p((Gk,yt)=>{yt.exports=global.process});var IA=p((dk,Yt)=>{var{SymbolAsyncIterator:bt,SymbolIterator:Nt,SymbolFor:xL}=XH(),kt=xL("nodejs.stream.destroyed"),Rt=xL("nodejs.stream.errored"),rI=xL("nodejs.stream.readable"),BI=xL("nodejs.stream.writable"),Ot=xL("nodejs.stream.disturbed"),Gn=xL("nodejs.webstream.isClosedPromise"),dn=xL("nodejs.webstream.controllerErrorFunction");function U0(H,$=!1){var A;return!!(H&&typeof H.pipe==="function"&&typeof H.on==="function"&&(!$||typeof H.pause==="function"&&typeof H.resume==="function")&&(!H._writableState||((A=H._readableState)===null||A===void 0?void 0:A.readable)!==!1)&&(!H._writableState||H._readableState))}function M0(H){var $;return!!(H&&typeof H.write==="function"&&typeof H.on==="function"&&(!H._readableState||(($=H._writableState)===null||$===void 0?void 0:$.writable)!==!1))}function an(H){return!!(H&&typeof H.pipe==="function"&&H._readableState&&typeof H.on==="function"&&typeof H.write==="function")}function EA(H){return H&&(H._readableState||H._writableState||typeof H.write==="function"&&typeof H.on==="function"||typeof H.pipe==="function"&&typeof H.on==="function")}function mt(H){return!!(H&&!EA(H)&&typeof H.pipeThrough==="function"&&typeof H.getReader==="function"&&typeof H.cancel==="function")}function wt(H){return!!(H&&!EA(H)&&typeof H.getWriter==="function"&&typeof H.abort==="function")}function et(H){return!!(H&&!EA(H)&&typeof H.readable==="object"&&typeof H.writable==="object")}function ln(H){return mt(H)||wt(H)||et(H)}function yn(H,$){if(H==null)return!1;if($===!0)return typeof H[bt]==="function";if($===!1)return typeof H[Nt]==="function";return typeof H[bt]==="function"||typeof H[Nt]==="function"}function t0(H){if(!EA(H))return null;let{_writableState:$,_readableState:A}=H,L=$||A;return!!(H.destroyed||H[kt]||L!==null&&L!==void 0&&L.destroyed)}function jt(H){if(!M0(H))return null;if(H.writableEnded===!0)return!0;let $=H._writableState;if($!==null&&$!==void 0&&$.errored)return!1;if(typeof($===null||$===void 0?void 0:$.ended)!=="boolean")return null;return $.ended}function bn(H,$){if(!M0(H))return null;if(H.writableFinished===!0)return!0;let A=H._writableState;if(A!==null&&A!==void 0&&A.errored)return!1;if(typeof(A===null||A===void 0?void 0:A.finished)!=="boolean")return null;return!!(A.finished||$===!1&&A.ended===!0&&A.length===0)}function Nn(H){if(!U0(H))return null;if(H.readableEnded===!0)return!0;let $=H._readableState;if(!$||$.errored)return!1;if(typeof($===null||$===void 0?void 0:$.ended)!=="boolean")return null;return $.ended}function Jt(H,$){if(!U0(H))return null;let A=H._readableState;if(A!==null&&A!==void 0&&A.errored)return!1;if(typeof(A===null||A===void 0?void 0:A.endEmitted)!=="boolean")return null;return!!(A.endEmitted||$===!1&&A.ended===!0&&A.length===0)}function Qt(H){if(H&&H[rI]!=null)return H[rI];if(typeof(H===null||H===void 0?void 0:H.readable)!=="boolean")return null;if(t0(H))return!1;return U0(H)&&H.readable&&!Jt(H)}function Kt(H){if(H&&H[BI]!=null)return H[BI];if(typeof(H===null||H===void 0?void 0:H.writable)!=="boolean")return null;if(t0(H))return!1;return M0(H)&&H.writable&&!jt(H)}function kn(H,$){if(!EA(H))return null;if(t0(H))return!0;if(($===null||$===void 0?void 0:$.readable)!==!1&&Qt(H))return!1;if(($===null||$===void 0?void 0:$.writable)!==!1&&Kt(H))return!1;return!0}function Rn(H){var $,A;if(!EA(H))return null;if(H.writableErrored)return H.writableErrored;return($=(A=H._writableState)===null||A===void 0?void 0:A.errored)!==null&&$!==void 0?$:null}function On(H){var $,A;if(!EA(H))return null;if(H.readableErrored)return H.readableErrored;return($=(A=H._readableState)===null||A===void 0?void 0:A.errored)!==null&&$!==void 0?$:null}function mn(H){if(!EA(H))return null;if(typeof H.closed==="boolean")return H.closed;let{_writableState:$,_readableState:A}=H;if(typeof($===null||$===void 0?void 0:$.closed)==="boolean"||typeof(A===null||A===void 0?void 0:A.closed)==="boolean")return($===null||$===void 0?void 0:$.closed)||(A===null||A===void 0?void 0:A.closed);if(typeof H._closed==="boolean"&>(H))return H._closed;return null}function gt(H){return typeof H._closed==="boolean"&&typeof H._defaultKeepAlive==="boolean"&&typeof H._removedConnection==="boolean"&&typeof H._removedContLen==="boolean"}function vt(H){return typeof H._sent100==="boolean"&>(H)}function wn(H){var $;return typeof H._consuming==="boolean"&&typeof H._dumped==="boolean"&&(($=H.req)===null||$===void 0?void 0:$.upgradeOrConnect)===void 0}function en(H){if(!EA(H))return null;let{_writableState:$,_readableState:A}=H,L=$||A;return!L&&vt(H)||!!(L&&L.autoDestroy&&L.emitClose&&L.closed===!1)}function jn(H){var $;return!!(H&&(($=H[Ot])!==null&&$!==void 0?$:H.readableDidRead||H.readableAborted))}function Jn(H){var $,A,L,D,f,E,I,P,T,U;return!!(H&&(($=(A=(L=(D=(f=(E=H[Rt])!==null&&E!==void 0?E:H.readableErrored)!==null&&f!==void 0?f:H.writableErrored)!==null&&D!==void 0?D:(I=H._readableState)===null||I===void 0?void 0:I.errorEmitted)!==null&&L!==void 0?L:(P=H._writableState)===null||P===void 0?void 0:P.errorEmitted)!==null&&A!==void 0?A:(T=H._readableState)===null||T===void 0?void 0:T.errored)!==null&&$!==void 0?$:(U=H._writableState)===null||U===void 0?void 0:U.errored))}Yt.exports={isDestroyed:t0,kIsDestroyed:kt,isDisturbed:jn,kIsDisturbed:Ot,isErrored:Jn,kIsErrored:Rt,isReadable:Qt,kIsReadable:rI,kIsClosedPromise:Gn,kControllerErrorFunction:dn,kIsWritable:BI,isClosed:mn,isDuplexNodeStream:an,isFinished:kn,isIterable:yn,isReadableNodeStream:U0,isReadableStream:mt,isReadableEnded:Nn,isReadableFinished:Jt,isReadableErrored:On,isNodeStream:EA,isWebStream:ln,isWritable:Kt,isWritableNodeStream:M0,isWritableStream:wt,isWritableEnded:jt,isWritableFinished:bn,isWritableErrored:Rn,isServerRequest:wn,isServerResponse:vt,willEmitClose:en,isTransformStream:et}});var dA=p((ak,CI)=>{var ZA=qA(),{AbortError:f_,codes:Qn}=qH(),{ERR_INVALID_ARG_TYPE:Kn,ERR_STREAM_PREMATURE_CLOSE:qt}=Qn,{kEmptyObject:oI,once:FI}=L$(),{validateAbortSignal:gn,validateFunction:vn,validateObject:Yn,validateBoolean:qn}=ZL(),{Promise:Zn,PromisePrototypeThen:zn,SymbolDispose:E_}=XH(),{isClosed:Ho,isReadable:Zt,isReadableNodeStream:nI,isReadableStream:$o,isReadableFinished:zt,isReadableErrored:H_,isWritable:$_,isWritableNodeStream:A_,isWritableStream:Ao,isWritableFinished:L_,isWritableErrored:D_,isNodeStream:Lo,willEmitClose:Do,kIsClosedPromise:fo}=IA(),zL;function Eo(H){return H.setHeader&&typeof H.abort==="function"}var sI=()=>{};function I_(H,$,A){var L,D;if(arguments.length===2)A=$,$=oI;else if($==null)$=oI;else Yn($,"options");if(vn(A,"callback"),gn($.signal,"options.signal"),A=FI(A),$o(H)||Ao(H))return Io(H,$,A);if(!Lo(H))throw new Kn("stream",["ReadableStream","WritableStream","Stream"],H);let f=(L=$.readable)!==null&&L!==void 0?L:nI(H),E=(D=$.writable)!==null&&D!==void 0?D:A_(H),I=H._writableState,P=H._readableState,T=()=>{if(!H.writable)t()},U=Do(H)&&nI(H)===f&&A_(H)===E,M=L_(H,!1),t=()=>{if(M=!0,H.destroyed)U=!1;if(U&&(!H.readable||f))return;if(!f||_)A.call(H)},_=zt(H,!1),x=()=>{if(_=!0,H.destroyed)U=!1;if(U&&(!H.writable||E))return;if(!E||M)A.call(H)},V=(N)=>{A.call(H,N)},h=Ho(H),W=()=>{h=!0;let N=D_(H)||H_(H);if(N&&typeof N!=="boolean")return A.call(H,N);if(f&&!_&&nI(H,!0)){if(!zt(H,!1))return A.call(H,new qt)}if(E&&!M){if(!L_(H,!1))return A.call(H,new qt)}A.call(H)},c=()=>{h=!0;let N=D_(H)||H_(H);if(N&&typeof N!=="boolean")return A.call(H,N);A.call(H)},r=()=>{H.req.on("finish",t)};if(Eo(H)){if(H.on("complete",t),!U)H.on("abort",W);if(H.req)r();else H.on("request",r)}else if(E&&!I)H.on("end",T),H.on("close",T);if(!U&&typeof H.aborted==="boolean")H.on("aborted",W);if(H.on("end",x),H.on("finish",t),$.error!==!1)H.on("error",V);if(H.on("close",W),h)ZA.nextTick(W);else if(I!==null&&I!==void 0&&I.errorEmitted||P!==null&&P!==void 0&&P.errorEmitted){if(!U)ZA.nextTick(c)}else if(!f&&(!U||Zt(H))&&(M||$_(H)===!1))ZA.nextTick(c);else if(!E&&(!U||$_(H))&&(_||Zt(H)===!1))ZA.nextTick(c);else if(P&&H.req&&H.aborted)ZA.nextTick(c);let F=()=>{if(A=sI,H.removeListener("aborted",W),H.removeListener("complete",t),H.removeListener("abort",W),H.removeListener("request",r),H.req)H.req.removeListener("finish",t);H.removeListener("end",T),H.removeListener("close",T),H.removeListener("finish",t),H.removeListener("end",x),H.removeListener("error",V),H.removeListener("close",W)};if($.signal&&!h){let N=()=>{let y=A;F(),y.call(H,new f_(void 0,{cause:$.signal.reason}))};if($.signal.aborted)ZA.nextTick(N);else{zL=zL||L$().addAbortListener;let y=zL($.signal,N),k=A;A=FI((...J)=>{y[E_](),k.apply(H,J)})}}return F}function Io(H,$,A){let L=!1,D=sI;if($.signal)if(D=()=>{L=!0,A.call(H,new f_(void 0,{cause:$.signal.reason}))},$.signal.aborted)ZA.nextTick(D);else{zL=zL||L$().addAbortListener;let E=zL($.signal,D),I=A;A=FI((...P)=>{E[E_](),I.apply(H,P)})}let f=(...E)=>{if(!L)ZA.nextTick(()=>A.apply(H,E))};return zn(H[fo].promise,f,f),sI}function Po(H,$){var A;let L=!1;if($===null)$=oI;if((A=$)!==null&&A!==void 0&&A.cleanup)qn($.cleanup,"cleanup"),L=$.cleanup;return new Zn((D,f)=>{let E=I_(H,$,(I)=>{if(L)E();if(I)f(I);else D()})})}CI.exports=I_;CI.exports.finished=Po});var hL=p((lk,V_)=>{var PA=qA(),{aggregateTwoErrors:To,codes:{ERR_MULTIPLE_CALLBACK:Uo},AbortError:Mo}=qH(),{Symbol:U_}=XH(),{kIsDestroyed:to,isDestroyed:_o,isFinished:po,isServerRequest:Vo}=IA(),M_=U_("kDestroy"),iI=U_("kConstruct");function t_(H,$,A){if(H){if(H.stack,$&&!$.errored)$.errored=H;if(A&&!A.errored)A.errored=H}}function Wo(H,$){let A=this._readableState,L=this._writableState,D=L||A;if(L!==null&&L!==void 0&&L.destroyed||A!==null&&A!==void 0&&A.destroyed){if(typeof $==="function")$();return this}if(t_(H,L,A),L)L.destroyed=!0;if(A)A.destroyed=!0;if(!D.constructed)this.once(M_,function(f){P_(this,To(f,H),$)});else P_(this,H,$);return this}function P_(H,$,A){let L=!1;function D(f){if(L)return;L=!0;let{_readableState:E,_writableState:I}=H;if(t_(f,I,E),I)I.closed=!0;if(E)E.closed=!0;if(typeof A==="function")A(f);if(f)PA.nextTick(uo,H,f);else PA.nextTick(__,H)}try{H._destroy($||null,D)}catch(f){D(f)}}function uo(H,$){GI(H,$),__(H)}function __(H){let{_readableState:$,_writableState:A}=H;if(A)A.closeEmitted=!0;if($)$.closeEmitted=!0;if(A!==null&&A!==void 0&&A.emitClose||$!==null&&$!==void 0&&$.emitClose)H.emit("close")}function GI(H,$){let{_readableState:A,_writableState:L}=H;if(L!==null&&L!==void 0&&L.errorEmitted||A!==null&&A!==void 0&&A.errorEmitted)return;if(L)L.errorEmitted=!0;if(A)A.errorEmitted=!0;H.emit("error",$)}function xo(){let H=this._readableState,$=this._writableState;if(H)H.constructed=!0,H.closed=!1,H.closeEmitted=!1,H.destroyed=!1,H.errored=null,H.errorEmitted=!1,H.reading=!1,H.ended=H.readable===!1,H.endEmitted=H.readable===!1;if($)$.constructed=!0,$.destroyed=!1,$.closed=!1,$.closeEmitted=!1,$.errored=null,$.errorEmitted=!1,$.finalCalled=!1,$.prefinished=!1,$.ended=$.writable===!1,$.ending=$.writable===!1,$.finished=$.writable===!1}function dI(H,$,A){let{_readableState:L,_writableState:D}=H;if(D!==null&&D!==void 0&&D.destroyed||L!==null&&L!==void 0&&L.destroyed)return this;if(L!==null&&L!==void 0&&L.autoDestroy||D!==null&&D!==void 0&&D.autoDestroy)H.destroy($);else if($){if($.stack,D&&!D.errored)D.errored=$;if(L&&!L.errored)L.errored=$;if(A)PA.nextTick(GI,H,$);else GI(H,$)}}function ho(H,$){if(typeof H._construct!=="function")return;let{_readableState:A,_writableState:L}=H;if(A)A.constructed=!1;if(L)L.constructed=!1;if(H.once(iI,$),H.listenerCount(iI)>1)return;PA.nextTick(co,H)}function co(H){let $=!1;function A(L){if($){dI(H,L!==null&&L!==void 0?L:new Uo);return}$=!0;let{_readableState:D,_writableState:f}=H,E=f||D;if(D)D.constructed=!0;if(f)f.constructed=!0;if(E.destroyed)H.emit(M_,L);else if(L)dI(H,L,!0);else PA.nextTick(Xo,H)}try{H._construct((L)=>{PA.nextTick(A,L)})}catch(L){PA.nextTick(A,L)}}function Xo(H){H.emit(iI)}function T_(H){return(H===null||H===void 0?void 0:H.setHeader)&&typeof H.abort==="function"}function p_(H){H.emit("close")}function So(H,$){H.emit("error",$),PA.nextTick(p_,H)}function ro(H,$){if(!H||_o(H))return;if(!$&&!po(H))$=new Mo;if(Vo(H))H.socket=null,H.destroy($);else if(T_(H))H.abort();else if(T_(H.req))H.req.abort();else if(typeof H.destroy==="function")H.destroy($);else if(typeof H.close==="function")H.close();else if($)PA.nextTick(So,H,$);else PA.nextTick(p_,H);if(!H.destroyed)H[to]=!0}V_.exports={construct:ho,destroyer:ro,destroy:Wo,undestroy:xo,errorOrDestroy:dI}});var V0=p((yk,u_)=>{var{ArrayIsArray:Bo,ObjectSetPrototypeOf:W_}=XH(),{EventEmitter:_0}=B("events");function p0(H){_0.call(this,H)}W_(p0.prototype,_0.prototype);W_(p0,_0);p0.prototype.pipe=function(H,$){let A=this;function L(U){if(H.writable&&H.write(U)===!1&&A.pause)A.pause()}A.on("data",L);function D(){if(A.readable&&A.resume)A.resume()}if(H.on("drain",D),!H._isStdio&&(!$||$.end!==!1))A.on("end",E),A.on("close",I);let f=!1;function E(){if(f)return;f=!0,H.end()}function I(){if(f)return;if(f=!0,typeof H.destroy==="function")H.destroy()}function P(U){if(T(),_0.listenerCount(this,"error")===0)this.emit("error",U)}aI(A,"error",P),aI(H,"error",P);function T(){A.removeListener("data",L),H.removeListener("drain",D),A.removeListener("end",E),A.removeListener("close",I),A.removeListener("error",P),H.removeListener("error",P),A.removeListener("end",T),A.removeListener("close",T),H.removeListener("close",T)}return A.on("end",T),A.on("close",T),H.on("close",T),H.emit("pipe",A),H};function aI(H,$,A){if(typeof H.prependListener==="function")return H.prependListener($,A);if(!H._events||!H._events[$])H.on($,A);else if(Bo(H._events[$]))H._events[$].unshift(A);else H._events[$]=[A,H._events[$]]}u_.exports={Stream:p0,prependListener:aI}});var RD=p((Go,W0)=>{var{SymbolDispose:no}=XH(),{AbortError:x_,codes:oo}=qH(),{isNodeStream:h_,isWebStream:Fo,kControllerErrorFunction:so}=IA(),Co=dA(),{ERR_INVALID_ARG_TYPE:c_}=oo,lI,io=(H,$)=>{if(typeof H!=="object"||!("aborted"in H))throw new c_($,"AbortSignal",H)};Go.addAbortSignal=function($,A){if(io($,"signal"),!h_(A)&&!Fo(A))throw new c_("stream",["ReadableStream","WritableStream","Stream"],A);return Go.addAbortSignalNoValidate($,A)};Go.addAbortSignalNoValidate=function(H,$){if(typeof H!=="object"||!("aborted"in H))return $;let A=h_($)?()=>{$.destroy(new x_(void 0,{cause:H.reason}))}:()=>{$[so](new x_(void 0,{cause:H.reason}))};if(H.aborted)A();else{lI=lI||L$().addAbortListener;let L=lI(H,A);Co($,L[no])}return $}});var r_=p((bk,S_)=>{var{StringPrototypeSlice:X_,SymbolIterator:yo,TypedArrayPrototypeSet:u0,Uint8Array:bo}=XH(),{Buffer:yI}=B("buffer"),{inspect:No}=L$();S_.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push($){let A={data:$,next:null};if(this.length>0)this.tail.next=A;else this.head=A;this.tail=A,++this.length}unshift($){let A={data:$,next:this.head};if(this.length===0)this.tail=A;this.head=A,++this.length}shift(){if(this.length===0)return;let $=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,$}clear(){this.head=this.tail=null,this.length=0}join($){if(this.length===0)return"";let A=this.head,L=""+A.data;while((A=A.next)!==null)L+=$+A.data;return L}concat($){if(this.length===0)return yI.alloc(0);let A=yI.allocUnsafe($>>>0),L=this.head,D=0;while(L)u0(A,L.data,D),D+=L.data.length,L=L.next;return A}consume($,A){let L=this.head.data;if($<L.length){let D=L.slice(0,$);return this.head.data=L.slice($),D}if($===L.length)return this.shift();return A?this._getString($):this._getBuffer($)}first(){return this.head.data}*[yo](){for(let $=this.head;$;$=$.next)yield $.data}_getString($){let A="",L=this.head,D=0;do{let f=L.data;if($>f.length)A+=f,$-=f.length;else{if($===f.length)if(A+=f,++D,L.next)this.head=L.next;else this.head=this.tail=null;else A+=X_(f,0,$),this.head=L,L.data=X_(f,$);break}++D}while((L=L.next)!==null);return this.length-=D,A}_getBuffer($){let A=yI.allocUnsafe($),L=$,D=this.head,f=0;do{let E=D.data;if($>E.length)u0(A,E,L-$),$-=E.length;else{if($===E.length)if(u0(A,E,L-$),++f,D.next)this.head=D.next;else this.head=this.tail=null;else u0(A,new bo(E.buffer,E.byteOffset,$),L-$),this.head=D,D.data=E.slice($);break}++f}while((D=D.next)!==null);return this.length-=f,A}[Symbol.for("nodejs.util.inspect.custom")]($,A){return No(this,{...A,depth:0,customInspect:!1})}}});var OD=p((Nk,F_)=>{var{MathFloor:ko,NumberIsInteger:Ro}=XH(),{validateInteger:Oo}=ZL(),{ERR_INVALID_ARG_VALUE:mo}=qH().codes,B_=16384,n_=16;function wo(H,$,A){return H.highWaterMark!=null?H.highWaterMark:$?H[A]:null}function o_(H){return H?n_:B_}function eo(H,$){if(Oo($,"value",0),H)n_=$;else B_=$}function jo(H,$,A,L){let D=wo($,L,A);if(D!=null){if(!Ro(D)||D<0){let f=L?`options.${A}`:"options.highWaterMark";throw new mo(f,D)}return ko(D)}return o_(H.objectMode)}F_.exports={getHighWaterMark:jo,getDefaultHighWaterMark:o_,setDefaultHighWaterMark:eo}});var i_=p((bI,C_)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var x0=B("buffer"),TA=x0.Buffer;function s_(H,$){for(var A in H)$[A]=H[A]}if(TA.from&&TA.alloc&&TA.allocUnsafe&&TA.allocUnsafeSlow)C_.exports=x0;else s_(x0,bI),bI.Buffer=cL;function cL(H,$,A){return TA(H,$,A)}cL.prototype=Object.create(TA.prototype);s_(TA,cL);cL.from=function(H,$,A){if(typeof H==="number")throw TypeError("Argument must not be a number");return TA(H,$,A)};cL.alloc=function(H,$,A){if(typeof H!=="number")throw TypeError("Argument must be a number");var L=TA(H);if($!==void 0)if(typeof A==="string")L.fill($,A);else L.fill($);else L.fill(0);return L};cL.allocUnsafe=function(H){if(typeof H!=="number")throw TypeError("Argument must be a number");return TA(H)};cL.allocUnsafeSlow=function(H){if(typeof H!=="number")throw TypeError("Argument must be a number");return x0.SlowBuffer(H)}});var d_=p((DF)=>{var kI=i_().Buffer,G_=kI.isEncoding||function(H){switch(H=""+H,H&&H.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function Jo(H){if(!H)return"utf8";var $;while(!0)switch(H){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return H;default:if($)return;H=(""+H).toLowerCase(),$=!0}}function Qo(H){var $=Jo(H);if(typeof $!=="string"&&(kI.isEncoding===G_||!G_(H)))throw Error("Unknown encoding: "+H);return $||H}DF.StringDecoder=mD;function mD(H){this.encoding=Qo(H);var $;switch(this.encoding){case"utf16le":this.text=Zo,this.end=zo,$=4;break;case"utf8":this.fillLast=vo,$=4;break;case"base64":this.text=HF,this.end=$F,$=3;break;default:this.write=AF,this.end=LF;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=kI.allocUnsafe($)}mD.prototype.write=function(H){if(H.length===0)return"";var $,A;if(this.lastNeed){if($=this.fillLast(H),$===void 0)return"";A=this.lastNeed,this.lastNeed=0}else A=0;if(A<H.length)return $?$+this.text(H,A):this.text(H,A);return $||""};mD.prototype.end=qo;mD.prototype.text=Yo;mD.prototype.fillLast=function(H){if(this.lastNeed<=H.length)return H.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);H.copy(this.lastChar,this.lastTotal-this.lastNeed,0,H.length),this.lastNeed-=H.length};function NI(H){if(H<=127)return 0;else if(H>>5===6)return 2;else if(H>>4===14)return 3;else if(H>>3===30)return 4;return H>>6===2?-1:-2}function Ko(H,$,A){var L=$.length-1;if(L<A)return 0;var D=NI($[L]);if(D>=0){if(D>0)H.lastNeed=D-1;return D}if(--L<A||D===-2)return 0;if(D=NI($[L]),D>=0){if(D>0)H.lastNeed=D-2;return D}if(--L<A||D===-2)return 0;if(D=NI($[L]),D>=0){if(D>0)if(D===2)D=0;else H.lastNeed=D-3;return D}return 0}function go(H,$,A){if(($[0]&192)!==128)return H.lastNeed=0,"\uFFFD";if(H.lastNeed>1&&$.length>1){if(($[1]&192)!==128)return H.lastNeed=1,"\uFFFD";if(H.lastNeed>2&&$.length>2){if(($[2]&192)!==128)return H.lastNeed=2,"\uFFFD"}}}function vo(H){var $=this.lastTotal-this.lastNeed,A=go(this,H,$);if(A!==void 0)return A;if(this.lastNeed<=H.length)return H.copy(this.lastChar,$,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);H.copy(this.lastChar,$,0,H.length),this.lastNeed-=H.length}function Yo(H,$){var A=Ko(this,H,$);if(!this.lastNeed)return H.toString("utf8",$);this.lastTotal=A;var L=H.length-(A-this.lastNeed);return H.copy(this.lastChar,0,L),H.toString("utf8",$,L)}function qo(H){var $=H&&H.length?this.write(H):"";if(this.lastNeed)return $+"\uFFFD";return $}function Zo(H,$){if((H.length-$)%2===0){var A=H.toString("utf16le",$);if(A){var L=A.charCodeAt(A.length-1);if(L>=55296&&L<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=H[H.length-2],this.lastChar[1]=H[H.length-1],A.slice(0,-1)}return A}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=H[H.length-1],H.toString("utf16le",$,H.length-1)}function zo(H){var $=H&&H.length?this.write(H):"";if(this.lastNeed){var A=this.lastTotal-this.lastNeed;return $+this.lastChar.toString("utf16le",0,A)}return $}function HF(H,$){var A=(H.length-$)%3;if(A===0)return H.toString("base64",$);if(this.lastNeed=3-A,this.lastTotal=3,A===1)this.lastChar[0]=H[H.length-1];else this.lastChar[0]=H[H.length-2],this.lastChar[1]=H[H.length-1];return H.toString("base64",$,H.length-A)}function $F(H){var $=H&&H.length?this.write(H):"";if(this.lastNeed)return $+this.lastChar.toString("base64",0,3-this.lastNeed);return $}function AF(H){return H.toString(this.encoding)}function LF(H){return H&&H.length?this.write(H):""}});var RI=p((Rk,b_)=>{var a_=qA(),{PromisePrototypeThen:EF,SymbolAsyncIterator:l_,SymbolIterator:y_}=XH(),{Buffer:IF}=B("buffer"),{ERR_INVALID_ARG_TYPE:PF,ERR_STREAM_NULL_VALUES:TF}=qH().codes;function UF(H,$,A){let L;if(typeof $==="string"||$ instanceof IF)return new H({objectMode:!0,...A,read(){this.push($),this.push(null)}});let D;if($&&$[l_])D=!0,L=$[l_]();else if($&&$[y_])D=!1,L=$[y_]();else throw new PF("iterable",["Iterable"],$);let f=new H({objectMode:!0,highWaterMark:1,...A}),E=!1;f._read=function(){if(!E)E=!0,P()},f._destroy=function(T,U){EF(I(T),()=>a_.nextTick(U,T),(M)=>a_.nextTick(U,M||T))};async function I(T){let U=T!==void 0&&T!==null,M=typeof L.throw==="function";if(U&&M){let{value:t,done:_}=await L.throw(T);if(await t,_)return}if(typeof L.return==="function"){let{value:t}=await L.return();await t}}async function P(){for(;;){try{let{value:T,done:U}=D?await L.next():L.next();if(U)f.push(null);else{let M=T&&typeof T.then==="function"?await T:T;if(M===null)throw E=!1,new TF;else if(f.push(M))continue;else E=!1}}catch(T){f.destroy(T)}break}}return f}b_.exports=UF});var eD=p((Ok,Hp)=>{var j$=qA(),{ArrayPrototypeIndexOf:MF,NumberIsInteger:tF,NumberIsNaN:_F,NumberParseInt:pF,ObjectDefineProperties:KI,ObjectKeys:VF,ObjectSetPrototypeOf:R_,Promise:O_,SafeSet:WF,SymbolAsyncDispose:uF,SymbolAsyncIterator:xF,Symbol:hF}=XH();Hp.exports=q;q.ReadableState=S0;var{EventEmitter:cF}=B("events"),{Stream:zA,prependListener:XF}=V0(),{Buffer:OI}=B("buffer"),{addAbortSignal:SF}=RD(),m_=dA(),LH=L$().debuglog("stream",(H)=>{LH=H}),rF=r_(),AD=hL(),{getHighWaterMark:BF,getDefaultHighWaterMark:nF}=OD(),{aggregateTwoErrors:N_,codes:{ERR_INVALID_ARG_TYPE:oF,ERR_METHOD_NOT_IMPLEMENTED:FF,ERR_OUT_OF_RANGE:sF,ERR_STREAM_PUSH_AFTER_EOF:CF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:iF},AbortError:GF}=qH(),{validateObject:dF}=ZL(),XL=hF("kPaused"),{StringDecoder:w_}=d_(),aF=RI();R_(q.prototype,zA.prototype);R_(q,zA);var mI=()=>{},{errorOrDestroy:HD}=AD,$D=1,lF=2,e_=4,wD=8,j_=16,h0=32,c0=64,J_=128,yF=256,bF=512,NF=1024,JI=2048,QI=4096,kF=8192,RF=16384,OF=32768,Q_=65536,mF=131072,wF=262144;function lH(H){return{enumerable:!1,get(){return(this.state&H)!==0},set($){if($)this.state|=H;else this.state&=~H}}}KI(S0.prototype,{objectMode:lH($D),ended:lH(lF),endEmitted:lH(e_),reading:lH(wD),constructed:lH(j_),sync:lH(h0),needReadable:lH(c0),emittedReadable:lH(J_),readableListening:lH(yF),resumeScheduled:lH(bF),errorEmitted:lH(NF),emitClose:lH(JI),autoDestroy:lH(QI),destroyed:lH(kF),closed:lH(RF),closeEmitted:lH(OF),multiAwaitDrain:lH(Q_),readingMore:lH(mF),dataEmitted:lH(wF)});function S0(H,$,A){if(typeof A!=="boolean")A=$ instanceof UA();if(this.state=JI|QI|j_|h0,H&&H.objectMode)this.state|=$D;if(A&&H&&H.readableObjectMode)this.state|=$D;if(this.highWaterMark=H?BF(this,H,"readableHighWaterMark",A):nF(!1),this.buffer=new rF,this.length=0,this.pipes=[],this.flowing=null,this[XL]=null,H&&H.emitClose===!1)this.state&=~JI;if(H&&H.autoDestroy===!1)this.state&=~QI;if(this.errored=null,this.defaultEncoding=H&&H.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,H&&H.encoding)this.decoder=new w_(H.encoding),this.encoding=H.encoding}function q(H){if(!(this instanceof q))return new q(H);let $=this instanceof UA();if(this._readableState=new S0(H,this,$),H){if(typeof H.read==="function")this._read=H.read;if(typeof H.destroy==="function")this._destroy=H.destroy;if(typeof H.construct==="function")this._construct=H.construct;if(H.signal&&!$)SF(H.signal,this)}zA.call(this,H),AD.construct(this,()=>{if(this._readableState.needReadable)X0(this,this._readableState)})}q.prototype.destroy=AD.destroy;q.prototype._undestroy=AD.undestroy;q.prototype._destroy=function(H,$){$(H)};q.prototype[cF.captureRejectionSymbol]=function(H){this.destroy(H)};q.prototype[uF]=function(){let H;if(!this.destroyed)H=this.readableEnded?null:new GF,this.destroy(H);return new O_(($,A)=>m_(this,(L)=>L&&L!==H?A(L):$(null)))};q.prototype.push=function(H,$){return K_(this,H,$,!1)};q.prototype.unshift=function(H,$){return K_(this,H,$,!0)};function K_(H,$,A,L){LH("readableAddChunk",$);let D=H._readableState,f;if((D.state&$D)===0){if(typeof $==="string"){if(A=A||D.defaultEncoding,D.encoding!==A)if(L&&D.encoding)$=OI.from($,A).toString(D.encoding);else $=OI.from($,A),A=""}else if($ instanceof OI)A="";else if(zA._isUint8Array($))$=zA._uint8ArrayToBuffer($),A="";else if($!=null)f=new oF("chunk",["string","Buffer","Uint8Array"],$)}if(f)HD(H,f);else if($===null)D.state&=~wD,JF(H,D);else if((D.state&$D)!==0||$&&$.length>0)if(L)if((D.state&e_)!==0)HD(H,new iF);else if(D.destroyed||D.errored)return!1;else wI(H,D,$,!0);else if(D.ended)HD(H,new CF);else if(D.destroyed||D.errored)return!1;else if(D.state&=~wD,D.decoder&&!A)if($=D.decoder.write($),D.objectMode||$.length!==0)wI(H,D,$,!1);else X0(H,D);else wI(H,D,$,!1);else if(!L)D.state&=~wD,X0(H,D);return!D.ended&&(D.length<D.highWaterMark||D.length===0)}function wI(H,$,A,L){if($.flowing&&$.length===0&&!$.sync&&H.listenerCount("data")>0){if(($.state&Q_)!==0)$.awaitDrainWriters.clear();else $.awaitDrainWriters=null;$.dataEmitted=!0,H.emit("data",A)}else{if($.length+=$.objectMode?1:A.length,L)$.buffer.unshift(A);else $.buffer.push(A);if(($.state&c0)!==0)r0(H)}X0(H,$)}q.prototype.isPaused=function(){let H=this._readableState;return H[XL]===!0||H.flowing===!1};q.prototype.setEncoding=function(H){let $=new w_(H);this._readableState.decoder=$,this._readableState.encoding=this._readableState.decoder.encoding;let A=this._readableState.buffer,L="";for(let D of A)L+=$.write(D);if(A.clear(),L!=="")A.push(L);return this._readableState.length=L.length,this};var eF=1073741824;function jF(H){if(H>eF)throw new sF("size","<= 1GiB",H);else H--,H|=H>>>1,H|=H>>>2,H|=H>>>4,H|=H>>>8,H|=H>>>16,H++;return H}function k_(H,$){if(H<=0||$.length===0&&$.ended)return 0;if(($.state&$D)!==0)return 1;if(_F(H)){if($.flowing&&$.length)return $.buffer.first().length;return $.length}if(H<=$.length)return H;return $.ended?$.length:0}q.prototype.read=function(H){if(LH("read",H),H===void 0)H=NaN;else if(!tF(H))H=pF(H,10);let $=this._readableState,A=H;if(H>$.highWaterMark)$.highWaterMark=jF(H);if(H!==0)$.state&=~J_;if(H===0&&$.needReadable&&(($.highWaterMark!==0?$.length>=$.highWaterMark:$.length>0)||$.ended)){if(LH("read: emitReadable",$.length,$.ended),$.length===0&&$.ended)eI(this);else r0(this);return null}if(H=k_(H,$),H===0&&$.ended){if($.length===0)eI(this);return null}let L=($.state&c0)!==0;if(LH("need readable",L),$.length===0||$.length-H<$.highWaterMark)L=!0,LH("length less than watermark",L);if($.ended||$.reading||$.destroyed||$.errored||!$.constructed)L=!1,LH("reading, ended or constructing",L);else if(L){if(LH("do read"),$.state|=wD|h0,$.length===0)$.state|=c0;try{this._read($.highWaterMark)}catch(f){HD(this,f)}if($.state&=~h0,!$.reading)H=k_(A,$)}let D;if(H>0)D=Z_(H,$);else D=null;if(D===null)$.needReadable=$.length<=$.highWaterMark,H=0;else if($.length-=H,$.multiAwaitDrain)$.awaitDrainWriters.clear();else $.awaitDrainWriters=null;if($.length===0){if(!$.ended)$.needReadable=!0;if(A!==H&&$.ended)eI(this)}if(D!==null&&!$.errorEmitted&&!$.closeEmitted)$.dataEmitted=!0,this.emit("data",D);return D};function JF(H,$){if(LH("onEofChunk"),$.ended)return;if($.decoder){let A=$.decoder.end();if(A&&A.length)$.buffer.push(A),$.length+=$.objectMode?1:A.length}if($.ended=!0,$.sync)r0(H);else $.needReadable=!1,$.emittedReadable=!0,g_(H)}function r0(H){let $=H._readableState;if(LH("emitReadable",$.needReadable,$.emittedReadable),$.needReadable=!1,!$.emittedReadable)LH("emitReadable",$.flowing),$.emittedReadable=!0,j$.nextTick(g_,H)}function g_(H){let $=H._readableState;if(LH("emitReadable_",$.destroyed,$.length,$.ended),!$.destroyed&&!$.errored&&($.length||$.ended))H.emit("readable"),$.emittedReadable=!1;$.needReadable=!$.flowing&&!$.ended&&$.length<=$.highWaterMark,Y_(H)}function X0(H,$){if(!$.readingMore&&$.constructed)$.readingMore=!0,j$.nextTick(QF,H,$)}function QF(H,$){while(!$.reading&&!$.ended&&($.length<$.highWaterMark||$.flowing&&$.length===0)){let A=$.length;if(LH("maybeReadMore read 0"),H.read(0),A===$.length)break}$.readingMore=!1}q.prototype._read=function(H){throw new FF("_read()")};q.prototype.pipe=function(H,$){let A=this,L=this._readableState;if(L.pipes.length===1){if(!L.multiAwaitDrain)L.multiAwaitDrain=!0,L.awaitDrainWriters=new WF(L.awaitDrainWriters?[L.awaitDrainWriters]:[])}L.pipes.push(H),LH("pipe count=%d opts=%j",L.pipes.length,$);let f=(!$||$.end!==!1)&&H!==j$.stdout&&H!==j$.stderr?I:h;if(L.endEmitted)j$.nextTick(f);else A.once("end",f);H.on("unpipe",E);function E(W,c){if(LH("onunpipe"),W===A){if(c&&c.hasUnpiped===!1)c.hasUnpiped=!0,U()}}function I(){LH("onend"),H.end()}let P,T=!1;function U(){if(LH("cleanup"),H.removeListener("close",x),H.removeListener("finish",V),P)H.removeListener("drain",P);if(H.removeListener("error",_),H.removeListener("unpipe",E),A.removeListener("end",I),A.removeListener("end",h),A.removeListener("data",t),T=!0,P&&L.awaitDrainWriters&&(!H._writableState||H._writableState.needDrain))P()}function M(){if(!T){if(L.pipes.length===1&&L.pipes[0]===H)LH("false write response, pause",0),L.awaitDrainWriters=H,L.multiAwaitDrain=!1;else if(L.pipes.length>1&&L.pipes.includes(H))LH("false write response, pause",L.awaitDrainWriters.size),L.awaitDrainWriters.add(H);A.pause()}if(!P)P=KF(A,H),H.on("drain",P)}A.on("data",t);function t(W){LH("ondata");let c=H.write(W);if(LH("dest.write",c),c===!1)M()}function _(W){if(LH("onerror",W),h(),H.removeListener("error",_),H.listenerCount("error")===0){let c=H._writableState||H._readableState;if(c&&!c.errorEmitted)HD(H,W);else H.emit("error",W)}}XF(H,"error",_);function x(){H.removeListener("finish",V),h()}H.once("close",x);function V(){LH("onfinish"),H.removeListener("close",x),h()}H.once("finish",V);function h(){LH("unpipe"),A.unpipe(H)}if(H.emit("pipe",A),H.writableNeedDrain===!0)M();else if(!L.flowing)LH("pipe resume"),A.resume();return H};function KF(H,$){return function(){let L=H._readableState;if(L.awaitDrainWriters===$)LH("pipeOnDrain",1),L.awaitDrainWriters=null;else if(L.multiAwaitDrain)LH("pipeOnDrain",L.awaitDrainWriters.size),L.awaitDrainWriters.delete($);if((!L.awaitDrainWriters||L.awaitDrainWriters.size===0)&&H.listenerCount("data"))H.resume()}}q.prototype.unpipe=function(H){let $=this._readableState,A={hasUnpiped:!1};if($.pipes.length===0)return this;if(!H){let D=$.pipes;$.pipes=[],this.pause();for(let f=0;f<D.length;f++)D[f].emit("unpipe",this,{hasUnpiped:!1});return this}let L=MF($.pipes,H);if(L===-1)return this;if($.pipes.splice(L,1),$.pipes.length===0)this.pause();return H.emit("unpipe",this,A),this};q.prototype.on=function(H,$){let A=zA.prototype.on.call(this,H,$),L=this._readableState;if(H==="data"){if(L.readableListening=this.listenerCount("readable")>0,L.flowing!==!1)this.resume()}else if(H==="readable"){if(!L.endEmitted&&!L.readableListening){if(L.readableListening=L.needReadable=!0,L.flowing=!1,L.emittedReadable=!1,LH("on readable",L.length,L.reading),L.length)r0(this);else if(!L.reading)j$.nextTick(gF,this)}}return A};q.prototype.addListener=q.prototype.on;q.prototype.removeListener=function(H,$){let A=zA.prototype.removeListener.call(this,H,$);if(H==="readable")j$.nextTick(v_,this);return A};q.prototype.off=q.prototype.removeListener;q.prototype.removeAllListeners=function(H){let $=zA.prototype.removeAllListeners.apply(this,arguments);if(H==="readable"||H===void 0)j$.nextTick(v_,this);return $};function v_(H){let $=H._readableState;if($.readableListening=H.listenerCount("readable")>0,$.resumeScheduled&&$[XL]===!1)$.flowing=!0;else if(H.listenerCount("data")>0)H.resume();else if(!$.readableListening)$.flowing=null}function gF(H){LH("readable nexttick read 0"),H.read(0)}q.prototype.resume=function(){let H=this._readableState;if(!H.flowing)LH("resume"),H.flowing=!H.readableListening,vF(this,H);return H[XL]=!1,this};function vF(H,$){if(!$.resumeScheduled)$.resumeScheduled=!0,j$.nextTick(YF,H,$)}function YF(H,$){if(LH("resume",$.reading),!$.reading)H.read(0);if($.resumeScheduled=!1,H.emit("resume"),Y_(H),$.flowing&&!$.reading)H.read(0)}q.prototype.pause=function(){if(LH("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)LH("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState[XL]=!0,this};function Y_(H){let $=H._readableState;LH("flow",$.flowing);while($.flowing&&H.read()!==null);}q.prototype.wrap=function(H){let $=!1;H.on("data",(L)=>{if(!this.push(L)&&H.pause)$=!0,H.pause()}),H.on("end",()=>{this.push(null)}),H.on("error",(L)=>{HD(this,L)}),H.on("close",()=>{this.destroy()}),H.on("destroy",()=>{this.destroy()}),this._read=()=>{if($&&H.resume)$=!1,H.resume()};let A=VF(H);for(let L=1;L<A.length;L++){let D=A[L];if(this[D]===void 0&&typeof H[D]==="function")this[D]=H[D].bind(H)}return this};q.prototype[xF]=function(){return q_(this)};q.prototype.iterator=function(H){if(H!==void 0)dF(H,"options");return q_(this,H)};function q_(H,$){if(typeof H.read!=="function")H=q.wrap(H,{objectMode:!0});let A=qF(H,$);return A.stream=H,A}async function*qF(H,$){let A=mI;function L(E){if(this===H)A(),A=mI;else A=E}H.on("readable",L);let D,f=m_(H,{writable:!1},(E)=>{D=E?N_(D,E):null,A(),A=mI});try{while(!0){let E=H.destroyed?null:H.read();if(E!==null)yield E;else if(D)throw D;else if(D===null)return;else await new O_(L)}}catch(E){throw D=N_(D,E),D}finally{if((D||($===null||$===void 0?void 0:$.destroyOnReturn)!==!1)&&(D===void 0||H._readableState.autoDestroy))AD.destroyer(H,null);else H.off("readable",L),f()}}KI(q.prototype,{readable:{__proto__:null,get(){let H=this._readableState;return!!H&&H.readable!==!1&&!H.destroyed&&!H.errorEmitted&&!H.endEmitted},set(H){if(this._readableState)this._readableState.readable=!!H}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(H){if(this._readableState)this._readableState.flowing=H}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(H){if(!this._readableState)return;this._readableState.destroyed=H}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});KI(S0.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[XL]!==!1},set(H){this[XL]=!!H}}});q._fromList=Z_;function Z_(H,$){if($.length===0)return null;let A;if($.objectMode)A=$.buffer.shift();else if(!H||H>=$.length){if($.decoder)A=$.buffer.join("");else if($.buffer.length===1)A=$.buffer.first();else A=$.buffer.concat($.length);$.buffer.clear()}else A=$.buffer.consume(H,$.decoder);return A}function eI(H){let $=H._readableState;if(LH("endReadable",$.endEmitted),!$.endEmitted)$.ended=!0,j$.nextTick(ZF,$,H)}function ZF(H,$){if(LH("endReadableNT",H.endEmitted,H.length),!H.errored&&!H.closeEmitted&&!H.endEmitted&&H.length===0){if(H.endEmitted=!0,$.emit("end"),$.writable&&$.allowHalfOpen===!1)j$.nextTick(zF,$);else if(H.autoDestroy){let A=$._writableState;if(!A||A.autoDestroy&&(A.finished||A.writable===!1))$.destroy()}}}function zF(H){if(H.writable&&!H.writableEnded&&!H.destroyed)H.end()}q.from=function(H,$){return aF(q,H,$)};var jI;function z_(){if(jI===void 0)jI={};return jI}q.fromWeb=function(H,$){return z_().newStreamReadableFromReadableStream(H,$)};q.toWeb=function(H,$){return z_().newReadableStreamFromStreamReadable(H,$)};q.wrap=function(H,$){var A,L;return new q({objectMode:(A=(L=H.readableObjectMode)!==null&&L!==void 0?L:H.objectMode)!==null&&A!==void 0?A:!0,...$,destroy(D,f){AD.destroyer(H,D),f(D)}}).wrap(H)}});var s0=p((mk,tp)=>{var SL=qA(),{ArrayPrototypeSlice:Lp,Error:Hs,FunctionPrototypeSymbolHasInstance:Dp,ObjectDefineProperty:fp,ObjectDefineProperties:$s,ObjectSetPrototypeOf:Ep,StringPrototypeToLowerCase:As,Symbol:Ls,SymbolHasInstance:Ds}=XH();tp.exports=BH;BH.WritableState=QD;var{EventEmitter:fs}=B("events"),jD=V0().Stream,{Buffer:B0}=B("buffer"),F0=hL(),{addAbortSignal:Es}=RD(),{getHighWaterMark:Is,getDefaultHighWaterMark:Ps}=OD(),{ERR_INVALID_ARG_TYPE:Ts,ERR_METHOD_NOT_IMPLEMENTED:Us,ERR_MULTIPLE_CALLBACK:Ip,ERR_STREAM_CANNOT_PIPE:Ms,ERR_STREAM_DESTROYED:JD,ERR_STREAM_ALREADY_FINISHED:ts,ERR_STREAM_NULL_VALUES:_s,ERR_STREAM_WRITE_AFTER_END:ps,ERR_UNKNOWN_ENCODING:Pp}=qH().codes,{errorOrDestroy:LD}=F0;Ep(BH.prototype,jD.prototype);Ep(BH,jD);function YI(){}var DD=Ls("kOnFinished");function QD(H,$,A){if(typeof A!=="boolean")A=$ instanceof UA();if(this.objectMode=!!(H&&H.objectMode),A)this.objectMode=this.objectMode||!!(H&&H.writableObjectMode);this.highWaterMark=H?Is(this,H,"writableHighWaterMark",A):Ps(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let L=!!(H&&H.decodeStrings===!1);this.decodeStrings=!L,this.defaultEncoding=H&&H.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=Ws.bind(void 0,$),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,o0(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!H||H.emitClose!==!1,this.autoDestroy=!H||H.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[DD]=[]}function o0(H){H.buffered=[],H.bufferedIndex=0,H.allBuffers=!0,H.allNoop=!0}QD.prototype.getBuffer=function(){return Lp(this.buffered,this.bufferedIndex)};fp(QD.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function BH(H){let $=this instanceof UA();if(!$&&!Dp(BH,this))return new BH(H);if(this._writableState=new QD(H,this,$),H){if(typeof H.write==="function")this._write=H.write;if(typeof H.writev==="function")this._writev=H.writev;if(typeof H.destroy==="function")this._destroy=H.destroy;if(typeof H.final==="function")this._final=H.final;if(typeof H.construct==="function")this._construct=H.construct;if(H.signal)Es(H.signal,this)}jD.call(this,H),F0.construct(this,()=>{let A=this._writableState;if(!A.writing)ZI(this,A);zI(this,A)})}fp(BH,Ds,{__proto__:null,value:function(H){if(Dp(this,H))return!0;if(this!==BH)return!1;return H&&H._writableState instanceof QD}});BH.prototype.pipe=function(){LD(this,new Ms)};function Tp(H,$,A,L){let D=H._writableState;if(typeof A==="function")L=A,A=D.defaultEncoding;else{if(!A)A=D.defaultEncoding;else if(A!=="buffer"&&!B0.isEncoding(A))throw new Pp(A);if(typeof L!=="function")L=YI}if($===null)throw new _s;else if(!D.objectMode)if(typeof $==="string"){if(D.decodeStrings!==!1)$=B0.from($,A),A="buffer"}else if($ instanceof B0)A="buffer";else if(jD._isUint8Array($))$=jD._uint8ArrayToBuffer($),A="buffer";else throw new Ts("chunk",["string","Buffer","Uint8Array"],$);let f;if(D.ending)f=new ps;else if(D.destroyed)f=new JD("write");if(f)return SL.nextTick(L,f),LD(H,f,!0),f;return D.pendingcb++,Vs(H,D,$,A,L)}BH.prototype.write=function(H,$,A){return Tp(this,H,$,A)===!0};BH.prototype.cork=function(){this._writableState.corked++};BH.prototype.uncork=function(){let H=this._writableState;if(H.corked){if(H.corked--,!H.writing)ZI(this,H)}};BH.prototype.setDefaultEncoding=function($){if(typeof $==="string")$=As($);if(!B0.isEncoding($))throw new Pp($);return this._writableState.defaultEncoding=$,this};function Vs(H,$,A,L,D){let f=$.objectMode?1:A.length;$.length+=f;let E=$.length<$.highWaterMark;if(!E)$.needDrain=!0;if($.writing||$.corked||$.errored||!$.constructed){if($.buffered.push({chunk:A,encoding:L,callback:D}),$.allBuffers&&L!=="buffer")$.allBuffers=!1;if($.allNoop&&D!==YI)$.allNoop=!1}else $.writelen=f,$.writecb=D,$.writing=!0,$.sync=!0,H._write(A,L,$.onwrite),$.sync=!1;return E&&!$.errored&&!$.destroyed}function $p(H,$,A,L,D,f,E){if($.writelen=L,$.writecb=E,$.writing=!0,$.sync=!0,$.destroyed)$.onwrite(new JD("write"));else if(A)H._writev(D,$.onwrite);else H._write(D,f,$.onwrite);$.sync=!1}function Ap(H,$,A,L){--$.pendingcb,L(A),qI($),LD(H,A)}function Ws(H,$){let A=H._writableState,L=A.sync,D=A.writecb;if(typeof D!=="function"){LD(H,new Ip);return}if(A.writing=!1,A.writecb=null,A.length-=A.writelen,A.writelen=0,$){if($.stack,!A.errored)A.errored=$;if(H._readableState&&!H._readableState.errored)H._readableState.errored=$;if(L)SL.nextTick(Ap,H,A,$,D);else Ap(H,A,$,D)}else{if(A.buffered.length>A.bufferedIndex)ZI(H,A);if(L)if(A.afterWriteTickInfo!==null&&A.afterWriteTickInfo.cb===D)A.afterWriteTickInfo.count++;else A.afterWriteTickInfo={count:1,cb:D,stream:H,state:A},SL.nextTick(us,A.afterWriteTickInfo);else Up(H,A,1,D)}}function us({stream:H,state:$,count:A,cb:L}){return $.afterWriteTickInfo=null,Up(H,$,A,L)}function Up(H,$,A,L){if(!$.ending&&!H.destroyed&&$.length===0&&$.needDrain)$.needDrain=!1,H.emit("drain");while(A-- >0)$.pendingcb--,L();if($.destroyed)qI($);zI(H,$)}function qI(H){if(H.writing)return;for(let D=H.bufferedIndex;D<H.buffered.length;++D){var $;let{chunk:f,callback:E}=H.buffered[D],I=H.objectMode?1:f.length;H.length-=I,E(($=H.errored)!==null&&$!==void 0?$:new JD("write"))}let A=H[DD].splice(0);for(let D=0;D<A.length;D++){var L;A[D]((L=H.errored)!==null&&L!==void 0?L:new JD("end"))}o0(H)}function ZI(H,$){if($.corked||$.bufferProcessing||$.destroyed||!$.constructed)return;let{buffered:A,bufferedIndex:L,objectMode:D}=$,f=A.length-L;if(!f)return;let E=L;if($.bufferProcessing=!0,f>1&&H._writev){$.pendingcb-=f-1;let I=$.allNoop?YI:(T)=>{for(let U=E;U<A.length;++U)A[U].callback(T)},P=$.allNoop&&E===0?A:Lp(A,E);P.allBuffers=$.allBuffers,$p(H,$,!0,$.length,P,"",I),o0($)}else{do{let{chunk:I,encoding:P,callback:T}=A[E];A[E++]=null;let U=D?1:I.length;$p(H,$,!1,U,I,P,T)}while(E<A.length&&!$.writing);if(E===A.length)o0($);else if(E>256)A.splice(0,E),$.bufferedIndex=0;else $.bufferedIndex=E}$.bufferProcessing=!1}BH.prototype._write=function(H,$,A){if(this._writev)this._writev([{chunk:H,encoding:$}],A);else throw new Us("_write()")};BH.prototype._writev=null;BH.prototype.end=function(H,$,A){let L=this._writableState;if(typeof H==="function")A=H,H=null,$=null;else if(typeof $==="function")A=$,$=null;let D;if(H!==null&&H!==void 0){let f=Tp(this,H,$);if(f instanceof Hs)D=f}if(L.corked)L.corked=1,this.uncork();if(D);else if(!L.errored&&!L.ending)L.ending=!0,zI(this,L,!0),L.ended=!0;else if(L.finished)D=new ts("end");else if(L.destroyed)D=new JD("end");if(typeof A==="function")if(D||L.finished)SL.nextTick(A,D);else L[DD].push(A);return this};function n0(H){return H.ending&&!H.destroyed&&H.constructed&&H.length===0&&!H.errored&&H.buffered.length===0&&!H.finished&&!H.writing&&!H.errorEmitted&&!H.closeEmitted}function xs(H,$){let A=!1;function L(D){if(A){LD(H,D!==null&&D!==void 0?D:Ip());return}if(A=!0,$.pendingcb--,D){let f=$[DD].splice(0);for(let E=0;E<f.length;E++)f[E](D);LD(H,D,$.sync)}else if(n0($))$.prefinished=!0,H.emit("prefinish"),$.pendingcb++,SL.nextTick(vI,H,$)}$.sync=!0,$.pendingcb++;try{H._final(L)}catch(D){L(D)}$.sync=!1}function hs(H,$){if(!$.prefinished&&!$.finalCalled)if(typeof H._final==="function"&&!$.destroyed)$.finalCalled=!0,xs(H,$);else $.prefinished=!0,H.emit("prefinish")}function zI(H,$,A){if(n0($)){if(hs(H,$),$.pendingcb===0){if(A)$.pendingcb++,SL.nextTick((L,D)=>{if(n0(D))vI(L,D);else D.pendingcb--},H,$);else if(n0($))$.pendingcb++,vI(H,$)}}}function vI(H,$){$.pendingcb--,$.finished=!0;let A=$[DD].splice(0);for(let L=0;L<A.length;L++)A[L]();if(H.emit("finish"),$.autoDestroy){let L=H._readableState;if(!L||L.autoDestroy&&(L.endEmitted||L.readable===!1))H.destroy()}}$s(BH.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(H){if(this._writableState)this._writableState.destroyed=H}},writable:{__proto__:null,get(){let H=this._writableState;return!!H&&H.writable!==!1&&!H.destroyed&&!H.errored&&!H.ending&&!H.ended},set(H){if(this._writableState)this._writableState.writable=!!H}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let H=this._writableState;if(!H)return!1;return!H.destroyed&&!H.ending&&H.needDrain}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var cs=F0.destroy;BH.prototype.destroy=function(H,$){let A=this._writableState;if(!A.destroyed&&(A.bufferedIndex<A.buffered.length||A[DD].length))SL.nextTick(qI,A);return cs.call(this,H,$),this};BH.prototype._undestroy=F0.undestroy;BH.prototype._destroy=function(H,$){$(H)};BH.prototype[fs.captureRejectionSymbol]=function(H){this.destroy(H)};var gI;function Mp(){if(gI===void 0)gI={};return gI}BH.fromWeb=function(H,$){return Mp().newStreamWritableFromWritableStream(H,$)};BH.toWeb=function(H){return Mp().newWritableStreamFromStreamWritable(H)}});var Fp=p((wk,op)=>{var HP=qA(),Xs=B("buffer"),{isReadable:Ss,isWritable:rs,isIterable:_p,isNodeStream:Bs,isReadableNodeStream:pp,isWritableNodeStream:Vp,isDuplexNodeStream:ns,isReadableStream:Wp,isWritableStream:up}=IA(),xp=dA(),{AbortError:Bp,codes:{ERR_INVALID_ARG_TYPE:os,ERR_INVALID_RETURN_VALUE:hp}}=qH(),{destroyer:ED}=hL(),Fs=UA(),np=eD(),ss=s0(),{createDeferredPromise:cp}=L$(),Xp=RI(),Sp=globalThis.Blob||Xs.Blob,Cs=typeof Sp<"u"?function($){return $ instanceof Sp}:function($){return!1},is=globalThis.AbortController||B("abort-controller").AbortController,{FunctionPrototypeCall:rp}=XH();class rL extends Fs{constructor(H){super(H);if((H===null||H===void 0?void 0:H.readable)===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if((H===null||H===void 0?void 0:H.writable)===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}}op.exports=function H($,A){if(ns($))return $;if(pp($))return fD({readable:$});if(Vp($))return fD({writable:$});if(Bs($))return fD({writable:!1,readable:!1});if(Wp($))return fD({readable:np.fromWeb($)});if(up($))return fD({writable:ss.fromWeb($)});if(typeof $==="function"){let{value:D,write:f,final:E,destroy:I}=Gs($);if(_p(D))return Xp(rL,D,{objectMode:!0,write:f,final:E,destroy:I});let P=D===null||D===void 0?void 0:D.then;if(typeof P==="function"){let T,U=rp(P,D,(M)=>{if(M!=null)throw new hp("nully","body",M)},(M)=>{ED(T,M)});return T=new rL({objectMode:!0,readable:!1,write:f,final(M){E(async()=>{try{await U,HP.nextTick(M,null)}catch(t){HP.nextTick(M,t)}})},destroy:I})}throw new hp("Iterable, AsyncIterable or AsyncFunction",A,D)}if(Cs($))return H($.arrayBuffer());if(_p($))return Xp(rL,$,{objectMode:!0,writable:!1});if(Wp($===null||$===void 0?void 0:$.readable)&&up($===null||$===void 0?void 0:$.writable))return rL.fromWeb($);if(typeof($===null||$===void 0?void 0:$.writable)==="object"||typeof($===null||$===void 0?void 0:$.readable)==="object"){let D=$!==null&&$!==void 0&&$.readable?pp($===null||$===void 0?void 0:$.readable)?$===null||$===void 0?void 0:$.readable:H($.readable):void 0,f=$!==null&&$!==void 0&&$.writable?Vp($===null||$===void 0?void 0:$.writable)?$===null||$===void 0?void 0:$.writable:H($.writable):void 0;return fD({readable:D,writable:f})}let L=$===null||$===void 0?void 0:$.then;if(typeof L==="function"){let D;return rp(L,$,(f)=>{if(f!=null)D.push(f);D.push(null)},(f)=>{ED(D,f)}),D=new rL({objectMode:!0,writable:!1,read(){}})}throw new os(A,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],$)};function Gs(H){let{promise:$,resolve:A}=cp(),L=new is,D=L.signal;return{value:H(async function*(){while(!0){let E=$;$=null;let{chunk:I,done:P,cb:T}=await E;if(HP.nextTick(T),P)return;if(D.aborted)throw new Bp(void 0,{cause:D.reason});({promise:$,resolve:A}=cp()),yield I}}(),{signal:D}),write(E,I,P){let T=A;A=null,T({chunk:E,done:!1,cb:P})},final(E){let I=A;A=null,I({done:!0,cb:E})},destroy(E,I){L.abort(),I(E)}}}function fD(H){let $=H.readable&&typeof H.readable.read!=="function"?np.wrap(H.readable):H.readable,A=H.writable,L=!!Ss($),D=!!rs(A),f,E,I,P,T;function U(M){let t=P;if(P=null,t)t(M);else if(M)T.destroy(M)}if(T=new rL({readableObjectMode:!!($!==null&&$!==void 0&&$.readableObjectMode),writableObjectMode:!!(A!==null&&A!==void 0&&A.writableObjectMode),readable:L,writable:D}),D)xp(A,(M)=>{if(D=!1,M)ED($,M);U(M)}),T._write=function(M,t,_){if(A.write(M,t))_();else f=_},T._final=function(M){A.end(),E=M},A.on("drain",function(){if(f){let M=f;f=null,M()}}),A.on("finish",function(){if(E){let M=E;E=null,M()}});if(L)xp($,(M)=>{if(L=!1,M)ED($,M);U(M)}),$.on("readable",function(){if(I){let M=I;I=null,M()}}),$.on("end",function(){T.push(null)}),T._read=function(){while(!0){let M=$.read();if(M===null){I=T._read;return}if(!T.push(M))return}};return T._destroy=function(M,t){if(!M&&P!==null)M=new Bp;if(I=null,f=null,E=null,P===null)t(M);else P=t,ED(A,M),ED($,M)},T}});var UA=p((ek,ip)=>{var{ObjectDefineProperties:ds,ObjectGetOwnPropertyDescriptor:aA,ObjectKeys:as,ObjectSetPrototypeOf:sp}=XH();ip.exports=J$;var LP=eD(),F$=s0();sp(J$.prototype,LP.prototype);sp(J$,LP);{let H=as(F$.prototype);for(let $=0;$<H.length;$++){let A=H[$];if(!J$.prototype[A])J$.prototype[A]=F$.prototype[A]}}function J$(H){if(!(this instanceof J$))return new J$(H);if(LP.call(this,H),F$.call(this,H),H){if(this.allowHalfOpen=H.allowHalfOpen!==!1,H.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(H.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}ds(J$.prototype,{writable:{__proto__:null,...aA(F$.prototype,"writable")},writableHighWaterMark:{__proto__:null,...aA(F$.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...aA(F$.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...aA(F$.prototype,"writableBuffer")},writableLength:{__proto__:null,...aA(F$.prototype,"writableLength")},writableFinished:{__proto__:null,...aA(F$.prototype,"writableFinished")},writableCorked:{__proto__:null,...aA(F$.prototype,"writableCorked")},writableEnded:{__proto__:null,...aA(F$.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...aA(F$.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(H){if(this._readableState&&this._writableState)this._readableState.destroyed=H,this._writableState.destroyed=H}}});var $P;function Cp(){if($P===void 0)$P={};return $P}J$.fromWeb=function(H,$){return Cp().newStreamDuplexFromReadableWritablePair(H,$)};J$.toWeb=function(H){return Cp().newReadableWritablePairFromDuplex(H)};var AP;J$.from=function(H){if(!AP)AP=Fp();return AP(H,"body")}});var EP=p((jk,dp)=>{var{ObjectSetPrototypeOf:Gp,Symbol:ls}=XH();dp.exports=lA;var{ERR_METHOD_NOT_IMPLEMENTED:ys}=qH().codes,fP=UA(),{getHighWaterMark:bs}=OD();Gp(lA.prototype,fP.prototype);Gp(lA,fP);var KD=ls("kCallback");function lA(H){if(!(this instanceof lA))return new lA(H);let $=H?bs(this,H,"readableHighWaterMark",!0):null;if($===0)H={...H,highWaterMark:null,readableHighWaterMark:$,writableHighWaterMark:H.writableHighWaterMark||0};if(fP.call(this,H),this._readableState.sync=!1,this[KD]=null,H){if(typeof H.transform==="function")this._transform=H.transform;if(typeof H.flush==="function")this._flush=H.flush}this.on("prefinish",Ns)}function DP(H){if(typeof this._flush==="function"&&!this.destroyed)this._flush(($,A)=>{if($){if(H)H($);else this.destroy($);return}if(A!=null)this.push(A);if(this.push(null),H)H()});else if(this.push(null),H)H()}function Ns(){if(this._final!==DP)DP.call(this)}lA.prototype._final=DP;lA.prototype._transform=function(H,$,A){throw new ys("_transform()")};lA.prototype._write=function(H,$,A){let L=this._readableState,D=this._writableState,f=L.length;this._transform(H,$,(E,I)=>{if(E){A(E);return}if(I!=null)this.push(I);if(D.ended||f===L.length||L.length<L.highWaterMark)A();else this[KD]=A})};lA.prototype._read=function(){if(this[KD]){let H=this[KD];this[KD]=null,H()}}});var PP=p((Jk,lp)=>{var{ObjectSetPrototypeOf:ap}=XH();lp.exports=ID;var IP=EP();ap(ID.prototype,IP.prototype);ap(ID,IP);function ID(H){if(!(this instanceof ID))return new ID(H);IP.call(this,H)}ID.prototype._transform=function(H,$,A){A(null,H)}});var d0=p((Qk,Rp)=>{var gD=qA(),{ArrayIsArray:ks,Promise:Rs,SymbolAsyncIterator:Os,SymbolDispose:ms}=XH(),G0=dA(),{once:ws}=L$(),es=hL(),yp=UA(),{aggregateTwoErrors:js,codes:{ERR_INVALID_ARG_TYPE:uP,ERR_INVALID_RETURN_VALUE:TP,ERR_MISSING_ARGS:Js,ERR_STREAM_DESTROYED:Qs,ERR_STREAM_PREMATURE_CLOSE:Ks},AbortError:gs}=qH(),{validateFunction:vs,validateAbortSignal:Ys}=ZL(),{isIterable:BL,isReadable:UP,isReadableNodeStream:i0,isNodeStream:bp,isTransformStream:PD,isWebStream:qs,isReadableStream:MP,isReadableFinished:Zs}=IA(),zs=globalThis.AbortController||B("abort-controller").AbortController,tP,_P,pP;function Np(H,$,A){let L=!1;H.on("close",()=>{L=!0});let D=G0(H,{readable:$,writable:A},(f)=>{L=!f});return{destroy:(f)=>{if(L)return;L=!0,es.destroyer(H,f||new Qs("pipe"))},cleanup:D}}function H2(H){return vs(H[H.length-1],"streams[stream.length - 1]"),H.pop()}function VP(H){if(BL(H))return H;else if(i0(H))return $2(H);throw new uP("val",["Readable","Iterable","AsyncIterable"],H)}async function*$2(H){if(!_P)_P=eD();yield*_P.prototype[Os].call(H)}async function C0(H,$,A,{end:L}){let D,f=null,E=(T)=>{if(T)D=T;if(f){let U=f;f=null,U()}},I=()=>new Rs((T,U)=>{if(D)U(D);else f=()=>{if(D)U(D);else T()}});$.on("drain",E);let P=G0($,{readable:!1},E);try{if($.writableNeedDrain)await I();for await(let T of H)if(!$.write(T))await I();if(L)$.end(),await I();A()}catch(T){A(D!==T?js(D,T):T)}finally{P(),$.off("drain",E)}}async function WP(H,$,A,{end:L}){if(PD($))$=$.writable;let D=$.getWriter();try{for await(let f of H)await D.ready,D.write(f).catch(()=>{});if(await D.ready,L)await D.close();A()}catch(f){try{await D.abort(f),A(f)}catch(E){A(E)}}}function A2(...H){return kp(H,ws(H2(H)))}function kp(H,$,A){if(H.length===1&&ks(H[0]))H=H[0];if(H.length<2)throw new Js("streams");let L=new zs,D=L.signal,f=A===null||A===void 0?void 0:A.signal,E=[];Ys(f,"options.signal");function I(){x(new gs)}pP=pP||L$().addAbortListener;let P;if(f)P=pP(f,I);let T,U,M=[],t=0;function _(r){x(r,--t===0)}function x(r,F){var N;if(r&&(!T||T.code==="ERR_STREAM_PREMATURE_CLOSE"))T=r;if(!T&&!F)return;while(M.length)M.shift()(T);if((N=P)===null||N===void 0||N[ms](),L.abort(),F){if(!T)E.forEach((y)=>y());gD.nextTick($,T,U)}}let V;for(let r=0;r<H.length;r++){let F=H[r],N=r<H.length-1,y=r>0,k=N||(A===null||A===void 0?void 0:A.end)!==!1,J=r===H.length-1;if(bp(F)){let e=function(WH){if(WH&&WH.name!=="AbortError"&&WH.code!=="ERR_STREAM_PREMATURE_CLOSE")_(WH)};var c=e;if(k){let{destroy:WH,cleanup:vH}=Np(F,N,y);if(M.push(WH),UP(F)&&J)E.push(vH)}if(F.on("error",e),UP(F)&&J)E.push(()=>{F.removeListener("error",e)})}if(r===0)if(typeof F==="function"){if(V=F({signal:D}),!BL(V))throw new TP("Iterable, AsyncIterable or Stream","source",V)}else if(BL(F)||i0(F)||PD(F))V=F;else V=yp.from(F);else if(typeof F==="function"){if(PD(V)){var h;V=VP((h=V)===null||h===void 0?void 0:h.readable)}else V=VP(V);if(V=F(V,{signal:D}),N){if(!BL(V,!0))throw new TP("AsyncIterable",`transform[${r-1}]`,V)}else{var W;if(!tP)tP=PP();let e=new tP({objectMode:!0}),WH=(W=V)===null||W===void 0?void 0:W.then;if(typeof WH==="function")t++,WH.call(V,(rH)=>{if(U=rH,rH!=null)e.write(rH);if(k)e.end();gD.nextTick(_)},(rH)=>{e.destroy(rH),gD.nextTick(_,rH)});else if(BL(V,!0))t++,C0(V,e,_,{end:k});else if(MP(V)||PD(V)){let rH=V.readable||V;t++,C0(rH,e,_,{end:k})}else throw new TP("AsyncIterable or Promise","destination",V);V=e;let{destroy:vH,cleanup:sH}=Np(V,!1,!0);if(M.push(vH),J)E.push(sH)}}else if(bp(F)){if(i0(V)){t+=2;let e=L2(V,F,_,{end:k});if(UP(F)&&J)E.push(e)}else if(PD(V)||MP(V)){let e=V.readable||V;t++,C0(e,F,_,{end:k})}else if(BL(V))t++,C0(V,F,_,{end:k});else throw new uP("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],V);V=F}else if(qs(F)){if(i0(V))t++,WP(VP(V),F,_,{end:k});else if(MP(V)||BL(V))t++,WP(V,F,_,{end:k});else if(PD(V))t++,WP(V.readable,F,_,{end:k});else throw new uP("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],V);V=F}else V=yp.from(F)}if(D!==null&&D!==void 0&&D.aborted||f!==null&&f!==void 0&&f.aborted)gD.nextTick(I);return V}function L2(H,$,A,{end:L}){let D=!1;if($.on("close",()=>{if(!D)A(new Ks)}),H.pipe($,{end:!1}),L){let E=function(){D=!0,$.end()};var f=E;if(Zs(H))gD.nextTick(E);else H.once("end",E)}else A();return G0(H,{readable:!0,writable:!1},(E)=>{let I=H._readableState;if(E&&E.code==="ERR_STREAM_PREMATURE_CLOSE"&&I&&I.ended&&!I.errored&&!I.errorEmitted)H.once("end",A).once("error",A);else A(E)}),G0($,{readable:!1,writable:!0},A)}Rp.exports={pipelineImpl:kp,pipeline:A2}});var hP=p((Kk,Jp)=>{var{pipeline:D2}=d0(),a0=UA(),{destroyer:f2}=hL(),{isNodeStream:l0,isReadable:Op,isWritable:mp,isWebStream:xP,isTransformStream:nL,isWritableStream:wp,isReadableStream:ep}=IA(),{AbortError:E2,codes:{ERR_INVALID_ARG_VALUE:jp,ERR_MISSING_ARGS:I2}}=qH(),P2=dA();Jp.exports=function(...$){if($.length===0)throw new I2("streams");if($.length===1)return a0.from($[0]);let A=[...$];if(typeof $[0]==="function")$[0]=a0.from($[0]);if(typeof $[$.length-1]==="function"){let _=$.length-1;$[_]=a0.from($[_])}for(let _=0;_<$.length;++_){if(!l0($[_])&&!xP($[_]))continue;if(_<$.length-1&&!(Op($[_])||ep($[_])||nL($[_])))throw new jp(`streams[${_}]`,A[_],"must be readable");if(_>0&&!(mp($[_])||wp($[_])||nL($[_])))throw new jp(`streams[${_}]`,A[_],"must be writable")}let L,D,f,E,I;function P(_){let x=E;if(E=null,x)x(_);else if(_)I.destroy(_);else if(!t&&!M)I.destroy()}let T=$[0],U=D2($,P),M=!!(mp(T)||wp(T)||nL(T)),t=!!(Op(U)||ep(U)||nL(U));if(I=new a0({writableObjectMode:!!(T!==null&&T!==void 0&&T.writableObjectMode),readableObjectMode:!!(U!==null&&U!==void 0&&U.readableObjectMode),writable:M,readable:t}),M){if(l0(T))I._write=function(x,V,h){if(T.write(x,V))h();else L=h},I._final=function(x){T.end(),D=x},T.on("drain",function(){if(L){let x=L;L=null,x()}});else if(xP(T)){let V=(nL(T)?T.writable:T).getWriter();I._write=async function(h,W,c){try{await V.ready,V.write(h).catch(()=>{}),c()}catch(r){c(r)}},I._final=async function(h){try{await V.ready,V.close().catch(()=>{}),D=h}catch(W){h(W)}}}let _=nL(U)?U.readable:U;P2(_,()=>{if(D){let x=D;D=null,x()}})}if(t){if(l0(U))U.on("readable",function(){if(f){let _=f;f=null,_()}}),U.on("end",function(){I.push(null)}),I._read=function(){while(!0){let _=U.read();if(_===null){f=I._read;return}if(!I.push(_))return}};else if(xP(U)){let x=(nL(U)?U.readable:U).getReader();I._read=async function(){while(!0)try{let{value:V,done:h}=await x.read();if(!I.push(V))return;if(h){I.push(null);return}}catch{return}}}}return I._destroy=function(_,x){if(!_&&E!==null)_=new E2;if(f=null,L=null,D=null,E===null)x(_);else if(E=x,l0(U))f2(U,_)},I}});var AV=p((b2,XP)=>{var T2=globalThis.AbortController||B("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:U2,ERR_INVALID_ARG_TYPE:vD,ERR_MISSING_ARGS:M2,ERR_OUT_OF_RANGE:t2},AbortError:MA}=qH(),{validateAbortSignal:oL,validateInteger:Qp,validateObject:FL}=ZL(),_2=XH().Symbol("kWeak"),p2=XH().Symbol("kResistStopPropagation"),{finished:V2}=dA(),W2=hP(),{addAbortSignalNoValidate:u2}=RD(),{isWritable:x2,isNodeStream:h2}=IA(),{deprecate:c2}=L$(),{ArrayPrototypePush:X2,Boolean:S2,MathFloor:Kp,Number:r2,NumberIsNaN:B2,Promise:gp,PromiseReject:vp,PromiseResolve:n2,PromisePrototypeThen:Yp,Symbol:Zp}=XH(),y0=Zp("kEmpty"),qp=Zp("kEof");function o2(H,$){if($!=null)FL($,"options");if(($===null||$===void 0?void 0:$.signal)!=null)oL($.signal,"options.signal");if(h2(H)&&!x2(H))throw new U2("stream",H,"must be writable");let A=W2(this,H);if($!==null&&$!==void 0&&$.signal)u2($.signal,A);return A}function b0(H,$){if(typeof H!=="function")throw new vD("fn",["Function","AsyncFunction"],H);if($!=null)FL($,"options");if(($===null||$===void 0?void 0:$.signal)!=null)oL($.signal,"options.signal");let A=1;if(($===null||$===void 0?void 0:$.concurrency)!=null)A=Kp($.concurrency);let L=A-1;if(($===null||$===void 0?void 0:$.highWaterMark)!=null)L=Kp($.highWaterMark);return Qp(A,"options.concurrency",1),Qp(L,"options.highWaterMark",0),L+=A,async function*(){let f=L$().AbortSignalAny([$===null||$===void 0?void 0:$.signal].filter(S2)),E=this,I=[],P={signal:f},T,U,M=!1,t=0;function _(){M=!0,x()}function x(){t-=1,V()}function V(){if(U&&!M&&t<A&&I.length<L)U(),U=null}async function h(){try{for await(let W of E){if(M)return;if(f.aborted)throw new MA;try{if(W=H(W,P),W===y0)continue;W=n2(W)}catch(c){W=vp(c)}if(t+=1,Yp(W,x,_),I.push(W),T)T(),T=null;if(!M&&(I.length>=L||t>=A))await new gp((c)=>{U=c})}I.push(qp)}catch(W){let c=vp(W);Yp(c,x,_),I.push(c)}finally{if(M=!0,T)T(),T=null}}h();try{while(!0){while(I.length>0){let W=await I[0];if(W===qp)return;if(f.aborted)throw new MA;if(W!==y0)yield W;I.shift(),V()}await new gp((W)=>{T=W})}}finally{if(M=!0,U)U(),U=null}}.call(this)}function F2(H=void 0){if(H!=null)FL(H,"options");if((H===null||H===void 0?void 0:H.signal)!=null)oL(H.signal,"options.signal");return async function*(){let A=0;for await(let D of this){var L;if(H!==null&&H!==void 0&&(L=H.signal)!==null&&L!==void 0&&L.aborted)throw new MA({cause:H.signal.reason});yield[A++,D]}}.call(this)}async function zp(H,$=void 0){for await(let A of cP.call(this,H,$))return!0;return!1}async function s2(H,$=void 0){if(typeof H!=="function")throw new vD("fn",["Function","AsyncFunction"],H);return!await zp.call(this,async(...A)=>{return!await H(...A)},$)}async function C2(H,$){for await(let A of cP.call(this,H,$))return A;return}async function i2(H,$){if(typeof H!=="function")throw new vD("fn",["Function","AsyncFunction"],H);async function A(L,D){return await H(L,D),y0}for await(let L of b0.call(this,A,$));}function cP(H,$){if(typeof H!=="function")throw new vD("fn",["Function","AsyncFunction"],H);async function A(L,D){if(await H(L,D))return L;return y0}return b0.call(this,A,$)}class HV extends M2{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function G2(H,$,A){var L;if(typeof H!=="function")throw new vD("reducer",["Function","AsyncFunction"],H);if(A!=null)FL(A,"options");if((A===null||A===void 0?void 0:A.signal)!=null)oL(A.signal,"options.signal");let D=arguments.length>1;if(A!==null&&A!==void 0&&(L=A.signal)!==null&&L!==void 0&&L.aborted){let T=new MA(void 0,{cause:A.signal.reason});throw this.once("error",()=>{}),await V2(this.destroy(T)),T}let f=new T2,E=f.signal;if(A!==null&&A!==void 0&&A.signal){let T={once:!0,[_2]:this,[p2]:!0};A.signal.addEventListener("abort",()=>f.abort(),T)}let I=!1;try{for await(let T of this){var P;if(I=!0,A!==null&&A!==void 0&&(P=A.signal)!==null&&P!==void 0&&P.aborted)throw new MA;if(!D)$=T,D=!0;else $=await H($,T,{signal:E})}if(!I&&!D)throw new HV}finally{f.abort()}return $}async function d2(H){if(H!=null)FL(H,"options");if((H===null||H===void 0?void 0:H.signal)!=null)oL(H.signal,"options.signal");let $=[];for await(let L of this){var A;if(H!==null&&H!==void 0&&(A=H.signal)!==null&&A!==void 0&&A.aborted)throw new MA(void 0,{cause:H.signal.reason});X2($,L)}return $}function a2(H,$){let A=b0.call(this,H,$);return async function*(){for await(let D of A)yield*D}.call(this)}function $V(H){if(H=r2(H),B2(H))return 0;if(H<0)throw new t2("number",">= 0",H);return H}function l2(H,$=void 0){if($!=null)FL($,"options");if(($===null||$===void 0?void 0:$.signal)!=null)oL($.signal,"options.signal");return H=$V(H),async function*(){var L;if($!==null&&$!==void 0&&(L=$.signal)!==null&&L!==void 0&&L.aborted)throw new MA;for await(let f of this){var D;if($!==null&&$!==void 0&&(D=$.signal)!==null&&D!==void 0&&D.aborted)throw new MA;if(H--<=0)yield f}}.call(this)}function y2(H,$=void 0){if($!=null)FL($,"options");if(($===null||$===void 0?void 0:$.signal)!=null)oL($.signal,"options.signal");return H=$V(H),async function*(){var L;if($!==null&&$!==void 0&&(L=$.signal)!==null&&L!==void 0&&L.aborted)throw new MA;for await(let f of this){var D;if($!==null&&$!==void 0&&(D=$.signal)!==null&&D!==void 0&&D.aborted)throw new MA;if(H-- >0)yield f;if(H<=0)return}}.call(this)}b2.streamReturningOperators={asIndexedPairs:c2(F2,"readable.asIndexedPairs will be removed in a future version."),drop:l2,filter:cP,flatMap:a2,map:b0,take:y2,compose:o2};b2.promiseReturningOperators={every:s2,forEach:i2,reduce:G2,toArray:d2,some:zp,find:C2}});var SP=p((gk,LV)=>{var{ArrayPrototypePop:R2,Promise:O2}=XH(),{isIterable:m2,isNodeStream:w2,isWebStream:e2}=IA(),{pipelineImpl:j2}=d0(),{finished:J2}=dA();rP();function Q2(...H){return new O2(($,A)=>{let L,D,f=H[H.length-1];if(f&&typeof f==="object"&&!w2(f)&&!m2(f)&&!e2(f)){let E=R2(H);L=E.signal,D=E.end}j2(H,(E,I)=>{if(E)A(E);else $(I)},{signal:L,end:D})})}LV.exports={finished:J2,pipeline:Q2}});var rP=p((vk,tV)=>{var{Buffer:K2}=B("buffer"),{ObjectDefineProperty:yA,ObjectKeys:EV,ReflectApply:IV}=XH(),{promisify:{custom:PV}}=L$(),{streamReturningOperators:DV,promiseReturningOperators:fV}=AV(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:TV}}=qH(),g2=hP(),{setDefaultHighWaterMark:v2,getDefaultHighWaterMark:Y2}=OD(),{pipeline:UV}=d0(),{destroyer:q2}=hL(),MV=dA(),BP=SP(),YD=IA(),cH=tV.exports=V0().Stream;cH.isDestroyed=YD.isDestroyed;cH.isDisturbed=YD.isDisturbed;cH.isErrored=YD.isErrored;cH.isReadable=YD.isReadable;cH.isWritable=YD.isWritable;cH.Readable=eD();for(let H of EV(DV)){let A=function(...L){if(new.target)throw TV();return cH.Readable.from(IV($,this,L))},$=DV[H];yA(A,"name",{__proto__:null,value:$.name}),yA(A,"length",{__proto__:null,value:$.length}),yA(cH.Readable.prototype,H,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}for(let H of EV(fV)){let A=function(...L){if(new.target)throw TV();return IV($,this,L)},$=fV[H];yA(A,"name",{__proto__:null,value:$.name}),yA(A,"length",{__proto__:null,value:$.length}),yA(cH.Readable.prototype,H,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}cH.Writable=s0();cH.Duplex=UA();cH.Transform=EP();cH.PassThrough=PP();cH.pipeline=UV;var{addAbortSignal:Z2}=RD();cH.addAbortSignal=Z2;cH.finished=MV;cH.destroy=q2;cH.compose=g2;cH.setDefaultHighWaterMark=v2;cH.getDefaultHighWaterMark=Y2;yA(cH,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return BP}});yA(UV,PV,{__proto__:null,enumerable:!0,get(){return BP.pipeline}});yA(MV,PV,{__proto__:null,enumerable:!0,get(){return BP.finished}});cH.Stream=cH;cH._isUint8Array=function($){return $ instanceof Uint8Array};cH._uint8ArrayToBuffer=function($){return K2.from($.buffer,$.byteOffset,$.byteLength)}});var HL=p((Yk,$H)=>{var yH=B("stream");if(yH&&process.env.READABLE_STREAM==="disable"){let H=yH.promises;$H.exports._uint8ArrayToBuffer=yH._uint8ArrayToBuffer,$H.exports._isUint8Array=yH._isUint8Array,$H.exports.isDisturbed=yH.isDisturbed,$H.exports.isErrored=yH.isErrored,$H.exports.isReadable=yH.isReadable,$H.exports.Readable=yH.Readable,$H.exports.Writable=yH.Writable,$H.exports.Duplex=yH.Duplex,$H.exports.Transform=yH.Transform,$H.exports.PassThrough=yH.PassThrough,$H.exports.addAbortSignal=yH.addAbortSignal,$H.exports.finished=yH.finished,$H.exports.destroy=yH.destroy,$H.exports.pipeline=yH.pipeline,$H.exports.compose=yH.compose,Object.defineProperty(yH,"promises",{configurable:!0,enumerable:!0,get(){return H}}),$H.exports.Stream=yH.Stream}else{let H=rP(),$=SP(),A=H.Readable.destroy;$H.exports=H.Readable,$H.exports._uint8ArrayToBuffer=H._uint8ArrayToBuffer,$H.exports._isUint8Array=H._isUint8Array,$H.exports.isDisturbed=H.isDisturbed,$H.exports.isErrored=H.isErrored,$H.exports.isReadable=H.isReadable,$H.exports.Readable=H.Readable,$H.exports.Writable=H.Writable,$H.exports.Duplex=H.Duplex,$H.exports.Transform=H.Transform,$H.exports.PassThrough=H.PassThrough,$H.exports.addAbortSignal=H.addAbortSignal,$H.exports.finished=H.finished,$H.exports.destroy=H.destroy,$H.exports.destroy=A,$H.exports.pipeline=H.pipeline,$H.exports.compose=H.compose,Object.defineProperty(H,"promises",{configurable:!0,enumerable:!0,get(){return $}}),$H.exports.Stream=H.Stream}$H.exports.default=$H.exports});var _V=p((_R,nP)=>{if(typeof Object.create==="function")nP.exports=function($,A){if(A)$.super_=A,$.prototype=Object.create(A.prototype,{constructor:{value:$,enumerable:!1,writable:!0,configurable:!0}})};else nP.exports=function($,A){if(A){$.super_=A;var L=function(){};L.prototype=A.prototype,$.prototype=new L,$.prototype.constructor=$}}});var pV=p((pR,oP)=>{try{if(N0=B("util"),typeof N0.inherits!=="function")throw"";oP.exports=N0.inherits}catch(H){oP.exports=_V()}var N0});var uV=p((VR,WV)=>{var{Buffer:Q$}=B("buffer"),VV=Symbol.for("BufferList");function TH(H){if(!(this instanceof TH))return new TH(H);TH._init.call(this,H)}TH._init=function($){if(Object.defineProperty(this,VV,{value:!0}),this._bufs=[],this.length=0,$)this.append($)};TH.prototype._new=function($){return new TH($)};TH.prototype._offset=function($){if($===0)return[0,0];let A=0;for(let L=0;L<this._bufs.length;L++){let D=A+this._bufs[L].length;if($<D||L===this._bufs.length-1)return[L,$-A];A=D}};TH.prototype._reverseOffset=function(H){let $=H[0],A=H[1];for(let L=0;L<$;L++)A+=this._bufs[L].length;return A};TH.prototype.getBuffers=function(){return this._bufs};TH.prototype.get=function($){if($>this.length||$<0)return;let A=this._offset($);return this._bufs[A[0]][A[1]]};TH.prototype.slice=function($,A){if(typeof $==="number"&&$<0)$+=this.length;if(typeof A==="number"&&A<0)A+=this.length;return this.copy(null,0,$,A)};TH.prototype.copy=function($,A,L,D){if(typeof L!=="number"||L<0)L=0;if(typeof D!=="number"||D>this.length)D=this.length;if(L>=this.length)return $||Q$.alloc(0);if(D<=0)return $||Q$.alloc(0);let f=!!$,E=this._offset(L),I=D-L,P=I,T=f&&A||0,U=E[1];if(L===0&&D===this.length){if(!f)return this._bufs.length===1?this._bufs[0]:Q$.concat(this._bufs,this.length);for(let M=0;M<this._bufs.length;M++)this._bufs[M].copy($,T),T+=this._bufs[M].length;return $}if(P<=this._bufs[E[0]].length-U)return f?this._bufs[E[0]].copy($,A,U,U+P):this._bufs[E[0]].slice(U,U+P);if(!f)$=Q$.allocUnsafe(I);for(let M=E[0];M<this._bufs.length;M++){let t=this._bufs[M].length-U;if(P>t)this._bufs[M].copy($,T,U),T+=t;else{this._bufs[M].copy($,T,U,U+P),T+=t;break}if(P-=t,U)U=0}if($.length>T)return $.slice(0,T);return $};TH.prototype.shallowSlice=function($,A){if($=$||0,A=typeof A!=="number"?this.length:A,$<0)$+=this.length;if(A<0)A+=this.length;if($===A)return this._new();let L=this._offset($),D=this._offset(A),f=this._bufs.slice(L[0],D[0]+1);if(D[1]===0)f.pop();else f[f.length-1]=f[f.length-1].slice(0,D[1]);if(L[1]!==0)f[0]=f[0].slice(L[1]);return this._new(f)};TH.prototype.toString=function($,A,L){return this.slice(A,L).toString($)};TH.prototype.consume=function($){if($=Math.trunc($),Number.isNaN($)||$<=0)return this;while(this._bufs.length)if($>=this._bufs[0].length)$-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice($),this.length-=$;break}return this};TH.prototype.duplicate=function(){let $=this._new();for(let A=0;A<this._bufs.length;A++)$.append(this._bufs[A]);return $};TH.prototype.append=function($){return this._attach($,TH.prototype._appendBuffer)};TH.prototype.prepend=function($){return this._attach($,TH.prototype._prependBuffer,!0)};TH.prototype._attach=function($,A,L){if($==null)return this;if($.buffer)A.call(this,Q$.from($.buffer,$.byteOffset,$.byteLength));else if(Array.isArray($)){let[D,f]=L?[$.length-1,-1]:[0,1];for(let E=D;E>=0&&E<$.length;E+=f)this._attach($[E],A,L)}else if(this._isBufferList($)){let[D,f]=L?[$._bufs.length-1,-1]:[0,1];for(let E=D;E>=0&&E<$._bufs.length;E+=f)this._attach($._bufs[E],A,L)}else{if(typeof $==="number")$=$.toString();A.call(this,Q$.from($))}return this};TH.prototype._appendBuffer=function($){this._bufs.push($),this.length+=$.length};TH.prototype._prependBuffer=function($){this._bufs.unshift($),this.length+=$.length};TH.prototype.indexOf=function(H,$,A){if(A===void 0&&typeof $==="string")A=$,$=void 0;if(typeof H==="function"||Array.isArray(H))throw TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');else if(typeof H==="number")H=Q$.from([H]);else if(typeof H==="string")H=Q$.from(H,A);else if(this._isBufferList(H))H=H.slice();else if(Array.isArray(H.buffer))H=Q$.from(H.buffer,H.byteOffset,H.byteLength);else if(!Q$.isBuffer(H))H=Q$.from(H);if($=Number($||0),isNaN($))$=0;if($<0)$=this.length+$;if($<0)$=0;if(H.length===0)return $>this.length?this.length:$;let L=this._offset($),D=L[0],f=L[1];for(;D<this._bufs.length;D++){let E=this._bufs[D];while(f<E.length)if(E.length-f>=H.length){let P=E.indexOf(H,f);if(P!==-1)return this._reverseOffset([D,P]);f=E.length-H.length+1}else{let P=this._reverseOffset([D,f]);if(this._match(P,H))return P;f++}f=0}return-1};TH.prototype._match=function(H,$){if(this.length-H<$.length)return!1;for(let A=0;A<$.length;A++)if(this.get(H+A)!==$[A])return!1;return!0};(function(){let H={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let $ in H)(function(A){if(H[A]===null)TH.prototype[A]=function(L,D){return this.slice(L,L+D)[A](0,D)};else TH.prototype[A]=function(L=0){return this.slice(L,L+H[A])[A](0)}})($)})();TH.prototype._isBufferList=function($){return $ instanceof TH||TH.isBufferList($)};TH.isBufferList=function($){return $!=null&&$[VV]};WV.exports=TH});var xV=p((WR,k0)=>{var FP=HL().Duplex,z2=pV(),qD=uV();function zH(H){if(!(this instanceof zH))return new zH(H);if(typeof H==="function"){this._callback=H;let $=function(L){if(this._callback)this._callback(L),this._callback=null}.bind(this);this.on("pipe",function(L){L.on("error",$)}),this.on("unpipe",function(L){L.removeListener("error",$)}),H=null}qD._init.call(this,H),FP.call(this)}z2(zH,FP);Object.assign(zH.prototype,qD.prototype);zH.prototype._new=function($){return new zH($)};zH.prototype._write=function($,A,L){if(this._appendBuffer($),typeof L==="function")L()};zH.prototype._read=function($){if(!this.length)return this.push(null);$=Math.min($,this.length),this.push(this.slice(0,$)),this.consume($)};zH.prototype.end=function($){if(FP.prototype.end.call(this,$),this._callback)this._callback(null,this.slice()),this._callback=null};zH.prototype._destroy=function($,A){this._bufs.length=0,this.length=0,A($)};zH.prototype._isBufferList=function($){return $ instanceof zH||$ instanceof qD||zH.isBufferList($)};zH.isBufferList=qD.isBufferList;k0.exports=zH;k0.exports.BufferListStream=zH;k0.exports.BufferList=qD});var XV=p((uR,cV)=>{class hV{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}cV.exports=hV});var sP=p((xR,SV)=>{var i=xR,{Buffer:t$}=B("buffer");i.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};i.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0};i.requiredHeaderFlagsErrors={};for(let H in i.requiredHeaderFlags){let $=i.requiredHeaderFlags[H];i.requiredHeaderFlagsErrors[H]="Invalid header flag bits, must be 0x"+$.toString(16)+" for "+i.types[H]+" packet"}i.codes={};for(let H in i.types){let $=i.types[H];i.codes[$]=H}i.CMD_SHIFT=4;i.CMD_MASK=240;i.DUP_MASK=8;i.QOS_MASK=3;i.QOS_SHIFT=1;i.RETAIN_MASK=1;i.VARBYTEINT_MASK=127;i.VARBYTEINT_FIN_MASK=128;i.VARBYTEINT_MAX=268435455;i.SESSIONPRESENT_MASK=1;i.SESSIONPRESENT_HEADER=t$.from([i.SESSIONPRESENT_MASK]);i.CONNACK_HEADER=t$.from([i.codes.connack<<i.CMD_SHIFT]);i.USERNAME_MASK=128;i.PASSWORD_MASK=64;i.WILL_RETAIN_MASK=32;i.WILL_QOS_MASK=24;i.WILL_QOS_SHIFT=3;i.WILL_FLAG_MASK=4;i.CLEAN_SESSION_MASK=2;i.CONNECT_HEADER=t$.from([i.codes.connect<<i.CMD_SHIFT]);i.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11};i.propertiesCodes={};for(let H in i.properties){let $=i.properties[H];i.propertiesCodes[$]=H}i.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function $L(H){return[0,1,2].map(($)=>{return[0,1].map((A)=>{return[0,1].map((L)=>{let D=t$.alloc(1);return D.writeUInt8(i.codes[H]<<i.CMD_SHIFT|(A?i.DUP_MASK:0)|$<<i.QOS_SHIFT|L,0,!0),D})})})}i.PUBLISH_HEADER=$L("publish");i.SUBSCRIBE_HEADER=$L("subscribe");i.SUBSCRIBE_OPTIONS_QOS_MASK=3;i.SUBSCRIBE_OPTIONS_NL_MASK=1;i.SUBSCRIBE_OPTIONS_NL_SHIFT=2;i.SUBSCRIBE_OPTIONS_RAP_MASK=1;i.SUBSCRIBE_OPTIONS_RAP_SHIFT=3;i.SUBSCRIBE_OPTIONS_RH_MASK=3;i.SUBSCRIBE_OPTIONS_RH_SHIFT=4;i.SUBSCRIBE_OPTIONS_RH=[0,16,32];i.SUBSCRIBE_OPTIONS_NL=4;i.SUBSCRIBE_OPTIONS_RAP=8;i.SUBSCRIBE_OPTIONS_QOS=[0,1,2];i.UNSUBSCRIBE_HEADER=$L("unsubscribe");i.ACKS={unsuback:$L("unsuback"),puback:$L("puback"),pubcomp:$L("pubcomp"),pubrel:$L("pubrel"),pubrec:$L("pubrec")};i.SUBACK_HEADER=t$.from([i.codes.suback<<i.CMD_SHIFT]);i.VERSION3=t$.from([3]);i.VERSION4=t$.from([4]);i.VERSION5=t$.from([5]);i.VERSION131=t$.from([131]);i.VERSION132=t$.from([132]);i.QOS=[0,1,2].map((H)=>{return t$.from([H])});i.EMPTY={pingreq:t$.from([i.codes.pingreq<<4,0]),pingresp:t$.from([i.codes.pingresp<<4,0]),disconnect:t$.from([i.codes.disconnect<<4,0])};i.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"};i.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"};i.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};i.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"};i.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};i.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}});var BV=p((hR,rV)=>{var TD=1000,UD=TD*60,MD=UD*60,sL=MD*24,H3=sL*7,$3=sL*365.25;rV.exports=function(H,$){$=$||{};var A=typeof H;if(A==="string"&&H.length>0)return A3(H);else if(A==="number"&&isFinite(H))return $.long?D3(H):L3(H);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(H))};function A3(H){if(H=String(H),H.length>100)return;var $=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(H);if(!$)return;var A=parseFloat($[1]),L=($[2]||"ms").toLowerCase();switch(L){case"years":case"year":case"yrs":case"yr":case"y":return A*$3;case"weeks":case"week":case"w":return A*H3;case"days":case"day":case"d":return A*sL;case"hours":case"hour":case"hrs":case"hr":case"h":return A*MD;case"minutes":case"minute":case"mins":case"min":case"m":return A*UD;case"seconds":case"second":case"secs":case"sec":case"s":return A*TD;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return}}function L3(H){var $=Math.abs(H);if($>=sL)return Math.round(H/sL)+"d";if($>=MD)return Math.round(H/MD)+"h";if($>=UD)return Math.round(H/UD)+"m";if($>=TD)return Math.round(H/TD)+"s";return H+"ms"}function D3(H){var $=Math.abs(H);if($>=sL)return R0(H,$,sL,"day");if($>=MD)return R0(H,$,MD,"hour");if($>=UD)return R0(H,$,UD,"minute");if($>=TD)return R0(H,$,TD,"second");return H+" ms"}function R0(H,$,A,L){var D=$>=A*1.5;return Math.round(H/A)+" "+L+(D?"s":"")}});var CP=p((cR,nV)=>{function f3(H){A.debug=A,A.default=A,A.coerce=P,A.disable=E,A.enable=D,A.enabled=I,A.humanize=BV(),A.destroy=T,Object.keys(H).forEach((U)=>{A[U]=H[U]}),A.names=[],A.skips=[],A.formatters={};function $(U){let M=0;for(let t=0;t<U.length;t++)M=(M<<5)-M+U.charCodeAt(t),M|=0;return A.colors[Math.abs(M)%A.colors.length]}A.selectColor=$;function A(U){let M,t=null,_,x;function V(...h){if(!V.enabled)return;let W=V,c=Number(new Date),r=c-(M||c);if(W.diff=r,W.prev=M,W.curr=c,M=c,h[0]=A.coerce(h[0]),typeof h[0]!=="string")h.unshift("%O");let F=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(y,k)=>{if(y==="%%")return"%";F++;let J=A.formatters[k];if(typeof J==="function"){let e=h[F];y=J.call(W,e),h.splice(F,1),F--}return y}),A.formatArgs.call(W,h),(W.log||A.log).apply(W,h)}if(V.namespace=U,V.useColors=A.useColors(),V.color=A.selectColor(U),V.extend=L,V.destroy=A.destroy,Object.defineProperty(V,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(t!==null)return t;if(_!==A.namespaces)_=A.namespaces,x=A.enabled(U);return x},set:(h)=>{t=h}}),typeof A.init==="function")A.init(V);return V}function L(U,M){let t=A(this.namespace+(typeof M>"u"?":":M)+U);return t.log=this.log,t}function D(U){A.save(U),A.namespaces=U,A.names=[],A.skips=[];let M=(typeof U==="string"?U:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let t of M)if(t[0]==="-")A.skips.push(t.slice(1));else A.names.push(t)}function f(U,M){let t=0,_=0,x=-1,V=0;while(t<U.length)if(_<M.length&&(M[_]===U[t]||M[_]==="*"))if(M[_]==="*")x=_,V=t,_++;else t++,_++;else if(x!==-1)_=x+1,V++,t=V;else return!1;while(_<M.length&&M[_]==="*")_++;return _===M.length}function E(){let U=[...A.names,...A.skips.map((M)=>"-"+M)].join(",");return A.enable(""),U}function I(U){for(let M of A.skips)if(f(U,M))return!1;for(let M of A.names)if(f(U,M))return!0;return!1}function P(U){if(U instanceof Error)return U.stack||U.message;return U}function T(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return A.enable(A.load()),A}nV.exports=f3});var FV=p((oV,O0)=>{oV.formatArgs=I3;oV.save=P3;oV.load=T3;oV.useColors=E3;oV.storage=U3();oV.destroy=(()=>{let H=!1;return()=>{if(!H)H=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();oV.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function E3(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let H;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(H=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(H[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function I3(H){if(H[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+H[0]+(this.useColors?"%c ":" ")+"+"+O0.exports.humanize(this.diff),!this.useColors)return;let $="color: "+this.color;H.splice(1,0,$,"color: inherit");let A=0,L=0;H[0].replace(/%[a-zA-Z%]/g,(D)=>{if(D==="%%")return;if(A++,D==="%c")L=A}),H.splice(L,0,$)}oV.log=console.debug||console.log||(()=>{});function P3(H){try{if(H)oV.storage.setItem("debug",H);else oV.storage.removeItem("debug")}catch($){}}function T3(){let H;try{H=oV.storage.getItem("debug")||oV.storage.getItem("DEBUG")}catch($){}if(!H&&typeof process<"u"&&"env"in process)H=process.env.DEBUG;return H}function U3(){try{return localStorage}catch(H){}}O0.exports=CP()(oV);var{formatters:M3}=O0.exports;M3.j=function(H){try{return JSON.stringify(H)}catch($){return"[UnexpectedJSONParseError]: "+$.message}}});var GV=p((CV,w0)=>{var h3=B("tty"),m0=B("util");CV.init=o3;CV.log=r3;CV.formatArgs=X3;CV.save=B3;CV.load=n3;CV.useColors=c3;CV.destroy=m0.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");CV.colors=[6,2,3,4,5,1];try{let H=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(H&&(H.stderr||H).level>=2)CV.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(H){}CV.inspectOpts=Object.keys(process.env).filter((H)=>{return/^debug_/i.test(H)}).reduce((H,$)=>{let A=$.substring(6).toLowerCase().replace(/_([a-z])/g,(D,f)=>{return f.toUpperCase()}),L=process.env[$];if(/^(yes|on|true|enabled)$/i.test(L))L=!0;else if(/^(no|off|false|disabled)$/i.test(L))L=!1;else if(L==="null")L=null;else L=Number(L);return H[A]=L,H},{});function c3(){return"colors"in CV.inspectOpts?Boolean(CV.inspectOpts.colors):h3.isatty(process.stderr.fd)}function X3(H){let{namespace:$,useColors:A}=this;if(A){let L=this.color,D="\x1B[3"+(L<8?L:"8;5;"+L),f=` ${D};1m${$} \x1B[0m`;H[0]=f+H[0].split(`
|
|
2
|
+
var MN=Object.create;var{getPrototypeOf:VN,defineProperty:$9,getOwnPropertyNames:zN}=Object;var FN=Object.prototype.hasOwnProperty;var v_=(_,T,A)=>{A=_!=null?MN(VN(_)):{};let E=T||!_||!_.__esModule?$9(A,"default",{value:_,enumerable:!0}):A;for(let L of zN(_))if(!FN.call(E,L))$9(E,L,{get:()=>_[L],enumerable:!0});return E};var W=(_,T)=>()=>(T||_((T={exports:{}}).exports,T),T.exports);var j=import.meta.require;var C9=W((Zk,F9)=>{F9.exports=yN;var SN=Object.prototype.hasOwnProperty;function yN(){var _={};for(var T=0;T<arguments.length;T++){var A=arguments[T];for(var E in A)if(SN.call(A,E))_[E]=A[E]}return _}});var k8=W((Yk,O9)=>{function vN(_){var T=new _,A=T;function E(){var J=T;if(J.next)T=J.next;else T=new _,A=T;return J.next=null,J}function L(J){A.next=J,A=J}return{get:E,release:L}}O9.exports=vN});var h5=W((Kk,D9)=>{var hN=C9(),R9=k8(),kN={released:R0,results:!0};function fN(_){_=hN(kN,_);var T=_.released,A=R9(_.results?mN:bN),E=R9(gN),L=_.results?K:$,J=_.results?Y:G;return X;function X(U,V,N,z){var Q=A.get();if(z=z||R0,V.length===0)z.call(U),T(Q);else{if(Q._callback=z,Q._callThat=U,Q._release=H,typeof V==="function")J(U,V,N,Q);else L(U,V,N,Q);if(Q._count===0)Q.release()}}function H(U){A.release(U),T(U)}function Z(U){E.release(U)}function Y(U,V,N,z){var Q=null;z._count=N.length,z._results=Array(z._count);for(var F=0;F<N.length;F++)if(Q=E.get(),Q._release=Z,Q.parent=z,Q.pos=F,U)V.call(U,N[F],Q.release);else V(N[F],Q.release)}function K(U,V,N,z){var Q=null,F=R0;z._count=V.length,z._results=Array(z._count);for(var R=0;R<V.length;R++)if(Q=E.get(),Q._release=Z,Q.parent=z,Q.pos=R,F=V[R],U)if(F.length===1)F.call(U,Q.release);else F.call(U,N,Q.release);else if(F.length===1)F(Q.release);else F(N,Q.release)}function G(U,V,N,z){z._count=N.length;for(var Q=0;Q<N.length;Q++)if(U)V.call(U,N[Q],z.release);else V(N[Q],z.release)}function $(U,V,N,z){var Q=null;z._count=V.length;for(var F=0;F<V.length;F++)if(Q=V[F],U)if(Q.length===1)Q.call(U,z.release);else Q.call(U,N,z.release);else if(Q.length===1)Q(z.release);else Q(N,z.release)}}function bN(){this._count=-1,this._callback=R0,this._callThat=null,this._release=null,this.next=null;var _=this,T=0;this.release=function(){var A=_._callback;if(++T===_._count||_._count===0){if(_._callThat)A.call(_._callThat);else A();_._callback=R0,_._callThat=null,T=0,_._release(_)}}}function gN(){this.pos=-1,this._release=R0,this.parent=null,this.next=null;var _=this;this.release=function(T,A){_.parent.release(T,_.pos,A),_.pos=-1,_.parent=null,_._release(_)}}function mN(){this._count=-1,this._callback=R0,this._results=null,this._err=null,this._callThat=null,this._release=R0,this.next=null;var _=this,T=0;this.release=function(A,E,L){if(_._err=_._err||A,E>=0)_._results[E]=L;var J=_._callback;if(++T===_._count||_._count===0){if(_._callThat)J.call(_._callThat,_._err,_._results);else J(_._err,_._results);_._callback=R0,_._results=null,_._err=null,_._callThat=null,T=0,_._release(_)}}}function R0(){}D9.exports=fN});var I9=W((Gk,q9)=>{var uN={results:!0};function dN(_){_=Object.assign({},uN,_);var T,A;if(_.results)T=lN,A=nN;else T=cN,A=pN;return E;function E(L,J,X,H){if(H=(H||iN).bind(L),J.length===0)H.call(L);else if(J.bind){if(L)J=J.bind(L);T(J,X,H)}else{var Z;if(L){var Y=J.length;Z=Array(Y);for(var K=0;K<Y;K++)Z[K]=J[K].bind(L)}else Z=J;A(Z,X,H)}}}function cN(_,T,A){var E=0,L=T.length;J();function J(){if(E<L)f8(_,T[E++],J);else A()}}function pN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=B9;else J=f8;X();function X(){if(E<L)J(_[E++],T,X);else A()}}function lN(_,T,A){var E=0,L=T.length,J=Array(L);X(null,null);function X(H,Z){if(H){A(H);return}if(E>0)J[E-1]=Z;if(E<L)f8(_,T[E++],X);else A(null,J)}}function nN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=B9;else J=f8;var X=Array(L);H(null,null);function H(Z,Y){if(Z){A(Z);return}if(E>0)X[E-1]=Y;if(E<L)J(_[E++],T,H);else A(null,X)}}function B9(_,T,A){_(A)}function f8(_,T,A){_(T,A)}function iN(){}q9.exports=dN});var x9=W((P9)=>{Object.defineProperty(P9,"__esModule",{value:!0});P9.default=void 0;var $k=P9.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var y9=W((w9)=>{Object.defineProperty(w9,"__esModule",{value:!0});w9.default=void 0;var Wk=w9.default="00000000-0000-0000-0000-000000000000"});var k9=W((v9)=>{Object.defineProperty(v9,"__esModule",{value:!0});v9.default=void 0;var Qk=v9.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var P4=W((f9)=>{Object.defineProperty(f9,"__esModule",{value:!0});f9.default=void 0;var aN=oN(k9());function oN(_){return _&&_.__esModule?_:{default:_}}function rN(_){return typeof _==="string"&&aN.default.test(_)}var Vk=f9.default=rN});var j4=W((g9)=>{Object.defineProperty(g9,"__esModule",{value:!0});g9.default=void 0;var sN=tN(P4());function tN(_){return _&&_.__esModule?_:{default:_}}function eN(_){if(!(0,sN.default)(_))throw TypeError("Invalid UUID");let T,A=new Uint8Array(16);return A[0]=(T=parseInt(_.slice(0,8),16))>>>24,A[1]=T>>>16&255,A[2]=T>>>8&255,A[3]=T&255,A[4]=(T=parseInt(_.slice(9,13),16))>>>8,A[5]=T&255,A[6]=(T=parseInt(_.slice(14,18),16))>>>8,A[7]=T&255,A[8]=(T=parseInt(_.slice(19,23),16))>>>8,A[9]=T&255,A[10]=(T=parseInt(_.slice(24,36),16))/1099511627776&255,A[11]=T/4294967296&255,A[12]=T>>>24&255,A[13]=T>>>16&255,A[14]=T>>>8&255,A[15]=T&255,A}var Fk=g9.default=eN});var D0=W((d9)=>{Object.defineProperty(d9,"__esModule",{value:!0});d9.default=void 0;d9.unsafeStringify=u9;var _Q=TQ(P4());function TQ(_){return _&&_.__esModule?_:{default:_}}var b_=[];for(let _=0;_<256;++_)b_.push((_+256).toString(16).slice(1));function u9(_,T=0){return(b_[_[T+0]]+b_[_[T+1]]+b_[_[T+2]]+b_[_[T+3]]+"-"+b_[_[T+4]]+b_[_[T+5]]+"-"+b_[_[T+6]]+b_[_[T+7]]+"-"+b_[_[T+8]]+b_[_[T+9]]+"-"+b_[_[T+10]]+b_[_[T+11]]+b_[_[T+12]]+b_[_[T+13]]+b_[_[T+14]]+b_[_[T+15]]).toLowerCase()}function AQ(_,T=0){let A=u9(_,T);if(!(0,_Q.default)(A))throw TypeError("Stringified UUID is invalid");return A}var Ok=d9.default=AQ});var m8=W((p9)=>{Object.defineProperty(p9,"__esModule",{value:!0});p9.default=XQ;var LQ=JQ(j("crypto"));function JQ(_){return _&&_.__esModule?_:{default:_}}var g8=new Uint8Array(256),b8=g8.length;function XQ(){if(b8>g8.length-16)LQ.default.randomFillSync(g8),b8=0;return g8.slice(b8,b8+=16)}});var g5=W((l9)=>{Object.defineProperty(l9,"__esModule",{value:!0});l9.default=void 0;var ZQ=KQ(m8()),YQ=D0();function KQ(_){return _&&_.__esModule?_:{default:_}}var k5,u8,f5=0,b5=0;function GQ(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let{node:J,clockseq:X}=_;if(!_._v6){if(!J)J=k5;if(X==null)X=u8}if(J==null||X==null){let $=_.random||(_.rng||ZQ.default)();if(J==null){if(J=[$[0],$[1],$[2],$[3],$[4],$[5]],!k5&&!_._v6)J[0]|=1,k5=J}if(X==null){if(X=($[6]<<8|$[7])&16383,u8===void 0&&!_._v6)u8=X}}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:b5+1,Y=H-f5+(Z-b5)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>f5)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");f5=H,b5=Z,u8=X,H+=12219292800000;let K=((H&268435455)*1e4+Z)%4294967296;L[E++]=K>>>24&255,L[E++]=K>>>16&255,L[E++]=K>>>8&255,L[E++]=K&255;let G=H/4294967296*1e4&268435455;L[E++]=G>>>8&255,L[E++]=G&255,L[E++]=G>>>24&15|16,L[E++]=G>>>16&255,L[E++]=X>>>8|128,L[E++]=X&255;for(let $=0;$<6;++$)L[E+$]=J[$];return T||(0,YQ.unsafeStringify)(L)}var Bk=l9.default=GQ});var m5=W((i9)=>{Object.defineProperty(i9,"__esModule",{value:!0});i9.default=NQ;var $Q=WQ(j4()),UQ=D0();function WQ(_){return _&&_.__esModule?_:{default:_}}function NQ(_){let T=typeof _==="string"?(0,$Q.default)(_):_,A=QQ(T);return typeof _==="string"?(0,UQ.unsafeStringify)(A):A}function QQ(_,T=!1){return Uint8Array.of((_[6]&15)<<4|_[7]>>4&15,(_[7]&15)<<4|(_[4]&240)>>4,(_[4]&15)<<4|(_[5]&240)>>4,(_[5]&15)<<4|(_[0]&240)>>4,(_[0]&15)<<4|(_[1]&240)>>4,(_[1]&15)<<4|(_[2]&240)>>4,96|_[2]&15,_[3],_[8],_[9],_[10],_[11],_[12],_[13],_[14],_[15])}});var u5=W((a9)=>{Object.defineProperty(a9,"__esModule",{value:!0});a9.URL=a9.DNS=void 0;a9.default=DQ;var VQ=D0(),zQ=FQ(j4());function FQ(_){return _&&_.__esModule?_:{default:_}}function CQ(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var OQ=a9.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",RQ=a9.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function DQ(_,T,A){function E(L,J,X,H){var Z;if(typeof L==="string")L=CQ(L);if(typeof J==="string")J=(0,zQ.default)(J);if(((Z=J)===null||Z===void 0?void 0:Z.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let Y=new Uint8Array(16+L.length);if(Y.set(J),Y.set(L,J.length),Y=A(Y),Y[6]=Y[6]&15|T,Y[8]=Y[8]&63|128,X){H=H||0;for(let K=0;K<16;++K)X[H+K]=Y[K];return X}return(0,VQ.unsafeStringify)(Y)}try{E.name=_}catch(L){}return E.DNS=OQ,E.URL=RQ,E}});var t9=W((r9)=>{Object.defineProperty(r9,"__esModule",{value:!0});r9.default=void 0;var IQ=PQ(j("crypto"));function PQ(_){return _&&_.__esModule?_:{default:_}}function jQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return IQ.default.createHash("md5").update(_).digest()}var jk=r9.default=jQ});var A7=W((_7)=>{Object.defineProperty(_7,"__esModule",{value:!0});_7.default=void 0;var xQ=e9(u5()),wQ=e9(t9());function e9(_){return _&&_.__esModule?_:{default:_}}var SQ=(0,xQ.default)("v3",48,wQ.default),wk=_7.default=SQ});var J7=W((E7)=>{Object.defineProperty(E7,"__esModule",{value:!0});E7.default=void 0;var yQ=vQ(j("crypto"));function vQ(_){return _&&_.__esModule?_:{default:_}}var yk=E7.default={randomUUID:yQ.default.randomUUID}});var K7=W((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});Z7.default=void 0;var X7=H7(J7()),hQ=H7(m8()),kQ=D0();function H7(_){return _&&_.__esModule?_:{default:_}}function fQ(_,T,A){if(X7.default.randomUUID&&!T&&!_)return X7.default.randomUUID();_=_||{};let E=_.random||(_.rng||hQ.default)();if(E[6]=E[6]&15|64,E[8]=E[8]&63|128,T){A=A||0;for(let L=0;L<16;++L)T[A+L]=E[L];return T}return(0,kQ.unsafeStringify)(E)}var hk=Z7.default=fQ});var U7=W((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});G7.default=void 0;var bQ=gQ(j("crypto"));function gQ(_){return _&&_.__esModule?_:{default:_}}function mQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return bQ.default.createHash("sha1").update(_).digest()}var fk=G7.default=mQ});var M7=W((N7)=>{Object.defineProperty(N7,"__esModule",{value:!0});N7.default=void 0;var uQ=W7(u5()),dQ=W7(U7());function W7(_){return _&&_.__esModule?_:{default:_}}var cQ=(0,uQ.default)("v5",80,dQ.default),gk=N7.default=cQ});var F7=W((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});z7.default=iQ;var pQ=D0(),lQ=V7(g5()),nQ=V7(m5());function V7(_){return _&&_.__esModule?_:{default:_}}function iQ(_={},T,A=0){let E=(0,lQ.default)({..._,_v6:!0},new Uint8Array(16));if(E=(0,nQ.default)(E),T){for(let L=0;L<16;L++)T[A+L]=E[L];return T}return(0,pQ.unsafeStringify)(E)}});var O7=W((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});C7.default=tQ;var oQ=sQ(j4()),rQ=D0();function sQ(_){return _&&_.__esModule?_:{default:_}}function tQ(_){let T=typeof _==="string"?(0,oQ.default)(_):_,A=eQ(T);return typeof _==="string"?(0,rQ.unsafeStringify)(A):A}function eQ(_){return Uint8Array.of((_[3]&15)<<4|_[4]>>4&15,(_[4]&15)<<4|(_[5]&240)>>4,(_[5]&15)<<4|_[6]&15,_[7],(_[1]&15)<<4|(_[2]&240)>>4,(_[2]&15)<<4|(_[3]&240)>>4,16|(_[0]&240)>>4,(_[0]&15)<<4|(_[1]&240)>>4,_[8],_[9],_[10],_[11],_[12],_[13],_[14],_[15])}});var I7=W((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});B7.default=void 0;var TM=EM(m8()),AM=D0();function EM(_){return _&&_.__esModule?_:{default:_}}var R7=null,D7=null,h1=0;function LM(_,T,A){_=_||{};let E=T&&A||0,L=T||new Uint8Array(16),J=_.random||(_.rng||TM.default)(),X=_.msecs!==void 0?_.msecs:Date.now(),H=_.seq!==void 0?_.seq:null,Z=D7,Y=R7;if(X>h1&&_.msecs===void 0){if(h1=X,H!==null)Z=null,Y=null}if(H!==null){if(H>2147483647)H=2147483647;Z=H>>>19&4095,Y=H&524287}if(Z===null||Y===null)Z=J[6]&127,Z=Z<<8|J[7],Y=J[8]&63,Y=Y<<8|J[9],Y=Y<<5|J[10]>>>3;if(X+1e4>h1&&H===null){if(++Y>524287){if(Y=0,++Z>4095)Z=0,h1++}}else h1=X;return D7=Z,R7=Y,L[E++]=h1/1099511627776&255,L[E++]=h1/4294967296&255,L[E++]=h1/16777216&255,L[E++]=h1/65536&255,L[E++]=h1/256&255,L[E++]=h1&255,L[E++]=Z>>>4&15|112,L[E++]=Z&255,L[E++]=Y>>>13&63|128,L[E++]=Y>>>5&255,L[E++]=Y<<3&255|J[10]&7,L[E++]=J[11],L[E++]=J[12],L[E++]=J[13],L[E++]=J[14],L[E++]=J[15],T||(0,AM.unsafeStringify)(L)}var ck=B7.default=LM});var x7=W((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});P7.default=void 0;var JM=XM(P4());function XM(_){return _&&_.__esModule?_:{default:_}}function HM(_){if(!(0,JM.default)(_))throw TypeError("Invalid UUID");return parseInt(_.slice(14,15),16)}var lk=P7.default=HM});var w7=W((p_)=>{Object.defineProperty(p_,"__esModule",{value:!0});Object.defineProperty(p_,"MAX",{enumerable:!0,get:function(){return ZM.default}});Object.defineProperty(p_,"NIL",{enumerable:!0,get:function(){return YM.default}});Object.defineProperty(p_,"parse",{enumerable:!0,get:function(){return KM.default}});Object.defineProperty(p_,"stringify",{enumerable:!0,get:function(){return GM.default}});Object.defineProperty(p_,"v1",{enumerable:!0,get:function(){return $M.default}});Object.defineProperty(p_,"v1ToV6",{enumerable:!0,get:function(){return UM.default}});Object.defineProperty(p_,"v3",{enumerable:!0,get:function(){return WM.default}});Object.defineProperty(p_,"v4",{enumerable:!0,get:function(){return NM.default}});Object.defineProperty(p_,"v5",{enumerable:!0,get:function(){return QM.default}});Object.defineProperty(p_,"v6",{enumerable:!0,get:function(){return MM.default}});Object.defineProperty(p_,"v6ToV1",{enumerable:!0,get:function(){return VM.default}});Object.defineProperty(p_,"v7",{enumerable:!0,get:function(){return zM.default}});Object.defineProperty(p_,"validate",{enumerable:!0,get:function(){return FM.default}});Object.defineProperty(p_,"version",{enumerable:!0,get:function(){return CM.default}});var ZM=J1(x9()),YM=J1(y9()),KM=J1(j4()),GM=J1(D0()),$M=J1(g5()),UM=J1(m5()),WM=J1(A7()),NM=J1(K7()),QM=J1(M7()),MM=J1(F7()),VM=J1(O7()),zM=J1(I7()),FM=J1(P4()),CM=J1(x7());function J1(_){return _&&_.__esModule?_:{default:_}}});var uT=W((ak,S7)=>{function OM(_,T){if(Object.prototype.hasOwnProperty.call(_,"clientId"))this.clientId=_.clientId;if(Object.prototype.hasOwnProperty.call(_,"nl"))this.nl=_.nl;if(this.cmd=_.cmd||"publish",this.brokerId=_.brokerId||T&&T.id,this.brokerCounter=_.brokerCounter||(T?++T.counter:0),this.topic=_.topic,this.payload=_.payload||Buffer.alloc(0),this.qos=_.qos||0,this.retain=_.retain||!1,this.dup=_.dup||!1,this.qos>0||this.cmd!=="publish")this.messageId=void 0}S7.exports=OM});var d5=W((ok,y7)=>{var k1=j("util");y7.exports=function(_,T){class A extends _{constructor(E){super(E);this.addP=k1.promisify(this.add_async),this.removeP=k1.promisify(this.remove_async),this.matchP=k1.promisify(this.match_async),this.testP=k1.promisify(this.test_async),this.clearP=k1.promisify(this.clear_async),this._get_visitorP=k1.promisify(this.get_visitor_async),this._visit_nextP=k1.promisify(this.visit_next_async),this._get_restorerP=k1.promisify(this.get_restorer_async),this._restore_nextP=k1.promisify(this.restore_next_async),this._match_iterP=k1.promisify(this.match_iter_async),this._match_nextP=k1.promisify(this.match_next_async)}*visit(){let E=this.get_visitor();while(!0){let L=this.visit_next(E);if(L===void 0)break;yield L}}async*visitP(){let E=await this._get_visitorP();while(!0){let L=await this._visit_nextP(E);if(L===void 0)break;yield L}}*match_iter(E,L){let J=super.match_iter(E,L);while(!0){let X=this.match_next(J);if(X===void 0)break;yield X.value}}async*match_iterP(E,L){let J=await this._match_iterP(E,L);while(!0){let X=await this._match_nextP(J);if(X===void 0)break;yield X.value}}get_trie(){let E=new T(this.options),L=E.get_restorer();for(let J of this.visit())L(J);return E.get_trie()}get_restorer(E){let L=super.get_restorer(E);return(J)=>{super.restore_next(L,J)}}async get_restorerP(E){let L=await this._get_restorerP(E);return async(J)=>{await this._restore_nextP(L,J)}}}return A.is_native=!0,A.nonNative=T,A}});var l5=W((h7)=>{var d8=j("util");function L_(_){if(_=_||{},this._separator=_.separator||".",this._wildcard_one=_.wildcard_one||"*",this._wildcard_some=_.wildcard_some||"#",this._max_words=_.max_words||100,this._max_wildcard_somes=_.max_wildcard_somes||3,this._match_empty_levels=_.match_empty_levels,this._trie=new Map,_.cache_adds instanceof Map)this._shortcuts=_.cache_adds;else if(_.cache_adds)this._shortcuts=new Map;if(_.cache_splits>0)this._cache_splits=_.cache_splits,this._split_cache=new Map}L_.prototype._initial_value=function(_){return[_]};L_.prototype._add_value=function(_,T){_[_.length]=T};L_.prototype._add_values=function(_,T){var A,E=_.length,L=T.length;for(A=0;A<L;A+=1)_[E+A]=T[A]};L_.prototype._iter_values=function(_,T){return _[Symbol.iterator](T)};L_.prototype._remove_value=function(_,T){if(T===void 0)return!0;var A=_.lastIndexOf(T);if(A>=0)_.splice(A,1);return _.length===0};L_.prototype._add=function(_,T,A,E){var L,J;if(T===A.length){if(L=E.get(this._separator),L)this._add_value(L,_);else L=this._initial_value(_),E.set(this._separator,L);return L}if(J=A[T],L=E.get(J),!L)L=new Map,E.set(J,L);return this._add(_,T+1,A,L)};L_.prototype._remove=function(_,T,A,E){var L,J,X;if(T===A.length){if(L=E.get(this._separator),L&&this._remove_value(L,_))return E.delete(this._separator),!0;return!1}if(J=A[T],L=E.get(J),!L)return!1;if(X=this._remove(_,T+1,A,L),L.size===0)E.delete(J);return X};L_.prototype._match_some=function(_,T,A,E,L){var J,X;for(X of E.keys())if(X!==this._separator){for(J=T;J<A.length;J+=1)_=this._match(_,J,A,E,L);break}return _};L_.prototype._match=function(_,T,A,E,L){var J,X;if(X=E.get(this._wildcard_some),X)_=this._match_some(_,T,A,X,L),_=this._match(_,A.length,A,X,L);if(T===A.length){if(X=E.get(this._separator),X)if(_.dest)this._add_values(_.dest,_.source,L),this._add_values(_.dest,X,L),_=_.dest;else if(_.source)_.dest=_.source,_.source=X;else this._add_values(_,X,L)}else{if(J=A[T],J!==this._wildcard_one&&J!==this._wildcard_some){if(X=E.get(J),X)_=this._match(_,T+1,A,X,L)}if(J||this._match_empty_levels){if(X=E.get(this._wildcard_one),X)_=this._match(_,T+1,A,X,L)}}return _};L_.prototype._match2=function(_,T,A){var E=this._match({source:_},0,this._split(T,!1),this._trie,A);return E.source||E};L_.prototype._test_some=function(_,T,A,E){var L,J;for(J of E.keys())if(J!==this._separator){for(L=T;L<A.length;L+=1)if(this._test(_,L,A,E))return!0;break}return!1};L_.prototype._test=function(_,T,A,E){var L,J;if(J=E.get(this._wildcard_some),J){if(this._test_some(_,T,A,J)||this._test(_,A.length,A,J))return!0}if(T===A.length){if(J=E.get(this._separator),J&&this.test_values(J,_))return!0}else{if(L=A[T],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=E.get(L),J&&this._test(_,T+1,A,J))return!0}if(L||this._match_empty_levels){if(J=E.get(this._wildcard_one),J&&this._test(_,T+1,A,J))return!0}}return!1};L_.prototype._match_some_iter=function*(_,T,A,E){var L,J;for(J of A.keys())if(J!==this._separator){for(L=_;L<T.length;L+=1)yield*this._match_iter(L,T,A,E);break}};L_.prototype._match_iter=function*(_,T,A,E){var L,J;if(J=A.get(this._wildcard_some),J)yield*this._match_some_iter(_,T,J,E),yield*this._match_iter(T.length,T,J,E);if(_===T.length){if(J=A.get(this._separator),J)yield*this._iter_values(J,E)}else{if(L=T[_],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=A.get(L),J)yield*this._match_iter(_+1,T,J,E)}if(L||this._match_empty_levels){if(J=A.get(this._wildcard_one),J)yield*this._match_iter(_+1,T,J,E)}}};L_.prototype._split_words=function(_){let T=_.split(this._separator);if(T.length>this._max_words)throw Error("too many words");return T};L_.prototype._split=function(_,T){let A;if(this._split_cache){if(A=this._split_cache.get(_),A===void 0){if(A=this._split_words(_),this._split_cache.set(_,A),this._split_cache.size>this._cache_splits)for(let E of this._split_cache.keys()){this._split_cache.delete(E);break}}}else A=this._split_words(_);if(T&&A.reduce((E,L)=>E+(L===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return A};L_.prototype.add=function(_,T){var A=this._shortcuts&&this._shortcuts.get(_);if(A)this._add_value(A,T);else if(A=this._add(T,0,this._split(_,!0),this._trie),this._shortcuts)this._shortcuts.set(_,A);return this};L_.prototype.remove=function(_,T){if(this._remove(T,0,this._split(_,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(_);return this};L_.prototype.match=function(_,T){return this._match2([],_,T)};L_.prototype.match_iter=function(_,T){return this._match_iter(0,this._split(_,!1),this._trie,T)};L_.prototype.test=function(_,T){return this._test(T,0,this._split(_,!1),this._trie)};L_.prototype.test_values=function(_,T){return _.indexOf(T)>=0};L_.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};L_.prototype.get_trie=function(){return this._trie};L_.prototype.visit=function*(){let _=[],T=this._trie.entries(),A=0;while(!0){if(A===0)yield{type:"start_entries"};let E=T.next();if(E.done){yield{type:"end_entries"};let X=_.pop();if(X===void 0)return;[T,A]=X;continue}let[L,J]=E.value;if(yield{type:"entry",key:L},++A,L===this._separator){if(yield{type:"start_values"},J[Symbol.iterator])for(let X of J)yield{type:"value",value:X};else yield{type:"value",value:J};yield{type:"end_values"};continue}_.push([T,A]),T=J.entries(),A=0}};L_.prototype.get_restorer=function(_){_=_||{};let T=[],A=this._trie,E="";return(L)=>{switch(L.type){case"entry":if(A=A||new Map,T.push([A,L.key,E]),A=A.get(L.key),_.cache_adds){if(E)E+=this._separator;E+=L.key}break;case"value":if(A)this._add_value(A,L.value);else A=this._initial_value(L.value);break;case"end_entries":if(A&&A.size===0)A=void 0;case"end_values":let J=T.pop();if(J===void 0)A=void 0,E="";else{let[X,H,Z]=J;if(A){if(_.cache_adds&&this._shortcuts&&L.type==="end_values")this._shortcuts.set(Z,A);X.set(H,A)}A=X,E=Z}break}}};function M1(_){L_.call(this,_)}d8.inherits(M1,L_);M1.prototype._initial_value=function(_){return new Set().add(_)};M1.prototype._add_value=function(_,T){_.add(T)};M1.prototype._add_values=function(_,T){T.forEach(function(A){_.add(A)})};M1.prototype._remove_value=function(_,T){if(T===void 0)return!0;return _.delete(T),_.size===0};M1.prototype.test_values=function(_,T){return _.has(T)};M1.prototype.match=function(_,T){return this._match2(new Set,_,T)};function r1(_){L_.call(this,_)}d8.inherits(r1,L_);r1.prototype._initial_value=function(){return!0};r1.prototype._add_value=function(){};r1.prototype._remove_value=function(){return!0};r1.prototype._iter_values=function*(){yield!0};r1.prototype.test_values=function(){return!0};r1.prototype.match=function(_,T){return this.test(_,T)};var c8=j("stream");function c5(_){c8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}d8.inherits(c5,c8.Readable);c5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function p5(_){c8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}d8.inherits(p5,c8.Writable);p5.prototype._write=function(_,T,A){this._restorer(_),A()};var v7=null;function RM(_){if(_!==v7){let T=d5();L_.nativeString=T(_.QlobberString,L_),L_.nativeNumber=T(_.QlobberNumber,L_),M1.nativeString=T(_.QlobberDedupString,M1),M1.nativeNumber=T(_.QlobberDedupNumber,M1),r1.native=T(_.QlobberTrue,r1),v7=_}return h7}h7.Qlobber=L_;h7.QlobberDedup=M1;h7.QlobberTrue=r1;h7.VisitorStream=c5;h7.RestorerStream=p5;h7.set_native=RM});var k7=W((sk,i5)=>{var xM=j("util"),wM=l5(),n5=wM.Qlobber;function V1(_){n5.call(this,_),this.subscriptionsCount=0}xM.inherits(V1,n5);V1.prototype._initial_value=function(_){this.subscriptionsCount+=1;let T={topic:_.topic,clientMap:new Map().set(_.clientId,{qos:_.qos,rh:_.rh,rap:_.rap,nl:_.nl})};return T[Symbol.iterator]=function*(A){if(A===void 0)for(let[E,L]of T.clientMap)yield{topic:T.topic,clientId:E,...L};else if(T.topic===A)for(let[E,L]of T.clientMap)yield{clientId:E,...L}},T};V1.prototype._add_value=function(_,T){var A=_.clientMap,E=A.size;if(A.set(T.clientId,{qos:T.qos,rh:T.rh,rap:T.rap,nl:T.nl}),A.size>E)this.subscriptionsCount+=1};V1.prototype._add_values=function(_,T,A){if(A===void 0)for(let[E,L]of T.clientMap)_.push({clientId:E,topic:T.topic,...L});else if(T.topic===A)for(let[E,L]of T.clientMap)_.push({clientId:E,...L})};V1.prototype._remove_value=function(_,T){var A=_.clientMap,E=A.size;A.delete(T.clientId);var L=A.size;if(L<E)this.subscriptionsCount-=1;return L===0};V1.prototype.test_values=function(_,T){var A=_.clientMap;return _.topic===T.topic&&A.size===1&&A.has(T.clientId)};V1.prototype.match=function(_,T){return this._match([],0,_.split(this._separator),this._trie,T)};V1.prototype.clear=function(){return this.subscriptionsCount=0,n5.prototype.clear.call(this)};V1.set_native=function(_){let T=d5();return V1.native=T(_.QlobberSub,V1),i5.exports};i5.exports=V1});var m7=W((tk,o5)=>{var{Readable:x4}=j("stream"),SM=k7(),{QlobberTrue:yM}=l5(),a5=uT(),b7={wildcard_one:"+",wildcard_some:"#",separator:"/"};function*vM(_){for(let T of _)yield*T}function*f7(_,T){let A=new yM(b7);A.add(T);for(let[E,L]of _)if(A.test(E))yield L}function*hM(_,T){for(let A of _.values())if(!T[A.brokerId])yield A}function*kM(_,T){for(let[A,E]of _)if(E.has(T))yield A}class g7{#J;#L;#Y;#K;#N;#z;#A;constructor(){this.#J=new Map,this.#L=new Map,this.#Y=new Map,this.#K=new Map,this.#N=new Map,this.#z=0,this.#A=new SM(b7)}storeRetained(_,T){let A=Object.assign({},_);if(A.payload.length===0)this.#J.delete(A.topic);else this.#J.set(A.topic,A);T(null)}createRetainedStreamCombi(_){let T=_.map((A)=>{return f7(this.#J,A)});return x4.from(vM(T))}createRetainedStream(_){return x4.from(f7(this.#J,_))}addSubscriptions(_,T,A){let E=this.#L.get(_.id),L=this.#A;if(!E)E=new Map,this.#L.set(_.id,E),this.#z++;for(let J of T){let X=E.get(J.topic);if(J.qos>0)L.add(J.topic,{clientId:_.id,topic:J.topic,qos:J.qos,rh:J.rh,rap:J.rap,nl:J.nl});else if(X?.qos>0)L.remove(J.topic,{clientId:_.id,topic:J.topic});E.set(J.topic,{qos:J.qos,rh:J.rh,rap:J.rap,nl:J.nl})}A(null,_)}removeSubscriptions(_,T,A){let E=this.#L.get(_.id),L=this.#A;if(E){for(let J of T){let X=E.get(J);if(X!==void 0){if(X.qos>0)L.remove(J,{clientId:_.id,topic:J});E.delete(J)}}if(E.size===0)this.#z--,this.#L.delete(_.id)}A(null,_)}subscriptionsByClient(_,T){let A=null,E=this.#L.get(_.id);if(E){A=[];for(let[L,J]of E)A.push({topic:L,...J})}T(null,A,_)}countOffline(_){return _(null,this.#A.subscriptionsCount,this.#z)}subscriptionsByTopic(_,T){T(null,this.#A.match(_))}cleanSubscriptions(_,T){let A=this.#A,E=this.#L.get(_.id);if(E){for(let[L,J]of E)if(J.qos>0)A.remove(L,{clientId:_.id,topic:L});this.#z--,this.#L.delete(_.id)}T(null,_)}#W(_,T){let A=_.clientId,E=HT(this.#Y,A,[],!0);E[E.length]=new a5(T)}outgoingEnqueue(_,T,A){this.#W(_,T),process.nextTick(A)}outgoingEnqueueCombi(_,T,A){for(let E=0;E<_.length;E++)this.#W(_[E],T);process.nextTick(A)}outgoingUpdate(_,T,A){let E=HT(this.#Y,_.id,[],!0),L;for(let J=0;J<E.length;J++)if(L=E[J],L.brokerId===T.brokerId){if(L.brokerCounter===T.brokerCounter)return L.messageId=T.messageId,A(null,_,T)}else if(L.messageId===T.messageId)return E[J]=T,A(null,_,T);A(Error("no such packet"),_,T)}outgoingClearMessageId(_,T,A){let E=HT(this.#Y,_.id,[],!0),L;for(let J=0;J<E.length;J++)if(L=E[J],L.messageId===T.messageId)return E.splice(J,1),A(null,L);A()}outgoingStream(_){let T=[].concat(HT(this.#Y,_.id,[]));return x4.from(T)}incomingStorePacket(_,T,A){let E=_.id,L=HT(this.#K,E,{},!0);L[T.messageId]=new a5(T),L[T.messageId].messageId=T.messageId,A(null)}incomingGetPacket(_,T,A){let E=_.id,L=HT(this.#K,E,{}),J=null;if(this.#K.set(E,L),!L[T.messageId])J=Error("no such packet");A(J,L[T.messageId])}incomingDelPacket(_,T,A){let E=_.id,L=HT(this.#K,E,{}),J=L[T.messageId],X=null;if(!J)X=Error("no such packet");else delete L[T.messageId];A(X)}putWill(_,T,A){T.brokerId=this.broker.id,T.clientId=_.id,this.#N.set(_.id,T),A(null,_)}getWill(_,T){T(null,this.#N.get(_.id),_)}delWill(_,T){let A=this.#N.get(_.id);this.#N.delete(_.id),T(null,A,_)}streamWill(_={}){return x4.from(hM(this.#N,_))}getClientList(_){return x4.from(kM(this.#L,_))}destroy(_){if(this.#J=null,_)_(null)}}function HT(_,T,A,E=!1){let L=_.get(T);if(L===void 0&&E)_.set(T,A);return L||A}o5.exports=()=>{return new g7};o5.exports.Packet=a5});var d7=W((ek,u7)=>{var f1=j("util");u7.exports=function(_,T){class A extends _{constructor(E){super(E);this.addP=f1.promisify(this.add_async),this.removeP=f1.promisify(this.remove_async),this.matchP=f1.promisify(this.match_async),this.testP=f1.promisify(this.test_async),this.clearP=f1.promisify(this.clear_async),this._get_visitorP=f1.promisify(this.get_visitor_async),this._visit_nextP=f1.promisify(this.visit_next_async),this._get_restorerP=f1.promisify(this.get_restorer_async),this._restore_nextP=f1.promisify(this.restore_next_async),this._match_iterP=f1.promisify(this.match_iter_async),this._match_nextP=f1.promisify(this.match_next_async)}*visit(){let E=this.get_visitor();while(!0){let L=this.visit_next(E);if(L===void 0)break;yield L}}async*visitP(){let E=await this._get_visitorP();while(!0){let L=await this._visit_nextP(E);if(L===void 0)break;yield L}}*match_iter(E,L){let J=super.match_iter(E,L);while(!0){let X=this.match_next(J);if(X===void 0)break;yield X.value}}async*match_iterP(E,L){let J=await this._match_iterP(E,L);while(!0){let X=await this._match_nextP(J);if(X===void 0)break;yield X.value}}get_trie(){let E=new T(this.options),L=E.get_restorer();for(let J of this.visit())L(J);return E.get_trie()}get_restorer(E){let L=super.get_restorer(E);return(J)=>{super.restore_next(L,J)}}async get_restorerP(E){let L=await this._get_restorerP(E);return async(J)=>{await this._restore_nextP(L,J)}}}return A.is_native=!0,A.nonNative=T,A}});var l7=W((p7)=>{var p8=j("util");function J_(_){if(_=_||{},this._separator=_.separator||".",this._wildcard_one=_.wildcard_one||"*",this._wildcard_some=_.wildcard_some||"#",this._max_words=_.max_words||100,this._max_wildcard_somes=_.max_wildcard_somes||3,this._match_empty_levels=_.match_empty_levels,this._trie=new Map,_.cache_adds instanceof Map)this._shortcuts=_.cache_adds;else if(_.cache_adds)this._shortcuts=new Map;if(_.cache_splits>0)this._cache_splits=_.cache_splits,this._split_cache=new Map}J_.prototype._initial_value=function(_){return[_]};J_.prototype._add_value=function(_,T){_[_.length]=T};J_.prototype._add_values=function(_,T){var A,E=_.length,L=T.length;for(A=0;A<L;A+=1)_[E+A]=T[A]};J_.prototype._iter_values=function(_,T){return _[Symbol.iterator](T)};J_.prototype._remove_value=function(_,T){if(T===void 0)return!0;var A=_.lastIndexOf(T);if(A>=0)_.splice(A,1);return _.length===0};J_.prototype._add=function(_,T,A,E){var L,J;if(T===A.length){if(L=E.get(this._separator),L)this._add_value(L,_);else L=this._initial_value(_),E.set(this._separator,L);return L}if(J=A[T],L=E.get(J),!L)L=new Map,E.set(J,L);return this._add(_,T+1,A,L)};J_.prototype._remove=function(_,T,A,E){var L,J,X;if(T===A.length){if(L=E.get(this._separator),L&&this._remove_value(L,_))return E.delete(this._separator),!0;return!1}if(J=A[T],L=E.get(J),!L)return!1;if(X=this._remove(_,T+1,A,L),L.size===0)E.delete(J);return X};J_.prototype._match_some=function(_,T,A,E,L){var J,X;for(X of E.keys())if(X!==this._separator){for(J=T;J<A.length;J+=1)_=this._match(_,J,A,E,L);break}return _};J_.prototype._match=function(_,T,A,E,L){var J,X;if(X=E.get(this._wildcard_some),X)_=this._match_some(_,T,A,X,L),_=this._match(_,A.length,A,X,L);if(T===A.length){if(X=E.get(this._separator),X)if(_.dest)this._add_values(_.dest,_.source,L),this._add_values(_.dest,X,L),_=_.dest;else if(_.source)_.dest=_.source,_.source=X;else this._add_values(_,X,L)}else{if(J=A[T],J!==this._wildcard_one&&J!==this._wildcard_some){if(X=E.get(J),X)_=this._match(_,T+1,A,X,L)}if(J||this._match_empty_levels){if(X=E.get(this._wildcard_one),X)_=this._match(_,T+1,A,X,L)}}return _};J_.prototype._match2=function(_,T,A){var E=this._match({source:_},0,this._split(T,!1),this._trie,A);return E.source||E};J_.prototype._test_some=function(_,T,A,E){var L,J;for(J of E.keys())if(J!==this._separator){for(L=T;L<A.length;L+=1)if(this._test(_,L,A,E))return!0;break}return!1};J_.prototype._test=function(_,T,A,E){var L,J;if(J=E.get(this._wildcard_some),J){if(this._test_some(_,T,A,J)||this._test(_,A.length,A,J))return!0}if(T===A.length){if(J=E.get(this._separator),J&&this.test_values(J,_))return!0}else{if(L=A[T],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=E.get(L),J&&this._test(_,T+1,A,J))return!0}if(L||this._match_empty_levels){if(J=E.get(this._wildcard_one),J&&this._test(_,T+1,A,J))return!0}}return!1};J_.prototype._match_some_iter=function*(_,T,A,E){var L,J;for(J of A.keys())if(J!==this._separator){for(L=_;L<T.length;L+=1)yield*this._match_iter(L,T,A,E);break}};J_.prototype._match_iter=function*(_,T,A,E){var L,J;if(J=A.get(this._wildcard_some),J)yield*this._match_some_iter(_,T,J,E),yield*this._match_iter(T.length,T,J,E);if(_===T.length){if(J=A.get(this._separator),J)yield*this._iter_values(J,E)}else{if(L=T[_],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=A.get(L),J)yield*this._match_iter(_+1,T,J,E)}if(L||this._match_empty_levels){if(J=A.get(this._wildcard_one),J)yield*this._match_iter(_+1,T,J,E)}}};J_.prototype._split_words=function(_){let T=_.split(this._separator);if(T.length>this._max_words)throw Error("too many words");return T};J_.prototype._split=function(_,T){let A;if(this._split_cache){if(A=this._split_cache.get(_),A===void 0){if(A=this._split_words(_),this._split_cache.set(_,A),this._split_cache.size>this._cache_splits)for(let E of this._split_cache.keys()){this._split_cache.delete(E);break}}}else A=this._split_words(_);if(T&&A.reduce((E,L)=>E+(L===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return A};J_.prototype.add=function(_,T){var A=this._shortcuts&&this._shortcuts.get(_);if(A)this._add_value(A,T);else if(A=this._add(T,0,this._split(_,!0),this._trie),this._shortcuts)this._shortcuts.set(_,A);return this};J_.prototype.remove=function(_,T){if(this._remove(T,0,this._split(_,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(_);return this};J_.prototype.match=function(_,T){return this._match2([],_,T)};J_.prototype.match_iter=function(_,T){return this._match_iter(0,this._split(_,!1),this._trie,T)};J_.prototype.test=function(_,T){return this._test(T,0,this._split(_,!1),this._trie)};J_.prototype.test_values=function(_,T){return _.indexOf(T)>=0};J_.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};J_.prototype.get_trie=function(){return this._trie};J_.prototype.visit=function*(){let _=[],T=this._trie.entries(),A=0;while(!0){if(A===0)yield{type:"start_entries"};let E=T.next();if(E.done){yield{type:"end_entries"};let X=_.pop();if(X===void 0)return;[T,A]=X;continue}let[L,J]=E.value;if(yield{type:"entry",key:L},++A,L===this._separator){if(yield{type:"start_values"},J[Symbol.iterator])for(let X of J)yield{type:"value",value:X};else yield{type:"value",value:J};yield{type:"end_values"};continue}_.push([T,A]),T=J.entries(),A=0}};J_.prototype.get_restorer=function(_){_=_||{};let T=[],A=this._trie,E="";return(L)=>{switch(L.type){case"entry":if(A=A||new Map,T.push([A,L.key,E]),A=A.get(L.key),_.cache_adds){if(E)E+=this._separator;E+=L.key}break;case"value":if(A)this._add_value(A,L.value);else A=this._initial_value(L.value);break;case"end_entries":if(A&&A.size===0)A=void 0;case"end_values":let J=T.pop();if(J===void 0)A=void 0,E="";else{let[X,H,Z]=J;if(A){if(_.cache_adds&&this._shortcuts&&L.type==="end_values")this._shortcuts.set(Z,A);X.set(H,A)}A=X,E=Z}break}}};function z1(_){J_.call(this,_)}p8.inherits(z1,J_);z1.prototype._initial_value=function(_){return new Set().add(_)};z1.prototype._add_value=function(_,T){_.add(T)};z1.prototype._add_values=function(_,T){T.forEach(function(A){_.add(A)})};z1.prototype._remove_value=function(_,T){if(T===void 0)return!0;return _.delete(T),_.size===0};z1.prototype.test_values=function(_,T){return _.has(T)};z1.prototype.match=function(_,T){return this._match2(new Set,_,T)};function s1(_){J_.call(this,_)}p8.inherits(s1,J_);s1.prototype._initial_value=function(){return!0};s1.prototype._add_value=function(){};s1.prototype._remove_value=function(){return!0};s1.prototype._iter_values=function*(){yield!0};s1.prototype.test_values=function(){return!0};s1.prototype.match=function(_,T){return this.test(_,T)};var l8=j("stream");function r5(_){l8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}p8.inherits(r5,l8.Readable);r5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function s5(_){l8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}p8.inherits(s5,l8.Writable);s5.prototype._write=function(_,T,A){this._restorer(_),A()};var c7=null;function fM(_){if(_!==c7){let T=d7();J_.nativeString=T(_.QlobberString,J_),J_.nativeNumber=T(_.QlobberNumber,J_),z1.nativeString=T(_.QlobberDedupString,z1),z1.nativeNumber=T(_.QlobberDedupNumber,z1),s1.native=T(_.QlobberTrue,s1),c7=_}return p7}p7.Qlobber=J_;p7.QlobberDedup=z1;p7.QlobberTrue=s1;p7.VisitorStream=r5;p7.RestorerStream=s5;p7.set_native=fM});var i7=W((Tf,n7)=>{var{Qlobber:pM}=l7(),dT=j("assert"),lM=h5();function t1(_){if(!(this instanceof t1))return new t1(_);let T=this;_=_||{},_.matchEmptyLevels=_.matchEmptyLevels===void 0?!0:!!_.matchEmptyLevels,_.separator=_.separator||"/",_.wildcardOne=_.wildcardOne||"+",_.wildcardSome=_.wildcardSome||"#",this._messageQueue=[],this._messageCallbacks=[],this._parallel=lM({results:!1,released:A}),this.concurrency=_.concurrency||0,this.current=0,this._doing=!1,this._matcher=new pM({match_empty_levels:_.matchEmptyLevels,separator:_.separator,wildcard_one:_.wildcardOne,wildcard_some:_.wildcardSome}),this.closed=!1,this._released=A;function A(){T.current--;let E=T._messageQueue.shift(),L=T._messageCallbacks.shift();if(E)T._do(E,L);else T._doing=!1}}Object.defineProperty(t1.prototype,"length",{get:function(){return this._messageQueue.length},enumerable:!0});t1.prototype.on=function(T,A,E){if(dT(T),dT(A),this._matcher.add(T,A),E)setImmediate(E);return this};t1.prototype.removeListener=function(T,A,E){dT(T),dT(A);let L=this;return setImmediate(function(){if(L._matcher.remove(T,A),E)E()}),this};t1.prototype.removeAllListeners=function(T,A){if(dT(T),this._matcher.remove(T),A)setImmediate(A);return this};t1.prototype.emit=function(T,A){if(dT(T),A=A||nM,this.closed)return A(Error("mqemitter is closed"));if(this.concurrency>0&&this.current>=this.concurrency){if(this._messageQueue.push(T),this._messageCallbacks.push(A),!this._doing)process.emitWarning("MqEmitter leak detected",{detail:"For more info check: https://github.com/mcollina/mqemitter/pull/94"}),this._released()}else this._do(T,A);return this};t1.prototype.close=function(T){return this.closed=!0,setImmediate(T),this};t1.prototype._do=function(_,T){this._doing=!0;let A=this._matcher.match(_.topic);return this.current++,this._parallel(this,A,_,T),this};function nM(){}n7.exports=t1});var z_=W((Af,o7)=>{class a7 extends Error{constructor(_){if(!Array.isArray(_))throw TypeError(`Expected input to be an Array, got ${typeof _}`);let T="";for(let A=0;A<_.length;A++)T+=` ${_[A].stack}
|
|
3
|
+
`;super(T);this.name="AggregateError",this.errors=_}}o7.exports={AggregateError:a7,ArrayIsArray(_){return Array.isArray(_)},ArrayPrototypeIncludes(_,T){return _.includes(T)},ArrayPrototypeIndexOf(_,T){return _.indexOf(T)},ArrayPrototypeJoin(_,T){return _.join(T)},ArrayPrototypeMap(_,T){return _.map(T)},ArrayPrototypePop(_,T){return _.pop(T)},ArrayPrototypePush(_,T){return _.push(T)},ArrayPrototypeSlice(_,T,A){return _.slice(T,A)},Error,FunctionPrototypeCall(_,T,...A){return _.call(T,...A)},FunctionPrototypeSymbolHasInstance(_,T){return Function.prototype[Symbol.hasInstance].call(_,T)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(_,T){return Object.defineProperties(_,T)},ObjectDefineProperty(_,T,A){return Object.defineProperty(_,T,A)},ObjectGetOwnPropertyDescriptor(_,T){return Object.getOwnPropertyDescriptor(_,T)},ObjectKeys(_){return Object.keys(_)},ObjectSetPrototypeOf(_,T){return Object.setPrototypeOf(_,T)},Promise,PromisePrototypeCatch(_,T){return _.catch(T)},PromisePrototypeThen(_,T,A){return _.then(T,A)},PromiseReject(_){return Promise.reject(_)},PromiseResolve(_){return Promise.resolve(_)},ReflectApply:Reflect.apply,RegExpPrototypeTest(_,T){return _.test(T)},SafeSet:Set,String,StringPrototypeSlice(_,T,A){return _.slice(T,A)},StringPrototypeToLowerCase(_){return _.toLowerCase()},StringPrototypeToUpperCase(_){return _.toUpperCase()},StringPrototypeTrim(_){return _.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(_,T,A){return _.set(T,A)},Boolean,Uint8Array}});var t5=W((Ef,r7)=>{r7.exports={format(_,...T){return _.replace(/%([sdifj])/g,function(...[A,E]){let L=T.shift();if(E==="f")return L.toFixed(6);else if(E==="j")return JSON.stringify(L);else if(E==="s"&&typeof L==="object")return`${L.constructor!==Object?L.constructor.name:""} {}`.trim();else return L.toString()})},inspect(_){switch(typeof _){case"string":if(_.includes("'")){if(!_.includes('"'))return`"${_}"`;else if(!_.includes("`")&&!_.includes("${"))return`\`${_}\``}return`'${_}'`;case"number":if(isNaN(_))return"NaN";else if(Object.is(_,-0))return String(_);return _;case"bigint":return`${String(_)}n`;case"boolean":case"undefined":return String(_);case"object":return"{}"}}}});var l_=W((Lf,_J)=>{var{format:iM,inspect:n8}=t5(),{AggregateError:aM}=z_(),oM=globalThis.AggregateError||aM,rM=Symbol("kIsNodeError"),sM=["string","function","number","object","Function","Object","boolean","bigint","symbol"],tM=/^([A-Z][a-z0-9]*)+$/,i8={};function ZT(_,T){if(!_)throw new i8.ERR_INTERNAL_ASSERTION(T)}function s7(_){let T="",A=_.length,E=_[0]==="-"?1:0;for(;A>=E+4;A-=3)T=`_${_.slice(A-3,A)}${T}`;return`${_.slice(0,A)}${T}`}function eM(_,T,A){if(typeof T==="function")return ZT(T.length<=A.length,`Code: ${_}; The provided arguments length (${A.length}) does not match the required ones (${T.length}).`),T(...A);let E=(T.match(/%[dfijoOs]/g)||[]).length;if(ZT(E===A.length,`Code: ${_}; The provided arguments length (${A.length}) does not match the required ones (${E}).`),A.length===0)return T;return iM(T,...A)}function g_(_,T,A){if(!A)A=Error;class E extends A{constructor(...L){super(eM(_,T,L))}toString(){return`${this.name} [${_}]: ${this.message}`}}Object.defineProperties(E.prototype,{name:{value:A.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${_}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),E.prototype.code=_,E.prototype[rM]=!0,i8[_]=E}function t7(_){let T="__node_internal_"+_.name;return Object.defineProperty(_,"name",{value:T}),_}function _V(_,T){if(_&&T&&_!==T){if(Array.isArray(T.errors))return T.errors.push(_),T;let A=new oM([T,_],T.message);return A.code=T.code,A}return _||T}class e7 extends Error{constructor(_="The operation was aborted",T=void 0){if(T!==void 0&&typeof T!=="object")throw new i8.ERR_INVALID_ARG_TYPE("options","Object",T);super(_,T);this.code="ABORT_ERR",this.name="AbortError"}}g_("ERR_ASSERTION","%s",Error);g_("ERR_INVALID_ARG_TYPE",(_,T,A)=>{if(ZT(typeof _==="string","'name' must be a string"),!Array.isArray(T))T=[T];let E="The ";if(_.endsWith(" argument"))E+=`${_} `;else E+=`"${_}" ${_.includes(".")?"property":"argument"} `;E+="must be ";let L=[],J=[],X=[];for(let Z of T)if(ZT(typeof Z==="string","All expected entries have to be of type string"),sM.includes(Z))L.push(Z.toLowerCase());else if(tM.test(Z))J.push(Z);else ZT(Z!=="object",'The value "object" should be written as "Object"'),X.push(Z);if(J.length>0){let Z=L.indexOf("object");if(Z!==-1)L.splice(L,Z,1),J.push("Object")}if(L.length>0){switch(L.length){case 1:E+=`of type ${L[0]}`;break;case 2:E+=`one of type ${L[0]} or ${L[1]}`;break;default:{let Z=L.pop();E+=`one of type ${L.join(", ")}, or ${Z}`}}if(J.length>0||X.length>0)E+=" or "}if(J.length>0){switch(J.length){case 1:E+=`an instance of ${J[0]}`;break;case 2:E+=`an instance of ${J[0]} or ${J[1]}`;break;default:{let Z=J.pop();E+=`an instance of ${J.join(", ")}, or ${Z}`}}if(X.length>0)E+=" or "}switch(X.length){case 0:break;case 1:if(X[0].toLowerCase()!==X[0])E+="an ";E+=`${X[0]}`;break;case 2:E+=`one of ${X[0]} or ${X[1]}`;break;default:{let Z=X.pop();E+=`one of ${X.join(", ")}, or ${Z}`}}if(A==null)E+=`. Received ${A}`;else if(typeof A==="function"&&A.name)E+=`. Received function ${A.name}`;else if(typeof A==="object"){var H;if((H=A.constructor)!==null&&H!==void 0&&H.name)E+=`. Received an instance of ${A.constructor.name}`;else{let Z=n8(A,{depth:-1});E+=`. Received ${Z}`}}else{let Z=n8(A,{colors:!1});if(Z.length>25)Z=`${Z.slice(0,25)}...`;E+=`. Received type ${typeof A} (${Z})`}return E},TypeError);g_("ERR_INVALID_ARG_VALUE",(_,T,A="is invalid")=>{let E=n8(T);if(E.length>128)E=E.slice(0,128)+"...";return`The ${_.includes(".")?"property":"argument"} '${_}' ${A}. Received ${E}`},TypeError);g_("ERR_INVALID_RETURN_VALUE",(_,T,A)=>{var E;let L=A!==null&&A!==void 0&&(E=A.constructor)!==null&&E!==void 0&&E.name?`instance of ${A.constructor.name}`:`type ${typeof A}`;return`Expected ${_} to be returned from the "${T}" function but got ${L}.`},TypeError);g_("ERR_MISSING_ARGS",(..._)=>{ZT(_.length>0,"At least one arg needs to be specified");let T,A=_.length;switch(_=(Array.isArray(_)?_:[_]).map((E)=>`"${E}"`).join(" or "),A){case 1:T+=`The ${_[0]} argument`;break;case 2:T+=`The ${_[0]} and ${_[1]} arguments`;break;default:{let E=_.pop();T+=`The ${_.join(", ")}, and ${E} arguments`}break}return`${T} must be specified`},TypeError);g_("ERR_OUT_OF_RANGE",(_,T,A)=>{ZT(T,'Missing "range" argument');let E;if(Number.isInteger(A)&&Math.abs(A)>4294967296)E=s7(String(A));else if(typeof A==="bigint"){E=String(A);let L=BigInt(2)**BigInt(32);if(A>L||A<-L)E=s7(E);E+="n"}else E=n8(A);return`The value of "${_}" is out of range. It must be ${T}. Received ${E}`},RangeError);g_("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);g_("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);g_("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);g_("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);g_("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);g_("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);g_("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);g_("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);g_("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);g_("ERR_STREAM_WRITE_AFTER_END","write after end",Error);g_("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);_J.exports={AbortError:e7,aggregateTwoErrors:t7(_V),hideStackFrames:t7,codes:i8}});var s_=W((Jf,_6)=>{var TV=j("buffer"),{format:AV,inspect:EV}=t5(),{codes:{ERR_INVALID_ARG_TYPE:e5}}=l_(),{kResistStopPropagation:LV,AggregateError:JV,SymbolDispose:XV}=z_(),HV=globalThis.AbortSignal||j("abort-controller").AbortSignal,ZV=globalThis.AbortController||j("abort-controller").AbortController,YV=Object.getPrototypeOf(async function(){}).constructor,TJ=globalThis.Blob||TV.Blob,KV=typeof TJ<"u"?function(T){return T instanceof TJ}:function(T){return!1},AJ=(_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new e5(T,"AbortSignal",_)},GV=(_,T)=>{if(typeof _!=="function")throw new e5(T,"Function",_)};_6.exports={AggregateError:JV,kEmptyObject:Object.freeze({}),once(_){let T=!1;return function(...A){if(T)return;T=!0,_.apply(this,A)}},createDeferredPromise:function(){let _,T;return{promise:new Promise((E,L)=>{_=E,T=L}),resolve:_,reject:T}},promisify(_){return new Promise((T,A)=>{_((E,...L)=>{if(E)return A(E);return T(...L)})})},debuglog(){return function(){}},format:AV,inspect:EV,types:{isAsyncFunction(_){return _ instanceof YV},isArrayBufferView(_){return ArrayBuffer.isView(_)}},isBlob:KV,deprecate(_,T){return _},addAbortListener:j("events").addAbortListener||function(T,A){if(T===void 0)throw new e5("signal","AbortSignal",T);AJ(T,"signal"),GV(A,"listener");let E;if(T.aborted)queueMicrotask(()=>A());else T.addEventListener("abort",A,{__proto__:null,once:!0,[LV]:!0}),E=()=>{T.removeEventListener("abort",A)};return{__proto__:null,[XV](){var L;(L=E)===null||L===void 0||L()}}},AbortSignalAny:HV.any||function(T){if(T.length===1)return T[0];let A=new ZV,E=()=>A.abort();return T.forEach((L)=>{AJ(L,"signals"),L.addEventListener("abort",E,{once:!0})}),A.signal.addEventListener("abort",()=>{T.forEach((L)=>L.removeEventListener("abort",E))},{once:!0}),A.signal}};_6.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var pT=W((Xf,$J)=>{var{ArrayIsArray:A6,ArrayPrototypeIncludes:XJ,ArrayPrototypeJoin:HJ,ArrayPrototypeMap:$V,NumberIsInteger:E6,NumberIsNaN:UV,NumberMAX_SAFE_INTEGER:WV,NumberMIN_SAFE_INTEGER:NV,NumberParseInt:QV,ObjectPrototypeHasOwnProperty:MV,RegExpPrototypeExec:ZJ,String:VV,StringPrototypeToUpperCase:zV,StringPrototypeTrim:FV}=z_(),{hideStackFrames:F1,codes:{ERR_SOCKET_BAD_PORT:CV,ERR_INVALID_ARG_TYPE:n_,ERR_INVALID_ARG_VALUE:cT,ERR_OUT_OF_RANGE:YT,ERR_UNKNOWN_SIGNAL:EJ}}=l_(),{normalizeEncoding:OV}=s_(),{isAsyncFunction:RV,isArrayBufferView:DV}=s_().types,LJ={};function BV(_){return _===(_|0)}function qV(_){return _===_>>>0}var IV=/^[0-7]+$/,PV="must be a 32-bit unsigned integer or an octal string";function jV(_,T,A){if(typeof _>"u")_=A;if(typeof _==="string"){if(ZJ(IV,_)===null)throw new cT(T,_,PV);_=QV(_,8)}return YJ(_,T),_}var xV=F1((_,T,A=NV,E=WV)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!E6(_))throw new YT(T,"an integer",_);if(_<A||_>E)throw new YT(T,`>= ${A} && <= ${E}`,_)}),wV=F1((_,T,A=-2147483648,E=2147483647)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!E6(_))throw new YT(T,"an integer",_);if(_<A||_>E)throw new YT(T,`>= ${A} && <= ${E}`,_)}),YJ=F1((_,T,A=!1)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!E6(_))throw new YT(T,"an integer",_);let E=A?1:0,L=4294967295;if(_<E||_>L)throw new YT(T,`>= ${E} && <= ${L}`,_)});function L6(_,T){if(typeof _!=="string")throw new n_(T,"string",_)}function SV(_,T,A=void 0,E){if(typeof _!=="number")throw new n_(T,"number",_);if(A!=null&&_<A||E!=null&&_>E||(A!=null||E!=null)&&UV(_))throw new YT(T,`${A!=null?`>= ${A}`:""}${A!=null&&E!=null?" && ":""}${E!=null?`<= ${E}`:""}`,_)}var yV=F1((_,T,A)=>{if(!XJ(A,_)){let L="must be one of: "+HJ($V(A,(J)=>typeof J==="string"?`'${J}'`:VV(J)),", ");throw new cT(T,_,L)}});function KJ(_,T){if(typeof _!=="boolean")throw new n_(T,"boolean",_)}function T6(_,T,A){return _==null||!MV(_,T)?A:_[T]}var vV=F1((_,T,A=null)=>{let E=T6(A,"allowArray",!1),L=T6(A,"allowFunction",!1);if(!T6(A,"nullable",!1)&&_===null||!E&&A6(_)||typeof _!=="object"&&(!L||typeof _!=="function"))throw new n_(T,"Object",_)}),hV=F1((_,T)=>{if(_!=null&&typeof _!=="object"&&typeof _!=="function")throw new n_(T,"a dictionary",_)}),a8=F1((_,T,A=0)=>{if(!A6(_))throw new n_(T,"Array",_);if(_.length<A){let E=`must be longer than ${A}`;throw new cT(T,_,E)}});function kV(_,T){a8(_,T);for(let A=0;A<_.length;A++)L6(_[A],`${T}[${A}]`)}function fV(_,T){a8(_,T);for(let A=0;A<_.length;A++)KJ(_[A],`${T}[${A}]`)}function bV(_,T){a8(_,T);for(let A=0;A<_.length;A++){let E=_[A],L=`${T}[${A}]`;if(E==null)throw new n_(L,"AbortSignal",E);GJ(E,L)}}function gV(_,T="signal"){if(L6(_,T),LJ[_]===void 0){if(LJ[zV(_)]!==void 0)throw new EJ(_+" (signals must use all capital letters)");throw new EJ(_)}}var mV=F1((_,T="buffer")=>{if(!DV(_))throw new n_(T,["Buffer","TypedArray","DataView"],_)});function uV(_,T){let A=OV(T),E=_.length;if(A==="hex"&&E%2!==0)throw new cT("encoding",T,`is invalid for data of length ${E}`)}function dV(_,T="Port",A=!0){if(typeof _!=="number"&&typeof _!=="string"||typeof _==="string"&&FV(_).length===0||+_!==+_>>>0||_>65535||_===0&&!A)throw new CV(T,_,A);return _|0}var GJ=F1((_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new n_(T,"AbortSignal",_)}),cV=F1((_,T)=>{if(typeof _!=="function")throw new n_(T,"Function",_)}),pV=F1((_,T)=>{if(typeof _!=="function"||RV(_))throw new n_(T,"Function",_)}),lV=F1((_,T)=>{if(_!==void 0)throw new n_(T,"undefined",_)});function nV(_,T,A){if(!XJ(A,_))throw new n_(T,`('${HJ(A,"|")}')`,_)}var iV=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function JJ(_,T){if(typeof _>"u"||!ZJ(iV,_))throw new cT(T,_,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function aV(_){if(typeof _==="string")return JJ(_,"hints"),_;else if(A6(_)){let T=_.length,A="";if(T===0)return A;for(let E=0;E<T;E++){let L=_[E];if(JJ(L,"hints"),A+=L,E!==T-1)A+=", "}return A}throw new cT("hints",_,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}$J.exports={isInt32:BV,isUint32:qV,parseFileMode:jV,validateArray:a8,validateStringArray:kV,validateBooleanArray:fV,validateAbortSignalArray:bV,validateBoolean:KJ,validateBuffer:mV,validateDictionary:hV,validateEncoding:uV,validateFunction:cV,validateInt32:wV,validateInteger:xV,validateNumber:SV,validateObject:vV,validateOneOf:yV,validatePlainFunction:pV,validatePort:dV,validateSignalName:gV,validateString:L6,validateUint32:YJ,validateUndefined:lV,validateUnion:nV,validateAbortSignal:GJ,validateLinkHeaderValue:aV}});var c0=W((Hf,UJ)=>{UJ.exports=global.process});var _0=W((Zf,PJ)=>{var{SymbolAsyncIterator:WJ,SymbolIterator:NJ,SymbolFor:KT}=z_(),QJ=KT("nodejs.stream.destroyed"),MJ=KT("nodejs.stream.errored"),J6=KT("nodejs.stream.readable"),X6=KT("nodejs.stream.writable"),VJ=KT("nodejs.stream.disturbed"),oV=KT("nodejs.webstream.isClosedPromise"),rV=KT("nodejs.webstream.controllerErrorFunction");function o8(_,T=!1){var A;return!!(_&&typeof _.pipe==="function"&&typeof _.on==="function"&&(!T||typeof _.pause==="function"&&typeof _.resume==="function")&&(!_._writableState||((A=_._readableState)===null||A===void 0?void 0:A.readable)!==!1)&&(!_._writableState||_._readableState))}function r8(_){var T;return!!(_&&typeof _.write==="function"&&typeof _.on==="function"&&(!_._readableState||((T=_._writableState)===null||T===void 0?void 0:T.writable)!==!1))}function sV(_){return!!(_&&typeof _.pipe==="function"&&_._readableState&&typeof _.on==="function"&&typeof _.write==="function")}function e1(_){return _&&(_._readableState||_._writableState||typeof _.write==="function"&&typeof _.on==="function"||typeof _.pipe==="function"&&typeof _.on==="function")}function zJ(_){return!!(_&&!e1(_)&&typeof _.pipeThrough==="function"&&typeof _.getReader==="function"&&typeof _.cancel==="function")}function FJ(_){return!!(_&&!e1(_)&&typeof _.getWriter==="function"&&typeof _.abort==="function")}function CJ(_){return!!(_&&!e1(_)&&typeof _.readable==="object"&&typeof _.writable==="object")}function tV(_){return zJ(_)||FJ(_)||CJ(_)}function eV(_,T){if(_==null)return!1;if(T===!0)return typeof _[WJ]==="function";if(T===!1)return typeof _[NJ]==="function";return typeof _[WJ]==="function"||typeof _[NJ]==="function"}function s8(_){if(!e1(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!!(_.destroyed||_[QJ]||E!==null&&E!==void 0&&E.destroyed)}function OJ(_){if(!r8(_))return null;if(_.writableEnded===!0)return!0;let T=_._writableState;if(T!==null&&T!==void 0&&T.errored)return!1;if(typeof(T===null||T===void 0?void 0:T.ended)!=="boolean")return null;return T.ended}function _z(_,T){if(!r8(_))return null;if(_.writableFinished===!0)return!0;let A=_._writableState;if(A!==null&&A!==void 0&&A.errored)return!1;if(typeof(A===null||A===void 0?void 0:A.finished)!=="boolean")return null;return!!(A.finished||T===!1&&A.ended===!0&&A.length===0)}function Tz(_){if(!o8(_))return null;if(_.readableEnded===!0)return!0;let T=_._readableState;if(!T||T.errored)return!1;if(typeof(T===null||T===void 0?void 0:T.ended)!=="boolean")return null;return T.ended}function RJ(_,T){if(!o8(_))return null;let A=_._readableState;if(A!==null&&A!==void 0&&A.errored)return!1;if(typeof(A===null||A===void 0?void 0:A.endEmitted)!=="boolean")return null;return!!(A.endEmitted||T===!1&&A.ended===!0&&A.length===0)}function DJ(_){if(_&&_[J6]!=null)return _[J6];if(typeof(_===null||_===void 0?void 0:_.readable)!=="boolean")return null;if(s8(_))return!1;return o8(_)&&_.readable&&!RJ(_)}function BJ(_){if(_&&_[X6]!=null)return _[X6];if(typeof(_===null||_===void 0?void 0:_.writable)!=="boolean")return null;if(s8(_))return!1;return r8(_)&&_.writable&&!OJ(_)}function Az(_,T){if(!e1(_))return null;if(s8(_))return!0;if((T===null||T===void 0?void 0:T.readable)!==!1&&DJ(_))return!1;if((T===null||T===void 0?void 0:T.writable)!==!1&&BJ(_))return!1;return!0}function Ez(_){var T,A;if(!e1(_))return null;if(_.writableErrored)return _.writableErrored;return(T=(A=_._writableState)===null||A===void 0?void 0:A.errored)!==null&&T!==void 0?T:null}function Lz(_){var T,A;if(!e1(_))return null;if(_.readableErrored)return _.readableErrored;return(T=(A=_._readableState)===null||A===void 0?void 0:A.errored)!==null&&T!==void 0?T:null}function Jz(_){if(!e1(_))return null;if(typeof _.closed==="boolean")return _.closed;let{_writableState:T,_readableState:A}=_;if(typeof(T===null||T===void 0?void 0:T.closed)==="boolean"||typeof(A===null||A===void 0?void 0:A.closed)==="boolean")return(T===null||T===void 0?void 0:T.closed)||(A===null||A===void 0?void 0:A.closed);if(typeof _._closed==="boolean"&&qJ(_))return _._closed;return null}function qJ(_){return typeof _._closed==="boolean"&&typeof _._defaultKeepAlive==="boolean"&&typeof _._removedConnection==="boolean"&&typeof _._removedContLen==="boolean"}function IJ(_){return typeof _._sent100==="boolean"&&qJ(_)}function Xz(_){var T;return typeof _._consuming==="boolean"&&typeof _._dumped==="boolean"&&((T=_.req)===null||T===void 0?void 0:T.upgradeOrConnect)===void 0}function Hz(_){if(!e1(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!E&&IJ(_)||!!(E&&E.autoDestroy&&E.emitClose&&E.closed===!1)}function Zz(_){var T;return!!(_&&((T=_[VJ])!==null&&T!==void 0?T:_.readableDidRead||_.readableAborted))}function Yz(_){var T,A,E,L,J,X,H,Z,Y,K;return!!(_&&((T=(A=(E=(L=(J=(X=_[MJ])!==null&&X!==void 0?X:_.readableErrored)!==null&&J!==void 0?J:_.writableErrored)!==null&&L!==void 0?L:(H=_._readableState)===null||H===void 0?void 0:H.errorEmitted)!==null&&E!==void 0?E:(Z=_._writableState)===null||Z===void 0?void 0:Z.errorEmitted)!==null&&A!==void 0?A:(Y=_._readableState)===null||Y===void 0?void 0:Y.errored)!==null&&T!==void 0?T:(K=_._writableState)===null||K===void 0?void 0:K.errored))}PJ.exports={isDestroyed:s8,kIsDestroyed:QJ,isDisturbed:Zz,kIsDisturbed:VJ,isErrored:Yz,kIsErrored:MJ,isReadable:DJ,kIsReadable:J6,kIsClosedPromise:oV,kControllerErrorFunction:rV,kIsWritable:X6,isClosed:Jz,isDuplexNodeStream:sV,isFinished:Az,isIterable:eV,isReadableNodeStream:o8,isReadableStream:zJ,isReadableEnded:Tz,isReadableFinished:RJ,isReadableErrored:Lz,isNodeStream:e1,isWebStream:tV,isWritable:BJ,isWritableNodeStream:r8,isWritableStream:FJ,isWritableEnded:OJ,isWritableFinished:_z,isWritableErrored:Ez,isServerRequest:Xz,isServerResponse:IJ,willEmitClose:Hz,isTransformStream:CJ}});var B0=W((Yf,G6)=>{var p0=c0(),{AbortError:fJ,codes:Kz}=l_(),{ERR_INVALID_ARG_TYPE:Gz,ERR_STREAM_PREMATURE_CLOSE:jJ}=Kz,{kEmptyObject:Z6,once:Y6}=s_(),{validateAbortSignal:$z,validateFunction:Uz,validateObject:Wz,validateBoolean:Nz}=pT(),{Promise:Qz,PromisePrototypeThen:Mz,SymbolDispose:bJ}=z_(),{isClosed:Vz,isReadable:xJ,isReadableNodeStream:H6,isReadableStream:zz,isReadableFinished:wJ,isReadableErrored:SJ,isWritable:yJ,isWritableNodeStream:vJ,isWritableStream:Fz,isWritableFinished:hJ,isWritableErrored:kJ,isNodeStream:Cz,willEmitClose:Oz,kIsClosedPromise:Rz}=_0(),lT;function Dz(_){return _.setHeader&&typeof _.abort==="function"}var K6=()=>{};function gJ(_,T,A){var E,L;if(arguments.length===2)A=T,T=Z6;else if(T==null)T=Z6;else Wz(T,"options");if(Uz(A,"callback"),$z(T.signal,"options.signal"),A=Y6(A),zz(_)||Fz(_))return Bz(_,T,A);if(!Cz(_))throw new Gz("stream",["ReadableStream","WritableStream","Stream"],_);let J=(E=T.readable)!==null&&E!==void 0?E:H6(_),X=(L=T.writable)!==null&&L!==void 0?L:vJ(_),H=_._writableState,Z=_._readableState,Y=()=>{if(!_.writable)$()},K=Oz(_)&&H6(_)===J&&vJ(_)===X,G=hJ(_,!1),$=()=>{if(G=!0,_.destroyed)K=!1;if(K&&(!_.readable||J))return;if(!J||U)A.call(_)},U=wJ(_,!1),V=()=>{if(U=!0,_.destroyed)K=!1;if(K&&(!_.writable||X))return;if(!X||G)A.call(_)},N=(f)=>{A.call(_,f)},z=Vz(_),Q=()=>{z=!0;let f=kJ(_)||SJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);if(J&&!U&&H6(_,!0)){if(!wJ(_,!1))return A.call(_,new jJ)}if(X&&!G){if(!hJ(_,!1))return A.call(_,new jJ)}A.call(_)},F=()=>{z=!0;let f=kJ(_)||SJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);A.call(_)},R=()=>{_.req.on("finish",$)};if(Dz(_)){if(_.on("complete",$),!K)_.on("abort",Q);if(_.req)R();else _.on("request",R)}else if(X&&!H)_.on("end",Y),_.on("close",Y);if(!K&&typeof _.aborted==="boolean")_.on("aborted",Q);if(_.on("end",V),_.on("finish",$),T.error!==!1)_.on("error",N);if(_.on("close",Q),z)p0.nextTick(Q);else if(H!==null&&H!==void 0&&H.errorEmitted||Z!==null&&Z!==void 0&&Z.errorEmitted){if(!K)p0.nextTick(F)}else if(!J&&(!K||xJ(_))&&(G||yJ(_)===!1))p0.nextTick(F);else if(!X&&(!K||yJ(_))&&(U||xJ(_)===!1))p0.nextTick(F);else if(Z&&_.req&&_.aborted)p0.nextTick(F);let q=()=>{if(A=K6,_.removeListener("aborted",Q),_.removeListener("complete",$),_.removeListener("abort",Q),_.removeListener("request",R),_.req)_.req.removeListener("finish",$);_.removeListener("end",Y),_.removeListener("close",Y),_.removeListener("finish",$),_.removeListener("end",V),_.removeListener("error",N),_.removeListener("close",Q)};if(T.signal&&!z){let f=()=>{let h=A;q(),h.call(_,new fJ(void 0,{cause:T.signal.reason}))};if(T.signal.aborted)p0.nextTick(f);else{lT=lT||s_().addAbortListener;let h=lT(T.signal,f),b=A;A=Y6((...l)=>{h[bJ](),b.apply(_,l)})}}return q}function Bz(_,T,A){let E=!1,L=K6;if(T.signal)if(L=()=>{E=!0,A.call(_,new fJ(void 0,{cause:T.signal.reason}))},T.signal.aborted)p0.nextTick(L);else{lT=lT||s_().addAbortListener;let X=lT(T.signal,L),H=A;A=Y6((...Z)=>{X[bJ](),H.apply(_,Z)})}let J=(...X)=>{if(!E)p0.nextTick(()=>A.apply(_,X))};return Mz(_[Rz].promise,J,J),K6}function qz(_,T){var A;let E=!1;if(T===null)T=Z6;if((A=T)!==null&&A!==void 0&&A.cleanup)Nz(T.cleanup,"cleanup"),E=T.cleanup;return new Qz((L,J)=>{let X=gJ(_,T,(H)=>{if(E)X();if(H)J(H);else L()})})}G6.exports=gJ;G6.exports.finished=qz});var GT=W((Kf,iJ)=>{var T0=c0(),{aggregateTwoErrors:Iz,codes:{ERR_MULTIPLE_CALLBACK:Pz},AbortError:jz}=l_(),{Symbol:dJ}=z_(),{kIsDestroyed:xz,isDestroyed:wz,isFinished:Sz,isServerRequest:yz}=_0(),cJ=dJ("kDestroy"),$6=dJ("kConstruct");function pJ(_,T,A){if(_){if(_.stack,T&&!T.errored)T.errored=_;if(A&&!A.errored)A.errored=_}}function vz(_,T){let A=this._readableState,E=this._writableState,L=E||A;if(E!==null&&E!==void 0&&E.destroyed||A!==null&&A!==void 0&&A.destroyed){if(typeof T==="function")T();return this}if(pJ(_,E,A),E)E.destroyed=!0;if(A)A.destroyed=!0;if(!L.constructed)this.once(cJ,function(J){mJ(this,Iz(J,_),T)});else mJ(this,_,T);return this}function mJ(_,T,A){let E=!1;function L(J){if(E)return;E=!0;let{_readableState:X,_writableState:H}=_;if(pJ(J,H,X),H)H.closed=!0;if(X)X.closed=!0;if(typeof A==="function")A(J);if(J)T0.nextTick(hz,_,J);else T0.nextTick(lJ,_)}try{_._destroy(T||null,L)}catch(J){L(J)}}function hz(_,T){U6(_,T),lJ(_)}function lJ(_){let{_readableState:T,_writableState:A}=_;if(A)A.closeEmitted=!0;if(T)T.closeEmitted=!0;if(A!==null&&A!==void 0&&A.emitClose||T!==null&&T!==void 0&&T.emitClose)_.emit("close")}function U6(_,T){let{_readableState:A,_writableState:E}=_;if(E!==null&&E!==void 0&&E.errorEmitted||A!==null&&A!==void 0&&A.errorEmitted)return;if(E)E.errorEmitted=!0;if(A)A.errorEmitted=!0;_.emit("error",T)}function kz(){let _=this._readableState,T=this._writableState;if(_)_.constructed=!0,_.closed=!1,_.closeEmitted=!1,_.destroyed=!1,_.errored=null,_.errorEmitted=!1,_.reading=!1,_.ended=_.readable===!1,_.endEmitted=_.readable===!1;if(T)T.constructed=!0,T.destroyed=!1,T.closed=!1,T.closeEmitted=!1,T.errored=null,T.errorEmitted=!1,T.finalCalled=!1,T.prefinished=!1,T.ended=T.writable===!1,T.ending=T.writable===!1,T.finished=T.writable===!1}function W6(_,T,A){let{_readableState:E,_writableState:L}=_;if(L!==null&&L!==void 0&&L.destroyed||E!==null&&E!==void 0&&E.destroyed)return this;if(E!==null&&E!==void 0&&E.autoDestroy||L!==null&&L!==void 0&&L.autoDestroy)_.destroy(T);else if(T){if(T.stack,L&&!L.errored)L.errored=T;if(E&&!E.errored)E.errored=T;if(A)T0.nextTick(U6,_,T);else U6(_,T)}}function fz(_,T){if(typeof _._construct!=="function")return;let{_readableState:A,_writableState:E}=_;if(A)A.constructed=!1;if(E)E.constructed=!1;if(_.once($6,T),_.listenerCount($6)>1)return;T0.nextTick(bz,_)}function bz(_){let T=!1;function A(E){if(T){W6(_,E!==null&&E!==void 0?E:new Pz);return}T=!0;let{_readableState:L,_writableState:J}=_,X=J||L;if(L)L.constructed=!0;if(J)J.constructed=!0;if(X.destroyed)_.emit(cJ,E);else if(E)W6(_,E,!0);else T0.nextTick(gz,_)}try{_._construct((E)=>{T0.nextTick(A,E)})}catch(E){T0.nextTick(A,E)}}function gz(_){_.emit($6)}function uJ(_){return(_===null||_===void 0?void 0:_.setHeader)&&typeof _.abort==="function"}function nJ(_){_.emit("close")}function mz(_,T){_.emit("error",T),T0.nextTick(nJ,_)}function uz(_,T){if(!_||wz(_))return;if(!T&&!Sz(_))T=new jz;if(yz(_))_.socket=null,_.destroy(T);else if(uJ(_))_.abort();else if(uJ(_.req))_.req.abort();else if(typeof _.destroy==="function")_.destroy(T);else if(typeof _.close==="function")_.close();else if(T)T0.nextTick(mz,_,T);else T0.nextTick(nJ,_);if(!_.destroyed)_[xz]=!0}iJ.exports={construct:fz,destroyer:uz,destroy:vz,undestroy:kz,errorOrDestroy:W6}});var _A=W((Gf,oJ)=>{var{ArrayIsArray:dz,ObjectSetPrototypeOf:aJ}=z_(),{EventEmitter:t8}=j("events");function e8(_){t8.call(this,_)}aJ(e8.prototype,t8.prototype);aJ(e8,t8);e8.prototype.pipe=function(_,T){let A=this;function E(K){if(_.writable&&_.write(K)===!1&&A.pause)A.pause()}A.on("data",E);function L(){if(A.readable&&A.resume)A.resume()}if(_.on("drain",L),!_._isStdio&&(!T||T.end!==!1))A.on("end",X),A.on("close",H);let J=!1;function X(){if(J)return;J=!0,_.end()}function H(){if(J)return;if(J=!0,typeof _.destroy==="function")_.destroy()}function Z(K){if(Y(),t8.listenerCount(this,"error")===0)this.emit("error",K)}N6(A,"error",Z),N6(_,"error",Z);function Y(){A.removeListener("data",E),_.removeListener("drain",L),A.removeListener("end",X),A.removeListener("close",H),A.removeListener("error",Z),_.removeListener("error",Z),A.removeListener("end",Y),A.removeListener("close",Y),_.removeListener("close",Y)}return A.on("end",Y),A.on("close",Y),_.on("close",Y),_.emit("pipe",A),_};function N6(_,T,A){if(typeof _.prependListener==="function")return _.prependListener(T,A);if(!_._events||!_._events[T])_.on(T,A);else if(dz(_._events[T]))_._events[T].unshift(A);else _._events[T]=[A,_._events[T]]}oJ.exports={Stream:e8,prependListener:N6}});var w4=W((oz,TA)=>{var{SymbolDispose:cz}=z_(),{AbortError:rJ,codes:pz}=l_(),{isNodeStream:sJ,isWebStream:lz,kControllerErrorFunction:nz}=_0(),iz=B0(),{ERR_INVALID_ARG_TYPE:tJ}=pz,Q6,az=(_,T)=>{if(typeof _!=="object"||!("aborted"in _))throw new tJ(T,"AbortSignal",_)};oz.addAbortSignal=function(T,A){if(az(T,"signal"),!sJ(A)&&!lz(A))throw new tJ("stream",["ReadableStream","WritableStream","Stream"],A);return oz.addAbortSignalNoValidate(T,A)};oz.addAbortSignalNoValidate=function(_,T){if(typeof _!=="object"||!("aborted"in _))return T;let A=sJ(T)?()=>{T.destroy(new rJ(void 0,{cause:_.reason}))}:()=>{T[nz](new rJ(void 0,{cause:_.reason}))};if(_.aborted)A();else{Q6=Q6||s_().addAbortListener;let E=Q6(_,A);iz(T,E[cz])}return T}});var TX=W(($f,_X)=>{var{StringPrototypeSlice:eJ,SymbolIterator:tz,TypedArrayPrototypeSet:AA,Uint8Array:ez}=z_(),{Buffer:M6}=j("buffer"),{inspect:_F}=s_();_X.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(T){let A={data:T,next:null};if(this.length>0)this.tail.next=A;else this.head=A;this.tail=A,++this.length}unshift(T){let A={data:T,next:this.head};if(this.length===0)this.tail=A;this.head=A,++this.length}shift(){if(this.length===0)return;let T=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,T}clear(){this.head=this.tail=null,this.length=0}join(T){if(this.length===0)return"";let A=this.head,E=""+A.data;while((A=A.next)!==null)E+=T+A.data;return E}concat(T){if(this.length===0)return M6.alloc(0);let A=M6.allocUnsafe(T>>>0),E=this.head,L=0;while(E)AA(A,E.data,L),L+=E.data.length,E=E.next;return A}consume(T,A){let E=this.head.data;if(T<E.length){let L=E.slice(0,T);return this.head.data=E.slice(T),L}if(T===E.length)return this.shift();return A?this._getString(T):this._getBuffer(T)}first(){return this.head.data}*[tz](){for(let T=this.head;T;T=T.next)yield T.data}_getString(T){let A="",E=this.head,L=0;do{let J=E.data;if(T>J.length)A+=J,T-=J.length;else{if(T===J.length)if(A+=J,++L,E.next)this.head=E.next;else this.head=this.tail=null;else A+=eJ(J,0,T),this.head=E,E.data=eJ(J,T);break}++L}while((E=E.next)!==null);return this.length-=L,A}_getBuffer(T){let A=M6.allocUnsafe(T),E=T,L=this.head,J=0;do{let X=L.data;if(T>X.length)AA(A,X,E-T),T-=X.length;else{if(T===X.length)if(AA(A,X,E-T),++J,L.next)this.head=L.next;else this.head=this.tail=null;else AA(A,new ez(X.buffer,X.byteOffset,T),E-T),this.head=L,L.data=X.slice(T);break}++J}while((L=L.next)!==null);return this.length-=J,A}[Symbol.for("nodejs.util.inspect.custom")](T,A){return _F(this,{...A,depth:0,customInspect:!1})}}});var S4=W((Uf,JX)=>{var{MathFloor:TF,NumberIsInteger:AF}=z_(),{validateInteger:EF}=pT(),{ERR_INVALID_ARG_VALUE:LF}=l_().codes,AX=16384,EX=16;function JF(_,T,A){return _.highWaterMark!=null?_.highWaterMark:T?_[A]:null}function LX(_){return _?EX:AX}function XF(_,T){if(EF(T,"value",0),_)EX=T;else AX=T}function HF(_,T,A,E){let L=JF(T,E,A);if(L!=null){if(!AF(L)||L<0){let J=E?`options.${A}`:"options.highWaterMark";throw new LF(J,L)}return TF(L)}return LX(_.objectMode)}JX.exports={getHighWaterMark:HF,getDefaultHighWaterMark:LX,setDefaultHighWaterMark:XF}});var ZX=W((V6,HX)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var EA=j("buffer"),A0=EA.Buffer;function XX(_,T){for(var A in _)T[A]=_[A]}if(A0.from&&A0.alloc&&A0.allocUnsafe&&A0.allocUnsafeSlow)HX.exports=EA;else XX(EA,V6),V6.Buffer=$T;function $T(_,T,A){return A0(_,T,A)}$T.prototype=Object.create(A0.prototype);XX(A0,$T);$T.from=function(_,T,A){if(typeof _==="number")throw TypeError("Argument must not be a number");return A0(_,T,A)};$T.alloc=function(_,T,A){if(typeof _!=="number")throw TypeError("Argument must be a number");var E=A0(_);if(T!==void 0)if(typeof A==="string")E.fill(T,A);else E.fill(T);else E.fill(0);return E};$T.allocUnsafe=function(_){if(typeof _!=="number")throw TypeError("Argument must be a number");return A0(_)};$T.allocUnsafeSlow=function(_){if(typeof _!=="number")throw TypeError("Argument must be a number");return EA.SlowBuffer(_)}});var KX=W((CF)=>{var F6=ZX().Buffer,YX=F6.isEncoding||function(_){switch(_=""+_,_&&_.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function ZF(_){if(!_)return"utf8";var T;while(!0)switch(_){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return _;default:if(T)return;_=(""+_).toLowerCase(),T=!0}}function YF(_){var T=ZF(_);if(typeof T!=="string"&&(F6.isEncoding===YX||!YX(_)))throw Error("Unknown encoding: "+_);return T||_}CF.StringDecoder=y4;function y4(_){this.encoding=YF(_);var T;switch(this.encoding){case"utf16le":this.text=NF,this.end=QF,T=4;break;case"utf8":this.fillLast=$F,T=4;break;case"base64":this.text=MF,this.end=VF,T=3;break;default:this.write=zF,this.end=FF;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=F6.allocUnsafe(T)}y4.prototype.write=function(_){if(_.length===0)return"";var T,A;if(this.lastNeed){if(T=this.fillLast(_),T===void 0)return"";A=this.lastNeed,this.lastNeed=0}else A=0;if(A<_.length)return T?T+this.text(_,A):this.text(_,A);return T||""};y4.prototype.end=WF;y4.prototype.text=UF;y4.prototype.fillLast=function(_){if(this.lastNeed<=_.length)return _.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);_.copy(this.lastChar,this.lastTotal-this.lastNeed,0,_.length),this.lastNeed-=_.length};function z6(_){if(_<=127)return 0;else if(_>>5===6)return 2;else if(_>>4===14)return 3;else if(_>>3===30)return 4;return _>>6===2?-1:-2}function KF(_,T,A){var E=T.length-1;if(E<A)return 0;var L=z6(T[E]);if(L>=0){if(L>0)_.lastNeed=L-1;return L}if(--E<A||L===-2)return 0;if(L=z6(T[E]),L>=0){if(L>0)_.lastNeed=L-2;return L}if(--E<A||L===-2)return 0;if(L=z6(T[E]),L>=0){if(L>0)if(L===2)L=0;else _.lastNeed=L-3;return L}return 0}function GF(_,T,A){if((T[0]&192)!==128)return _.lastNeed=0,"\uFFFD";if(_.lastNeed>1&&T.length>1){if((T[1]&192)!==128)return _.lastNeed=1,"\uFFFD";if(_.lastNeed>2&&T.length>2){if((T[2]&192)!==128)return _.lastNeed=2,"\uFFFD"}}}function $F(_){var T=this.lastTotal-this.lastNeed,A=GF(this,_,T);if(A!==void 0)return A;if(this.lastNeed<=_.length)return _.copy(this.lastChar,T,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);_.copy(this.lastChar,T,0,_.length),this.lastNeed-=_.length}function UF(_,T){var A=KF(this,_,T);if(!this.lastNeed)return _.toString("utf8",T);this.lastTotal=A;var E=_.length-(A-this.lastNeed);return _.copy(this.lastChar,0,E),_.toString("utf8",T,E)}function WF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+"\uFFFD";return T}function NF(_,T){if((_.length-T)%2===0){var A=_.toString("utf16le",T);if(A){var E=A.charCodeAt(A.length-1);if(E>=55296&&E<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=_[_.length-2],this.lastChar[1]=_[_.length-1],A.slice(0,-1)}return A}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=_[_.length-1],_.toString("utf16le",T,_.length-1)}function QF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed){var A=this.lastTotal-this.lastNeed;return T+this.lastChar.toString("utf16le",0,A)}return T}function MF(_,T){var A=(_.length-T)%3;if(A===0)return _.toString("base64",T);if(this.lastNeed=3-A,this.lastTotal=3,A===1)this.lastChar[0]=_[_.length-1];else this.lastChar[0]=_[_.length-2],this.lastChar[1]=_[_.length-1];return _.toString("base64",T,_.length-A)}function VF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+this.lastChar.toString("base64",0,3-this.lastNeed);return T}function zF(_){return _.toString(this.encoding)}function FF(_){return _&&_.length?this.write(_):""}});var C6=W((Nf,WX)=>{var GX=c0(),{PromisePrototypeThen:RF,SymbolAsyncIterator:$X,SymbolIterator:UX}=z_(),{Buffer:DF}=j("buffer"),{ERR_INVALID_ARG_TYPE:BF,ERR_STREAM_NULL_VALUES:qF}=l_().codes;function IF(_,T,A){let E;if(typeof T==="string"||T instanceof DF)return new _({objectMode:!0,...A,read(){this.push(T),this.push(null)}});let L;if(T&&T[$X])L=!0,E=T[$X]();else if(T&&T[UX])L=!1,E=T[UX]();else throw new BF("iterable",["Iterable"],T);let J=new _({objectMode:!0,highWaterMark:1,...A}),X=!1;J._read=function(){if(!X)X=!0,Z()},J._destroy=function(Y,K){RF(H(Y),()=>GX.nextTick(K,Y),(G)=>GX.nextTick(K,G||Y))};async function H(Y){let K=Y!==void 0&&Y!==null,G=typeof E.throw==="function";if(K&&G){let{value:$,done:U}=await E.throw(Y);if(await $,U)return}if(typeof E.return==="function"){let{value:$}=await E.return();await $}}async function Z(){for(;;){try{let{value:Y,done:K}=L?await E.next():E.next();if(K)J.push(null);else{let G=Y&&typeof Y.then==="function"?await Y:Y;if(G===null)throw X=!1,new qF;else if(J.push(G))continue;else X=!1}}catch(Y){J.destroy(Y)}break}}return J}WX.exports=IF});var h4=W((Qf,SX)=>{var b1=c0(),{ArrayPrototypeIndexOf:PF,NumberIsInteger:jF,NumberIsNaN:xF,NumberParseInt:wF,ObjectDefineProperties:j6,ObjectKeys:SF,ObjectSetPrototypeOf:MX,Promise:VX,SafeSet:yF,SymbolAsyncDispose:vF,SymbolAsyncIterator:hF,Symbol:kF}=z_();SX.exports=s;s.ReadableState=HA;var{EventEmitter:fF}=j("events"),{Stream:l0,prependListener:bF}=_A(),{Buffer:O6}=j("buffer"),{addAbortSignal:gF}=w4(),zX=B0(),A_=s_().debuglog("stream",(_)=>{A_=_}),mF=TX(),aT=GT(),{getHighWaterMark:uF,getDefaultHighWaterMark:dF}=S4(),{aggregateTwoErrors:NX,codes:{ERR_INVALID_ARG_TYPE:cF,ERR_METHOD_NOT_IMPLEMENTED:pF,ERR_OUT_OF_RANGE:lF,ERR_STREAM_PUSH_AFTER_EOF:nF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:iF},AbortError:aF}=l_(),{validateObject:oF}=pT(),UT=kF("kPaused"),{StringDecoder:FX}=KX(),rF=C6();MX(s.prototype,l0.prototype);MX(s,l0);var R6=()=>{},{errorOrDestroy:nT}=aT,iT=1,sF=2,CX=4,v4=8,OX=16,LA=32,JA=64,RX=128,tF=256,eF=512,_C=1024,I6=2048,P6=4096,TC=8192,AC=16384,EC=32768,DX=65536,LC=131072,JC=262144;function x_(_){return{enumerable:!1,get(){return(this.state&_)!==0},set(T){if(T)this.state|=_;else this.state&=~_}}}j6(HA.prototype,{objectMode:x_(iT),ended:x_(sF),endEmitted:x_(CX),reading:x_(v4),constructed:x_(OX),sync:x_(LA),needReadable:x_(JA),emittedReadable:x_(RX),readableListening:x_(tF),resumeScheduled:x_(eF),errorEmitted:x_(_C),emitClose:x_(I6),autoDestroy:x_(P6),destroyed:x_(TC),closed:x_(AC),closeEmitted:x_(EC),multiAwaitDrain:x_(DX),readingMore:x_(LC),dataEmitted:x_(JC)});function HA(_,T,A){if(typeof A!=="boolean")A=T instanceof E0();if(this.state=I6|P6|OX|LA,_&&_.objectMode)this.state|=iT;if(A&&_&&_.readableObjectMode)this.state|=iT;if(this.highWaterMark=_?uF(this,_,"readableHighWaterMark",A):dF(!1),this.buffer=new mF,this.length=0,this.pipes=[],this.flowing=null,this[UT]=null,_&&_.emitClose===!1)this.state&=~I6;if(_&&_.autoDestroy===!1)this.state&=~P6;if(this.errored=null,this.defaultEncoding=_&&_.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,_&&_.encoding)this.decoder=new FX(_.encoding),this.encoding=_.encoding}function s(_){if(!(this instanceof s))return new s(_);let T=this instanceof E0();if(this._readableState=new HA(_,this,T),_){if(typeof _.read==="function")this._read=_.read;if(typeof _.destroy==="function")this._destroy=_.destroy;if(typeof _.construct==="function")this._construct=_.construct;if(_.signal&&!T)gF(_.signal,this)}l0.call(this,_),aT.construct(this,()=>{if(this._readableState.needReadable)XA(this,this._readableState)})}s.prototype.destroy=aT.destroy;s.prototype._undestroy=aT.undestroy;s.prototype._destroy=function(_,T){T(_)};s.prototype[fF.captureRejectionSymbol]=function(_){this.destroy(_)};s.prototype[vF]=function(){let _;if(!this.destroyed)_=this.readableEnded?null:new aF,this.destroy(_);return new VX((T,A)=>zX(this,(E)=>E&&E!==_?A(E):T(null)))};s.prototype.push=function(_,T){return BX(this,_,T,!1)};s.prototype.unshift=function(_,T){return BX(this,_,T,!0)};function BX(_,T,A,E){A_("readableAddChunk",T);let L=_._readableState,J;if((L.state&iT)===0){if(typeof T==="string"){if(A=A||L.defaultEncoding,L.encoding!==A)if(E&&L.encoding)T=O6.from(T,A).toString(L.encoding);else T=O6.from(T,A),A=""}else if(T instanceof O6)A="";else if(l0._isUint8Array(T))T=l0._uint8ArrayToBuffer(T),A="";else if(T!=null)J=new cF("chunk",["string","Buffer","Uint8Array"],T)}if(J)nT(_,J);else if(T===null)L.state&=~v4,ZC(_,L);else if((L.state&iT)!==0||T&&T.length>0)if(E)if((L.state&CX)!==0)nT(_,new iF);else if(L.destroyed||L.errored)return!1;else D6(_,L,T,!0);else if(L.ended)nT(_,new nF);else if(L.destroyed||L.errored)return!1;else if(L.state&=~v4,L.decoder&&!A)if(T=L.decoder.write(T),L.objectMode||T.length!==0)D6(_,L,T,!1);else XA(_,L);else D6(_,L,T,!1);else if(!E)L.state&=~v4,XA(_,L);return!L.ended&&(L.length<L.highWaterMark||L.length===0)}function D6(_,T,A,E){if(T.flowing&&T.length===0&&!T.sync&&_.listenerCount("data")>0){if((T.state&DX)!==0)T.awaitDrainWriters.clear();else T.awaitDrainWriters=null;T.dataEmitted=!0,_.emit("data",A)}else{if(T.length+=T.objectMode?1:A.length,E)T.buffer.unshift(A);else T.buffer.push(A);if((T.state&JA)!==0)ZA(_)}XA(_,T)}s.prototype.isPaused=function(){let _=this._readableState;return _[UT]===!0||_.flowing===!1};s.prototype.setEncoding=function(_){let T=new FX(_);this._readableState.decoder=T,this._readableState.encoding=this._readableState.decoder.encoding;let A=this._readableState.buffer,E="";for(let L of A)E+=T.write(L);if(A.clear(),E!=="")A.push(E);return this._readableState.length=E.length,this};var XC=1073741824;function HC(_){if(_>XC)throw new lF("size","<= 1GiB",_);else _--,_|=_>>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++;return _}function QX(_,T){if(_<=0||T.length===0&&T.ended)return 0;if((T.state&iT)!==0)return 1;if(xF(_)){if(T.flowing&&T.length)return T.buffer.first().length;return T.length}if(_<=T.length)return _;return T.ended?T.length:0}s.prototype.read=function(_){if(A_("read",_),_===void 0)_=NaN;else if(!jF(_))_=wF(_,10);let T=this._readableState,A=_;if(_>T.highWaterMark)T.highWaterMark=HC(_);if(_!==0)T.state&=~RX;if(_===0&&T.needReadable&&((T.highWaterMark!==0?T.length>=T.highWaterMark:T.length>0)||T.ended)){if(A_("read: emitReadable",T.length,T.ended),T.length===0&&T.ended)B6(this);else ZA(this);return null}if(_=QX(_,T),_===0&&T.ended){if(T.length===0)B6(this);return null}let E=(T.state&JA)!==0;if(A_("need readable",E),T.length===0||T.length-_<T.highWaterMark)E=!0,A_("length less than watermark",E);if(T.ended||T.reading||T.destroyed||T.errored||!T.constructed)E=!1,A_("reading, ended or constructing",E);else if(E){if(A_("do read"),T.state|=v4|LA,T.length===0)T.state|=JA;try{this._read(T.highWaterMark)}catch(J){nT(this,J)}if(T.state&=~LA,!T.reading)_=QX(A,T)}let L;if(_>0)L=xX(_,T);else L=null;if(L===null)T.needReadable=T.length<=T.highWaterMark,_=0;else if(T.length-=_,T.multiAwaitDrain)T.awaitDrainWriters.clear();else T.awaitDrainWriters=null;if(T.length===0){if(!T.ended)T.needReadable=!0;if(A!==_&&T.ended)B6(this)}if(L!==null&&!T.errorEmitted&&!T.closeEmitted)T.dataEmitted=!0,this.emit("data",L);return L};function ZC(_,T){if(A_("onEofChunk"),T.ended)return;if(T.decoder){let A=T.decoder.end();if(A&&A.length)T.buffer.push(A),T.length+=T.objectMode?1:A.length}if(T.ended=!0,T.sync)ZA(_);else T.needReadable=!1,T.emittedReadable=!0,qX(_)}function ZA(_){let T=_._readableState;if(A_("emitReadable",T.needReadable,T.emittedReadable),T.needReadable=!1,!T.emittedReadable)A_("emitReadable",T.flowing),T.emittedReadable=!0,b1.nextTick(qX,_)}function qX(_){let T=_._readableState;if(A_("emitReadable_",T.destroyed,T.length,T.ended),!T.destroyed&&!T.errored&&(T.length||T.ended))_.emit("readable"),T.emittedReadable=!1;T.needReadable=!T.flowing&&!T.ended&&T.length<=T.highWaterMark,PX(_)}function XA(_,T){if(!T.readingMore&&T.constructed)T.readingMore=!0,b1.nextTick(YC,_,T)}function YC(_,T){while(!T.reading&&!T.ended&&(T.length<T.highWaterMark||T.flowing&&T.length===0)){let A=T.length;if(A_("maybeReadMore read 0"),_.read(0),A===T.length)break}T.readingMore=!1}s.prototype._read=function(_){throw new pF("_read()")};s.prototype.pipe=function(_,T){let A=this,E=this._readableState;if(E.pipes.length===1){if(!E.multiAwaitDrain)E.multiAwaitDrain=!0,E.awaitDrainWriters=new yF(E.awaitDrainWriters?[E.awaitDrainWriters]:[])}E.pipes.push(_),A_("pipe count=%d opts=%j",E.pipes.length,T);let J=(!T||T.end!==!1)&&_!==b1.stdout&&_!==b1.stderr?H:z;if(E.endEmitted)b1.nextTick(J);else A.once("end",J);_.on("unpipe",X);function X(Q,F){if(A_("onunpipe"),Q===A){if(F&&F.hasUnpiped===!1)F.hasUnpiped=!0,K()}}function H(){A_("onend"),_.end()}let Z,Y=!1;function K(){if(A_("cleanup"),_.removeListener("close",V),_.removeListener("finish",N),Z)_.removeListener("drain",Z);if(_.removeListener("error",U),_.removeListener("unpipe",X),A.removeListener("end",H),A.removeListener("end",z),A.removeListener("data",$),Y=!0,Z&&E.awaitDrainWriters&&(!_._writableState||_._writableState.needDrain))Z()}function G(){if(!Y){if(E.pipes.length===1&&E.pipes[0]===_)A_("false write response, pause",0),E.awaitDrainWriters=_,E.multiAwaitDrain=!1;else if(E.pipes.length>1&&E.pipes.includes(_))A_("false write response, pause",E.awaitDrainWriters.size),E.awaitDrainWriters.add(_);A.pause()}if(!Z)Z=KC(A,_),_.on("drain",Z)}A.on("data",$);function $(Q){A_("ondata");let F=_.write(Q);if(A_("dest.write",F),F===!1)G()}function U(Q){if(A_("onerror",Q),z(),_.removeListener("error",U),_.listenerCount("error")===0){let F=_._writableState||_._readableState;if(F&&!F.errorEmitted)nT(_,Q);else _.emit("error",Q)}}bF(_,"error",U);function V(){_.removeListener("finish",N),z()}_.once("close",V);function N(){A_("onfinish"),_.removeListener("close",V),z()}_.once("finish",N);function z(){A_("unpipe"),A.unpipe(_)}if(_.emit("pipe",A),_.writableNeedDrain===!0)G();else if(!E.flowing)A_("pipe resume"),A.resume();return _};function KC(_,T){return function(){let E=_._readableState;if(E.awaitDrainWriters===T)A_("pipeOnDrain",1),E.awaitDrainWriters=null;else if(E.multiAwaitDrain)A_("pipeOnDrain",E.awaitDrainWriters.size),E.awaitDrainWriters.delete(T);if((!E.awaitDrainWriters||E.awaitDrainWriters.size===0)&&_.listenerCount("data"))_.resume()}}s.prototype.unpipe=function(_){let T=this._readableState,A={hasUnpiped:!1};if(T.pipes.length===0)return this;if(!_){let L=T.pipes;T.pipes=[],this.pause();for(let J=0;J<L.length;J++)L[J].emit("unpipe",this,{hasUnpiped:!1});return this}let E=PF(T.pipes,_);if(E===-1)return this;if(T.pipes.splice(E,1),T.pipes.length===0)this.pause();return _.emit("unpipe",this,A),this};s.prototype.on=function(_,T){let A=l0.prototype.on.call(this,_,T),E=this._readableState;if(_==="data"){if(E.readableListening=this.listenerCount("readable")>0,E.flowing!==!1)this.resume()}else if(_==="readable"){if(!E.endEmitted&&!E.readableListening){if(E.readableListening=E.needReadable=!0,E.flowing=!1,E.emittedReadable=!1,A_("on readable",E.length,E.reading),E.length)ZA(this);else if(!E.reading)b1.nextTick(GC,this)}}return A};s.prototype.addListener=s.prototype.on;s.prototype.removeListener=function(_,T){let A=l0.prototype.removeListener.call(this,_,T);if(_==="readable")b1.nextTick(IX,this);return A};s.prototype.off=s.prototype.removeListener;s.prototype.removeAllListeners=function(_){let T=l0.prototype.removeAllListeners.apply(this,arguments);if(_==="readable"||_===void 0)b1.nextTick(IX,this);return T};function IX(_){let T=_._readableState;if(T.readableListening=_.listenerCount("readable")>0,T.resumeScheduled&&T[UT]===!1)T.flowing=!0;else if(_.listenerCount("data")>0)_.resume();else if(!T.readableListening)T.flowing=null}function GC(_){A_("readable nexttick read 0"),_.read(0)}s.prototype.resume=function(){let _=this._readableState;if(!_.flowing)A_("resume"),_.flowing=!_.readableListening,$C(this,_);return _[UT]=!1,this};function $C(_,T){if(!T.resumeScheduled)T.resumeScheduled=!0,b1.nextTick(UC,_,T)}function UC(_,T){if(A_("resume",T.reading),!T.reading)_.read(0);if(T.resumeScheduled=!1,_.emit("resume"),PX(_),T.flowing&&!T.reading)_.read(0)}s.prototype.pause=function(){if(A_("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)A_("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState[UT]=!0,this};function PX(_){let T=_._readableState;A_("flow",T.flowing);while(T.flowing&&_.read()!==null);}s.prototype.wrap=function(_){let T=!1;_.on("data",(E)=>{if(!this.push(E)&&_.pause)T=!0,_.pause()}),_.on("end",()=>{this.push(null)}),_.on("error",(E)=>{nT(this,E)}),_.on("close",()=>{this.destroy()}),_.on("destroy",()=>{this.destroy()}),this._read=()=>{if(T&&_.resume)T=!1,_.resume()};let A=SF(_);for(let E=1;E<A.length;E++){let L=A[E];if(this[L]===void 0&&typeof _[L]==="function")this[L]=_[L].bind(_)}return this};s.prototype[hF]=function(){return jX(this)};s.prototype.iterator=function(_){if(_!==void 0)oF(_,"options");return jX(this,_)};function jX(_,T){if(typeof _.read!=="function")_=s.wrap(_,{objectMode:!0});let A=WC(_,T);return A.stream=_,A}async function*WC(_,T){let A=R6;function E(X){if(this===_)A(),A=R6;else A=X}_.on("readable",E);let L,J=zX(_,{writable:!1},(X)=>{L=X?NX(L,X):null,A(),A=R6});try{while(!0){let X=_.destroyed?null:_.read();if(X!==null)yield X;else if(L)throw L;else if(L===null)return;else await new VX(E)}}catch(X){throw L=NX(L,X),L}finally{if((L||(T===null||T===void 0?void 0:T.destroyOnReturn)!==!1)&&(L===void 0||_._readableState.autoDestroy))aT.destroyer(_,null);else _.off("readable",E),J()}}j6(s.prototype,{readable:{__proto__:null,get(){let _=this._readableState;return!!_&&_.readable!==!1&&!_.destroyed&&!_.errorEmitted&&!_.endEmitted},set(_){if(this._readableState)this._readableState.readable=!!_}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(_){if(this._readableState)this._readableState.flowing=_}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(_){if(!this._readableState)return;this._readableState.destroyed=_}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});j6(HA.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[UT]!==!1},set(_){this[UT]=!!_}}});s._fromList=xX;function xX(_,T){if(T.length===0)return null;let A;if(T.objectMode)A=T.buffer.shift();else if(!_||_>=T.length){if(T.decoder)A=T.buffer.join("");else if(T.buffer.length===1)A=T.buffer.first();else A=T.buffer.concat(T.length);T.buffer.clear()}else A=T.buffer.consume(_,T.decoder);return A}function B6(_){let T=_._readableState;if(A_("endReadable",T.endEmitted),!T.endEmitted)T.ended=!0,b1.nextTick(NC,T,_)}function NC(_,T){if(A_("endReadableNT",_.endEmitted,_.length),!_.errored&&!_.closeEmitted&&!_.endEmitted&&_.length===0){if(_.endEmitted=!0,T.emit("end"),T.writable&&T.allowHalfOpen===!1)b1.nextTick(QC,T);else if(_.autoDestroy){let A=T._writableState;if(!A||A.autoDestroy&&(A.finished||A.writable===!1))T.destroy()}}}function QC(_){if(_.writable&&!_.writableEnded&&!_.destroyed)_.end()}s.from=function(_,T){return rF(s,_,T)};var q6;function wX(){if(q6===void 0)q6={};return q6}s.fromWeb=function(_,T){return wX().newStreamReadableFromReadableStream(_,T)};s.toWeb=function(_,T){return wX().newReadableStreamFromStreamReadable(_,T)};s.wrap=function(_,T){var A,E;return new s({objectMode:(A=(E=_.readableObjectMode)!==null&&E!==void 0?E:_.objectMode)!==null&&A!==void 0?A:!0,...T,destroy(L,J){aT.destroyer(_,L),J(L)}}).wrap(_)}});var UA=W((Mf,pX)=>{var WT=c0(),{ArrayPrototypeSlice:hX,Error:MC,FunctionPrototypeSymbolHasInstance:kX,ObjectDefineProperty:fX,ObjectDefineProperties:VC,ObjectSetPrototypeOf:bX,StringPrototypeToLowerCase:zC,Symbol:FC,SymbolHasInstance:CC}=z_();pX.exports=O_;O_.WritableState=b4;var{EventEmitter:OC}=j("events"),k4=_A().Stream,{Buffer:YA}=j("buffer"),$A=GT(),{addAbortSignal:RC}=w4(),{getHighWaterMark:DC,getDefaultHighWaterMark:BC}=S4(),{ERR_INVALID_ARG_TYPE:qC,ERR_METHOD_NOT_IMPLEMENTED:IC,ERR_MULTIPLE_CALLBACK:gX,ERR_STREAM_CANNOT_PIPE:PC,ERR_STREAM_DESTROYED:f4,ERR_STREAM_ALREADY_FINISHED:jC,ERR_STREAM_NULL_VALUES:xC,ERR_STREAM_WRITE_AFTER_END:wC,ERR_UNKNOWN_ENCODING:mX}=l_().codes,{errorOrDestroy:oT}=$A;bX(O_.prototype,k4.prototype);bX(O_,k4);function S6(){}var rT=FC("kOnFinished");function b4(_,T,A){if(typeof A!=="boolean")A=T instanceof E0();if(this.objectMode=!!(_&&_.objectMode),A)this.objectMode=this.objectMode||!!(_&&_.writableObjectMode);this.highWaterMark=_?DC(this,_,"writableHighWaterMark",A):BC(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let E=!!(_&&_.decodeStrings===!1);this.decodeStrings=!E,this.defaultEncoding=_&&_.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=yC.bind(void 0,T),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,GA(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!_||_.emitClose!==!1,this.autoDestroy=!_||_.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[rT]=[]}function GA(_){_.buffered=[],_.bufferedIndex=0,_.allBuffers=!0,_.allNoop=!0}b4.prototype.getBuffer=function(){return hX(this.buffered,this.bufferedIndex)};fX(b4.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function O_(_){let T=this instanceof E0();if(!T&&!kX(O_,this))return new O_(_);if(this._writableState=new b4(_,this,T),_){if(typeof _.write==="function")this._write=_.write;if(typeof _.writev==="function")this._writev=_.writev;if(typeof _.destroy==="function")this._destroy=_.destroy;if(typeof _.final==="function")this._final=_.final;if(typeof _.construct==="function")this._construct=_.construct;if(_.signal)RC(_.signal,this)}k4.call(this,_),$A.construct(this,()=>{let A=this._writableState;if(!A.writing)v6(this,A);h6(this,A)})}fX(O_,CC,{__proto__:null,value:function(_){if(kX(this,_))return!0;if(this!==O_)return!1;return _&&_._writableState instanceof b4}});O_.prototype.pipe=function(){oT(this,new PC)};function uX(_,T,A,E){let L=_._writableState;if(typeof A==="function")E=A,A=L.defaultEncoding;else{if(!A)A=L.defaultEncoding;else if(A!=="buffer"&&!YA.isEncoding(A))throw new mX(A);if(typeof E!=="function")E=S6}if(T===null)throw new xC;else if(!L.objectMode)if(typeof T==="string"){if(L.decodeStrings!==!1)T=YA.from(T,A),A="buffer"}else if(T instanceof YA)A="buffer";else if(k4._isUint8Array(T))T=k4._uint8ArrayToBuffer(T),A="buffer";else throw new qC("chunk",["string","Buffer","Uint8Array"],T);let J;if(L.ending)J=new wC;else if(L.destroyed)J=new f4("write");if(J)return WT.nextTick(E,J),oT(_,J,!0),J;return L.pendingcb++,SC(_,L,T,A,E)}O_.prototype.write=function(_,T,A){return uX(this,_,T,A)===!0};O_.prototype.cork=function(){this._writableState.corked++};O_.prototype.uncork=function(){let _=this._writableState;if(_.corked){if(_.corked--,!_.writing)v6(this,_)}};O_.prototype.setDefaultEncoding=function(T){if(typeof T==="string")T=zC(T);if(!YA.isEncoding(T))throw new mX(T);return this._writableState.defaultEncoding=T,this};function SC(_,T,A,E,L){let J=T.objectMode?1:A.length;T.length+=J;let X=T.length<T.highWaterMark;if(!X)T.needDrain=!0;if(T.writing||T.corked||T.errored||!T.constructed){if(T.buffered.push({chunk:A,encoding:E,callback:L}),T.allBuffers&&E!=="buffer")T.allBuffers=!1;if(T.allNoop&&L!==S6)T.allNoop=!1}else T.writelen=J,T.writecb=L,T.writing=!0,T.sync=!0,_._write(A,E,T.onwrite),T.sync=!1;return X&&!T.errored&&!T.destroyed}function yX(_,T,A,E,L,J,X){if(T.writelen=E,T.writecb=X,T.writing=!0,T.sync=!0,T.destroyed)T.onwrite(new f4("write"));else if(A)_._writev(L,T.onwrite);else _._write(L,J,T.onwrite);T.sync=!1}function vX(_,T,A,E){--T.pendingcb,E(A),y6(T),oT(_,A)}function yC(_,T){let A=_._writableState,E=A.sync,L=A.writecb;if(typeof L!=="function"){oT(_,new gX);return}if(A.writing=!1,A.writecb=null,A.length-=A.writelen,A.writelen=0,T){if(T.stack,!A.errored)A.errored=T;if(_._readableState&&!_._readableState.errored)_._readableState.errored=T;if(E)WT.nextTick(vX,_,A,T,L);else vX(_,A,T,L)}else{if(A.buffered.length>A.bufferedIndex)v6(_,A);if(E)if(A.afterWriteTickInfo!==null&&A.afterWriteTickInfo.cb===L)A.afterWriteTickInfo.count++;else A.afterWriteTickInfo={count:1,cb:L,stream:_,state:A},WT.nextTick(vC,A.afterWriteTickInfo);else dX(_,A,1,L)}}function vC({stream:_,state:T,count:A,cb:E}){return T.afterWriteTickInfo=null,dX(_,T,A,E)}function dX(_,T,A,E){if(!T.ending&&!_.destroyed&&T.length===0&&T.needDrain)T.needDrain=!1,_.emit("drain");while(A-- >0)T.pendingcb--,E();if(T.destroyed)y6(T);h6(_,T)}function y6(_){if(_.writing)return;for(let L=_.bufferedIndex;L<_.buffered.length;++L){var T;let{chunk:J,callback:X}=_.buffered[L],H=_.objectMode?1:J.length;_.length-=H,X((T=_.errored)!==null&&T!==void 0?T:new f4("write"))}let A=_[rT].splice(0);for(let L=0;L<A.length;L++){var E;A[L]((E=_.errored)!==null&&E!==void 0?E:new f4("end"))}GA(_)}function v6(_,T){if(T.corked||T.bufferProcessing||T.destroyed||!T.constructed)return;let{buffered:A,bufferedIndex:E,objectMode:L}=T,J=A.length-E;if(!J)return;let X=E;if(T.bufferProcessing=!0,J>1&&_._writev){T.pendingcb-=J-1;let H=T.allNoop?S6:(Y)=>{for(let K=X;K<A.length;++K)A[K].callback(Y)},Z=T.allNoop&&X===0?A:hX(A,X);Z.allBuffers=T.allBuffers,yX(_,T,!0,T.length,Z,"",H),GA(T)}else{do{let{chunk:H,encoding:Z,callback:Y}=A[X];A[X++]=null;let K=L?1:H.length;yX(_,T,!1,K,H,Z,Y)}while(X<A.length&&!T.writing);if(X===A.length)GA(T);else if(X>256)A.splice(0,X),T.bufferedIndex=0;else T.bufferedIndex=X}T.bufferProcessing=!1}O_.prototype._write=function(_,T,A){if(this._writev)this._writev([{chunk:_,encoding:T}],A);else throw new IC("_write()")};O_.prototype._writev=null;O_.prototype.end=function(_,T,A){let E=this._writableState;if(typeof _==="function")A=_,_=null,T=null;else if(typeof T==="function")A=T,T=null;let L;if(_!==null&&_!==void 0){let J=uX(this,_,T);if(J instanceof MC)L=J}if(E.corked)E.corked=1,this.uncork();if(L);else if(!E.errored&&!E.ending)E.ending=!0,h6(this,E,!0),E.ended=!0;else if(E.finished)L=new jC("end");else if(E.destroyed)L=new f4("end");if(typeof A==="function")if(L||E.finished)WT.nextTick(A,L);else E[rT].push(A);return this};function KA(_){return _.ending&&!_.destroyed&&_.constructed&&_.length===0&&!_.errored&&_.buffered.length===0&&!_.finished&&!_.writing&&!_.errorEmitted&&!_.closeEmitted}function hC(_,T){let A=!1;function E(L){if(A){oT(_,L!==null&&L!==void 0?L:gX());return}if(A=!0,T.pendingcb--,L){let J=T[rT].splice(0);for(let X=0;X<J.length;X++)J[X](L);oT(_,L,T.sync)}else if(KA(T))T.prefinished=!0,_.emit("prefinish"),T.pendingcb++,WT.nextTick(w6,_,T)}T.sync=!0,T.pendingcb++;try{_._final(E)}catch(L){E(L)}T.sync=!1}function kC(_,T){if(!T.prefinished&&!T.finalCalled)if(typeof _._final==="function"&&!T.destroyed)T.finalCalled=!0,hC(_,T);else T.prefinished=!0,_.emit("prefinish")}function h6(_,T,A){if(KA(T)){if(kC(_,T),T.pendingcb===0){if(A)T.pendingcb++,WT.nextTick((E,L)=>{if(KA(L))w6(E,L);else L.pendingcb--},_,T);else if(KA(T))T.pendingcb++,w6(_,T)}}}function w6(_,T){T.pendingcb--,T.finished=!0;let A=T[rT].splice(0);for(let E=0;E<A.length;E++)A[E]();if(_.emit("finish"),T.autoDestroy){let E=_._readableState;if(!E||E.autoDestroy&&(E.endEmitted||E.readable===!1))_.destroy()}}VC(O_.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(_){if(this._writableState)this._writableState.destroyed=_}},writable:{__proto__:null,get(){let _=this._writableState;return!!_&&_.writable!==!1&&!_.destroyed&&!_.errored&&!_.ending&&!_.ended},set(_){if(this._writableState)this._writableState.writable=!!_}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let _=this._writableState;if(!_)return!1;return!_.destroyed&&!_.ending&&_.needDrain}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var fC=$A.destroy;O_.prototype.destroy=function(_,T){let A=this._writableState;if(!A.destroyed&&(A.bufferedIndex<A.buffered.length||A[rT].length))WT.nextTick(y6,A);return fC.call(this,_,T),this};O_.prototype._undestroy=$A.undestroy;O_.prototype._destroy=function(_,T){T(_)};O_.prototype[OC.captureRejectionSymbol]=function(_){this.destroy(_)};var x6;function cX(){if(x6===void 0)x6={};return x6}O_.fromWeb=function(_,T){return cX().newStreamWritableFromWritableStream(_,T)};O_.toWeb=function(_){return cX().newWritableStreamFromStreamWritable(_)}});var JH=W((Vf,LH)=>{var k6=c0(),bC=j("buffer"),{isReadable:gC,isWritable:mC,isIterable:lX,isNodeStream:uC,isReadableNodeStream:nX,isWritableNodeStream:iX,isDuplexNodeStream:dC,isReadableStream:aX,isWritableStream:oX}=_0(),rX=B0(),{AbortError:AH,codes:{ERR_INVALID_ARG_TYPE:cC,ERR_INVALID_RETURN_VALUE:sX}}=l_(),{destroyer:tT}=GT(),pC=E0(),EH=h4(),lC=UA(),{createDeferredPromise:tX}=s_(),eX=C6(),_H=globalThis.Blob||bC.Blob,nC=typeof _H<"u"?function(T){return T instanceof _H}:function(T){return!1},iC=globalThis.AbortController||j("abort-controller").AbortController,{FunctionPrototypeCall:TH}=z_();class NT extends pC{constructor(_){super(_);if((_===null||_===void 0?void 0:_.readable)===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if((_===null||_===void 0?void 0:_.writable)===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}}LH.exports=function _(T,A){if(dC(T))return T;if(nX(T))return sT({readable:T});if(iX(T))return sT({writable:T});if(uC(T))return sT({writable:!1,readable:!1});if(aX(T))return sT({readable:EH.fromWeb(T)});if(oX(T))return sT({writable:lC.fromWeb(T)});if(typeof T==="function"){let{value:L,write:J,final:X,destroy:H}=aC(T);if(lX(L))return eX(NT,L,{objectMode:!0,write:J,final:X,destroy:H});let Z=L===null||L===void 0?void 0:L.then;if(typeof Z==="function"){let Y,K=TH(Z,L,(G)=>{if(G!=null)throw new sX("nully","body",G)},(G)=>{tT(Y,G)});return Y=new NT({objectMode:!0,readable:!1,write:J,final(G){X(async()=>{try{await K,k6.nextTick(G,null)}catch($){k6.nextTick(G,$)}})},destroy:H})}throw new sX("Iterable, AsyncIterable or AsyncFunction",A,L)}if(nC(T))return _(T.arrayBuffer());if(lX(T))return eX(NT,T,{objectMode:!0,writable:!1});if(aX(T===null||T===void 0?void 0:T.readable)&&oX(T===null||T===void 0?void 0:T.writable))return NT.fromWeb(T);if(typeof(T===null||T===void 0?void 0:T.writable)==="object"||typeof(T===null||T===void 0?void 0:T.readable)==="object"){let L=T!==null&&T!==void 0&&T.readable?nX(T===null||T===void 0?void 0:T.readable)?T===null||T===void 0?void 0:T.readable:_(T.readable):void 0,J=T!==null&&T!==void 0&&T.writable?iX(T===null||T===void 0?void 0:T.writable)?T===null||T===void 0?void 0:T.writable:_(T.writable):void 0;return sT({readable:L,writable:J})}let E=T===null||T===void 0?void 0:T.then;if(typeof E==="function"){let L;return TH(E,T,(J)=>{if(J!=null)L.push(J);L.push(null)},(J)=>{tT(L,J)}),L=new NT({objectMode:!0,writable:!1,read(){}})}throw new cC(A,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],T)};function aC(_){let{promise:T,resolve:A}=tX(),E=new iC,L=E.signal;return{value:_(async function*(){while(!0){let X=T;T=null;let{chunk:H,done:Z,cb:Y}=await X;if(k6.nextTick(Y),Z)return;if(L.aborted)throw new AH(void 0,{cause:L.reason});({promise:T,resolve:A}=tX()),yield H}}(),{signal:L}),write(X,H,Z){let Y=A;A=null,Y({chunk:X,done:!1,cb:Z})},final(X){let H=A;A=null,H({done:!0,cb:X})},destroy(X,H){E.abort(),H(X)}}}function sT(_){let T=_.readable&&typeof _.readable.read!=="function"?EH.wrap(_.readable):_.readable,A=_.writable,E=!!gC(T),L=!!mC(A),J,X,H,Z,Y;function K(G){let $=Z;if(Z=null,$)$(G);else if(G)Y.destroy(G)}if(Y=new NT({readableObjectMode:!!(T!==null&&T!==void 0&&T.readableObjectMode),writableObjectMode:!!(A!==null&&A!==void 0&&A.writableObjectMode),readable:E,writable:L}),L)rX(A,(G)=>{if(L=!1,G)tT(T,G);K(G)}),Y._write=function(G,$,U){if(A.write(G,$))U();else J=U},Y._final=function(G){A.end(),X=G},A.on("drain",function(){if(J){let G=J;J=null,G()}}),A.on("finish",function(){if(X){let G=X;X=null,G()}});if(E)rX(T,(G)=>{if(E=!1,G)tT(T,G);K(G)}),T.on("readable",function(){if(H){let G=H;H=null,G()}}),T.on("end",function(){Y.push(null)}),Y._read=function(){while(!0){let G=T.read();if(G===null){H=Y._read;return}if(!Y.push(G))return}};return Y._destroy=function(G,$){if(!G&&Z!==null)G=new AH;if(H=null,J=null,X=null,Z===null)$(G);else Z=$,tT(A,G),tT(T,G)},Y}});var E0=W((zf,ZH)=>{var{ObjectDefineProperties:oC,ObjectGetOwnPropertyDescriptor:q0,ObjectKeys:rC,ObjectSetPrototypeOf:XH}=z_();ZH.exports=g1;var g6=h4(),C1=UA();XH(g1.prototype,g6.prototype);XH(g1,g6);{let _=rC(C1.prototype);for(let T=0;T<_.length;T++){let A=_[T];if(!g1.prototype[A])g1.prototype[A]=C1.prototype[A]}}function g1(_){if(!(this instanceof g1))return new g1(_);if(g6.call(this,_),C1.call(this,_),_){if(this.allowHalfOpen=_.allowHalfOpen!==!1,_.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(_.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}oC(g1.prototype,{writable:{__proto__:null,...q0(C1.prototype,"writable")},writableHighWaterMark:{__proto__:null,...q0(C1.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...q0(C1.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...q0(C1.prototype,"writableBuffer")},writableLength:{__proto__:null,...q0(C1.prototype,"writableLength")},writableFinished:{__proto__:null,...q0(C1.prototype,"writableFinished")},writableCorked:{__proto__:null,...q0(C1.prototype,"writableCorked")},writableEnded:{__proto__:null,...q0(C1.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...q0(C1.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(_){if(this._readableState&&this._writableState)this._readableState.destroyed=_,this._writableState.destroyed=_}}});var f6;function HH(){if(f6===void 0)f6={};return f6}g1.fromWeb=function(_,T){return HH().newStreamDuplexFromReadableWritablePair(_,T)};g1.toWeb=function(_){return HH().newReadableWritablePairFromDuplex(_)};var b6;g1.from=function(_){if(!b6)b6=JH();return b6(_,"body")}});var d6=W((Ff,KH)=>{var{ObjectSetPrototypeOf:YH,Symbol:sC}=z_();KH.exports=I0;var{ERR_METHOD_NOT_IMPLEMENTED:tC}=l_().codes,u6=E0(),{getHighWaterMark:eC}=S4();YH(I0.prototype,u6.prototype);YH(I0,u6);var g4=sC("kCallback");function I0(_){if(!(this instanceof I0))return new I0(_);let T=_?eC(this,_,"readableHighWaterMark",!0):null;if(T===0)_={..._,highWaterMark:null,readableHighWaterMark:T,writableHighWaterMark:_.writableHighWaterMark||0};if(u6.call(this,_),this._readableState.sync=!1,this[g4]=null,_){if(typeof _.transform==="function")this._transform=_.transform;if(typeof _.flush==="function")this._flush=_.flush}this.on("prefinish",_O)}function m6(_){if(typeof this._flush==="function"&&!this.destroyed)this._flush((T,A)=>{if(T){if(_)_(T);else this.destroy(T);return}if(A!=null)this.push(A);if(this.push(null),_)_()});else if(this.push(null),_)_()}function _O(){if(this._final!==m6)m6.call(this)}I0.prototype._final=m6;I0.prototype._transform=function(_,T,A){throw new tC("_transform()")};I0.prototype._write=function(_,T,A){let E=this._readableState,L=this._writableState,J=E.length;this._transform(_,T,(X,H)=>{if(X){A(X);return}if(H!=null)this.push(H);if(L.ended||J===E.length||E.length<E.highWaterMark)A();else this[g4]=A})};I0.prototype._read=function(){if(this[g4]){let _=this[g4];this[g4]=null,_()}}});var p6=W((Cf,$H)=>{var{ObjectSetPrototypeOf:GH}=z_();$H.exports=eT;var c6=d6();GH(eT.prototype,c6.prototype);GH(eT,c6);function eT(_){if(!(this instanceof eT))return new eT(_);c6.call(this,_)}eT.prototype._transform=function(_,T,A){A(null,_)}});var MA=W((Of,MH)=>{var m4=c0(),{ArrayIsArray:TO,Promise:AO,SymbolAsyncIterator:EO,SymbolDispose:LO}=z_(),QA=B0(),{once:JO}=s_(),XO=GT(),UH=E0(),{aggregateTwoErrors:HO,codes:{ERR_INVALID_ARG_TYPE:e6,ERR_INVALID_RETURN_VALUE:l6,ERR_MISSING_ARGS:ZO,ERR_STREAM_DESTROYED:YO,ERR_STREAM_PREMATURE_CLOSE:KO},AbortError:GO}=l_(),{validateFunction:$O,validateAbortSignal:UO}=pT(),{isIterable:QT,isReadable:n6,isReadableNodeStream:NA,isNodeStream:WH,isTransformStream:_4,isWebStream:WO,isReadableStream:i6,isReadableFinished:NO}=_0(),QO=globalThis.AbortController||j("abort-controller").AbortController,a6,o6,r6;function NH(_,T,A){let E=!1;_.on("close",()=>{E=!0});let L=QA(_,{readable:T,writable:A},(J)=>{E=!J});return{destroy:(J)=>{if(E)return;E=!0,XO.destroyer(_,J||new YO("pipe"))},cleanup:L}}function MO(_){return $O(_[_.length-1],"streams[stream.length - 1]"),_.pop()}function s6(_){if(QT(_))return _;else if(NA(_))return VO(_);throw new e6("val",["Readable","Iterable","AsyncIterable"],_)}async function*VO(_){if(!o6)o6=h4();yield*o6.prototype[EO].call(_)}async function WA(_,T,A,{end:E}){let L,J=null,X=(Y)=>{if(Y)L=Y;if(J){let K=J;J=null,K()}},H=()=>new AO((Y,K)=>{if(L)K(L);else J=()=>{if(L)K(L);else Y()}});T.on("drain",X);let Z=QA(T,{readable:!1},X);try{if(T.writableNeedDrain)await H();for await(let Y of _)if(!T.write(Y))await H();if(E)T.end(),await H();A()}catch(Y){A(L!==Y?HO(L,Y):Y)}finally{Z(),T.off("drain",X)}}async function t6(_,T,A,{end:E}){if(_4(T))T=T.writable;let L=T.getWriter();try{for await(let J of _)await L.ready,L.write(J).catch(()=>{});if(await L.ready,E)await L.close();A()}catch(J){try{await L.abort(J),A(J)}catch(X){A(X)}}}function zO(..._){return QH(_,JO(MO(_)))}function QH(_,T,A){if(_.length===1&&TO(_[0]))_=_[0];if(_.length<2)throw new ZO("streams");let E=new QO,L=E.signal,J=A===null||A===void 0?void 0:A.signal,X=[];UO(J,"options.signal");function H(){V(new GO)}r6=r6||s_().addAbortListener;let Z;if(J)Z=r6(J,H);let Y,K,G=[],$=0;function U(R){V(R,--$===0)}function V(R,q){var f;if(R&&(!Y||Y.code==="ERR_STREAM_PREMATURE_CLOSE"))Y=R;if(!Y&&!q)return;while(G.length)G.shift()(Y);if((f=Z)===null||f===void 0||f[LO](),E.abort(),q){if(!Y)X.forEach((h)=>h());m4.nextTick(T,Y,K)}}let N;for(let R=0;R<_.length;R++){let q=_[R],f=R<_.length-1,h=R>0,b=f||(A===null||A===void 0?void 0:A.end)!==!1,l=R===_.length-1;if(WH(q)){let c=function(W_){if(W_&&W_.name!=="AbortError"&&W_.code!=="ERR_STREAM_PREMATURE_CLOSE")U(W_)};var F=c;if(b){let{destroy:W_,cleanup:c_}=NH(q,f,h);if(G.push(W_),n6(q)&&l)X.push(c_)}if(q.on("error",c),n6(q)&&l)X.push(()=>{q.removeListener("error",c)})}if(R===0)if(typeof q==="function"){if(N=q({signal:L}),!QT(N))throw new l6("Iterable, AsyncIterable or Stream","source",N)}else if(QT(q)||NA(q)||_4(q))N=q;else N=UH.from(q);else if(typeof q==="function"){if(_4(N)){var z;N=s6((z=N)===null||z===void 0?void 0:z.readable)}else N=s6(N);if(N=q(N,{signal:L}),f){if(!QT(N,!0))throw new l6("AsyncIterable",`transform[${R-1}]`,N)}else{var Q;if(!a6)a6=p6();let c=new a6({objectMode:!0}),W_=(Q=N)===null||Q===void 0?void 0:Q.then;if(typeof W_==="function")$++,W_.call(N,(C_)=>{if(K=C_,C_!=null)c.write(C_);if(b)c.end();m4.nextTick(U)},(C_)=>{c.destroy(C_),m4.nextTick(U,C_)});else if(QT(N,!0))$++,WA(N,c,U,{end:b});else if(i6(N)||_4(N)){let C_=N.readable||N;$++,WA(C_,c,U,{end:b})}else throw new l6("AsyncIterable or Promise","destination",N);N=c;let{destroy:c_,cleanup:B_}=NH(N,!1,!0);if(G.push(c_),l)X.push(B_)}}else if(WH(q)){if(NA(N)){$+=2;let c=FO(N,q,U,{end:b});if(n6(q)&&l)X.push(c)}else if(_4(N)||i6(N)){let c=N.readable||N;$++,WA(c,q,U,{end:b})}else if(QT(N))$++,WA(N,q,U,{end:b});else throw new e6("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else if(WO(q)){if(NA(N))$++,t6(s6(N),q,U,{end:b});else if(i6(N)||QT(N))$++,t6(N,q,U,{end:b});else if(_4(N))$++,t6(N.readable,q,U,{end:b});else throw new e6("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else N=UH.from(q)}if(L!==null&&L!==void 0&&L.aborted||J!==null&&J!==void 0&&J.aborted)m4.nextTick(H);return N}function FO(_,T,A,{end:E}){let L=!1;if(T.on("close",()=>{if(!L)A(new KO)}),_.pipe(T,{end:!1}),E){let X=function(){L=!0,T.end()};var J=X;if(NO(_))m4.nextTick(X);else _.once("end",X)}else A();return QA(_,{readable:!0,writable:!1},(X)=>{let H=_._readableState;if(X&&X.code==="ERR_STREAM_PREMATURE_CLOSE"&&H&&H.ended&&!H.errored&&!H.errorEmitted)_.once("end",A).once("error",A);else A(X)}),QA(T,{readable:!1,writable:!0},A)}MH.exports={pipelineImpl:QH,pipeline:zO}});var TE=W((Rf,RH)=>{var{pipeline:CO}=MA(),VA=E0(),{destroyer:OO}=GT(),{isNodeStream:zA,isReadable:VH,isWritable:zH,isWebStream:_E,isTransformStream:MT,isWritableStream:FH,isReadableStream:CH}=_0(),{AbortError:RO,codes:{ERR_INVALID_ARG_VALUE:OH,ERR_MISSING_ARGS:DO}}=l_(),BO=B0();RH.exports=function(...T){if(T.length===0)throw new DO("streams");if(T.length===1)return VA.from(T[0]);let A=[...T];if(typeof T[0]==="function")T[0]=VA.from(T[0]);if(typeof T[T.length-1]==="function"){let U=T.length-1;T[U]=VA.from(T[U])}for(let U=0;U<T.length;++U){if(!zA(T[U])&&!_E(T[U]))continue;if(U<T.length-1&&!(VH(T[U])||CH(T[U])||MT(T[U])))throw new OH(`streams[${U}]`,A[U],"must be readable");if(U>0&&!(zH(T[U])||FH(T[U])||MT(T[U])))throw new OH(`streams[${U}]`,A[U],"must be writable")}let E,L,J,X,H;function Z(U){let V=X;if(X=null,V)V(U);else if(U)H.destroy(U);else if(!$&&!G)H.destroy()}let Y=T[0],K=CO(T,Z),G=!!(zH(Y)||FH(Y)||MT(Y)),$=!!(VH(K)||CH(K)||MT(K));if(H=new VA({writableObjectMode:!!(Y!==null&&Y!==void 0&&Y.writableObjectMode),readableObjectMode:!!(K!==null&&K!==void 0&&K.readableObjectMode),writable:G,readable:$}),G){if(zA(Y))H._write=function(V,N,z){if(Y.write(V,N))z();else E=z},H._final=function(V){Y.end(),L=V},Y.on("drain",function(){if(E){let V=E;E=null,V()}});else if(_E(Y)){let N=(MT(Y)?Y.writable:Y).getWriter();H._write=async function(z,Q,F){try{await N.ready,N.write(z).catch(()=>{}),F()}catch(R){F(R)}},H._final=async function(z){try{await N.ready,N.close().catch(()=>{}),L=z}catch(Q){z(Q)}}}let U=MT(K)?K.readable:K;BO(U,()=>{if(L){let V=L;L=null,V()}})}if($){if(zA(K))K.on("readable",function(){if(J){let U=J;J=null,U()}}),K.on("end",function(){H.push(null)}),H._read=function(){while(!0){let U=K.read();if(U===null){J=H._read;return}if(!H.push(U))return}};else if(_E(K)){let V=(MT(K)?K.readable:K).getReader();H._read=async function(){while(!0)try{let{value:N,done:z}=await V.read();if(!H.push(N))return;if(z){H.push(null);return}}catch{return}}}}return H._destroy=function(U,V){if(!U&&X!==null)U=new RO;if(J=null,E=null,L=null,X===null)V(U);else if(X=V,zA(K))OO(K,U)},H}});var vH=W((eO,EE)=>{var qO=globalThis.AbortController||j("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:IO,ERR_INVALID_ARG_TYPE:u4,ERR_MISSING_ARGS:PO,ERR_OUT_OF_RANGE:jO},AbortError:L0}=l_(),{validateAbortSignal:VT,validateInteger:DH,validateObject:zT}=pT(),xO=z_().Symbol("kWeak"),wO=z_().Symbol("kResistStopPropagation"),{finished:SO}=B0(),yO=TE(),{addAbortSignalNoValidate:vO}=w4(),{isWritable:hO,isNodeStream:kO}=_0(),{deprecate:fO}=s_(),{ArrayPrototypePush:bO,Boolean:gO,MathFloor:BH,Number:mO,NumberIsNaN:uO,Promise:qH,PromiseReject:IH,PromiseResolve:dO,PromisePrototypeThen:PH,Symbol:xH}=z_(),FA=xH("kEmpty"),jH=xH("kEof");function cO(_,T){if(T!=null)zT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)VT(T.signal,"options.signal");if(kO(_)&&!hO(_))throw new IO("stream",_,"must be writable");let A=yO(this,_);if(T!==null&&T!==void 0&&T.signal)vO(T.signal,A);return A}function CA(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);if(T!=null)zT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)VT(T.signal,"options.signal");let A=1;if((T===null||T===void 0?void 0:T.concurrency)!=null)A=BH(T.concurrency);let E=A-1;if((T===null||T===void 0?void 0:T.highWaterMark)!=null)E=BH(T.highWaterMark);return DH(A,"options.concurrency",1),DH(E,"options.highWaterMark",0),E+=A,async function*(){let J=s_().AbortSignalAny([T===null||T===void 0?void 0:T.signal].filter(gO)),X=this,H=[],Z={signal:J},Y,K,G=!1,$=0;function U(){G=!0,V()}function V(){$-=1,N()}function N(){if(K&&!G&&$<A&&H.length<E)K(),K=null}async function z(){try{for await(let Q of X){if(G)return;if(J.aborted)throw new L0;try{if(Q=_(Q,Z),Q===FA)continue;Q=dO(Q)}catch(F){Q=IH(F)}if($+=1,PH(Q,V,U),H.push(Q),Y)Y(),Y=null;if(!G&&(H.length>=E||$>=A))await new qH((F)=>{K=F})}H.push(jH)}catch(Q){let F=IH(Q);PH(F,V,U),H.push(F)}finally{if(G=!0,Y)Y(),Y=null}}z();try{while(!0){while(H.length>0){let Q=await H[0];if(Q===jH)return;if(J.aborted)throw new L0;if(Q!==FA)yield Q;H.shift(),N()}await new qH((Q)=>{Y=Q})}}finally{if(G=!0,K)K(),K=null}}.call(this)}function pO(_=void 0){if(_!=null)zT(_,"options");if((_===null||_===void 0?void 0:_.signal)!=null)VT(_.signal,"options.signal");return async function*(){let A=0;for await(let L of this){var E;if(_!==null&&_!==void 0&&(E=_.signal)!==null&&E!==void 0&&E.aborted)throw new L0({cause:_.signal.reason});yield[A++,L]}}.call(this)}async function wH(_,T=void 0){for await(let A of AE.call(this,_,T))return!0;return!1}async function lO(_,T=void 0){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);return!await wH.call(this,async(...A)=>{return!await _(...A)},T)}async function nO(_,T){for await(let A of AE.call(this,_,T))return A;return}async function iO(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){return await _(E,L),FA}for await(let E of CA.call(this,A,T));}function AE(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){if(await _(E,L))return E;return FA}return CA.call(this,A,T)}class SH extends PO{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function aO(_,T,A){var E;if(typeof _!=="function")throw new u4("reducer",["Function","AsyncFunction"],_);if(A!=null)zT(A,"options");if((A===null||A===void 0?void 0:A.signal)!=null)VT(A.signal,"options.signal");let L=arguments.length>1;if(A!==null&&A!==void 0&&(E=A.signal)!==null&&E!==void 0&&E.aborted){let Y=new L0(void 0,{cause:A.signal.reason});throw this.once("error",()=>{}),await SO(this.destroy(Y)),Y}let J=new qO,X=J.signal;if(A!==null&&A!==void 0&&A.signal){let Y={once:!0,[xO]:this,[wO]:!0};A.signal.addEventListener("abort",()=>J.abort(),Y)}let H=!1;try{for await(let Y of this){var Z;if(H=!0,A!==null&&A!==void 0&&(Z=A.signal)!==null&&Z!==void 0&&Z.aborted)throw new L0;if(!L)T=Y,L=!0;else T=await _(T,Y,{signal:X})}if(!H&&!L)throw new SH}finally{J.abort()}return T}async function oO(_){if(_!=null)zT(_,"options");if((_===null||_===void 0?void 0:_.signal)!=null)VT(_.signal,"options.signal");let T=[];for await(let E of this){var A;if(_!==null&&_!==void 0&&(A=_.signal)!==null&&A!==void 0&&A.aborted)throw new L0(void 0,{cause:_.signal.reason});bO(T,E)}return T}function rO(_,T){let A=CA.call(this,_,T);return async function*(){for await(let L of A)yield*L}.call(this)}function yH(_){if(_=mO(_),uO(_))return 0;if(_<0)throw new jO("number",">= 0",_);return _}function sO(_,T=void 0){if(T!=null)zT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)VT(T.signal,"options.signal");return _=yH(_),async function*(){var E;if(T!==null&&T!==void 0&&(E=T.signal)!==null&&E!==void 0&&E.aborted)throw new L0;for await(let J of this){var L;if(T!==null&&T!==void 0&&(L=T.signal)!==null&&L!==void 0&&L.aborted)throw new L0;if(_--<=0)yield J}}.call(this)}function tO(_,T=void 0){if(T!=null)zT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)VT(T.signal,"options.signal");return _=yH(_),async function*(){var E;if(T!==null&&T!==void 0&&(E=T.signal)!==null&&E!==void 0&&E.aborted)throw new L0;for await(let J of this){var L;if(T!==null&&T!==void 0&&(L=T.signal)!==null&&L!==void 0&&L.aborted)throw new L0;if(_-- >0)yield J;if(_<=0)return}}.call(this)}eO.streamReturningOperators={asIndexedPairs:fO(pO,"readable.asIndexedPairs will be removed in a future version."),drop:sO,filter:AE,flatMap:rO,map:CA,take:tO,compose:cO};eO.promiseReturningOperators={every:lO,forEach:iO,reduce:aO,toArray:oO,some:wH,find:nO}});var LE=W((Df,hH)=>{var{ArrayPrototypePop:AR,Promise:ER}=z_(),{isIterable:LR,isNodeStream:JR,isWebStream:XR}=_0(),{pipelineImpl:HR}=MA(),{finished:ZR}=B0();JE();function YR(..._){return new ER((T,A)=>{let E,L,J=_[_.length-1];if(J&&typeof J==="object"&&!JR(J)&&!LR(J)&&!XR(J)){let X=AR(_);E=X.signal,L=X.end}HR(_,(X,H)=>{if(X)A(X);else T(H)},{signal:E,end:L})})}hH.exports={finished:ZR,pipeline:YR}});var JE=W((Bf,pH)=>{var{Buffer:KR}=j("buffer"),{ObjectDefineProperty:P0,ObjectKeys:bH,ReflectApply:gH}=z_(),{promisify:{custom:mH}}=s_(),{streamReturningOperators:kH,promiseReturningOperators:fH}=vH(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:uH}}=l_(),GR=TE(),{setDefaultHighWaterMark:$R,getDefaultHighWaterMark:UR}=S4(),{pipeline:dH}=MA(),{destroyer:WR}=GT(),cH=B0(),XE=LE(),d4=_0(),V_=pH.exports=_A().Stream;V_.isDestroyed=d4.isDestroyed;V_.isDisturbed=d4.isDisturbed;V_.isErrored=d4.isErrored;V_.isReadable=d4.isReadable;V_.isWritable=d4.isWritable;V_.Readable=h4();for(let _ of bH(kH)){let A=function(...E){if(new.target)throw uH();return V_.Readable.from(gH(T,this,E))},T=kH[_];P0(A,"name",{__proto__:null,value:T.name}),P0(A,"length",{__proto__:null,value:T.length}),P0(V_.Readable.prototype,_,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}for(let _ of bH(fH)){let A=function(...E){if(new.target)throw uH();return gH(T,this,E)},T=fH[_];P0(A,"name",{__proto__:null,value:T.name}),P0(A,"length",{__proto__:null,value:T.length}),P0(V_.Readable.prototype,_,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}V_.Writable=UA();V_.Duplex=E0();V_.Transform=d6();V_.PassThrough=p6();V_.pipeline=dH;var{addAbortSignal:NR}=w4();V_.addAbortSignal=NR;V_.finished=cH;V_.destroy=WR;V_.compose=GR;V_.setDefaultHighWaterMark=$R;V_.getDefaultHighWaterMark=UR;P0(V_,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return XE}});P0(dH,mH,{__proto__:null,enumerable:!0,get(){return XE.pipeline}});P0(cH,mH,{__proto__:null,enumerable:!0,get(){return XE.finished}});V_.Stream=V_;V_._isUint8Array=function(T){return T instanceof Uint8Array};V_._uint8ArrayToBuffer=function(T){return KR.from(T.buffer,T.byteOffset,T.byteLength)}});var n0=W((qf,__)=>{var w_=j("stream");if(w_&&process.env.READABLE_STREAM==="disable"){let _=w_.promises;__.exports._uint8ArrayToBuffer=w_._uint8ArrayToBuffer,__.exports._isUint8Array=w_._isUint8Array,__.exports.isDisturbed=w_.isDisturbed,__.exports.isErrored=w_.isErrored,__.exports.isReadable=w_.isReadable,__.exports.Readable=w_.Readable,__.exports.Writable=w_.Writable,__.exports.Duplex=w_.Duplex,__.exports.Transform=w_.Transform,__.exports.PassThrough=w_.PassThrough,__.exports.addAbortSignal=w_.addAbortSignal,__.exports.finished=w_.finished,__.exports.destroy=w_.destroy,__.exports.pipeline=w_.pipeline,__.exports.compose=w_.compose,Object.defineProperty(w_,"promises",{configurable:!0,enumerable:!0,get(){return _}}),__.exports.Stream=w_.Stream}else{let _=JE(),T=LE(),A=_.Readable.destroy;__.exports=_.Readable,__.exports._uint8ArrayToBuffer=_._uint8ArrayToBuffer,__.exports._isUint8Array=_._isUint8Array,__.exports.isDisturbed=_.isDisturbed,__.exports.isErrored=_.isErrored,__.exports.isReadable=_.isReadable,__.exports.Readable=_.Readable,__.exports.Writable=_.Writable,__.exports.Duplex=_.Duplex,__.exports.Transform=_.Transform,__.exports.PassThrough=_.PassThrough,__.exports.addAbortSignal=_.addAbortSignal,__.exports.finished=_.finished,__.exports.destroy=_.destroy,__.exports.destroy=A,__.exports.pipeline=_.pipeline,__.exports.compose=_.compose,Object.defineProperty(_,"promises",{configurable:!0,enumerable:!0,get(){return T}}),__.exports.Stream=_.Stream}__.exports.default=__.exports});var lH=W((cf,HE)=>{if(typeof Object.create==="function")HE.exports=function(T,A){if(A)T.super_=A,T.prototype=Object.create(A.prototype,{constructor:{value:T,enumerable:!1,writable:!0,configurable:!0}})};else HE.exports=function(T,A){if(A){T.super_=A;var E=function(){};E.prototype=A.prototype,T.prototype=new E,T.prototype.constructor=T}}});var nH=W((pf,ZE)=>{try{if(OA=j("util"),typeof OA.inherits!=="function")throw"";ZE.exports=OA.inherits}catch(_){ZE.exports=lH()}var OA});var oH=W((lf,aH)=>{var{Buffer:m1}=j("buffer"),iH=Symbol.for("BufferList");function H_(_){if(!(this instanceof H_))return new H_(_);H_._init.call(this,_)}H_._init=function(T){if(Object.defineProperty(this,iH,{value:!0}),this._bufs=[],this.length=0,T)this.append(T)};H_.prototype._new=function(T){return new H_(T)};H_.prototype._offset=function(T){if(T===0)return[0,0];let A=0;for(let E=0;E<this._bufs.length;E++){let L=A+this._bufs[E].length;if(T<L||E===this._bufs.length-1)return[E,T-A];A=L}};H_.prototype._reverseOffset=function(_){let T=_[0],A=_[1];for(let E=0;E<T;E++)A+=this._bufs[E].length;return A};H_.prototype.getBuffers=function(){return this._bufs};H_.prototype.get=function(T){if(T>this.length||T<0)return;let A=this._offset(T);return this._bufs[A[0]][A[1]]};H_.prototype.slice=function(T,A){if(typeof T==="number"&&T<0)T+=this.length;if(typeof A==="number"&&A<0)A+=this.length;return this.copy(null,0,T,A)};H_.prototype.copy=function(T,A,E,L){if(typeof E!=="number"||E<0)E=0;if(typeof L!=="number"||L>this.length)L=this.length;if(E>=this.length)return T||m1.alloc(0);if(L<=0)return T||m1.alloc(0);let J=!!T,X=this._offset(E),H=L-E,Z=H,Y=J&&A||0,K=X[1];if(E===0&&L===this.length){if(!J)return this._bufs.length===1?this._bufs[0]:m1.concat(this._bufs,this.length);for(let G=0;G<this._bufs.length;G++)this._bufs[G].copy(T,Y),Y+=this._bufs[G].length;return T}if(Z<=this._bufs[X[0]].length-K)return J?this._bufs[X[0]].copy(T,A,K,K+Z):this._bufs[X[0]].slice(K,K+Z);if(!J)T=m1.allocUnsafe(H);for(let G=X[0];G<this._bufs.length;G++){let $=this._bufs[G].length-K;if(Z>$)this._bufs[G].copy(T,Y,K),Y+=$;else{this._bufs[G].copy(T,Y,K,K+Z),Y+=$;break}if(Z-=$,K)K=0}if(T.length>Y)return T.slice(0,Y);return T};H_.prototype.shallowSlice=function(T,A){if(T=T||0,A=typeof A!=="number"?this.length:A,T<0)T+=this.length;if(A<0)A+=this.length;if(T===A)return this._new();let E=this._offset(T),L=this._offset(A),J=this._bufs.slice(E[0],L[0]+1);if(L[1]===0)J.pop();else J[J.length-1]=J[J.length-1].slice(0,L[1]);if(E[1]!==0)J[0]=J[0].slice(E[1]);return this._new(J)};H_.prototype.toString=function(T,A,E){return this.slice(A,E).toString(T)};H_.prototype.consume=function(T){if(T=Math.trunc(T),Number.isNaN(T)||T<=0)return this;while(this._bufs.length)if(T>=this._bufs[0].length)T-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(T),this.length-=T;break}return this};H_.prototype.duplicate=function(){let T=this._new();for(let A=0;A<this._bufs.length;A++)T.append(this._bufs[A]);return T};H_.prototype.append=function(T){return this._attach(T,H_.prototype._appendBuffer)};H_.prototype.prepend=function(T){return this._attach(T,H_.prototype._prependBuffer,!0)};H_.prototype._attach=function(T,A,E){if(T==null)return this;if(T.buffer)A.call(this,m1.from(T.buffer,T.byteOffset,T.byteLength));else if(Array.isArray(T)){let[L,J]=E?[T.length-1,-1]:[0,1];for(let X=L;X>=0&&X<T.length;X+=J)this._attach(T[X],A,E)}else if(this._isBufferList(T)){let[L,J]=E?[T._bufs.length-1,-1]:[0,1];for(let X=L;X>=0&&X<T._bufs.length;X+=J)this._attach(T._bufs[X],A,E)}else{if(typeof T==="number")T=T.toString();A.call(this,m1.from(T))}return this};H_.prototype._appendBuffer=function(T){this._bufs.push(T),this.length+=T.length};H_.prototype._prependBuffer=function(T){this._bufs.unshift(T),this.length+=T.length};H_.prototype.indexOf=function(_,T,A){if(A===void 0&&typeof T==="string")A=T,T=void 0;if(typeof _==="function"||Array.isArray(_))throw TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');else if(typeof _==="number")_=m1.from([_]);else if(typeof _==="string")_=m1.from(_,A);else if(this._isBufferList(_))_=_.slice();else if(Array.isArray(_.buffer))_=m1.from(_.buffer,_.byteOffset,_.byteLength);else if(!m1.isBuffer(_))_=m1.from(_);if(T=Number(T||0),isNaN(T))T=0;if(T<0)T=this.length+T;if(T<0)T=0;if(_.length===0)return T>this.length?this.length:T;let E=this._offset(T),L=E[0],J=E[1];for(;L<this._bufs.length;L++){let X=this._bufs[L];while(J<X.length)if(X.length-J>=_.length){let Z=X.indexOf(_,J);if(Z!==-1)return this._reverseOffset([L,Z]);J=X.length-_.length+1}else{let Z=this._reverseOffset([L,J]);if(this._match(Z,_))return Z;J++}J=0}return-1};H_.prototype._match=function(_,T){if(this.length-_<T.length)return!1;for(let A=0;A<T.length;A++)if(this.get(_+A)!==T[A])return!1;return!0};(function(){let _={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let T in _)(function(A){if(_[A]===null)H_.prototype[A]=function(E,L){return this.slice(E,E+L)[A](0,L)};else H_.prototype[A]=function(E=0){return this.slice(E,E+_[A])[A](0)}})(T)})();H_.prototype._isBufferList=function(T){return T instanceof H_||H_.isBufferList(T)};H_.isBufferList=function(T){return T!=null&&T[iH]};aH.exports=H_});var rH=W((nf,RA)=>{var YE=n0().Duplex,QR=nH(),c4=oH();function i_(_){if(!(this instanceof i_))return new i_(_);if(typeof _==="function"){this._callback=_;let T=function(E){if(this._callback)this._callback(E),this._callback=null}.bind(this);this.on("pipe",function(E){E.on("error",T)}),this.on("unpipe",function(E){E.removeListener("error",T)}),_=null}c4._init.call(this,_),YE.call(this)}QR(i_,YE);Object.assign(i_.prototype,c4.prototype);i_.prototype._new=function(T){return new i_(T)};i_.prototype._write=function(T,A,E){if(this._appendBuffer(T),typeof E==="function")E()};i_.prototype._read=function(T){if(!this.length)return this.push(null);T=Math.min(T,this.length),this.push(this.slice(0,T)),this.consume(T)};i_.prototype.end=function(T){if(YE.prototype.end.call(this,T),this._callback)this._callback(null,this.slice()),this._callback=null};i_.prototype._destroy=function(T,A){this._bufs.length=0,this.length=0,A(T)};i_.prototype._isBufferList=function(T){return T instanceof i_||T instanceof c4||i_.isBufferList(T)};i_.isBufferList=c4.isBufferList;RA.exports=i_;RA.exports.BufferListStream=i_;RA.exports.BufferList=c4});var eH=W((af,tH)=>{class sH{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}tH.exports=sH});var KE=W((of,_Z)=>{var x=of,{Buffer:X1}=j("buffer");x.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};x.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0};x.requiredHeaderFlagsErrors={};for(let _ in x.requiredHeaderFlags){let T=x.requiredHeaderFlags[_];x.requiredHeaderFlagsErrors[_]="Invalid header flag bits, must be 0x"+T.toString(16)+" for "+x.types[_]+" packet"}x.codes={};for(let _ in x.types){let T=x.types[_];x.codes[T]=_}x.CMD_SHIFT=4;x.CMD_MASK=240;x.DUP_MASK=8;x.QOS_MASK=3;x.QOS_SHIFT=1;x.RETAIN_MASK=1;x.VARBYTEINT_MASK=127;x.VARBYTEINT_FIN_MASK=128;x.VARBYTEINT_MAX=268435455;x.SESSIONPRESENT_MASK=1;x.SESSIONPRESENT_HEADER=X1.from([x.SESSIONPRESENT_MASK]);x.CONNACK_HEADER=X1.from([x.codes.connack<<x.CMD_SHIFT]);x.USERNAME_MASK=128;x.PASSWORD_MASK=64;x.WILL_RETAIN_MASK=32;x.WILL_QOS_MASK=24;x.WILL_QOS_SHIFT=3;x.WILL_FLAG_MASK=4;x.CLEAN_SESSION_MASK=2;x.CONNECT_HEADER=X1.from([x.codes.connect<<x.CMD_SHIFT]);x.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11};x.propertiesCodes={};for(let _ in x.properties){let T=x.properties[_];x.propertiesCodes[T]=_}x.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function i0(_){return[0,1,2].map((T)=>{return[0,1].map((A)=>{return[0,1].map((E)=>{let L=X1.alloc(1);return L.writeUInt8(x.codes[_]<<x.CMD_SHIFT|(A?x.DUP_MASK:0)|T<<x.QOS_SHIFT|E,0,!0),L})})})}x.PUBLISH_HEADER=i0("publish");x.SUBSCRIBE_HEADER=i0("subscribe");x.SUBSCRIBE_OPTIONS_QOS_MASK=3;x.SUBSCRIBE_OPTIONS_NL_MASK=1;x.SUBSCRIBE_OPTIONS_NL_SHIFT=2;x.SUBSCRIBE_OPTIONS_RAP_MASK=1;x.SUBSCRIBE_OPTIONS_RAP_SHIFT=3;x.SUBSCRIBE_OPTIONS_RH_MASK=3;x.SUBSCRIBE_OPTIONS_RH_SHIFT=4;x.SUBSCRIBE_OPTIONS_RH=[0,16,32];x.SUBSCRIBE_OPTIONS_NL=4;x.SUBSCRIBE_OPTIONS_RAP=8;x.SUBSCRIBE_OPTIONS_QOS=[0,1,2];x.UNSUBSCRIBE_HEADER=i0("unsubscribe");x.ACKS={unsuback:i0("unsuback"),puback:i0("puback"),pubcomp:i0("pubcomp"),pubrel:i0("pubrel"),pubrec:i0("pubrec")};x.SUBACK_HEADER=X1.from([x.codes.suback<<x.CMD_SHIFT]);x.VERSION3=X1.from([3]);x.VERSION4=X1.from([4]);x.VERSION5=X1.from([5]);x.VERSION131=X1.from([131]);x.VERSION132=X1.from([132]);x.QOS=[0,1,2].map((_)=>{return X1.from([_])});x.EMPTY={pingreq:X1.from([x.codes.pingreq<<4,0]),pingresp:X1.from([x.codes.pingresp<<4,0]),disconnect:X1.from([x.codes.disconnect<<4,0])};x.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"};x.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"};x.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};x.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"};x.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};x.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}});var AZ=W((rf,TZ)=>{var T4=1000,A4=T4*60,E4=A4*60,FT=E4*24,MR=FT*7,VR=FT*365.25;TZ.exports=function(_,T){T=T||{};var A=typeof _;if(A==="string"&&_.length>0)return zR(_);else if(A==="number"&&isFinite(_))return T.long?CR(_):FR(_);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(_))};function zR(_){if(_=String(_),_.length>100)return;var T=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(_);if(!T)return;var A=parseFloat(T[1]),E=(T[2]||"ms").toLowerCase();switch(E){case"years":case"year":case"yrs":case"yr":case"y":return A*VR;case"weeks":case"week":case"w":return A*MR;case"days":case"day":case"d":return A*FT;case"hours":case"hour":case"hrs":case"hr":case"h":return A*E4;case"minutes":case"minute":case"mins":case"min":case"m":return A*A4;case"seconds":case"second":case"secs":case"sec":case"s":return A*T4;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return}}function FR(_){var T=Math.abs(_);if(T>=FT)return Math.round(_/FT)+"d";if(T>=E4)return Math.round(_/E4)+"h";if(T>=A4)return Math.round(_/A4)+"m";if(T>=T4)return Math.round(_/T4)+"s";return _+"ms"}function CR(_){var T=Math.abs(_);if(T>=FT)return DA(_,T,FT,"day");if(T>=E4)return DA(_,T,E4,"hour");if(T>=A4)return DA(_,T,A4,"minute");if(T>=T4)return DA(_,T,T4,"second");return _+" ms"}function DA(_,T,A,E){var L=T>=A*1.5;return Math.round(_/A)+" "+E+(L?"s":"")}});var GE=W((sf,EZ)=>{function OR(_){A.debug=A,A.default=A,A.coerce=Z,A.disable=X,A.enable=L,A.enabled=H,A.humanize=AZ(),A.destroy=Y,Object.keys(_).forEach((K)=>{A[K]=_[K]}),A.names=[],A.skips=[],A.formatters={};function T(K){let G=0;for(let $=0;$<K.length;$++)G=(G<<5)-G+K.charCodeAt($),G|=0;return A.colors[Math.abs(G)%A.colors.length]}A.selectColor=T;function A(K){let G,$=null,U,V;function N(...z){if(!N.enabled)return;let Q=N,F=Number(new Date),R=F-(G||F);if(Q.diff=R,Q.prev=G,Q.curr=F,G=F,z[0]=A.coerce(z[0]),typeof z[0]!=="string")z.unshift("%O");let q=0;z[0]=z[0].replace(/%([a-zA-Z%])/g,(h,b)=>{if(h==="%%")return"%";q++;let l=A.formatters[b];if(typeof l==="function"){let c=z[q];h=l.call(Q,c),z.splice(q,1),q--}return h}),A.formatArgs.call(Q,z),(Q.log||A.log).apply(Q,z)}if(N.namespace=K,N.useColors=A.useColors(),N.color=A.selectColor(K),N.extend=E,N.destroy=A.destroy,Object.defineProperty(N,"enabled",{enumerable:!0,configurable:!1,get:()=>{if($!==null)return $;if(U!==A.namespaces)U=A.namespaces,V=A.enabled(K);return V},set:(z)=>{$=z}}),typeof A.init==="function")A.init(N);return N}function E(K,G){let $=A(this.namespace+(typeof G>"u"?":":G)+K);return $.log=this.log,$}function L(K){A.save(K),A.namespaces=K,A.names=[],A.skips=[];let G=(typeof K==="string"?K:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let $ of G)if($[0]==="-")A.skips.push($.slice(1));else A.names.push($)}function J(K,G){let $=0,U=0,V=-1,N=0;while($<K.length)if(U<G.length&&(G[U]===K[$]||G[U]==="*"))if(G[U]==="*")V=U,N=$,U++;else $++,U++;else if(V!==-1)U=V+1,N++,$=N;else return!1;while(U<G.length&&G[U]==="*")U++;return U===G.length}function X(){let K=[...A.names,...A.skips.map((G)=>"-"+G)].join(",");return A.enable(""),K}function H(K){for(let G of A.skips)if(J(K,G))return!1;for(let G of A.names)if(J(K,G))return!0;return!1}function Z(K){if(K instanceof Error)return K.stack||K.message;return K}function Y(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return A.enable(A.load()),A}EZ.exports=OR});var JZ=W((LZ,BA)=>{LZ.formatArgs=DR;LZ.save=BR;LZ.load=qR;LZ.useColors=RR;LZ.storage=IR();LZ.destroy=(()=>{let _=!1;return()=>{if(!_)_=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();LZ.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function RR(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let _;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(_=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(_[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function DR(_){if(_[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+_[0]+(this.useColors?"%c ":" ")+"+"+BA.exports.humanize(this.diff),!this.useColors)return;let T="color: "+this.color;_.splice(1,0,T,"color: inherit");let A=0,E=0;_[0].replace(/%[a-zA-Z%]/g,(L)=>{if(L==="%%")return;if(A++,L==="%c")E=A}),_.splice(E,0,T)}LZ.log=console.debug||console.log||(()=>{});function BR(_){try{if(_)LZ.storage.setItem("debug",_);else LZ.storage.removeItem("debug")}catch(T){}}function qR(){let _;try{_=LZ.storage.getItem("debug")||LZ.storage.getItem("DEBUG")}catch(T){}if(!_&&typeof process<"u"&&"env"in process)_=process.env.DEBUG;return _}function IR(){try{return localStorage}catch(_){}}BA.exports=GE()(LZ);var{formatters:PR}=BA.exports;PR.j=function(_){try{return JSON.stringify(_)}catch(T){return"[UnexpectedJSONParseError]: "+T.message}}});var YZ=W((HZ,IA)=>{var kR=j("tty"),qA=j("util");HZ.init=cR;HZ.log=mR;HZ.formatArgs=bR;HZ.save=uR;HZ.load=dR;HZ.useColors=fR;HZ.destroy=qA.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");HZ.colors=[6,2,3,4,5,1];try{let _=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(_&&(_.stderr||_).level>=2)HZ.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(_){}HZ.inspectOpts=Object.keys(process.env).filter((_)=>{return/^debug_/i.test(_)}).reduce((_,T)=>{let A=T.substring(6).toLowerCase().replace(/_([a-z])/g,(L,J)=>{return J.toUpperCase()}),E=process.env[T];if(/^(yes|on|true|enabled)$/i.test(E))E=!0;else if(/^(no|off|false|disabled)$/i.test(E))E=!1;else if(E==="null")E=null;else E=Number(E);return _[A]=E,_},{});function fR(){return"colors"in HZ.inspectOpts?Boolean(HZ.inspectOpts.colors):kR.isatty(process.stderr.fd)}function bR(_){let{namespace:T,useColors:A}=this;if(A){let E=this.color,L="\x1B[3"+(E<8?E:"8;5;"+E),J=` ${L};1m${T} \x1B[0m`;_[0]=J+_[0].split(`
|
|
4
4
|
`).join(`
|
|
5
|
-
`+
|
|
6
|
-
`)}function
|
|
7
|
-
`).map(($)=>$.trim()).join(" ")};sV.O=function(H){return this.inspectOpts.colors=this.useColors,m0.inspect(H,this.inspectOpts)}});var K$=p((rR,iP)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)iP.exports=FV();else iP.exports=GV()});var lV=p((BR,aV)=>{var l3=xV(),{EventEmitter:y3}=B("events"),dV=XV(),DH=sP(),Q=K$()("mqtt-packet:parser");class e0 extends y3{constructor(){super();this.parser=this.constructor.parser}static parser(H){if(!(this instanceof e0))return new e0().parser(H);return this.settings=H||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this}_resetState(){Q("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new dV,this.error=null,this._list=l3(),this._stateCounter=0}parse(H){if(this.error)this._resetState();this._list.append(H),Q("parse: current state: %s",this._states[this._stateCounter]);while((this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error)if(this._stateCounter++,Q("parse: state complete. _stateCounter is now: %d",this._stateCounter),Q("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length)this._stateCounter=0;return Q("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let H=this._list.readUInt8(0),$=H>>DH.CMD_SHIFT;this.packet.cmd=DH.types[$];let A=H&15,L=DH.requiredHeaderFlags[$];if(L!=null&&A!==L)return this._emitError(Error(DH.requiredHeaderFlagsErrors[$]));if(this.packet.retain=(H&DH.RETAIN_MASK)!==0,this.packet.qos=H>>DH.QOS_SHIFT&DH.QOS_MASK,this.packet.qos>2)return this._emitError(Error("Packet must not have both QoS bits set to 1"));return this.packet.dup=(H&DH.DUP_MASK)!==0,Q("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){let H=this._parseVarByteNum(!0);if(H)this.packet.length=H.value,this._list.consume(H.bytes);return Q("_parseLength %d",H.value),!!H}_parsePayload(){Q("_parsePayload: payload %O",this._list);let H=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(Error("Not supported"))}H=!0}return Q("_parsePayload complete result: %s",H),H}_parseConnect(){Q("_parseConnect");let H,$,A,L,D={},f=this.packet,E=this._parseString();if(E===null)return this._emitError(Error("Cannot parse protocolId"));if(E!=="MQTT"&&E!=="MQIsdp")return this._emitError(Error("Invalid protocolId"));if(f.protocolId=E,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(f.protocolVersion=this._list.readUInt8(this._pos),f.protocolVersion>=128)f.bridgeMode=!0,f.protocolVersion=f.protocolVersion-128;if(f.protocolVersion!==3&&f.protocolVersion!==4&&f.protocolVersion!==5)return this._emitError(Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(Error("Connect flag bit 0 must be 0, but got 1"));D.username=this._list.readUInt8(this._pos)&DH.USERNAME_MASK,D.password=this._list.readUInt8(this._pos)&DH.PASSWORD_MASK,D.will=this._list.readUInt8(this._pos)&DH.WILL_FLAG_MASK;let I=!!(this._list.readUInt8(this._pos)&DH.WILL_RETAIN_MASK),P=(this._list.readUInt8(this._pos)&DH.WILL_QOS_MASK)>>DH.WILL_QOS_SHIFT;if(D.will)f.will={},f.will.retain=I,f.will.qos=P;else{if(I)return this._emitError(Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(P)return this._emitError(Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(f.clean=(this._list.readUInt8(this._pos)&DH.CLEAN_SESSION_MASK)!==0,this._pos++,f.keepalive=this._parseNum(),f.keepalive===-1)return this._emitError(Error("Packet too short"));if(f.protocolVersion===5){let U=this._parseProperties();if(Object.getOwnPropertyNames(U).length)f.properties=U}let T=this._parseString();if(T===null)return this._emitError(Error("Packet too short"));if(f.clientId=T,Q("_parseConnect: packet.clientId: %s",f.clientId),D.will){if(f.protocolVersion===5){let U=this._parseProperties();if(Object.getOwnPropertyNames(U).length)f.will.properties=U}if(H=this._parseString(),H===null)return this._emitError(Error("Cannot parse will topic"));if(f.will.topic=H,Q("_parseConnect: packet.will.topic: %s",f.will.topic),$=this._parseBuffer(),$===null)return this._emitError(Error("Cannot parse will payload"));f.will.payload=$,Q("_parseConnect: packet.will.paylaod: %s",f.will.payload)}if(D.username){if(L=this._parseString(),L===null)return this._emitError(Error("Cannot parse username"));f.username=L,Q("_parseConnect: packet.username: %s",f.username)}if(D.password){if(A=this._parseBuffer(),A===null)return this._emitError(Error("Cannot parse password"));f.password=A}return this.settings=f,Q("_parseConnect: complete"),f}_parseConnack(){Q("_parseConnack");let H=this.packet;if(this._list.length<1)return null;let $=this._list.readUInt8(this._pos++);if($>1)return this._emitError(Error("Invalid connack flags, bits 7-1 must be set to 0"));if(H.sessionPresent=!!($&DH.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)if(this._list.length>=2)H.reasonCode=this._list.readUInt8(this._pos++);else H.reasonCode=0;else{if(this._list.length<2)return null;H.returnCode=this._list.readUInt8(this._pos++)}if(H.returnCode===-1||H.reasonCode===-1)return this._emitError(Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let A=this._parseProperties();if(Object.getOwnPropertyNames(A).length)H.properties=A}Q("_parseConnack: complete")}_parsePublish(){Q("_parsePublish");let H=this.packet;if(H.topic=this._parseString(),H.topic===null)return this._emitError(Error("Cannot parse topic"));if(H.qos>0){if(!this._parseMessageId())return}if(this.settings.protocolVersion===5){let $=this._parseProperties();if(Object.getOwnPropertyNames($).length)H.properties=$}H.payload=this._list.slice(this._pos,H.length),Q("_parsePublish: payload from buffer list: %o",H.payload)}_parseSubscribe(){Q("_parseSubscribe");let H=this.packet,$,A,L,D,f,E,I;if(H.subscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let P=this._parseProperties();if(Object.getOwnPropertyNames(P).length)H.properties=P}if(H.length<=0)return this._emitError(Error("Malformed subscribe, no payload specified"));while(this._pos<H.length){if($=this._parseString(),$===null)return this._emitError(Error("Cannot parse topic"));if(this._pos>=H.length)return this._emitError(Error("Malformed Subscribe Payload"));if(A=this._parseByte(),this.settings.protocolVersion===5){if(A&192)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(A&252)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(L=A&DH.SUBSCRIBE_OPTIONS_QOS_MASK,L>2)return this._emitError(Error("Invalid subscribe QoS, must be <= 2"));if(E=(A>>DH.SUBSCRIBE_OPTIONS_NL_SHIFT&DH.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(A>>DH.SUBSCRIBE_OPTIONS_RAP_SHIFT&DH.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,D=A>>DH.SUBSCRIBE_OPTIONS_RH_SHIFT&DH.SUBSCRIBE_OPTIONS_RH_MASK,D>2)return this._emitError(Error("Invalid retain handling, must be <= 2"));if(I={topic:$,qos:L},this.settings.protocolVersion===5)I.nl=E,I.rap=f,I.rh=D;else if(this.settings.bridgeMode)I.rh=0,I.rap=!0,I.nl=!0;Q("_parseSubscribe: push subscription `%s` to subscription",I),H.subscriptions.push(I)}}_parseSuback(){Q("_parseSuback");let H=this.packet;if(this.packet.granted=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let $=this._parseProperties();if(Object.getOwnPropertyNames($).length)H.properties=$}if(H.length<=0)return this._emitError(Error("Malformed suback, no payload specified"));while(this._pos<this.packet.length){let $=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!DH.MQTT5_SUBACK_CODES[$])return this._emitError(Error("Invalid suback code"))}else if($>2&&$!==128)return this._emitError(Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push($)}}_parseUnsubscribe(){Q("_parseUnsubscribe");let H=this.packet;if(H.unsubscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let $=this._parseProperties();if(Object.getOwnPropertyNames($).length)H.properties=$}if(H.length<=0)return this._emitError(Error("Malformed unsubscribe, no payload specified"));while(this._pos<H.length){let $=this._parseString();if($===null)return this._emitError(Error("Cannot parse topic"));Q("_parseUnsubscribe: push topic `%s` to unsubscriptions",$),H.unsubscriptions.push($)}}_parseUnsuback(){Q("_parseUnsuback");let H=this.packet;if(!this._parseMessageId())return this._emitError(Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&H.length!==2)return this._emitError(Error("Malformed unsuback, payload length must be 2"));if(H.length<=0)return this._emitError(Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let $=this._parseProperties();if(Object.getOwnPropertyNames($).length)H.properties=$;H.granted=[];while(this._pos<this.packet.length){let A=this._list.readUInt8(this._pos++);if(!DH.MQTT5_UNSUBACK_CODES[A])return this._emitError(Error("Invalid unsuback code"));this.packet.granted.push(A)}}}_parseConfirmation(){Q("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let H=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(H.length>2){switch(H.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!DH.MQTT5_PUBACK_PUBREC_CODES[H.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!DH.MQTT5_PUBREL_PUBCOMP_CODES[H.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break}Q("_parseConfirmation: packet.reasonCode `%d`",H.reasonCode)}else H.reasonCode=0;if(H.length>3){let $=this._parseProperties();if(Object.getOwnPropertyNames($).length)H.properties=$}}return!0}_parseDisconnect(){let H=this.packet;if(Q("_parseDisconnect"),this.settings.protocolVersion===5){if(this._list.length>0){if(H.reasonCode=this._parseByte(),!DH.MQTT5_DISCONNECT_CODES[H.reasonCode])this._emitError(Error("Invalid disconnect reason code"))}else H.reasonCode=0;let $=this._parseProperties();if(Object.getOwnPropertyNames($).length)H.properties=$}return Q("_parseDisconnect result: true"),!0}_parseAuth(){Q("_parseAuth");let H=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(Error("Not supported auth packet for this version MQTT"));if(H.reasonCode=this._parseByte(),!DH.MQTT5_AUTH_CODES[H.reasonCode])return this._emitError(Error("Invalid auth reason code"));let $=this._parseProperties();if(Object.getOwnPropertyNames($).length)H.properties=$;return Q("_parseAuth: result: true"),!0}_parseMessageId(){let H=this.packet;if(H.messageId=this._parseNum(),H.messageId===null)return this._emitError(Error("Cannot parse messageId")),!1;return Q("_parseMessageId: packet.messageId %d",H.messageId),!0}_parseString(H){let $=this._parseNum(),A=$+this._pos;if($===-1||A>this._list.length||A>this.packet.length)return null;let L=this._list.toString("utf8",this._pos,A);return this._pos+=$,Q("_parseString: result: %s",L),L}_parseStringPair(){return Q("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let H=this._parseNum(),$=H+this._pos;if(H===-1||$>this._list.length||$>this.packet.length)return null;let A=this._list.slice(this._pos,$);return this._pos+=H,Q("_parseBuffer: result: %o",A),A}_parseNum(){if(this._list.length-this._pos<2)return-1;let H=this._list.readUInt16BE(this._pos);return this._pos+=2,Q("_parseNum: result: %s",H),H}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let H=this._list.readUInt32BE(this._pos);return this._pos+=4,Q("_parse4ByteNum: result: %s",H),H}_parseVarByteNum(H){Q("_parseVarByteNum");let $=4,A=0,L=1,D=0,f=!1,E,I=this._pos?this._pos:0;while(A<$&&I+A<this._list.length){if(E=this._list.readUInt8(I+A++),D+=L*(E&DH.VARBYTEINT_MASK),L*=128,(E&DH.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=A)break}if(!f&&A===$&&this._list.length>=A)this._emitError(Error("Invalid variable byte integer"));if(I)this._pos+=A;if(f)if(H)f={bytes:A,value:D};else f=D;else f=!1;return Q("_parseVarByteNum: result: %o",f),f}_parseByte(){let H;if(this._pos<this._list.length)H=this._list.readUInt8(this._pos),this._pos++;return Q("_parseByte: result: %o",H),H}_parseByType(H){switch(Q("_parseByType: type: %s",H),H){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){Q("_parseProperties");let H=this._parseVarByteNum(),A=this._pos+H,L={};while(this._pos<A){let D=this._parseByte();if(!D)return this._emitError(Error("Cannot parse property code type")),!1;let f=DH.propertiesCodes[D];if(!f)return this._emitError(Error("Unknown property")),!1;if(f==="userProperties"){if(!L[f])L[f]=Object.create(null);let E=this._parseByType(DH.propertiesTypes[f]);if(L[f][E.name])if(Array.isArray(L[f][E.name]))L[f][E.name].push(E.value);else{let I=L[f][E.name];L[f][E.name]=[I],L[f][E.name].push(E.value)}else L[f][E.name]=E.value;continue}if(L[f])if(Array.isArray(L[f]))L[f].push(this._parseByType(DH.propertiesTypes[f]));else L[f]=[L[f]],L[f].push(this._parseByType(DH.propertiesTypes[f]));else L[f]=this._parseByType(DH.propertiesTypes[f])}return L}_newPacket(){if(Q("_newPacket"),this.packet)this._list.consume(this.packet.length),Q("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet);return Q("_newPacket: new packet"),this.packet=new dV,this._pos=0,!0}_emitError(H){Q("_emitError",H),this.error=H,this.emit("error",H)}}aV.exports=e0});var kV=p((nR,NV)=>{var{Buffer:zD}=B("buffer"),yV={},b3=zD.isBuffer(zD.from([1,2]).subarray(0,1));function bV(H){let $=zD.allocUnsafe(2);return $.writeUInt8(H>>8,0),$.writeUInt8(H&255,1),$}function N3(){for(let H=0;H<65536;H++)yV[H]=bV(H)}function k3(H){let A=0,L=0,D=zD.allocUnsafe(4);do{if(A=H%128|0,H=H/128|0,H>0)A=A|128;D.writeUInt8(A,L++)}while(H>0&&L<4);if(H>0)L=0;return b3?D.subarray(0,L):D.slice(0,L)}function R3(H){let $=zD.allocUnsafe(4);return $.writeUInt32BE(H,0),$}NV.exports={cache:yV,generateCache:N3,generateNumber:bV,genBufVariableByteInt:k3,generate4ByteBuffer:R3}});var RV=p((oR,GP)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)GP.exports={nextTick:O3};else GP.exports=process;function O3(H,$,A,L){if(typeof H!=="function")throw TypeError('"callback" argument must be a function');var D=arguments.length,f,E;switch(D){case 0:case 1:return process.nextTick(H);case 2:return process.nextTick(function(){H.call(null,$)});case 3:return process.nextTick(function(){H.call(null,$,A)});case 4:return process.nextTick(function(){H.call(null,$,A,L)});default:f=Array(D-1),E=0;while(E<f.length)f[E++]=arguments[E];return process.nextTick(function(){H.apply(null,f)})}}});var lP=p((FR,KV)=>{var K=sP(),{Buffer:j}=B("buffer"),m3=j.allocUnsafe(0),w3=j.from([0]),Hf=kV(),e3=RV().nextTick,s$=K$()("mqtt-packet:writeToStream"),j0=Hf.cache,j3=Hf.generateNumber,J3=Hf.generateCache,dP=Hf.genBufVariableByteInt,Q3=Hf.generate4ByteBuffer,D$=aP,J0=!0;function JV(H,$,A){if(s$("generate called"),$.cork)$.cork(),e3(K3,$);if(J0)J0=!1,J3();switch(s$("generate: packet.cmd: %s",H.cmd),H.cmd){case"connect":return g3(H,$,A);case"connack":return v3(H,$,A);case"publish":return Y3(H,$,A);case"puback":case"pubrec":case"pubrel":case"pubcomp":return q3(H,$,A);case"subscribe":return Z3(H,$,A);case"suback":return z3(H,$,A);case"unsubscribe":return H5(H,$,A);case"unsuback":return $5(H,$,A);case"pingreq":case"pingresp":return A5(H,$,A);case"disconnect":return L5(H,$,A);case"auth":return D5(H,$,A);default:return $.destroy(Error("Unknown command")),!1}}Object.defineProperty(JV,"cacheNumbers",{get(){return D$===aP},set(H){if(H){if(!j0||Object.keys(j0).length===0)J0=!0;D$=aP}else J0=!1,D$=f5}});function K3(H){H.uncork()}function g3(H,$,A){let L=H||{},D=L.protocolId||"MQTT",f=L.protocolVersion||4,E=L.will,I=L.clean,P=L.keepalive||0,T=L.clientId||"",U=L.username,M=L.password,t=L.properties;if(I===void 0)I=!0;let _=0;if(!D||typeof D!=="string"&&!j.isBuffer(D))return $.destroy(Error("Invalid protocolId")),!1;else _+=D.length+2;if(f!==3&&f!==4&&f!==5)return $.destroy(Error("Invalid protocol version")),!1;else _+=1;if((typeof T==="string"||j.isBuffer(T))&&(T||f>=4)&&(T||I))_+=j.byteLength(T)+2;else{if(f<4)return $.destroy(Error("clientId must be supplied before 3.1.1")),!1;if(I*1===0)return $.destroy(Error("clientId must be given if cleanSession set to 0")),!1}if(typeof P!=="number"||P<0||P>65535||P%1!==0)return $.destroy(Error("Invalid keepalive")),!1;else _+=2;_+=1;let x,V;if(f===5){if(x=AL($,t),!x)return!1;_+=x.length}if(E){if(typeof E!=="object")return $.destroy(Error("Invalid will")),!1;if(!E.topic||typeof E.topic!=="string")return $.destroy(Error("Invalid will topic")),!1;else _+=j.byteLength(E.topic)+2;if(_+=2,E.payload)if(E.payload.length>=0)if(typeof E.payload==="string")_+=j.byteLength(E.payload);else _+=E.payload.length;else return $.destroy(Error("Invalid will payload")),!1;if(V={},f===5){if(V=AL($,E.properties),!V)return!1;_+=V.length}}let h=!1;if(U!=null)if(jV(U))h=!0,_+=j.byteLength(U)+2;else return $.destroy(Error("Invalid username")),!1;if(M!=null){if(!h)return $.destroy(Error("Username is required to use password")),!1;if(jV(M))_+=QV(M)+2;else return $.destroy(Error("Invalid password")),!1}if($.write(K.CONNECT_HEADER),C$($,_),tD($,D),L.bridgeMode)f+=128;$.write(f===131?K.VERSION131:f===132?K.VERSION132:f===4?K.VERSION4:f===5?K.VERSION5:K.VERSION3);let W=0;if(W|=U!=null?K.USERNAME_MASK:0,W|=M!=null?K.PASSWORD_MASK:0,W|=E&&E.retain?K.WILL_RETAIN_MASK:0,W|=E&&E.qos?E.qos<<K.WILL_QOS_SHIFT:0,W|=E?K.WILL_FLAG_MASK:0,W|=I?K.CLEAN_SESSION_MASK:0,$.write(j.from([W])),D$($,P),f===5)x.write();if(tD($,T),E){if(f===5)V.write();iL($,E.topic),tD($,E.payload)}if(U!=null)tD($,U);if(M!=null)tD($,M);return!0}function v3(H,$,A){let L=A?A.protocolVersion:4,D=H||{},f=L===5?D.reasonCode:D.returnCode,E=D.properties,I=2;if(typeof f!=="number")return $.destroy(Error("Invalid return code")),!1;let P=null;if(L===5){if(P=AL($,E),!P)return!1;I+=P.length}if($.write(K.CONNACK_HEADER),C$($,I),$.write(D.sessionPresent?K.SESSIONPRESENT_HEADER:w3),$.write(j.from([f])),P!=null)P.write();return!0}function Y3(H,$,A){s$("publish: packet: %o",H);let L=A?A.protocolVersion:4,D=H||{},f=D.qos||0,E=D.retain?K.RETAIN_MASK:0,I=D.topic,P=D.payload||m3,T=D.messageId,U=D.properties,M=0;if(typeof I==="string")M+=j.byteLength(I)+2;else if(j.isBuffer(I))M+=I.length+2;else return $.destroy(Error("Invalid topic")),!1;if(!j.isBuffer(P))M+=j.byteLength(P);else M+=P.length;if(f&&typeof T!=="number")return $.destroy(Error("Invalid messageId")),!1;else if(f)M+=2;let t=null;if(L===5){if(t=AL($,U),!t)return!1;M+=t.length}if($.write(K.PUBLISH_HEADER[f][D.dup?1:0][E?1:0]),C$($,M),D$($,QV(I)),$.write(I),f>0)D$($,T);if(t!=null)t.write();return s$("publish: payload: %o",P),$.write(P)}function q3(H,$,A){let L=A?A.protocolVersion:4,D=H||{},f=D.cmd||"puback",E=D.messageId,I=D.dup&&f==="pubrel"?K.DUP_MASK:0,P=0,T=D.reasonCode,U=D.properties,M=L===5?3:2;if(f==="pubrel")P=1;if(typeof E!=="number")return $.destroy(Error("Invalid messageId")),!1;let t=null;if(L===5){if(typeof U==="object"){if(t=$f($,U,A,M),!t)return!1;M+=t.length}}if($.write(K.ACKS[f][P][I][0]),M===3)M+=T!==0?1:-1;if(C$($,M),D$($,E),L===5&&M!==2)$.write(j.from([T]));if(t!==null)t.write();else if(M===4)$.write(j.from([0]));return!0}function Z3(H,$,A){s$("subscribe: packet: ");let L=A?A.protocolVersion:4,D=H||{},f=D.dup?K.DUP_MASK:0,E=D.messageId,I=D.subscriptions,P=D.properties,T=0;if(typeof E!=="number")return $.destroy(Error("Invalid messageId")),!1;else T+=2;let U=null;if(L===5){if(U=AL($,P),!U)return!1;T+=U.length}if(typeof I==="object"&&I.length)for(let t=0;t<I.length;t+=1){let _=I[t].topic,x=I[t].qos;if(typeof _!=="string")return $.destroy(Error("Invalid subscriptions - invalid topic")),!1;if(typeof x!=="number")return $.destroy(Error("Invalid subscriptions - invalid qos")),!1;if(L===5){if(typeof(I[t].nl||!1)!=="boolean")return $.destroy(Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(I[t].rap||!1)!=="boolean")return $.destroy(Error("Invalid subscriptions - invalid Retain as Published")),!1;let W=I[t].rh||0;if(typeof W!=="number"||W>2)return $.destroy(Error("Invalid subscriptions - invalid Retain Handling")),!1}T+=j.byteLength(_)+2+1}else return $.destroy(Error("Invalid subscriptions")),!1;if(s$("subscribe: writing to stream: %o",K.SUBSCRIBE_HEADER),$.write(K.SUBSCRIBE_HEADER[1][f?1:0][0]),C$($,T),D$($,E),U!==null)U.write();let M=!0;for(let t of I){let{topic:_,qos:x}=t,V=+t.nl,h=+t.rap,W=t.rh,c;if(iL($,_),c=K.SUBSCRIBE_OPTIONS_QOS[x],L===5)c|=V?K.SUBSCRIBE_OPTIONS_NL:0,c|=h?K.SUBSCRIBE_OPTIONS_RAP:0,c|=W?K.SUBSCRIBE_OPTIONS_RH[W]:0;M=$.write(j.from([c]))}return M}function z3(H,$,A){let L=A?A.protocolVersion:4,D=H||{},f=D.messageId,E=D.granted,I=D.properties,P=0;if(typeof f!=="number")return $.destroy(Error("Invalid messageId")),!1;else P+=2;if(typeof E==="object"&&E.length)for(let U=0;U<E.length;U+=1){if(typeof E[U]!=="number")return $.destroy(Error("Invalid qos vector")),!1;P+=1}else return $.destroy(Error("Invalid qos vector")),!1;let T=null;if(L===5){if(T=$f($,I,A,P),!T)return!1;P+=T.length}if($.write(K.SUBACK_HEADER),C$($,P),D$($,f),T!==null)T.write();return $.write(j.from(E))}function H5(H,$,A){let L=A?A.protocolVersion:4,D=H||{},f=D.messageId,E=D.dup?K.DUP_MASK:0,I=D.unsubscriptions,P=D.properties,T=0;if(typeof f!=="number")return $.destroy(Error("Invalid messageId")),!1;else T+=2;if(typeof I==="object"&&I.length)for(let t=0;t<I.length;t+=1){if(typeof I[t]!=="string")return $.destroy(Error("Invalid unsubscriptions")),!1;T+=j.byteLength(I[t])+2}else return $.destroy(Error("Invalid unsubscriptions")),!1;let U=null;if(L===5){if(U=AL($,P),!U)return!1;T+=U.length}if($.write(K.UNSUBSCRIBE_HEADER[1][E?1:0][0]),C$($,T),D$($,f),U!==null)U.write();let M=!0;for(let t=0;t<I.length;t++)M=iL($,I[t]);return M}function $5(H,$,A){let L=A?A.protocolVersion:4,D=H||{},f=D.messageId,E=D.dup?K.DUP_MASK:0,I=D.granted,P=D.properties,T=D.cmd,U=0,M=2;if(typeof f!=="number")return $.destroy(Error("Invalid messageId")),!1;if(L===5)if(typeof I==="object"&&I.length)for(let _=0;_<I.length;_+=1){if(typeof I[_]!=="number")return $.destroy(Error("Invalid qos vector")),!1;M+=1}else return $.destroy(Error("Invalid qos vector")),!1;let t=null;if(L===5){if(t=$f($,P,A,M),!t)return!1;M+=t.length}if($.write(K.ACKS[T][0][E][0]),C$($,M),D$($,f),t!==null)t.write();if(L===5)$.write(j.from(I));return!0}function A5(H,$,A){return $.write(K.EMPTY[H.cmd])}function L5(H,$,A){let L=A?A.protocolVersion:4,D=H||{},f=D.reasonCode,E=D.properties,I=L===5?1:0,P=null;if(L===5){if(P=$f($,E,A,I),!P)return!1;I+=P.length}if($.write(j.from([K.codes.disconnect<<4])),C$($,I),L===5)$.write(j.from([f]));if(P!==null)P.write();return!0}function D5(H,$,A){let L=A?A.protocolVersion:4,D=H||{},f=D.reasonCode,E=D.properties,I=L===5?1:0;if(L!==5)$.destroy(Error("Invalid mqtt version for auth packet"));let P=$f($,E,A,I);if(!P)return!1;if(I+=P.length,$.write(j.from([K.codes.auth<<4])),C$($,I),$.write(j.from([f])),P!==null)P.write();return!0}var OV={};function C$(H,$){if($>K.VARBYTEINT_MAX)return H.destroy(Error(`Invalid variable byte integer: ${$}`)),!1;let A=OV[$];if(!A){if(A=dP($),$<16384)OV[$]=A}return s$("writeVarByteInt: writing to stream: %o",A),H.write(A)}function iL(H,$){let A=j.byteLength($);return D$(H,A),s$("writeString: %s",$),H.write($,"utf8")}function mV(H,$,A){iL(H,$),iL(H,A)}function aP(H,$){return s$("writeNumberCached: number: %d",$),s$("writeNumberCached: %o",j0[$]),H.write(j0[$])}function f5(H,$){let A=j3($);return s$("writeNumberGenerated: %o",A),H.write(A)}function E5(H,$){let A=Q3($);return s$("write4ByteNumber: %o",A),H.write(A)}function tD(H,$){if(typeof $==="string")iL(H,$);else if($)D$(H,$.length),H.write($);else D$(H,0)}function AL(H,$){if(typeof $!=="object"||$.length!=null)return{length:1,write(){eV(H,{},0)}};let A=0;function L(f,E){let I=K.propertiesTypes[f],P=0;switch(I){case"byte":{if(typeof E!=="boolean")return H.destroy(Error(`Invalid ${f}: ${E}`)),!1;P+=2;break}case"int8":{if(typeof E!=="number"||E<0||E>255)return H.destroy(Error(`Invalid ${f}: ${E}`)),!1;P+=2;break}case"binary":{if(E&&E===null)return H.destroy(Error(`Invalid ${f}: ${E}`)),!1;P+=1+j.byteLength(E)+2;break}case"int16":{if(typeof E!=="number"||E<0||E>65535)return H.destroy(Error(`Invalid ${f}: ${E}`)),!1;P+=3;break}case"int32":{if(typeof E!=="number"||E<0||E>4294967295)return H.destroy(Error(`Invalid ${f}: ${E}`)),!1;P+=5;break}case"var":{if(typeof E!=="number"||E<0||E>268435455)return H.destroy(Error(`Invalid ${f}: ${E}`)),!1;P+=1+j.byteLength(dP(E));break}case"string":{if(typeof E!=="string")return H.destroy(Error(`Invalid ${f}: ${E}`)),!1;P+=3+j.byteLength(E.toString());break}case"pair":{if(typeof E!=="object")return H.destroy(Error(`Invalid ${f}: ${E}`)),!1;P+=Object.getOwnPropertyNames(E).reduce((T,U)=>{let M=E[U];if(Array.isArray(M))T+=M.reduce((t,_)=>{return t+=3+j.byteLength(U.toString())+2+j.byteLength(_.toString()),t},0);else T+=3+j.byteLength(U.toString())+2+j.byteLength(E[U].toString());return T},0);break}default:return H.destroy(Error(`Invalid property ${f}: ${E}`)),!1}return P}if($)for(let f in $){let E=0,I=0,P=$[f];if(P===void 0)continue;else if(Array.isArray(P))for(let T=0;T<P.length;T++){if(I=L(f,P[T]),!I)return!1;E+=I}else{if(I=L(f,P),!I)return!1;E=I}if(!E)return!1;A+=E}return{length:j.byteLength(dP(A))+A,write(){eV(H,$,A)}}}function $f(H,$,A,L){let D=["reasonString","userProperties"],f=A&&A.properties&&A.properties.maximumPacketSize?A.properties.maximumPacketSize:0,E=AL(H,$);if(f)while(L+E.length>f){let I=D.shift();if(I&&$[I])delete $[I],E=AL(H,$);else return!1}return E}function wV(H,$,A){switch(K.propertiesTypes[$]){case"byte":{H.write(j.from([K.properties[$]])),H.write(j.from([+A]));break}case"int8":{H.write(j.from([K.properties[$]])),H.write(j.from([A]));break}case"binary":{H.write(j.from([K.properties[$]])),tD(H,A);break}case"int16":{H.write(j.from([K.properties[$]])),D$(H,A);break}case"int32":{H.write(j.from([K.properties[$]])),E5(H,A);break}case"var":{H.write(j.from([K.properties[$]])),C$(H,A);break}case"string":{H.write(j.from([K.properties[$]])),iL(H,A);break}case"pair":{Object.getOwnPropertyNames(A).forEach((D)=>{let f=A[D];if(Array.isArray(f))f.forEach((E)=>{H.write(j.from([K.properties[$]])),mV(H,D.toString(),E.toString())});else H.write(j.from([K.properties[$]])),mV(H,D.toString(),f.toString())});break}default:return H.destroy(Error(`Invalid property ${$} value: ${A}`)),!1}}function eV(H,$,A){C$(H,A);for(let L in $)if(Object.prototype.hasOwnProperty.call($,L)&&$[L]!=null){let D=$[L];if(Array.isArray(D))for(let f=0;f<D.length;f++)wV(H,L,D[f]);else wV(H,L,D)}}function QV(H){if(!H)return 0;else if(H instanceof j)return H.length;else return j.byteLength(H)}function jV(H){return typeof H==="string"||H instanceof j}KV.exports=JV});var qV=p((sR,YV)=>{var I5=lP(),{EventEmitter:P5}=B("events"),{Buffer:gV}=B("buffer");function T5(H,$){let A=new vV;return I5(H,A,$),A.concat()}class vV extends P5{constructor(){super();this._array=Array(20),this._i=0}write(H){return this._array[this._i++]=H,!0}concat(){let H=0,$=Array(this._array.length),A=this._array,L=0,D;for(D=0;D<A.length&&A[D]!==void 0;D++){if(typeof A[D]!=="string")$[D]=A[D].length;else $[D]=gV.byteLength(A[D]);H+=$[D]}let f=gV.allocUnsafe(H);for(D=0;D<A.length&&A[D]!==void 0;D++)if(typeof A[D]!=="string")A[D].copy(f,L),L+=$[D];else f.write(A[D],L),L+=$[D];return f}destroy(H){if(H)this.emit("error",H)}}YV.exports=T5});var Q0=p((U5)=>{U5.parser=lV().parser;U5.generate=qV();U5.writeToStream=lP()});var H8=p((iR,zV)=>{zV.exports=ZV;function ZV(H,$){if(H&&$)return ZV(H)($);if(typeof H!=="function")throw TypeError("need wrapper function");return Object.keys(H).forEach(function(L){A[L]=H[L]}),A;function A(){var L=Array(arguments.length);for(var D=0;D<L.length;D++)L[D]=arguments[D];var f=H.apply(this,L),E=L[L.length-1];if(typeof f==="function"&&f!==E)Object.keys(E).forEach(function(I){f[I]=E[I]});return f}}});var L8=p((GR,yP)=>{var $8=H8();yP.exports=$8(K0);yP.exports.strict=$8(A8);K0.proto=K0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return K0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return A8(this)},configurable:!0})});function K0(H){var $=function(){if($.called)return $.value;return $.called=!0,$.value=H.apply(this,arguments)};return $.called=!1,$}function A8(H){var $=function(){if($.called)throw Error($.onceError);return $.called=!0,$.value=H.apply(this,arguments)},A=H.name||"Function wrapped with `once`";return $.onceError=A+" shouldn't be called more than once",$.called=!1,$}});var E8=p((dR,f8)=>{var p5=L8(),V5=function(){},W5=global.Bare?queueMicrotask:process.nextTick.bind(process),u5=function(H){return H.setHeader&&typeof H.abort==="function"},x5=function(H){return H.stdio&&Array.isArray(H.stdio)&&H.stdio.length===3},D8=function(H,$,A){if(typeof $==="function")return D8(H,null,$);if(!$)$={};A=p5(A||V5);var{_writableState:L,_readableState:D}=H,f=$.readable||$.readable!==!1&&H.readable,E=$.writable||$.writable!==!1&&H.writable,I=!1,P=function(){if(!H.writable)T()},T=function(){if(E=!1,!f)A.call(H)},U=function(){if(f=!1,!E)A.call(H)},M=function(h){A.call(H,h?Error("exited with error code: "+h):null)},t=function(h){A.call(H,h)},_=function(){W5(x)},x=function(){if(I)return;if(f&&!(D&&(D.ended&&!D.destroyed)))return A.call(H,Error("premature close"));if(E&&!(L&&(L.ended&&!L.destroyed)))return A.call(H,Error("premature close"))},V=function(){H.req.on("finish",T)};if(u5(H))if(H.on("complete",T),H.on("abort",_),H.req)V();else H.on("request",V);else if(E&&!L)H.on("end",P),H.on("close",P);if(x5(H))H.on("exit",M);if(H.on("end",U),H.on("finish",T),$.error!==!1)H.on("error",t);return H.on("close",_),function(){if(I=!0,H.removeListener("complete",T),H.removeListener("abort",_),H.removeListener("request",V),H.req)H.req.removeListener("finish",T);H.removeListener("end",P),H.removeListener("close",P),H.removeListener("finish",T),H.removeListener("exit",M),H.removeListener("end",U),H.removeListener("error",t),H.removeListener("close",_)}};f8.exports=D8});var bA=p((aR,I8)=>{var h5=Q0();function c5(H,$,A){let L=null;if(H.connecting||H.connected)try{if(!h5.writeToStream($,H.conn)&&!H.errored){H.conn.once("drain",A);return}}catch(D){L=Error("packet received not valid")}else L=Error("connection closed");setImmediate(A,L,H)}I8.exports=c5});var bP=p((lR,U8)=>{var P8=vL(),X5=B("util");function T8(H,$){if(P8.call(this,H,$.broker),this.writeCallback=$._onError.bind($),!H.messageId)if(this.messageId=$._nextId,$._nextId>=65535)$._nextId=1;else $._nextId++;else this.messageId=H.messageId}X5.inherits(T8,P8);U8.exports=T8});var _8=p((yR,t8)=>{var S5=qf(),M8=[];function r5(H,$){if(Array.isArray(H))$=H,H=null;var A=S5(B5);return $?f:L;function L(){var E=A.get();if(E.release=D,arguments.length===3)E.context=arguments[0],E.list=arguments[1],E.callback=arguments[2]||Af;else E.context=H,E.list=arguments[0],E.callback=arguments[1]||Af;E.work()}function D(E){A.release(E)}function f(){var E=A.get();E.release=D,E.list=$;var I,P,T=arguments.length-1;switch(E.context=this||H,E.callback=arguments[T]||Af,T){case 0:E.work();break;case 1:E.work(null,arguments[0]);break;case 2:E.work(null,arguments[0],arguments[1]);break;case 3:E.work(null,arguments[0],arguments[1],arguments[2]);break;case 4:E.work(null,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:I=Array(T+1),I[0]=null;for(P=0;P<T;P++)I[P+1]=arguments[P];E.work.apply(null,I)}}}function Af(){}function B5(){this.list=M8,this.callback=Af,this.count=0,this.context=void 0,this.release=Af;var H=this;this.work=function $(){if(arguments.length>0&&arguments[0])return H.callback.call(H.context,arguments[0]);var A=arguments.length,L,D,f;if(H.count<H.list.length)switch(f=H.list[H.count++],A){case 0:case 1:return f.call(H.context,$);case 2:return f.call(H.context,arguments[1],$);case 3:return f.call(H.context,arguments[1],arguments[2],$);case 4:return f.call(H.context,arguments[1],arguments[2],arguments[3],$);default:D=Array(A);for(L=1;L<A;L++)D[L-1]=arguments[L];D[A-1]=$,f.apply(H.context,D)}else{switch(A){case 0:H.callback.call(H.context);break;case 1:H.callback.call(H.context,arguments[0]);break;case 2:H.callback.call(H.context,arguments[0],arguments[1]);break;case 3:H.callback.call(H.context,arguments[0],arguments[1],arguments[2]);break;case 4:H.callback.call(H.context,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:D=Array(A);for(L=0;L<A;L++)D[L]=arguments[L];H.callback.apply(H.context,D)}H.context=void 0,H.list=M8,H.count=0,H.release(H)}}}t8.exports=r5});var GL=p((bR,p8)=>{var{Transform:n5,Writable:o5}=B("stream");function F5(H,$){if(!H||H.length===0)return Error("impossible to "+$+" to an empty topic");let A=H.length-1,L=A-1,D=L>0&&H.charCodeAt(L)!==47;for(let f=0;f<H.length;f++)switch(H.charCodeAt(f)){case 35:{if(f!==A||D)return Error("# is only allowed in "+$+" in the last position");break}case 43:{let E=f<A-1&&H.charCodeAt(f+1)!==47,I=f>1&&H.charCodeAt(f-1)!==47;if(E||I)return Error("+ is only allowed in "+$+" between /");break}}}function s5(H){return new n5({objectMode:!0,transform:H})}function C5(H){return new o5({objectMode:!0,writev:function($,A){H($.map((L)=>L.chunk),A)}})}p8.exports={validateTopic:F5,through:s5,bulk:C5,$SYS_PREFIX:"$SYS/"}});var g0=p((NR,c8)=>{var W8=_8(),u8=vL(),{through:i5}=GL(),{validateTopic:G5,$SYS_PREFIX:d5}=GL(),a5=bA(),l5=W8([x8,e5,h8]),y5=W8([x8,h8]);function b5(H,$){this.cmd="suback",this.messageId=H.messageId,this.granted=$}function V8(H,$,A,L,D){this.qos=H,this.func=$,this.rh=A,this.rap=L,this.nl=D}function N5(H,$,A,L){this.client=H,this.packet=$,this.actions=A?y5:l5,this.finish=L,this.subState=[]}function k5(H,$,A,L,D,f){this.client=H,this.packet=$,this.granted=A,this.rh=L,this.rap=D,this.nl=f}function R5(H){let $={};for(let L=0;L<H.length;L++){let D=H[L];$[D.topic]=D}let A=[];for(let L in $)A.push($[L]);return A}function O5(H,$,A,L){$.subscriptions=$.subscriptions.length===1?$.subscriptions:R5($.subscriptions),H.broker._parallel(new N5(H,$,A,L),m5,$.subscriptions,A?L:J5)}function m5(H,$){let A=new k5(this.client,this.packet,H.qos,H.rh,H.rap,H.nl);this.subState.push(A),this.actions.call(A,H,$)}function x8(H,$){let A=G5(H.topic,"SUBSCRIBE");if(A)return $(A);let L=this.client;L.broker.authorizeSubscribe(L,H,$)}function w5(H){return function(A,L){if(A.topic.charCodeAt(0)===36)L();else H(A,L)}}function e5(H,$){if(!H||typeof H!=="object")return this.granted=128,$(null,null);let A=this.packet,L=this.client;if(L.clean)return $(null,H);L.broker.persistence.addSubscriptions(L,A.subscriptions,function(f){$(f,H)})}function h8(H,$){if(!H||typeof H!=="object")return $();let A=this.client,L=A.broker,D=H.topic,f=H.qos,E=this.rh,I=this.rap,P=this.nl,T=f>0?A.deliverQoS:A.deliver0,U=T;if(T=function(t,_){if(t=new u8(t,L),t.nl=P,!I)t.retain=!1;U(t,_)},j5(D))T=w5(T);if(A.closed||A.broker.closed)return;if(!A.subscriptions[D])A.subscriptions[D]=new V8(f,T,E,I,P),L.subscribe(D,T,$);else if(A.subscriptions[D].qos!==f||A.subscriptions[D].rh!==E||A.subscriptions[D].rap!==I||A.subscriptions[D].nl!==P)L.unsubscribe(D,A.subscriptions[D].func),A.subscriptions[D]=new V8(f,T,E,I,P),L.subscribe(D,T,$);else $()}function j5(H){let $=H.charCodeAt(0);return $===43||$===35}function J5(H){let $=this.finish;if(H)return $(H);let A=this.packet,L=this.client;if(A.messageId!==void 0)a5(L,new b5(A,this.subState.map((I)=>I.granted)),$);else $();let D=L.broker,f=A.subscriptions,E=[];for(let I=0;I<f.length;I++){if(this.subState[I].granted!==128)E.push(f[I].topic);f[I].qos=this.subState[I].granted}if(this.subState=[],D.emit("subscribe",f,L),D.publish({topic:d5+D.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:L.id,subs:f}),"utf8")},Q5),E.length>0)D.persistence.createRetainedStreamCombi(E).pipe(i5(function(U,M,t){U=new u8({cmd:U.cmd,qos:U.qos,topic:U.topic,payload:U.payload,retain:!0},D),U.brokerId=null,L.deliverQoS(U,t)}))}function Q5(){}c8.exports=O5});var kP=p((kR,X8)=>{var K5=bA(),{validateTopic:g5,$SYS_PREFIX:v5}=GL();function Y5(H){this.cmd="unsuback",this.messageId=H.messageId}function q5(H,$,A){this.client=H,this.packet=$,this.finish=A}function Z5(H,$,A){let L=H.broker,D=$.unsubscriptions,f;for(let E=0;E<D.length;E++)if(f=g5(D[E],"UNSUBSCRIBE"),f)return A(f);if($.messageId!==void 0){if(H.clean)return NP(H,$,A);L.persistence.removeSubscriptions(H,D,function(E){if(E)return A(E);NP(H,$,A)})}else NP(H,$,A)}function NP(H,$,A){H.broker._parallel(new q5(H,$,A),z5,$.unsubscriptions,HC)}function z5(H,$){let A=this.client,L=A.broker,D=A.subscriptions[H];if(D){let f=D.func;delete A.subscriptions[H],L.unsubscribe(H,f,$)}else $()}function HC(H){let $=this.client;if(H){$.emit("error",H);return}let A=this.packet,L=this.finish;if(A.messageId!==void 0)K5($,new Y5(A),L);else L();if((!$.closed||$.clean===!0)&&A.unsubscriptions.length>0)$.broker.emit("unsubscribe",A.unsubscriptions,$),$.broker.publish({topic:v5+$.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:$.id,subs:A.unsubscriptions}),"utf8")},$C)}function $C(){}X8.exports=Z5});var r8=p((RR,S8)=>{S8.exports=function(){let $=process.hrtime();return Math.floor($[0]*1000+$[1]/1e6)}});var n8=p((OR,B8)=>{B8.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var s8=p((mR,OP)=>{var v0=r8(),{clearTimeout:o8,setTimeout:F8}=n8();class RP{constructor(H,$,A){let L=this;this._started=v0(),this._rescheduled=0,this._scheduled=$,this._args=A,this._triggered=!1,this._timerWrapper=()=>{if(L._rescheduled>0)L._scheduled=L._rescheduled-(v0()-L._started),L._schedule(L._scheduled);else L._triggered=!0,H.apply(null,L._args)},this._timer=F8(this._timerWrapper,$)}reschedule(H){if(!H)H=this._scheduled;let $=v0();if($+H-(this._started+this._scheduled)<0)o8(this._timer),this._schedule(H);else if(!this._triggered)this._started=$,this._rescheduled=H;else this._schedule(H)}_schedule(H){this._triggered=!1,this._started=v0(),this._rescheduled=0,this._scheduled=H,this._timer=F8(this._timerWrapper,H)}clear(){o8(this._timer)}}function AC(){if(typeof arguments[0]!=="function")throw Error("callback needed");if(typeof arguments[1]!=="number")throw Error("timeout needed");let H;if(arguments.length>0){H=Array(arguments.length-2);for(var $=0;$<H.length;$++)H[$]=arguments[$+2]}return new RP(arguments[0],arguments[1],H)}OP.exports=AC;OP.exports.Retimer=RP});var mP=p((C8)=>{Object.defineProperty(C8,"__esModule",{value:!0});C8.default=fC;var LC=DC(B("crypto"));function DC(H){return H&&H.__esModule?H:{default:H}}var q0=new Uint8Array(256),Y0=q0.length;function fC(){if(Y0>q0.length-16)LC.default.randomFillSync(q0),Y0=0;return q0.slice(Y0,Y0+=16)}});var d8=p((i8)=>{Object.defineProperty(i8,"__esModule",{value:!0});i8.default=void 0;var IC=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;i8.default=IC});var Lf=p((a8)=>{Object.defineProperty(a8,"__esModule",{value:!0});a8.default=void 0;var PC=TC(d8());function TC(H){return H&&H.__esModule?H:{default:H}}function UC(H){return typeof H==="string"&&PC.default.test(H)}var MC=UC;a8.default=MC});var Df=p((y8)=>{Object.defineProperty(y8,"__esModule",{value:!0});y8.default=void 0;var tC=_C(Lf());function _C(H){return H&&H.__esModule?H:{default:H}}var QH=[];for(let H=0;H<256;++H)QH.push((H+256).toString(16).substr(1));function pC(H,$=0){let A=(QH[H[$+0]]+QH[H[$+1]]+QH[H[$+2]]+QH[H[$+3]]+"-"+QH[H[$+4]]+QH[H[$+5]]+"-"+QH[H[$+6]]+QH[H[$+7]]+"-"+QH[H[$+8]]+QH[H[$+9]]+"-"+QH[H[$+10]]+QH[H[$+11]]+QH[H[$+12]]+QH[H[$+13]]+QH[H[$+14]]+QH[H[$+15]]).toLowerCase();if(!(0,tC.default)(A))throw TypeError("Stringified UUID is invalid");return A}var VC=pC;y8.default=VC});var m8=p((R8)=>{Object.defineProperty(R8,"__esModule",{value:!0});R8.default=void 0;var WC=k8(mP()),uC=k8(Df());function k8(H){return H&&H.__esModule?H:{default:H}}var N8,wP,eP=0,jP=0;function xC(H,$,A){let L=$&&A||0,D=$||Array(16);H=H||{};let f=H.node||N8,E=H.clockseq!==void 0?H.clockseq:wP;if(f==null||E==null){let t=H.random||(H.rng||WC.default)();if(f==null)f=N8=[t[0]|1,t[1],t[2],t[3],t[4],t[5]];if(E==null)E=wP=(t[6]<<8|t[7])&16383}let I=H.msecs!==void 0?H.msecs:Date.now(),P=H.nsecs!==void 0?H.nsecs:jP+1,T=I-eP+(P-jP)/1e4;if(T<0&&H.clockseq===void 0)E=E+1&16383;if((T<0||I>eP)&&H.nsecs===void 0)P=0;if(P>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");eP=I,jP=P,wP=E,I+=12219292800000;let U=((I&268435455)*1e4+P)%4294967296;D[L++]=U>>>24&255,D[L++]=U>>>16&255,D[L++]=U>>>8&255,D[L++]=U&255;let M=I/4294967296*1e4&268435455;D[L++]=M>>>8&255,D[L++]=M&255,D[L++]=M>>>24&15|16,D[L++]=M>>>16&255,D[L++]=E>>>8|128,D[L++]=E&255;for(let t=0;t<6;++t)D[L+t]=f[t];return $||(0,uC.default)(D)}var hC=xC;R8.default=hC});var JP=p((w8)=>{Object.defineProperty(w8,"__esModule",{value:!0});w8.default=void 0;var cC=XC(Lf());function XC(H){return H&&H.__esModule?H:{default:H}}function SC(H){if(!(0,cC.default)(H))throw TypeError("Invalid UUID");let $,A=new Uint8Array(16);return A[0]=($=parseInt(H.slice(0,8),16))>>>24,A[1]=$>>>16&255,A[2]=$>>>8&255,A[3]=$&255,A[4]=($=parseInt(H.slice(9,13),16))>>>8,A[5]=$&255,A[6]=($=parseInt(H.slice(14,18),16))>>>8,A[7]=$&255,A[8]=($=parseInt(H.slice(19,23),16))>>>8,A[9]=$&255,A[10]=($=parseInt(H.slice(24,36),16))/1099511627776&255,A[11]=$/4294967296&255,A[12]=$>>>24&255,A[13]=$>>>16&255,A[14]=$>>>8&255,A[15]=$&255,A}var rC=SC;w8.default=rC});var QP=p((K8)=>{Object.defineProperty(K8,"__esModule",{value:!0});K8.default=FC;K8.URL=K8.DNS=void 0;var BC=j8(Df()),nC=j8(JP());function j8(H){return H&&H.__esModule?H:{default:H}}function oC(H){H=unescape(encodeURIComponent(H));let $=[];for(let A=0;A<H.length;++A)$.push(H.charCodeAt(A));return $}var J8="6ba7b810-9dad-11d1-80b4-00c04fd430c8";K8.DNS=J8;var Q8="6ba7b811-9dad-11d1-80b4-00c04fd430c8";K8.URL=Q8;function FC(H,$,A){function L(D,f,E,I){if(typeof D==="string")D=oC(D);if(typeof f==="string")f=(0,nC.default)(f);if(f.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let P=new Uint8Array(16+D.length);if(P.set(f),P.set(D,f.length),P=A(P),P[6]=P[6]&15|$,P[8]=P[8]&63|128,E){I=I||0;for(let T=0;T<16;++T)E[I+T]=P[T];return E}return(0,BC.default)(P)}try{L.name=H}catch(D){}return L.DNS=J8,L.URL=Q8,L}});var q8=p((v8)=>{Object.defineProperty(v8,"__esModule",{value:!0});v8.default=void 0;var iC=GC(B("crypto"));function GC(H){return H&&H.__esModule?H:{default:H}}function dC(H){if(Array.isArray(H))H=Buffer.from(H);else if(typeof H==="string")H=Buffer.from(H,"utf8");return iC.default.createHash("md5").update(H).digest()}var aC=dC;v8.default=aC});var $W=p((z8)=>{Object.defineProperty(z8,"__esModule",{value:!0});z8.default=void 0;var lC=Z8(QP()),yC=Z8(q8());function Z8(H){return H&&H.__esModule?H:{default:H}}var bC=(0,lC.default)("v3",48,yC.default),NC=bC;z8.default=NC});var fW=p((LW)=>{Object.defineProperty(LW,"__esModule",{value:!0});LW.default=void 0;var kC=AW(mP()),RC=AW(Df());function AW(H){return H&&H.__esModule?H:{default:H}}function OC(H,$,A){H=H||{};let L=H.random||(H.rng||kC.default)();if(L[6]=L[6]&15|64,L[8]=L[8]&63|128,$){A=A||0;for(let D=0;D<16;++D)$[A+D]=L[D];return $}return(0,RC.default)(L)}var mC=OC;LW.default=mC});var PW=p((EW)=>{Object.defineProperty(EW,"__esModule",{value:!0});EW.default=void 0;var wC=eC(B("crypto"));function eC(H){return H&&H.__esModule?H:{default:H}}function jC(H){if(Array.isArray(H))H=Buffer.from(H);else if(typeof H==="string")H=Buffer.from(H,"utf8");return wC.default.createHash("sha1").update(H).digest()}var JC=jC;EW.default=JC});var tW=p((UW)=>{Object.defineProperty(UW,"__esModule",{value:!0});UW.default=void 0;var QC=TW(QP()),KC=TW(PW());function TW(H){return H&&H.__esModule?H:{default:H}}var gC=(0,QC.default)("v5",80,KC.default),vC=gC;UW.default=vC});var VW=p((_W)=>{Object.defineProperty(_W,"__esModule",{value:!0});_W.default=void 0;var YC="00000000-0000-0000-0000-000000000000";_W.default=YC});var xW=p((WW)=>{Object.defineProperty(WW,"__esModule",{value:!0});WW.default=void 0;var qC=ZC(Lf());function ZC(H){return H&&H.__esModule?H:{default:H}}function zC(H){if(!(0,qC.default)(H))throw TypeError("Invalid UUID");return parseInt(H.substr(14,1),16)}var Hi=zC;WW.default=Hi});var hW=p((g$)=>{Object.defineProperty(g$,"__esModule",{value:!0});Object.defineProperty(g$,"v1",{enumerable:!0,get:function(){return $i.default}});Object.defineProperty(g$,"v3",{enumerable:!0,get:function(){return Ai.default}});Object.defineProperty(g$,"v4",{enumerable:!0,get:function(){return Li.default}});Object.defineProperty(g$,"v5",{enumerable:!0,get:function(){return Di.default}});Object.defineProperty(g$,"NIL",{enumerable:!0,get:function(){return fi.default}});Object.defineProperty(g$,"version",{enumerable:!0,get:function(){return Ei.default}});Object.defineProperty(g$,"validate",{enumerable:!0,get:function(){return Ii.default}});Object.defineProperty(g$,"stringify",{enumerable:!0,get:function(){return Pi.default}});Object.defineProperty(g$,"parse",{enumerable:!0,get:function(){return Ti.default}});var $i=NA(m8()),Ai=NA($W()),Li=NA(fW()),Di=NA(tW()),fi=NA(VW()),Ei=NA(xW()),Ii=NA(Lf()),Pi=NA(Df()),Ti=NA(JP());function NA(H){return H&&H.__esModule?H:{default:H}}});var SW=p((LO,XW)=>{var Ui=hW(),cW=B("crypto");XW.exports=typeof cW.randomUUID==="function"?cW.randomUUID:Ui.v4});var nW=p((DO,BW)=>{var KP=[],rW={};for(LL=0;LL<256;LL++)KP[LL]=(LL+256).toString(16).substr(1),rW[KP[LL]]=LL;var LL;function Mi(H,$,A){var L=$&&A||0,D=0;$=$||[],H.toLowerCase().replace(/[0-9a-f]{2}/g,function(f){if(D<16)$[L+D++]=rW[f]});while(D<16)$[L+D++]=0;return $}function ti(H,$){var A=$||0,L=KP;return L[H[A++]]+L[H[A++]]+L[H[A++]]+L[H[A++]]+"-"+L[H[A++]]+L[H[A++]]+"-"+L[H[A++]]+L[H[A++]]+"-"+L[H[A++]]+L[H[A++]]+"-"+L[H[A++]]+L[H[A++]]+L[H[A++]]+L[H[A++]]+L[H[A++]]+L[H[A++]]}BW.exports={parse:Mi,unparse:ti}});var FW=p((ci)=>{ci.byteLength=pi;ci.toByteArray=Wi;ci.fromByteArray=hi;var tA=[],i$=[],_i=typeof Uint8Array<"u"?Uint8Array:Array,gP="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(DL=0,vP=gP.length;DL<vP;++DL)tA[DL]=gP[DL],i$[gP.charCodeAt(DL)]=DL;var DL,vP;i$[45]=62;i$[95]=63;function oW(H){var $=H.length;if($%4>0)throw Error("Invalid string. Length must be a multiple of 4");var A=H.indexOf("=");if(A===-1)A=$;var L=A===$?0:4-A%4;return[A,L]}function pi(H){var $=oW(H),A=$[0],L=$[1];return(A+L)*3/4-L}function Vi(H,$,A){return($+A)*3/4-A}function Wi(H){var $,A=oW(H),L=A[0],D=A[1],f=new _i(Vi(H,L,D)),E=0,I=D>0?L-4:L,P;for(P=0;P<I;P+=4)$=i$[H.charCodeAt(P)]<<18|i$[H.charCodeAt(P+1)]<<12|i$[H.charCodeAt(P+2)]<<6|i$[H.charCodeAt(P+3)],f[E++]=$>>16&255,f[E++]=$>>8&255,f[E++]=$&255;if(D===2)$=i$[H.charCodeAt(P)]<<2|i$[H.charCodeAt(P+1)]>>4,f[E++]=$&255;if(D===1)$=i$[H.charCodeAt(P)]<<10|i$[H.charCodeAt(P+1)]<<4|i$[H.charCodeAt(P+2)]>>2,f[E++]=$>>8&255,f[E++]=$&255;return f}function ui(H){return tA[H>>18&63]+tA[H>>12&63]+tA[H>>6&63]+tA[H&63]}function xi(H,$,A){var L,D=[];for(var f=$;f<A;f+=3)L=(H[f]<<16&16711680)+(H[f+1]<<8&65280)+(H[f+2]&255),D.push(ui(L));return D.join("")}function hi(H){var $,A=H.length,L=A%3,D=[],f=16383;for(var E=0,I=A-L;E<I;E+=f)D.push(xi(H,E,E+f>I?I:E+f));if(L===1)$=H[A-1],D.push(tA[$>>2]+tA[$<<4&63]+"==");else if(L===2)$=(H[A-2]<<8)+H[A-1],D.push(tA[$>>10]+tA[$>>4&63]+tA[$<<2&63]+"=");return D.join("")}});var sW=p((Bi)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Bi.read=function(H,$,A,L,D){var f,E,I=D*8-L-1,P=(1<<I)-1,T=P>>1,U=-7,M=A?D-1:0,t=A?-1:1,_=H[$+M];M+=t,f=_&(1<<-U)-1,_>>=-U,U+=I;for(;U>0;f=f*256+H[$+M],M+=t,U-=8);E=f&(1<<-U)-1,f>>=-U,U+=L;for(;U>0;E=E*256+H[$+M],M+=t,U-=8);if(f===0)f=1-T;else if(f===P)return E?NaN:(_?-1:1)*(1/0);else E=E+Math.pow(2,L),f=f-T;return(_?-1:1)*E*Math.pow(2,f-L)};Bi.write=function(H,$,A,L,D,f){var E,I,P,T=f*8-D-1,U=(1<<T)-1,M=U>>1,t=D===23?Math.pow(2,-24)-Math.pow(2,-77):0,_=L?0:f-1,x=L?1:-1,V=$<0||$===0&&1/$<0?1:0;if($=Math.abs($),isNaN($)||$===1/0)I=isNaN($)?1:0,E=U;else{if(E=Math.floor(Math.log($)/Math.LN2),$*(P=Math.pow(2,-E))<1)E--,P*=2;if(E+M>=1)$+=t/P;else $+=t*Math.pow(2,1-M);if($*P>=2)E++,P/=2;if(E+M>=U)I=0,E=U;else if(E+M>=1)I=($*P-1)*Math.pow(2,D),E=E+M;else I=$*Math.pow(2,M-1)*Math.pow(2,D),E=0}for(;D>=8;H[A+_]=I&255,_+=x,I/=256,D-=8);E=E<<D|I,T+=D;for(;T>0;H[A+_]=E&255,_+=x,E/=256,T-=8);H[A+_-x]|=V*128}});var wW=p((Yi)=>{/*!
|
|
5
|
+
`+J),_.push(L+"m+"+IA.exports.humanize(this.diff)+"\x1B[0m")}else _[0]=gR()+T+" "+_[0]}function gR(){if(HZ.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function mR(..._){return process.stderr.write(qA.formatWithOptions(HZ.inspectOpts,..._)+`
|
|
6
|
+
`)}function uR(_){if(_)process.env.DEBUG=_;else delete process.env.DEBUG}function dR(){return process.env.DEBUG}function cR(_){_.inspectOpts={};let T=Object.keys(HZ.inspectOpts);for(let A=0;A<T.length;A++)_.inspectOpts[T[A]]=HZ.inspectOpts[T[A]]}IA.exports=GE()(HZ);var{formatters:XZ}=IA.exports;XZ.o=function(_){return this.inspectOpts.colors=this.useColors,qA.inspect(_,this.inspectOpts).split(`
|
|
7
|
+
`).map((T)=>T.trim()).join(" ")};XZ.O=function(_){return this.inspectOpts.colors=this.useColors,qA.inspect(_,this.inspectOpts)}});var u1=W((_b,$E)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)$E.exports=JZ();else $E.exports=YZ()});var $Z=W((Tb,GZ)=>{var sR=rH(),{EventEmitter:tR}=j("events"),KZ=eH(),E_=KE(),n=u1()("mqtt-packet:parser");class PA extends tR{constructor(){super();this.parser=this.constructor.parser}static parser(_){if(!(this instanceof PA))return new PA().parser(_);return this.settings=_||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this}_resetState(){n("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new KZ,this.error=null,this._list=sR(),this._stateCounter=0}parse(_){if(this.error)this._resetState();this._list.append(_),n("parse: current state: %s",this._states[this._stateCounter]);while((this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error)if(this._stateCounter++,n("parse: state complete. _stateCounter is now: %d",this._stateCounter),n("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length)this._stateCounter=0;return n("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let _=this._list.readUInt8(0),T=_>>E_.CMD_SHIFT;this.packet.cmd=E_.types[T];let A=_&15,E=E_.requiredHeaderFlags[T];if(E!=null&&A!==E)return this._emitError(Error(E_.requiredHeaderFlagsErrors[T]));if(this.packet.retain=(_&E_.RETAIN_MASK)!==0,this.packet.qos=_>>E_.QOS_SHIFT&E_.QOS_MASK,this.packet.qos>2)return this._emitError(Error("Packet must not have both QoS bits set to 1"));return this.packet.dup=(_&E_.DUP_MASK)!==0,n("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){let _=this._parseVarByteNum(!0);if(_)this.packet.length=_.value,this._list.consume(_.bytes);return n("_parseLength %d",_.value),!!_}_parsePayload(){n("_parsePayload: payload %O",this._list);let _=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(Error("Not supported"))}_=!0}return n("_parsePayload complete result: %s",_),_}_parseConnect(){n("_parseConnect");let _,T,A,E,L={},J=this.packet,X=this._parseString();if(X===null)return this._emitError(Error("Cannot parse protocolId"));if(X!=="MQTT"&&X!=="MQIsdp")return this._emitError(Error("Invalid protocolId"));if(J.protocolId=X,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(J.protocolVersion=this._list.readUInt8(this._pos),J.protocolVersion>=128)J.bridgeMode=!0,J.protocolVersion=J.protocolVersion-128;if(J.protocolVersion!==3&&J.protocolVersion!==4&&J.protocolVersion!==5)return this._emitError(Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(Error("Connect flag bit 0 must be 0, but got 1"));L.username=this._list.readUInt8(this._pos)&E_.USERNAME_MASK,L.password=this._list.readUInt8(this._pos)&E_.PASSWORD_MASK,L.will=this._list.readUInt8(this._pos)&E_.WILL_FLAG_MASK;let H=!!(this._list.readUInt8(this._pos)&E_.WILL_RETAIN_MASK),Z=(this._list.readUInt8(this._pos)&E_.WILL_QOS_MASK)>>E_.WILL_QOS_SHIFT;if(L.will)J.will={},J.will.retain=H,J.will.qos=Z;else{if(H)return this._emitError(Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(Z)return this._emitError(Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(J.clean=(this._list.readUInt8(this._pos)&E_.CLEAN_SESSION_MASK)!==0,this._pos++,J.keepalive=this._parseNum(),J.keepalive===-1)return this._emitError(Error("Packet too short"));if(J.protocolVersion===5){let K=this._parseProperties();if(Object.getOwnPropertyNames(K).length)J.properties=K}let Y=this._parseString();if(Y===null)return this._emitError(Error("Packet too short"));if(J.clientId=Y,n("_parseConnect: packet.clientId: %s",J.clientId),L.will){if(J.protocolVersion===5){let K=this._parseProperties();if(Object.getOwnPropertyNames(K).length)J.will.properties=K}if(_=this._parseString(),_===null)return this._emitError(Error("Cannot parse will topic"));if(J.will.topic=_,n("_parseConnect: packet.will.topic: %s",J.will.topic),T=this._parseBuffer(),T===null)return this._emitError(Error("Cannot parse will payload"));J.will.payload=T,n("_parseConnect: packet.will.paylaod: %s",J.will.payload)}if(L.username){if(E=this._parseString(),E===null)return this._emitError(Error("Cannot parse username"));J.username=E,n("_parseConnect: packet.username: %s",J.username)}if(L.password){if(A=this._parseBuffer(),A===null)return this._emitError(Error("Cannot parse password"));J.password=A}return this.settings=J,n("_parseConnect: complete"),J}_parseConnack(){n("_parseConnack");let _=this.packet;if(this._list.length<1)return null;let T=this._list.readUInt8(this._pos++);if(T>1)return this._emitError(Error("Invalid connack flags, bits 7-1 must be set to 0"));if(_.sessionPresent=!!(T&E_.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)if(this._list.length>=2)_.reasonCode=this._list.readUInt8(this._pos++);else _.reasonCode=0;else{if(this._list.length<2)return null;_.returnCode=this._list.readUInt8(this._pos++)}if(_.returnCode===-1||_.reasonCode===-1)return this._emitError(Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let A=this._parseProperties();if(Object.getOwnPropertyNames(A).length)_.properties=A}n("_parseConnack: complete")}_parsePublish(){n("_parsePublish");let _=this.packet;if(_.topic=this._parseString(),_.topic===null)return this._emitError(Error("Cannot parse topic"));if(_.qos>0){if(!this._parseMessageId())return}if(this.settings.protocolVersion===5){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}_.payload=this._list.slice(this._pos,_.length),n("_parsePublish: payload from buffer list: %o",_.payload)}_parseSubscribe(){n("_parseSubscribe");let _=this.packet,T,A,E,L,J,X,H;if(_.subscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let Z=this._parseProperties();if(Object.getOwnPropertyNames(Z).length)_.properties=Z}if(_.length<=0)return this._emitError(Error("Malformed subscribe, no payload specified"));while(this._pos<_.length){if(T=this._parseString(),T===null)return this._emitError(Error("Cannot parse topic"));if(this._pos>=_.length)return this._emitError(Error("Malformed Subscribe Payload"));if(A=this._parseByte(),this.settings.protocolVersion===5){if(A&192)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(A&252)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(E=A&E_.SUBSCRIBE_OPTIONS_QOS_MASK,E>2)return this._emitError(Error("Invalid subscribe QoS, must be <= 2"));if(X=(A>>E_.SUBSCRIBE_OPTIONS_NL_SHIFT&E_.SUBSCRIBE_OPTIONS_NL_MASK)!==0,J=(A>>E_.SUBSCRIBE_OPTIONS_RAP_SHIFT&E_.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,L=A>>E_.SUBSCRIBE_OPTIONS_RH_SHIFT&E_.SUBSCRIBE_OPTIONS_RH_MASK,L>2)return this._emitError(Error("Invalid retain handling, must be <= 2"));if(H={topic:T,qos:E},this.settings.protocolVersion===5)H.nl=X,H.rap=J,H.rh=L;else if(this.settings.bridgeMode)H.rh=0,H.rap=!0,H.nl=!0;n("_parseSubscribe: push subscription `%s` to subscription",H),_.subscriptions.push(H)}}_parseSuback(){n("_parseSuback");let _=this.packet;if(this.packet.granted=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}if(_.length<=0)return this._emitError(Error("Malformed suback, no payload specified"));while(this._pos<this.packet.length){let T=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!E_.MQTT5_SUBACK_CODES[T])return this._emitError(Error("Invalid suback code"))}else if(T>2&&T!==128)return this._emitError(Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(T)}}_parseUnsubscribe(){n("_parseUnsubscribe");let _=this.packet;if(_.unsubscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}if(_.length<=0)return this._emitError(Error("Malformed unsubscribe, no payload specified"));while(this._pos<_.length){let T=this._parseString();if(T===null)return this._emitError(Error("Cannot parse topic"));n("_parseUnsubscribe: push topic `%s` to unsubscriptions",T),_.unsubscriptions.push(T)}}_parseUnsuback(){n("_parseUnsuback");let _=this.packet;if(!this._parseMessageId())return this._emitError(Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&_.length!==2)return this._emitError(Error("Malformed unsuback, payload length must be 2"));if(_.length<=0)return this._emitError(Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T;_.granted=[];while(this._pos<this.packet.length){let A=this._list.readUInt8(this._pos++);if(!E_.MQTT5_UNSUBACK_CODES[A])return this._emitError(Error("Invalid unsuback code"));this.packet.granted.push(A)}}}_parseConfirmation(){n("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let _=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(_.length>2){switch(_.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!E_.MQTT5_PUBACK_PUBREC_CODES[_.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!E_.MQTT5_PUBREL_PUBCOMP_CODES[_.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break}n("_parseConfirmation: packet.reasonCode `%d`",_.reasonCode)}else _.reasonCode=0;if(_.length>3){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}}return!0}_parseDisconnect(){let _=this.packet;if(n("_parseDisconnect"),this.settings.protocolVersion===5){if(this._list.length>0){if(_.reasonCode=this._parseByte(),!E_.MQTT5_DISCONNECT_CODES[_.reasonCode])this._emitError(Error("Invalid disconnect reason code"))}else _.reasonCode=0;let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}return n("_parseDisconnect result: true"),!0}_parseAuth(){n("_parseAuth");let _=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(Error("Not supported auth packet for this version MQTT"));if(_.reasonCode=this._parseByte(),!E_.MQTT5_AUTH_CODES[_.reasonCode])return this._emitError(Error("Invalid auth reason code"));let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T;return n("_parseAuth: result: true"),!0}_parseMessageId(){let _=this.packet;if(_.messageId=this._parseNum(),_.messageId===null)return this._emitError(Error("Cannot parse messageId")),!1;return n("_parseMessageId: packet.messageId %d",_.messageId),!0}_parseString(_){let T=this._parseNum(),A=T+this._pos;if(T===-1||A>this._list.length||A>this.packet.length)return null;let E=this._list.toString("utf8",this._pos,A);return this._pos+=T,n("_parseString: result: %s",E),E}_parseStringPair(){return n("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let _=this._parseNum(),T=_+this._pos;if(_===-1||T>this._list.length||T>this.packet.length)return null;let A=this._list.slice(this._pos,T);return this._pos+=_,n("_parseBuffer: result: %o",A),A}_parseNum(){if(this._list.length-this._pos<2)return-1;let _=this._list.readUInt16BE(this._pos);return this._pos+=2,n("_parseNum: result: %s",_),_}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let _=this._list.readUInt32BE(this._pos);return this._pos+=4,n("_parse4ByteNum: result: %s",_),_}_parseVarByteNum(_){n("_parseVarByteNum");let T=4,A=0,E=1,L=0,J=!1,X,H=this._pos?this._pos:0;while(A<T&&H+A<this._list.length){if(X=this._list.readUInt8(H+A++),L+=E*(X&E_.VARBYTEINT_MASK),E*=128,(X&E_.VARBYTEINT_FIN_MASK)===0){J=!0;break}if(this._list.length<=A)break}if(!J&&A===T&&this._list.length>=A)this._emitError(Error("Invalid variable byte integer"));if(H)this._pos+=A;if(J)if(_)J={bytes:A,value:L};else J=L;else J=!1;return n("_parseVarByteNum: result: %o",J),J}_parseByte(){let _;if(this._pos<this._list.length)_=this._list.readUInt8(this._pos),this._pos++;return n("_parseByte: result: %o",_),_}_parseByType(_){switch(n("_parseByType: type: %s",_),_){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){n("_parseProperties");let _=this._parseVarByteNum(),A=this._pos+_,E={};while(this._pos<A){let L=this._parseByte();if(!L)return this._emitError(Error("Cannot parse property code type")),!1;let J=E_.propertiesCodes[L];if(!J)return this._emitError(Error("Unknown property")),!1;if(J==="userProperties"){if(!E[J])E[J]=Object.create(null);let X=this._parseByType(E_.propertiesTypes[J]);if(E[J][X.name])if(Array.isArray(E[J][X.name]))E[J][X.name].push(X.value);else{let H=E[J][X.name];E[J][X.name]=[H],E[J][X.name].push(X.value)}else E[J][X.name]=X.value;continue}if(E[J])if(Array.isArray(E[J]))E[J].push(this._parseByType(E_.propertiesTypes[J]));else E[J]=[E[J]],E[J].push(this._parseByType(E_.propertiesTypes[J]));else E[J]=this._parseByType(E_.propertiesTypes[J])}return E}_newPacket(){if(n("_newPacket"),this.packet)this._list.consume(this.packet.length),n("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet);return n("_newPacket: new packet"),this.packet=new KZ,this._pos=0,!0}_emitError(_){n("_emitError",_),this.error=_,this.emit("error",_)}}GZ.exports=PA});var QZ=W((Ab,NZ)=>{var{Buffer:l4}=j("buffer"),UZ={},eR=l4.isBuffer(l4.from([1,2]).subarray(0,1));function WZ(_){let T=l4.allocUnsafe(2);return T.writeUInt8(_>>8,0),T.writeUInt8(_&255,1),T}function _D(){for(let _=0;_<65536;_++)UZ[_]=WZ(_)}function TD(_){let A=0,E=0,L=l4.allocUnsafe(4);do{if(A=_%128|0,_=_/128|0,_>0)A=A|128;L.writeUInt8(A,E++)}while(_>0&&E<4);if(_>0)E=0;return eR?L.subarray(0,E):L.slice(0,E)}function AD(_){let T=l4.allocUnsafe(4);return T.writeUInt32BE(_,0),T}NZ.exports={cache:UZ,generateCache:_D,generateNumber:WZ,genBufVariableByteInt:TD,generate4ByteBuffer:AD}});var MZ=W((Eb,UE)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)UE.exports={nextTick:ED};else UE.exports=process;function ED(_,T,A,E){if(typeof _!=="function")throw TypeError('"callback" argument must be a function');var L=arguments.length,J,X;switch(L){case 0:case 1:return process.nextTick(_);case 2:return process.nextTick(function(){_.call(null,T)});case 3:return process.nextTick(function(){_.call(null,T,A)});case 4:return process.nextTick(function(){_.call(null,T,A,E)});default:J=Array(L-1),X=0;while(X<J.length)J[X++]=arguments[X];return process.nextTick(function(){_.apply(null,J)})}}});var QE=W((Lb,BZ)=>{var i=KE(),{Buffer:p}=j("buffer"),LD=p.allocUnsafe(0),JD=p.from([0]),n4=QZ(),XD=MZ().nextTick,O1=u1()("mqtt-packet:writeToStream"),jA=n4.cache,HD=n4.generateNumber,ZD=n4.generateCache,WE=n4.genBufVariableByteInt,YD=n4.generate4ByteBuffer,t_=NE,xA=!0;function RZ(_,T,A){if(O1("generate called"),T.cork)T.cork(),XD(KD,T);if(xA)xA=!1,ZD();switch(O1("generate: packet.cmd: %s",_.cmd),_.cmd){case"connect":return GD(_,T,A);case"connack":return $D(_,T,A);case"publish":return UD(_,T,A);case"puback":case"pubrec":case"pubrel":case"pubcomp":return WD(_,T,A);case"subscribe":return ND(_,T,A);case"suback":return QD(_,T,A);case"unsubscribe":return MD(_,T,A);case"unsuback":return VD(_,T,A);case"pingreq":case"pingresp":return zD(_,T,A);case"disconnect":return FD(_,T,A);case"auth":return CD(_,T,A);default:return T.destroy(Error("Unknown command")),!1}}Object.defineProperty(RZ,"cacheNumbers",{get(){return t_===NE},set(_){if(_){if(!jA||Object.keys(jA).length===0)xA=!0;t_=NE}else xA=!1,t_=OD}});function KD(_){_.uncork()}function GD(_,T,A){let E=_||{},L=E.protocolId||"MQTT",J=E.protocolVersion||4,X=E.will,H=E.clean,Z=E.keepalive||0,Y=E.clientId||"",K=E.username,G=E.password,$=E.properties;if(H===void 0)H=!0;let U=0;if(!L||typeof L!=="string"&&!p.isBuffer(L))return T.destroy(Error("Invalid protocolId")),!1;else U+=L.length+2;if(J!==3&&J!==4&&J!==5)return T.destroy(Error("Invalid protocol version")),!1;else U+=1;if((typeof Y==="string"||p.isBuffer(Y))&&(Y||J>=4)&&(Y||H))U+=p.byteLength(Y)+2;else{if(J<4)return T.destroy(Error("clientId must be supplied before 3.1.1")),!1;if(H*1===0)return T.destroy(Error("clientId must be given if cleanSession set to 0")),!1}if(typeof Z!=="number"||Z<0||Z>65535||Z%1!==0)return T.destroy(Error("Invalid keepalive")),!1;else U+=2;U+=1;let V,N;if(J===5){if(V=a0(T,$),!V)return!1;U+=V.length}if(X){if(typeof X!=="object")return T.destroy(Error("Invalid will")),!1;if(!X.topic||typeof X.topic!=="string")return T.destroy(Error("Invalid will topic")),!1;else U+=p.byteLength(X.topic)+2;if(U+=2,X.payload)if(X.payload.length>=0)if(typeof X.payload==="string")U+=p.byteLength(X.payload);else U+=X.payload.length;else return T.destroy(Error("Invalid will payload")),!1;if(N={},J===5){if(N=a0(T,X.properties),!N)return!1;U+=N.length}}let z=!1;if(K!=null)if(OZ(K))z=!0,U+=p.byteLength(K)+2;else return T.destroy(Error("Invalid username")),!1;if(G!=null){if(!z)return T.destroy(Error("Username is required to use password")),!1;if(OZ(G))U+=DZ(G)+2;else return T.destroy(Error("Invalid password")),!1}if(T.write(i.CONNECT_HEADER),R1(T,U),L4(T,L),E.bridgeMode)J+=128;T.write(J===131?i.VERSION131:J===132?i.VERSION132:J===4?i.VERSION4:J===5?i.VERSION5:i.VERSION3);let Q=0;if(Q|=K!=null?i.USERNAME_MASK:0,Q|=G!=null?i.PASSWORD_MASK:0,Q|=X&&X.retain?i.WILL_RETAIN_MASK:0,Q|=X&&X.qos?X.qos<<i.WILL_QOS_SHIFT:0,Q|=X?i.WILL_FLAG_MASK:0,Q|=H?i.CLEAN_SESSION_MASK:0,T.write(p.from([Q])),t_(T,Z),J===5)V.write();if(L4(T,Y),X){if(J===5)N.write();OT(T,X.topic),L4(T,X.payload)}if(K!=null)L4(T,K);if(G!=null)L4(T,G);return!0}function $D(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=E===5?L.reasonCode:L.returnCode,X=L.properties,H=2;if(typeof J!=="number")return T.destroy(Error("Invalid return code")),!1;let Z=null;if(E===5){if(Z=a0(T,X),!Z)return!1;H+=Z.length}if(T.write(i.CONNACK_HEADER),R1(T,H),T.write(L.sessionPresent?i.SESSIONPRESENT_HEADER:JD),T.write(p.from([J])),Z!=null)Z.write();return!0}function UD(_,T,A){O1("publish: packet: %o",_);let E=A?A.protocolVersion:4,L=_||{},J=L.qos||0,X=L.retain?i.RETAIN_MASK:0,H=L.topic,Z=L.payload||LD,Y=L.messageId,K=L.properties,G=0;if(typeof H==="string")G+=p.byteLength(H)+2;else if(p.isBuffer(H))G+=H.length+2;else return T.destroy(Error("Invalid topic")),!1;if(!p.isBuffer(Z))G+=p.byteLength(Z);else G+=Z.length;if(J&&typeof Y!=="number")return T.destroy(Error("Invalid messageId")),!1;else if(J)G+=2;let $=null;if(E===5){if($=a0(T,K),!$)return!1;G+=$.length}if(T.write(i.PUBLISH_HEADER[J][L.dup?1:0][X?1:0]),R1(T,G),t_(T,DZ(H)),T.write(H),J>0)t_(T,Y);if($!=null)$.write();return O1("publish: payload: %o",Z),T.write(Z)}function WD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.cmd||"puback",X=L.messageId,H=L.dup&&J==="pubrel"?i.DUP_MASK:0,Z=0,Y=L.reasonCode,K=L.properties,G=E===5?3:2;if(J==="pubrel")Z=1;if(typeof X!=="number")return T.destroy(Error("Invalid messageId")),!1;let $=null;if(E===5){if(typeof K==="object"){if($=i4(T,K,A,G),!$)return!1;G+=$.length}}if(T.write(i.ACKS[J][Z][H][0]),G===3)G+=Y!==0?1:-1;if(R1(T,G),t_(T,X),E===5&&G!==2)T.write(p.from([Y]));if($!==null)$.write();else if(G===4)T.write(p.from([0]));return!0}function ND(_,T,A){O1("subscribe: packet: ");let E=A?A.protocolVersion:4,L=_||{},J=L.dup?i.DUP_MASK:0,X=L.messageId,H=L.subscriptions,Z=L.properties,Y=0;if(typeof X!=="number")return T.destroy(Error("Invalid messageId")),!1;else Y+=2;let K=null;if(E===5){if(K=a0(T,Z),!K)return!1;Y+=K.length}if(typeof H==="object"&&H.length)for(let $=0;$<H.length;$+=1){let U=H[$].topic,V=H[$].qos;if(typeof U!=="string")return T.destroy(Error("Invalid subscriptions - invalid topic")),!1;if(typeof V!=="number")return T.destroy(Error("Invalid subscriptions - invalid qos")),!1;if(E===5){if(typeof(H[$].nl||!1)!=="boolean")return T.destroy(Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(H[$].rap||!1)!=="boolean")return T.destroy(Error("Invalid subscriptions - invalid Retain as Published")),!1;let Q=H[$].rh||0;if(typeof Q!=="number"||Q>2)return T.destroy(Error("Invalid subscriptions - invalid Retain Handling")),!1}Y+=p.byteLength(U)+2+1}else return T.destroy(Error("Invalid subscriptions")),!1;if(O1("subscribe: writing to stream: %o",i.SUBSCRIBE_HEADER),T.write(i.SUBSCRIBE_HEADER[1][J?1:0][0]),R1(T,Y),t_(T,X),K!==null)K.write();let G=!0;for(let $ of H){let{topic:U,qos:V}=$,N=+$.nl,z=+$.rap,Q=$.rh,F;if(OT(T,U),F=i.SUBSCRIBE_OPTIONS_QOS[V],E===5)F|=N?i.SUBSCRIBE_OPTIONS_NL:0,F|=z?i.SUBSCRIBE_OPTIONS_RAP:0,F|=Q?i.SUBSCRIBE_OPTIONS_RH[Q]:0;G=T.write(p.from([F]))}return G}function QD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.messageId,X=L.granted,H=L.properties,Z=0;if(typeof J!=="number")return T.destroy(Error("Invalid messageId")),!1;else Z+=2;if(typeof X==="object"&&X.length)for(let K=0;K<X.length;K+=1){if(typeof X[K]!=="number")return T.destroy(Error("Invalid qos vector")),!1;Z+=1}else return T.destroy(Error("Invalid qos vector")),!1;let Y=null;if(E===5){if(Y=i4(T,H,A,Z),!Y)return!1;Z+=Y.length}if(T.write(i.SUBACK_HEADER),R1(T,Z),t_(T,J),Y!==null)Y.write();return T.write(p.from(X))}function MD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.messageId,X=L.dup?i.DUP_MASK:0,H=L.unsubscriptions,Z=L.properties,Y=0;if(typeof J!=="number")return T.destroy(Error("Invalid messageId")),!1;else Y+=2;if(typeof H==="object"&&H.length)for(let $=0;$<H.length;$+=1){if(typeof H[$]!=="string")return T.destroy(Error("Invalid unsubscriptions")),!1;Y+=p.byteLength(H[$])+2}else return T.destroy(Error("Invalid unsubscriptions")),!1;let K=null;if(E===5){if(K=a0(T,Z),!K)return!1;Y+=K.length}if(T.write(i.UNSUBSCRIBE_HEADER[1][X?1:0][0]),R1(T,Y),t_(T,J),K!==null)K.write();let G=!0;for(let $=0;$<H.length;$++)G=OT(T,H[$]);return G}function VD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.messageId,X=L.dup?i.DUP_MASK:0,H=L.granted,Z=L.properties,Y=L.cmd,K=0,G=2;if(typeof J!=="number")return T.destroy(Error("Invalid messageId")),!1;if(E===5)if(typeof H==="object"&&H.length)for(let U=0;U<H.length;U+=1){if(typeof H[U]!=="number")return T.destroy(Error("Invalid qos vector")),!1;G+=1}else return T.destroy(Error("Invalid qos vector")),!1;let $=null;if(E===5){if($=i4(T,Z,A,G),!$)return!1;G+=$.length}if(T.write(i.ACKS[Y][0][X][0]),R1(T,G),t_(T,J),$!==null)$.write();if(E===5)T.write(p.from(H));return!0}function zD(_,T,A){return T.write(i.EMPTY[_.cmd])}function FD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.reasonCode,X=L.properties,H=E===5?1:0,Z=null;if(E===5){if(Z=i4(T,X,A,H),!Z)return!1;H+=Z.length}if(T.write(p.from([i.codes.disconnect<<4])),R1(T,H),E===5)T.write(p.from([J]));if(Z!==null)Z.write();return!0}function CD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.reasonCode,X=L.properties,H=E===5?1:0;if(E!==5)T.destroy(Error("Invalid mqtt version for auth packet"));let Z=i4(T,X,A,H);if(!Z)return!1;if(H+=Z.length,T.write(p.from([i.codes.auth<<4])),R1(T,H),T.write(p.from([J])),Z!==null)Z.write();return!0}var VZ={};function R1(_,T){if(T>i.VARBYTEINT_MAX)return _.destroy(Error(`Invalid variable byte integer: ${T}`)),!1;let A=VZ[T];if(!A){if(A=WE(T),T<16384)VZ[T]=A}return O1("writeVarByteInt: writing to stream: %o",A),_.write(A)}function OT(_,T){let A=p.byteLength(T);return t_(_,A),O1("writeString: %s",T),_.write(T,"utf8")}function zZ(_,T,A){OT(_,T),OT(_,A)}function NE(_,T){return O1("writeNumberCached: number: %d",T),O1("writeNumberCached: %o",jA[T]),_.write(jA[T])}function OD(_,T){let A=HD(T);return O1("writeNumberGenerated: %o",A),_.write(A)}function RD(_,T){let A=YD(T);return O1("write4ByteNumber: %o",A),_.write(A)}function L4(_,T){if(typeof T==="string")OT(_,T);else if(T)t_(_,T.length),_.write(T);else t_(_,0)}function a0(_,T){if(typeof T!=="object"||T.length!=null)return{length:1,write(){CZ(_,{},0)}};let A=0;function E(J,X){let H=i.propertiesTypes[J],Z=0;switch(H){case"byte":{if(typeof X!=="boolean")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=2;break}case"int8":{if(typeof X!=="number"||X<0||X>255)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=2;break}case"binary":{if(X&&X===null)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=1+p.byteLength(X)+2;break}case"int16":{if(typeof X!=="number"||X<0||X>65535)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=3;break}case"int32":{if(typeof X!=="number"||X<0||X>4294967295)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=5;break}case"var":{if(typeof X!=="number"||X<0||X>268435455)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=1+p.byteLength(WE(X));break}case"string":{if(typeof X!=="string")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=3+p.byteLength(X.toString());break}case"pair":{if(typeof X!=="object")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=Object.getOwnPropertyNames(X).reduce((Y,K)=>{let G=X[K];if(Array.isArray(G))Y+=G.reduce(($,U)=>{return $+=3+p.byteLength(K.toString())+2+p.byteLength(U.toString()),$},0);else Y+=3+p.byteLength(K.toString())+2+p.byteLength(X[K].toString());return Y},0);break}default:return _.destroy(Error(`Invalid property ${J}: ${X}`)),!1}return Z}if(T)for(let J in T){let X=0,H=0,Z=T[J];if(Z===void 0)continue;else if(Array.isArray(Z))for(let Y=0;Y<Z.length;Y++){if(H=E(J,Z[Y]),!H)return!1;X+=H}else{if(H=E(J,Z),!H)return!1;X=H}if(!X)return!1;A+=X}return{length:p.byteLength(WE(A))+A,write(){CZ(_,T,A)}}}function i4(_,T,A,E){let L=["reasonString","userProperties"],J=A&&A.properties&&A.properties.maximumPacketSize?A.properties.maximumPacketSize:0,X=a0(_,T);if(J)while(E+X.length>J){let H=L.shift();if(H&&T[H])delete T[H],X=a0(_,T);else return!1}return X}function FZ(_,T,A){switch(i.propertiesTypes[T]){case"byte":{_.write(p.from([i.properties[T]])),_.write(p.from([+A]));break}case"int8":{_.write(p.from([i.properties[T]])),_.write(p.from([A]));break}case"binary":{_.write(p.from([i.properties[T]])),L4(_,A);break}case"int16":{_.write(p.from([i.properties[T]])),t_(_,A);break}case"int32":{_.write(p.from([i.properties[T]])),RD(_,A);break}case"var":{_.write(p.from([i.properties[T]])),R1(_,A);break}case"string":{_.write(p.from([i.properties[T]])),OT(_,A);break}case"pair":{Object.getOwnPropertyNames(A).forEach((L)=>{let J=A[L];if(Array.isArray(J))J.forEach((X)=>{_.write(p.from([i.properties[T]])),zZ(_,L.toString(),X.toString())});else _.write(p.from([i.properties[T]])),zZ(_,L.toString(),J.toString())});break}default:return _.destroy(Error(`Invalid property ${T} value: ${A}`)),!1}}function CZ(_,T,A){R1(_,A);for(let E in T)if(Object.prototype.hasOwnProperty.call(T,E)&&T[E]!=null){let L=T[E];if(Array.isArray(L))for(let J=0;J<L.length;J++)FZ(_,E,L[J]);else FZ(_,E,L)}}function DZ(_){if(!_)return 0;else if(_ instanceof p)return _.length;else return p.byteLength(_)}function OZ(_){return typeof _==="string"||_ instanceof p}BZ.exports=RZ});var jZ=W((Jb,PZ)=>{var DD=QE(),{EventEmitter:BD}=j("events"),{Buffer:qZ}=j("buffer");function qD(_,T){let A=new IZ;return DD(_,A,T),A.concat()}class IZ extends BD{constructor(){super();this._array=Array(20),this._i=0}write(_){return this._array[this._i++]=_,!0}concat(){let _=0,T=Array(this._array.length),A=this._array,E=0,L;for(L=0;L<A.length&&A[L]!==void 0;L++){if(typeof A[L]!=="string")T[L]=A[L].length;else T[L]=qZ.byteLength(A[L]);_+=T[L]}let J=qZ.allocUnsafe(_);for(L=0;L<A.length&&A[L]!==void 0;L++)if(typeof A[L]!=="string")A[L].copy(J,E),E+=T[L];else J.write(A[L],E),E+=T[L];return J}destroy(_){if(_)this.emit("error",_)}}PZ.exports=qD});var wA=W((ID)=>{ID.parser=$Z().parser;ID.generate=jZ();ID.writeToStream=QE()});var SZ=W((Hb,wZ)=>{wZ.exports=xZ;function xZ(_,T){if(_&&T)return xZ(_)(T);if(typeof _!=="function")throw TypeError("need wrapper function");return Object.keys(_).forEach(function(E){A[E]=_[E]}),A;function A(){var E=Array(arguments.length);for(var L=0;L<E.length;L++)E[L]=arguments[L];var J=_.apply(this,E),X=E[E.length-1];if(typeof J==="function"&&J!==X)Object.keys(X).forEach(function(H){J[H]=X[H]});return J}}});var hZ=W((Zb,ME)=>{var yZ=SZ();ME.exports=yZ(SA);ME.exports.strict=yZ(vZ);SA.proto=SA(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return SA(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return vZ(this)},configurable:!0})});function SA(_){var T=function(){if(T.called)return T.value;return T.called=!0,T.value=_.apply(this,arguments)};return T.called=!1,T}function vZ(_){var T=function(){if(T.called)throw Error(T.onceError);return T.called=!0,T.value=_.apply(this,arguments)},A=_.name||"Function wrapped with `once`";return T.onceError=A+" shouldn't be called more than once",T.called=!1,T}});var bZ=W((Yb,fZ)=>{var wD=hZ(),SD=function(){},yD=global.Bare?queueMicrotask:process.nextTick.bind(process),vD=function(_){return _.setHeader&&typeof _.abort==="function"},hD=function(_){return _.stdio&&Array.isArray(_.stdio)&&_.stdio.length===3},kZ=function(_,T,A){if(typeof T==="function")return kZ(_,null,T);if(!T)T={};A=wD(A||SD);var{_writableState:E,_readableState:L}=_,J=T.readable||T.readable!==!1&&_.readable,X=T.writable||T.writable!==!1&&_.writable,H=!1,Z=function(){if(!_.writable)Y()},Y=function(){if(X=!1,!J)A.call(_)},K=function(){if(J=!1,!X)A.call(_)},G=function(z){A.call(_,z?Error("exited with error code: "+z):null)},$=function(z){A.call(_,z)},U=function(){yD(V)},V=function(){if(H)return;if(J&&!(L&&(L.ended&&!L.destroyed)))return A.call(_,Error("premature close"));if(X&&!(E&&(E.ended&&!E.destroyed)))return A.call(_,Error("premature close"))},N=function(){_.req.on("finish",Y)};if(vD(_))if(_.on("complete",Y),_.on("abort",U),_.req)N();else _.on("request",N);else if(X&&!E)_.on("end",Z),_.on("close",Z);if(hD(_))_.on("exit",G);if(_.on("end",K),_.on("finish",Y),T.error!==!1)_.on("error",$);return _.on("close",U),function(){if(H=!0,_.removeListener("complete",Y),_.removeListener("abort",U),_.removeListener("request",N),_.req)_.req.removeListener("finish",Y);_.removeListener("end",Z),_.removeListener("close",Z),_.removeListener("finish",Y),_.removeListener("exit",G),_.removeListener("end",K),_.removeListener("error",$),_.removeListener("close",U)}};fZ.exports=kZ});var j0=W((Kb,gZ)=>{var kD=wA();function fD(_,T,A){let E=null;if(_.connecting||_.connected)try{if(!kD.writeToStream(T,_.conn)&&!_.errored){_.conn.once("drain",A);return}}catch(L){E=Error("packet received not valid")}else E=Error("connection closed");setImmediate(A,E,_)}gZ.exports=fD});var VE=W((Gb,dZ)=>{var mZ=uT(),bD=j("util");function uZ(_,T){if(mZ.call(this,_,T.broker),this.writeCallback=T._onError.bind(T),!_.messageId)if(this.messageId=T._nextId,T._nextId>=65535)T._nextId=1;else T._nextId++;else this.messageId=_.messageId}bD.inherits(uZ,mZ);dZ.exports=uZ});var lZ=W(($b,pZ)=>{var gD=k8(),cZ=[];function mD(_,T){if(Array.isArray(_))T=_,_=null;var A=gD(uD);return T?J:E;function E(){var X=A.get();if(X.release=L,arguments.length===3)X.context=arguments[0],X.list=arguments[1],X.callback=arguments[2]||a4;else X.context=_,X.list=arguments[0],X.callback=arguments[1]||a4;X.work()}function L(X){A.release(X)}function J(){var X=A.get();X.release=L,X.list=T;var H,Z,Y=arguments.length-1;switch(X.context=this||_,X.callback=arguments[Y]||a4,Y){case 0:X.work();break;case 1:X.work(null,arguments[0]);break;case 2:X.work(null,arguments[0],arguments[1]);break;case 3:X.work(null,arguments[0],arguments[1],arguments[2]);break;case 4:X.work(null,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:H=Array(Y+1),H[0]=null;for(Z=0;Z<Y;Z++)H[Z+1]=arguments[Z];X.work.apply(null,H)}}}function a4(){}function uD(){this.list=cZ,this.callback=a4,this.count=0,this.context=void 0,this.release=a4;var _=this;this.work=function T(){if(arguments.length>0&&arguments[0])return _.callback.call(_.context,arguments[0]);var A=arguments.length,E,L,J;if(_.count<_.list.length)switch(J=_.list[_.count++],A){case 0:case 1:return J.call(_.context,T);case 2:return J.call(_.context,arguments[1],T);case 3:return J.call(_.context,arguments[1],arguments[2],T);case 4:return J.call(_.context,arguments[1],arguments[2],arguments[3],T);default:L=Array(A);for(E=1;E<A;E++)L[E-1]=arguments[E];L[A-1]=T,J.apply(_.context,L)}else{switch(A){case 0:_.callback.call(_.context);break;case 1:_.callback.call(_.context,arguments[0]);break;case 2:_.callback.call(_.context,arguments[0],arguments[1]);break;case 3:_.callback.call(_.context,arguments[0],arguments[1],arguments[2]);break;case 4:_.callback.call(_.context,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:L=Array(A);for(E=0;E<A;E++)L[E]=arguments[E];_.callback.apply(_.context,L)}_.context=void 0,_.list=cZ,_.count=0,_.release(_)}}}pZ.exports=mD});var RT=W((Ub,nZ)=>{var{Transform:dD,Writable:cD}=j("stream");function pD(_,T){if(!_||_.length===0)return Error("impossible to "+T+" to an empty topic");let A=_.length-1,E=A-1,L=E>0&&_.charCodeAt(E)!==47;for(let J=0;J<_.length;J++)switch(_.charCodeAt(J)){case 35:{if(J!==A||L)return Error("# is only allowed in "+T+" in the last position");break}case 43:{let X=J<A-1&&_.charCodeAt(J+1)!==47,H=J>1&&_.charCodeAt(J-1)!==47;if(X||H)return Error("+ is only allowed in "+T+" between /");break}}}function lD(_){return new dD({objectMode:!0,transform:_})}function nD(_){return new cD({objectMode:!0,writev:function(T,A){_(T.map((E)=>E.chunk),A)}})}nZ.exports={validateTopic:pD,through:lD,bulk:nD,$SYS_PREFIX:"$SYS/"}});var yA=W((Wb,tZ)=>{var aZ=lZ(),oZ=uT(),{through:iD}=RT(),{validateTopic:aD,$SYS_PREFIX:oD}=RT(),rD=j0(),sD=aZ([rZ,XB,sZ]),tD=aZ([rZ,sZ]);function eD(_,T){this.cmd="suback",this.messageId=_.messageId,this.granted=T}function iZ(_,T,A,E,L){this.qos=_,this.func=T,this.rh=A,this.rap=E,this.nl=L}function _B(_,T,A,E){this.client=_,this.packet=T,this.actions=A?tD:sD,this.finish=E,this.subState=[]}function TB(_,T,A,E,L,J){this.client=_,this.packet=T,this.granted=A,this.rh=E,this.rap=L,this.nl=J}function AB(_){let T={};for(let E=0;E<_.length;E++){let L=_[E];T[L.topic]=L}let A=[];for(let E in T)A.push(T[E]);return A}function EB(_,T,A,E){T.subscriptions=T.subscriptions.length===1?T.subscriptions:AB(T.subscriptions),_.broker._parallel(new _B(_,T,A,E),LB,T.subscriptions,A?E:ZB)}function LB(_,T){let A=new TB(this.client,this.packet,_.qos,_.rh,_.rap,_.nl);this.subState.push(A),this.actions.call(A,_,T)}function rZ(_,T){let A=aD(_.topic,"SUBSCRIBE");if(A)return T(A);let E=this.client;E.broker.authorizeSubscribe(E,_,T)}function JB(_){return function(A,E){if(A.topic.charCodeAt(0)===36)E();else _(A,E)}}function XB(_,T){if(!_||typeof _!=="object")return this.granted=128,T(null,null);let A=this.packet,E=this.client;if(E.clean)return T(null,_);E.broker.persistence.addSubscriptions(E,A.subscriptions,function(J){T(J,_)})}function sZ(_,T){if(!_||typeof _!=="object")return T();let A=this.client,E=A.broker,L=_.topic,J=_.qos,X=this.rh,H=this.rap,Z=this.nl,Y=J>0?A.deliverQoS:A.deliver0,K=Y;if(Y=function($,U){if($=new oZ($,E),$.nl=Z,!H)$.retain=!1;K($,U)},HB(L))Y=JB(Y);if(A.closed||A.broker.closed)return;if(!A.subscriptions[L])A.subscriptions[L]=new iZ(J,Y,X,H,Z),E.subscribe(L,Y,T);else if(A.subscriptions[L].qos!==J||A.subscriptions[L].rh!==X||A.subscriptions[L].rap!==H||A.subscriptions[L].nl!==Z)E.unsubscribe(L,A.subscriptions[L].func),A.subscriptions[L]=new iZ(J,Y,X,H,Z),E.subscribe(L,Y,T);else T()}function HB(_){let T=_.charCodeAt(0);return T===43||T===35}function ZB(_){let T=this.finish;if(_)return T(_);let A=this.packet,E=this.client;if(A.messageId!==void 0)rD(E,new eD(A,this.subState.map((H)=>H.granted)),T);else T();let L=E.broker,J=A.subscriptions,X=[];for(let H=0;H<J.length;H++){if(this.subState[H].granted!==128)X.push(J[H].topic);J[H].qos=this.subState[H].granted}if(this.subState=[],L.emit("subscribe",J,E),L.publish({topic:oD+L.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:E.id,subs:J}),"utf8")},YB),X.length>0)L.persistence.createRetainedStreamCombi(X).pipe(iD(function(K,G,$){K=new oZ({cmd:K.cmd,qos:K.qos,topic:K.topic,payload:K.payload,retain:!0},L),K.brokerId=null,E.deliverQoS(K,$)}))}function YB(){}tZ.exports=EB});var FE=W((Nb,eZ)=>{var KB=j0(),{validateTopic:GB,$SYS_PREFIX:$B}=RT();function UB(_){this.cmd="unsuback",this.messageId=_.messageId}function WB(_,T,A){this.client=_,this.packet=T,this.finish=A}function NB(_,T,A){let E=_.broker,L=T.unsubscriptions,J;for(let X=0;X<L.length;X++)if(J=GB(L[X],"UNSUBSCRIBE"),J)return A(J);if(T.messageId!==void 0){if(_.clean)return zE(_,T,A);E.persistence.removeSubscriptions(_,L,function(X){if(X)return A(X);zE(_,T,A)})}else zE(_,T,A)}function zE(_,T,A){_.broker._parallel(new WB(_,T,A),QB,T.unsubscriptions,MB)}function QB(_,T){let A=this.client,E=A.broker,L=A.subscriptions[_];if(L){let J=L.func;delete A.subscriptions[_],E.unsubscribe(_,J,T)}else T()}function MB(_){let T=this.client;if(_){T.emit("error",_);return}let A=this.packet,E=this.finish;if(A.messageId!==void 0)KB(T,new UB(A),E);else E();if((!T.closed||T.clean===!0)&&A.unsubscriptions.length>0)T.broker.emit("unsubscribe",A.unsubscriptions,T),T.broker.publish({topic:$B+T.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:T.id,subs:A.unsubscriptions}),"utf8")},VB)}function VB(){}eZ.exports=NB});var T2=W((Qb,_2)=>{_2.exports=function(){let T=process.hrtime();return Math.floor(T[0]*1000+T[1]/1e6)}});var E2=W((Mb,A2)=>{A2.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var X2=W((Vb,OE)=>{var vA=T2(),{clearTimeout:L2,setTimeout:J2}=E2();class CE{constructor(_,T,A){let E=this;this._started=vA(),this._rescheduled=0,this._scheduled=T,this._args=A,this._triggered=!1,this._timerWrapper=()=>{if(E._rescheduled>0)E._scheduled=E._rescheduled-(vA()-E._started),E._schedule(E._scheduled);else E._triggered=!0,_.apply(null,E._args)},this._timer=J2(this._timerWrapper,T)}reschedule(_){if(!_)_=this._scheduled;let T=vA();if(T+_-(this._started+this._scheduled)<0)L2(this._timer),this._schedule(_);else if(!this._triggered)this._started=T,this._rescheduled=_;else this._schedule(_)}_schedule(_){this._triggered=!1,this._started=vA(),this._rescheduled=0,this._scheduled=_,this._timer=J2(this._timerWrapper,_)}clear(){L2(this._timer)}}function zB(){if(typeof arguments[0]!=="function")throw Error("callback needed");if(typeof arguments[1]!=="number")throw Error("timeout needed");let _;if(arguments.length>0){_=Array(arguments.length-2);for(var T=0;T<_.length;T++)_[T]=arguments[T+2]}return new CE(arguments[0],arguments[1],_)}OE.exports=zB;OE.exports.Retimer=CE});var RE=W((H2)=>{Object.defineProperty(H2,"__esModule",{value:!0});H2.default=OB;var FB=CB(j("crypto"));function CB(_){return _&&_.__esModule?_:{default:_}}var kA=new Uint8Array(256),hA=kA.length;function OB(){if(hA>kA.length-16)FB.default.randomFillSync(kA),hA=0;return kA.slice(hA,hA+=16)}});var K2=W((Z2)=>{Object.defineProperty(Z2,"__esModule",{value:!0});Z2.default=void 0;var DB=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;Z2.default=DB});var o4=W((G2)=>{Object.defineProperty(G2,"__esModule",{value:!0});G2.default=void 0;var BB=qB(K2());function qB(_){return _&&_.__esModule?_:{default:_}}function IB(_){return typeof _==="string"&&BB.default.test(_)}var PB=IB;G2.default=PB});var r4=W((U2)=>{Object.defineProperty(U2,"__esModule",{value:!0});U2.default=void 0;var jB=xB(o4());function xB(_){return _&&_.__esModule?_:{default:_}}var m_=[];for(let _=0;_<256;++_)m_.push((_+256).toString(16).substr(1));function wB(_,T=0){let A=(m_[_[T+0]]+m_[_[T+1]]+m_[_[T+2]]+m_[_[T+3]]+"-"+m_[_[T+4]]+m_[_[T+5]]+"-"+m_[_[T+6]]+m_[_[T+7]]+"-"+m_[_[T+8]]+m_[_[T+9]]+"-"+m_[_[T+10]]+m_[_[T+11]]+m_[_[T+12]]+m_[_[T+13]]+m_[_[T+14]]+m_[_[T+15]]).toLowerCase();if(!(0,jB.default)(A))throw TypeError("Stringified UUID is invalid");return A}var SB=wB;U2.default=SB});var z2=W((M2)=>{Object.defineProperty(M2,"__esModule",{value:!0});M2.default=void 0;var yB=Q2(RE()),vB=Q2(r4());function Q2(_){return _&&_.__esModule?_:{default:_}}var N2,DE,BE=0,qE=0;function hB(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let J=_.node||N2,X=_.clockseq!==void 0?_.clockseq:DE;if(J==null||X==null){let $=_.random||(_.rng||yB.default)();if(J==null)J=N2=[$[0]|1,$[1],$[2],$[3],$[4],$[5]];if(X==null)X=DE=($[6]<<8|$[7])&16383}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:qE+1,Y=H-BE+(Z-qE)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>BE)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");BE=H,qE=Z,DE=X,H+=12219292800000;let K=((H&268435455)*1e4+Z)%4294967296;L[E++]=K>>>24&255,L[E++]=K>>>16&255,L[E++]=K>>>8&255,L[E++]=K&255;let G=H/4294967296*1e4&268435455;L[E++]=G>>>8&255,L[E++]=G&255,L[E++]=G>>>24&15|16,L[E++]=G>>>16&255,L[E++]=X>>>8|128,L[E++]=X&255;for(let $=0;$<6;++$)L[E+$]=J[$];return T||(0,vB.default)(L)}var kB=hB;M2.default=kB});var IE=W((F2)=>{Object.defineProperty(F2,"__esModule",{value:!0});F2.default=void 0;var fB=bB(o4());function bB(_){return _&&_.__esModule?_:{default:_}}function gB(_){if(!(0,fB.default)(_))throw TypeError("Invalid UUID");let T,A=new Uint8Array(16);return A[0]=(T=parseInt(_.slice(0,8),16))>>>24,A[1]=T>>>16&255,A[2]=T>>>8&255,A[3]=T&255,A[4]=(T=parseInt(_.slice(9,13),16))>>>8,A[5]=T&255,A[6]=(T=parseInt(_.slice(14,18),16))>>>8,A[7]=T&255,A[8]=(T=parseInt(_.slice(19,23),16))>>>8,A[9]=T&255,A[10]=(T=parseInt(_.slice(24,36),16))/1099511627776&255,A[11]=T/4294967296&255,A[12]=T>>>24&255,A[13]=T>>>16&255,A[14]=T>>>8&255,A[15]=T&255,A}var mB=gB;F2.default=mB});var PE=W((B2)=>{Object.defineProperty(B2,"__esModule",{value:!0});B2.default=pB;B2.URL=B2.DNS=void 0;var uB=O2(r4()),dB=O2(IE());function O2(_){return _&&_.__esModule?_:{default:_}}function cB(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var R2="6ba7b810-9dad-11d1-80b4-00c04fd430c8";B2.DNS=R2;var D2="6ba7b811-9dad-11d1-80b4-00c04fd430c8";B2.URL=D2;function pB(_,T,A){function E(L,J,X,H){if(typeof L==="string")L=cB(L);if(typeof J==="string")J=(0,dB.default)(J);if(J.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let Z=new Uint8Array(16+L.length);if(Z.set(J),Z.set(L,J.length),Z=A(Z),Z[6]=Z[6]&15|T,Z[8]=Z[8]&63|128,X){H=H||0;for(let Y=0;Y<16;++Y)X[H+Y]=Z[Y];return X}return(0,uB.default)(Z)}try{E.name=_}catch(L){}return E.DNS=R2,E.URL=D2,E}});var j2=W((I2)=>{Object.defineProperty(I2,"__esModule",{value:!0});I2.default=void 0;var iB=aB(j("crypto"));function aB(_){return _&&_.__esModule?_:{default:_}}function oB(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return iB.default.createHash("md5").update(_).digest()}var rB=oB;I2.default=rB});var y2=W((w2)=>{Object.defineProperty(w2,"__esModule",{value:!0});w2.default=void 0;var sB=x2(PE()),tB=x2(j2());function x2(_){return _&&_.__esModule?_:{default:_}}var eB=(0,sB.default)("v3",48,tB.default),_q=eB;w2.default=_q});var f2=W((h2)=>{Object.defineProperty(h2,"__esModule",{value:!0});h2.default=void 0;var Tq=v2(RE()),Aq=v2(r4());function v2(_){return _&&_.__esModule?_:{default:_}}function Eq(_,T,A){_=_||{};let E=_.random||(_.rng||Tq.default)();if(E[6]=E[6]&15|64,E[8]=E[8]&63|128,T){A=A||0;for(let L=0;L<16;++L)T[A+L]=E[L];return T}return(0,Aq.default)(E)}var Lq=Eq;h2.default=Lq});var m2=W((b2)=>{Object.defineProperty(b2,"__esModule",{value:!0});b2.default=void 0;var Jq=Xq(j("crypto"));function Xq(_){return _&&_.__esModule?_:{default:_}}function Hq(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return Jq.default.createHash("sha1").update(_).digest()}var Zq=Hq;b2.default=Zq});var p2=W((d2)=>{Object.defineProperty(d2,"__esModule",{value:!0});d2.default=void 0;var Yq=u2(PE()),Kq=u2(m2());function u2(_){return _&&_.__esModule?_:{default:_}}var Gq=(0,Yq.default)("v5",80,Kq.default),$q=Gq;d2.default=$q});var i2=W((l2)=>{Object.defineProperty(l2,"__esModule",{value:!0});l2.default=void 0;var Uq="00000000-0000-0000-0000-000000000000";l2.default=Uq});var r2=W((a2)=>{Object.defineProperty(a2,"__esModule",{value:!0});a2.default=void 0;var Wq=Nq(o4());function Nq(_){return _&&_.__esModule?_:{default:_}}function Qq(_){if(!(0,Wq.default)(_))throw TypeError("Invalid UUID");return parseInt(_.substr(14,1),16)}var Mq=Qq;a2.default=Mq});var s2=W((d1)=>{Object.defineProperty(d1,"__esModule",{value:!0});Object.defineProperty(d1,"v1",{enumerable:!0,get:function(){return Vq.default}});Object.defineProperty(d1,"v3",{enumerable:!0,get:function(){return zq.default}});Object.defineProperty(d1,"v4",{enumerable:!0,get:function(){return Fq.default}});Object.defineProperty(d1,"v5",{enumerable:!0,get:function(){return Cq.default}});Object.defineProperty(d1,"NIL",{enumerable:!0,get:function(){return Oq.default}});Object.defineProperty(d1,"version",{enumerable:!0,get:function(){return Rq.default}});Object.defineProperty(d1,"validate",{enumerable:!0,get:function(){return Dq.default}});Object.defineProperty(d1,"stringify",{enumerable:!0,get:function(){return Bq.default}});Object.defineProperty(d1,"parse",{enumerable:!0,get:function(){return qq.default}});var Vq=x0(z2()),zq=x0(y2()),Fq=x0(f2()),Cq=x0(p2()),Oq=x0(i2()),Rq=x0(r2()),Dq=x0(o4()),Bq=x0(r4()),qq=x0(IE());function x0(_){return _&&_.__esModule?_:{default:_}}});var _Y=W((vb,e2)=>{var Iq=s2(),t2=j("crypto");e2.exports=typeof t2.randomUUID==="function"?t2.randomUUID:Iq.v4});var EY=W((hb,AY)=>{var jE=[],TY={};for(o0=0;o0<256;o0++)jE[o0]=(o0+256).toString(16).substr(1),TY[jE[o0]]=o0;var o0;function Pq(_,T,A){var E=T&&A||0,L=0;T=T||[],_.toLowerCase().replace(/[0-9a-f]{2}/g,function(J){if(L<16)T[E+L++]=TY[J]});while(L<16)T[E+L++]=0;return T}function jq(_,T){var A=T||0,E=jE;return E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]}AY.exports={parse:Pq,unparse:jq}});var JY=W((fq)=>{fq.byteLength=wq;fq.toByteArray=yq;fq.fromByteArray=kq;var J0=[],D1=[],xq=typeof Uint8Array<"u"?Uint8Array:Array,xE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(r0=0,wE=xE.length;r0<wE;++r0)J0[r0]=xE[r0],D1[xE.charCodeAt(r0)]=r0;var r0,wE;D1[45]=62;D1[95]=63;function LY(_){var T=_.length;if(T%4>0)throw Error("Invalid string. Length must be a multiple of 4");var A=_.indexOf("=");if(A===-1)A=T;var E=A===T?0:4-A%4;return[A,E]}function wq(_){var T=LY(_),A=T[0],E=T[1];return(A+E)*3/4-E}function Sq(_,T,A){return(T+A)*3/4-A}function yq(_){var T,A=LY(_),E=A[0],L=A[1],J=new xq(Sq(_,E,L)),X=0,H=L>0?E-4:E,Z;for(Z=0;Z<H;Z+=4)T=D1[_.charCodeAt(Z)]<<18|D1[_.charCodeAt(Z+1)]<<12|D1[_.charCodeAt(Z+2)]<<6|D1[_.charCodeAt(Z+3)],J[X++]=T>>16&255,J[X++]=T>>8&255,J[X++]=T&255;if(L===2)T=D1[_.charCodeAt(Z)]<<2|D1[_.charCodeAt(Z+1)]>>4,J[X++]=T&255;if(L===1)T=D1[_.charCodeAt(Z)]<<10|D1[_.charCodeAt(Z+1)]<<4|D1[_.charCodeAt(Z+2)]>>2,J[X++]=T>>8&255,J[X++]=T&255;return J}function vq(_){return J0[_>>18&63]+J0[_>>12&63]+J0[_>>6&63]+J0[_&63]}function hq(_,T,A){var E,L=[];for(var J=T;J<A;J+=3)E=(_[J]<<16&16711680)+(_[J+1]<<8&65280)+(_[J+2]&255),L.push(vq(E));return L.join("")}function kq(_){var T,A=_.length,E=A%3,L=[],J=16383;for(var X=0,H=A-E;X<H;X+=J)L.push(hq(_,X,X+J>H?H:X+J));if(E===1)T=_[A-1],L.push(J0[T>>2]+J0[T<<4&63]+"==");else if(E===2)T=(_[A-2]<<8)+_[A-1],L.push(J0[T>>10]+J0[T>>4&63]+J0[T<<2&63]+"=");return L.join("")}});var XY=W((uq)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */uq.read=function(_,T,A,E,L){var J,X,H=L*8-E-1,Z=(1<<H)-1,Y=Z>>1,K=-7,G=A?L-1:0,$=A?-1:1,U=_[T+G];G+=$,J=U&(1<<-K)-1,U>>=-K,K+=H;for(;K>0;J=J*256+_[T+G],G+=$,K-=8);X=J&(1<<-K)-1,J>>=-K,K+=E;for(;K>0;X=X*256+_[T+G],G+=$,K-=8);if(J===0)J=1-Y;else if(J===Z)return X?NaN:(U?-1:1)*(1/0);else X=X+Math.pow(2,E),J=J-Y;return(U?-1:1)*X*Math.pow(2,J-E)};uq.write=function(_,T,A,E,L,J){var X,H,Z,Y=J*8-L-1,K=(1<<Y)-1,G=K>>1,$=L===23?Math.pow(2,-24)-Math.pow(2,-77):0,U=E?0:J-1,V=E?1:-1,N=T<0||T===0&&1/T<0?1:0;if(T=Math.abs(T),isNaN(T)||T===1/0)H=isNaN(T)?1:0,X=K;else{if(X=Math.floor(Math.log(T)/Math.LN2),T*(Z=Math.pow(2,-X))<1)X--,Z*=2;if(X+G>=1)T+=$/Z;else T+=$*Math.pow(2,1-G);if(T*Z>=2)X++,Z/=2;if(X+G>=K)H=0,X=K;else if(X+G>=1)H=(T*Z-1)*Math.pow(2,L),X=X+G;else H=T*Math.pow(2,G-1)*Math.pow(2,L),X=0}for(;L>=8;_[A+U]=H&255,U+=V,H/=256,L-=8);X=X<<L|H,Y+=L;for(;Y>0;_[A+U]=X&255,U+=V,X/=256,Y-=8);_[A+U-V]|=N*128}});var FY=W((UI)=>{/*!
|
|
8
8
|
* The buffer module from node.js, for the browser.
|
|
9
9
|
*
|
|
10
10
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
11
11
|
* @license MIT
|
|
12
|
-
*/var YP=FW(),_D=sW(),CW=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;Yi.Buffer=o;Yi.SlowBuffer=di;Yi.INSPECT_MAX_BYTES=50;var Z0=2147483647;Yi.kMaxLength=Z0;o.TYPED_ARRAY_SUPPORT=Fi();if(!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error==="function")console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Fi(){try{var H=new Uint8Array(1),$={foo:function(){return 42}};return Object.setPrototypeOf($,Uint8Array.prototype),Object.setPrototypeOf(H,$),H.foo()===42}catch(A){return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(!o.isBuffer(this))return;return this.buffer}});Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(!o.isBuffer(this))return;return this.byteOffset}});function kA(H){if(H>Z0)throw RangeError('The value "'+H+'" is invalid for option "size"');var $=new Uint8Array(H);return Object.setPrototypeOf($,o.prototype),$}function o(H,$,A){if(typeof H==="number"){if(typeof $==="string")throw TypeError('The "string" argument must be of type string. Received type number');return HT(H)}return dW(H,$,A)}o.poolSize=8192;function dW(H,$,A){if(typeof H==="string")return Ci(H,$);if(ArrayBuffer.isView(H))return ii(H);if(H==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof H);if(_A(H,ArrayBuffer)||H&&_A(H.buffer,ArrayBuffer))return ZP(H,$,A);if(typeof SharedArrayBuffer<"u"&&(_A(H,SharedArrayBuffer)||H&&_A(H.buffer,SharedArrayBuffer)))return ZP(H,$,A);if(typeof H==="number")throw TypeError('The "value" argument must not be of type number. Received type number');var L=H.valueOf&&H.valueOf();if(L!=null&&L!==H)return o.from(L,$,A);var D=Gi(H);if(D)return D;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof H[Symbol.toPrimitive]==="function")return o.from(H[Symbol.toPrimitive]("string"),$,A);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof H)}o.from=function(H,$,A){return dW(H,$,A)};Object.setPrototypeOf(o.prototype,Uint8Array.prototype);Object.setPrototypeOf(o,Uint8Array);function aW(H){if(typeof H!=="number")throw TypeError('"size" argument must be of type number');else if(H<0)throw RangeError('The value "'+H+'" is invalid for option "size"')}function si(H,$,A){if(aW(H),H<=0)return kA(H);if($!==void 0)return typeof A==="string"?kA(H).fill($,A):kA(H).fill($);return kA(H)}o.alloc=function(H,$,A){return si(H,$,A)};function HT(H){return aW(H),kA(H<0?0:$T(H)|0)}o.allocUnsafe=function(H){return HT(H)};o.allocUnsafeSlow=function(H){return HT(H)};function Ci(H,$){if(typeof $!=="string"||$==="")$="utf8";if(!o.isEncoding($))throw TypeError("Unknown encoding: "+$);var A=lW(H,$)|0,L=kA(A),D=L.write(H,$);if(D!==A)L=L.slice(0,D);return L}function qP(H){var $=H.length<0?0:$T(H.length)|0,A=kA($);for(var L=0;L<$;L+=1)A[L]=H[L]&255;return A}function ii(H){if(_A(H,Uint8Array)){var $=new Uint8Array(H);return ZP($.buffer,$.byteOffset,$.byteLength)}return qP(H)}function ZP(H,$,A){if($<0||H.byteLength<$)throw RangeError('"offset" is outside of buffer bounds');if(H.byteLength<$+(A||0))throw RangeError('"length" is outside of buffer bounds');var L;if($===void 0&&A===void 0)L=new Uint8Array(H);else if(A===void 0)L=new Uint8Array(H,$);else L=new Uint8Array(H,$,A);return Object.setPrototypeOf(L,o.prototype),L}function Gi(H){if(o.isBuffer(H)){var $=$T(H.length)|0,A=kA($);if(A.length===0)return A;return H.copy(A,0,0,$),A}if(H.length!==void 0){if(typeof H.length!=="number"||AT(H.length))return kA(0);return qP(H)}if(H.type==="Buffer"&&Array.isArray(H.data))return qP(H.data)}function $T(H){if(H>=Z0)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Z0.toString(16)+" bytes");return H|0}function di(H){if(+H!=H)H=0;return o.alloc(+H)}o.isBuffer=function($){return $!=null&&$._isBuffer===!0&&$!==o.prototype};o.compare=function($,A){if(_A($,Uint8Array))$=o.from($,$.offset,$.byteLength);if(_A(A,Uint8Array))A=o.from(A,A.offset,A.byteLength);if(!o.isBuffer($)||!o.isBuffer(A))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if($===A)return 0;var L=$.length,D=A.length;for(var f=0,E=Math.min(L,D);f<E;++f)if($[f]!==A[f]){L=$[f],D=A[f];break}if(L<D)return-1;if(D<L)return 1;return 0};o.isEncoding=function($){switch(String($).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};o.concat=function($,A){if(!Array.isArray($))throw TypeError('"list" argument must be an Array of Buffers');if($.length===0)return o.alloc(0);var L;if(A===void 0){A=0;for(L=0;L<$.length;++L)A+=$[L].length}var D=o.allocUnsafe(A),f=0;for(L=0;L<$.length;++L){var E=$[L];if(_A(E,Uint8Array))if(f+E.length>D.length)o.from(E).copy(D,f);else Uint8Array.prototype.set.call(D,E,f);else if(!o.isBuffer(E))throw TypeError('"list" argument must be an Array of Buffers');else E.copy(D,f);f+=E.length}return D};function lW(H,$){if(o.isBuffer(H))return H.length;if(ArrayBuffer.isView(H)||_A(H,ArrayBuffer))return H.byteLength;if(typeof H!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof H);var A=H.length,L=arguments.length>2&&arguments[2]===!0;if(!L&&A===0)return 0;var D=!1;for(;;)switch($){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return zP(H).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return OW(H).length;default:if(D)return L?-1:zP(H).length;$=(""+$).toLowerCase(),D=!0}}o.byteLength=lW;function ai(H,$,A){var L=!1;if($===void 0||$<0)$=0;if($>this.length)return"";if(A===void 0||A>this.length)A=this.length;if(A<=0)return"";if(A>>>=0,$>>>=0,A<=$)return"";if(!H)H="utf8";while(!0)switch(H){case"hex":return ei(this,$,A);case"utf8":case"utf-8":return bW(this,$,A);case"ascii":return mi(this,$,A);case"latin1":case"binary":return wi(this,$,A);case"base64":return Ri(this,$,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ji(this,$,A);default:if(L)throw TypeError("Unknown encoding: "+H);H=(H+"").toLowerCase(),L=!0}}o.prototype._isBuffer=!0;function dL(H,$,A){var L=H[$];H[$]=H[A],H[A]=L}o.prototype.swap16=function(){var $=this.length;if($%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var A=0;A<$;A+=2)dL(this,A,A+1);return this};o.prototype.swap32=function(){var $=this.length;if($%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var A=0;A<$;A+=4)dL(this,A,A+3),dL(this,A+1,A+2);return this};o.prototype.swap64=function(){var $=this.length;if($%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var A=0;A<$;A+=8)dL(this,A,A+7),dL(this,A+1,A+6),dL(this,A+2,A+5),dL(this,A+3,A+4);return this};o.prototype.toString=function(){var $=this.length;if($===0)return"";if(arguments.length===0)return bW(this,0,$);return ai.apply(this,arguments)};o.prototype.toLocaleString=o.prototype.toString;o.prototype.equals=function($){if(!o.isBuffer($))throw TypeError("Argument must be a Buffer");if(this===$)return!0;return o.compare(this,$)===0};o.prototype.inspect=function(){var $="",A=Yi.INSPECT_MAX_BYTES;if($=this.toString("hex",0,A).replace(/(.{2})/g,"$1 ").trim(),this.length>A)$+=" ... ";return"<Buffer "+$+">"};if(CW)o.prototype[CW]=o.prototype.inspect;o.prototype.compare=function($,A,L,D,f){if(_A($,Uint8Array))$=o.from($,$.offset,$.byteLength);if(!o.isBuffer($))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof $);if(A===void 0)A=0;if(L===void 0)L=$?$.length:0;if(D===void 0)D=0;if(f===void 0)f=this.length;if(A<0||L>$.length||D<0||f>this.length)throw RangeError("out of range index");if(D>=f&&A>=L)return 0;if(D>=f)return-1;if(A>=L)return 1;if(A>>>=0,L>>>=0,D>>>=0,f>>>=0,this===$)return 0;var E=f-D,I=L-A,P=Math.min(E,I),T=this.slice(D,f),U=$.slice(A,L);for(var M=0;M<P;++M)if(T[M]!==U[M]){E=T[M],I=U[M];break}if(E<I)return-1;if(I<E)return 1;return 0};function yW(H,$,A,L,D){if(H.length===0)return-1;if(typeof A==="string")L=A,A=0;else if(A>2147483647)A=2147483647;else if(A<-2147483648)A=-2147483648;if(A=+A,AT(A))A=D?0:H.length-1;if(A<0)A=H.length+A;if(A>=H.length)if(D)return-1;else A=H.length-1;else if(A<0)if(D)A=0;else return-1;if(typeof $==="string")$=o.from($,L);if(o.isBuffer($)){if($.length===0)return-1;return iW(H,$,A,L,D)}else if(typeof $==="number"){if($=$&255,typeof Uint8Array.prototype.indexOf==="function")if(D)return Uint8Array.prototype.indexOf.call(H,$,A);else return Uint8Array.prototype.lastIndexOf.call(H,$,A);return iW(H,[$],A,L,D)}throw TypeError("val must be string, number or Buffer")}function iW(H,$,A,L,D){var f=1,E=H.length,I=$.length;if(L!==void 0){if(L=String(L).toLowerCase(),L==="ucs2"||L==="ucs-2"||L==="utf16le"||L==="utf-16le"){if(H.length<2||$.length<2)return-1;f=2,E/=2,I/=2,A/=2}}function P(_,x){if(f===1)return _[x];else return _.readUInt16BE(x*f)}var T;if(D){var U=-1;for(T=A;T<E;T++)if(P(H,T)===P($,U===-1?0:T-U)){if(U===-1)U=T;if(T-U+1===I)return U*f}else{if(U!==-1)T-=T-U;U=-1}}else{if(A+I>E)A=E-I;for(T=A;T>=0;T--){var M=!0;for(var t=0;t<I;t++)if(P(H,T+t)!==P($,t)){M=!1;break}if(M)return T}}return-1}o.prototype.includes=function($,A,L){return this.indexOf($,A,L)!==-1};o.prototype.indexOf=function($,A,L){return yW(this,$,A,L,!0)};o.prototype.lastIndexOf=function($,A,L){return yW(this,$,A,L,!1)};function li(H,$,A,L){A=Number(A)||0;var D=H.length-A;if(!L)L=D;else if(L=Number(L),L>D)L=D;var f=$.length;if(L>f/2)L=f/2;for(var E=0;E<L;++E){var I=parseInt($.substr(E*2,2),16);if(AT(I))return E;H[A+E]=I}return E}function yi(H,$,A,L){return z0(zP($,H.length-A),H,A,L)}function bi(H,$,A,L){return z0(Ki($),H,A,L)}function Ni(H,$,A,L){return z0(OW($),H,A,L)}function ki(H,$,A,L){return z0(gi($,H.length-A),H,A,L)}o.prototype.write=function($,A,L,D){if(A===void 0)D="utf8",L=this.length,A=0;else if(L===void 0&&typeof A==="string")D=A,L=this.length,A=0;else if(isFinite(A))if(A=A>>>0,isFinite(L)){if(L=L>>>0,D===void 0)D="utf8"}else D=L,L=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var f=this.length-A;if(L===void 0||L>f)L=f;if($.length>0&&(L<0||A<0)||A>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!D)D="utf8";var E=!1;for(;;)switch(D){case"hex":return li(this,$,A,L);case"utf8":case"utf-8":return yi(this,$,A,L);case"ascii":case"latin1":case"binary":return bi(this,$,A,L);case"base64":return Ni(this,$,A,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ki(this,$,A,L);default:if(E)throw TypeError("Unknown encoding: "+D);D=(""+D).toLowerCase(),E=!0}};o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ri(H,$,A){if($===0&&A===H.length)return YP.fromByteArray(H);else return YP.fromByteArray(H.slice($,A))}function bW(H,$,A){A=Math.min(H.length,A);var L=[],D=$;while(D<A){var f=H[D],E=null,I=f>239?4:f>223?3:f>191?2:1;if(D+I<=A){var P,T,U,M;switch(I){case 1:if(f<128)E=f;break;case 2:if(P=H[D+1],(P&192)===128){if(M=(f&31)<<6|P&63,M>127)E=M}break;case 3:if(P=H[D+1],T=H[D+2],(P&192)===128&&(T&192)===128){if(M=(f&15)<<12|(P&63)<<6|T&63,M>2047&&(M<55296||M>57343))E=M}break;case 4:if(P=H[D+1],T=H[D+2],U=H[D+3],(P&192)===128&&(T&192)===128&&(U&192)===128){if(M=(f&15)<<18|(P&63)<<12|(T&63)<<6|U&63,M>65535&&M<1114112)E=M}}}if(E===null)E=65533,I=1;else if(E>65535)E-=65536,L.push(E>>>10&1023|55296),E=56320|E&1023;L.push(E),D+=I}return Oi(L)}var GW=4096;function Oi(H){var $=H.length;if($<=GW)return String.fromCharCode.apply(String,H);var A="",L=0;while(L<$)A+=String.fromCharCode.apply(String,H.slice(L,L+=GW));return A}function mi(H,$,A){var L="";A=Math.min(H.length,A);for(var D=$;D<A;++D)L+=String.fromCharCode(H[D]&127);return L}function wi(H,$,A){var L="";A=Math.min(H.length,A);for(var D=$;D<A;++D)L+=String.fromCharCode(H[D]);return L}function ei(H,$,A){var L=H.length;if(!$||$<0)$=0;if(!A||A<0||A>L)A=L;var D="";for(var f=$;f<A;++f)D+=vi[H[f]];return D}function ji(H,$,A){var L=H.slice($,A),D="";for(var f=0;f<L.length-1;f+=2)D+=String.fromCharCode(L[f]+L[f+1]*256);return D}o.prototype.slice=function($,A){var L=this.length;if($=~~$,A=A===void 0?L:~~A,$<0){if($+=L,$<0)$=0}else if($>L)$=L;if(A<0){if(A+=L,A<0)A=0}else if(A>L)A=L;if(A<$)A=$;var D=this.subarray($,A);return Object.setPrototypeOf(D,o.prototype),D};function RH(H,$,A){if(H%1!==0||H<0)throw RangeError("offset is not uint");if(H+$>A)throw RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function($,A,L){if($=$>>>0,A=A>>>0,!L)RH($,A,this.length);var D=this[$],f=1,E=0;while(++E<A&&(f*=256))D+=this[$+E]*f;return D};o.prototype.readUintBE=o.prototype.readUIntBE=function($,A,L){if($=$>>>0,A=A>>>0,!L)RH($,A,this.length);var D=this[$+--A],f=1;while(A>0&&(f*=256))D+=this[$+--A]*f;return D};o.prototype.readUint8=o.prototype.readUInt8=function($,A){if($=$>>>0,!A)RH($,1,this.length);return this[$]};o.prototype.readUint16LE=o.prototype.readUInt16LE=function($,A){if($=$>>>0,!A)RH($,2,this.length);return this[$]|this[$+1]<<8};o.prototype.readUint16BE=o.prototype.readUInt16BE=function($,A){if($=$>>>0,!A)RH($,2,this.length);return this[$]<<8|this[$+1]};o.prototype.readUint32LE=o.prototype.readUInt32LE=function($,A){if($=$>>>0,!A)RH($,4,this.length);return(this[$]|this[$+1]<<8|this[$+2]<<16)+this[$+3]*16777216};o.prototype.readUint32BE=o.prototype.readUInt32BE=function($,A){if($=$>>>0,!A)RH($,4,this.length);return this[$]*16777216+(this[$+1]<<16|this[$+2]<<8|this[$+3])};o.prototype.readIntLE=function($,A,L){if($=$>>>0,A=A>>>0,!L)RH($,A,this.length);var D=this[$],f=1,E=0;while(++E<A&&(f*=256))D+=this[$+E]*f;if(f*=128,D>=f)D-=Math.pow(2,8*A);return D};o.prototype.readIntBE=function($,A,L){if($=$>>>0,A=A>>>0,!L)RH($,A,this.length);var D=A,f=1,E=this[$+--D];while(D>0&&(f*=256))E+=this[$+--D]*f;if(f*=128,E>=f)E-=Math.pow(2,8*A);return E};o.prototype.readInt8=function($,A){if($=$>>>0,!A)RH($,1,this.length);if(!(this[$]&128))return this[$];return(255-this[$]+1)*-1};o.prototype.readInt16LE=function($,A){if($=$>>>0,!A)RH($,2,this.length);var L=this[$]|this[$+1]<<8;return L&32768?L|4294901760:L};o.prototype.readInt16BE=function($,A){if($=$>>>0,!A)RH($,2,this.length);var L=this[$+1]|this[$]<<8;return L&32768?L|4294901760:L};o.prototype.readInt32LE=function($,A){if($=$>>>0,!A)RH($,4,this.length);return this[$]|this[$+1]<<8|this[$+2]<<16|this[$+3]<<24};o.prototype.readInt32BE=function($,A){if($=$>>>0,!A)RH($,4,this.length);return this[$]<<24|this[$+1]<<16|this[$+2]<<8|this[$+3]};o.prototype.readFloatLE=function($,A){if($=$>>>0,!A)RH($,4,this.length);return _D.read(this,$,!0,23,4)};o.prototype.readFloatBE=function($,A){if($=$>>>0,!A)RH($,4,this.length);return _D.read(this,$,!1,23,4)};o.prototype.readDoubleLE=function($,A){if($=$>>>0,!A)RH($,8,this.length);return _D.read(this,$,!0,52,8)};o.prototype.readDoubleBE=function($,A){if($=$>>>0,!A)RH($,8,this.length);return _D.read(this,$,!1,52,8)};function _$(H,$,A,L,D,f){if(!o.isBuffer(H))throw TypeError('"buffer" argument must be a Buffer instance');if($>D||$<f)throw RangeError('"value" argument is out of bounds');if(A+L>H.length)throw RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function($,A,L,D){if($=+$,A=A>>>0,L=L>>>0,!D){var f=Math.pow(2,8*L)-1;_$(this,$,A,L,f,0)}var E=1,I=0;this[A]=$&255;while(++I<L&&(E*=256))this[A+I]=$/E&255;return A+L};o.prototype.writeUintBE=o.prototype.writeUIntBE=function($,A,L,D){if($=+$,A=A>>>0,L=L>>>0,!D){var f=Math.pow(2,8*L)-1;_$(this,$,A,L,f,0)}var E=L-1,I=1;this[A+E]=$&255;while(--E>=0&&(I*=256))this[A+E]=$/I&255;return A+L};o.prototype.writeUint8=o.prototype.writeUInt8=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,1,255,0);return this[A]=$&255,A+1};o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,2,65535,0);return this[A]=$&255,this[A+1]=$>>>8,A+2};o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,2,65535,0);return this[A]=$>>>8,this[A+1]=$&255,A+2};o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,4,4294967295,0);return this[A+3]=$>>>24,this[A+2]=$>>>16,this[A+1]=$>>>8,this[A]=$&255,A+4};o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,4,4294967295,0);return this[A]=$>>>24,this[A+1]=$>>>16,this[A+2]=$>>>8,this[A+3]=$&255,A+4};o.prototype.writeIntLE=function($,A,L,D){if($=+$,A=A>>>0,!D){var f=Math.pow(2,8*L-1);_$(this,$,A,L,f-1,-f)}var E=0,I=1,P=0;this[A]=$&255;while(++E<L&&(I*=256)){if($<0&&P===0&&this[A+E-1]!==0)P=1;this[A+E]=($/I>>0)-P&255}return A+L};o.prototype.writeIntBE=function($,A,L,D){if($=+$,A=A>>>0,!D){var f=Math.pow(2,8*L-1);_$(this,$,A,L,f-1,-f)}var E=L-1,I=1,P=0;this[A+E]=$&255;while(--E>=0&&(I*=256)){if($<0&&P===0&&this[A+E+1]!==0)P=1;this[A+E]=($/I>>0)-P&255}return A+L};o.prototype.writeInt8=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,1,127,-128);if($<0)$=255+$+1;return this[A]=$&255,A+1};o.prototype.writeInt16LE=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,2,32767,-32768);return this[A]=$&255,this[A+1]=$>>>8,A+2};o.prototype.writeInt16BE=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,2,32767,-32768);return this[A]=$>>>8,this[A+1]=$&255,A+2};o.prototype.writeInt32LE=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,4,2147483647,-2147483648);return this[A]=$&255,this[A+1]=$>>>8,this[A+2]=$>>>16,this[A+3]=$>>>24,A+4};o.prototype.writeInt32BE=function($,A,L){if($=+$,A=A>>>0,!L)_$(this,$,A,4,2147483647,-2147483648);if($<0)$=4294967295+$+1;return this[A]=$>>>24,this[A+1]=$>>>16,this[A+2]=$>>>8,this[A+3]=$&255,A+4};function NW(H,$,A,L,D,f){if(A+L>H.length)throw RangeError("Index out of range");if(A<0)throw RangeError("Index out of range")}function kW(H,$,A,L,D){if($=+$,A=A>>>0,!D)NW(H,$,A,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return _D.write(H,$,A,L,23,4),A+4}o.prototype.writeFloatLE=function($,A,L){return kW(this,$,A,!0,L)};o.prototype.writeFloatBE=function($,A,L){return kW(this,$,A,!1,L)};function RW(H,$,A,L,D){if($=+$,A=A>>>0,!D)NW(H,$,A,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return _D.write(H,$,A,L,52,8),A+8}o.prototype.writeDoubleLE=function($,A,L){return RW(this,$,A,!0,L)};o.prototype.writeDoubleBE=function($,A,L){return RW(this,$,A,!1,L)};o.prototype.copy=function($,A,L,D){if(!o.isBuffer($))throw TypeError("argument should be a Buffer");if(!L)L=0;if(!D&&D!==0)D=this.length;if(A>=$.length)A=$.length;if(!A)A=0;if(D>0&&D<L)D=L;if(D===L)return 0;if($.length===0||this.length===0)return 0;if(A<0)throw RangeError("targetStart out of bounds");if(L<0||L>=this.length)throw RangeError("Index out of range");if(D<0)throw RangeError("sourceEnd out of bounds");if(D>this.length)D=this.length;if($.length-A<D-L)D=$.length-A+L;var f=D-L;if(this===$&&typeof Uint8Array.prototype.copyWithin==="function")this.copyWithin(A,L,D);else Uint8Array.prototype.set.call($,this.subarray(L,D),A);return f};o.prototype.fill=function($,A,L,D){if(typeof $==="string"){if(typeof A==="string")D=A,A=0,L=this.length;else if(typeof L==="string")D=L,L=this.length;if(D!==void 0&&typeof D!=="string")throw TypeError("encoding must be a string");if(typeof D==="string"&&!o.isEncoding(D))throw TypeError("Unknown encoding: "+D);if($.length===1){var f=$.charCodeAt(0);if(D==="utf8"&&f<128||D==="latin1")$=f}}else if(typeof $==="number")$=$&255;else if(typeof $==="boolean")$=Number($);if(A<0||this.length<A||this.length<L)throw RangeError("Out of range index");if(L<=A)return this;if(A=A>>>0,L=L===void 0?this.length:L>>>0,!$)$=0;var E;if(typeof $==="number")for(E=A;E<L;++E)this[E]=$;else{var I=o.isBuffer($)?$:o.from($,D),P=I.length;if(P===0)throw TypeError('The value "'+$+'" is invalid for argument "value"');for(E=0;E<L-A;++E)this[E+A]=I[E%P]}return this};var Ji=/[^+/0-9A-Za-z-_]/g;function Qi(H){if(H=H.split("=")[0],H=H.trim().replace(Ji,""),H.length<2)return"";while(H.length%4!==0)H=H+"=";return H}function zP(H,$){$=$||1/0;var A,L=H.length,D=null,f=[];for(var E=0;E<L;++E){if(A=H.charCodeAt(E),A>55295&&A<57344){if(!D){if(A>56319){if(($-=3)>-1)f.push(239,191,189);continue}else if(E+1===L){if(($-=3)>-1)f.push(239,191,189);continue}D=A;continue}if(A<56320){if(($-=3)>-1)f.push(239,191,189);D=A;continue}A=(D-55296<<10|A-56320)+65536}else if(D){if(($-=3)>-1)f.push(239,191,189)}if(D=null,A<128){if(($-=1)<0)break;f.push(A)}else if(A<2048){if(($-=2)<0)break;f.push(A>>6|192,A&63|128)}else if(A<65536){if(($-=3)<0)break;f.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if(($-=4)<0)break;f.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw Error("Invalid code point")}return f}function Ki(H){var $=[];for(var A=0;A<H.length;++A)$.push(H.charCodeAt(A)&255);return $}function gi(H,$){var A,L,D,f=[];for(var E=0;E<H.length;++E){if(($-=2)<0)break;A=H.charCodeAt(E),L=A>>8,D=A%256,f.push(D),f.push(L)}return f}function OW(H){return YP.toByteArray(Qi(H))}function z0(H,$,A,L){for(var D=0;D<L;++D){if(D+A>=$.length||D>=H.length)break;$[D+A]=H[D]}return D}function _A(H,$){return H instanceof $||H!=null&&H.constructor!=null&&H.constructor.name!=null&&H.constructor.name===$.name}function AT(H){return H!==H}var vi=function(){var H="0123456789abcdef",$=Array(256);for(var A=0;A<16;++A){var L=A*16;for(var D=0;D<16;++D)$[L+D]=H[A]+H[D]}return $}()});var KW=p((PO,LT)=>{var eW=SW(),JW=nW(),HE=HG();function HG(){let H=B("buffer");return H&&H.Buffer?H.Buffer:wW().Buffer}var $G=HE.from("==","base64");function AG(H){let $=!1,A=!1,L=Math.pow(2,31)-1;if(typeof H==="boolean")$=H;else H=H||{},L=H.maxInt||Math.pow(2,31)-1,A=!!H.urlSafe,$=!!H.fixedLength;E.uuid=eW(),E.decode=QW;let D=jW(E.uuid,A),f=Math.floor(H.startFrom||0);if(isNaN(L))throw Error(`maxInt must be a number. recieved ${H.maxInt}`);if(isNaN(f)||!(L>f&&f>=0))throw Error([`when passed, opts.startFrom must be a number between 0 and ${L}.`,"Only the integer part matters.",`- got: ${H.startFrom}`].join(`
|
|
13
|
-
`));return E;function E(){let I;if(f===L)E.uuid=eW(),D=jW(E.uuid,A),f=0;if($)I=D+`0000000000${f}`.slice(-10);else I=D+f;return f=f+1|0,I}}function jW(H,$){let A=HE.concat([HE.from(JW.parse(H)),$G]).toString("base64");if($)return A.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"-");return A.replace(/=+$/,"/")}function QW(H,$){if($=$||{},!!$.urlSafe)H=H.replace(/-([^-]*)$/,"/$1").replace(/-/g,"+").replace(/_/g,"/");if(H.length<22)return null;let L=H.lastIndexOf("/");if(L===-1)return null;let D=H.substring(0,L),f=Number(H.substring(L+1));if(!D||isNaN(f))return null;return{uuid:JW.unparse(HE.from(D+"==","base64")),count:f}}LT.exports=AG;LT.exports.decode=QW});var YW=p((TO,vW)=>{var LG=s8(),{pipeline:DG}=B("stream"),gW=bA(),fG=bP(),{through:EG}=GL(),IG=g0(),PG=KW()();function TG(H){this.cmd="connack",this.returnCode=H.returnCode,this.sessionPresent=H.sessionPresent}function UG(H,$){this.client=H,this.packet=$}var MG=[pG,VG,WG,xG,hG,cG,fT,XG],DT=["","unacceptable protocol version","identifier rejected","Server unavailable","bad user name or password","not authorized","keep alive limit exceeded"];function tG(H,$,A){clearTimeout(H._connectTimer),H._connectTimer=null,H.connecting=!0,H.broker.preConnect(H,$,L);function L(D,f){if(!D&&f===!0)setImmediate(_G,H,$,A);else H.connecting=!1,A(D)}}function _G(H,$,A){let L=$.clientId,D=0;if($.protocolVersion<3||$.protocolVersion>4)D=1;if($.protocolVersion===3&&L.length>H.broker.maxClientsIdLength)D=2;if(H.broker.keepaliveLimit&&(!$.keepalive||$.keepalive>H.broker.keepaliveLimit))D=6;if(D>0){let f=Error(DT[D]);f.errorCode=D,fT({client:H,returnCode:D,sessionPresent:!1},A.bind(this,f));return}H.id=L||"aedes_"+PG(),H.clean=$.clean,H.version=$.protocolVersion,H._will=$.will,H.broker._series(new UG(H,$),MG,{returnCode:0,sessionPresent:!1},function(f){if(this.client.connecting=!1,!f)this.client.connected=!0,this.client.broker.emit("clientReady",H),this.client.emit("connected");A(f)})}function pG(H,$){let A=this.client;A.pause(),A.broker.authenticate(A,this.packet.username,this.packet.password,L);function L(D,f){if(A.closed||A.broker.closed)return;if(!D&&f)return A._authorized=!0,$();if(D){let E=D.returnCode;if(E&&(E>=2&&E<=5))H.returnCode=E;else H.returnCode=5;if(!D.message)D.message=DT[H.returnCode]}else H.returnCode=5,D=Error(DT[H.returnCode]);D.errorCode=H.returnCode,H.client=A,fT(H,A.close.bind(A,$.bind(this,D)))}}function VG(H,$){if(this.packet.keepalive>0){let A=this.client;A._keepaliveInterval=this.packet.keepalive*1500+1,A._keepaliveTimer=LG(function(){A.broker.emit("keepaliveTimeout",A),A.emit("error",Error("keep alive timeout"))},A._keepaliveInterval)}$()}function WG(H,$){let A=this.client;if(!this.packet.clean){A.broker.persistence.subscriptionsByClient({id:A.id,done:$,arg:H},uG);return}H.sessionPresent=!1,A.broker.persistence.cleanSubscriptions(A,$)}function uG(H,$,A){if(H)return A.done(H);A.arg.subs=$,A.done()}function xG(H,$){if(H.subs){IG(this.client,{subscriptions:H.subs},!0,$),H.sessionPresent=!!H.subs;return}H.sessionPresent=!1,$()}function hG(H,$){let A=this.client;A.will=A._will,A.broker.persistence.delWill(A,function(){if(A.will)A.broker.persistence.putWill(A,A.will,$);else $()})}function cG(H,$){let A=this.client;A.broker.registerClient(A),$()}function fT(H,$){let A=H.client||this.client,L=new TG(H);gW(A,L,function(D){if(!D)A.broker.emit("connackSent",L,A),A.connackSent=!0;$(D)})}function XG(H,$){let A=this.client,L=A.broker.persistence,D=L.outgoingStream(A);A.resume(),DG(D,EG(function(E,I,P){let T=new fG(E,A);T.writeCallback=(U,M)=>P(U),L.outgoingUpdate(A,T,SG)}),$)}function SG(H,$,A){let L=A.writeCallback;if(H)return $.emit("error",H),L();let D=A.cmd==="publish"?$.broker.authorizeForward($,A):!0,f=$.broker.persistence;if($.clean||!D)f.outgoingClearMessageId($,A,L);else gW($,A,L)}vW.exports=tG});var zW=p((UO,ZW)=>{var qW=bA();function rG(H){this.cmd="puback",this.messageId=H.messageId}function BG(H){this.cmd="pubrec",this.messageId=H.messageId}var nG=[sG,FG];function oG(H,$,A){let L=$.topic,D;if(L.length===0)return D=Error("empty topic not allowed in PUBLISH"),A(D);if(L.indexOf("#")>-1)return D=Error("# is not allowed in PUBLISH"),A(D);if(L.indexOf("+")>-1)return D=Error("+ is not allowed in PUBLISH"),A(D);H.broker._series(H,nG,$,A)}function FG(H,$){let A=this;switch(H.qos){case 2:A.broker.persistence.incomingStorePacket(A,H,function(L){if(L)return $(L);qW(A,new BG(H),$)});break;case 1:qW(A,new rG(H),function(L){if(L)return $(L);A.broker.publish(H,A,$)});break;case 0:A.broker.publish(H,A,$);break;default:}}function sG(H,$){this.broker.authorizePublish(this,H,$)}ZW.exports=oG});var $1=p((MO,H1)=>{function CG(H,$,A){H.broker.persistence.outgoingClearMessageId(H,$,function(D,f){H.broker.emit("ack",f,H),A(D)})}H1.exports=CG});var L1=p((tO,A1)=>{var iG=bA();function GG(H,$){this.client=H,this.packet=$}function dG(H){this.cmd="pubcomp",this.messageId=H.messageId}var aG=[yG,bG,NG,kG];function lG(H,$,A){H.broker._series(new GG(H,$),aG,{},A)}function yG(H,$){this.client.broker.persistence.incomingGetPacket(this.client,this.packet,L);function L(D,f){H.packet=f,$(D)}}function bG(H,$){this.client.broker.publish(H.packet,this.client,$)}function NG(H,$){iG(this.client,new dG(H.packet),$)}function kG(H,$){this.client.broker.persistence.incomingDelPacket(this.client,H.packet,$)}A1.exports=lG});var E1=p((_O,f1)=>{var D1=bA();function RG(H){this.cmd="pubrel",this.messageId=H.messageId}function OG(H,$,A){let L=new RG($);if(H.clean){D1(H,L,A);return}H.broker.persistence.outgoingUpdate(H,L,D);function D(f){if(f)A(f);else D1(H,L,A)}}f1.exports=OG});var P1=p((pO,I1)=>{var mG=bA(),wG={cmd:"pingresp"};function eG(H,$,A){H.broker.emit("ping",$,H),mG(H,wG,A)}I1.exports=eG});var M1=p((VO,U1)=>{var jG=YW(),JG=g0(),QG=kP(),KG=zW(),gG=$1(),vG=L1(),YG=E1(),qG=P1();function ZG(H,$,A){if($.cmd==="connect"){if(H.connecting||H.connected){T1(H.conn,$,A);return}jG(H,$,A);return}if(!H.connecting&&!H.connected){T1(H.conn,$,A);return}switch($.cmd){case"publish":KG(H,$,A);break;case"subscribe":JG(H,$,!1,A);break;case"unsubscribe":QG(H,$,A);break;case"pubcomp":case"puback":gG(H,$,A);break;case"pubrel":vG(H,$,A);break;case"pubrec":YG(H,$,A);break;case"pingreq":qG(H,$,A);break;case"disconnect":H._disconnected=!0,H.conn.destroy(),A();return;default:H.conn.destroy(),A();return}if(H._keepaliveInterval>0)H._keepaliveTimer.reschedule(H._keepaliveInterval)}function T1(H,$,A){H.destroy();let L=Error("Invalid protocol");L.info=$,A(L)}U1.exports=ZG});var h1=p((WO,x1)=>{var zG=Q0(),H4=B("events"),$4=B("util"),A4=E8(),_1=vL(),p1=bA(),L4=bP(),D4=g0(),V1=kP(),W1=M1(),{pipeline:f4}=B("stream"),{through:E4}=GL();x1.exports=pA;function pA(H,$,A){let L=this;this.closed=!1,this.connecting=!1,this.connected=!1,this.connackSent=!1,this.errored=!1,this.id=null,this.clean=!0,this.version=null,this.subscriptions={},this.duplicates={},this.broker=H,this.conn=$,$.client=this,this._disconnected=!1,this._authorized=!1,this._parsingBatch=1,this._nextId=Math.ceil(Math.random()*65535),this.req=A,this.connDetails=A?A.connDetails:null,this.will=null,this._will=null,this._parser=zG.parser(),this._parser.client=this,this._parser._queue=[],this._parser.on("packet",T4),this.once("connected",U4);function D(E){if(E){L.emit("error",E);return}let I=L;if(I._paused)return;if(L._parsingBatch--,L._parsingBatch<=0){L._parsingBatch=0;let P=I.conn.read(null);if(P)I._parser.parse(P)}}this._nextBatch=D,$.on("readable",D),this.on("error",u1),$.on("error",this.emit.bind(this,"error")),this._parser.on("error",this.emit.bind(this,"error")),$.on("end",this.close.bind(this)),this._eos=A4(this.conn,this.close.bind(this));let f=(E)=>{if(E.clientId===L.id&&E.nl)return;return I4(L,E)&&L.broker.authorizeForward(L,E)};this.deliver0=function(I,P){let T=f(I);if(T)setImmediate(()=>{let U=new _1(T,H);U.qos=0,p1(L,U,function(M){L._onError(M),P()})});else setImmediate(P)},this.deliverQoS=function(I,P){if(I.qos===0){L.deliver0(I,P);return}let T=f(I);if(T)setImmediate(()=>{let U=new L4(T,L),M=L.subscriptions[U.topic];if(M&&(M.qos||0)<U.qos)U.qos=M.qos;if(U.writeCallback=P,L.clean||U.retain)t1(null,L,U);else H.persistence.outgoingUpdate(L,U,t1)});else if(L.clean===!1)L.broker.persistence.outgoingClearMessageId(L,I,pD),setImmediate(P);else setImmediate(P)},this._keepaliveTimer=null,this._keepaliveInterval=-1,this._connectTimer=setTimeout(function(){L.emit("error",Error("connect did not arrive in time"))},H.connectTimeout)}function I4(H,$){let A=$.brokerId;if(!A)return!0;let L=H.duplicates,D=$.brokerCounter,f=(L[A]||0)<D;if(f)L[A]=D;return f}function t1(H,$,A){if(H)$.emit("error",H),A.writeCallback();else p1($,A,function(L){if(L)$.emit("error",L);A.writeCallback()})}function P4(H){H.callback()}function u1(H){if(!H)return;this.errored=!0,this.conn.removeAllListeners("error"),this.conn.on("error",pD);let $=this.conn._writableState;(typeof $.getBuffer==="function"?$.getBuffer():$.buffer).forEach(P4),this.broker.emit(this.id?"clientError":"connectionError",this,H),this.close()}$4.inherits(pA,H4);pA.prototype._onError=u1;pA.prototype.publish=function(H,$){let A=new _1(H,this.broker),L=this;if(A.qos===0){this.deliver0(A,$);return}if(!this.clean&&this.id)this.broker.persistence.outgoingEnqueue({clientId:this.id},A,function(f){if(f)return $(f);L.deliverQoS(A,$)});else L.deliverQoS(A,$)};pA.prototype.subscribe=function(H,$){if(!H.subscriptions){if(!Array.isArray(H))H=[H];H={subscriptions:H}}D4(this,H,!1,$)};pA.prototype.unsubscribe=function(H,$){if(!H.unsubscriptions){if(!Array.isArray(H))H=[H];H={unsubscriptions:H}}V1(this,H,$)};pA.prototype.close=function(H){if(this.closed){if(typeof H==="function")H();return}let $=this,A=this.conn;if(this.closed=!0,this._parser.removeAllListeners("packet"),A.removeAllListeners("readable"),this._parser._queue=null,this._keepaliveTimer)this._keepaliveTimer.clear(),this._keepaliveInterval=-1,this._keepaliveTimer=null;if(this._connectTimer)clearTimeout(this._connectTimer),this._connectTimer=null;this._eos(),this._eos=pD,V1(this,{unsubscriptions:Object.keys(this.subscriptions)},L);function L(){let D=$.will;if(!$._disconnected&&D)$.broker.authorizePublish($,D,function(f){if(f)return E();$.broker.publish(D,$,E);function E(){$.broker.persistence.delWill({id:$.id,brokerId:$.broker.id},pD)}});else if(D)$.broker.persistence.delWill({id:$.id,brokerId:$.broker.id},pD);if($.will=null,$._will=null,$.connected=!1,$.connecting=!1,A.removeAllListeners("error"),A.on("error",pD),$.broker.clients[$.id]&&$._authorized)$.broker.unregisterClient($);if($.conn.emit("drain"),$.conn.removeAllListeners("drain"),A.destroy(),typeof H==="function")H()}};pA.prototype.pause=function(){this._paused=!0};pA.prototype.resume=function(){this._paused=!1,this._nextBatch()};function T4(H){let $=this.client;if($._parsingBatch++,$.connackSent||$._parsingBatch===1)W1($,H,$._nextBatch);else if(this._queue.length<$.broker.queueLimit)this._queue.push(H);else this.emit("error",Error("Client queue limit reached"))}function U4(){let H=this._parser._queue;if(H){for(let $=0,A=H.length;$<A;$++)W1(this,H[$],this._nextBatch);this._parser._queue=null}}pA.prototype.emptyOutgoingQueue=function(H){let $=this,A=$.broker.persistence;function L(D,f,E){A.outgoingClearMessageId($,D,E)}f4(A.outgoingStream($),E4(L),H)};function pD(){}});var c1=p((uO,M4)=>{M4.exports={name:"aedes",version:"0.51.3",description:"Stream-based MQTT broker",main:"aedes.js",types:"aedes.d.ts",scripts:{lint:"npm run lint:standard && npm run lint:typescript && npm run lint:markdown","lint:fix":"standard --fix && eslint -c types/.eslintrc.json --fix aedes.d.ts types/**/*.ts test/types/**/*.test-d.ts","lint:standard":"standard --verbose | snazzy","lint:typescript":"eslint -c types/.eslintrc.json aedes.d.ts types/**/*.ts test/types/**/*.test-d.ts","lint:markdown":"markdownlint docs/*.md README.md",test:"npm run lint && npm run unit && npm run test:typescript","test:ci":"npm run lint && npm run unit -- --cov --no-check-coverage --coverage-report=lcovonly && npm run test:typescript","test:report":"npm run lint && npm run unit:report && npm run test:typescript","test:typescript":"tsd",unit:"tap -J test/*.js","unit:report":"tap -J test/*.js --cov --coverage-report=html --coverage-report=cobertura | tee out.tap","license-checker":'license-checker --production --onlyAllow="MIT;ISC;BSD-3-Clause;BSD-2-Clause;0BSD"',release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it --disable-metrics"},"release-it":{github:{release:!0},git:{tagName:"v${version}"},hooks:{"before:init":["npm run test:ci"]},npm:{publish:!0}},"pre-commit":["test"],tsd:{directory:"test/types"},standard:{ignore:["types/*","test/types/*"]},repository:{type:"git",url:"git+https://github.com/moscajs/aedes.git"},keywords:["mqtt","broker","server","mqtt-server","stream","streams","publish","subscribe","pubsub","messaging","mosca","mosquitto","iot","internet","of","things"],author:"Matteo Collina <hello@matteocollina.com>",contributors:[{name:"Gavin D'mello",url:"https://github.com/GavinDmello"},{name:"Behrad Zari",url:"https://github.com/behrad"},{name:"Gnought",url:"https://github.com/gnought"},{name:"Daniel Lando",url:"https://github.com/robertsLando"}],license:"MIT",funding:{type:"opencollective",url:"https://opencollective.com/aedes"},bugs:{url:"https://github.com/moscajs/aedes/issues"},homepage:"https://github.com/moscajs/aedes#readme",engines:{node:">=16"},devDependencies:{"@sinonjs/fake-timers":"^11.2.2","@types/node":"^20.11.17","@typescript-eslint/eslint-plugin":"^7.0.1","@typescript-eslint/parser":"^7.0.1","concat-stream":"^2.0.0",duplexify:"^4.1.2","license-checker":"^25.0.1","markdownlint-cli":"^0.41.0",mqtt:"^5.3.5","mqtt-connection":"^4.1.0","pre-commit":"^1.2.2",proxyquire:"^2.1.3","release-it":"^17.0.5",snazzy:"^9.0.0",standard:"^17.1.0",tap:"^16.3.10",tsd:"^0.31.0",typescript:"^5.3.3","websocket-stream":"^5.5.2"},dependencies:{"aedes-packet":"^3.0.0","aedes-persistence":"^9.1.2","end-of-stream":"^1.4.4",fastfall:"^1.5.1",fastparallel:"^2.4.1",fastseries:"^2.0.0",hyperid:"^3.2.0",mqemitter:"^6.0.0","mqtt-packet":"^9.0.0",retimer:"^4.0.0",reusify:"^1.0.4",uuid:"^10.0.0"}}});var n1=p((xO,B1)=>{var t4=B("events"),_4=B("util"),p4=zE(),V4=vU(),{v4:W4}=zM(),u4=qf(),{pipeline:x4}=B("stream"),h4=vL(),c4=Pt(),X4=Vt(),S4=h1(),{$SYS_PREFIX:VA,bulk:r4}=GL();B1.exports=p$.createBroker=p$;var B4={concurrency:100,heartbeatInterval:60000,connectTimeout:30000,decodeProtocol:null,preConnect:G4,authenticate:d4,authorizePublish:a4,authorizeSubscribe:l4,authorizeForward:y4,published:b4,trustProxy:!1,trustedProxies:[],queueLimit:42,maxClientsIdLength:23,keepaliveLimit:0};function p$(H){let $=this;if(!(this instanceof p$))return new p$(H);H=Object.assign({},B4,H),this.id=H.id||W4(),this.counter=0,this.queueLimit=H.queueLimit,this.connectTimeout=H.connectTimeout,this.keepaliveLimit=H.keepaliveLimit,this.maxClientsIdLength=H.maxClientsIdLength,this.mq=H.mq||X4({concurrency:H.concurrency,matchEmptyLevels:!0}),this.handle=function(U,M){return U.setMaxListeners(H.concurrency*2),new S4($,U,M)},this.persistence=H.persistence||c4(),this.persistence.broker=this,this._parallel=p4(),this._series=V4(),this._enqueuers=u4(o4),this.preConnect=H.preConnect,this.authenticate=H.authenticate,this.authorizePublish=H.authorizePublish,this.authorizeSubscribe=H.authorizeSubscribe,this.authorizeForward=H.authorizeForward,this.published=H.published,this.decodeProtocol=H.decodeProtocol,this.trustProxy=H.trustProxy,this.trustedProxies=H.trustedProxies,this.clients={},this.brokers={};let A=VA+$.id+"/heartbeat",L=VA+$.id+"/birth";this._heartbeatInterval=setInterval(f,H.heartbeatInterval);let D=Buffer.from($.id,"utf8");$.publish({topic:L,payload:D},ff);function f(){$.publish({topic:A,payload:D},ff)}function E(T){if($.brokers[T]+3*H.heartbeatInterval<Date.now())delete $.brokers[T]}this._clearWillInterval=setInterval(function(){Object.keys($.brokers).forEach(E),x4($.persistence.streamWill($.brokers),r4(I),function(U){if(U)$.emit("error",U)})},H.heartbeatInterval*4);function I(T,U){$._parallel($,P,T,U)}function P(T,U){if($.brokers[T.brokerId]!==void 0&&$.brokers[T.brokerId]+3*H.heartbeatInterval>=Date.now())return U();this.authorizePublish($.clients[T.clientId]||null,T,function(t){if(t)return _();$.publish(T,_);function _(x){if(x)return U(x);$.persistence.delWill({id:T.clientId,brokerId:T.brokerId},U)}})}this.mq.on(VA+"+/heartbeat",function(U,M){$.brokers[U.payload.toString()]=Date.now(),M()}),this.mq.on(VA+"+/birth",function(U,M){let t=U.payload.toString();if(t!==$.id)for(let _ in $.clients)delete $.clients[_].duplicates[t];M()}),this.mq.on(VA+"+/new/clients",function(U,M){let t=U.topic.split("/")[1],_=U.payload.toString();if($.clients[_]&&t!==$.id)if($.clients[_].closed)$.deleteClient(_),M();else $.clients[_].close(M);else M()}),this.connectedClients=0,this.closed=!1}_4.inherits(p$,t4);function X1(H,$){if(H.retain)this.broker.persistence.storeRetained(H,$);else $()}function S1(H,$){if(this.client)H.clientId=this.client.id;this.broker.mq.emit(H,$)}function n4(H,$){let A=this.broker._enqueuers.get();A.complete=$,A.packet=H,A.topic=H.topic,A.broker=this.broker,this.broker.persistence.subscriptionsByTopic(H.topic,A.done)}function o4(){this.next=null,this.complete=null,this.packet=null,this.topic=null,this.broker=null;let H=this;this.done=function(A,L){let D=H.broker;if(A){D.emit("error",A);return}if(H.topic.indexOf(VA)===0)L=L.filter(F4);let{packet:f,complete:E}=H;H.packet=null,H.complete=null,H.topic=null,D.persistence.outgoingEnqueueCombi(L,f,E),D._enqueuers.release(H)}}function F4(H){let $=H.topic.charCodeAt(0);return $!==43&&$!==35}function r1(H,$){this.broker.published(this.packet,this.client,$),this.broker.emit("publish",this.packet,this.client)}var s4=[X1,S1,r1],C4=[X1,n4,S1,r1];p$.prototype.publish=function(H,$,A){if(typeof $==="function")A=$,$=null;let L=new h4(H,this),D=L.qos>0?C4:s4;this._series(new N4(this,$,H),D,L,A)};p$.prototype.subscribe=function(H,$,A){this.mq.on(H,$,A)};p$.prototype.unsubscribe=function(H,$,A){this.mq.removeListener(H,$,A)};p$.prototype.registerClient=function(H){let $=this;if(this.clients[H.id])this.clients[H.id].close(function(){$._finishRegisterClient(H)});else this._finishRegisterClient(H)};p$.prototype._finishRegisterClient=function(H){this.connectedClients++,this.clients[H.id]=H,this.emit("client",H),this.publish({topic:VA+this.id+"/new/clients",payload:Buffer.from(H.id,"utf8")},ff)};p$.prototype.unregisterClient=function(H){this.deleteClient(H.id),this.emit("clientDisconnect",H),this.publish({topic:VA+this.id+"/disconnect/clients",payload:Buffer.from(H.id,"utf8")},ff)};p$.prototype.deleteClient=function(H){this.connectedClients--,delete this.clients[H]};function i4(H,$){this.clients[H].close($)}p$.prototype.close=function(H=ff){let $=this;if(this.closed)return H();this.closed=!0,clearInterval(this._heartbeatInterval),clearInterval(this._clearWillInterval),this._parallel(this,i4,Object.keys(this.clients),A);function A(){$.emit("closed"),$.mq.close(H)}};p$.prototype.version=c1().version;function G4(H,$,A){A(null,!0)}function d4(H,$,A,L){L(null,!0)}function a4(H,$,A){if($.topic.startsWith(VA))return A(Error(VA+" topic is reserved"));A(null)}function l4(H,$,A){A(null,$)}function y4(H,$){return $}function b4(H,$,A){A(null)}function N4(H,$,A){this.broker=H,this.client=$,this.packet=A}function ff(){}});var C1=p((FO,s1)=>{s1.exports=R4;function VD(H){if(H instanceof Buffer)return Buffer.from(H);return new H.constructor(H.buffer.slice(),H.byteOffset,H.length)}function R4(H){if(H=H||{},H.circles)return O4(H);let $=new Map;if($.set(Date,(E)=>new Date(E)),$.set(Map,(E,I)=>new Map(L(Array.from(E),I))),$.set(Set,(E,I)=>new Set(L(Array.from(E),I))),H.constructorHandlers)for(let E of H.constructorHandlers)$.set(E[0],E[1]);let A=null;return H.proto?f:D;function L(E,I){let P=Object.keys(E),T=Array(P.length);for(let U=0;U<P.length;U++){let M=P[U],t=E[M];if(typeof t!=="object"||t===null)T[M]=t;else if(t.constructor!==Object&&(A=$.get(t.constructor)))T[M]=A(t,I);else if(ArrayBuffer.isView(t))T[M]=VD(t);else T[M]=I(t)}return T}function D(E){if(typeof E!=="object"||E===null)return E;if(Array.isArray(E))return L(E,D);if(E.constructor!==Object&&(A=$.get(E.constructor)))return A(E,D);let I={};for(let P in E){if(Object.hasOwnProperty.call(E,P)===!1)continue;let T=E[P];if(typeof T!=="object"||T===null)I[P]=T;else if(T.constructor!==Object&&(A=$.get(T.constructor)))I[P]=A(T,D);else if(ArrayBuffer.isView(T))I[P]=VD(T);else I[P]=D(T)}return I}function f(E){if(typeof E!=="object"||E===null)return E;if(Array.isArray(E))return L(E,f);if(E.constructor!==Object&&(A=$.get(E.constructor)))return A(E,f);let I={};for(let P in E){let T=E[P];if(typeof T!=="object"||T===null)I[P]=T;else if(T.constructor!==Object&&(A=$.get(T.constructor)))I[P]=A(T,f);else if(ArrayBuffer.isView(T))I[P]=VD(T);else I[P]=f(T)}return I}}function O4(H){let $=[],A=[],L=new Map;if(L.set(Date,(P)=>new Date(P)),L.set(Map,(P,T)=>new Map(f(Array.from(P),T))),L.set(Set,(P,T)=>new Set(f(Array.from(P),T))),H.constructorHandlers)for(let P of H.constructorHandlers)L.set(P[0],P[1]);let D=null;return H.proto?I:E;function f(P,T){let U=Object.keys(P),M=Array(U.length);for(let t=0;t<U.length;t++){let _=U[t],x=P[_];if(typeof x!=="object"||x===null)M[_]=x;else if(x.constructor!==Object&&(D=L.get(x.constructor)))M[_]=D(x,T);else if(ArrayBuffer.isView(x))M[_]=VD(x);else{let V=$.indexOf(x);if(V!==-1)M[_]=A[V];else M[_]=T(x)}}return M}function E(P){if(typeof P!=="object"||P===null)return P;if(Array.isArray(P))return f(P,E);if(P.constructor!==Object&&(D=L.get(P.constructor)))return D(P,E);let T={};$.push(P),A.push(T);for(let U in P){if(Object.hasOwnProperty.call(P,U)===!1)continue;let M=P[U];if(typeof M!=="object"||M===null)T[U]=M;else if(M.constructor!==Object&&(D=L.get(M.constructor)))T[U]=D(M,E);else if(ArrayBuffer.isView(M))T[U]=VD(M);else{let t=$.indexOf(M);if(t!==-1)T[U]=A[t];else T[U]=E(M)}}return $.pop(),A.pop(),T}function I(P){if(typeof P!=="object"||P===null)return P;if(Array.isArray(P))return f(P,I);if(P.constructor!==Object&&(D=L.get(P.constructor)))return D(P,I);let T={};$.push(P),A.push(T);for(let U in P){let M=P[U];if(typeof M!=="object"||M===null)T[U]=M;else if(M.constructor!==Object&&(D=L.get(M.constructor)))T[U]=D(M,I);else if(ArrayBuffer.isView(M))T[U]=VD(M);else{let t=$.indexOf(M);if(t!==-1)T[U]=A[t];else T[U]=I(M)}}return $.pop(),A.pop(),T}}});var G1=p((sO,i1)=>{i1.exports=C1()()});var l1=p((a1)=>{Object.defineProperty(a1,"__esModule",{value:!0});a1.validateTopic=d1;a1.validateTopics=m4;function d1(H){let $=H.split("/");for(let A=0;A<$.length;A++){if($[A]==="+")continue;if($[A]==="#")return A===$.length-1;if($[A].indexOf("+")!==-1||$[A].indexOf("#")!==-1)return!1}return!0}function m4(H){if(H.length===0)return"empty_topic_list";for(let $=0;$<H.length;$++)if(!d1(H[$]))return H[$];return null}});var ET=p((b1)=>{Object.defineProperty(b1,"__esModule",{value:!0});var j4=HL(),J4={objectMode:!0},Q4={clean:!0};class y1{options;_inflights;constructor(H){this.options=H||{},this.options={...Q4,...H},this._inflights=new Map}put(H,$){if(this._inflights.set(H.messageId,H),$)$();return this}createStream(){let H=new j4.Readable(J4),$=[],A=!1,L=0;return this._inflights.forEach((D,f)=>{$.push(D)}),H._read=()=>{if(!A&&L<$.length)H.push($[L++]);else H.push(null)},H.destroy=(D)=>{if(A)return;return A=!0,setTimeout(()=>{H.emit("close")},0),H},H}del(H,$){let A=this._inflights.get(H.messageId);if(A)this._inflights.delete(H.messageId),$(null,A);else if($)$(Error("missing packet"));return this}get(H,$){let A=this._inflights.get(H.messageId);if(A)$(null,A);else if($)$(Error("missing packet"));return this}close(H){if(this.options.clean)this._inflights=null;if(H)H()}}b1.default=y1});var R1=p((k1)=>{Object.defineProperty(k1,"__esModule",{value:!0});var N1=[0,16,128,131,135,144,145,151,153],g4=(H,$,A)=>{H.log("handlePublish: packet %o",$),A=typeof A<"u"?A:H.noop;let L=$.topic.toString(),D=$.payload,{qos:f}=$,{messageId:E}=$,{options:I}=H;if(H.options.protocolVersion===5){let P;if($.properties)P=$.properties.topicAlias;if(typeof P<"u")if(L.length===0)if(P>0&&P<=65535){let T=H.topicAliasRecv.getTopicByAlias(P);if(T)L=T,H.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",L,P);else{H.log("handlePublish :: unregistered topic alias. alias: %d",P),H.emit("error",Error("Received unregistered Topic Alias"));return}}else{H.log("handlePublish :: topic alias out of range. alias: %d",P),H.emit("error",Error("Received Topic Alias is out of range"));return}else if(H.topicAliasRecv.put(L,P))H.log("handlePublish :: registered topic: %s - alias: %d",L,P);else{H.log("handlePublish :: topic alias out of range. alias: %d",P),H.emit("error",Error("Received Topic Alias is out of range"));return}}switch(H.log("handlePublish: qos %d",f),f){case 2:{I.customHandleAcks(L,D,$,(P,T)=>{if(typeof P==="number")T=P,P=null;if(P)return H.emit("error",P);if(N1.indexOf(T)===-1)return H.emit("error",Error("Wrong reason code for pubrec"));if(T)H._sendPacket({cmd:"pubrec",messageId:E,reasonCode:T},A);else H.incomingStore.put($,()=>{H._sendPacket({cmd:"pubrec",messageId:E},A)})});break}case 1:{I.customHandleAcks(L,D,$,(P,T)=>{if(typeof P==="number")T=P,P=null;if(P)return H.emit("error",P);if(N1.indexOf(T)===-1)return H.emit("error",Error("Wrong reason code for puback"));if(!T)H.emit("message",L,D,$);H.handleMessage($,(U)=>{if(U)return A&&A(U);H._sendPacket({cmd:"puback",messageId:E,reasonCode:T},A)})});break}case 0:H.emit("message",L,D,$),H.handleMessage($,A);break;default:H.log("handlePublish: unknown QoS. Doing nothing.");break}};k1.default=g4});var O1=p((dO,Y4)=>{Y4.exports={name:"mqtt",description:"A library for the MQTT protocol",version:"5.14.1",contributors:["Adam Rudd <adamvrr@gmail.com>","Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)","Siarhei Buntsevich <scarry0506@gmail.com> (https://github.com/scarry1992)","Yoseph Maguire <yomaguir@microsoft.com> (https://github.com/YoDaMa)","Daniel Lando <daniel.sorridi@gmail.com> (https://github.com/robertsLando)"],keywords:["mqtt","publish/subscribe","publish","subscribe"],license:"MIT",repository:{type:"git",url:"git://github.com/mqttjs/MQTT.js.git"},main:"./build/index.js",module:"./dist/mqtt.esm.js",bin:{mqtt_pub:"./build/bin/pub.js",mqtt_sub:"./build/bin/sub.js",mqtt:"./build/bin/mqtt.js"},files:["dist/","CONTRIBUTING.md","LICENSE.md","help/","build/"],exports:{".":{"react-native":"./dist/mqtt.esm.js",browser:{import:"./dist/mqtt.esm.js",default:"./dist/mqtt.min.js"},default:"./build/index.js"},"./package.json":"./package.json","./*.map":"./build/*.js.map","./dist/*":"./dist/*.js","./*":"./build/*.js"},types:"build/index.d.ts",typesVersions:{"*":{"*":["./build/index.d.ts"]}},scripts:{lint:"eslint --ext .ts .","lint-fix":"eslint --fix --ext .ts .","build:ts":"rimraf build/ && tsc -p tsconfig.build.json","build:browser":"node esbuild.js",build:"npm run build:ts && npm run build:browser",prepare:"npm run build","unit-test:node":"node -r esbuild-register --test-concurrency 4 --test-reporter=junit --test-reporter-destination=junit.xml --test-reporter=spec --test-reporter-destination=stdout --test test/node/*.ts ","unit-test:browser":"wtr","test:node":"node_modules/.bin/nyc npm run unit-test:node","test:browser":"npm run build && npm run unit-test:browser",test:"npm run test:node",changelog:"conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md","changelog-init":"conventional-changelog -p angular -i CHANGELOG.md -s -r 0",release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it"},"release-it":{github:{release:!0},git:{tagName:"v${version}",commitMessage:"chore(release): ${version}"},hooks:{"before:init":["npm run test"]},npm:{publish:!0},plugins:{"@release-it/conventional-changelog":{preset:"angular",infile:"CHANGELOG.md"}}},publishConfig:{provenance:!0},"pre-commit":["lint"],engines:{node:">=16.0.0"},browser:{"./mqtt.js":"./dist/mqtt.js",fs:!1,tls:!1,net:!1},dependencies:{"@types/readable-stream":"^4.0.21","@types/ws":"^8.18.1",commist:"^3.2.0","concat-stream":"^2.0.0",debug:"^4.4.1","help-me":"^5.0.0","lru-cache":"^10.4.3",minimist:"^1.2.8","mqtt-packet":"^9.0.2","number-allocator":"^1.0.14","readable-stream":"^4.7.0",rfdc:"^1.4.1",socks:"^2.8.6",split2:"^4.2.0","worker-timers":"^8.0.23",ws:"^8.18.3"},devDependencies:{"@eslint/eslintrc":"^3.3.1","@eslint/js":"^9.32.0","@esm-bundle/chai":"^4.3.4","@release-it/conventional-changelog":"^10.0.1","@tsconfig/node20":"^20.1.6","@types/chai":"^5.2.2","@types/node":"^20.17.16","@types/sinon":"^17.0.4","@types/tape":"^5.8.1","@typescript-eslint/eslint-plugin":"^8.38.0","@typescript-eslint/parser":"^8.38.0","@web/test-runner":"^0.20.2","@web/test-runner-playwright":"^0.11.1","aedes-cli":"^0.8.0",chai:"^5.2.1",chokidar:"^4.0.3","conventional-changelog-cli":"^5.0.0","end-of-stream":"^1.4.5",esbuild:"^0.25.8","esbuild-plugin-polyfill-node":"^0.3.0","esbuild-register":"^3.6.0",eslint:"^9.32.0","eslint-config-prettier":"^10.1.8","eslint-plugin-import":"^2.32.0","eslint-plugin-prettier":"^5.5.3",global:"^4.4.0",globals:"^16.3.0","leaked-handles":"^5.2.0",mkdirp:"^3.0.1","mqtt-connection":"^4.1.0","mqtt-level-store":"^3.1.0",nyc:"^17.1.0","pre-commit":"^1.2.2",prettier:"^3.6.2","release-it":"^19.0.4",rimraf:"^6.0.1",should:"^13.2.3",sinon:"^17.0.2",snazzy:"^9.0.0",tape:"^5.9.0","ts-node":"^10.9.2",typescript:"^5.8.3"}}});var aL=p((m1)=>{Object.defineProperty(m1,"__esModule",{value:!0});m1.MQTTJS_VERSION=m1.nextTick=m1.ErrorWithSubackPacket=m1.ErrorWithReasonCode=void 0;m1.applyMixin=q4;class IT extends Error{code;constructor(H,$){super(H);this.code=$,Object.setPrototypeOf(this,IT.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}m1.ErrorWithReasonCode=IT;class PT extends Error{packet;constructor(H,$){super(H);this.packet=$,Object.setPrototypeOf(this,PT.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}m1.ErrorWithSubackPacket=PT;function q4(H,$,A=!1){let L=[$];while(!0){let D=L[0],f=Object.getPrototypeOf(D);if(f?.prototype)L.unshift(f);else break}for(let D of L)for(let f of Object.getOwnPropertyNames(D.prototype))if(A||f!=="constructor")Object.defineProperty(H.prototype,f,Object.getOwnPropertyDescriptor(D.prototype,f)??Object.create(null))}m1.nextTick=typeof process?.nextTick==="function"?process.nextTick:(H)=>{setTimeout(H,0)};m1.MQTTJS_VERSION=O1().version});var If=p((j1)=>{Object.defineProperty(j1,"__esModule",{value:!0});j1.ReasonCodes=void 0;var e1=aL();j1.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var Ad=(H,$)=>{let{messageId:A}=$,L=$.cmd,D=null,f=H.outgoing[A]?H.outgoing[A].cb:null,E=null;if(!f){H.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(H.log("_handleAck :: packet type",L),L){case"pubcomp":case"puback":{let I=$.reasonCode;if(I&&I>0&&I!==16)E=new e1.ErrorWithReasonCode(`Publish error: ${j1.ReasonCodes[I]}`,I),H._removeOutgoingAndStoreMessage(A,()=>{f(E,$)});else H._removeOutgoingAndStoreMessage(A,f);break}case"pubrec":{D={cmd:"pubrel",qos:2,messageId:A};let I=$.reasonCode;if(I&&I>0&&I!==16)E=new e1.ErrorWithReasonCode(`Publish error: ${j1.ReasonCodes[I]}`,I),H._removeOutgoingAndStoreMessage(A,()=>{f(E,$)});else H._sendPacket(D);break}case"suback":{delete H.outgoing[A],H.messageIdProvider.deallocate(A);let I=$.granted;for(let P=0;P<I.length;P++){let T=I[P];if((T&128)!==0){E=Error(`Subscribe error: ${j1.ReasonCodes[T]}`),E.code=T;let U=H.messageIdToTopic[A];if(U)U.forEach((M)=>{delete H._resubscribeTopics[M]})}}delete H.messageIdToTopic[A],H._invokeStoreProcessingQueue(),f(E,$);break}case"unsuback":{delete H.outgoing[A],H.messageIdProvider.deallocate(A),H._invokeStoreProcessingQueue(),f(null,$);break}default:H.emit("error",Error("unrecognized packet type"))}if(H.disconnecting&&Object.keys(H.outgoing).length===0)H.emit("outgoingEmpty")};j1.default=Ad});var K1=p((Q1)=>{Object.defineProperty(Q1,"__esModule",{value:!0});var J1=aL(),Dd=If(),fd=(H,$)=>{let{options:A}=H,L=A.protocolVersion,D=L===5?$.reasonCode:$.returnCode;if(L!==5){let f=new J1.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${L}`,D);H.emit("error",f);return}H.handleAuth($,(f,E)=>{if(f){H.emit("error",f);return}if(D===24)H.reconnecting=!1,H._sendPacket(E);else{let I=new J1.ErrorWithReasonCode(`Connection refused: ${Dd.ReasonCodes[D]}`,D);H.emit("error",I)}})};Q1.default=fd});var Hu=p((Z1)=>{Object.defineProperty(Z1,"__esModule",{value:!0});Z1.LRUCache=void 0;var WD=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,v1=new Set,TT=typeof process==="object"&&!!process?process:{},Y1=(H,$,A,L)=>{typeof TT.emitWarning==="function"?TT.emitWarning(H,$,A,L):console.error(`[${A}] ${$}: ${H}`)},AE=globalThis.AbortController,g1=globalThis.AbortSignal;if(typeof AE>"u"){g1=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(L,D){this._onabort.push(D)}},AE=class{constructor(){$()}signal=new g1;abort(L){if(this.signal.aborted)return;this.signal.reason=L,this.signal.aborted=!0;for(let D of this.signal._onabort)D(L);this.signal.onabort?.(L)}};let H=TT.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",$=()=>{if(!H)return;H=!1,Y1("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",$)}}var Id=(H)=>!v1.has(H),bO=Symbol("type"),fL=(H)=>H&&H===Math.floor(H)&&H>0&&isFinite(H),q1=(H)=>!fL(H)?null:H<=Math.pow(2,8)?Uint8Array:H<=Math.pow(2,16)?Uint16Array:H<=Math.pow(2,32)?Uint32Array:H<=Number.MAX_SAFE_INTEGER?Pf:null;class Pf extends Array{constructor(H){super(H);this.fill(0)}}class uD{heap;length;static#f=!1;static create(H){let $=q1(H);if(!$)return[];uD.#f=!0;let A=new uD(H,$);return uD.#f=!1,A}constructor(H,$){if(!uD.#f)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new $(H),this.length=0}push(H){this.heap[this.length++]=H}pop(){return this.heap[--this.length]}}class UT{#f;#D;#T;#U;#V;#h;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#A;#p;#E;#L;#H;#t;#W;#M;#I;#c;#P;#X;#S;#u;#r;#s;#_;static unsafeExposeInternals(H){return{starts:H.#S,ttls:H.#u,sizes:H.#X,keyMap:H.#E,keyList:H.#L,valList:H.#H,next:H.#t,prev:H.#W,get head(){return H.#M},get tail(){return H.#I},free:H.#c,isBackgroundFetch:($)=>H.#$($),backgroundFetch:($,A,L,D)=>H.#l($,A,L,D),moveToTail:($)=>H.#G($),indexes:($)=>H.#B($),rindexes:($)=>H.#n($),isStale:($)=>H.#x($)}}get max(){return this.#f}get maxSize(){return this.#D}get calculatedSize(){return this.#p}get size(){return this.#A}get fetchMethod(){return this.#V}get memoMethod(){return this.#h}get dispose(){return this.#T}get disposeAfter(){return this.#U}constructor(H){let{max:$=0,ttl:A,ttlResolution:L=1,ttlAutopurge:D,updateAgeOnGet:f,updateAgeOnHas:E,allowStale:I,dispose:P,disposeAfter:T,noDisposeOnSet:U,noUpdateTTL:M,maxSize:t=0,maxEntrySize:_=0,sizeCalculation:x,fetchMethod:V,memoMethod:h,noDeleteOnFetchRejection:W,noDeleteOnStaleGet:c,allowStaleOnFetchRejection:r,allowStaleOnFetchAbort:F,ignoreFetchAbort:N}=H;if($!==0&&!fL($))throw TypeError("max option must be a nonnegative integer");let y=$?q1($):Array;if(!y)throw Error("invalid max value: "+$);if(this.#f=$,this.#D=t,this.maxEntrySize=_||this.#D,this.sizeCalculation=x,this.sizeCalculation){if(!this.#D&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(h!==void 0&&typeof h!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#h=h,V!==void 0&&typeof V!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#V=V,this.#s=!!V,this.#E=new Map,this.#L=Array($).fill(void 0),this.#H=Array($).fill(void 0),this.#t=new y($),this.#W=new y($),this.#M=0,this.#I=0,this.#c=uD.create($),this.#A=0,this.#p=0,typeof P==="function")this.#T=P;if(typeof T==="function")this.#U=T,this.#P=[];else this.#U=void 0,this.#P=void 0;if(this.#r=!!this.#T,this.#_=!!this.#U,this.noDisposeOnSet=!!U,this.noUpdateTTL=!!M,this.noDeleteOnFetchRejection=!!W,this.allowStaleOnFetchRejection=!!r,this.allowStaleOnFetchAbort=!!F,this.ignoreFetchAbort=!!N,this.maxEntrySize!==0){if(this.#D!==0){if(!fL(this.#D))throw TypeError("maxSize must be a positive integer if specified")}if(!fL(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#m()}if(this.allowStale=!!I,this.noDeleteOnStaleGet=!!c,this.updateAgeOnGet=!!f,this.updateAgeOnHas=!!E,this.ttlResolution=fL(L)||L===0?L:1,this.ttlAutopurge=!!D,this.ttl=A||0,this.ttl){if(!fL(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#y()}if(this.#f===0&&this.ttl===0&&this.#D===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#f&&!this.#D){if(Id("LRU_CACHE_UNBOUNDED"))v1.add("LRU_CACHE_UNBOUNDED"),Y1("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",UT)}}getRemainingTTL(H){return this.#E.has(H)?1/0:0}#y(){let H=new Pf(this.#f),$=new Pf(this.#f);this.#u=H,this.#S=$,this.#b=(D,f,E=WD.now())=>{if($[D]=f!==0?E:0,H[D]=f,f!==0&&this.ttlAutopurge){let I=setTimeout(()=>{if(this.#x(D))this.#o(this.#L[D],"expire")},f+1);if(I.unref)I.unref()}},this.#C=(D)=>{$[D]=H[D]!==0?WD.now():0},this.#F=(D,f)=>{if(H[f]){let E=H[f],I=$[f];if(!E||!I)return;D.ttl=E,D.start=I,D.now=A||L();let P=D.now-I;D.remainingTTL=E-P}};let A=0,L=()=>{let D=WD.now();if(this.ttlResolution>0){A=D;let f=setTimeout(()=>A=0,this.ttlResolution);if(f.unref)f.unref()}return D};this.getRemainingTTL=(D)=>{let f=this.#E.get(D);if(f===void 0)return 0;let E=H[f],I=$[f];if(!E||!I)return 1/0;let P=(A||L())-I;return E-P},this.#x=(D)=>{let f=$[D],E=H[D];return!!E&&!!f&&(A||L())-f>E}}#C=()=>{};#F=()=>{};#b=()=>{};#x=()=>!1;#m(){let H=new Pf(this.#f);this.#p=0,this.#X=H,this.#i=($)=>{this.#p-=H[$],H[$]=0},this.#N=($,A,L,D)=>{if(this.#$(A))return 0;if(!fL(L))if(D){if(typeof D!=="function")throw TypeError("sizeCalculation must be a function");if(L=D(A,$),!fL(L))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return L},this.#d=($,A,L)=>{if(H[$]=A,this.#D){let D=this.#D-H[$];while(this.#p>D)this.#a(!0)}if(this.#p+=H[$],L)L.entrySize=A,L.totalCalculatedSize=this.#p}}#i=(H)=>{};#d=(H,$,A)=>{};#N=(H,$,A,L)=>{if(A||L)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#B({allowStale:H=this.allowStale}={}){if(this.#A)for(let $=this.#I;;){if(!this.#k($))break;if(H||!this.#x($))yield $;if($===this.#M)break;else $=this.#W[$]}}*#n({allowStale:H=this.allowStale}={}){if(this.#A)for(let $=this.#M;;){if(!this.#k($))break;if(H||!this.#x($))yield $;if($===this.#I)break;else $=this.#t[$]}}#k(H){return H!==void 0&&this.#E.get(this.#L[H])===H}*entries(){for(let H of this.#B())if(this.#H[H]!==void 0&&this.#L[H]!==void 0&&!this.#$(this.#H[H]))yield[this.#L[H],this.#H[H]]}*rentries(){for(let H of this.#n())if(this.#H[H]!==void 0&&this.#L[H]!==void 0&&!this.#$(this.#H[H]))yield[this.#L[H],this.#H[H]]}*keys(){for(let H of this.#B()){let $=this.#L[H];if($!==void 0&&!this.#$(this.#H[H]))yield $}}*rkeys(){for(let H of this.#n()){let $=this.#L[H];if($!==void 0&&!this.#$(this.#H[H]))yield $}}*values(){for(let H of this.#B())if(this.#H[H]!==void 0&&!this.#$(this.#H[H]))yield this.#H[H]}*rvalues(){for(let H of this.#n())if(this.#H[H]!==void 0&&!this.#$(this.#H[H]))yield this.#H[H]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(H,$={}){for(let A of this.#B()){let L=this.#H[A],D=this.#$(L)?L.__staleWhileFetching:L;if(D===void 0)continue;if(H(D,this.#L[A],this))return this.get(this.#L[A],$)}}forEach(H,$=this){for(let A of this.#B()){let L=this.#H[A],D=this.#$(L)?L.__staleWhileFetching:L;if(D===void 0)continue;H.call($,D,this.#L[A],this)}}rforEach(H,$=this){for(let A of this.#n()){let L=this.#H[A],D=this.#$(L)?L.__staleWhileFetching:L;if(D===void 0)continue;H.call($,D,this.#L[A],this)}}purgeStale(){let H=!1;for(let $ of this.#n({allowStale:!0}))if(this.#x($))this.#o(this.#L[$],"expire"),H=!0;return H}info(H){let $=this.#E.get(H);if($===void 0)return;let A=this.#H[$],L=this.#$(A)?A.__staleWhileFetching:A;if(L===void 0)return;let D={value:L};if(this.#u&&this.#S){let f=this.#u[$],E=this.#S[$];if(f&&E){let I=f-(WD.now()-E);D.ttl=I,D.start=Date.now()}}if(this.#X)D.size=this.#X[$];return D}dump(){let H=[];for(let $ of this.#B({allowStale:!0})){let A=this.#L[$],L=this.#H[$],D=this.#$(L)?L.__staleWhileFetching:L;if(D===void 0||A===void 0)continue;let f={value:D};if(this.#u&&this.#S){f.ttl=this.#u[$];let E=WD.now()-this.#S[$];f.start=Math.floor(Date.now()-E)}if(this.#X)f.size=this.#X[$];H.unshift([A,f])}return H}load(H){this.clear();for(let[$,A]of H){if(A.start){let L=Date.now()-A.start;A.start=WD.now()-L}this.set($,A.value,A)}}set(H,$,A={}){if($===void 0)return this.delete(H),this;let{ttl:L=this.ttl,start:D,noDisposeOnSet:f=this.noDisposeOnSet,sizeCalculation:E=this.sizeCalculation,status:I}=A,{noUpdateTTL:P=this.noUpdateTTL}=A,T=this.#N(H,$,A.size||0,E);if(this.maxEntrySize&&T>this.maxEntrySize){if(I)I.set="miss",I.maxEntrySizeExceeded=!0;return this.#o(H,"set"),this}let U=this.#A===0?void 0:this.#E.get(H);if(U===void 0){if(U=this.#A===0?this.#I:this.#c.length!==0?this.#c.pop():this.#A===this.#f?this.#a(!1):this.#A,this.#L[U]=H,this.#H[U]=$,this.#E.set(H,U),this.#t[this.#I]=U,this.#W[U]=this.#I,this.#I=U,this.#A++,this.#d(U,T,I),I)I.set="add";P=!1}else{this.#G(U);let M=this.#H[U];if($!==M){if(this.#s&&this.#$(M)){M.__abortController.abort(Error("replaced"));let{__staleWhileFetching:t}=M;if(t!==void 0&&!f){if(this.#r)this.#T?.(t,H,"set");if(this.#_)this.#P?.push([t,H,"set"])}}else if(!f){if(this.#r)this.#T?.(M,H,"set");if(this.#_)this.#P?.push([M,H,"set"])}if(this.#i(U),this.#d(U,T,I),this.#H[U]=$,I){I.set="replace";let t=M&&this.#$(M)?M.__staleWhileFetching:M;if(t!==void 0)I.oldValue=t}}else if(I)I.set="update"}if(L!==0&&!this.#u)this.#y();if(this.#u){if(!P)this.#b(U,L,D);if(I)this.#F(I,U)}if(!f&&this.#_&&this.#P){let M=this.#P,t;while(t=M?.shift())this.#U?.(...t)}return this}pop(){try{while(this.#A){let H=this.#H[this.#M];if(this.#a(!0),this.#$(H)){if(H.__staleWhileFetching)return H.__staleWhileFetching}else if(H!==void 0)return H}}finally{if(this.#_&&this.#P){let H=this.#P,$;while($=H?.shift())this.#U?.(...$)}}}#a(H){let $=this.#M,A=this.#L[$],L=this.#H[$];if(this.#s&&this.#$(L))L.__abortController.abort(Error("evicted"));else if(this.#r||this.#_){if(this.#r)this.#T?.(L,A,"evict");if(this.#_)this.#P?.push([L,A,"evict"])}if(this.#i($),H)this.#L[$]=void 0,this.#H[$]=void 0,this.#c.push($);if(this.#A===1)this.#M=this.#I=0,this.#c.length=0;else this.#M=this.#t[$];return this.#E.delete(A),this.#A--,$}has(H,$={}){let{updateAgeOnHas:A=this.updateAgeOnHas,status:L}=$,D=this.#E.get(H);if(D!==void 0){let f=this.#H[D];if(this.#$(f)&&f.__staleWhileFetching===void 0)return!1;if(!this.#x(D)){if(A)this.#C(D);if(L)L.has="hit",this.#F(L,D);return!0}else if(L)L.has="stale",this.#F(L,D)}else if(L)L.has="miss";return!1}peek(H,$={}){let{allowStale:A=this.allowStale}=$,L=this.#E.get(H);if(L===void 0||!A&&this.#x(L))return;let D=this.#H[L];return this.#$(D)?D.__staleWhileFetching:D}#l(H,$,A,L){let D=$===void 0?void 0:this.#H[$];if(this.#$(D))return D;let f=new AE,{signal:E}=A;E?.addEventListener("abort",()=>f.abort(E.reason),{signal:f.signal});let I={signal:f.signal,options:A,context:L},P=(x,V=!1)=>{let{aborted:h}=f.signal,W=A.ignoreFetchAbort&&x!==void 0;if(A.status)if(h&&!V){if(A.status.fetchAborted=!0,A.status.fetchError=f.signal.reason,W)A.status.fetchAbortIgnored=!0}else A.status.fetchResolved=!0;if(h&&!W&&!V)return U(f.signal.reason);let c=t;if(this.#H[$]===t)if(x===void 0)if(c.__staleWhileFetching)this.#H[$]=c.__staleWhileFetching;else this.#o(H,"fetch");else{if(A.status)A.status.fetchUpdated=!0;this.set(H,x,I.options)}return x},T=(x)=>{if(A.status)A.status.fetchRejected=!0,A.status.fetchError=x;return U(x)},U=(x)=>{let{aborted:V}=f.signal,h=V&&A.allowStaleOnFetchAbort,W=h||A.allowStaleOnFetchRejection,c=W||A.noDeleteOnFetchRejection,r=t;if(this.#H[$]===t){if(!c||r.__staleWhileFetching===void 0)this.#o(H,"fetch");else if(!h)this.#H[$]=r.__staleWhileFetching}if(W){if(A.status&&r.__staleWhileFetching!==void 0)A.status.returnedStale=!0;return r.__staleWhileFetching}else if(r.__returned===r)throw x},M=(x,V)=>{let h=this.#V?.(H,D,I);if(h&&h instanceof Promise)h.then((W)=>x(W===void 0?void 0:W),V);f.signal.addEventListener("abort",()=>{if(!A.ignoreFetchAbort||A.allowStaleOnFetchAbort){if(x(void 0),A.allowStaleOnFetchAbort)x=(W)=>P(W,!0)}})};if(A.status)A.status.fetchDispatched=!0;let t=new Promise(M).then(P,T),_=Object.assign(t,{__abortController:f,__staleWhileFetching:D,__returned:void 0});if($===void 0)this.set(H,_,{...I.options,status:void 0}),$=this.#E.get(H);else this.#H[$]=_;return _}#$(H){if(!this.#s)return!1;let $=H;return!!$&&$ instanceof Promise&&$.hasOwnProperty("__staleWhileFetching")&&$.__abortController instanceof AE}async fetch(H,$={}){let{allowStale:A=this.allowStale,updateAgeOnGet:L=this.updateAgeOnGet,noDeleteOnStaleGet:D=this.noDeleteOnStaleGet,ttl:f=this.ttl,noDisposeOnSet:E=this.noDisposeOnSet,size:I=0,sizeCalculation:P=this.sizeCalculation,noUpdateTTL:T=this.noUpdateTTL,noDeleteOnFetchRejection:U=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:M=this.allowStaleOnFetchRejection,ignoreFetchAbort:t=this.ignoreFetchAbort,allowStaleOnFetchAbort:_=this.allowStaleOnFetchAbort,context:x,forceRefresh:V=!1,status:h,signal:W}=$;if(!this.#s){if(h)h.fetch="get";return this.get(H,{allowStale:A,updateAgeOnGet:L,noDeleteOnStaleGet:D,status:h})}let c={allowStale:A,updateAgeOnGet:L,noDeleteOnStaleGet:D,ttl:f,noDisposeOnSet:E,size:I,sizeCalculation:P,noUpdateTTL:T,noDeleteOnFetchRejection:U,allowStaleOnFetchRejection:M,allowStaleOnFetchAbort:_,ignoreFetchAbort:t,status:h,signal:W},r=this.#E.get(H);if(r===void 0){if(h)h.fetch="miss";let F=this.#l(H,r,c,x);return F.__returned=F}else{let F=this.#H[r];if(this.#$(F)){let e=A&&F.__staleWhileFetching!==void 0;if(h){if(h.fetch="inflight",e)h.returnedStale=!0}return e?F.__staleWhileFetching:F.__returned=F}let N=this.#x(r);if(!V&&!N){if(h)h.fetch="hit";if(this.#G(r),L)this.#C(r);if(h)this.#F(h,r);return F}let y=this.#l(H,r,c,x),J=y.__staleWhileFetching!==void 0&&A;if(h){if(h.fetch=N?"stale":"refresh",J&&N)h.returnedStale=!0}return J?y.__staleWhileFetching:y.__returned=y}}async forceFetch(H,$={}){let A=await this.fetch(H,$);if(A===void 0)throw Error("fetch() returned undefined");return A}memo(H,$={}){let A=this.#h;if(!A)throw Error("no memoMethod provided to constructor");let{context:L,forceRefresh:D,...f}=$,E=this.get(H,f);if(!D&&E!==void 0)return E;let I=A(H,E,{options:f,context:L});return this.set(H,I,f),I}get(H,$={}){let{allowStale:A=this.allowStale,updateAgeOnGet:L=this.updateAgeOnGet,noDeleteOnStaleGet:D=this.noDeleteOnStaleGet,status:f}=$,E=this.#E.get(H);if(E!==void 0){let I=this.#H[E],P=this.#$(I);if(f)this.#F(f,E);if(this.#x(E)){if(f)f.get="stale";if(!P){if(!D)this.#o(H,"expire");if(f&&A)f.returnedStale=!0;return A?I:void 0}else{if(f&&A&&I.__staleWhileFetching!==void 0)f.returnedStale=!0;return A?I.__staleWhileFetching:void 0}}else{if(f)f.get="hit";if(P)return I.__staleWhileFetching;if(this.#G(E),L)this.#C(E);return I}}else if(f)f.get="miss"}#R(H,$){this.#W[$]=H,this.#t[H]=$}#G(H){if(H!==this.#I){if(H===this.#M)this.#M=this.#t[H];else this.#R(this.#W[H],this.#t[H]);this.#R(this.#I,H),this.#I=H}}delete(H){return this.#o(H,"delete")}#o(H,$){let A=!1;if(this.#A!==0){let L=this.#E.get(H);if(L!==void 0)if(A=!0,this.#A===1)this.#O($);else{this.#i(L);let D=this.#H[L];if(this.#$(D))D.__abortController.abort(Error("deleted"));else if(this.#r||this.#_){if(this.#r)this.#T?.(D,H,$);if(this.#_)this.#P?.push([D,H,$])}if(this.#E.delete(H),this.#L[L]=void 0,this.#H[L]=void 0,L===this.#I)this.#I=this.#W[L];else if(L===this.#M)this.#M=this.#t[L];else{let f=this.#W[L];this.#t[f]=this.#t[L];let E=this.#t[L];this.#W[E]=this.#W[L]}this.#A--,this.#c.push(L)}}if(this.#_&&this.#P?.length){let L=this.#P,D;while(D=L?.shift())this.#U?.(...D)}return A}clear(){return this.#O("delete")}#O(H){for(let $ of this.#n({allowStale:!0})){let A=this.#H[$];if(this.#$(A))A.__abortController.abort(Error("deleted"));else{let L=this.#L[$];if(this.#r)this.#T?.(A,L,H);if(this.#_)this.#P?.push([A,L,H])}}if(this.#E.clear(),this.#H.fill(void 0),this.#L.fill(void 0),this.#u&&this.#S)this.#u.fill(0),this.#S.fill(0);if(this.#X)this.#X.fill(0);if(this.#M=0,this.#I=0,this.#c.length=0,this.#p=0,this.#A=0,this.#_&&this.#P){let $=this.#P,A;while(A=$?.shift())this.#U?.(...A)}}}Z1.LRUCache=UT});var WA=p((Lu)=>{Object.defineProperty(Lu,"t",{value:!0});Lu.ContainerIterator=Lu.Container=Lu.Base=void 0;class $u{constructor(H=0){this.iteratorType=H}equals(H){return this.o===H.o}}Lu.ContainerIterator=$u;class MT{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}}Lu.Base=MT;class Au extends MT{}Lu.Container=Au});var Pu=p((Eu)=>{Object.defineProperty(Eu,"t",{value:!0});Eu.default=void 0;var Ud=WA();class fu extends Ud.Base{constructor(H=[]){super();this.S=[];let $=this;H.forEach(function(A){$.push(A)})}clear(){this.i=0,this.S=[]}push(H){return this.S.push(H),this.i+=1,this.i}pop(){if(this.i===0)return;return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}}var Md=fu;Eu.default=Md});var tu=p((Uu)=>{Object.defineProperty(Uu,"t",{value:!0});Uu.default=void 0;var td=WA();class Tu extends td.Base{constructor(H=[]){super();this.j=0,this.q=[];let $=this;H.forEach(function(A){$.push(A)})}clear(){this.q=[],this.i=this.j=0}push(H){let $=this.q.length;if(this.j/$>0.5&&this.j+this.i>=$&&$>4096){let A=this.i;for(let L=0;L<A;++L)this.q[L]=this.q[this.j+L];this.j=0,this.q[this.i]=H}else this.q[this.j+this.i]=H;return++this.i}pop(){if(this.i===0)return;let H=this.q[this.j++];return this.i-=1,H}front(){if(this.i===0)return;return this.q[this.j]}}var _d=Tu;Uu.default=_d});var Wu=p((pu)=>{Object.defineProperty(pu,"t",{value:!0});pu.default=void 0;var pd=WA();class _u extends pd.Base{constructor(H=[],$=function(L,D){if(L>D)return-1;if(L<D)return 1;return 0},A=!0){super();if(this.v=$,Array.isArray(H))this.C=A?[...H]:H;else{this.C=[];let D=this;H.forEach(function(f){D.C.push(f)})}this.i=this.C.length;let L=this.i>>1;for(let D=this.i-1>>1;D>=0;--D)this.k(D,L)}m(H){let $=this.C[H];while(H>0){let A=H-1>>1,L=this.C[A];if(this.v(L,$)<=0)break;this.C[H]=L,H=A}this.C[H]=$}k(H,$){let A=this.C[H];while(H<$){let L=H<<1|1,D=L+1,f=this.C[L];if(D<this.i&&this.v(f,this.C[D])>0)L=D,f=this.C[D];if(this.v(f,A)>=0)break;this.C[H]=f,H=L}this.C[H]=A}clear(){this.i=0,this.C.length=0}push(H){this.C.push(H),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let H=this.C[0],$=this.C.pop();if(this.i-=1,this.i)this.C[0]=$,this.k(0,this.i>>1);return H}top(){return this.C[0]}find(H){return this.C.indexOf(H)>=0}remove(H){let $=this.C.indexOf(H);if($<0)return!1;if($===0)this.pop();else if($===this.i-1)this.C.pop(),this.i-=1;else this.C.splice($,1,this.C.pop()),this.i-=1,this.m($),this.k($,this.i>>1);return!0}updateItem(H){let $=this.C.indexOf(H);if($<0)return!1;return this.m($),this.k($,this.i>>1),!0}toArray(){return[...this.C]}}var Vd=_u;pu.default=Vd});var LE=p((xu)=>{Object.defineProperty(xu,"t",{value:!0});xu.default=void 0;var Wd=WA();class uu extends Wd.Container{}var ud=uu;xu.default=ud});var uA=p((cu)=>{Object.defineProperty(cu,"t",{value:!0});cu.throwIteratorAccessError=xd;function xd(){throw RangeError("Iterator access denied!")}});var tT=p((Su)=>{Object.defineProperty(Su,"t",{value:!0});Su.RandomIterator=void 0;var cd=WA(),DE=uA();class Xu extends cd.ContainerIterator{constructor(H,$){super($);if(this.o=H,this.iteratorType===0)this.pre=function(){if(this.o===0)(0,DE.throwIteratorAccessError)();return this.o-=1,this},this.next=function(){if(this.o===this.container.size())(0,DE.throwIteratorAccessError)();return this.o+=1,this};else this.pre=function(){if(this.o===this.container.size()-1)(0,DE.throwIteratorAccessError)();return this.o+=1,this},this.next=function(){if(this.o===-1)(0,DE.throwIteratorAccessError)();return this.o-=1,this}}get pointer(){return this.container.getElementByPos(this.o)}set pointer(H){this.container.setElementByPos(this.o,H)}}Su.RandomIterator=Xu});var Fu=p((nu)=>{Object.defineProperty(nu,"t",{value:!0});nu.default=void 0;var Xd=rd(LE()),Sd=tT();function rd(H){return H&&H.t?H:{default:H}}class lL extends Sd.RandomIterator{constructor(H,$,A){super(H,A);this.container=$}copy(){return new lL(this.o,this.container,this.iteratorType)}}class Bu extends Xd.default{constructor(H=[],$=!0){super();if(Array.isArray(H))this.J=$?[...H]:H,this.i=H.length;else{this.J=[];let A=this;H.forEach(function(L){A.pushBack(L)})}}clear(){this.i=0,this.J.length=0}begin(){return new lL(0,this)}end(){return new lL(this.i,this)}rBegin(){return new lL(this.i-1,this,1)}rEnd(){return new lL(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(H){if(H<0||H>this.i-1)throw RangeError();return this.J[H]}eraseElementByPos(H){if(H<0||H>this.i-1)throw RangeError();return this.J.splice(H,1),this.i-=1,this.i}eraseElementByValue(H){let $=0;for(let A=0;A<this.i;++A)if(this.J[A]!==H)this.J[$++]=this.J[A];return this.i=this.J.length=$,this.i}eraseElementByIterator(H){let $=H.o;return H=H.next(),this.eraseElementByPos($),H}pushBack(H){return this.J.push(H),this.i+=1,this.i}popBack(){if(this.i===0)return;return this.i-=1,this.J.pop()}setElementByPos(H,$){if(H<0||H>this.i-1)throw RangeError();this.J[H]=$}insert(H,$,A=1){if(H<0||H>this.i)throw RangeError();return this.J.splice(H,0,...Array(A).fill($)),this.i+=A,this.i}find(H){for(let $=0;$<this.i;++$)if(this.J[$]===H)return new lL($,this);return this.end()}reverse(){this.J.reverse()}unique(){let H=1;for(let $=1;$<this.i;++$)if(this.J[$]!==this.J[$-1])this.J[H++]=this.J[$];return this.i=this.J.length=H,this.i}sort(H){this.J.sort(H)}forEach(H){for(let $=0;$<this.i;++$)H(this.J[$],$,this)}[Symbol.iterator](){return function*(){yield*this.J}.bind(this)()}}var Bd=Bu;nu.default=Bd});var Gu=p((Cu)=>{Object.defineProperty(Cu,"t",{value:!0});Cu.default=void 0;var nd=Fd(LE()),od=WA(),yL=uA();function Fd(H){return H&&H.t?H:{default:H}}class bL extends od.ContainerIterator{constructor(H,$,A,L){super(L);if(this.o=H,this.h=$,this.container=A,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,yL.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,yL.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,yL.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,yL.throwIteratorAccessError)();return this.o=this.o.L,this}}get pointer(){if(this.o===this.h)(0,yL.throwIteratorAccessError)();return this.o.l}set pointer(H){if(this.o===this.h)(0,yL.throwIteratorAccessError)();this.o.l=H}copy(){return new bL(this.o,this.h,this.container,this.iteratorType)}}class su extends nd.default{constructor(H=[]){super();this.h={},this.p=this._=this.h.L=this.h.B=this.h;let $=this;H.forEach(function(A){$.pushBack(A)})}V(H){let{L:$,B:A}=H;if($.B=A,A.L=$,H===this.p)this.p=A;if(H===this._)this._=$;this.i-=1}G(H,$){let A=$.B,L={l:H,L:$,B:A};if($.B=L,A.L=L,$===this.h)this.p=L;if(A===this.h)this._=L;this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new bL(this.p,this.h,this)}end(){return new bL(this.h,this.h,this)}rBegin(){return new bL(this._,this.h,this,1)}rEnd(){return new bL(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(H){if(H<0||H>this.i-1)throw RangeError();let $=this.p;while(H--)$=$.B;return $.l}eraseElementByPos(H){if(H<0||H>this.i-1)throw RangeError();let $=this.p;while(H--)$=$.B;return this.V($),this.i}eraseElementByValue(H){let $=this.p;while($!==this.h){if($.l===H)this.V($);$=$.B}return this.i}eraseElementByIterator(H){let $=H.o;if($===this.h)(0,yL.throwIteratorAccessError)();return H=H.next(),this.V($),H}pushBack(H){return this.G(H,this._),this.i}popBack(){if(this.i===0)return;let H=this._.l;return this.V(this._),H}pushFront(H){return this.G(H,this.h),this.i}popFront(){if(this.i===0)return;let H=this.p.l;return this.V(this.p),H}setElementByPos(H,$){if(H<0||H>this.i-1)throw RangeError();let A=this.p;while(H--)A=A.B;A.l=$}insert(H,$,A=1){if(H<0||H>this.i)throw RangeError();if(A<=0)return this.i;if(H===0)while(A--)this.pushFront($);else if(H===this.i)while(A--)this.pushBack($);else{let L=this.p;for(let f=1;f<H;++f)L=L.B;let D=L.B;this.i+=A;while(A--)L.B={l:$,L},L.B.L=L,L=L.B;L.B=D,D.L=L}return this.i}find(H){let $=this.p;while($!==this.h){if($.l===H)return new bL($,this.h,this);$=$.B}return this.end()}reverse(){if(this.i<=1)return;let H=this.p,$=this._,A=0;while(A<<1<this.i){let L=H.l;H.l=$.l,$.l=L,H=H.B,$=$.L,A+=1}}unique(){if(this.i<=1)return this.i;let H=this.p;while(H!==this.h){let $=H;while($.B!==this.h&&$.l===$.B.l)$=$.B,this.i-=1;H.B=$.B,H.B.L=H,H=H.B}return this.i}sort(H){if(this.i<=1)return;let $=[];this.forEach(function(L){$.push(L)}),$.sort(H);let A=this.p;$.forEach(function(L){A.l=L,A=A.B})}merge(H){let $=this;if(this.i===0)H.forEach(function(A){$.pushBack(A)});else{let A=this.p;H.forEach(function(L){while(A!==$.h&&A.l<=L)A=A.B;$.G(L,A.L)})}return this.i}forEach(H){let $=this.p,A=0;while($!==this.h)H($.l,A++,this),$=$.B}[Symbol.iterator](){return function*(){if(this.i===0)return;let H=this.p;while(H!==this.h)yield H.l,H=H.B}.bind(this)()}}var sd=su;Cu.default=sd});var yu=p((au)=>{Object.defineProperty(au,"t",{value:!0});au.default=void 0;var Cd=Gd(LE()),id=tT();function Gd(H){return H&&H.t?H:{default:H}}class NL extends id.RandomIterator{constructor(H,$,A){super(H,A);this.container=$}copy(){return new NL(this.o,this.container,this.iteratorType)}}class du extends Cd.default{constructor(H=[],$=4096){super();this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let A=(()=>{if(typeof H.length==="number")return H.length;if(typeof H.size==="number")return H.size;if(typeof H.size==="function")return H.size();throw TypeError("Cannot get the length or size of the container")})();this.F=$,this.P=Math.max(Math.ceil(A/this.F),1);for(let f=0;f<this.P;++f)this.A.push(Array(this.F));let L=Math.ceil(A/this.F);this.j=this.R=(this.P>>1)-(L>>1),this.D=this.N=this.F-A%this.F>>1;let D=this;H.forEach(function(f){D.pushBack(f)})}T(){let H=[],$=Math.max(this.P>>1,1);for(let A=0;A<$;++A)H[A]=Array(this.F);for(let A=this.j;A<this.P;++A)H[H.length]=this.A[A];for(let A=0;A<this.R;++A)H[H.length]=this.A[A];H[H.length]=[...this.A[this.R]],this.j=$,this.R=H.length-1;for(let A=0;A<$;++A)H[H.length]=Array(this.F);this.A=H,this.P=H.length}O(H){let $=this.D+H+1,A=$%this.F,L=A-1,D=this.j+($-A)/this.F;if(A===0)D-=1;if(D%=this.P,L<0)L+=this.F;return{curNodeBucketIndex:D,curNodePointerIndex:L}}clear(){this.A=[Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new NL(0,this)}end(){return new NL(this.i,this)}rBegin(){return new NL(this.i-1,this,1)}rEnd(){return new NL(-1,this,1)}front(){if(this.i===0)return;return this.A[this.j][this.D]}back(){if(this.i===0)return;return this.A[this.R][this.N]}pushBack(H){if(this.i){if(this.N<this.F-1)this.N+=1;else if(this.R<this.P-1)this.R+=1,this.N=0;else this.R=0,this.N=0;if(this.R===this.j&&this.N===this.D)this.T()}return this.i+=1,this.A[this.R][this.N]=H,this.i}popBack(){if(this.i===0)return;let H=this.A[this.R][this.N];if(this.i!==1)if(this.N>0)this.N-=1;else if(this.R>0)this.R-=1,this.N=this.F-1;else this.R=this.P-1,this.N=this.F-1;return this.i-=1,H}pushFront(H){if(this.i){if(this.D>0)this.D-=1;else if(this.j>0)this.j-=1,this.D=this.F-1;else this.j=this.P-1,this.D=this.F-1;if(this.j===this.R&&this.D===this.N)this.T()}return this.i+=1,this.A[this.j][this.D]=H,this.i}popFront(){if(this.i===0)return;let H=this.A[this.j][this.D];if(this.i!==1)if(this.D<this.F-1)this.D+=1;else if(this.j<this.P-1)this.j+=1,this.D=0;else this.j=0,this.D=0;return this.i-=1,H}getElementByPos(H){if(H<0||H>this.i-1)throw RangeError();let{curNodeBucketIndex:$,curNodePointerIndex:A}=this.O(H);return this.A[$][A]}setElementByPos(H,$){if(H<0||H>this.i-1)throw RangeError();let{curNodeBucketIndex:A,curNodePointerIndex:L}=this.O(H);this.A[A][L]=$}insert(H,$,A=1){if(H<0||H>this.i)throw RangeError();if(H===0)while(A--)this.pushFront($);else if(H===this.i)while(A--)this.pushBack($);else{let L=[];for(let D=H;D<this.i;++D)L.push(this.getElementByPos(D));this.cut(H-1);for(let D=0;D<A;++D)this.pushBack($);for(let D=0;D<L.length;++D)this.pushBack(L[D])}return this.i}cut(H){if(H<0)return this.clear(),0;let{curNodeBucketIndex:$,curNodePointerIndex:A}=this.O(H);return this.R=$,this.N=A,this.i=H+1,this.i}eraseElementByPos(H){if(H<0||H>this.i-1)throw RangeError();if(H===0)this.popFront();else if(H===this.i-1)this.popBack();else{let $=[];for(let L=H+1;L<this.i;++L)$.push(this.getElementByPos(L));this.cut(H),this.popBack();let A=this;$.forEach(function(L){A.pushBack(L)})}return this.i}eraseElementByValue(H){if(this.i===0)return 0;let $=[];for(let L=0;L<this.i;++L){let D=this.getElementByPos(L);if(D!==H)$.push(D)}let A=$.length;for(let L=0;L<A;++L)this.setElementByPos(L,$[L]);return this.cut(A-1)}eraseElementByIterator(H){let $=H.o;return this.eraseElementByPos($),H=H.next(),H}find(H){for(let $=0;$<this.i;++$)if(this.getElementByPos($)===H)return new NL($,this);return this.end()}reverse(){let H=0,$=this.i-1;while(H<$){let A=this.getElementByPos(H);this.setElementByPos(H,this.getElementByPos($)),this.setElementByPos($,A),H+=1,$-=1}}unique(){if(this.i<=1)return this.i;let H=1,$=this.getElementByPos(0);for(let A=1;A<this.i;++A){let L=this.getElementByPos(A);if(L!==$)$=L,this.setElementByPos(H++,L)}while(this.i>H)this.popBack();return this.i}sort(H){let $=[];for(let A=0;A<this.i;++A)$.push(this.getElementByPos(A));$.sort(H);for(let A=0;A<this.i;++A)this.setElementByPos(A,$[A])}shrinkToFit(){if(this.i===0)return;let H=[];this.forEach(function($){H.push($)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let $=0;$<this.P;++$)this.A.push(Array(this.F));for(let $=0;$<H.length;++$)this.pushBack(H[$])}forEach(H){for(let $=0;$<this.i;++$)H(this.getElementByPos($),$,this)}[Symbol.iterator](){return function*(){for(let H=0;H<this.i;++H)yield this.getElementByPos(H)}.bind(this)()}}var dd=du;au.default=dd});var Ru=p((Nu)=>{Object.defineProperty(Nu,"t",{value:!0});Nu.TreeNodeEnableIndex=Nu.TreeNode=void 0;class _T{constructor(H,$){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=H,this.l=$}L(){let H=this;if(H.ee===1&&H.tt.tt===H)H=H.W;else if(H.U){H=H.U;while(H.W)H=H.W}else{let $=H.tt;while($.U===H)H=$,$=H.tt;H=$}return H}B(){let H=this;if(H.W){H=H.W;while(H.U)H=H.U;return H}else{let $=H.tt;while($.W===H)H=$,$=H.tt;if(H.W!==$)return $;else return H}}te(){let H=this.tt,$=this.W,A=$.U;if(H.tt===this)H.tt=$;else if(H.U===this)H.U=$;else H.W=$;if($.tt=H,$.U=this,this.tt=$,this.W=A,A)A.tt=this;return $}se(){let H=this.tt,$=this.U,A=$.W;if(H.tt===this)H.tt=$;else if(H.U===this)H.U=$;else H.W=$;if($.tt=H,$.W=this,this.tt=$,this.U=A,A)A.tt=this;return $}}Nu.TreeNode=_T;class bu extends _T{constructor(){super(...arguments);this.rt=1}te(){let H=super.te();return this.ie(),H.ie(),H}se(){let H=super.se();return this.ie(),H.ie(),H}ie(){if(this.rt=1,this.U)this.rt+=this.U.rt;if(this.W)this.rt+=this.W.rt}}Nu.TreeNodeEnableIndex=bu});var pT=p((eu)=>{Object.defineProperty(eu,"t",{value:!0});eu.default=void 0;var Ou=Ru(),ld=WA(),mu=uA();class wu extends ld.Container{constructor(H=function(A,L){if(A<L)return-1;if(A>L)return 1;return 0},$=!1){super();if(this.Y=void 0,this.v=H,$)this.re=Ou.TreeNodeEnableIndex,this.M=function(A,L,D){let f=this.ne(A,L,D);if(f){let E=f.tt;while(E!==this.h)E.rt+=1,E=E.tt;let I=this.he(f);if(I){let{parentNode:P,grandParent:T,curNode:U}=I;P.ie(),T.ie(),U.ie()}}return this.i},this.V=function(A){let L=this.fe(A);while(L!==this.h)L.rt-=1,L=L.tt};else this.re=Ou.TreeNode,this.M=function(A,L,D){let f=this.ne(A,L,D);if(f)this.he(f);return this.i},this.V=this.fe;this.h=new this.re}X(H,$){let A=this.h;while(H){let L=this.v(H.u,$);if(L<0)H=H.W;else if(L>0)A=H,H=H.U;else return H}return A}Z(H,$){let A=this.h;while(H)if(this.v(H.u,$)<=0)H=H.W;else A=H,H=H.U;return A}$(H,$){let A=this.h;while(H){let L=this.v(H.u,$);if(L<0)A=H,H=H.W;else if(L>0)H=H.U;else return H}return A}rr(H,$){let A=this.h;while(H)if(this.v(H.u,$)<0)A=H,H=H.W;else H=H.U;return A}ue(H){while(!0){let $=H.tt;if($===this.h)return;if(H.ee===1){H.ee=0;return}if(H===$.U){let A=$.W;if(A.ee===1)if(A.ee=0,$.ee=1,$===this.Y)this.Y=$.te();else $.te();else if(A.W&&A.W.ee===1){if(A.ee=$.ee,$.ee=0,A.W.ee=0,$===this.Y)this.Y=$.te();else $.te();return}else if(A.U&&A.U.ee===1)A.ee=1,A.U.ee=0,A.se();else A.ee=1,H=$}else{let A=$.U;if(A.ee===1)if(A.ee=0,$.ee=1,$===this.Y)this.Y=$.se();else $.se();else if(A.U&&A.U.ee===1){if(A.ee=$.ee,$.ee=0,A.U.ee=0,$===this.Y)this.Y=$.se();else $.se();return}else if(A.W&&A.W.ee===1)A.ee=1,A.W.ee=0,A.te();else A.ee=1,H=$}}}fe(H){if(this.i===1)return this.clear(),this.h;let $=H;while($.U||$.W){if($.W){$=$.W;while($.U)$=$.U}else $=$.U;[H.u,$.u]=[$.u,H.u],[H.l,$.l]=[$.l,H.l],H=$}if(this.h.U===$)this.h.U=$.tt;else if(this.h.W===$)this.h.W=$.tt;this.ue($);let A=$.tt;if($===A.U)A.U=void 0;else A.W=void 0;return this.i-=1,this.Y.ee=0,A}oe(H,$){if(H===void 0)return!1;if(this.oe(H.U,$))return!0;if($(H))return!0;return this.oe(H.W,$)}he(H){while(!0){let $=H.tt;if($.ee===0)return;let A=$.tt;if($===A.U){let L=A.W;if(L&&L.ee===1){if(L.ee=$.ee=0,A===this.Y)return;A.ee=1,H=A;continue}else if(H===$.W){if(H.ee=0,H.U)H.U.tt=$;if(H.W)H.W.tt=A;if($.W=H.U,A.U=H.W,H.U=$,H.W=A,A===this.Y)this.Y=H,this.h.tt=H;else{let D=A.tt;if(D.U===A)D.U=H;else D.W=H}return H.tt=A.tt,$.tt=H,A.tt=H,A.ee=1,{parentNode:$,grandParent:A,curNode:H}}else{if($.ee=0,A===this.Y)this.Y=A.se();else A.se();A.ee=1}}else{let L=A.U;if(L&&L.ee===1){if(L.ee=$.ee=0,A===this.Y)return;A.ee=1,H=A;continue}else if(H===$.U){if(H.ee=0,H.U)H.U.tt=A;if(H.W)H.W.tt=$;if(A.W=H.U,$.U=H.W,H.U=A,H.W=$,A===this.Y)this.Y=H,this.h.tt=H;else{let D=A.tt;if(D.U===A)D.U=H;else D.W=H}return H.tt=A.tt,$.tt=H,A.tt=H,A.ee=1,{parentNode:$,grandParent:A,curNode:H}}else{if($.ee=0,A===this.Y)this.Y=A.te();else A.te();A.ee=1}}return}}ne(H,$,A){if(this.Y===void 0){this.i+=1,this.Y=new this.re(H,$),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let L,D=this.h.U,f=this.v(D.u,H);if(f===0){D.l=$;return}else if(f>0)D.U=new this.re(H,$),D.U.tt=D,L=D.U,this.h.U=L;else{let E=this.h.W,I=this.v(E.u,H);if(I===0){E.l=$;return}else if(I<0)E.W=new this.re(H,$),E.W.tt=E,L=E.W,this.h.W=L;else{if(A!==void 0){let P=A.o;if(P!==this.h){let T=this.v(P.u,H);if(T===0){P.l=$;return}else if(T>0){let U=P.L(),M=this.v(U.u,H);if(M===0){U.l=$;return}else if(M<0)if(L=new this.re(H,$),U.W===void 0)U.W=L,L.tt=U;else P.U=L,L.tt=P}}}if(L===void 0){L=this.Y;while(!0){let P=this.v(L.u,H);if(P>0){if(L.U===void 0){L.U=new this.re(H,$),L.U.tt=L,L=L.U;break}L=L.U}else if(P<0){if(L.W===void 0){L.W=new this.re(H,$),L.W.tt=L,L=L.W;break}L=L.W}else{L.l=$;return}}}}}return this.i+=1,L}I(H,$){while(H){let A=this.v(H.u,$);if(A<0)H=H.W;else if(A>0)H=H.U;else return H}return H||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(H,$){let A=H.o;if(A===this.h)(0,mu.throwIteratorAccessError)();if(this.i===1)return A.u=$,!0;if(A===this.h.U){if(this.v(A.B().u,$)>0)return A.u=$,!0;return!1}if(A===this.h.W){if(this.v(A.L().u,$)<0)return A.u=$,!0;return!1}let L=A.L().u;if(this.v(L,$)>=0)return!1;let D=A.B().u;if(this.v(D,$)<=0)return!1;return A.u=$,!0}eraseElementByPos(H){if(H<0||H>this.i-1)throw RangeError();let $=0,A=this;return this.oe(this.Y,function(L){if(H===$)return A.V(L),!0;return $+=1,!1}),this.i}eraseElementByKey(H){if(this.i===0)return!1;let $=this.I(this.Y,H);if($===this.h)return!1;return this.V($),!0}eraseElementByIterator(H){let $=H.o;if($===this.h)(0,mu.throwIteratorAccessError)();let A=$.W===void 0;if(H.iteratorType===0){if(A)H.next()}else if(!A||$.U===void 0)H.next();return this.V($),H}forEach(H){let $=0;for(let A of this)H(A,$++,this)}getElementByPos(H){if(H<0||H>this.i-1)throw RangeError();let $,A=0;for(let L of this){if(A===H){$=L;break}A+=1}return $}getHeight(){if(this.i===0)return 0;let H=function($){if(!$)return 0;return Math.max(H($.U),H($.W))+1};return H(this.Y)}}var yd=wu;eu.default=yd});var VT=p((Qu)=>{Object.defineProperty(Qu,"t",{value:!0});Qu.default=void 0;var bd=WA(),fE=uA();class Ju extends bd.ContainerIterator{constructor(H,$,A){super(A);if(this.o=H,this.h=$,this.iteratorType===0)this.pre=function(){if(this.o===this.h.U)(0,fE.throwIteratorAccessError)();return this.o=this.o.L(),this},this.next=function(){if(this.o===this.h)(0,fE.throwIteratorAccessError)();return this.o=this.o.B(),this};else this.pre=function(){if(this.o===this.h.W)(0,fE.throwIteratorAccessError)();return this.o=this.o.B(),this},this.next=function(){if(this.o===this.h)(0,fE.throwIteratorAccessError)();return this.o=this.o.L(),this}}get index(){let H=this.o,$=this.h.tt;if(H===this.h){if($)return $.rt-1;return 0}let A=0;if(H.U)A+=H.U.rt;while(H!==$){let L=H.tt;if(H===L.W){if(A+=1,L.U)A+=L.U.rt}H=L}return A}}var Nd=Ju;Qu.default=Nd});var Zu=p((Yu)=>{Object.defineProperty(Yu,"t",{value:!0});Yu.default=void 0;var kd=gu(pT()),Rd=gu(VT()),Od=uA();function gu(H){return H&&H.t?H:{default:H}}class v$ extends Rd.default{constructor(H,$,A,L){super(H,$,L);this.container=A}get pointer(){if(this.o===this.h)(0,Od.throwIteratorAccessError)();return this.o.u}copy(){return new v$(this.o,this.h,this.container,this.iteratorType)}}class vu extends kd.default{constructor(H=[],$,A){super($,A);let L=this;H.forEach(function(D){L.insert(D)})}*K(H){if(H===void 0)return;yield*this.K(H.U),yield H.u,yield*this.K(H.W)}begin(){return new v$(this.h.U||this.h,this.h,this)}end(){return new v$(this.h,this.h,this)}rBegin(){return new v$(this.h.W||this.h,this.h,this,1)}rEnd(){return new v$(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(H,$){return this.M(H,void 0,$)}find(H){let $=this.I(this.Y,H);return new v$($,this.h,this)}lowerBound(H){let $=this.X(this.Y,H);return new v$($,this.h,this)}upperBound(H){let $=this.Z(this.Y,H);return new v$($,this.h,this)}reverseLowerBound(H){let $=this.$(this.Y,H);return new v$($,this.h,this)}reverseUpperBound(H){let $=this.rr(this.Y,H);return new v$($,this.h,this)}union(H){let $=this;return H.forEach(function(A){$.insert(A)}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var md=vu;Yu.default=md});var Lx=p(($x)=>{Object.defineProperty($x,"t",{value:!0});$x.default=void 0;var wd=zu(pT()),ed=zu(VT()),jd=uA();function zu(H){return H&&H.t?H:{default:H}}class Y$ extends ed.default{constructor(H,$,A,L){super(H,$,L);this.container=A}get pointer(){if(this.o===this.h)(0,jd.throwIteratorAccessError)();let H=this;return new Proxy([],{get($,A){if(A==="0")return H.o.u;else if(A==="1")return H.o.l},set($,A,L){if(A!=="1")throw TypeError("props must be 1");return H.o.l=L,!0}})}copy(){return new Y$(this.o,this.h,this.container,this.iteratorType)}}class Hx extends wd.default{constructor(H=[],$,A){super($,A);let L=this;H.forEach(function(D){L.setElement(D[0],D[1])})}*K(H){if(H===void 0)return;yield*this.K(H.U),yield[H.u,H.l],yield*this.K(H.W)}begin(){return new Y$(this.h.U||this.h,this.h,this)}end(){return new Y$(this.h,this.h,this)}rBegin(){return new Y$(this.h.W||this.h,this.h,this,1)}rEnd(){return new Y$(this.h,this.h,this,1)}front(){if(this.i===0)return;let H=this.h.U;return[H.u,H.l]}back(){if(this.i===0)return;let H=this.h.W;return[H.u,H.l]}lowerBound(H){let $=this.X(this.Y,H);return new Y$($,this.h,this)}upperBound(H){let $=this.Z(this.Y,H);return new Y$($,this.h,this)}reverseLowerBound(H){let $=this.$(this.Y,H);return new Y$($,this.h,this)}reverseUpperBound(H){let $=this.rr(this.Y,H);return new Y$($,this.h,this)}setElement(H,$,A){return this.M(H,$,A)}find(H){let $=this.I(this.Y,H);return new Y$($,this.h,this)}getElementByKey(H){return this.I(this.Y,H).l}union(H){let $=this;return H.forEach(function(A){$.setElement(A[0],A[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var Jd=Hx;$x.default=Jd});var WT=p((Dx)=>{Object.defineProperty(Dx,"t",{value:!0});Dx.default=Qd;function Qd(H){let $=typeof H;return $==="object"&&H!==null||$==="function"}});var xT=p((Px)=>{Object.defineProperty(Px,"t",{value:!0});Px.HashContainerIterator=Px.HashContainer=void 0;var fx=WA(),uT=gd(WT()),Tf=uA();function gd(H){return H&&H.t?H:{default:H}}class Ex extends fx.ContainerIterator{constructor(H,$,A){super(A);if(this.o=H,this.h=$,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,Tf.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,Tf.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,Tf.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,Tf.throwIteratorAccessError)();return this.o=this.o.L,this}}}Px.HashContainerIterator=Ex;class Ix extends fx.Container{constructor(){super();this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(H){let{L:$,B:A}=H;if($.B=A,A.L=$,H===this.p)this.p=A;if(H===this._)this._=$;this.i-=1}M(H,$,A){if(A===void 0)A=(0,uT.default)(H);let L;if(A){let D=H[this.HASH_TAG];if(D!==void 0)return this.H[D].l=$,this.i;Object.defineProperty(H,this.HASH_TAG,{value:this.H.length,configurable:!0}),L={u:H,l:$,L:this._,B:this.h},this.H.push(L)}else{let D=this.g[H];if(D)return D.l=$,this.i;L={u:H,l:$,L:this._,B:this.h},this.g[H]=L}if(this.i===0)this.p=L,this.h.B=L;else this._.B=L;return this._=L,this.h.L=L,++this.i}I(H,$){if($===void 0)$=(0,uT.default)(H);if($){let A=H[this.HASH_TAG];if(A===void 0)return this.h;return this.H[A]}else return this.g[H]||this.h}clear(){let H=this.HASH_TAG;this.H.forEach(function($){delete $.u[H]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(H,$){let A;if($===void 0)$=(0,uT.default)(H);if($){let L=H[this.HASH_TAG];if(L===void 0)return!1;delete H[this.HASH_TAG],A=this.H[L],delete this.H[L]}else{if(A=this.g[H],A===void 0)return!1;delete this.g[H]}return this.V(A),!0}eraseElementByIterator(H){let $=H.o;if($===this.h)(0,Tf.throwIteratorAccessError)();return this.V($),H.next()}eraseElementByPos(H){if(H<0||H>this.i-1)throw RangeError();let $=this.p;while(H--)$=$.B;return this.V($),this.i}}Px.HashContainer=Ix});var px=p((tx)=>{Object.defineProperty(tx,"t",{value:!0});tx.default=void 0;var Ux=xT(),Yd=uA();class kL extends Ux.HashContainerIterator{constructor(H,$,A,L){super(H,$,L);this.container=A}get pointer(){if(this.o===this.h)(0,Yd.throwIteratorAccessError)();return this.o.u}copy(){return new kL(this.o,this.h,this.container,this.iteratorType)}}class Mx extends Ux.HashContainer{constructor(H=[]){super();let $=this;H.forEach(function(A){$.insert(A)})}begin(){return new kL(this.p,this.h,this)}end(){return new kL(this.h,this.h,this)}rBegin(){return new kL(this._,this.h,this,1)}rEnd(){return new kL(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(H,$){return this.M(H,void 0,$)}getElementByPos(H){if(H<0||H>this.i-1)throw RangeError();let $=this.p;while(H--)$=$.B;return $.u}find(H,$){let A=this.I(H,$);return new kL(A,this.h,this)}forEach(H){let $=0,A=this.p;while(A!==this.h)H(A.u,$++,this),A=A.B}[Symbol.iterator](){return function*(){let H=this.p;while(H!==this.h)yield H.u,H=H.B}.bind(this)()}}var qd=Mx;tx.default=qd});var hx=p((ux)=>{Object.defineProperty(ux,"t",{value:!0});ux.default=void 0;var Vx=xT(),Zd=Ha(WT()),zd=uA();function Ha(H){return H&&H.t?H:{default:H}}class RL extends Vx.HashContainerIterator{constructor(H,$,A,L){super(H,$,L);this.container=A}get pointer(){if(this.o===this.h)(0,zd.throwIteratorAccessError)();let H=this;return new Proxy([],{get($,A){if(A==="0")return H.o.u;else if(A==="1")return H.o.l},set($,A,L){if(A!=="1")throw TypeError("props must be 1");return H.o.l=L,!0}})}copy(){return new RL(this.o,this.h,this.container,this.iteratorType)}}class Wx extends Vx.HashContainer{constructor(H=[]){super();let $=this;H.forEach(function(A){$.setElement(A[0],A[1])})}begin(){return new RL(this.p,this.h,this)}end(){return new RL(this.h,this.h,this)}rBegin(){return new RL(this._,this.h,this,1)}rEnd(){return new RL(this.h,this.h,this,1)}front(){if(this.i===0)return;return[this.p.u,this.p.l]}back(){if(this.i===0)return;return[this._.u,this._.l]}setElement(H,$,A){return this.M(H,$,A)}getElementByKey(H,$){if($===void 0)$=(0,Zd.default)(H);if($){let L=H[this.HASH_TAG];return L!==void 0?this.H[L].l:void 0}let A=this.g[H];return A?A.l:void 0}getElementByPos(H){if(H<0||H>this.i-1)throw RangeError();let $=this.p;while(H--)$=$.B;return[$.u,$.l]}find(H,$){let A=this.I(H,$);return new RL(A,this.h,this)}forEach(H){let $=0,A=this.p;while(A!==this.h)H([A.u,A.l],$++,this),A=A.B}[Symbol.iterator](){return function*(){let H=this.p;while(H!==this.h)yield[H.u,H.l],H=H.B}.bind(this)()}}var $a=Wx;ux.default=$a});var cx=p((G$)=>{Object.defineProperty(G$,"t",{value:!0});Object.defineProperty(G$,"Deque",{enumerable:!0,get:function(){return Ia.default}});Object.defineProperty(G$,"HashMap",{enumerable:!0,get:function(){return Ma.default}});Object.defineProperty(G$,"HashSet",{enumerable:!0,get:function(){return Ua.default}});Object.defineProperty(G$,"LinkList",{enumerable:!0,get:function(){return Ea.default}});Object.defineProperty(G$,"OrderedMap",{enumerable:!0,get:function(){return Ta.default}});Object.defineProperty(G$,"OrderedSet",{enumerable:!0,get:function(){return Pa.default}});Object.defineProperty(G$,"PriorityQueue",{enumerable:!0,get:function(){return Da.default}});Object.defineProperty(G$,"Queue",{enumerable:!0,get:function(){return La.default}});Object.defineProperty(G$,"Stack",{enumerable:!0,get:function(){return Aa.default}});Object.defineProperty(G$,"Vector",{enumerable:!0,get:function(){return fa.default}});var Aa=xA(Pu()),La=xA(tu()),Da=xA(Wu()),fa=xA(Fu()),Ea=xA(Gu()),Ia=xA(yu()),Pa=xA(Zu()),Ta=xA(Lx()),Ua=xA(px()),Ma=xA(hx());function xA(H){return H&&H.t?H:{default:H}}});var Sx=p((Dm,Xx)=>{var ta=cx().OrderedSet,hA=K$()("number-allocator:trace"),_a=K$()("number-allocator:error");function f$(H,$){this.low=H,this.high=$}f$.prototype.equals=function(H){return this.low===H.low&&this.high===H.high};f$.prototype.compare=function(H){if(this.low<H.low&&this.high<H.low)return-1;if(H.low<this.low&&H.high<this.low)return 1;return 0};function cA(H,$){if(!(this instanceof cA))return new cA(H,$);this.min=H,this.max=$,this.ss=new ta([],(A,L)=>{return A.compare(L)}),hA("Create"),this.clear()}cA.prototype.firstVacant=function(){if(this.ss.size()===0)return null;return this.ss.front().low};cA.prototype.alloc=function(){if(this.ss.size()===0)return hA("alloc():empty"),null;let H=this.ss.begin(),$=H.pointer.low,A=H.pointer.high,L=$;if(L+1<=A)this.ss.updateKeyByIterator(H,new f$($+1,A));else this.ss.eraseElementByPos(0);return hA("alloc():"+L),L};cA.prototype.use=function(H){let $=new f$(H,H),A=this.ss.lowerBound($);if(!A.equals(this.ss.end())){let L=A.pointer.low,D=A.pointer.high;if(A.pointer.equals($))return this.ss.eraseElementByIterator(A),hA("use():"+H),!0;if(L>H)return!1;if(L===H)return this.ss.updateKeyByIterator(A,new f$(L+1,D)),hA("use():"+H),!0;if(D===H)return this.ss.updateKeyByIterator(A,new f$(L,D-1)),hA("use():"+H),!0;return this.ss.updateKeyByIterator(A,new f$(H+1,D)),this.ss.insert(new f$(L,H-1)),hA("use():"+H),!0}return hA("use():failed"),!1};cA.prototype.free=function(H){if(H<this.min||H>this.max){_a("free():"+H+" is out of range");return}let $=new f$(H,H),A=this.ss.upperBound($);if(A.equals(this.ss.end())){if(A.equals(this.ss.begin())){this.ss.insert($);return}A.pre();let L=A.pointer.high;if(A.pointer.high+1===H)this.ss.updateKeyByIterator(A,new f$(L,H));else this.ss.insert($)}else if(A.equals(this.ss.begin()))if(H+1===A.pointer.low){let L=A.pointer.high;this.ss.updateKeyByIterator(A,new f$(H,L))}else this.ss.insert($);else{let L=A.pointer.low,D=A.pointer.high;A.pre();let f=A.pointer.low;if(A.pointer.high+1===H)if(H+1===L)this.ss.eraseElementByIterator(A),this.ss.updateKeyByIterator(A,new f$(f,D));else this.ss.updateKeyByIterator(A,new f$(f,H));else if(H+1===L)this.ss.eraseElementByIterator(A.next()),this.ss.insert(new f$(H,D));else this.ss.insert($)}hA("free():"+H)};cA.prototype.clear=function(){hA("clear()"),this.ss.clear(),this.ss.insert(new f$(this.min,this.max))};cA.prototype.intervalCount=function(){return this.ss.size()};cA.prototype.dump=function(){console.log("length:"+this.ss.size());for(let H of this.ss)console.log(H)};Xx.exports=cA});var hT=p((Va,rx)=>{var pa=Sx();Va.NumberAllocator=pa});var ox=p((nx)=>{Object.defineProperty(nx,"__esModule",{value:!0});var ua=Hu(),xa=hT();class Bx{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(H){if(H>0)this.aliasToTopic=new ua.LRUCache({max:H}),this.topicToAlias={},this.numberAllocator=new xa.NumberAllocator(1,H),this.max=H,this.length=0}put(H,$){if($===0||$>this.max)return!1;let A=this.aliasToTopic.get($);if(A)delete this.topicToAlias[A];return this.aliasToTopic.set($,H),this.topicToAlias[H]=$,this.numberAllocator.use($),this.length=this.aliasToTopic.size,!0}getTopicByAlias(H){return this.aliasToTopic.get(H)}getAliasByTopic(H){let $=this.topicToAlias[H];if(typeof $<"u")this.aliasToTopic.get($);return $}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){let H=this.numberAllocator.firstVacant();if(H)return H;return[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}}nx.default=Bx});var Fx=p((Uf)=>{var ca=Uf&&Uf.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(Uf,"__esModule",{value:!0});var Xa=If(),Sa=ca(ox()),ra=aL(),Ba=(H,$)=>{H.log("_handleConnack");let{options:A}=H,D=A.protocolVersion===5?$.reasonCode:$.returnCode;if(clearTimeout(H.connackTimer),delete H.topicAliasSend,$.properties){if($.properties.topicAliasMaximum){if($.properties.topicAliasMaximum>65535){H.emit("error",Error("topicAliasMaximum from broker is out of range"));return}if($.properties.topicAliasMaximum>0)H.topicAliasSend=new Sa.default($.properties.topicAliasMaximum)}if($.properties.serverKeepAlive&&A.keepalive)A.keepalive=$.properties.serverKeepAlive;if($.properties.maximumPacketSize){if(!A.properties)A.properties={};A.properties.maximumPacketSize=$.properties.maximumPacketSize}}if(D===0)H.reconnecting=!1,H._onConnect($);else if(D>0){let f=new ra.ErrorWithReasonCode(`Connection refused: ${Xa.ReasonCodes[D]}`,D);if(H.emit("error",f),H.options.reconnectOnConnackError)H._cleanUp(!0)}};Uf.default=Ba});var Cx=p((sx)=>{Object.defineProperty(sx,"__esModule",{value:!0});var na=(H,$,A)=>{H.log("handling pubrel packet");let L=typeof A<"u"?A:H.noop,{messageId:D}=$,f={cmd:"pubcomp",messageId:D};H.incomingStore.get($,(E,I)=>{if(!E)H.emit("message",I.topic,I.payload,I),H.handleMessage(I,(P)=>{if(P)return L(P);H.incomingStore.del(I,H.noop),H._sendPacket(f,L)});else H._sendPacket(f,L)})};sx.default=na});var ix=p((Mf)=>{var tf=Mf&&Mf.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(Mf,"__esModule",{value:!0});var Fa=tf(R1()),sa=tf(K1()),Ca=tf(Fx()),ia=tf(If()),Ga=tf(Cx()),da=(H,$,A)=>{let{options:L}=H;if(L.protocolVersion===5&&L.properties&&L.properties.maximumPacketSize&&L.properties.maximumPacketSize<$.length)return H.emit("error",Error(`exceeding packets size ${$.cmd}`)),H.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),H;switch(H.log("_handlePacket :: emitting packetreceive"),H.emit("packetreceive",$),$.cmd){case"publish":(0,Fa.default)(H,$,A);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":H.reschedulePing(),(0,ia.default)(H,$),A();break;case"pubrel":H.reschedulePing(),(0,Ga.default)(H,$,A);break;case"connack":(0,Ca.default)(H,$),A();break;case"auth":H.reschedulePing(),(0,sa.default)(H,$),A();break;case"pingresp":H.log("_handlePacket :: received pingresp"),H.reschedulePing(!0),A();break;case"disconnect":H.emit("disconnect",$),A();break;default:H.log("_handlePacket :: unknown command"),A();break}};Mf.default=da});var cT=p((dx)=>{Object.defineProperty(dx,"__esModule",{value:!0});class Gx{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let H=this.nextId++;if(this.nextId===65536)this.nextId=1;return H}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(H){return!0}deallocate(H){}clear(){}}dx.default=Gx});var yx=p((lx)=>{Object.defineProperty(lx,"__esModule",{value:!0});class ax{aliasToTopic;max;length;constructor(H){this.aliasToTopic={},this.max=H}put(H,$){if($===0||$>this.max)return!1;return this.aliasToTopic[$]=H,this.length=Object.keys(this.aliasToTopic).length,!0}getTopicByAlias(H){return this.aliasToTopic[H]}clear(){this.aliasToTopic={}}}lx.default=ax});var bx=p((xD)=>{var ya=xD&&xD.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(xD,"__esModule",{value:!0});xD.TypedEventEmitter=void 0;var ba=ya(B("events")),Na=aL();class XT{}xD.TypedEventEmitter=XT;(0,Na.applyMixin)(XT,ba.default)});var _f=p((tm,RA)=>{function ST(H){return RA.exports=ST=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},RA.exports.__esModule=!0,RA.exports.default=RA.exports,ST(H)}RA.exports=ST,RA.exports.__esModule=!0,RA.exports.default=RA.exports});var kx=p((_m,pf)=>{var Nx=_f().default;function ka(H,$){if(Nx(H)!="object"||!H)return H;var A=H[Symbol.toPrimitive];if(A!==void 0){var L=A.call(H,$||"default");if(Nx(L)!="object")return L;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(H)}pf.exports=ka,pf.exports.__esModule=!0,pf.exports.default=pf.exports});var Rx=p((pm,Vf)=>{var Ra=_f().default,Oa=kx();function ma(H){var $=Oa(H,"string");return Ra($)=="symbol"?$:$+""}Vf.exports=ma,Vf.exports.__esModule=!0,Vf.exports.default=Vf.exports});var Ox=p((Vm,Wf)=>{var wa=Rx();function ea(H,$,A){return($=wa($))in H?Object.defineProperty(H,$,{value:A,enumerable:!0,configurable:!0,writable:!0}):H[$]=A,H}Wf.exports=ea,Wf.exports.__esModule=!0,Wf.exports.default=Wf.exports});var mx=p((Wm,uf)=>{function ja(H){if(Array.isArray(H))return H}uf.exports=ja,uf.exports.__esModule=!0,uf.exports.default=uf.exports});var ex=p((um,xf)=>{function Ja(H,$){var A=H==null?null:typeof Symbol<"u"&&H[Symbol.iterator]||H["@@iterator"];if(A!=null){var L,D,f,E,I=[],P=!0,T=!1;try{if(f=(A=A.call(H)).next,$===0){if(Object(A)!==A)return;P=!1}else for(;!(P=(L=f.call(A)).done)&&(I.push(L.value),I.length!==$);P=!0);}catch(U){T=!0,D=U}finally{try{if(!P&&A.return!=null&&(E=A.return(),Object(E)!==E))return}finally{if(T)throw D}}return I}}xf.exports=Ja,xf.exports.__esModule=!0,xf.exports.default=xf.exports});var jx=p((xm,hf)=>{function Qa(H,$){($==null||$>H.length)&&($=H.length);for(var A=0,L=Array($);A<$;A++)L[A]=H[A];return L}hf.exports=Qa,hf.exports.__esModule=!0,hf.exports.default=hf.exports});var Qx=p((hm,cf)=>{var Jx=jx();function Ka(H,$){if(H){if(typeof H=="string")return Jx(H,$);var A={}.toString.call(H).slice(8,-1);return A==="Object"&&H.constructor&&(A=H.constructor.name),A==="Map"||A==="Set"?Array.from(H):A==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(A)?Jx(H,$):void 0}}cf.exports=Ka,cf.exports.__esModule=!0,cf.exports.default=cf.exports});var Kx=p((cm,Xf)=>{function ga(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
14
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}Xf.exports=ga,Xf.exports.__esModule=!0,Xf.exports.default=Xf.exports});var gx=p((Xm,Sf)=>{var va=mx(),Ya=ex(),qa=Qx(),Za=Kx();function za(H,$){return va(H)||Ya(H,$)||qa(H,$)||Za()}Sf.exports=za,Sf.exports.__esModule=!0,Sf.exports.default=Sf.exports});var qx=p((vx)=>{Object.defineProperty(vx,"__esModule",{value:!0});vx.createAddUniqueNumber=void 0;var Hl=(H)=>{return($)=>{let A=H($);return $.add(A),A}};vx.createAddUniqueNumber=Hl});var H9=p((Zx)=>{Object.defineProperty(Zx,"__esModule",{value:!0});Zx.createCache=void 0;var $l=(H)=>{return($,A)=>{return H.set($,A),A}};Zx.createCache=$l});var E9=p((D9)=>{Object.defineProperty(D9,"__esModule",{value:!0});D9.createGenerateUniqueNumber=void 0;var $9=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,L9=536870912,A9=L9*2,Al=(H,$)=>{return(A)=>{let L=$.get(A),D=L===void 0?A.size:L<A9?L+1:0;if(!A.has(D))return H(A,D);if(A.size<L9){while(A.has(D))D=Math.floor(Math.random()*A9);return H(A,D)}if(A.size>$9)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(A.has(D))D=Math.floor(Math.random()*$9);return H(A,D)}};D9.createGenerateUniqueNumber=Al});var rT=p((P9)=>{Object.defineProperty(P9,"__esModule",{value:!0});P9.generateUniqueNumber=P9.addUniqueNumber=void 0;var Ll=qx(),Dl=H9(),fl=E9(),I9=new WeakMap,El=(0,Dl.createCache)(I9),Il=P9.generateUniqueNumber=(0,fl.createGenerateUniqueNumber)(El,I9),nm=P9.addUniqueNumber=(0,Ll.createAddUniqueNumber)(Il)});var M9=p((Fm,rf)=>{function U9(H,$,A,L,D,f,E){try{var I=H[f](E),P=I.value}catch(T){return void A(T)}I.done?$(P):Promise.resolve(P).then(L,D)}function Tl(H){return function(){var $=this,A=arguments;return new Promise(function(L,D){var f=H.apply($,A);function E(P){U9(f,L,D,E,I,"next",P)}function I(P){U9(f,L,D,E,I,"throw",P)}E(void 0)})}}rf.exports=Tl,rf.exports.__esModule=!0,rf.exports.default=rf.exports});var BT=p((sm,Bf)=>{function Ul(H,$){this.v=H,this.k=$}Bf.exports=Ul,Bf.exports.__esModule=!0,Bf.exports.default=Bf.exports});var nT=p((Cm,OA)=>{function EE(H,$,A,L){var D=Object.defineProperty;try{D({},"",{})}catch(f){D=0}OA.exports=EE=function(E,I,P,T){function U(M,t){EE(E,M,function(_){return this._invoke(M,t,_)})}I?D?D(E,I,{value:P,enumerable:!T,configurable:!T,writable:!T}):E[I]=P:(U("next",0),U("throw",1),U("return",2))},OA.exports.__esModule=!0,OA.exports.default=OA.exports,EE(H,$,A,L)}OA.exports=EE,OA.exports.__esModule=!0,OA.exports.default=OA.exports});var oT=p((im,mA)=>{var XA=nT();function t9(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var H,$,A=typeof Symbol=="function"?Symbol:{},L=A.iterator||"@@iterator",D=A.toStringTag||"@@toStringTag";function f(_,x,V,h){var W=x&&x.prototype instanceof I?x:I,c=Object.create(W.prototype);return XA(c,"_invoke",function(r,F,N){var y,k,J,e=0,WH=N||[],vH=!1,sH={p:0,n:0,v:H,a:rH,f:rH.bind(H,4),d:function(hH,CH){return y=hH,k=0,J=H,sH.n=CH,E}};function rH(tH,hH){for(k=tH,J=hH,$=0;!vH&&e&&!CH&&$<WH.length;$++){var CH,GH=WH[$],CA=sH.p,k$=GH[2];tH>3?(CH=k$===hH)&&(J=GH[(k=GH[4])?5:(k=3,3)],GH[4]=GH[5]=H):GH[0]<=CA&&((CH=tH<2&&CA<GH[1])?(k=0,sH.v=hH,sH.n=GH[1]):CA<k$&&(CH=tH<3||GH[0]>hH||hH>k$)&&(GH[4]=tH,GH[5]=hH,sH.n=k$,k=0))}if(CH||tH>1)return E;throw vH=!0,hH}return function(tH,hH,CH){if(e>1)throw TypeError("Generator is already running");for(vH&&hH===1&&rH(hH,CH),k=hH,J=CH;($=k<2?H:J)||!vH;){y||(k?k<3?(k>1&&(sH.n=-1),rH(k,J)):sH.n=J:sH.v=J);try{if(e=2,y){if(k||(tH="next"),$=y[tH]){if(!($=$.call(y,J)))throw TypeError("iterator result is not an object");if(!$.done)return $;J=$.value,k<2&&(k=0)}else k===1&&($=y.return)&&$.call(y),k<2&&(J=TypeError("The iterator does not provide a '"+tH+"' method"),k=1);y=H}else if(($=(vH=sH.n<0)?J:r.call(F,sH))!==E)break}catch(GH){y=H,k=1,J=GH}finally{e=1}}return{value:$,done:vH}}}(_,V,h),!0),c}var E={};function I(){}function P(){}function T(){}$=Object.getPrototypeOf;var U=[][L]?$($([][L]())):(XA($={},L,function(){return this}),$),M=T.prototype=I.prototype=Object.create(U);function t(_){return Object.setPrototypeOf?Object.setPrototypeOf(_,T):(_.__proto__=T,XA(_,D,"GeneratorFunction")),_.prototype=Object.create(M),_}return P.prototype=T,XA(M,"constructor",T),XA(T,"constructor",P),P.displayName="GeneratorFunction",XA(T,D,"GeneratorFunction"),XA(M),XA(M,D,"Generator"),XA(M,L,function(){return this}),XA(M,"toString",function(){return"[object Generator]"}),(mA.exports=t9=function(){return{w:f,m:t}},mA.exports.__esModule=!0,mA.exports.default=mA.exports)()}mA.exports=t9,mA.exports.__esModule=!0,mA.exports.default=mA.exports});var CT=p((Gm,nf)=>{var Ml=BT(),FT=nT();function sT(H,$){function A(D,f,E,I){try{var P=H[D](f),T=P.value;return T instanceof Ml?$.resolve(T.v).then(function(U){A("next",U,E,I)},function(U){A("throw",U,E,I)}):$.resolve(T).then(function(U){P.value=U,E(P)},function(U){return A("throw",U,E,I)})}catch(U){I(U)}}var L;this.next||(FT(sT.prototype),FT(sT.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),FT(this,"_invoke",function(D,f,E){function I(){return new $(function(P,T){A(D,E,P,T)})}return L=L?L.then(I,I):I()},!0)}nf.exports=sT,nf.exports.__esModule=!0,nf.exports.default=nf.exports});var iT=p((dm,of)=>{var tl=oT(),_l=CT();function pl(H,$,A,L,D){return new _l(tl().w(H,$,A,L),D||Promise)}of.exports=pl,of.exports.__esModule=!0,of.exports.default=of.exports});var _9=p((am,Ff)=>{var Vl=iT();function Wl(H,$,A,L,D){var f=Vl(H,$,A,L,D);return f.next().then(function(E){return E.done?E.value:f.next()})}Ff.exports=Wl,Ff.exports.__esModule=!0,Ff.exports.default=Ff.exports});var p9=p((lm,sf)=>{function ul(H){var $=Object(H),A=[];for(var L in $)A.unshift(L);return function D(){for(;A.length;)if((L=A.pop())in $)return D.value=L,D.done=!1,D;return D.done=!0,D}}sf.exports=ul,sf.exports.__esModule=!0,sf.exports.default=sf.exports});var V9=p((ym,Cf)=>{var xl=_f().default;function hl(H){if(H!=null){var $=H[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],A=0;if($)return $.call(H);if(typeof H.next=="function")return H;if(!isNaN(H.length))return{next:function(){return H&&A>=H.length&&(H=void 0),{value:H&&H[A++],done:!H}}}}throw TypeError(xl(H)+" is not iterable")}Cf.exports=hl,Cf.exports.__esModule=!0,Cf.exports.default=Cf.exports});var u9=p((bm,wA)=>{var cl=BT(),Xl=oT(),Sl=_9(),rl=iT(),Bl=CT(),nl=p9(),W9=V9();function GT(){var H=Xl(),$=H.m(GT),A=(Object.getPrototypeOf?Object.getPrototypeOf($):$.__proto__).constructor;function L(E){var I=typeof E=="function"&&E.constructor;return!!I&&(I===A||(I.displayName||I.name)==="GeneratorFunction")}var D={throw:1,return:2,break:3,continue:3};function f(E){var I,P;return function(T){I||(I={stop:function(){return P(T.a,2)},catch:function(){return T.v},abrupt:function(M,t){return P(T.a,D[M],t)},delegateYield:function(M,t,_){return I.resultName=t,P(T.d,W9(M),_)},finish:function(M){return P(T.f,M)}},P=function(M,t,_){T.p=I.prev,T.n=I.next;try{return M(t,_)}finally{I.next=T.n}}),I.resultName&&(I[I.resultName]=T.v,I.resultName=void 0),I.sent=T.v,I.next=T.n;try{return E.call(this,I)}finally{T.p=I.prev,T.n=I.next}}}return(wA.exports=GT=function(){return{wrap:function(P,T,U,M){return H.w(f(P),T,U,M&&M.reverse())},isGeneratorFunction:L,mark:H.m,awrap:function(P,T){return new cl(P,T)},AsyncIterator:Bl,async:function(P,T,U,M,t){return(L(T)?rl:Sl)(f(P),T,U,M,t)},keys:nl,values:W9}},wA.exports.__esModule=!0,wA.exports.default=wA.exports)()}wA.exports=GT,wA.exports.__esModule=!0,wA.exports.default=wA.exports});var h9=p((Nm,x9)=>{var IE=u9()();x9.exports=IE;try{regeneratorRuntime=IE}catch(H){if(typeof globalThis==="object")globalThis.regeneratorRuntime=IE;else Function("r","regeneratorRuntime = r")(IE)}});var X9=p((PE,c9)=>{(function(H,$){typeof PE==="object"&&typeof c9<"u"?$(PE,Ox(),gx(),rT(),M9(),h9()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],$):(H=typeof globalThis<"u"?globalThis:H||self,$(H.brokerFactory={},H._defineProperty,H._slicedToArray,H.fastUniqueNumbers,H._asyncToGenerator,H._regeneratorRuntime))})(PE,function(H,$,A,L,D,f){var E=function(W){return typeof W.start==="function"},I=new WeakMap;function P(h,W){var c=Object.keys(h);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(h);W&&(r=r.filter(function(F){return Object.getOwnPropertyDescriptor(h,F).enumerable})),c.push.apply(c,r)}return c}function T(h){for(var W=1;W<arguments.length;W++){var c=arguments[W]!=null?arguments[W]:{};W%2?P(Object(c),!0).forEach(function(r){$(h,r,c[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(h,Object.getOwnPropertyDescriptors(c)):P(Object(c)).forEach(function(r){Object.defineProperty(h,r,Object.getOwnPropertyDescriptor(c,r))})}return h}var U=function(W){return T(T({},W),{},{connect:function(r){var F=r.call;return D(f.mark(function N(){var y,k,J,e;return f.wrap(function(WH){while(!0)switch(WH.prev=WH.next){case 0:return y=new MessageChannel,k=y.port1,J=y.port2,WH.next=1,F("connect",{port:k},[k]);case 1:return e=WH.sent,I.set(J,e),WH.abrupt("return",J);case 2:case"end":return WH.stop()}},N)}))},disconnect:function(r){var F=r.call;return function(){var N=D(f.mark(function y(k){var J;return f.wrap(function(e){while(!0)switch(e.prev=e.next){case 0:if(J=I.get(k),J!==void 0){e.next=1;break}throw Error("The given port is not connected.");case 1:return e.next=2,F("disconnect",{portId:J});case 2:case"end":return e.stop()}},y)}));return function(y){return N.apply(this,arguments)}}()},isSupported:function(r){var F=r.call;return function(){return F("isSupported")}}})};function M(h,W){var c=Object.keys(h);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(h);W&&(r=r.filter(function(F){return Object.getOwnPropertyDescriptor(h,F).enumerable})),c.push.apply(c,r)}return c}function t(h){for(var W=1;W<arguments.length;W++){var c=arguments[W]!=null?arguments[W]:{};W%2?M(Object(c),!0).forEach(function(r){$(h,r,c[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(h,Object.getOwnPropertyDescriptors(c)):M(Object(c)).forEach(function(r){Object.defineProperty(h,r,Object.getOwnPropertyDescriptor(c,r))})}return h}var _=new WeakMap,x=function(W){if(_.has(W))return _.get(W);var c=new Map;return _.set(W,c),c},V=function(W){var c=U(W);return function(r){var F=x(r);if(r.addEventListener("message",function(rH){var tH=rH.data,hH=tH.id;if(hH!==null&&F.has(hH)){var CH=F.get(hH),GH=CH.reject,CA=CH.resolve;if(F.delete(hH),tH.error===void 0)CA(tH.result);else GH(Error(tH.error.message))}}),E(r))r.start();var N=function(tH){var hH=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,CH=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(GH,CA){var k$=L.generateUniqueNumber(F);if(F.set(k$,{reject:CA,resolve:GH}),hH===null)r.postMessage({id:k$,method:tH},CH);else r.postMessage({id:k$,method:tH,params:hH},CH)})},y=function(tH,hH){var CH=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];r.postMessage({id:null,method:tH,params:hH},CH)},k={};for(var J=0,e=Object.entries(c);J<e.length;J++){var WH=A(e[J],2),vH=WH[0],sH=WH[1];k=t(t({},k),{},$({},vH,sH({call:N,notify:y})))}return t({},k)}};H.createBroker=V})});var r9=p((TE,S9)=>{(function(H,$){typeof TE==="object"&&typeof S9<"u"?$(TE,_f(),X9(),rT()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],$):(H=typeof globalThis<"u"?globalThis:H||self,$(H.workerTimersBroker={},H._typeof,H.brokerFactory,H.fastUniqueNumbers))})(TE,function(H,$,A,L){var D=new Map([[0,null]]),f=new Map([[0,null]]),E=A.createBroker({clearInterval:function(T){var U=T.call;return function(M){if($(D.get(M))==="symbol")D.set(M,null),U("clear",{timerId:M,timerType:"interval"}).then(function(){D.delete(M)})}},clearTimeout:function(T){var U=T.call;return function(M){if($(f.get(M))==="symbol")f.set(M,null),U("clear",{timerId:M,timerType:"timeout"}).then(function(){f.delete(M)})}},setInterval:function(T){var U=T.call;return function(M){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var _=arguments.length,x=Array(_>2?_-2:0),V=2;V<_;V++)x[V-2]=arguments[V];var h=Symbol(),W=L.generateUniqueNumber(D);D.set(W,h);var c=function(){return U("set",{delay:t,now:performance.timeOrigin+performance.now(),timerId:W,timerType:"interval"}).then(function(){var F=D.get(W);if(F===void 0)throw Error("The timer is in an undefined state.");if(F===h){if(M.apply(void 0,x),D.get(W)===h)c()}})};return c(),W}},setTimeout:function(T){var U=T.call;return function(M){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var _=arguments.length,x=Array(_>2?_-2:0),V=2;V<_;V++)x[V-2]=arguments[V];var h=Symbol(),W=L.generateUniqueNumber(f);return f.set(W,h),U("set",{delay:t,now:performance.timeOrigin+performance.now(),timerId:W,timerType:"timeout"}).then(function(){var c=f.get(W);if(c===void 0)throw Error("The timer is in an undefined state.");if(c===h)f.delete(W),M.apply(void 0,x)}),W}}}),I=function(T){var U=new Worker(T);return E(U)};H.load=I,H.wrap=E})});var n9=p((UE,B9)=>{(function(H,$){typeof UE==="object"&&typeof B9<"u"?$(UE,r9()):typeof define==="function"&&define.amd?define(["exports","worker-timers-broker"],$):(H=typeof globalThis<"u"?globalThis:H||self,$(H.workerTimers={},H.workerTimersBroker))})(UE,function(H,$){var A=function(U,M){var t=null;return function(){if(t!==null)return t;var _=new Blob([M],{type:"application/javascript; charset=utf-8"}),x=URL.createObjectURL(_);return t=U(x),setTimeout(function(){return URL.revokeObjectURL(x)}),t}},L='(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise(function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)})}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise(function(t){e.set(a,[r(n,s,i,e,t,a),t])})}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark(function e(r){var n,o,u;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark(function e(r){var n,o,u,a,i;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){function u(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n:(u("next",0),u("throw",1),u("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a(\'The requested method called "\'.concat(e,\'" is not supported.\'),u.METHOD_NOT_FOUND)},s=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned no required result.\'),u.INTERNAL_ERROR)},c=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned an unexpected result.\'),u.INTERNAL_ERROR)},f=function(e){return a(\'The specified parameter called "portId" with the given value "\'.concat(e,\'" does not identify a port connected to this worker.\'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark(function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}},t,null,[[1,11]])}));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise(function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])})};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach(function(t){n(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,function(){u(),r.close(),x.delete(a)}),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark(function e(){var t,n,o;return r.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}},e)}));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then(function(e){u("next",e,a,i)},function(e){u("throw",e,a,i)}):r.resolve(c).then(function(e){s.value=e,a(s)},function(e){return u("throw",e,a,i)})}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),o(this,"_invoke",function(e,t,n){function o(){return new r(function(t,r){u(e,n,t,r)})}return a=a?a.then(o,o):o()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a \'"+o+"\' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,function(){return this}),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,function(){return this}),n(v,"toString",function(){return"[object Generator]"}),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();',D=A($.load,L),f=function(U){return D().clearInterval(U)},E=function(U){return D().clearTimeout(U)},I=function(){var U;return(U=D()).setInterval.apply(U,arguments)},P=function(){var U;return(U=D()).setTimeout.apply(U,arguments)};H.clearInterval=f,H.clearTimeout=E,H.setInterval=I,H.setTimeout=P})});var Gf=p((s9)=>{Object.defineProperty(s9,"__esModule",{value:!0});s9.isReactNativeBrowser=s9.isWebWorker=void 0;var ol=()=>{if(typeof window<"u"){if(typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&process?.versions)return!Object.prototype.hasOwnProperty.call(process.versions,"electron");return typeof window.document<"u"}return!1},o9=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),F9=()=>typeof navigator<"u"&&navigator.product==="ReactNative",Fl=ol()||o9()||F9();s9.isWebWorker=o9();s9.isReactNativeBrowser=F9();s9.default=Fl});var a9=p((eA)=>{var il=eA&&eA.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),Gl=eA&&eA.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),dl=eA&&eA.__importStar||function(){var H=function($){return H=Object.getOwnPropertyNames||function(A){var L=[];for(var D in A)if(Object.prototype.hasOwnProperty.call(A,D))L[L.length]=D;return L},H($)};return function($){if($&&$.__esModule)return $;var A={};if($!=null){for(var L=H($),D=0;D<L.length;D++)if(L[D]!=="default")il(A,$,L[D])}return Gl(A,$),A}}();Object.defineProperty(eA,"__esModule",{value:!0});var i9=n9(),dT=dl(Gf()),G9={set:i9.setInterval,clear:i9.clearInterval},d9={set:(H,$)=>setInterval(H,$),clear:(H)=>clearInterval(H)},al=(H)=>{switch(H){case"native":return d9;case"worker":return G9;case"auto":default:return dT.default&&!dT.isWebWorker&&!dT.isReactNativeBrowser?G9:d9}};eA.default=al});var aT=p((df)=>{var ll=df&&df.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(df,"__esModule",{value:!0});var yl=ll(a9());class l9{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(H,$){this.client=H,this.timer=typeof $==="object"&&"set"in $&&"clear"in $?$:(0,yl.default)($),this.setKeepalive(H.options.keepalive)}clear(){if(this.timerId)this.timer.clear(this.timerId),this.timerId=null}setKeepalive(H){if(H*=1000,isNaN(H)||H<=0||H>2147483647)throw Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${H}`);this._keepalive=H,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${H}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let H=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+H,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{if(this.destroyed)return;if(this.counter+=1,this.counter===2)this.client.sendPing();else if(this.counter>2)this.client.onKeepaliveTimeout()},this._intervalEvery)}}df.default=l9});var tE=p((q$)=>{var bl=q$&&q$.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),Nl=q$&&q$.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),R9=q$&&q$.__importStar||function(){var H=function($){return H=Object.getOwnPropertyNames||function(A){var L=[];for(var D in A)if(Object.prototype.hasOwnProperty.call(A,D))L[L.length]=D;return L},H($)};return function($){if($&&$.__esModule)return $;var A={};if($!=null){for(var L=H($),D=0;D<L.length;D++)if(L[D]!=="default")bl(A,$,L[D])}return Nl(A,$),A}}(),EL=q$&&q$.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(q$,"__esModule",{value:!0});var lT=EL(Q0()),kl=HL(),y9=EL(G1()),Rl=EL(K$()),b9=R9(l1()),hD=EL(ET()),Ol=EL(ix()),ml=EL(cT()),wl=EL(yx()),af=aL(),el=bx(),jl=EL(aT()),N9=R9(Gf()),yT=globalThis.setImmediate||((...H)=>{let $=H.shift();(0,af.nextTick)(()=>{$(...H)})}),k9={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1000,connectTimeout:30000,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class ME extends el.TypedEventEmitter{static VERSION=af.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(H,$){super();this.options=$||{};for(let A in k9)if(typeof this.options[A]>"u")this.options[A]=k9[A];else this.options[A]=$[A];if(this.log=this.options.log||(0,Rl.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",ME.VERSION),N9.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",N9.default?"browser":"node");if(this.log("MqttClient :: options.protocol",$.protocol),this.log("MqttClient :: options.protocolVersion",$.protocolVersion),this.log("MqttClient :: options.username",$.username),this.log("MqttClient :: options.keepalive",$.keepalive),this.log("MqttClient :: options.reconnectPeriod",$.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",$.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",$.properties?$.properties.topicAliasMaximum:void 0),this.options.clientId=typeof $.clientId==="string"?$.clientId:ME.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=$.protocolVersion===5&&$.customHandleAcks?$.customHandleAcks:(...A)=>{A[3](null,0)},!this.options.writeCache)lT.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=H,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new ml.default:this.options.messageIdProvider,this.outgoingStore=$.outgoingStore||new hD.default,this.incomingStore=$.incomingStore||new hD.default,this.queueQoSZero=$.queueQoSZero===void 0?!0:$.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,$.properties&&$.properties.topicAliasMaximum>0)if($.properties.topicAliasMaximum>65535)this.log("MqttClient :: options.properties.topicAliasMaximum is out of range");else this.topicAliasRecv=new wl.default($.properties.topicAliasMaximum);if(this.on("connect",()=>{let{queue:A}=this,L=()=>{let D=A.shift();this.log("deliver :: entry %o",D);let f=null;if(!D){this._resubscribe();return}f=D.packet,this.log("deliver :: call _sendPacket for %o",f);let E=!0;if(f.messageId&&f.messageId!==0){if(!this.messageIdProvider.register(f.messageId))E=!1}if(E)this._sendPacket(f,(I)=>{if(D.cb)D.cb(I);L()});else this.log("messageId: %d has already used. The message is skipped and removed.",f.messageId),L()};this.log("connect :: sending queued packets"),L()}),this.on("close",()=>{if(this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv)this.topicAliasRecv.clear();this.log("close :: calling _setupReconnect"),this._setupReconnect()}),!this.options.manualConnect)this.log("MqttClient :: setting up stream"),this.connect()}handleAuth(H,$){$()}handleMessage(H,$){$()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let H=new kl.Writable,$=lT.default.parser(this.options),A=null,L=[];if(this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting)this.incomingStore=this.options.incomingStore||new hD.default,this.outgoingStore=this.options.outgoingStore||new hD.default,this.disconnecting=!1,this.disconnected=!1;this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),$.on("packet",(P)=>{this.log("parser :: on packet push to packets array."),L.push(P)});let D=()=>{this.log("work :: getting next packet in queue");let P=L.shift();if(P)this.log("work :: packet pulled from queue"),(0,Ol.default)(this,P,f);else{this.log("work :: no packets in queue");let T=A;if(A=null,this.log("work :: done flag is %s",!!T),T)T()}},f=()=>{if(L.length)(0,af.nextTick)(D);else{let P=A;A=null,P()}};H._write=(P,T,U)=>{A=U,this.log("writable stream :: parsing buffer"),$.parse(P),D()};let E=(P)=>{if(this.log("streamErrorHandler :: error",P.message),P.code)this.log("streamErrorHandler :: emitting error"),this.emit("error",P);else this.noop(P)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(H),this.stream.on("error",E),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let I={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will)I.will={...this.options.will,payload:this.options.will?.payload};if(this.topicAliasRecv){if(!I.properties)I.properties={};if(this.topicAliasRecv)I.properties.topicAliasMaximum=this.topicAliasRecv.max}if(this._writePacket(I),$.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket==="object"){let P={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(P)}}return this.stream.setMaxListeners(1000),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(H,$,A,L){this.log("publish :: message `%s` to topic `%s`",$,H);let{options:D}=this;if(typeof A==="function")L=A,A=null;A=A||{},A={...{qos:0,retain:!1,dup:!1},...A};let{qos:E,retain:I,dup:P,properties:T,cbStorePut:U}=A;if(this._checkDisconnecting(L))return this;let M=()=>{let t=0;if(E===1||E===2){if(t=this._nextId(),t===null)return this.log("No messageId left"),!1}let _={cmd:"publish",topic:H,payload:$,qos:E,retain:I,messageId:t,dup:P};if(D.protocolVersion===5)_.properties=T;switch(this.log("publish :: qos",E),E){case 1:case 2:this.outgoing[_.messageId]={volatile:!1,cb:L||this.noop},this.log("MqttClient:publish: packet cmd: %s",_.cmd),this._sendPacket(_,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",_.cmd),this._sendPacket(_,L,U);break}return!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!M())this._storeProcessingQueue.push({invoke:M,cbStorePut:A.cbStorePut,callback:L});return this}publishAsync(H,$,A){return new Promise((L,D)=>{this.publish(H,$,A,(f,E)=>{if(f)D(f);else L(E)})})}subscribe(H,$,A){let L=this.options.protocolVersion;if(typeof $==="function")A=$;A=A||this.noop;let D=!1,f=[];if(typeof H==="string")H=[H],f=H;else if(Array.isArray(H))f=H;else if(typeof H==="object")D=H.resubscribe,delete H.resubscribe,f=Object.keys(H);let E=b9.validateTopics(f);if(E!==null)return yT(A,Error(`Invalid topic ${E}`)),this;if(this._checkDisconnecting(A))return this.log("subscribe: discconecting true"),this;let I={qos:0};if(L===5)I.nl=!1,I.rap=!1,I.rh=0;$={...I,...$};let{properties:P}=$,T=[],U=(_,x)=>{if(x=x||$,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,_)||this._resubscribeTopics[_].qos<x.qos||D){let V={topic:_,qos:x.qos};if(L===5)V.nl=x.nl,V.rap=x.rap,V.rh=x.rh,V.properties=P;this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",V.topic,V.qos),T.push(V)}};if(Array.isArray(H))H.forEach((_)=>{this.log("subscribe: array topic %s",_),U(_)});else Object.keys(H).forEach((_)=>{this.log("subscribe: object topic %s, %o",_,H[_]),U(_,H[_])});if(!T.length)return A(null,[]),this;let M=(_,x)=>{let V={cmd:"subscribe",subscriptions:_,messageId:x};if(P)V.properties=P;if(this.options.resubscribe){this.log("subscribe :: resubscribe true");let W=[];_.forEach((c)=>{if(this.options.reconnectPeriod>0){let r={qos:c.qos};if(L===5)r.nl=c.nl||!1,r.rap=c.rap||!1,r.rh=c.rh||0,r.properties=c.properties;this._resubscribeTopics[c.topic]=r,W.push(c.topic)}}),this.messageIdToTopic[V.messageId]=W}let h=new Promise((W,c)=>{this.outgoing[V.messageId]={volatile:!0,cb(r,F){if(!r){let{granted:N}=F;for(let y=0;y<N.length;y+=1)_[y].qos=N[y]}if(!r)W(F);else c(new af.ErrorWithSubackPacket(r.message,F))}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(V),h},t=()=>{let _=this.options.subscribeBatchSize??T.length,x=[];for(let V=0;V<T.length;V+=_){let h=T.slice(V,V+_),W=this._nextId();if(W===null)return this.log("No messageId left"),!1;x.push(M(h,W))}return Promise.all(x).then((V)=>{A(null,T,V.at(-1))}).catch((V)=>{A(V,T,V.packet)}),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!t())this._storeProcessingQueue.push({invoke:t,callback:A});return this}subscribeAsync(H,$){return new Promise((A,L)=>{this.subscribe(H,$,(D,f)=>{if(D)L(D);else A(f)})})}unsubscribe(H,$,A){if(typeof H==="string")H=[H];if(typeof $==="function")A=$;A=A||this.noop;let L=b9.validateTopics(H);if(L!==null)return yT(A,Error(`Invalid topic ${L}`)),this;if(this._checkDisconnecting(A))return this;let D=()=>{let f=this._nextId();if(f===null)return this.log("No messageId left"),!1;let E={cmd:"unsubscribe",messageId:f,unsubscriptions:[]};if(typeof H==="string")E.unsubscriptions=[H];else if(Array.isArray(H))E.unsubscriptions=H;if(this.options.resubscribe)E.unsubscriptions.forEach((I)=>{delete this._resubscribeTopics[I]});if(typeof $==="object"&&$.properties)E.properties=$.properties;return this.outgoing[E.messageId]={volatile:!0,cb:A},this.log("unsubscribe: call _sendPacket"),this._sendPacket(E),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!D())this._storeProcessingQueue.push({invoke:D,callback:A});return this}unsubscribeAsync(H,$){return new Promise((A,L)=>{this.unsubscribe(H,$,(D,f)=>{if(D)L(D);else A(f)})})}end(H,$,A){if(this.log("end :: (%s)",this.options.clientId),H==null||typeof H!=="boolean")A=A||$,$=H,H=!1;if(typeof $!=="object")A=A||$,$=null;if(this.log("end :: cb? %s",!!A),!A||typeof A!=="function")A=this.noop;let L=()=>{if(this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close((f)=>{this.outgoingStore.close((E)=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),A){let I=f||E;this.log("end :: closeStores: invoking callback with args"),A(I)}})}),this._deferredReconnect)this._deferredReconnect();else if(this.options.reconnectPeriod===0||this.options.manualConnect)this.disconnecting=!1},D=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,H),this._cleanUp(H,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,af.nextTick)(L)},$)};if(this.disconnecting)return A(),this;if(this._clearReconnect(),this.disconnecting=!0,!H&&Object.keys(this.outgoing).length>0)this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,D,10));else this.log("end :: (%s) :: immediately calling finish",this.options.clientId),D();return this}endAsync(H,$){return new Promise((A,L)=>{this.end(H,$,(D)=>{if(D)L(D);else A()})})}removeOutgoingMessage(H){if(this.outgoing[H]){let{cb:$}=this.outgoing[H];this._removeOutgoingAndStoreMessage(H,()=>{$(Error("Message removed"))})}return this}reconnect(H){this.log("client reconnect");let $=()=>{if(H)this.options.incomingStore=H.incomingStore,this.options.outgoingStore=H.outgoingStore;else this.options.incomingStore=null,this.options.outgoingStore=null;this.incomingStore=this.options.incomingStore||new hD.default,this.outgoingStore=this.options.outgoingStore||new hD.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};if(this.disconnecting&&!this.disconnected)this._deferredReconnect=$;else $();return this}_flushVolatile(){if(this.outgoing)this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach((H)=>{if(this.outgoing[H].volatile&&typeof this.outgoing[H].cb==="function")this.outgoing[H].cb(Error("Connection closed")),delete this.outgoing[H]})}_flush(){if(this.outgoing)this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach((H)=>{if(typeof this.outgoing[H].cb==="function")this.outgoing[H].cb(Error("Connection closed")),delete this.outgoing[H]})}_removeTopicAliasAndRecoverTopicName(H){let $;if(H.properties)$=H.properties.topicAlias;let A=H.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",$,A),A.length===0){if(typeof $>"u")return Error("Unregistered Topic Alias");if(A=this.topicAliasSend.getTopicByAlias($),typeof A>"u")return Error("Unregistered Topic Alias");H.topic=A}if($)delete H.properties.topicAlias}_checkDisconnecting(H){if(this.disconnecting)if(H&&H!==this.noop)H(Error("client disconnecting"));else this.emit("error",Error("client disconnecting"));return this.disconnecting}_reconnect(){if(this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected)this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.");else this.log("_reconnect: calling connect"),this.connect()}_setupReconnect(){if(!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0){if(!this.reconnecting)this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0;this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)}else this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){if(this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer)clearInterval(this.reconnectTimer),this.reconnectTimer=null}_cleanUp(H,$,A={}){if($)this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",$);if(this.log("_cleanUp :: forced? %s",H),H){if(this.options.reconnectPeriod===0&&this.options.clean)this._flush();this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy()}else{let L={cmd:"disconnect",...A};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(L,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),yT(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}if(!this.disconnecting&&!this.reconnecting)this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect();if(this._destroyKeepaliveManager(),$&&!this.connected)this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",$),$()}_storeAndSend(H,$,A){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",H.cmd);let L=H,D;if(L.cmd==="publish"){if(L=(0,y9.default)(H),D=this._removeTopicAliasAndRecoverTopicName(L),D)return $&&$(D)}this.outgoingStore.put(L,(f)=>{if(f)return $&&$(f);A(),this._writePacket(H,$)})}_applyTopicAlias(H){if(this.options.protocolVersion===5){if(H.cmd==="publish"){let $;if(H.properties)$=H.properties.topicAlias;let A=H.topic.toString();if(this.topicAliasSend){if($){if(A.length!==0){if(this.log("applyTopicAlias :: register topic: %s - alias: %d",A,$),!this.topicAliasSend.put(A,$))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,$),Error("Sending Topic Alias out of range")}}else if(A.length!==0){if(this.options.autoAssignTopicAlias)if($=this.topicAliasSend.getAliasByTopic(A),$)H.topic="",H.properties={...H.properties,topicAlias:$},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",A,$);else $=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(A,$),H.properties={...H.properties,topicAlias:$},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",A,$);else if(this.options.autoUseTopicAlias){if($=this.topicAliasSend.getAliasByTopic(A),$)H.topic="",H.properties={...H.properties,topicAlias:$},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",A,$)}}}else if($)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,$),Error("Sending Topic Alias out of range")}}}_noop(H){this.log("noop ::",H)}_writePacket(H,$){this.log("_writePacket :: packet: %O",H),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",H),this.log("_writePacket :: writing to stream");let A=lT.default.writeToStream(H,this.stream,this.options);if(this.log("_writePacket :: writeToStream result %s",A),!A&&$&&$!==this.noop)this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",$);else if($)this.log("_writePacket :: invoking cb"),$()}_sendPacket(H,$,A,L){this.log("_sendPacket :: (%s) :: start",this.options.clientId),A=A||this.noop,$=$||this.noop;let D=this._applyTopicAlias(H);if(D){$(D);return}if(!this.connected){if(H.cmd==="auth"){this._writePacket(H,$);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(H,$,A);return}if(L){this._writePacket(H,$);return}switch(H.cmd){case"publish":break;case"pubrel":this._storeAndSend(H,$,A);return;default:this._writePacket(H,$);return}switch(H.qos){case 2:case 1:this._storeAndSend(H,$,A);break;case 0:default:this._writePacket(H,$);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(H,$,A){this.log("_storePacket :: packet: %o",H),this.log("_storePacket :: cb? %s",!!$),A=A||this.noop;let L=H;if(L.cmd==="publish"){L=(0,y9.default)(H);let f=this._removeTopicAliasAndRecoverTopicName(L);if(f)return $&&$(f)}let D=L.qos||0;if(D===0&&this.queueQoSZero||L.cmd!=="publish")this.queue.push({packet:L,cb:$});else if(D>0)$=this.outgoing[L.messageId]?this.outgoing[L.messageId].cb:null,this.outgoingStore.put(L,(f)=>{if(f)return $&&$(f);A()});else if($)$(Error("No connection to broker"))}_setupKeepaliveManager(){if(this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive)this.keepaliveManager=new jl.default(this,this.options.timerVariant)}_destroyKeepaliveManager(){if(this.keepaliveManager)this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null}reschedulePing(H=!1){if(this.keepaliveManager&&this.options.keepalive&&(H||this.options.reschedulePings))this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let H=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&H.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let $=0;$<H.length;$++){let A={};A[H[$]]=this._resubscribeTopics[H[$]],A.resubscribe=!0,this.subscribe(A,{properties:A[H[$]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(H){if(this.disconnected){this.emit("connect",H);return}this.connackPacket=H,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let $=()=>{let A=this.outgoingStore.createStream(),L=()=>{A.destroy(),A=null,this._flushStoreProcessingQueue(),D()},D=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",L),A.on("error",(E)=>{D(),this._flushStoreProcessingQueue(),this.removeListener("close",L),this.emit("error",E)});let f=()=>{if(!A)return;let E=A.read(1),I;if(!E){A.once("readable",f);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[E.messageId]){f();return}if(!this.disconnecting&&!this.reconnectTimer)if(I=this.outgoing[E.messageId]?this.outgoing[E.messageId].cb:null,this.outgoing[E.messageId]={volatile:!1,cb(P,T){if(I)I(P,T);f()}},this._packetIdsDuringStoreProcessing[E.messageId]=!0,this.messageIdProvider.register(E.messageId))this._sendPacket(E,void 0,void 0,!0);else this.log("messageId: %d has already used.",E.messageId);else if(A.destroy)A.destroy()};A.on("end",()=>{let E=!0;for(let I in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[I]){E=!1;break}if(this.removeListener("close",L),E)D(),this._invokeAllStoreProcessingQueue(),this.emit("connect",H);else $()}),f()};$()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let H=this._storeProcessingQueue[0];if(H&&H.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){while(this._invokeStoreProcessingQueue());}_flushStoreProcessingQueue(){for(let H of this._storeProcessingQueue){if(H.cbStorePut)H.cbStorePut(Error("Connection closed"));if(H.callback)H.callback(Error("Connection closed"))}this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(H,$){delete this.outgoing[H],this.outgoingStore.del({messageId:H},(A,L)=>{$(A,L),this.messageIdProvider.deallocate(H),this._invokeStoreProcessingQueue()})}}q$.default=ME});var w9=p((m9)=>{Object.defineProperty(m9,"__esModule",{value:!0});var Jl=hT();class O9{numberAllocator;lastId;constructor(){this.numberAllocator=new Jl.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(H){return this.numberAllocator.use(H)}deallocate(H){this.numberAllocator.free(H)}clear(){this.numberAllocator.clear()}}m9.default=O9});var _E=p((Q9)=>{Object.defineProperty(Q9,"__esModule",{value:!0});Q9.BufferedDuplex=void 0;Q9.writev=j9;var Kl=HL(),e9=B("buffer");function j9(H,$){let A=Array(H.length);for(let L=0;L<H.length;L++)if(typeof H[L].chunk==="string")A[L]=e9.Buffer.from(H[L].chunk,"utf8");else A[L]=H[L].chunk;this._write(e9.Buffer.concat(A),"binary",$)}class J9 extends Kl.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(H,$,A){super({objectMode:!0});if(this.proxy=$,this.socket=A,this.writeQueue=[],!H.objectMode)this._writev=j9.bind(this);this.isSocketOpen=!1,this.proxy.on("data",(L)=>{if(!this.destroyed&&this.readable)this.push(L)})}_read(H){this.proxy.read(H)}_write(H,$,A){if(!this.isSocketOpen)this.writeQueue.push({chunk:H,encoding:$,cb:A});else this.writeToProxy(H,$,A)}_final(H){this.writeQueue=[],this.proxy.end(H)}_destroy(H,$){this.writeQueue=[],this.proxy.destroy(),$(H)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(H,$,A){if(this.proxy.write(H,$)===!1)this.proxy.once("drain",A);else A()}processWriteQueue(){while(this.writeQueue.length>0){let{chunk:H,encoding:$,cb:A}=this.writeQueue.shift();this.writeToProxy(H,$,A)}}}Q9.BufferedDuplex=J9});var lf=p((PL)=>{var NT=PL&&PL.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(PL,"__esModule",{value:!0});PL.streamBuilder=PL.browserStreamBuilder=void 0;var pE=B("buffer"),g9=NT(B("ws")),vl=NT(K$()),Yl=HL(),ql=NT(Gf()),bT=_E(),IL=(0,vl.default)("mqttjs:ws"),Zl=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function v9(H,$){let A=`${H.protocol}://${H.hostname}:${H.port}${H.path}`;if(typeof H.transformWsUrl==="function")A=H.transformWsUrl(A,H,$);return A}function Y9(H){let $=H;if(!H.port)if(H.protocol==="wss")$.port=443;else $.port=80;if(!H.path)$.path="/";if(!H.wsOptions)$.wsOptions={};if(!ql.default&&!H.forceNativeWebSocket&&H.protocol==="wss")Zl.forEach((A)=>{if(Object.prototype.hasOwnProperty.call(H,A)&&!Object.prototype.hasOwnProperty.call(H.wsOptions,A))$.wsOptions[A]=H[A]});return $}function zl(H){let $=Y9(H);if(!$.hostname)$.hostname=$.host;if(!$.hostname){if(typeof document>"u")throw Error("Could not determine host. Specify host manually.");let A=new URL(document.URL);if($.hostname=A.hostname,!$.port)$.port=Number(A.port)}if($.objectMode===void 0)$.objectMode=!($.binary===!0||$.binary===void 0);return $}function Hy(H,$,A){IL("createWebSocket"),IL(`protocol: ${A.protocolId} ${A.protocolVersion}`);let L=A.protocolId==="MQIsdp"&&A.protocolVersion===3?"mqttv3.1":"mqtt";IL(`creating new Websocket for url: ${$} and protocol: ${L}`);let D;if(A.createWebsocket)D=A.createWebsocket($,[L],A);else D=new g9.default($,[L],A.wsOptions);return D}function $y(H,$){let A=$.protocolId==="MQIsdp"&&$.protocolVersion===3?"mqttv3.1":"mqtt",L=v9($,H),D;if($.createWebsocket)D=$.createWebsocket(L,[A],$);else D=new WebSocket(L,[A]);return D.binaryType="arraybuffer",D}var Ay=(H,$)=>{IL("streamBuilder");let A=Y9($);A.hostname=A.hostname||A.host||"localhost";let L=v9(A,H),D=Hy(H,L,A),f=g9.default.createWebSocketStream(D,A.wsOptions);return f.url=L,D.on("close",()=>{f.destroy()}),f};PL.streamBuilder=Ay;var Ly=(H,$)=>{IL("browserStreamBuilder");let A,D=zl($).browserBufferSize||524288,f=$.browserBufferTimeout||1000,E=!$.objectMode,I=$y(H,$),P=U($,V,h);if(!$.objectMode)P._writev=bT.writev.bind(P);P.on("close",()=>{I.close()});let T=typeof I.addEventListener<"u";if(I.readyState===I.OPEN)A=P,A.socket=I;else if(A=new bT.BufferedDuplex($,P,I),T)I.addEventListener("open",M);else I.onopen=M;if(T)I.addEventListener("close",t),I.addEventListener("error",_),I.addEventListener("message",x);else I.onclose=t,I.onerror=_,I.onmessage=x;function U(W,c,r){let F=new Yl.Transform({objectMode:W.objectMode});return F._write=c,F._flush=r,F}function M(){if(IL("WebSocket onOpen"),A instanceof bT.BufferedDuplex)A.socketReady()}function t(W){IL("WebSocket onClose",W),A.end(),A.destroy()}function _(W){IL("WebSocket onError",W);let c=Error("WebSocket error");c.event=W,A.destroy(c)}async function x(W){if(!P||!P.readable||!P.writable)return;let{data:c}=W;if(c instanceof ArrayBuffer)c=pE.Buffer.from(c);else if(c instanceof Blob)c=pE.Buffer.from(await new Response(c).arrayBuffer());else c=pE.Buffer.from(c,"utf8");P.push(c)}function V(W,c,r){if(I.bufferedAmount>D){setTimeout(V,f,W,c,r);return}if(E&&typeof W==="string")W=pE.Buffer.from(W,"utf8");try{I.send(W)}catch(F){return r(F)}r()}function h(W){I.close(),W()}return A};PL.browserStreamBuilder=Ly});var $h=p((Hh)=>{Object.defineProperty(Hh,"__esModule",{value:!0});var q9=B("buffer"),OL={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};Hh.ERRORS=OL;function Dy(H){if(!q9.Buffer.isEncoding(H))throw Error(OL.INVALID_ENCODING)}Hh.checkEncoding=Dy;function Z9(H){return typeof H==="number"&&isFinite(H)&&Py(H)}Hh.isFiniteInteger=Z9;function z9(H,$){if(typeof H==="number"){if(!Z9(H)||H<0)throw Error($?OL.INVALID_OFFSET:OL.INVALID_LENGTH)}else throw Error($?OL.INVALID_OFFSET_NON_NUMBER:OL.INVALID_LENGTH_NON_NUMBER)}function fy(H){z9(H,!1)}Hh.checkLengthValue=fy;function Ey(H){z9(H,!0)}Hh.checkOffsetValue=Ey;function Iy(H,$){if(H<0||H>$.length)throw Error(OL.INVALID_TARGET_OFFSET)}Hh.checkTargetOffset=Iy;function Py(H){return typeof H==="number"&&isFinite(H)&&Math.floor(H)===H}function Ty(H){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof q9.Buffer.prototype[H]>"u")throw Error(`Platform does not support Buffer.prototype.${H}.`)}Hh.bigIntAndBufferInt64Check=Ty});var Dh=p((Lh)=>{Object.defineProperty(Lh,"__esModule",{value:!0});var Z=$h(),Ah=4096,uy="utf8";class kT{constructor(H){if(this.length=0,this._encoding=uy,this._writeOffset=0,this._readOffset=0,kT.isSmartBufferOptions(H)){if(H.encoding)Z.checkEncoding(H.encoding),this._encoding=H.encoding;if(H.size)if(Z.isFiniteInteger(H.size)&&H.size>0)this._buff=Buffer.allocUnsafe(H.size);else throw Error(Z.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(H.buff)if(Buffer.isBuffer(H.buff))this._buff=H.buff,this.length=H.buff.length;else throw Error(Z.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(Ah)}else{if(typeof H<"u")throw Error(Z.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(Ah)}}static fromSize(H,$){return new this({size:H,encoding:$})}static fromBuffer(H,$){return new this({buff:H,encoding:$})}static fromOptions(H){return new this(H)}static isSmartBufferOptions(H){let $=H;return $&&($.encoding!==void 0||$.size!==void 0||$.buff!==void 0)}readInt8(H){return this._readNumberValue(Buffer.prototype.readInt8,1,H)}readInt16BE(H){return this._readNumberValue(Buffer.prototype.readInt16BE,2,H)}readInt16LE(H){return this._readNumberValue(Buffer.prototype.readInt16LE,2,H)}readInt32BE(H){return this._readNumberValue(Buffer.prototype.readInt32BE,4,H)}readInt32LE(H){return this._readNumberValue(Buffer.prototype.readInt32LE,4,H)}readBigInt64BE(H){return Z.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,H)}readBigInt64LE(H){return Z.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,H)}writeInt8(H,$){return this._writeNumberValue(Buffer.prototype.writeInt8,1,H,$),this}insertInt8(H,$){return this._insertNumberValue(Buffer.prototype.writeInt8,1,H,$)}writeInt16BE(H,$){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,H,$)}insertInt16BE(H,$){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,H,$)}writeInt16LE(H,$){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,H,$)}insertInt16LE(H,$){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,H,$)}writeInt32BE(H,$){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,H,$)}insertInt32BE(H,$){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,H,$)}writeInt32LE(H,$){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,H,$)}insertInt32LE(H,$){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,H,$)}writeBigInt64BE(H,$){return Z.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,H,$)}insertBigInt64BE(H,$){return Z.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,H,$)}writeBigInt64LE(H,$){return Z.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,H,$)}insertBigInt64LE(H,$){return Z.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,H,$)}readUInt8(H){return this._readNumberValue(Buffer.prototype.readUInt8,1,H)}readUInt16BE(H){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,H)}readUInt16LE(H){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,H)}readUInt32BE(H){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,H)}readUInt32LE(H){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,H)}readBigUInt64BE(H){return Z.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,H)}readBigUInt64LE(H){return Z.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,H)}writeUInt8(H,$){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,H,$)}insertUInt8(H,$){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,H,$)}writeUInt16BE(H,$){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,H,$)}insertUInt16BE(H,$){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,H,$)}writeUInt16LE(H,$){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,H,$)}insertUInt16LE(H,$){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,H,$)}writeUInt32BE(H,$){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,H,$)}insertUInt32BE(H,$){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,H,$)}writeUInt32LE(H,$){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,H,$)}insertUInt32LE(H,$){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,H,$)}writeBigUInt64BE(H,$){return Z.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,H,$)}insertBigUInt64BE(H,$){return Z.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,H,$)}writeBigUInt64LE(H,$){return Z.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,H,$)}insertBigUInt64LE(H,$){return Z.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,H,$)}readFloatBE(H){return this._readNumberValue(Buffer.prototype.readFloatBE,4,H)}readFloatLE(H){return this._readNumberValue(Buffer.prototype.readFloatLE,4,H)}writeFloatBE(H,$){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,H,$)}insertFloatBE(H,$){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,H,$)}writeFloatLE(H,$){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,H,$)}insertFloatLE(H,$){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,H,$)}readDoubleBE(H){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,H)}readDoubleLE(H){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,H)}writeDoubleBE(H,$){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,H,$)}insertDoubleBE(H,$){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,H,$)}writeDoubleLE(H,$){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,H,$)}insertDoubleLE(H,$){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,H,$)}readString(H,$){let A;if(typeof H==="number")Z.checkLengthValue(H),A=Math.min(H,this.length-this._readOffset);else $=H,A=this.length-this._readOffset;if(typeof $<"u")Z.checkEncoding($);let L=this._buff.slice(this._readOffset,this._readOffset+A).toString($||this._encoding);return this._readOffset+=A,L}insertString(H,$,A){return Z.checkOffsetValue($),this._handleString(H,!0,$,A)}writeString(H,$,A){return this._handleString(H,!1,$,A)}readStringNT(H){if(typeof H<"u")Z.checkEncoding(H);let $=this.length;for(let L=this._readOffset;L<this.length;L++)if(this._buff[L]===0){$=L;break}let A=this._buff.slice(this._readOffset,$);return this._readOffset=$+1,A.toString(H||this._encoding)}insertStringNT(H,$,A){return Z.checkOffsetValue($),this.insertString(H,$,A),this.insertUInt8(0,$+H.length),this}writeStringNT(H,$,A){return this.writeString(H,$,A),this.writeUInt8(0,typeof $==="number"?$+H.length:this.writeOffset),this}readBuffer(H){if(typeof H<"u")Z.checkLengthValue(H);let $=typeof H==="number"?H:this.length,A=Math.min(this.length,this._readOffset+$),L=this._buff.slice(this._readOffset,A);return this._readOffset=A,L}insertBuffer(H,$){return Z.checkOffsetValue($),this._handleBuffer(H,!0,$)}writeBuffer(H,$){return this._handleBuffer(H,!1,$)}readBufferNT(){let H=this.length;for(let A=this._readOffset;A<this.length;A++)if(this._buff[A]===0){H=A;break}let $=this._buff.slice(this._readOffset,H);return this._readOffset=H+1,$}insertBufferNT(H,$){return Z.checkOffsetValue($),this.insertBuffer(H,$),this.insertUInt8(0,$+H.length),this}writeBufferNT(H,$){if(typeof $<"u")Z.checkOffsetValue($);return this.writeBuffer(H,$),this.writeUInt8(0,typeof $==="number"?$+H.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(H){Z.checkOffsetValue(H),Z.checkTargetOffset(H,this),this._readOffset=H}get writeOffset(){return this._writeOffset}set writeOffset(H){Z.checkOffsetValue(H),Z.checkTargetOffset(H,this),this._writeOffset=H}get encoding(){return this._encoding}set encoding(H){Z.checkEncoding(H),this._encoding=H}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(H){let $=typeof H==="string"?H:this._encoding;return Z.checkEncoding($),this._buff.toString($,0,this.length)}destroy(){return this.clear(),this}_handleString(H,$,A,L){let D=this._writeOffset,f=this._encoding;if(typeof A==="number")D=A;else if(typeof A==="string")Z.checkEncoding(A),f=A;if(typeof L==="string")Z.checkEncoding(L),f=L;let E=Buffer.byteLength(H,f);if($)this.ensureInsertable(E,D);else this._ensureWriteable(E,D);if(this._buff.write(H,D,E,f),$)this._writeOffset+=E;else if(typeof A==="number")this._writeOffset=Math.max(this._writeOffset,D+E);else this._writeOffset+=E;return this}_handleBuffer(H,$,A){let L=typeof A==="number"?A:this._writeOffset;if($)this.ensureInsertable(H.length,L);else this._ensureWriteable(H.length,L);if(H.copy(this._buff,L),$)this._writeOffset+=H.length;else if(typeof A==="number")this._writeOffset=Math.max(this._writeOffset,L+H.length);else this._writeOffset+=H.length;return this}ensureReadable(H,$){let A=this._readOffset;if(typeof $<"u")Z.checkOffsetValue($),A=$;if(A<0||A+H>this.length)throw Error(Z.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(H,$){if(Z.checkOffsetValue($),this._ensureCapacity(this.length+H),$<this.length)this._buff.copy(this._buff,$+H,$,this._buff.length);if($+H>this.length)this.length=$+H;else this.length+=H}_ensureWriteable(H,$){let A=typeof $==="number"?$:this._writeOffset;if(this._ensureCapacity(A+H),A+H>this.length)this.length=A+H}_ensureCapacity(H){let $=this._buff.length;if(H>$){let A=this._buff,L=$*3/2+1;if(L<H)L=H;this._buff=Buffer.allocUnsafe(L),A.copy(this._buff,0,0,$)}}_readNumberValue(H,$,A){this.ensureReadable($,A);let L=H.call(this._buff,typeof A==="number"?A:this._readOffset);if(typeof A>"u")this._readOffset+=$;return L}_insertNumberValue(H,$,A,L){return Z.checkOffsetValue(L),this.ensureInsertable($,L),H.call(this._buff,A,L),this._writeOffset+=$,this}_writeNumberValue(H,$,A,L){if(typeof L==="number"){if(L<0)throw Error(Z.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);Z.checkOffsetValue(L)}let D=typeof L==="number"?L:this._writeOffset;if(this._ensureWriteable($,D),H.call(this._buff,A,D),typeof L==="number")this._writeOffset=Math.max(this._writeOffset,D+$);else this._writeOffset+=$;return this}}Lh.SmartBuffer=kT});var RT=p((Mh)=>{Object.defineProperty(Mh,"__esModule",{value:!0});Mh.SOCKS5_NO_ACCEPTABLE_AUTH=Mh.SOCKS5_CUSTOM_AUTH_END=Mh.SOCKS5_CUSTOM_AUTH_START=Mh.SOCKS_INCOMING_PACKET_SIZES=Mh.SocksClientState=Mh.Socks5Response=Mh.Socks5HostType=Mh.Socks5Auth=Mh.Socks4Response=Mh.SocksCommand=Mh.ERRORS=Mh.DEFAULT_TIMEOUT=void 0;var hy=30000;Mh.DEFAULT_TIMEOUT=hy;var cy={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};Mh.ERRORS=cy;var Xy={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(H)=>H+7,Socks4Response:8};Mh.SOCKS_INCOMING_PACKET_SIZES=Xy;var fh;(function(H){H[H.connect=1]="connect",H[H.bind=2]="bind",H[H.associate=3]="associate"})(fh||(Mh.SocksCommand=fh={}));var Eh;(function(H){H[H.Granted=90]="Granted",H[H.Failed=91]="Failed",H[H.Rejected=92]="Rejected",H[H.RejectedIdent=93]="RejectedIdent"})(Eh||(Mh.Socks4Response=Eh={}));var Ih;(function(H){H[H.NoAuth=0]="NoAuth",H[H.GSSApi=1]="GSSApi",H[H.UserPass=2]="UserPass"})(Ih||(Mh.Socks5Auth=Ih={}));var Sy=128;Mh.SOCKS5_CUSTOM_AUTH_START=Sy;var ry=254;Mh.SOCKS5_CUSTOM_AUTH_END=ry;var By=255;Mh.SOCKS5_NO_ACCEPTABLE_AUTH=By;var Ph;(function(H){H[H.Granted=0]="Granted",H[H.Failure=1]="Failure",H[H.NotAllowed=2]="NotAllowed",H[H.NetworkUnreachable=3]="NetworkUnreachable",H[H.HostUnreachable=4]="HostUnreachable",H[H.ConnectionRefused=5]="ConnectionRefused",H[H.TTLExpired=6]="TTLExpired",H[H.CommandNotSupported=7]="CommandNotSupported",H[H.AddressNotSupported=8]="AddressNotSupported"})(Ph||(Mh.Socks5Response=Ph={}));var Th;(function(H){H[H.IPv4=1]="IPv4",H[H.Hostname=3]="Hostname",H[H.IPv6=4]="IPv6"})(Th||(Mh.Socks5HostType=Th={}));var Uh;(function(H){H[H.Created=0]="Created",H[H.Connecting=1]="Connecting",H[H.Connected=2]="Connected",H[H.SentInitialHandshake=3]="SentInitialHandshake",H[H.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",H[H.SentAuthentication=5]="SentAuthentication",H[H.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",H[H.SentFinalHandshake=7]="SentFinalHandshake",H[H.ReceivedFinalResponse=8]="ReceivedFinalResponse",H[H.BoundWaitingForConnection=9]="BoundWaitingForConnection",H[H.Established=10]="Established",H[H.Disconnected=11]="Disconnected",H[H.Error=99]="Error"})(Uh||(Mh.SocksClientState=Uh={}))});var OT=p((ph)=>{Object.defineProperty(ph,"__esModule",{value:!0});ph.shuffleArray=ph.SocksClientError=void 0;class _h extends Error{constructor(H,$){super(H);this.options=$}}ph.SocksClientError=_h;function by(H){for(let $=H.length-1;$>0;$--){let A=Math.floor(Math.random()*($+1));[H[$],H[A]]=[H[A],H[$]]}}ph.shuffleArray=by});var VE=p((uh)=>{Object.defineProperty(uh,"__esModule",{value:!0});uh.isInSubnet=ky;uh.isCorrect=Ry;uh.numberToPaddedHex=Wh;uh.stringToPaddedHex=Oy;uh.testBit=my;function ky(H){if(this.subnetMask<H.subnetMask)return!1;if(this.mask(H.subnetMask)===H.mask())return!0;return!1}function Ry(H){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===H&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function Wh(H){return H.toString(16).padStart(2,"0")}function Oy(H){return Wh(parseInt(H,10))}function my(H,$){let{length:A}=H;if($>A)return!1;let L=A-$;return H.substring(L,L+1)==="1"}});var mT=p((xh)=>{Object.defineProperty(xh,"__esModule",{value:!0});xh.RE_SUBNET_STRING=xh.RE_ADDRESS=xh.GROUPS=xh.BITS=void 0;xh.BITS=32;xh.GROUPS=4;xh.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;xh.RE_SUBNET_STRING=/\/\d{1,2}$/});var WE=p((Xh)=>{Object.defineProperty(Xh,"__esModule",{value:!0});Xh.AddressError=void 0;class ch extends Error{constructor(H,$){super(H);this.name="AddressError",this.parseMessage=$}}Xh.AddressError=ch});var wT=p((SA)=>{var Yy=SA&&SA.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),qy=SA&&SA.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),rh=SA&&SA.__importStar||function(H){if(H&&H.__esModule)return H;var $={};if(H!=null){for(var A in H)if(A!=="default"&&Object.prototype.hasOwnProperty.call(H,A))Yy($,H,A)}return qy($,H),$};Object.defineProperty(SA,"__esModule",{value:!0});SA.Address4=void 0;var cD=rh(VE()),Z$=rh(mT()),yf=WE();class x${constructor(H){this.groups=Z$.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=cD.isCorrect(Z$.BITS),this.isInSubnet=cD.isInSubnet,this.address=H;let $=Z$.RE_SUBNET_STRING.exec(H);if($){if(this.parsedSubnet=$[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>Z$.BITS)throw new yf.AddressError("Invalid subnet mask.");H=H.replace(Z$.RE_SUBNET_STRING,"")}this.addressMinusSuffix=H,this.parsedAddress=this.parse(H)}static isValid(H){try{return new x$(H),!0}catch($){return!1}}parse(H){let $=H.split(".");if(!H.match(Z$.RE_ADDRESS))throw new yf.AddressError("Invalid IPv4 address.");return $}correctForm(){return this.parsedAddress.map((H)=>parseInt(H,10)).join(".")}static fromHex(H){let $=H.replace(/:/g,"").padStart(8,"0"),A=[],L;for(L=0;L<8;L+=2){let D=$.slice(L,L+2);A.push(parseInt(D,16))}return new x$(A.join("."))}static fromInteger(H){return x$.fromHex(H.toString(16))}static fromArpa(H){let A=H.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new x$(A)}toHex(){return this.parsedAddress.map((H)=>cD.stringToPaddedHex(H)).join(":")}toArray(){return this.parsedAddress.map((H)=>parseInt(H,10))}toGroup6(){let H=[],$;for($=0;$<Z$.GROUPS;$+=2)H.push(`${cD.stringToPaddedHex(this.parsedAddress[$])}${cD.stringToPaddedHex(this.parsedAddress[$+1])}`);return H.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map((H)=>cD.stringToPaddedHex(H)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(Z$.BITS-this.subnetMask)}`)}startAddress(){return x$.fromBigInt(this._startAddress())}startAddressExclusive(){let H=BigInt("1");return x$.fromBigInt(this._startAddress()+H)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(Z$.BITS-this.subnetMask)}`)}endAddress(){return x$.fromBigInt(this._endAddress())}endAddressExclusive(){let H=BigInt("1");return x$.fromBigInt(this._endAddress()-H)}static fromBigInt(H){return x$.fromHex(H.toString(16))}static fromByteArray(H){if(H.length!==4)throw new yf.AddressError("IPv4 addresses require exactly 4 bytes");for(let $=0;$<H.length;$++)if(!Number.isInteger(H[$])||H[$]<0||H[$]>255)throw new yf.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(H)}static fromUnsignedByteArray(H){if(H.length!==4)throw new yf.AddressError("IPv4 addresses require exactly 4 bytes");let $=H.join(".");return new x$($)}mask(H){if(H===void 0)H=this.subnetMask;return this.getBitsBase2(0,H)}getBitsBase2(H,$){return this.binaryZeroPad().slice(H,$)}reverseForm(H){if(!H)H={};let $=this.correctForm().split(".").reverse().join(".");if(H.omitSuffix)return $;return`${$}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new x$("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(Z$.BITS,"0")}groupForV6(){let H=this.parsedAddress;return this.address.replace(Z$.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${H.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${H.slice(2,4).join(".")}</span>`)}}SA.Address4=x$});var eT=p((Bh)=>{Object.defineProperty(Bh,"__esModule",{value:!0});Bh.RE_URL_WITH_PORT=Bh.RE_URL=Bh.RE_ZONE_STRING=Bh.RE_SUBNET_STRING=Bh.RE_BAD_ADDRESS=Bh.RE_BAD_CHARACTERS=Bh.TYPES=Bh.SCOPES=Bh.GROUPS=Bh.BITS=void 0;Bh.BITS=128;Bh.GROUPS=8;Bh.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};Bh.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"};Bh.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;Bh.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;Bh.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;Bh.RE_ZONE_STRING=/%.*$/;Bh.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;Bh.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var jT=p((sh)=>{Object.defineProperty(sh,"__esModule",{value:!0});sh.spanAllZeroes=oh;sh.spanAll=Ib;sh.spanLeadingZeroes=Pb;sh.simpleGroup=Tb;function oh(H){return H.replace(/(0+)/g,'<span class="zero">$1</span>')}function Ib(H,$=0){return H.split("").map((L,D)=>`<span class="digit value-${L} position-${D+$}">${oh(L)}</span>`).join("")}function Fh(H){return H.replace(/^(0+)/,'<span class="zero">$1</span>')}function Pb(H){return H.split(":").map((A)=>Fh(A)).join(":")}function Tb(H,$=0){return H.split(":").map((L,D)=>{if(/group-v4/.test(L))return L;return`<span class="hover-group group-${D+$}">${Fh(L)}</span>`})}});var Ch=p((V$)=>{var pb=V$&&V$.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),Vb=V$&&V$.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),Wb=V$&&V$.__importStar||function(H){if(H&&H.__esModule)return H;var $={};if(H!=null){for(var A in H)if(A!=="default"&&Object.prototype.hasOwnProperty.call(H,A))pb($,H,A)}return Vb($,H),$};Object.defineProperty(V$,"__esModule",{value:!0});V$.ADDRESS_BOUNDARY=void 0;V$.groupPossibilities=xE;V$.padGroup=uE;V$.simpleRegularExpression=xb;V$.possibleElisions=hb;var ub=Wb(eT());function xE(H){return`(${H.join("|")})`}function uE(H){if(H.length<4)return`0{0,${4-H.length}}${H}`;return H}V$.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function xb(H){let $=[];H.forEach((L,D)=>{if(parseInt(L,16)===0)$.push(D)});let A=$.map((L)=>H.map((D,f)=>{if(f===L){let E=f===0||f===ub.GROUPS-1?":":"";return xE([uE(D),E])}return uE(D)}).join(":"));return A.push(H.map(uE).join(":")),xE(A)}function hb(H,$,A){let L=$?"":":",D=A?"":":",f=[];if(!$&&!A)f.push("::");if($&&A)f.push("");if(A&&!$||!A&&$)f.push(":");f.push(`${L}(:0{1,4}){1,${H-1}}`),f.push(`(0{1,4}:){1,${H-1}}${D}`),f.push(`(0{1,4}:){${H-1}}0{1,4}`);for(let E=1;E<H-1;E++)for(let I=1;I<H-E;I++)f.push(`(0{1,4}:){${I}}:(0{1,4}:){${H-I-E-1}}0{1,4}`);return xE(f)}});var ah=p((rA)=>{var cb=rA&&rA.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),Xb=rA&&rA.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),XE=rA&&rA.__importStar||function(H){if(H&&H.__esModule)return H;var $={};if(H!=null){for(var A in H)if(A!=="default"&&Object.prototype.hasOwnProperty.call(H,A))cb($,H,A)}return Xb($,H),$};Object.defineProperty(rA,"__esModule",{value:!0});rA.Address6=void 0;var ih=XE(VE()),JT=XE(mT()),uH=XE(eT()),QT=XE(jT()),mL=wT(),wL=Ch(),jA=WE(),hE=VE();function cE(H){if(!H)throw Error("Assertion failed.")}function Sb(H){let $=/(\d+)(\d{3})/;while($.test(H))H=H.replace($,"$1,$2");return H}function rb(H){return H=H.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),H=H.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),H}function Bb(H,$){let A=[],L=[],D;for(D=0;D<H.length;D++)if(D<$[0])A.push(H[D]);else if(D>$[1])L.push(H[D]);return A.concat(["compact"]).concat(L)}function Gh(H){return parseInt(H,16).toString(16).padStart(4,"0")}function dh(H){return H&255}class OH{constructor(H,$){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=ih.isInSubnet,this.isCorrect=ih.isCorrect(uH.BITS),$===void 0)this.groups=uH.GROUPS;else this.groups=$;this.address=H;let A=uH.RE_SUBNET_STRING.exec(H);if(A){if(this.parsedSubnet=A[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>uH.BITS)throw new jA.AddressError("Invalid subnet mask.");H=H.replace(uH.RE_SUBNET_STRING,"")}else if(/\//.test(H))throw new jA.AddressError("Invalid subnet mask.");let L=uH.RE_ZONE_STRING.exec(H);if(L)this.zone=L[0],H=H.replace(uH.RE_ZONE_STRING,"");this.addressMinusSuffix=H,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(H){try{return new OH(H),!0}catch($){return!1}}static fromBigInt(H){let $=H.toString(16).padStart(32,"0"),A=[],L;for(L=0;L<uH.GROUPS;L++)A.push($.slice(L*4,(L+1)*4));return new OH(A.join(":"))}static fromURL(H){let $,A=null,L;if(H.indexOf("[")!==-1&&H.indexOf("]:")!==-1){if(L=uH.RE_URL_WITH_PORT.exec(H),L===null)return{error:"failed to parse address with port",address:null,port:null};$=L[1],A=L[2]}else if(H.indexOf("/")!==-1){if(H=H.replace(/^[a-z0-9]+:\/\//,""),L=uH.RE_URL.exec(H),L===null)return{error:"failed to parse address from URL",address:null,port:null};$=L[1]}else $=H;if(A){if(A=parseInt(A,10),A<0||A>65536)A=null}else A=null;return{address:new OH($),port:A}}static fromAddress4(H){let $=new mL.Address4(H),A=uH.BITS-(JT.BITS-$.subnetMask);return new OH(`::ffff:${$.correctForm()}/${A}`)}static fromArpa(H){let $=H.replace(/(\.ip6\.arpa)?\.$/,""),A=7;if($.length!==63)throw new jA.AddressError("Invalid 'ip6.arpa' form.");let L=$.split(".").reverse();for(let D=A;D>0;D--){let f=D*4;L.splice(f,0,":")}return $=L.join(""),new OH($)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(H=this.subnetMask){return this.getBitsBase2(0,H)}possibleSubnets(H=128){let $=uH.BITS-this.subnetMask,A=Math.abs(H-uH.BITS),L=$-A;if(L<0)return"0";return Sb((BigInt("2")**BigInt(L)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(uH.BITS-this.subnetMask)}`)}startAddress(){return OH.fromBigInt(this._startAddress())}startAddressExclusive(){let H=BigInt("1");return OH.fromBigInt(this._startAddress()+H)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(uH.BITS-this.subnetMask)}`)}endAddress(){return OH.fromBigInt(this._endAddress())}endAddressExclusive(){let H=BigInt("1");return OH.fromBigInt(this._endAddress()-H)}getScope(){let H=uH.SCOPES[parseInt(this.getBits(12,16).toString(10),10)];if(this.getType()==="Global unicast"&&H!=="Link local")H="Global";return H||"Unknown"}getType(){for(let H of Object.keys(uH.TYPES))if(this.isInSubnet(new OH(H)))return uH.TYPES[H];return"Global unicast"}getBits(H,$){return BigInt(`0b${this.getBitsBase2(H,$)}`)}getBitsBase2(H,$){return this.binaryZeroPad().slice(H,$)}getBitsBase16(H,$){let A=$-H;if(A%4!==0)throw Error("Length of bits to retrieve must be divisible by four");return this.getBits(H,$).toString(16).padStart(A/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,uH.BITS)}reverseForm(H){if(!H)H={};let $=Math.floor(this.subnetMask/4),A=this.canonicalForm().replace(/:/g,"").split("").slice(0,$).reverse().join(".");if($>0){if(H.omitSuffix)return A;return`${A}.ip6.arpa.`}if(H.omitSuffix)return"";return"ip6.arpa."}correctForm(){let H,$=[],A=0,L=[];for(H=0;H<this.parsedAddress.length;H++){let E=parseInt(this.parsedAddress[H],16);if(E===0)A++;if(E!==0&&A>0){if(A>1)L.push([H-A,H-1]);A=0}}if(A>1)L.push([this.parsedAddress.length-A,this.parsedAddress.length-1]);let D=L.map((E)=>E[1]-E[0]+1);if(L.length>0){let E=D.indexOf(Math.max(...D));$=Bb(this.parsedAddress,L[E])}else $=this.parsedAddress;for(H=0;H<$.length;H++)if($[H]!=="compact")$[H]=parseInt($[H],16).toString(16);let f=$.join(":");return f=f.replace(/^compact$/,"::"),f=f.replace(/(^compact)|(compact$)/,":"),f=f.replace(/compact/,""),f}binaryZeroPad(){return this.bigInt().toString(2).padStart(uH.BITS,"0")}parse4in6(H){let $=H.split(":"),L=$.slice(-1)[0].match(JT.RE_ADDRESS);if(L){this.parsedAddress4=L[0],this.address4=new mL.Address4(this.parsedAddress4);for(let D=0;D<this.address4.groups;D++)if(/^0[0-9]+/.test(this.address4.parsedAddress[D]))throw new jA.AddressError("IPv4 addresses can't have leading zeroes.",H.replace(JT.RE_ADDRESS,this.address4.parsedAddress.map(rb).join(".")));this.v4=!0,$[$.length-1]=this.address4.toGroup6(),H=$.join(":")}return H}parse(H){H=this.parse4in6(H);let $=H.match(uH.RE_BAD_CHARACTERS);if($)throw new jA.AddressError(`Bad character${$.length>1?"s":""} detected in address: ${$.join("")}`,H.replace(uH.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let A=H.match(uH.RE_BAD_ADDRESS);if(A)throw new jA.AddressError(`Address failed regex: ${A.join("")}`,H.replace(uH.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let L=[],D=H.split("::");if(D.length===2){let f=D[0].split(":"),E=D[1].split(":");if(f.length===1&&f[0]==="")f=[];if(E.length===1&&E[0]==="")E=[];let I=this.groups-(f.length+E.length);if(!I)throw new jA.AddressError("Error parsing groups");this.elidedGroups=I,this.elisionBegin=f.length,this.elisionEnd=f.length+this.elidedGroups,L=L.concat(f);for(let P=0;P<I;P++)L.push("0");L=L.concat(E)}else if(D.length===1)L=H.split(":"),this.elidedGroups=0;else throw new jA.AddressError("Too many :: groups found");if(L=L.map((f)=>parseInt(f,16).toString(16)),L.length!==this.groups)throw new jA.AddressError("Incorrect number of groups found");return L}canonicalForm(){return this.parsedAddress.map(Gh).join(":")}decimal(){return this.parsedAddress.map((H)=>parseInt(H,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(Gh).join("")}`)}to4(){let H=this.binaryZeroPad().split("");return mL.Address4.fromHex(BigInt(`0b${H.slice(96,128).join("")}`).toString(16))}to4in6(){let H=this.to4(),A=new OH(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),L="";if(!/:$/.test(A))L=":";return A+L+H.address}inspectTeredo(){let H=this.getBitsBase16(0,32),A=(this.getBits(80,96)^BigInt("0xffff")).toString(),L=mL.Address4.fromHex(this.getBitsBase16(32,64)),D=this.getBits(96,128),f=mL.Address4.fromHex((D^BigInt("0xffffffff")).toString(16)),E=this.getBitsBase2(64,80),I=(0,hE.testBit)(E,15),P=(0,hE.testBit)(E,14),T=(0,hE.testBit)(E,8),U=(0,hE.testBit)(E,9),M=BigInt(`0b${E.slice(2,6)+E.slice(8,16)}`).toString(10);return{prefix:`${H.slice(0,4)}:${H.slice(4,8)}`,server4:L.address,client4:f.address,flags:E,coneNat:I,microsoft:{reserved:P,universalLocal:U,groupIndividual:T,nonce:M},udpPort:A}}inspect6to4(){let H=this.getBitsBase16(0,16),$=mL.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:H.slice(0,4),gateway:$.address}}to6to4(){if(!this.is4())return null;let H=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new OH(H)}toByteArray(){let H=this.bigInt().toString(16),A=`${"0".repeat(H.length%2)}${H}`,L=[];for(let D=0,f=A.length;D<f;D+=2)L.push(parseInt(A.substring(D,D+2),16));return L}toUnsignedByteArray(){return this.toByteArray().map(dh)}static fromByteArray(H){return this.fromUnsignedByteArray(H.map(dh))}static fromUnsignedByteArray(H){let $=BigInt("256"),A=BigInt("0"),L=BigInt("1");for(let D=H.length-1;D>=0;D--)A+=L*BigInt(H[D].toString(10)),L*=$;return OH.fromBigInt(A)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){if(this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000")return!0;return!1}isMulticast(){return this.getType()==="Multicast"}is4(){return this.v4}isTeredo(){return this.isInSubnet(new OH("2001::/32"))}is6to4(){return this.isInSubnet(new OH("2002::/16"))}isLoopback(){return this.getType()==="Loopback"}href(H){if(H===void 0)H="";else H=`:${H}`;return`http://[${this.correctForm()}]${H}/`}link(H){if(!H)H={};if(H.className===void 0)H.className="";if(H.prefix===void 0)H.prefix="/#address=";if(H.v4===void 0)H.v4=!1;let $=this.correctForm;if(H.v4)$=this.to4in6;let A=$.call(this);if(H.className)return`<a href="${H.prefix}${A}" class="${H.className}">${A}</a>`;return`<a href="${H.prefix}${A}">${A}</a>`}group(){if(this.elidedGroups===0)return QT.simpleGroup(this.address).join(":");cE(typeof this.elidedGroups==="number"),cE(typeof this.elisionBegin==="number");let H=[],[$,A]=this.address.split("::");if($.length)H.push(...QT.simpleGroup($));else H.push("");let L=["hover-group"];for(let D=this.elisionBegin;D<this.elisionBegin+this.elidedGroups;D++)L.push(`group-${D}`);if(H.push(`<span class="${L.join(" ")}"></span>`),A.length)H.push(...QT.simpleGroup(A,this.elisionEnd));else H.push("");if(this.is4())cE(this.address4 instanceof mL.Address4),H.pop(),H.push(this.address4.groupForV6());return H.join(":")}regularExpressionString(H=!1){let $=[],A=new OH(this.correctForm());if(A.elidedGroups===0)$.push((0,wL.simpleRegularExpression)(A.parsedAddress));else if(A.elidedGroups===uH.GROUPS)$.push((0,wL.possibleElisions)(uH.GROUPS));else{let L=A.address.split("::");if(L[0].length)$.push((0,wL.simpleRegularExpression)(L[0].split(":")));if(cE(typeof A.elidedGroups==="number"),$.push((0,wL.possibleElisions)(A.elidedGroups,L[0].length!==0,L[1].length!==0)),L[1].length)$.push((0,wL.simpleRegularExpression)(L[1].split(":")));$=[$.join(":")]}if(!H)$=["(?=^|",wL.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...$,")(?=[^\\w\\:]|",wL.ADDRESS_BOUNDARY,"|$)"];return $.join("")}regularExpression(H=!1){return new RegExp(this.regularExpressionString(H),"i")}}rA.Address6=OH});var KT=p((H$)=>{var nb=H$&&H$.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),ob=H$&&H$.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),Fb=H$&&H$.__importStar||function(H){if(H&&H.__esModule)return H;var $={};if(H!=null){for(var A in H)if(A!=="default"&&Object.prototype.hasOwnProperty.call(H,A))nb($,H,A)}return ob($,H),$};Object.defineProperty(H$,"__esModule",{value:!0});H$.v6=H$.AddressError=H$.Address6=H$.Address4=void 0;var sb=wT();Object.defineProperty(H$,"Address4",{enumerable:!0,get:function(){return sb.Address4}});var Cb=ah();Object.defineProperty(H$,"Address6",{enumerable:!0,get:function(){return Cb.Address6}});var ib=WE();Object.defineProperty(H$,"AddressError",{enumerable:!0,get:function(){return ib.AddressError}});var Gb=Fb(jT());H$.v6={helpers:Gb}});var mh=p((Rh)=>{Object.defineProperty(Rh,"__esModule",{value:!0});Rh.ipToBuffer=Rh.int32ToIpv4=Rh.ipv4ToInt32=Rh.validateSocksClientChainOptions=Rh.validateSocksClientOptions=void 0;var E$=OT(),mH=RT(),db=B("stream"),gT=KT(),lh=B("net");function ab(H,$=["connect","bind","associate"]){if(!mH.SocksCommand[H.command])throw new E$.SocksClientError(mH.ERRORS.InvalidSocksCommand,H);if($.indexOf(H.command)===-1)throw new E$.SocksClientError(mH.ERRORS.InvalidSocksCommandForOperation,H);if(!bh(H.destination))throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsDestination,H);if(!Nh(H.proxy))throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsProxy,H);if(yh(H.proxy,H),H.timeout&&!kh(H.timeout))throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsTimeout,H);if(H.existing_socket&&!(H.existing_socket instanceof db.Duplex))throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsExistingSocket,H)}Rh.validateSocksClientOptions=ab;function lb(H){if(H.command!=="connect")throw new E$.SocksClientError(mH.ERRORS.InvalidSocksCommandChain,H);if(!bh(H.destination))throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsDestination,H);if(!(H.proxies&&Array.isArray(H.proxies)&&H.proxies.length>=2))throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsProxiesLength,H);if(H.proxies.forEach(($)=>{if(!Nh($))throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsProxy,H);yh($,H)}),H.timeout&&!kh(H.timeout))throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsTimeout,H)}Rh.validateSocksClientChainOptions=lb;function yh(H,$){if(H.custom_auth_method!==void 0){if(H.custom_auth_method<mH.SOCKS5_CUSTOM_AUTH_START||H.custom_auth_method>mH.SOCKS5_CUSTOM_AUTH_END)throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsCustomAuthRange,$);if(H.custom_auth_request_handler===void 0||typeof H.custom_auth_request_handler!=="function")throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,$);if(H.custom_auth_response_size===void 0)throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,$);if(H.custom_auth_response_handler===void 0||typeof H.custom_auth_response_handler!=="function")throw new E$.SocksClientError(mH.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,$)}}function bh(H){return H&&typeof H.host==="string"&&Buffer.byteLength(H.host)<256&&typeof H.port==="number"&&H.port>=0&&H.port<=65535}function Nh(H){return H&&(typeof H.host==="string"||typeof H.ipaddress==="string")&&typeof H.port==="number"&&H.port>=0&&H.port<=65535&&(H.type===4||H.type===5)}function kh(H){return typeof H==="number"&&H>0}function yb(H){return new gT.Address4(H).toArray().reduce((A,L)=>(A<<8)+L,0)>>>0}Rh.ipv4ToInt32=yb;function bb(H){let $=H>>>24&255,A=H>>>16&255,L=H>>>8&255,D=H&255;return[$,A,L,D].join(".")}Rh.int32ToIpv4=bb;function Nb(H){if(lh.isIPv4(H)){let $=new gT.Address4(H);return Buffer.from($.toArray())}else if(lh.isIPv6(H)){let $=new gT.Address6(H);return Buffer.from($.canonicalForm().split(":").map((A)=>A.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}Rh.ipToBuffer=Nb});var Jh=p((eh)=>{Object.defineProperty(eh,"__esModule",{value:!0});eh.ReceiveBuffer=void 0;class wh{constructor(H=4096){this.buffer=Buffer.allocUnsafe(H),this.offset=0,this.originalSize=H}get length(){return this.offset}append(H){if(!Buffer.isBuffer(H))throw Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+H.length>=this.buffer.length){let $=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+H.length)),$.copy(this.buffer)}return H.copy(this.buffer,this.offset),this.offset+=H.length}peek(H){if(H>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,H)}get(H){if(H>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");let $=Buffer.allocUnsafe(H);return this.buffer.slice(0,H).copy($),this.buffer.copyWithin(0,H,H+this.offset-H),this.offset-=H,$}}eh.ReceiveBuffer=wh});var Qh=p((TL)=>{var XD=TL&&TL.__awaiter||function(H,$,A,L){function D(f){return f instanceof A?f:new A(function(E){E(f)})}return new(A||(A=Promise))(function(f,E){function I(U){try{T(L.next(U))}catch(M){E(M)}}function P(U){try{T(L.throw(U))}catch(M){E(M)}}function T(U){U.done?f(U.value):D(U.value).then(I,P)}T((L=L.apply(H,$||[])).next())})};Object.defineProperty(TL,"__esModule",{value:!0});TL.SocksClientError=TL.SocksClient=void 0;var wb=B("events"),SD=B("net"),W$=Dh(),s=RT(),h$=mh(),eb=Jh(),YT=OT();Object.defineProperty(TL,"SocksClientError",{enumerable:!0,get:function(){return YT.SocksClientError}});var vT=KT();class SE extends wb.EventEmitter{constructor(H){super();this.options=Object.assign({},H),(0,h$.validateSocksClientOptions)(H),this.setState(s.SocksClientState.Created)}static createConnection(H,$){return new Promise((A,L)=>{try{(0,h$.validateSocksClientOptions)(H,["connect"])}catch(f){if(typeof $==="function")return $(f),A(f);else return L(f)}let D=new SE(H);D.connect(H.existing_socket),D.once("established",(f)=>{if(D.removeAllListeners(),typeof $==="function")$(null,f),A(f);else A(f)}),D.once("error",(f)=>{if(D.removeAllListeners(),typeof $==="function")$(f),A(f);else L(f)})})}static createConnectionChain(H,$){return new Promise((A,L)=>XD(this,void 0,void 0,function*(){try{(0,h$.validateSocksClientChainOptions)(H)}catch(D){if(typeof $==="function")return $(D),A(D);else return L(D)}if(H.randomizeChain)(0,YT.shuffleArray)(H.proxies);try{let D;for(let f=0;f<H.proxies.length;f++){let E=H.proxies[f],I=f===H.proxies.length-1?H.destination:{host:H.proxies[f+1].host||H.proxies[f+1].ipaddress,port:H.proxies[f+1].port},P=yield SE.createConnection({command:"connect",proxy:E,destination:I,existing_socket:D});D=D||P.socket}if(typeof $==="function")$(null,{socket:D}),A({socket:D});else A({socket:D})}catch(D){if(typeof $==="function")$(D),A(D);else L(D)}}))}static createUDPFrame(H){let $=new W$.SmartBuffer;if($.writeUInt16BE(0),$.writeUInt8(H.frameNumber||0),SD.isIPv4(H.remoteHost.host))$.writeUInt8(s.Socks5HostType.IPv4),$.writeUInt32BE((0,h$.ipv4ToInt32)(H.remoteHost.host));else if(SD.isIPv6(H.remoteHost.host))$.writeUInt8(s.Socks5HostType.IPv6),$.writeBuffer((0,h$.ipToBuffer)(H.remoteHost.host));else $.writeUInt8(s.Socks5HostType.Hostname),$.writeUInt8(Buffer.byteLength(H.remoteHost.host)),$.writeString(H.remoteHost.host);return $.writeUInt16BE(H.remoteHost.port),$.writeBuffer(H.data),$.toBuffer()}static parseUDPFrame(H){let $=W$.SmartBuffer.fromBuffer(H);$.readOffset=2;let A=$.readUInt8(),L=$.readUInt8(),D;if(L===s.Socks5HostType.IPv4)D=(0,h$.int32ToIpv4)($.readUInt32BE());else if(L===s.Socks5HostType.IPv6)D=vT.Address6.fromByteArray(Array.from($.readBuffer(16))).canonicalForm();else D=$.readString($.readUInt8());let f=$.readUInt16BE();return{frameNumber:A,remoteHost:{host:D,port:f},data:$.readBuffer()}}setState(H){if(this.state!==s.SocksClientState.Error)this.state=H}connect(H){this.onDataReceived=(A)=>this.onDataReceivedHandler(A),this.onClose=()=>this.onCloseHandler(),this.onError=(A)=>this.onErrorHandler(A),this.onConnect=()=>this.onConnectHandler();let $=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||s.DEFAULT_TIMEOUT);if($.unref&&typeof $.unref==="function")$.unref();if(H)this.socket=H;else this.socket=new SD.Socket;if(this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(s.SocksClientState.Connecting),this.receiveBuffer=new eb.ReceiveBuffer,H)this.socket.emit("connect");else if(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null)this.socket.setNoDelay(!!this.options.set_tcp_nodelay);this.prependOnceListener("established",(A)=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let L=this.receiveBuffer.get(this.receiveBuffer.length);A.socket.emit("data",L)}A.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){if(this.state!==s.SocksClientState.Established&&this.state!==s.SocksClientState.BoundWaitingForConnection)this.closeSocket(s.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){if(this.setState(s.SocksClientState.Connected),this.options.proxy.type===4)this.sendSocks4InitialHandshake();else this.sendSocks5InitialHandshake();this.setState(s.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(H){this.receiveBuffer.append(H),this.processData()}processData(){while(this.state!==s.SocksClientState.Established&&this.state!==s.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize)if(this.state===s.SocksClientState.SentInitialHandshake)if(this.options.proxy.type===4)this.handleSocks4FinalHandshakeResponse();else this.handleInitialSocks5HandshakeResponse();else if(this.state===s.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===s.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===s.SocksClientState.BoundWaitingForConnection)if(this.options.proxy.type===4)this.handleSocks4IncomingConnectionResponse();else this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(s.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(s.ERRORS.SocketClosed)}onErrorHandler(H){this.closeSocket(H.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(H){if(this.state!==s.SocksClientState.Error)this.setState(s.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new YT.SocksClientError(H,this.options))}sendSocks4InitialHandshake(){let H=this.options.proxy.userId||"",$=new W$.SmartBuffer;if($.writeUInt8(4),$.writeUInt8(s.SocksCommand[this.options.command]),$.writeUInt16BE(this.options.destination.port),SD.isIPv4(this.options.destination.host))$.writeBuffer((0,h$.ipToBuffer)(this.options.destination.host)),$.writeStringNT(H);else $.writeUInt8(0),$.writeUInt8(0),$.writeUInt8(0),$.writeUInt8(1),$.writeStringNT(H),$.writeStringNT(this.options.destination.host);this.nextRequiredPacketBufferSize=s.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write($.toBuffer())}handleSocks4FinalHandshakeResponse(){let H=this.receiveBuffer.get(8);if(H[1]!==s.Socks4Response.Granted)this.closeSocket(`${s.ERRORS.Socks4ProxyRejectedConnection} - (${s.Socks4Response[H[1]]})`);else if(s.SocksCommand[this.options.command]===s.SocksCommand.bind){let $=W$.SmartBuffer.fromBuffer(H);$.readOffset=2;let A={port:$.readUInt16BE(),host:(0,h$.int32ToIpv4)($.readUInt32BE())};if(A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress;this.setState(s.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:A,socket:this.socket})}else this.setState(s.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let H=this.receiveBuffer.get(8);if(H[1]!==s.Socks4Response.Granted)this.closeSocket(`${s.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${s.Socks4Response[H[1]]})`);else{let $=W$.SmartBuffer.fromBuffer(H);$.readOffset=2;let A={port:$.readUInt16BE(),host:(0,h$.int32ToIpv4)($.readUInt32BE())};this.setState(s.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}sendSocks5InitialHandshake(){let H=new W$.SmartBuffer,$=[s.Socks5Auth.NoAuth];if(this.options.proxy.userId||this.options.proxy.password)$.push(s.Socks5Auth.UserPass);if(this.options.proxy.custom_auth_method!==void 0)$.push(this.options.proxy.custom_auth_method);H.writeUInt8(5),H.writeUInt8($.length);for(let A of $)H.writeUInt8(A);this.nextRequiredPacketBufferSize=s.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(H.toBuffer()),this.setState(s.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let H=this.receiveBuffer.get(2);if(H[0]!==5)this.closeSocket(s.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);else if(H[1]===s.SOCKS5_NO_ACCEPTABLE_AUTH)this.closeSocket(s.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);else if(H[1]===s.Socks5Auth.NoAuth)this.socks5ChosenAuthType=s.Socks5Auth.NoAuth,this.sendSocks5CommandRequest();else if(H[1]===s.Socks5Auth.UserPass)this.socks5ChosenAuthType=s.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication();else if(H[1]===this.options.proxy.custom_auth_method)this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication();else this.closeSocket(s.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let H=this.options.proxy.userId||"",$=this.options.proxy.password||"",A=new W$.SmartBuffer;A.writeUInt8(1),A.writeUInt8(Buffer.byteLength(H)),A.writeString(H),A.writeUInt8(Buffer.byteLength($)),A.writeString($),this.nextRequiredPacketBufferSize=s.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(A.toBuffer()),this.setState(s.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return XD(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(s.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(H){return XD(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(H)})}handleSocks5AuthenticationNoAuthHandshakeResponse(H){return XD(this,void 0,void 0,function*(){return H[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(H){return XD(this,void 0,void 0,function*(){return H[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return XD(this,void 0,void 0,function*(){this.setState(s.SocksClientState.ReceivedAuthenticationResponse);let H=!1;if(this.socks5ChosenAuthType===s.Socks5Auth.NoAuth)H=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===s.Socks5Auth.UserPass)H=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===this.options.proxy.custom_auth_method)H=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));if(!H)this.closeSocket(s.ERRORS.Socks5AuthenticationFailed);else this.sendSocks5CommandRequest()})}sendSocks5CommandRequest(){let H=new W$.SmartBuffer;if(H.writeUInt8(5),H.writeUInt8(s.SocksCommand[this.options.command]),H.writeUInt8(0),SD.isIPv4(this.options.destination.host))H.writeUInt8(s.Socks5HostType.IPv4),H.writeBuffer((0,h$.ipToBuffer)(this.options.destination.host));else if(SD.isIPv6(this.options.destination.host))H.writeUInt8(s.Socks5HostType.IPv6),H.writeBuffer((0,h$.ipToBuffer)(this.options.destination.host));else H.writeUInt8(s.Socks5HostType.Hostname),H.writeUInt8(this.options.destination.host.length),H.writeString(this.options.destination.host);H.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=s.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(H.toBuffer()),this.setState(s.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let H=this.receiveBuffer.peek(5);if(H[0]!==5||H[1]!==s.Socks5Response.Granted)this.closeSocket(`${s.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${s.Socks5Response[H[1]]}`);else{let $=H[3],A,L;if($===s.Socks5HostType.IPv4){let D=s.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<D){this.nextRequiredPacketBufferSize=D;return}if(L=W$.SmartBuffer.fromBuffer(this.receiveBuffer.get(D).slice(4)),A={host:(0,h$.int32ToIpv4)(L.readUInt32BE()),port:L.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if($===s.Socks5HostType.Hostname){let D=H[4],f=s.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(D);if(this.receiveBuffer.length<f){this.nextRequiredPacketBufferSize=f;return}L=W$.SmartBuffer.fromBuffer(this.receiveBuffer.get(f).slice(5)),A={host:L.readString(D),port:L.readUInt16BE()}}else if($===s.Socks5HostType.IPv6){let D=s.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<D){this.nextRequiredPacketBufferSize=D;return}L=W$.SmartBuffer.fromBuffer(this.receiveBuffer.get(D).slice(4)),A={host:vT.Address6.fromByteArray(Array.from(L.readBuffer(16))).canonicalForm(),port:L.readUInt16BE()}}if(this.setState(s.SocksClientState.ReceivedFinalResponse),s.SocksCommand[this.options.command]===s.SocksCommand.connect)this.setState(s.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket});else if(s.SocksCommand[this.options.command]===s.SocksCommand.bind)this.setState(s.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=s.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:A,socket:this.socket});else if(s.SocksCommand[this.options.command]===s.SocksCommand.associate)this.setState(s.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}handleSocks5IncomingConnectionResponse(){let H=this.receiveBuffer.peek(5);if(H[0]!==5||H[1]!==s.Socks5Response.Granted)this.closeSocket(`${s.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${s.Socks5Response[H[1]]}`);else{let $=H[3],A,L;if($===s.Socks5HostType.IPv4){let D=s.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<D){this.nextRequiredPacketBufferSize=D;return}if(L=W$.SmartBuffer.fromBuffer(this.receiveBuffer.get(D).slice(4)),A={host:(0,h$.int32ToIpv4)(L.readUInt32BE()),port:L.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if($===s.Socks5HostType.Hostname){let D=H[4],f=s.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(D);if(this.receiveBuffer.length<f){this.nextRequiredPacketBufferSize=f;return}L=W$.SmartBuffer.fromBuffer(this.receiveBuffer.get(f).slice(5)),A={host:L.readString(D),port:L.readUInt16BE()}}else if($===s.Socks5HostType.IPv6){let D=s.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<D){this.nextRequiredPacketBufferSize=D;return}L=W$.SmartBuffer.fromBuffer(this.receiveBuffer.get(D).slice(4)),A={host:vT.Address6.fromByteArray(Array.from(L.readBuffer(16))).canonicalForm(),port:L.readUInt16BE()}}this.setState(s.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}TL.SocksClient=SE});var Kh=p((eL)=>{var jb=eL&&eL.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),Jb=eL&&eL.__exportStar||function(H,$){for(var A in H)if(A!=="default"&&!Object.prototype.hasOwnProperty.call($,A))jb($,H,A)};Object.defineProperty(eL,"__esModule",{value:!0});Jb(Qh(),eL)});var ZT=p((z$)=>{var Qb=z$&&z$.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),Kb=z$&&z$.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),gb=z$&&z$.__importStar||function(){var H=function($){return H=Object.getOwnPropertyNames||function(A){var L=[];for(var D in A)if(Object.prototype.hasOwnProperty.call(A,D))L[L.length]=D;return L},H($)};return function($){if($&&$.__esModule)return $;var A={};if($!=null){for(var L=H($),D=0;D<L.length;D++)if(L[D]!=="default")Qb(A,$,L[D])}return Kb(A,$),A}}(),gh=z$&&z$.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(z$,"__esModule",{value:!0});z$.default=LN;var vb=gh(K$()),Yb=B("stream"),qb=Kh(),Zb=gb(B("dns")),zb=B("util"),qT=gh(B("assert")),JA=(0,vb.default)("mqttjs:socks");class vh extends Yb.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(H){if(JA("proxy stream started"),(0,qT.default)(!this._socket),this.destroyed){H.destroy(this.errored);return}if(this._socket=H,!this._flowing)H.pause();H.on("data",this._onData),H.on("end",this._onEnd),H.on("error",this._onError),H.on("close",this._onClose),H.emit("connect"),this.uncork()}_write(H,$,A){(0,qT.default)(this._socket),this._socket.write(H,A)}_read(H){this._flowing=!0,this._socket?.resume?.()}_destroy(H,$){this._socket?.destroy?.(H),$(H)}_onData=(H)=>{if((0,qT.default)(this._socket),this._flowing=this.push(H),!this._flowing)this._socket.pause()};_onEnd=()=>{JA("proxy stream received EOF"),this.push(null)};_onClose=()=>{JA("proxy stream closed"),this.destroy()};_onError=(H)=>{JA("proxy stream died with error %s",H),this.destroy(H)}}function rE(H){try{if(H.code===void 0)H.code="SOCKS";return H}catch{return H}}function HN(H){switch(H){case"socks5h:":return[5,!0];case"socks4a:":return[4,!0];case"socks5:":return[5,!1];case"socks4:":return[4,!1];default:return[void 0,!1]}}function $N(H){let $=new URL(H);if($.pathname||$.hash||$.search)throw rE(Error("bad SOCKS URL"));let[A,L]=HN($.protocol);if(!A)throw rE(Error("bad SOCKS URL: invalid protocol"));let D=parseInt($.port,10);if(Number.isNaN(D))throw rE(Error("bad SOCKS URL: invalid port"));return[{host:$.hostname,port:D,type:A},L]}async function AN(H,$,A,L,D={}){let f=D.lookup??(0,zb.promisify)(Zb.lookup),[E,I]=$N(A);if(!I)JA("resolving %s locally",H),H=(await f(H,{family:E.type===4?4:0})).address;JA("establishing SOCKS%d connection to %s:%d via %s:%d",E.type,H,$,E.host,E.port);let P=new qb.SocksClient({command:"connect",destination:{host:H,port:$},proxy:{...E},timeout:D.timeout});P.connect(),P.on("established",({socket:T})=>L._start(T)),P.on("error",(T)=>{JA("SOCKS failed: %s",T),L.destroy(rE(T))})}function LN(H,$,A,L){JA("SOCKS connection to %s:%d via %s",H,$,A);let D=new vh;return AN(H,$,A,D,L).catch((f)=>{JA("SOCKS failed: %s",f),D.destroy(f)}),D}});var HU=p((bf)=>{var zT=bf&&bf.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(bf,"__esModule",{value:!0});var DN=zT(B("net")),fN=zT(K$()),EN=zT(ZT()),IN=(0,fN.default)("mqttjs:tcp"),PN=(H,$)=>{if($.port=$.port||1883,$.hostname=$.hostname||$.host||"localhost",$.socksProxy)return(0,EN.default)($.hostname,$.port,$.socksProxy,{timeout:$.socksTimeout});let{port:A,path:L}=$,D=$.hostname;return IN("port %d and host %s",A,D),DN.default.createConnection({port:A,host:D,path:L})};bf.default=PN});var AU=p((Nf)=>{var $U=Nf&&Nf.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(Nf,"__esModule",{value:!0});var Yh=B("tls"),TN=$U(B("net")),UN=$U(K$()),MN=$U(ZT()),tN=(0,UN.default)("mqttjs:tls");function _N(H){let{host:$,port:A,socksProxy:L,...D}=H;if(L!==void 0){let f=(0,MN.default)($,A,L,{timeout:H.socksTimeout});return(0,Yh.connect)({...D,socket:f})}return(0,Yh.connect)(H)}var pN=(H,$)=>{if($.port=$.port||8883,$.host=$.hostname||$.host||"localhost",TN.default.isIP($.host)===0)$.servername=$.host;$.rejectUnauthorized=$.rejectUnauthorized!==!1,delete $.path,tN("port %d host %s rejectUnauthorized %b",$.port,$.host,$.rejectUnauthorized);let A=_N($);A.on("secureConnect",()=>{if($.rejectUnauthorized&&!A.authorized)A.emit("error",Error("TLS not authorized"));else A.removeListener("error",L)});function L(D){if($.rejectUnauthorized)H.emit("error",D);A.end()}return A.on("error",L),A};Nf.default=pN});var DU=p((Zh)=>{Object.defineProperty(Zh,"__esModule",{value:!0});var qh=B("buffer"),VN=HL(),WN=_E(),BA,LU,c$;function uN(){let H=new VN.Transform;return H._write=($,A,L)=>{BA.send({data:$.buffer,success(){L()},fail(D){L(Error(D))}})},H._flush=($)=>{BA.close({success(){$()}})},H}function xN(H){if(!H.hostname)H.hostname="localhost";if(!H.path)H.path="/";if(!H.wsOptions)H.wsOptions={}}function hN(H,$){let A=H.protocol==="wxs"?"wss":"ws",L=`${A}://${H.hostname}${H.path}`;if(H.port&&H.port!==80&&H.port!==443)L=`${A}://${H.hostname}:${H.port}${H.path}`;if(typeof H.transformWsUrl==="function")L=H.transformWsUrl(L,H,$);return L}function cN(){BA.onOpen(()=>{c$.socketReady()}),BA.onMessage((H)=>{let{data:$}=H;if($ instanceof ArrayBuffer)$=qh.Buffer.from($);else $=qh.Buffer.from($,"utf8");LU.push($)}),BA.onClose(()=>{c$.emit("close"),c$.end(),c$.destroy()}),BA.onError((H)=>{let $=Error(H.errMsg);c$.destroy($)})}var XN=(H,$)=>{if($.hostname=$.hostname||$.host,!$.hostname)throw Error("Could not determine host. Specify host manually.");let A=$.protocolId==="MQIsdp"&&$.protocolVersion===3?"mqttv3.1":"mqtt";xN($);let L=hN($,H);BA=wx.connectSocket({url:L,protocols:[A]}),LU=uN(),c$=new WN.BufferedDuplex($,LU,BA),c$._destroy=(f,E)=>{BA.close({success(){if(E)E(f)}})};let D=c$.destroy;return c$.destroy=(f,E)=>{return c$.destroy=D,setTimeout(()=>{BA.close({fail(){c$._destroy(f,E)}})},0),c$},cN(),c$};Zh.default=XN});var EU=p((Hc)=>{Object.defineProperty(Hc,"__esModule",{value:!0});var fU=B("buffer"),rN=HL(),BN=_E(),QA,kf,rD,zh=!1;function nN(){let H=new rN.Transform;return H._write=($,A,L)=>{QA.sendSocketMessage({data:$.buffer,success(){L()},fail(){L(Error())}})},H._flush=($)=>{QA.closeSocket({success(){$()}})},H}function oN(H){if(!H.hostname)H.hostname="localhost";if(!H.path)H.path="/";if(!H.wsOptions)H.wsOptions={}}function FN(H,$){let A=H.protocol==="alis"?"wss":"ws",L=`${A}://${H.hostname}${H.path}`;if(H.port&&H.port!==80&&H.port!==443)L=`${A}://${H.hostname}:${H.port}${H.path}`;if(typeof H.transformWsUrl==="function")L=H.transformWsUrl(L,H,$);return L}function sN(){if(zh)return;zh=!0,QA.onSocketOpen(()=>{rD.socketReady()}),QA.onSocketMessage((H)=>{if(typeof H.data==="string"){let $=fU.Buffer.from(H.data,"base64");kf.push($)}else{let $=new FileReader;$.addEventListener("load",()=>{if($.result instanceof ArrayBuffer){kf.push(fU.Buffer.from($.result));return}kf.push(fU.Buffer.from($.result,"utf-8"))}),$.readAsArrayBuffer(H.data)}}),QA.onSocketClose(()=>{rD.end(),rD.destroy()}),QA.onSocketError((H)=>{rD.destroy(H)})}var CN=(H,$)=>{if($.hostname=$.hostname||$.host,!$.hostname)throw Error("Could not determine host. Specify host manually.");let A=$.protocolId==="MQIsdp"&&$.protocolVersion===3?"mqttv3.1":"mqtt";oN($);let L=FN($,H);return QA=$.my,QA.connectSocket({url:L,protocols:A}),kf=nN(),rD=new BN.BufferedDuplex($,kf,QA),sN(),rD};Hc.default=CN});var Dc=p((BD)=>{var BE=BD&&BD.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(BD,"__esModule",{value:!0});BD.connectAsync=yN;var GN=BE(K$()),dN=BE(B("url")),aN=BE(tE()),$c=BE(Gf());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var Ac=(0,GN.default)("mqttjs"),bH=null;function lN(H){let $;if(H.auth)if($=H.auth.match(/^(.+):(.+)$/),$){let[,A,L]=$;H.username=A,H.password=L}else H.username=H.auth}function Lc(H,$){if(Ac("connecting to an MQTT broker..."),typeof H==="object"&&!$)$=H,H="";if($=$||{},H&&typeof H==="string"){let D=dN.default.parse(H,!0),f={};if(D.port!=null)f.port=Number(D.port);if(f.host=D.hostname,f.query=D.query,f.auth=D.auth,f.protocol=D.protocol,f.path=D.path,$={...f,...$},!$.protocol)throw Error("Missing protocol");$.protocol=$.protocol.replace(/:$/,"")}if($.unixSocket=$.unixSocket||$.protocol?.includes("+unix"),$.unixSocket)$.protocol=$.protocol.replace("+unix","");else if(!$.protocol?.startsWith("ws")&&!$.protocol?.startsWith("wx"))delete $.path;if(lN($),$.query&&typeof $.query.clientId==="string")$.clientId=$.query.clientId;if($c.default||$.unixSocket)$.socksProxy=void 0;else if($.socksProxy===void 0&&typeof process<"u")$.socksProxy=process.env.MQTTJS_SOCKS_PROXY;if($.cert&&$.key)if($.protocol){if(["mqtts","wss","wxs","alis"].indexOf($.protocol)===-1)switch($.protocol){case"mqtt":$.protocol="mqtts";break;case"ws":$.protocol="wss";break;case"wx":$.protocol="wxs";break;case"ali":$.protocol="alis";break;default:throw Error(`Unknown protocol for secure connection: "${$.protocol}"!`)}}else throw Error("Missing secure protocol key");if(!bH)if(bH={},!$c.default&&!$.forceNativeWebSocket)bH.ws=lf().streamBuilder,bH.wss=lf().streamBuilder,bH.mqtt=HU().default,bH.tcp=HU().default,bH.ssl=AU().default,bH.tls=bH.ssl,bH.mqtts=AU().default;else bH.ws=lf().browserStreamBuilder,bH.wss=lf().browserStreamBuilder,bH.wx=DU().default,bH.wxs=DU().default,bH.ali=EU().default,bH.alis=EU().default;if(!bH[$.protocol]){let D=["mqtts","wss"].indexOf($.protocol)!==-1;$.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((f,E)=>{if(D&&E%2===0)return!1;return typeof bH[f]==="function"})[0]}if($.clean===!1&&!$.clientId)throw Error("Missing clientId for unclean clients");if($.protocol)$.defaultProtocol=$.protocol;function A(D){if($.servers){if(!D._reconnectCount||D._reconnectCount===$.servers.length)D._reconnectCount=0;$.host=$.servers[D._reconnectCount].host,$.port=$.servers[D._reconnectCount].port,$.protocol=!$.servers[D._reconnectCount].protocol?$.defaultProtocol:$.servers[D._reconnectCount].protocol,$.hostname=$.host,D._reconnectCount++}return Ac("calling streambuilder for",$.protocol),bH[$.protocol](D,$)}let L=new aN.default(A,$);return L.on("error",()=>{}),L}function yN(H,$,A=!0){return new Promise((L,D)=>{let f=Lc(H,$),E={connect:(P)=>{I(),L(f)},end:()=>{I(),L(f)},error:(P)=>{I(),f.end(),D(P)}};if(A===!1)E.close=()=>{E.error(Error("Couldn't connect to server"))};function I(){Object.keys(E).forEach((P)=>{f.off(P,E[P])})}Object.keys(E).forEach((P)=>{f.on(P,E[P])})})}BD.default=Lc});var IU=p((UH)=>{var fc=UH&&UH.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),bN=UH&&UH.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),NN=UH&&UH.__importStar||function(){var H=function($){return H=Object.getOwnPropertyNames||function(A){var L=[];for(var D in A)if(Object.prototype.hasOwnProperty.call(A,D))L[L.length]=D;return L},H($)};return function($){if($&&$.__esModule)return $;var A={};if($!=null){for(var L=H($),D=0;D<L.length;D++)if(L[D]!=="default")fc(A,$,L[D])}return bN(A,$),A}}(),Ec=UH&&UH.__exportStar||function(H,$){for(var A in H)if(A!=="default"&&!Object.prototype.hasOwnProperty.call($,A))fc($,H,A)},Rf=UH&&UH.__importDefault||function(H){return H&&H.__esModule?H:{default:H}};Object.defineProperty(UH,"__esModule",{value:!0});UH.ReasonCodes=UH.KeepaliveManager=UH.UniqueMessageIdProvider=UH.DefaultMessageIdProvider=UH.Store=UH.MqttClient=UH.connectAsync=UH.connect=UH.Client=void 0;var Ic=Rf(tE());UH.MqttClient=Ic.default;var kN=Rf(cT());UH.DefaultMessageIdProvider=kN.default;var RN=Rf(w9());UH.UniqueMessageIdProvider=RN.default;var ON=Rf(ET());UH.Store=ON.default;var Pc=NN(Dc());UH.connect=Pc.default;Object.defineProperty(UH,"connectAsync",{enumerable:!0,get:function(){return Pc.connectAsync}});var mN=Rf(aT());UH.KeepaliveManager=mN.default;UH.Client=Ic.default;Ec(tE(),UH);Ec(aL(),UH);var wN=If();Object.defineProperty(UH,"ReasonCodes",{enumerable:!0,get:function(){return wN.ReasonCodes}})});var Uc=p((d$)=>{var Tc=d$&&d$.__createBinding||(Object.create?function(H,$,A,L){if(L===void 0)L=A;var D=Object.getOwnPropertyDescriptor($,A);if(!D||("get"in D?!$.__esModule:D.writable||D.configurable))D={enumerable:!0,get:function(){return $[A]}};Object.defineProperty(H,L,D)}:function(H,$,A,L){if(L===void 0)L=A;H[L]=$[A]}),eN=d$&&d$.__setModuleDefault||(Object.create?function(H,$){Object.defineProperty(H,"default",{enumerable:!0,value:$})}:function(H,$){H.default=$}),jN=d$&&d$.__importStar||function(){var H=function($){return H=Object.getOwnPropertyNames||function(A){var L=[];for(var D in A)if(Object.prototype.hasOwnProperty.call(A,D))L[L.length]=D;return L},H($)};return function($){if($&&$.__esModule)return $;var A={};if($!=null){for(var L=H($),D=0;D<L.length;D++)if(L[D]!=="default")Tc(A,$,L[D])}return eN(A,$),A}}(),JN=d$&&d$.__exportStar||function(H,$){for(var A in H)if(A!=="default"&&!Object.prototype.hasOwnProperty.call($,A))Tc($,H,A)};Object.defineProperty(d$,"__esModule",{value:!0});var QN=jN(IU());d$.default=QN;JN(IU(),d$)});var uc=p((ww,ZN)=>{ZN.exports=B("./ngrok.win32-x64-msvc-zjj4rz8c.node")});var Fc=p((S7,nH)=>{var __dirname="C:\\Users\\Vishal\\Projects\\ccc\\backend-v2\\node_modules\\@ngrok\\ngrok",{existsSync:wH,readFileSync:zN}=B("fs"),{join:eH}=B("path"),{platform:Of,arch:HA}=process,HH=null,fH=!1,NH=null;function CE(){if(!process.report||typeof process.report.getReport!=="function")try{let H=B("child_process").execSync("which ldd").toString().trim();return zN(H,"utf8").includes("musl")}catch(H){return!0}else{let{glibcVersionRuntime:H}=process.report.getReport().header;return!H}}switch(Of){case"android":switch(HA){case"arm64":fH=wH(eH(__dirname,"ngrok.android-arm64.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.android-arm64.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-android-arm64");})()}catch(H){NH=H}break;case"arm":fH=wH(eH(__dirname,"ngrok.android-arm-eabi.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.android-arm-eabi.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-android-arm-eabi");})()}catch(H){NH=H}break;default:throw Error(`Unsupported architecture on Android ${HA}`)}break;case"win32":switch(HA){case"x64":fH=wH(eH(__dirname,"ngrok.win32-x64-msvc.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.win32-x64-msvc.node");})();else HH=uc()}catch(H){NH=H}break;case"ia32":fH=wH(eH(__dirname,"ngrok.win32-ia32-msvc.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.win32-ia32-msvc.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-win32-ia32-msvc");})()}catch(H){NH=H}break;case"arm64":fH=wH(eH(__dirname,"ngrok.win32-arm64-msvc.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.win32-arm64-msvc.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-win32-arm64-msvc");})()}catch(H){NH=H}break;default:throw Error(`Unsupported architecture on Windows: ${HA}`)}break;case"darwin":fH=wH(eH(__dirname,"ngrok.darwin-universal.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.darwin-universal.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-darwin-universal");})();break}catch{}switch(HA){case"x64":fH=wH(eH(__dirname,"ngrok.darwin-x64.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.darwin-x64.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-darwin-x64");})()}catch(H){NH=H}break;case"arm64":fH=wH(eH(__dirname,"ngrok.darwin-arm64.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.darwin-arm64.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-darwin-arm64");})()}catch(H){NH=H}break;default:throw Error(`Unsupported architecture on macOS: ${HA}`)}break;case"freebsd":if(HA!=="x64")throw Error(`Unsupported architecture on FreeBSD: ${HA}`);fH=wH(eH(__dirname,"ngrok.freebsd-x64.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.freebsd-x64.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-freebsd-x64");})()}catch(H){NH=H}break;case"linux":switch(HA){case"x64":if(CE()){fH=wH(eH(__dirname,"ngrok.linux-x64-musl.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-x64-musl.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-x64-musl");})()}catch(H){NH=H}}else{fH=wH(eH(__dirname,"ngrok.linux-x64-gnu.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-x64-gnu.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-x64-gnu");})()}catch(H){NH=H}}break;case"arm64":if(CE()){fH=wH(eH(__dirname,"ngrok.linux-arm64-musl.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-arm64-musl.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-arm64-musl");})()}catch(H){NH=H}}else{fH=wH(eH(__dirname,"ngrok.linux-arm64-gnu.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-arm64-gnu.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-arm64-gnu");})()}catch(H){NH=H}}break;case"arm":if(CE()){fH=wH(eH(__dirname,"ngrok.linux-arm-musleabihf.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-arm-musleabihf.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-arm-musleabihf");})()}catch(H){NH=H}}else{fH=wH(eH(__dirname,"ngrok.linux-arm-gnueabihf.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-arm-gnueabihf.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-arm-gnueabihf");})()}catch(H){NH=H}}break;case"riscv64":if(CE()){fH=wH(eH(__dirname,"ngrok.linux-riscv64-musl.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-riscv64-musl.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-riscv64-musl");})()}catch(H){NH=H}}else{fH=wH(eH(__dirname,"ngrok.linux-riscv64-gnu.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-riscv64-gnu.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-riscv64-gnu");})()}catch(H){NH=H}}break;case"s390x":fH=wH(eH(__dirname,"ngrok.linux-s390x-gnu.node"));try{if(fH)HH=(()=>{throw new Error("Cannot require module "+"./ngrok.linux-s390x-gnu.node");})();else HH=(()=>{throw new Error("Cannot require module "+"@ngrok/ngrok-linux-s390x-gnu");})()}catch(H){NH=H}break;default:throw Error(`Unsupported architecture on Linux: ${HA}`)}break;default:throw Error(`Unsupported OS: ${Of}, architecture: ${HA}`)}if(!HH){if(NH)throw NH;throw Error("Failed to load native binding")}var{connect:H7,forward:cc,disconnect:$7,kill:A7,Listener:L7,listeners:D7,getListener:f7,getListenerByUrl:E7,HttpListenerBuilder:mf,TcpListenerBuilder:wf,TlsListenerBuilder:ef,LabeledListenerBuilder:jf,loggingCallback:MU,authtoken:I7,SessionBuilder:Jf,Session:P7,UpdateRequest:T7}=HH;S7.connect=H7;S7.forward=cc;S7.disconnect=$7;S7.kill=A7;S7.Listener=L7;S7.listeners=D7;S7.getListener=f7;S7.getListenerByUrl=E7;S7.HttpListenerBuilder=mf;S7.TcpListenerBuilder=wf;S7.TlsListenerBuilder=ef;S7.LabeledListenerBuilder=jf;S7.loggingCallback=MU;S7.authtoken=I7;S7.SessionBuilder=Jf;S7.Session=P7;S7.UpdateRequest=T7;var U7=B("net"),KA=B("fs"),UU=B("os"),xc=B("path");Jf.prototype._connect=Jf.prototype.connect;Jf.prototype.connect=M7;mf.prototype._listen=mf.prototype.listen;wf.prototype._listen=wf.prototype.listen;ef.prototype._listen=ef.prototype.listen;jf.prototype._listen=jf.prototype.listen;mf.prototype.listen=iE;wf.prototype.listen=iE;ef.prototype.listen=iE;jf.prototype.listen=iE;mf.prototype.listenAndServe=GE;wf.prototype.listenAndServe=GE;ef.prototype.listenAndServe=GE;jf.prototype.listenAndServe=GE;async function M7(){try{return await this._connect()}catch(H){throw tU(H),H}}async function iE(H){try{let $=await this._listen();if(H!==!1){let A=await _7();$.socket=A,t7($,A)}return $}catch($){throw tU($),$}}async function GE(H){let $=await this._listen();return $.socket=await Sc(H,$),$}function tU(H){if(H.message){let $=/error_code: (ERR_NGROK_\d+)$/,A=H.message.match($);if(A&&A.length>1)H.errorCode=A[1]}}function t7(H,$){Object.defineProperty(H,"handle",{get:function(){return H.forward("localhost:"+$.address().port),$._handle}})}async function _7(){return await _U(new U7.Server,{host:"localhost",port:0})}function _U(H,$){return new Promise((A,L)=>{let D=H.listen($);D.once("listening",()=>{A(D)}).once("error",(f)=>{L(f)})})}async function Xc(H){var $=new Jf;$.authtokenFromEnv();var A=await $.connect(),L=await A.httpEndpoint().listen(H);return L.session=A,L}async function p7(){return await Xc()}async function Sc(H,$){if($&&$.socket)$.socket.close();if(!$)$=await Xc(!1);try{socket=await u7($,H)}catch(A){console.debug("Using TCP socket. "+A),socket=await V7($,H)}return x7($,socket),H.listener=$,socket.listener=$,socket}async function V7(H,$){let A=await _U($,{host:"localhost",port:0});return H.forward("localhost:"+A.address().port),A}function W7(H,$){var A="tun-"+H.id()+".sock";if(Of=="win32")return"\\\\.\\pipe\\"+A;let L=".ngrok";try{KA.mkdirSync(L)}catch(D){}try{return KA.accessSync(L,KA.constants.W_OK),L+xc.sep+A}catch(D){}if(UU.tmpdir().length<90)try{if(KA.accessSync(UU.tmpdir(),KA.constants.W_OK),filepath=UU.tmpdir()+xc.sep+A,filepath.length>100)filepath=filepath.substring(0,100);return filepath}catch(D){}return KA.accessSync(process.cwd(),KA.constants.W_OK),A}async function u7(H,$){var A=W7(H);let L=await _U($,{path:A});try{if(Of!="win32")KA.chmodSync(A,KA.constants.S_IRWXU)}catch(f){console.debug("Cannot change permissions of file: "+A)}var D="unix:"+A;if(Of=="win32")D="pipe:"+A.replace("\\\\.\\pipe\\","//./");return H.forward(D),L.path=A,L}var hc=!1;function x7(H,$){for(let A of["SIGINT","SIGTERM"])process.on(A,function(){if(process.listenerCount(A)>1)return;if(hc)return;if(hc=!0,H)H.close().catch((L)=>{console.error(`Error closing listener: ${L}`)});if($)$.close();MU()})}function h7(H){MU(($,A,L)=>{console.log(`${$} ${A} - ${L}`)},H)}var c7=cc;async function rc(H){if(H==null)H=80;if(Number.isInteger(H)||typeof H==="string"||H instanceof String){if(address=String(H),Number.isInteger(H)&&!address.includes(":"))address=`localhost:${address}`;H={addr:address}}if(typeof H.port==="string"||H.port instanceof String){let f=parseInt(H.port,10);if(isNaN(f))throw Error(`port must be a number: '${H.port}'`);H.port=f}let $=H.addr;if(Number.isInteger($))H.addr="localhost:"+String(H.addr);["allow_user_agent","auth","basic_auth","deny_user_agent","ip_restriction.allow_cidrs","ip_restriction.deny_cidrs","labels","oauth.allow_domains","oauth.allow_emails","oauth.scopes","oidc.scopes","oidc.allow_domains","oidc.allow_emails","request_header.add","request_header.remove","response_header.add","response_header.remove","schemes"].forEach((f)=>{Bc(H,f)}),["ip_restriction.allow_cidrs","ip_restriction.deny_cidrs","oauth.allow_domains","oauth.allow_emails","oauth.scopes","oauth.provider","oidc.client_id","oidc.client_secret","oidc.scopes","oidc.issuer_url","oidc.allow_domains","oidc.allow_emails","request_header.add","request_header.remove","response_header.add","response_header.remove","verify_webhook.provider","verify_webhook.secret"].forEach((f)=>{X7(H,f)});var A;if(H.onLogEvent){let f=H.onLogEvent;A=(E,I,P)=>{f(`${E} ${I} - ${P}`)},H.onLogEvent=!0}var L,D;if(H.onStatusChange){let f=H.onStatusChange;L=(E,I)=>{f(E)},D=(E,I)=>{f("closed")},H.onStatusChange=!0}try{return await c7(H,A,L,D)}catch(f){throw tU(f),f}}function X7(H,$){let A=$.replace(".","_");if(H[$]==null)return;if(H[A]==null){H[A]=H[$];return}if(H[$]instanceof Array&&H[A]instanceof Array)for(let L of H[$])H[A].push(L)}function Bc(H,$){let A=$.replace(".","_");if($!=A)Bc(H,A);if(H[$]==null)return;if(!(H[$]instanceof Array))H[$]=[H[$]]}S7.connect=rc;S7.forward=rc;S7.consoleLog=h7;S7.listen=Sc;S7.listenable=p7});var pU=p((Kw,Cc)=>{Cc.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var dc=p((gw,Gc)=>{var m7=pU();function ic(H){this.mode=m7.MODE_8BIT_BYTE,this.data=H}ic.prototype={getLength:function(){return this.data.length},write:function(H){for(var $=0;$<this.data.length;$++)H.put(this.data.charCodeAt($),8)}};Gc.exports=ic});var VU=p((vw,ac)=>{var $A={glog:function(H){if(H<1)throw Error("glog("+H+")");return $A.LOG_TABLE[H]},gexp:function(H){while(H<0)H+=255;while(H>=256)H-=255;return $A.EXP_TABLE[H]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(oH=0;oH<8;oH++)$A.EXP_TABLE[oH]=1<<oH;var oH;for(oH=8;oH<256;oH++)$A.EXP_TABLE[oH]=$A.EXP_TABLE[oH-4]^$A.EXP_TABLE[oH-5]^$A.EXP_TABLE[oH-6]^$A.EXP_TABLE[oH-8];var oH;for(oH=0;oH<255;oH++)$A.LOG_TABLE[$A.EXP_TABLE[oH]]=oH;var oH;ac.exports=$A});var WU=p((Yw,lc)=>{var jL=VU();function aE(H,$){if(H.length===void 0)throw Error(H.length+"/"+$);var A=0;while(A<H.length&&H[A]===0)A++;this.num=Array(H.length-A+$);for(var L=0;L<H.length-A;L++)this.num[L]=H[L+A]}aE.prototype={get:function(H){return this.num[H]},getLength:function(){return this.num.length},multiply:function(H){var $=Array(this.getLength()+H.getLength()-1);for(var A=0;A<this.getLength();A++)for(var L=0;L<H.getLength();L++)$[A+L]^=jL.gexp(jL.glog(this.get(A))+jL.glog(H.get(L)));return new aE($,0)},mod:function(H){if(this.getLength()-H.getLength()<0)return this;var $=jL.glog(this.get(0))-jL.glog(H.get(0)),A=Array(this.getLength());for(var L=0;L<this.getLength();L++)A[L]=this.get(L);for(var D=0;D<H.getLength();D++)A[D]^=jL.gexp(jL.glog(H.get(D))+$);return new aE(A,0).mod(H)}};lc.exports=aE});var bc=p((qw,yc)=>{yc.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Rc=p((Zw,kc)=>{var l$=pU(),Nc=WU(),w7=VU(),UL=bc(),KH={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(H){var $=H<<10;while(KH.getBCHDigit($)-KH.getBCHDigit(KH.G15)>=0)$^=KH.G15<<KH.getBCHDigit($)-KH.getBCHDigit(KH.G15);return(H<<10|$)^KH.G15_MASK},getBCHTypeNumber:function(H){var $=H<<12;while(KH.getBCHDigit($)-KH.getBCHDigit(KH.G18)>=0)$^=KH.G18<<KH.getBCHDigit($)-KH.getBCHDigit(KH.G18);return H<<12|$},getBCHDigit:function(H){var $=0;while(H!==0)$++,H>>>=1;return $},getPatternPosition:function(H){return KH.PATTERN_POSITION_TABLE[H-1]},getMask:function(H,$,A){switch(H){case UL.PATTERN000:return($+A)%2===0;case UL.PATTERN001:return $%2===0;case UL.PATTERN010:return A%3===0;case UL.PATTERN011:return($+A)%3===0;case UL.PATTERN100:return(Math.floor($/2)+Math.floor(A/3))%2===0;case UL.PATTERN101:return $*A%2+$*A%3===0;case UL.PATTERN110:return($*A%2+$*A%3)%2===0;case UL.PATTERN111:return($*A%3+($+A)%2)%2===0;default:throw Error("bad maskPattern:"+H)}},getErrorCorrectPolynomial:function(H){var $=new Nc([1],0);for(var A=0;A<H;A++)$=$.multiply(new Nc([1,w7.gexp(A)],0));return $},getLengthInBits:function(H,$){if(1<=$&&$<10)switch(H){case l$.MODE_NUMBER:return 10;case l$.MODE_ALPHA_NUM:return 9;case l$.MODE_8BIT_BYTE:return 8;case l$.MODE_KANJI:return 8;default:throw Error("mode:"+H)}else if($<27)switch(H){case l$.MODE_NUMBER:return 12;case l$.MODE_ALPHA_NUM:return 11;case l$.MODE_8BIT_BYTE:return 16;case l$.MODE_KANJI:return 10;default:throw Error("mode:"+H)}else if($<41)switch(H){case l$.MODE_NUMBER:return 14;case l$.MODE_ALPHA_NUM:return 13;case l$.MODE_8BIT_BYTE:return 16;case l$.MODE_KANJI:return 12;default:throw Error("mode:"+H)}else throw Error("type:"+$)},getLostPoint:function(H){var $=H.getModuleCount(),A=0,L=0,D=0;for(L=0;L<$;L++)for(D=0;D<$;D++){var f=0,E=H.isDark(L,D);for(var I=-1;I<=1;I++){if(L+I<0||$<=L+I)continue;for(var P=-1;P<=1;P++){if(D+P<0||$<=D+P)continue;if(I===0&&P===0)continue;if(E===H.isDark(L+I,D+P))f++}}if(f>5)A+=3+f-5}for(L=0;L<$-1;L++)for(D=0;D<$-1;D++){var T=0;if(H.isDark(L,D))T++;if(H.isDark(L+1,D))T++;if(H.isDark(L,D+1))T++;if(H.isDark(L+1,D+1))T++;if(T===0||T===4)A+=3}for(L=0;L<$;L++)for(D=0;D<$-6;D++)if(H.isDark(L,D)&&!H.isDark(L,D+1)&&H.isDark(L,D+2)&&H.isDark(L,D+3)&&H.isDark(L,D+4)&&!H.isDark(L,D+5)&&H.isDark(L,D+6))A+=40;for(D=0;D<$;D++)for(L=0;L<$-6;L++)if(H.isDark(L,D)&&!H.isDark(L+1,D)&&H.isDark(L+2,D)&&H.isDark(L+3,D)&&H.isDark(L+4,D)&&!H.isDark(L+5,D)&&H.isDark(L+6,D))A+=40;var U=0;for(D=0;D<$;D++)for(L=0;L<$;L++)if(H.isDark(L,D))U++;var M=Math.abs(100*U/$/$-50)/5;return A+=M*10,A}};kc.exports=KH});var uU=p((zw,Oc)=>{Oc.exports={L:1,M:0,Q:3,H:2}});var wc=p((He,mc)=>{var lE=uU();function nA(H,$){this.totalCount=H,this.dataCount=$}nA.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];nA.getRSBlocks=function(H,$){var A=nA.getRsBlockTable(H,$);if(A===void 0)throw Error("bad rs block @ typeNumber:"+H+"/errorCorrectLevel:"+$);var L=A.length/3,D=[];for(var f=0;f<L;f++){var E=A[f*3+0],I=A[f*3+1],P=A[f*3+2];for(var T=0;T<E;T++)D.push(new nA(I,P))}return D};nA.getRsBlockTable=function(H,$){switch($){case lE.L:return nA.RS_BLOCK_TABLE[(H-1)*4+0];case lE.M:return nA.RS_BLOCK_TABLE[(H-1)*4+1];case lE.Q:return nA.RS_BLOCK_TABLE[(H-1)*4+2];case lE.H:return nA.RS_BLOCK_TABLE[(H-1)*4+3];default:return}};mc.exports=nA});var Jc=p(($e,jc)=>{function ec(){this.buffer=[],this.length=0}ec.prototype={get:function(H){var $=Math.floor(H/8);return(this.buffer[$]>>>7-H%8&1)==1},put:function(H,$){for(var A=0;A<$;A++)this.putBit((H>>>$-A-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(H){var $=Math.floor(this.length/8);if(this.buffer.length<=$)this.buffer.push(0);if(H)this.buffer[$]|=128>>>this.length%8;this.length++}};jc.exports=ec});var vc=p((Ae,gc)=>{var e7=dc(),ML=Rc(),j7=WU(),Qc=wc(),Kc=Jc();function oA(H,$){this.typeNumber=H,this.errorCorrectLevel=$,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}oA.prototype={addData:function(H){var $=new e7(H);this.dataList.push($),this.dataCache=null},isDark:function(H,$){if(H<0||this.moduleCount<=H||$<0||this.moduleCount<=$)throw Error(H+","+$);return this.modules[H][$]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var H=1;for(H=1;H<40;H++){var $=Qc.getRSBlocks(H,this.errorCorrectLevel),A=new Kc,L=0;for(var D=0;D<$.length;D++)L+=$[D].dataCount;for(var f=0;f<this.dataList.length;f++){var E=this.dataList[f];A.put(E.mode,4),A.put(E.getLength(),ML.getLengthInBits(E.mode,H)),E.write(A)}if(A.getLengthInBits()<=L*8)break}this.typeNumber=H}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(H,$){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var A=0;A<this.moduleCount;A++){this.modules[A]=Array(this.moduleCount);for(var L=0;L<this.moduleCount;L++)this.modules[A][L]=null}if(this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(H,$),this.typeNumber>=7)this.setupTypeNumber(H);if(this.dataCache===null)this.dataCache=oA.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);this.mapData(this.dataCache,$)},setupPositionProbePattern:function(H,$){for(var A=-1;A<=7;A++){if(H+A<=-1||this.moduleCount<=H+A)continue;for(var L=-1;L<=7;L++){if($+L<=-1||this.moduleCount<=$+L)continue;if(0<=A&&A<=6&&(L===0||L===6)||0<=L&&L<=6&&(A===0||A===6)||2<=A&&A<=4&&2<=L&&L<=4)this.modules[H+A][$+L]=!0;else this.modules[H+A][$+L]=!1}}},getBestMaskPattern:function(){var H=0,$=0;for(var A=0;A<8;A++){this.makeImpl(!0,A);var L=ML.getLostPoint(this);if(A===0||H>L)H=L,$=A}return $},createMovieClip:function(H,$,A){var L=H.createEmptyMovieClip($,A),D=1;this.make();for(var f=0;f<this.modules.length;f++){var E=f*D;for(var I=0;I<this.modules[f].length;I++){var P=I*D,T=this.modules[f][I];if(T)L.beginFill(0,100),L.moveTo(P,E),L.lineTo(P+D,E),L.lineTo(P+D,E+D),L.lineTo(P,E+D),L.endFill()}}return L},setupTimingPattern:function(){for(var H=8;H<this.moduleCount-8;H++){if(this.modules[H][6]!==null)continue;this.modules[H][6]=H%2===0}for(var $=8;$<this.moduleCount-8;$++){if(this.modules[6][$]!==null)continue;this.modules[6][$]=$%2===0}},setupPositionAdjustPattern:function(){var H=ML.getPatternPosition(this.typeNumber);for(var $=0;$<H.length;$++)for(var A=0;A<H.length;A++){var L=H[$],D=H[A];if(this.modules[L][D]!==null)continue;for(var f=-2;f<=2;f++)for(var E=-2;E<=2;E++)if(Math.abs(f)===2||Math.abs(E)===2||f===0&&E===0)this.modules[L+f][D+E]=!0;else this.modules[L+f][D+E]=!1}},setupTypeNumber:function(H){var $=ML.getBCHTypeNumber(this.typeNumber),A;for(var L=0;L<18;L++)A=!H&&($>>L&1)===1,this.modules[Math.floor(L/3)][L%3+this.moduleCount-8-3]=A;for(var D=0;D<18;D++)A=!H&&($>>D&1)===1,this.modules[D%3+this.moduleCount-8-3][Math.floor(D/3)]=A},setupTypeInfo:function(H,$){var A=this.errorCorrectLevel<<3|$,L=ML.getBCHTypeInfo(A),D;for(var f=0;f<15;f++)if(D=!H&&(L>>f&1)===1,f<6)this.modules[f][8]=D;else if(f<8)this.modules[f+1][8]=D;else this.modules[this.moduleCount-15+f][8]=D;for(var E=0;E<15;E++)if(D=!H&&(L>>E&1)===1,E<8)this.modules[8][this.moduleCount-E-1]=D;else if(E<9)this.modules[8][15-E-1+1]=D;else this.modules[8][15-E-1]=D;this.modules[this.moduleCount-8][8]=!H},mapData:function(H,$){var A=-1,L=this.moduleCount-1,D=7,f=0;for(var E=this.moduleCount-1;E>0;E-=2){if(E===6)E--;while(!0){for(var I=0;I<2;I++)if(this.modules[L][E-I]===null){var P=!1;if(f<H.length)P=(H[f]>>>D&1)===1;var T=ML.getMask($,L,E-I);if(T)P=!P;if(this.modules[L][E-I]=P,D--,D===-1)f++,D=7}if(L+=A,L<0||this.moduleCount<=L){L-=A,A=-A;break}}}}};oA.PAD0=236;oA.PAD1=17;oA.createData=function(H,$,A){var L=Qc.getRSBlocks(H,$),D=new Kc;for(var f=0;f<A.length;f++){var E=A[f];D.put(E.mode,4),D.put(E.getLength(),ML.getLengthInBits(E.mode,H)),E.write(D)}var I=0;for(var P=0;P<L.length;P++)I+=L[P].dataCount;if(D.getLengthInBits()>I*8)throw Error("code length overflow. ("+D.getLengthInBits()+">"+I*8+")");if(D.getLengthInBits()+4<=I*8)D.put(0,4);while(D.getLengthInBits()%8!==0)D.putBit(!1);while(!0){if(D.getLengthInBits()>=I*8)break;if(D.put(oA.PAD0,8),D.getLengthInBits()>=I*8)break;D.put(oA.PAD1,8)}return oA.createBytes(D,L)};oA.createBytes=function(H,$){var A=0,L=0,D=0,f=Array($.length),E=Array($.length);for(var I=0;I<$.length;I++){var P=$[I].dataCount,T=$[I].totalCount-P;L=Math.max(L,P),D=Math.max(D,T),f[I]=Array(P);for(var U=0;U<f[I].length;U++)f[I][U]=255&H.buffer[U+A];A+=P;var M=ML.getErrorCorrectPolynomial(T),t=new j7(f[I],M.getLength()-1),_=t.mod(M);E[I]=Array(M.getLength()-1);for(var x=0;x<E[I].length;x++){var V=x+_.getLength()-E[I].length;E[I][x]=V>=0?_.get(V):0}}var h=0;for(var W=0;W<$.length;W++)h+=$[W].totalCount;var c=Array(h),r=0;for(var F=0;F<L;F++)for(var N=0;N<$.length;N++)if(F<f[N].length)c[r++]=f[N][F];for(var y=0;y<D;y++)for(var k=0;k<$.length;k++)if(y<E[k].length)c[r++]=E[k][y];return c};gc.exports=oA});var Zc=p((Le,qc)=>{var J7=vc(),Yc=uU(),Q7="\x1B[40m \x1B[0m",yE="\x1B[47m \x1B[0m",K7=function(H){return H?Q7:yE},xU=function(H){return{times:function($){return Array($).join(H)}}},g7=function(H,$){var A=Array(H);for(var L=0;L<H;L++)A[L]=$;return A};qc.exports={error:Yc.L,generate:function(H,$,A){if(typeof $==="function")A=$,$={};var L=new J7(-1,this.error);L.addData(H),L.make();var D="";if($&&$.small){var f=!0,E=!1,I=L.getModuleCount(),P=L.modules.slice(),T=I%2===1;if(T)P.push(g7(I,E));var U={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},M=xU(U.BLACK_WHITE).times(I+3),t=xU(U.WHITE_BLACK).times(I+3);D+=M+`
|
|
15
|
-
`;for(var
|
|
16
|
-
`}if(!
|
|
17
|
-
`,
|
|
18
|
-
`}),
|
|
12
|
+
*/var SE=JY(),J4=XY(),HY=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;UI.Buffer=B;UI.SlowBuffer=oq;UI.INSPECT_MAX_BYTES=50;var fA=2147483647;UI.kMaxLength=fA;B.TYPED_ARRAY_SUPPORT=pq();if(!B.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error==="function")console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function pq(){try{var _=new Uint8Array(1),T={foo:function(){return 42}};return Object.setPrototypeOf(T,Uint8Array.prototype),Object.setPrototypeOf(_,T),_.foo()===42}catch(A){return!1}}Object.defineProperty(B.prototype,"parent",{enumerable:!0,get:function(){if(!B.isBuffer(this))return;return this.buffer}});Object.defineProperty(B.prototype,"offset",{enumerable:!0,get:function(){if(!B.isBuffer(this))return;return this.byteOffset}});function w0(_){if(_>fA)throw RangeError('The value "'+_+'" is invalid for option "size"');var T=new Uint8Array(_);return Object.setPrototypeOf(T,B.prototype),T}function B(_,T,A){if(typeof _==="number"){if(typeof T==="string")throw TypeError('The "string" argument must be of type string. Received type number');return kE(_)}return KY(_,T,A)}B.poolSize=8192;function KY(_,T,A){if(typeof _==="string")return nq(_,T);if(ArrayBuffer.isView(_))return iq(_);if(_==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _);if(X0(_,ArrayBuffer)||_&&X0(_.buffer,ArrayBuffer))return vE(_,T,A);if(typeof SharedArrayBuffer<"u"&&(X0(_,SharedArrayBuffer)||_&&X0(_.buffer,SharedArrayBuffer)))return vE(_,T,A);if(typeof _==="number")throw TypeError('The "value" argument must not be of type number. Received type number');var E=_.valueOf&&_.valueOf();if(E!=null&&E!==_)return B.from(E,T,A);var L=aq(_);if(L)return L;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof _[Symbol.toPrimitive]==="function")return B.from(_[Symbol.toPrimitive]("string"),T,A);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _)}B.from=function(_,T,A){return KY(_,T,A)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function GY(_){if(typeof _!=="number")throw TypeError('"size" argument must be of type number');else if(_<0)throw RangeError('The value "'+_+'" is invalid for option "size"')}function lq(_,T,A){if(GY(_),_<=0)return w0(_);if(T!==void 0)return typeof A==="string"?w0(_).fill(T,A):w0(_).fill(T);return w0(_)}B.alloc=function(_,T,A){return lq(_,T,A)};function kE(_){return GY(_),w0(_<0?0:fE(_)|0)}B.allocUnsafe=function(_){return kE(_)};B.allocUnsafeSlow=function(_){return kE(_)};function nq(_,T){if(typeof T!=="string"||T==="")T="utf8";if(!B.isEncoding(T))throw TypeError("Unknown encoding: "+T);var A=$Y(_,T)|0,E=w0(A),L=E.write(_,T);if(L!==A)E=E.slice(0,L);return E}function yE(_){var T=_.length<0?0:fE(_.length)|0,A=w0(T);for(var E=0;E<T;E+=1)A[E]=_[E]&255;return A}function iq(_){if(X0(_,Uint8Array)){var T=new Uint8Array(_);return vE(T.buffer,T.byteOffset,T.byteLength)}return yE(_)}function vE(_,T,A){if(T<0||_.byteLength<T)throw RangeError('"offset" is outside of buffer bounds');if(_.byteLength<T+(A||0))throw RangeError('"length" is outside of buffer bounds');var E;if(T===void 0&&A===void 0)E=new Uint8Array(_);else if(A===void 0)E=new Uint8Array(_,T);else E=new Uint8Array(_,T,A);return Object.setPrototypeOf(E,B.prototype),E}function aq(_){if(B.isBuffer(_)){var T=fE(_.length)|0,A=w0(T);if(A.length===0)return A;return _.copy(A,0,0,T),A}if(_.length!==void 0){if(typeof _.length!=="number"||bE(_.length))return w0(0);return yE(_)}if(_.type==="Buffer"&&Array.isArray(_.data))return yE(_.data)}function fE(_){if(_>=fA)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+fA.toString(16)+" bytes");return _|0}function oq(_){if(+_!=_)_=0;return B.alloc(+_)}B.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==B.prototype};B.compare=function(T,A){if(X0(T,Uint8Array))T=B.from(T,T.offset,T.byteLength);if(X0(A,Uint8Array))A=B.from(A,A.offset,A.byteLength);if(!B.isBuffer(T)||!B.isBuffer(A))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===A)return 0;var E=T.length,L=A.length;for(var J=0,X=Math.min(E,L);J<X;++J)if(T[J]!==A[J]){E=T[J],L=A[J];break}if(E<L)return-1;if(L<E)return 1;return 0};B.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};B.concat=function(T,A){if(!Array.isArray(T))throw TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return B.alloc(0);var E;if(A===void 0){A=0;for(E=0;E<T.length;++E)A+=T[E].length}var L=B.allocUnsafe(A),J=0;for(E=0;E<T.length;++E){var X=T[E];if(X0(X,Uint8Array))if(J+X.length>L.length)B.from(X).copy(L,J);else Uint8Array.prototype.set.call(L,X,J);else if(!B.isBuffer(X))throw TypeError('"list" argument must be an Array of Buffers');else X.copy(L,J);J+=X.length}return L};function $Y(_,T){if(B.isBuffer(_))return _.length;if(ArrayBuffer.isView(_)||X0(_,ArrayBuffer))return _.byteLength;if(typeof _!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof _);var A=_.length,E=arguments.length>2&&arguments[2]===!0;if(!E&&A===0)return 0;var L=!1;for(;;)switch(T){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return hE(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return VY(_).length;default:if(L)return E?-1:hE(_).length;T=(""+T).toLowerCase(),L=!0}}B.byteLength=$Y;function rq(_,T,A){var E=!1;if(T===void 0||T<0)T=0;if(T>this.length)return"";if(A===void 0||A>this.length)A=this.length;if(A<=0)return"";if(A>>>=0,T>>>=0,A<=T)return"";if(!_)_="utf8";while(!0)switch(_){case"hex":return XI(this,T,A);case"utf8":case"utf-8":return WY(this,T,A);case"ascii":return LI(this,T,A);case"latin1":case"binary":return JI(this,T,A);case"base64":return AI(this,T,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return HI(this,T,A);default:if(E)throw TypeError("Unknown encoding: "+_);_=(_+"").toLowerCase(),E=!0}}B.prototype._isBuffer=!0;function DT(_,T,A){var E=_[T];_[T]=_[A],_[A]=E}B.prototype.swap16=function(){var T=this.length;if(T%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var A=0;A<T;A+=2)DT(this,A,A+1);return this};B.prototype.swap32=function(){var T=this.length;if(T%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var A=0;A<T;A+=4)DT(this,A,A+3),DT(this,A+1,A+2);return this};B.prototype.swap64=function(){var T=this.length;if(T%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var A=0;A<T;A+=8)DT(this,A,A+7),DT(this,A+1,A+6),DT(this,A+2,A+5),DT(this,A+3,A+4);return this};B.prototype.toString=function(){var T=this.length;if(T===0)return"";if(arguments.length===0)return WY(this,0,T);return rq.apply(this,arguments)};B.prototype.toLocaleString=B.prototype.toString;B.prototype.equals=function(T){if(!B.isBuffer(T))throw TypeError("Argument must be a Buffer");if(this===T)return!0;return B.compare(this,T)===0};B.prototype.inspect=function(){var T="",A=UI.INSPECT_MAX_BYTES;if(T=this.toString("hex",0,A).replace(/(.{2})/g,"$1 ").trim(),this.length>A)T+=" ... ";return"<Buffer "+T+">"};if(HY)B.prototype[HY]=B.prototype.inspect;B.prototype.compare=function(T,A,E,L,J){if(X0(T,Uint8Array))T=B.from(T,T.offset,T.byteLength);if(!B.isBuffer(T))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(A===void 0)A=0;if(E===void 0)E=T?T.length:0;if(L===void 0)L=0;if(J===void 0)J=this.length;if(A<0||E>T.length||L<0||J>this.length)throw RangeError("out of range index");if(L>=J&&A>=E)return 0;if(L>=J)return-1;if(A>=E)return 1;if(A>>>=0,E>>>=0,L>>>=0,J>>>=0,this===T)return 0;var X=J-L,H=E-A,Z=Math.min(X,H),Y=this.slice(L,J),K=T.slice(A,E);for(var G=0;G<Z;++G)if(Y[G]!==K[G]){X=Y[G],H=K[G];break}if(X<H)return-1;if(H<X)return 1;return 0};function UY(_,T,A,E,L){if(_.length===0)return-1;if(typeof A==="string")E=A,A=0;else if(A>2147483647)A=2147483647;else if(A<-2147483648)A=-2147483648;if(A=+A,bE(A))A=L?0:_.length-1;if(A<0)A=_.length+A;if(A>=_.length)if(L)return-1;else A=_.length-1;else if(A<0)if(L)A=0;else return-1;if(typeof T==="string")T=B.from(T,E);if(B.isBuffer(T)){if(T.length===0)return-1;return ZY(_,T,A,E,L)}else if(typeof T==="number"){if(T=T&255,typeof Uint8Array.prototype.indexOf==="function")if(L)return Uint8Array.prototype.indexOf.call(_,T,A);else return Uint8Array.prototype.lastIndexOf.call(_,T,A);return ZY(_,[T],A,E,L)}throw TypeError("val must be string, number or Buffer")}function ZY(_,T,A,E,L){var J=1,X=_.length,H=T.length;if(E!==void 0){if(E=String(E).toLowerCase(),E==="ucs2"||E==="ucs-2"||E==="utf16le"||E==="utf-16le"){if(_.length<2||T.length<2)return-1;J=2,X/=2,H/=2,A/=2}}function Z(U,V){if(J===1)return U[V];else return U.readUInt16BE(V*J)}var Y;if(L){var K=-1;for(Y=A;Y<X;Y++)if(Z(_,Y)===Z(T,K===-1?0:Y-K)){if(K===-1)K=Y;if(Y-K+1===H)return K*J}else{if(K!==-1)Y-=Y-K;K=-1}}else{if(A+H>X)A=X-H;for(Y=A;Y>=0;Y--){var G=!0;for(var $=0;$<H;$++)if(Z(_,Y+$)!==Z(T,$)){G=!1;break}if(G)return Y}}return-1}B.prototype.includes=function(T,A,E){return this.indexOf(T,A,E)!==-1};B.prototype.indexOf=function(T,A,E){return UY(this,T,A,E,!0)};B.prototype.lastIndexOf=function(T,A,E){return UY(this,T,A,E,!1)};function sq(_,T,A,E){A=Number(A)||0;var L=_.length-A;if(!E)E=L;else if(E=Number(E),E>L)E=L;var J=T.length;if(E>J/2)E=J/2;for(var X=0;X<E;++X){var H=parseInt(T.substr(X*2,2),16);if(bE(H))return X;_[A+X]=H}return X}function tq(_,T,A,E){return bA(hE(T,_.length-A),_,A,E)}function eq(_,T,A,E){return bA(KI(T),_,A,E)}function _I(_,T,A,E){return bA(VY(T),_,A,E)}function TI(_,T,A,E){return bA(GI(T,_.length-A),_,A,E)}B.prototype.write=function(T,A,E,L){if(A===void 0)L="utf8",E=this.length,A=0;else if(E===void 0&&typeof A==="string")L=A,E=this.length,A=0;else if(isFinite(A))if(A=A>>>0,isFinite(E)){if(E=E>>>0,L===void 0)L="utf8"}else L=E,E=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var J=this.length-A;if(E===void 0||E>J)E=J;if(T.length>0&&(E<0||A<0)||A>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!L)L="utf8";var X=!1;for(;;)switch(L){case"hex":return sq(this,T,A,E);case"utf8":case"utf-8":return tq(this,T,A,E);case"ascii":case"latin1":case"binary":return eq(this,T,A,E);case"base64":return _I(this,T,A,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return TI(this,T,A,E);default:if(X)throw TypeError("Unknown encoding: "+L);L=(""+L).toLowerCase(),X=!0}};B.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function AI(_,T,A){if(T===0&&A===_.length)return SE.fromByteArray(_);else return SE.fromByteArray(_.slice(T,A))}function WY(_,T,A){A=Math.min(_.length,A);var E=[],L=T;while(L<A){var J=_[L],X=null,H=J>239?4:J>223?3:J>191?2:1;if(L+H<=A){var Z,Y,K,G;switch(H){case 1:if(J<128)X=J;break;case 2:if(Z=_[L+1],(Z&192)===128){if(G=(J&31)<<6|Z&63,G>127)X=G}break;case 3:if(Z=_[L+1],Y=_[L+2],(Z&192)===128&&(Y&192)===128){if(G=(J&15)<<12|(Z&63)<<6|Y&63,G>2047&&(G<55296||G>57343))X=G}break;case 4:if(Z=_[L+1],Y=_[L+2],K=_[L+3],(Z&192)===128&&(Y&192)===128&&(K&192)===128){if(G=(J&15)<<18|(Z&63)<<12|(Y&63)<<6|K&63,G>65535&&G<1114112)X=G}}}if(X===null)X=65533,H=1;else if(X>65535)X-=65536,E.push(X>>>10&1023|55296),X=56320|X&1023;E.push(X),L+=H}return EI(E)}var YY=4096;function EI(_){var T=_.length;if(T<=YY)return String.fromCharCode.apply(String,_);var A="",E=0;while(E<T)A+=String.fromCharCode.apply(String,_.slice(E,E+=YY));return A}function LI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]&127);return E}function JI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]);return E}function XI(_,T,A){var E=_.length;if(!T||T<0)T=0;if(!A||A<0||A>E)A=E;var L="";for(var J=T;J<A;++J)L+=$I[_[J]];return L}function HI(_,T,A){var E=_.slice(T,A),L="";for(var J=0;J<E.length-1;J+=2)L+=String.fromCharCode(E[J]+E[J+1]*256);return L}B.prototype.slice=function(T,A){var E=this.length;if(T=~~T,A=A===void 0?E:~~A,T<0){if(T+=E,T<0)T=0}else if(T>E)T=E;if(A<0){if(A+=E,A<0)A=0}else if(A>E)A=E;if(A<T)A=T;var L=this.subarray(T,A);return Object.setPrototypeOf(L,B.prototype),L};function h_(_,T,A){if(_%1!==0||_<0)throw RangeError("offset is not uint");if(_+T>A)throw RangeError("Trying to access beyond buffer length")}B.prototype.readUintLE=B.prototype.readUIntLE=function(T,A,E){if(T=T>>>0,A=A>>>0,!E)h_(T,A,this.length);var L=this[T],J=1,X=0;while(++X<A&&(J*=256))L+=this[T+X]*J;return L};B.prototype.readUintBE=B.prototype.readUIntBE=function(T,A,E){if(T=T>>>0,A=A>>>0,!E)h_(T,A,this.length);var L=this[T+--A],J=1;while(A>0&&(J*=256))L+=this[T+--A]*J;return L};B.prototype.readUint8=B.prototype.readUInt8=function(T,A){if(T=T>>>0,!A)h_(T,1,this.length);return this[T]};B.prototype.readUint16LE=B.prototype.readUInt16LE=function(T,A){if(T=T>>>0,!A)h_(T,2,this.length);return this[T]|this[T+1]<<8};B.prototype.readUint16BE=B.prototype.readUInt16BE=function(T,A){if(T=T>>>0,!A)h_(T,2,this.length);return this[T]<<8|this[T+1]};B.prototype.readUint32LE=B.prototype.readUInt32LE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216};B.prototype.readUint32BE=B.prototype.readUInt32BE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])};B.prototype.readIntLE=function(T,A,E){if(T=T>>>0,A=A>>>0,!E)h_(T,A,this.length);var L=this[T],J=1,X=0;while(++X<A&&(J*=256))L+=this[T+X]*J;if(J*=128,L>=J)L-=Math.pow(2,8*A);return L};B.prototype.readIntBE=function(T,A,E){if(T=T>>>0,A=A>>>0,!E)h_(T,A,this.length);var L=A,J=1,X=this[T+--L];while(L>0&&(J*=256))X+=this[T+--L]*J;if(J*=128,X>=J)X-=Math.pow(2,8*A);return X};B.prototype.readInt8=function(T,A){if(T=T>>>0,!A)h_(T,1,this.length);if(!(this[T]&128))return this[T];return(255-this[T]+1)*-1};B.prototype.readInt16LE=function(T,A){if(T=T>>>0,!A)h_(T,2,this.length);var E=this[T]|this[T+1]<<8;return E&32768?E|4294901760:E};B.prototype.readInt16BE=function(T,A){if(T=T>>>0,!A)h_(T,2,this.length);var E=this[T+1]|this[T]<<8;return E&32768?E|4294901760:E};B.prototype.readInt32LE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24};B.prototype.readInt32BE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]};B.prototype.readFloatLE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return J4.read(this,T,!0,23,4)};B.prototype.readFloatBE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return J4.read(this,T,!1,23,4)};B.prototype.readDoubleLE=function(T,A){if(T=T>>>0,!A)h_(T,8,this.length);return J4.read(this,T,!0,52,8)};B.prototype.readDoubleBE=function(T,A){if(T=T>>>0,!A)h_(T,8,this.length);return J4.read(this,T,!1,52,8)};function H1(_,T,A,E,L,J){if(!B.isBuffer(_))throw TypeError('"buffer" argument must be a Buffer instance');if(T>L||T<J)throw RangeError('"value" argument is out of bounds');if(A+E>_.length)throw RangeError("Index out of range")}B.prototype.writeUintLE=B.prototype.writeUIntLE=function(T,A,E,L){if(T=+T,A=A>>>0,E=E>>>0,!L){var J=Math.pow(2,8*E)-1;H1(this,T,A,E,J,0)}var X=1,H=0;this[A]=T&255;while(++H<E&&(X*=256))this[A+H]=T/X&255;return A+E};B.prototype.writeUintBE=B.prototype.writeUIntBE=function(T,A,E,L){if(T=+T,A=A>>>0,E=E>>>0,!L){var J=Math.pow(2,8*E)-1;H1(this,T,A,E,J,0)}var X=E-1,H=1;this[A+X]=T&255;while(--X>=0&&(H*=256))this[A+X]=T/H&255;return A+E};B.prototype.writeUint8=B.prototype.writeUInt8=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,1,255,0);return this[A]=T&255,A+1};B.prototype.writeUint16LE=B.prototype.writeUInt16LE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,2,65535,0);return this[A]=T&255,this[A+1]=T>>>8,A+2};B.prototype.writeUint16BE=B.prototype.writeUInt16BE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,2,65535,0);return this[A]=T>>>8,this[A+1]=T&255,A+2};B.prototype.writeUint32LE=B.prototype.writeUInt32LE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,4,4294967295,0);return this[A+3]=T>>>24,this[A+2]=T>>>16,this[A+1]=T>>>8,this[A]=T&255,A+4};B.prototype.writeUint32BE=B.prototype.writeUInt32BE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,4,4294967295,0);return this[A]=T>>>24,this[A+1]=T>>>16,this[A+2]=T>>>8,this[A+3]=T&255,A+4};B.prototype.writeIntLE=function(T,A,E,L){if(T=+T,A=A>>>0,!L){var J=Math.pow(2,8*E-1);H1(this,T,A,E,J-1,-J)}var X=0,H=1,Z=0;this[A]=T&255;while(++X<E&&(H*=256)){if(T<0&&Z===0&&this[A+X-1]!==0)Z=1;this[A+X]=(T/H>>0)-Z&255}return A+E};B.prototype.writeIntBE=function(T,A,E,L){if(T=+T,A=A>>>0,!L){var J=Math.pow(2,8*E-1);H1(this,T,A,E,J-1,-J)}var X=E-1,H=1,Z=0;this[A+X]=T&255;while(--X>=0&&(H*=256)){if(T<0&&Z===0&&this[A+X+1]!==0)Z=1;this[A+X]=(T/H>>0)-Z&255}return A+E};B.prototype.writeInt8=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,1,127,-128);if(T<0)T=255+T+1;return this[A]=T&255,A+1};B.prototype.writeInt16LE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,2,32767,-32768);return this[A]=T&255,this[A+1]=T>>>8,A+2};B.prototype.writeInt16BE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,2,32767,-32768);return this[A]=T>>>8,this[A+1]=T&255,A+2};B.prototype.writeInt32LE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,4,2147483647,-2147483648);return this[A]=T&255,this[A+1]=T>>>8,this[A+2]=T>>>16,this[A+3]=T>>>24,A+4};B.prototype.writeInt32BE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,4,2147483647,-2147483648);if(T<0)T=4294967295+T+1;return this[A]=T>>>24,this[A+1]=T>>>16,this[A+2]=T>>>8,this[A+3]=T&255,A+4};function NY(_,T,A,E,L,J){if(A+E>_.length)throw RangeError("Index out of range");if(A<0)throw RangeError("Index out of range")}function QY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)NY(_,T,A,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return J4.write(_,T,A,E,23,4),A+4}B.prototype.writeFloatLE=function(T,A,E){return QY(this,T,A,!0,E)};B.prototype.writeFloatBE=function(T,A,E){return QY(this,T,A,!1,E)};function MY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)NY(_,T,A,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return J4.write(_,T,A,E,52,8),A+8}B.prototype.writeDoubleLE=function(T,A,E){return MY(this,T,A,!0,E)};B.prototype.writeDoubleBE=function(T,A,E){return MY(this,T,A,!1,E)};B.prototype.copy=function(T,A,E,L){if(!B.isBuffer(T))throw TypeError("argument should be a Buffer");if(!E)E=0;if(!L&&L!==0)L=this.length;if(A>=T.length)A=T.length;if(!A)A=0;if(L>0&&L<E)L=E;if(L===E)return 0;if(T.length===0||this.length===0)return 0;if(A<0)throw RangeError("targetStart out of bounds");if(E<0||E>=this.length)throw RangeError("Index out of range");if(L<0)throw RangeError("sourceEnd out of bounds");if(L>this.length)L=this.length;if(T.length-A<L-E)L=T.length-A+E;var J=L-E;if(this===T&&typeof Uint8Array.prototype.copyWithin==="function")this.copyWithin(A,E,L);else Uint8Array.prototype.set.call(T,this.subarray(E,L),A);return J};B.prototype.fill=function(T,A,E,L){if(typeof T==="string"){if(typeof A==="string")L=A,A=0,E=this.length;else if(typeof E==="string")L=E,E=this.length;if(L!==void 0&&typeof L!=="string")throw TypeError("encoding must be a string");if(typeof L==="string"&&!B.isEncoding(L))throw TypeError("Unknown encoding: "+L);if(T.length===1){var J=T.charCodeAt(0);if(L==="utf8"&&J<128||L==="latin1")T=J}}else if(typeof T==="number")T=T&255;else if(typeof T==="boolean")T=Number(T);if(A<0||this.length<A||this.length<E)throw RangeError("Out of range index");if(E<=A)return this;if(A=A>>>0,E=E===void 0?this.length:E>>>0,!T)T=0;var X;if(typeof T==="number")for(X=A;X<E;++X)this[X]=T;else{var H=B.isBuffer(T)?T:B.from(T,L),Z=H.length;if(Z===0)throw TypeError('The value "'+T+'" is invalid for argument "value"');for(X=0;X<E-A;++X)this[X+A]=H[X%Z]}return this};var ZI=/[^+/0-9A-Za-z-_]/g;function YI(_){if(_=_.split("=")[0],_=_.trim().replace(ZI,""),_.length<2)return"";while(_.length%4!==0)_=_+"=";return _}function hE(_,T){T=T||1/0;var A,E=_.length,L=null,J=[];for(var X=0;X<E;++X){if(A=_.charCodeAt(X),A>55295&&A<57344){if(!L){if(A>56319){if((T-=3)>-1)J.push(239,191,189);continue}else if(X+1===E){if((T-=3)>-1)J.push(239,191,189);continue}L=A;continue}if(A<56320){if((T-=3)>-1)J.push(239,191,189);L=A;continue}A=(L-55296<<10|A-56320)+65536}else if(L){if((T-=3)>-1)J.push(239,191,189)}if(L=null,A<128){if((T-=1)<0)break;J.push(A)}else if(A<2048){if((T-=2)<0)break;J.push(A>>6|192,A&63|128)}else if(A<65536){if((T-=3)<0)break;J.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((T-=4)<0)break;J.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw Error("Invalid code point")}return J}function KI(_){var T=[];for(var A=0;A<_.length;++A)T.push(_.charCodeAt(A)&255);return T}function GI(_,T){var A,E,L,J=[];for(var X=0;X<_.length;++X){if((T-=2)<0)break;A=_.charCodeAt(X),E=A>>8,L=A%256,J.push(L),J.push(E)}return J}function VY(_){return SE.toByteArray(YI(_))}function bA(_,T,A,E){for(var L=0;L<E;++L){if(L+A>=T.length||L>=_.length)break;T[L+A]=_[L]}return L}function X0(_,T){return _ instanceof T||_!=null&&_.constructor!=null&&_.constructor.name!=null&&_.constructor.name===T.name}function bE(_){return _!==_}var $I=function(){var _="0123456789abcdef",T=Array(256);for(var A=0;A<16;++A){var E=A*16;for(var L=0;L<16;++L)T[E+L]=_[A]+_[L]}return T}()});var BY=W((gb,gE)=>{var CY=_Y(),RY=EY(),gA=MI();function MI(){let _=j("buffer");return _&&_.Buffer?_.Buffer:FY().Buffer}var VI=gA.from("==","base64");function zI(_){let T=!1,A=!1,E=Math.pow(2,31)-1;if(typeof _==="boolean")T=_;else _=_||{},E=_.maxInt||Math.pow(2,31)-1,A=!!_.urlSafe,T=!!_.fixedLength;X.uuid=CY(),X.decode=DY;let L=OY(X.uuid,A),J=Math.floor(_.startFrom||0);if(isNaN(E))throw Error(`maxInt must be a number. recieved ${_.maxInt}`);if(isNaN(J)||!(E>J&&J>=0))throw Error([`when passed, opts.startFrom must be a number between 0 and ${E}.`,"Only the integer part matters.",`- got: ${_.startFrom}`].join(`
|
|
13
|
+
`));return X;function X(){let H;if(J===E)X.uuid=CY(),L=OY(X.uuid,A),J=0;if(T)H=L+`0000000000${J}`.slice(-10);else H=L+J;return J=J+1|0,H}}function OY(_,T){let A=gA.concat([gA.from(RY.parse(_)),VI]).toString("base64");if(T)return A.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"-");return A.replace(/=+$/,"/")}function DY(_,T){if(T=T||{},!!T.urlSafe)_=_.replace(/-([^-]*)$/,"/$1").replace(/-/g,"+").replace(/_/g,"/");if(_.length<22)return null;let E=_.lastIndexOf("/");if(E===-1)return null;let L=_.substring(0,E),J=Number(_.substring(E+1));if(!L||isNaN(J))return null;return{uuid:RY.unparse(gA.from(L+"==","base64")),count:J}}gE.exports=zI;gE.exports.decode=DY});var PY=W((mb,IY)=>{var FI=X2(),{pipeline:CI}=j("stream"),qY=j0(),OI=VE(),{through:RI}=RT(),DI=yA(),BI=BY()();function qI(_){this.cmd="connack",this.returnCode=_.returnCode,this.sessionPresent=_.sessionPresent}function II(_,T){this.client=_,this.packet=T}var PI=[wI,SI,yI,hI,kI,fI,uE,bI],mE=["","unacceptable protocol version","identifier rejected","Server unavailable","bad user name or password","not authorized","keep alive limit exceeded"];function jI(_,T,A){clearTimeout(_._connectTimer),_._connectTimer=null,_.connecting=!0,_.broker.preConnect(_,T,E);function E(L,J){if(!L&&J===!0)setImmediate(xI,_,T,A);else _.connecting=!1,A(L)}}function xI(_,T,A){let E=T.clientId,L=0;if(T.protocolVersion<3||T.protocolVersion>4)L=1;if(T.protocolVersion===3&&E.length>_.broker.maxClientsIdLength)L=2;if(_.broker.keepaliveLimit&&(!T.keepalive||T.keepalive>_.broker.keepaliveLimit))L=6;if(L>0){let J=Error(mE[L]);J.errorCode=L,uE({client:_,returnCode:L,sessionPresent:!1},A.bind(this,J));return}_.id=E||"aedes_"+BI(),_.clean=T.clean,_.version=T.protocolVersion,_._will=T.will,_.broker._series(new II(_,T),PI,{returnCode:0,sessionPresent:!1},function(J){if(this.client.connecting=!1,!J)this.client.connected=!0,this.client.broker.emit("clientReady",_),this.client.emit("connected");A(J)})}function wI(_,T){let A=this.client;A.pause(),A.broker.authenticate(A,this.packet.username,this.packet.password,E);function E(L,J){if(A.closed||A.broker.closed)return;if(!L&&J)return A._authorized=!0,T();if(L){let X=L.returnCode;if(X&&(X>=2&&X<=5))_.returnCode=X;else _.returnCode=5;if(!L.message)L.message=mE[_.returnCode]}else _.returnCode=5,L=Error(mE[_.returnCode]);L.errorCode=_.returnCode,_.client=A,uE(_,A.close.bind(A,T.bind(this,L)))}}function SI(_,T){if(this.packet.keepalive>0){let A=this.client;A._keepaliveInterval=this.packet.keepalive*1500+1,A._keepaliveTimer=FI(function(){A.broker.emit("keepaliveTimeout",A),A.emit("error",Error("keep alive timeout"))},A._keepaliveInterval)}T()}function yI(_,T){let A=this.client;if(!this.packet.clean){A.broker.persistence.subscriptionsByClient({id:A.id,done:T,arg:_},vI);return}_.sessionPresent=!1,A.broker.persistence.cleanSubscriptions(A,T)}function vI(_,T,A){if(_)return A.done(_);A.arg.subs=T,A.done()}function hI(_,T){if(_.subs){DI(this.client,{subscriptions:_.subs},!0,T),_.sessionPresent=!!_.subs;return}_.sessionPresent=!1,T()}function kI(_,T){let A=this.client;A.will=A._will,A.broker.persistence.delWill(A,function(){if(A.will)A.broker.persistence.putWill(A,A.will,T);else T()})}function fI(_,T){let A=this.client;A.broker.registerClient(A),T()}function uE(_,T){let A=_.client||this.client,E=new qI(_);qY(A,E,function(L){if(!L)A.broker.emit("connackSent",E,A),A.connackSent=!0;T(L)})}function bI(_,T){let A=this.client,E=A.broker.persistence,L=E.outgoingStream(A);A.resume(),CI(L,RI(function(X,H,Z){let Y=new OI(X,A);Y.writeCallback=(K,G)=>Z(K),E.outgoingUpdate(A,Y,gI)}),T)}function gI(_,T,A){let E=A.writeCallback;if(_)return T.emit("error",_),E();let L=A.cmd==="publish"?T.broker.authorizeForward(T,A):!0,J=T.broker.persistence;if(T.clean||!L)J.outgoingClearMessageId(T,A,E);else qY(T,A,E)}IY.exports=jI});var wY=W((ub,xY)=>{var jY=j0();function mI(_){this.cmd="puback",this.messageId=_.messageId}function uI(_){this.cmd="pubrec",this.messageId=_.messageId}var dI=[lI,pI];function cI(_,T,A){let E=T.topic,L;if(E.length===0)return L=Error("empty topic not allowed in PUBLISH"),A(L);if(E.indexOf("#")>-1)return L=Error("# is not allowed in PUBLISH"),A(L);if(E.indexOf("+")>-1)return L=Error("+ is not allowed in PUBLISH"),A(L);_.broker._series(_,dI,T,A)}function pI(_,T){let A=this;switch(_.qos){case 2:A.broker.persistence.incomingStorePacket(A,_,function(E){if(E)return T(E);jY(A,new uI(_),T)});break;case 1:jY(A,new mI(_),function(E){if(E)return T(E);A.broker.publish(_,A,T)});break;case 0:A.broker.publish(_,A,T);break;default:}}function lI(_,T){this.broker.authorizePublish(this,_,T)}xY.exports=cI});var yY=W((db,SY)=>{function nI(_,T,A){_.broker.persistence.outgoingClearMessageId(_,T,function(L,J){_.broker.emit("ack",J,_),A(L)})}SY.exports=nI});var hY=W((cb,vY)=>{var iI=j0();function aI(_,T){this.client=_,this.packet=T}function oI(_){this.cmd="pubcomp",this.messageId=_.messageId}var rI=[tI,eI,_P,TP];function sI(_,T,A){_.broker._series(new aI(_,T),rI,{},A)}function tI(_,T){this.client.broker.persistence.incomingGetPacket(this.client,this.packet,E);function E(L,J){_.packet=J,T(L)}}function eI(_,T){this.client.broker.publish(_.packet,this.client,T)}function _P(_,T){iI(this.client,new oI(_.packet),T)}function TP(_,T){this.client.broker.persistence.incomingDelPacket(this.client,_.packet,T)}vY.exports=sI});var bY=W((pb,fY)=>{var kY=j0();function AP(_){this.cmd="pubrel",this.messageId=_.messageId}function EP(_,T,A){let E=new AP(T);if(_.clean){kY(_,E,A);return}_.broker.persistence.outgoingUpdate(_,E,L);function L(J){if(J)A(J);else kY(_,E,A)}}fY.exports=EP});var mY=W((lb,gY)=>{var LP=j0(),JP={cmd:"pingresp"};function XP(_,T,A){_.broker.emit("ping",T,_),LP(_,JP,A)}gY.exports=XP});var cY=W((nb,dY)=>{var HP=PY(),ZP=yA(),YP=FE(),KP=wY(),GP=yY(),$P=hY(),UP=bY(),WP=mY();function NP(_,T,A){if(T.cmd==="connect"){if(_.connecting||_.connected){uY(_.conn,T,A);return}HP(_,T,A);return}if(!_.connecting&&!_.connected){uY(_.conn,T,A);return}switch(T.cmd){case"publish":KP(_,T,A);break;case"subscribe":ZP(_,T,!1,A);break;case"unsubscribe":YP(_,T,A);break;case"pubcomp":case"puback":GP(_,T,A);break;case"pubrel":$P(_,T,A);break;case"pubrec":UP(_,T,A);break;case"pingreq":WP(_,T,A);break;case"disconnect":_._disconnected=!0,_.conn.destroy(),A();return;default:_.conn.destroy(),A();return}if(_._keepaliveInterval>0)_._keepaliveTimer.reschedule(_._keepaliveInterval)}function uY(_,T,A){_.destroy();let E=Error("Invalid protocol");E.info=T,A(E)}dY.exports=NP});var sY=W((ib,rY)=>{var QP=wA(),MP=j("events"),VP=j("util"),zP=bZ(),lY=uT(),nY=j0(),FP=VE(),CP=yA(),iY=FE(),aY=cY(),{pipeline:OP}=j("stream"),{through:RP}=RT();rY.exports=H0;function H0(_,T,A){let E=this;this.closed=!1,this.connecting=!1,this.connected=!1,this.connackSent=!1,this.errored=!1,this.id=null,this.clean=!0,this.version=null,this.subscriptions={},this.duplicates={},this.broker=_,this.conn=T,T.client=this,this._disconnected=!1,this._authorized=!1,this._parsingBatch=1,this._nextId=Math.ceil(Math.random()*65535),this.req=A,this.connDetails=A?A.connDetails:null,this.will=null,this._will=null,this._parser=QP.parser(),this._parser.client=this,this._parser._queue=[],this._parser.on("packet",qP),this.once("connected",IP);function L(X){if(X){E.emit("error",X);return}let H=E;if(H._paused)return;if(E._parsingBatch--,E._parsingBatch<=0){E._parsingBatch=0;let Z=H.conn.read(null);if(Z)H._parser.parse(Z)}}this._nextBatch=L,T.on("readable",L),this.on("error",oY),T.on("error",this.emit.bind(this,"error")),this._parser.on("error",this.emit.bind(this,"error")),T.on("end",this.close.bind(this)),this._eos=zP(this.conn,this.close.bind(this));let J=(X)=>{if(X.clientId===E.id&&X.nl)return;return DP(E,X)&&E.broker.authorizeForward(E,X)};this.deliver0=function(H,Z){let Y=J(H);if(Y)setImmediate(()=>{let K=new lY(Y,_);K.qos=0,nY(E,K,function(G){E._onError(G),Z()})});else setImmediate(Z)},this.deliverQoS=function(H,Z){if(H.qos===0){E.deliver0(H,Z);return}let Y=J(H);if(Y)setImmediate(()=>{let K=new FP(Y,E),G=E.subscriptions[K.topic];if(G&&(G.qos||0)<K.qos)K.qos=G.qos;if(K.writeCallback=Z,E.clean||K.retain)pY(null,E,K);else _.persistence.outgoingUpdate(E,K,pY)});else if(E.clean===!1)E.broker.persistence.outgoingClearMessageId(E,H,X4),setImmediate(Z);else setImmediate(Z)},this._keepaliveTimer=null,this._keepaliveInterval=-1,this._connectTimer=setTimeout(function(){E.emit("error",Error("connect did not arrive in time"))},_.connectTimeout)}function DP(_,T){let A=T.brokerId;if(!A)return!0;let E=_.duplicates,L=T.brokerCounter,J=(E[A]||0)<L;if(J)E[A]=L;return J}function pY(_,T,A){if(_)T.emit("error",_),A.writeCallback();else nY(T,A,function(E){if(E)T.emit("error",E);A.writeCallback()})}function BP(_){_.callback()}function oY(_){if(!_)return;this.errored=!0,this.conn.removeAllListeners("error"),this.conn.on("error",X4);let T=this.conn._writableState;(typeof T.getBuffer==="function"?T.getBuffer():T.buffer).forEach(BP),this.broker.emit(this.id?"clientError":"connectionError",this,_),this.close()}VP.inherits(H0,MP);H0.prototype._onError=oY;H0.prototype.publish=function(_,T){let A=new lY(_,this.broker),E=this;if(A.qos===0){this.deliver0(A,T);return}if(!this.clean&&this.id)this.broker.persistence.outgoingEnqueue({clientId:this.id},A,function(J){if(J)return T(J);E.deliverQoS(A,T)});else E.deliverQoS(A,T)};H0.prototype.subscribe=function(_,T){if(!_.subscriptions){if(!Array.isArray(_))_=[_];_={subscriptions:_}}CP(this,_,!1,T)};H0.prototype.unsubscribe=function(_,T){if(!_.unsubscriptions){if(!Array.isArray(_))_=[_];_={unsubscriptions:_}}iY(this,_,T)};H0.prototype.close=function(_){if(this.closed){if(typeof _==="function")_();return}let T=this,A=this.conn;if(this.closed=!0,this._parser.removeAllListeners("packet"),A.removeAllListeners("readable"),this._parser._queue=null,this._keepaliveTimer)this._keepaliveTimer.clear(),this._keepaliveInterval=-1,this._keepaliveTimer=null;if(this._connectTimer)clearTimeout(this._connectTimer),this._connectTimer=null;this._eos(),this._eos=X4,iY(this,{unsubscriptions:Object.keys(this.subscriptions)},E);function E(){let L=T.will;if(!T._disconnected&&L)T.broker.authorizePublish(T,L,function(J){if(J)return X();T.broker.publish(L,T,X);function X(){T.broker.persistence.delWill({id:T.id,brokerId:T.broker.id},X4)}});else if(L)T.broker.persistence.delWill({id:T.id,brokerId:T.broker.id},X4);if(T.will=null,T._will=null,T.connected=!1,T.connecting=!1,A.removeAllListeners("error"),A.on("error",X4),T.broker.clients[T.id]&&T._authorized)T.broker.unregisterClient(T);if(T.conn.emit("drain"),T.conn.removeAllListeners("drain"),A.destroy(),typeof _==="function")_()}};H0.prototype.pause=function(){this._paused=!0};H0.prototype.resume=function(){this._paused=!1,this._nextBatch()};function qP(_){let T=this.client;if(T._parsingBatch++,T.connackSent||T._parsingBatch===1)aY(T,_,T._nextBatch);else if(this._queue.length<T.broker.queueLimit)this._queue.push(_);else this.emit("error",Error("Client queue limit reached"))}function IP(){let _=this._parser._queue;if(_){for(let T=0,A=_.length;T<A;T++)aY(this,_[T],this._nextBatch);this._parser._queue=null}}H0.prototype.emptyOutgoingQueue=function(_){let T=this,A=T.broker.persistence;function E(L,J,X){A.outgoingClearMessageId(T,L,X)}OP(A.outgoingStream(T),RP(E),_)};function X4(){}});var tY=W((ab,PP)=>{PP.exports={name:"aedes",version:"0.51.3",description:"Stream-based MQTT broker",main:"aedes.js",types:"aedes.d.ts",scripts:{lint:"npm run lint:standard && npm run lint:typescript && npm run lint:markdown","lint:fix":"standard --fix && eslint -c types/.eslintrc.json --fix aedes.d.ts types/**/*.ts test/types/**/*.test-d.ts","lint:standard":"standard --verbose | snazzy","lint:typescript":"eslint -c types/.eslintrc.json aedes.d.ts types/**/*.ts test/types/**/*.test-d.ts","lint:markdown":"markdownlint docs/*.md README.md",test:"npm run lint && npm run unit && npm run test:typescript","test:ci":"npm run lint && npm run unit -- --cov --no-check-coverage --coverage-report=lcovonly && npm run test:typescript","test:report":"npm run lint && npm run unit:report && npm run test:typescript","test:typescript":"tsd",unit:"tap -J test/*.js","unit:report":"tap -J test/*.js --cov --coverage-report=html --coverage-report=cobertura | tee out.tap","license-checker":'license-checker --production --onlyAllow="MIT;ISC;BSD-3-Clause;BSD-2-Clause;0BSD"',release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it --disable-metrics"},"release-it":{github:{release:!0},git:{tagName:"v${version}"},hooks:{"before:init":["npm run test:ci"]},npm:{publish:!0}},"pre-commit":["test"],tsd:{directory:"test/types"},standard:{ignore:["types/*","test/types/*"]},repository:{type:"git",url:"git+https://github.com/moscajs/aedes.git"},keywords:["mqtt","broker","server","mqtt-server","stream","streams","publish","subscribe","pubsub","messaging","mosca","mosquitto","iot","internet","of","things"],author:"Matteo Collina <hello@matteocollina.com>",contributors:[{name:"Gavin D'mello",url:"https://github.com/GavinDmello"},{name:"Behrad Zari",url:"https://github.com/behrad"},{name:"Gnought",url:"https://github.com/gnought"},{name:"Daniel Lando",url:"https://github.com/robertsLando"}],license:"MIT",funding:{type:"opencollective",url:"https://opencollective.com/aedes"},bugs:{url:"https://github.com/moscajs/aedes/issues"},homepage:"https://github.com/moscajs/aedes#readme",engines:{node:">=16"},devDependencies:{"@sinonjs/fake-timers":"^11.2.2","@types/node":"^20.11.17","@typescript-eslint/eslint-plugin":"^7.0.1","@typescript-eslint/parser":"^7.0.1","concat-stream":"^2.0.0",duplexify:"^4.1.2","license-checker":"^25.0.1","markdownlint-cli":"^0.41.0",mqtt:"^5.3.5","mqtt-connection":"^4.1.0","pre-commit":"^1.2.2",proxyquire:"^2.1.3","release-it":"^17.0.5",snazzy:"^9.0.0",standard:"^17.1.0",tap:"^16.3.10",tsd:"^0.31.0",typescript:"^5.3.3","websocket-stream":"^5.5.2"},dependencies:{"aedes-packet":"^3.0.0","aedes-persistence":"^9.1.2","end-of-stream":"^1.4.4",fastfall:"^1.5.1",fastparallel:"^2.4.1",fastseries:"^2.0.0",hyperid:"^3.2.0",mqemitter:"^6.0.0","mqtt-packet":"^9.0.0",retimer:"^4.0.0",reusify:"^1.0.4",uuid:"^10.0.0"}}});var EK=W((ob,AK)=>{var jP=j("events"),xP=j("util"),wP=h5(),SP=I9(),{v4:yP}=w7(),vP=k8(),{pipeline:hP}=j("stream"),kP=uT(),fP=m7(),bP=i7(),gP=sY(),{$SYS_PREFIX:Z0,bulk:mP}=RT();AK.exports=Z1.createBroker=Z1;var uP={concurrency:100,heartbeatInterval:60000,connectTimeout:30000,decodeProtocol:null,preConnect:aP,authenticate:oP,authorizePublish:rP,authorizeSubscribe:sP,authorizeForward:tP,published:eP,trustProxy:!1,trustedProxies:[],queueLimit:42,maxClientsIdLength:23,keepaliveLimit:0};function Z1(_){let T=this;if(!(this instanceof Z1))return new Z1(_);_=Object.assign({},uP,_),this.id=_.id||yP(),this.counter=0,this.queueLimit=_.queueLimit,this.connectTimeout=_.connectTimeout,this.keepaliveLimit=_.keepaliveLimit,this.maxClientsIdLength=_.maxClientsIdLength,this.mq=_.mq||bP({concurrency:_.concurrency,matchEmptyLevels:!0}),this.handle=function(K,G){return K.setMaxListeners(_.concurrency*2),new gP(T,K,G)},this.persistence=_.persistence||fP(),this.persistence.broker=this,this._parallel=wP(),this._series=SP(),this._enqueuers=vP(cP),this.preConnect=_.preConnect,this.authenticate=_.authenticate,this.authorizePublish=_.authorizePublish,this.authorizeSubscribe=_.authorizeSubscribe,this.authorizeForward=_.authorizeForward,this.published=_.published,this.decodeProtocol=_.decodeProtocol,this.trustProxy=_.trustProxy,this.trustedProxies=_.trustedProxies,this.clients={},this.brokers={};let A=Z0+T.id+"/heartbeat",E=Z0+T.id+"/birth";this._heartbeatInterval=setInterval(J,_.heartbeatInterval);let L=Buffer.from(T.id,"utf8");T.publish({topic:E,payload:L},s4);function J(){T.publish({topic:A,payload:L},s4)}function X(Y){if(T.brokers[Y]+3*_.heartbeatInterval<Date.now())delete T.brokers[Y]}this._clearWillInterval=setInterval(function(){Object.keys(T.brokers).forEach(X),hP(T.persistence.streamWill(T.brokers),mP(H),function(K){if(K)T.emit("error",K)})},_.heartbeatInterval*4);function H(Y,K){T._parallel(T,Z,Y,K)}function Z(Y,K){if(T.brokers[Y.brokerId]!==void 0&&T.brokers[Y.brokerId]+3*_.heartbeatInterval>=Date.now())return K();this.authorizePublish(T.clients[Y.clientId]||null,Y,function($){if($)return U();T.publish(Y,U);function U(V){if(V)return K(V);T.persistence.delWill({id:Y.clientId,brokerId:Y.brokerId},K)}})}this.mq.on(Z0+"+/heartbeat",function(K,G){T.brokers[K.payload.toString()]=Date.now(),G()}),this.mq.on(Z0+"+/birth",function(K,G){let $=K.payload.toString();if($!==T.id)for(let U in T.clients)delete T.clients[U].duplicates[$];G()}),this.mq.on(Z0+"+/new/clients",function(K,G){let $=K.topic.split("/")[1],U=K.payload.toString();if(T.clients[U]&&$!==T.id)if(T.clients[U].closed)T.deleteClient(U),G();else T.clients[U].close(G);else G()}),this.connectedClients=0,this.closed=!1}xP.inherits(Z1,jP);function eY(_,T){if(_.retain)this.broker.persistence.storeRetained(_,T);else T()}function _K(_,T){if(this.client)_.clientId=this.client.id;this.broker.mq.emit(_,T)}function dP(_,T){let A=this.broker._enqueuers.get();A.complete=T,A.packet=_,A.topic=_.topic,A.broker=this.broker,this.broker.persistence.subscriptionsByTopic(_.topic,A.done)}function cP(){this.next=null,this.complete=null,this.packet=null,this.topic=null,this.broker=null;let _=this;this.done=function(A,E){let L=_.broker;if(A){L.emit("error",A);return}if(_.topic.indexOf(Z0)===0)E=E.filter(pP);let{packet:J,complete:X}=_;_.packet=null,_.complete=null,_.topic=null,L.persistence.outgoingEnqueueCombi(E,J,X),L._enqueuers.release(_)}}function pP(_){let T=_.topic.charCodeAt(0);return T!==43&&T!==35}function TK(_,T){this.broker.published(this.packet,this.client,T),this.broker.emit("publish",this.packet,this.client)}var lP=[eY,_K,TK],nP=[eY,dP,_K,TK];Z1.prototype.publish=function(_,T,A){if(typeof T==="function")A=T,T=null;let E=new kP(_,this),L=E.qos>0?nP:lP;this._series(new _j(this,T,_),L,E,A)};Z1.prototype.subscribe=function(_,T,A){this.mq.on(_,T,A)};Z1.prototype.unsubscribe=function(_,T,A){this.mq.removeListener(_,T,A)};Z1.prototype.registerClient=function(_){let T=this;if(this.clients[_.id])this.clients[_.id].close(function(){T._finishRegisterClient(_)});else this._finishRegisterClient(_)};Z1.prototype._finishRegisterClient=function(_){this.connectedClients++,this.clients[_.id]=_,this.emit("client",_),this.publish({topic:Z0+this.id+"/new/clients",payload:Buffer.from(_.id,"utf8")},s4)};Z1.prototype.unregisterClient=function(_){this.deleteClient(_.id),this.emit("clientDisconnect",_),this.publish({topic:Z0+this.id+"/disconnect/clients",payload:Buffer.from(_.id,"utf8")},s4)};Z1.prototype.deleteClient=function(_){this.connectedClients--,delete this.clients[_]};function iP(_,T){this.clients[_].close(T)}Z1.prototype.close=function(_=s4){let T=this;if(this.closed)return _();this.closed=!0,clearInterval(this._heartbeatInterval),clearInterval(this._clearWillInterval),this._parallel(this,iP,Object.keys(this.clients),A);function A(){T.emit("closed"),T.mq.close(_)}};Z1.prototype.version=tY().version;function aP(_,T,A){A(null,!0)}function oP(_,T,A,E){E(null,!0)}function rP(_,T,A){if(T.topic.startsWith(Z0))return A(Error(Z0+" topic is reserved"));A(null)}function sP(_,T,A){A(null,T)}function tP(_,T){return T}function eP(_,T,A){A(null)}function _j(_,T,A){this.broker=_,this.client=T,this.packet=A}function s4(){}});var HK=W((Lg,XK)=>{XK.exports=Aj;function H4(_){if(_ instanceof Buffer)return Buffer.from(_);return new _.constructor(_.buffer.slice(),_.byteOffset,_.length)}function Aj(_){if(_=_||{},_.circles)return Ej(_);let T=new Map;if(T.set(Date,(X)=>new Date(X)),T.set(Map,(X,H)=>new Map(E(Array.from(X),H))),T.set(Set,(X,H)=>new Set(E(Array.from(X),H))),_.constructorHandlers)for(let X of _.constructorHandlers)T.set(X[0],X[1]);let A=null;return _.proto?J:L;function E(X,H){let Z=Object.keys(X),Y=Array(Z.length);for(let K=0;K<Z.length;K++){let G=Z[K],$=X[G];if(typeof $!=="object"||$===null)Y[G]=$;else if($.constructor!==Object&&(A=T.get($.constructor)))Y[G]=A($,H);else if(ArrayBuffer.isView($))Y[G]=H4($);else Y[G]=H($)}return Y}function L(X){if(typeof X!=="object"||X===null)return X;if(Array.isArray(X))return E(X,L);if(X.constructor!==Object&&(A=T.get(X.constructor)))return A(X,L);let H={};for(let Z in X){if(Object.hasOwnProperty.call(X,Z)===!1)continue;let Y=X[Z];if(typeof Y!=="object"||Y===null)H[Z]=Y;else if(Y.constructor!==Object&&(A=T.get(Y.constructor)))H[Z]=A(Y,L);else if(ArrayBuffer.isView(Y))H[Z]=H4(Y);else H[Z]=L(Y)}return H}function J(X){if(typeof X!=="object"||X===null)return X;if(Array.isArray(X))return E(X,J);if(X.constructor!==Object&&(A=T.get(X.constructor)))return A(X,J);let H={};for(let Z in X){let Y=X[Z];if(typeof Y!=="object"||Y===null)H[Z]=Y;else if(Y.constructor!==Object&&(A=T.get(Y.constructor)))H[Z]=A(Y,J);else if(ArrayBuffer.isView(Y))H[Z]=H4(Y);else H[Z]=J(Y)}return H}}function Ej(_){let T=[],A=[],E=new Map;if(E.set(Date,(Z)=>new Date(Z)),E.set(Map,(Z,Y)=>new Map(J(Array.from(Z),Y))),E.set(Set,(Z,Y)=>new Set(J(Array.from(Z),Y))),_.constructorHandlers)for(let Z of _.constructorHandlers)E.set(Z[0],Z[1]);let L=null;return _.proto?H:X;function J(Z,Y){let K=Object.keys(Z),G=Array(K.length);for(let $=0;$<K.length;$++){let U=K[$],V=Z[U];if(typeof V!=="object"||V===null)G[U]=V;else if(V.constructor!==Object&&(L=E.get(V.constructor)))G[U]=L(V,Y);else if(ArrayBuffer.isView(V))G[U]=H4(V);else{let N=T.indexOf(V);if(N!==-1)G[U]=A[N];else G[U]=Y(V)}}return G}function X(Z){if(typeof Z!=="object"||Z===null)return Z;if(Array.isArray(Z))return J(Z,X);if(Z.constructor!==Object&&(L=E.get(Z.constructor)))return L(Z,X);let Y={};T.push(Z),A.push(Y);for(let K in Z){if(Object.hasOwnProperty.call(Z,K)===!1)continue;let G=Z[K];if(typeof G!=="object"||G===null)Y[K]=G;else if(G.constructor!==Object&&(L=E.get(G.constructor)))Y[K]=L(G,X);else if(ArrayBuffer.isView(G))Y[K]=H4(G);else{let $=T.indexOf(G);if($!==-1)Y[K]=A[$];else Y[K]=X(G)}}return T.pop(),A.pop(),Y}function H(Z){if(typeof Z!=="object"||Z===null)return Z;if(Array.isArray(Z))return J(Z,H);if(Z.constructor!==Object&&(L=E.get(Z.constructor)))return L(Z,H);let Y={};T.push(Z),A.push(Y);for(let K in Z){let G=Z[K];if(typeof G!=="object"||G===null)Y[K]=G;else if(G.constructor!==Object&&(L=E.get(G.constructor)))Y[K]=L(G,H);else if(ArrayBuffer.isView(G))Y[K]=H4(G);else{let $=T.indexOf(G);if($!==-1)Y[K]=A[$];else Y[K]=H(G)}}return T.pop(),A.pop(),Y}}});var YK=W((Jg,ZK)=>{ZK.exports=HK()()});var $K=W((GK)=>{Object.defineProperty(GK,"__esModule",{value:!0});GK.validateTopic=KK;GK.validateTopics=Lj;function KK(_){let T=_.split("/");for(let A=0;A<T.length;A++){if(T[A]==="+")continue;if(T[A]==="#")return A===T.length-1;if(T[A].indexOf("+")!==-1||T[A].indexOf("#")!==-1)return!1}return!0}function Lj(_){if(_.length===0)return"empty_topic_list";for(let T=0;T<_.length;T++)if(!KK(_[T]))return _[T];return null}});var dE=W((WK)=>{Object.defineProperty(WK,"__esModule",{value:!0});var Hj=n0(),Zj={objectMode:!0},Yj={clean:!0};class UK{options;_inflights;constructor(_){this.options=_||{},this.options={...Yj,..._},this._inflights=new Map}put(_,T){if(this._inflights.set(_.messageId,_),T)T();return this}createStream(){let _=new Hj.Readable(Zj),T=[],A=!1,E=0;return this._inflights.forEach((L,J)=>{T.push(L)}),_._read=()=>{if(!A&&E<T.length)_.push(T[E++]);else _.push(null)},_.destroy=(L)=>{if(A)return;return A=!0,setTimeout(()=>{_.emit("close")},0),_},_}del(_,T){let A=this._inflights.get(_.messageId);if(A)this._inflights.delete(_.messageId),T(null,A);else if(T)T(Error("missing packet"));return this}get(_,T){let A=this._inflights.get(_.messageId);if(A)T(null,A);else if(T)T(Error("missing packet"));return this}close(_){if(this.options.clean)this._inflights=null;if(_)_()}}WK.default=UK});var MK=W((QK)=>{Object.defineProperty(QK,"__esModule",{value:!0});var NK=[0,16,128,131,135,144,145,151,153],Gj=(_,T,A)=>{_.log("handlePublish: packet %o",T),A=typeof A<"u"?A:_.noop;let E=T.topic.toString(),L=T.payload,{qos:J}=T,{messageId:X}=T,{options:H}=_;if(_.options.protocolVersion===5){let Z;if(T.properties)Z=T.properties.topicAlias;if(typeof Z<"u")if(E.length===0)if(Z>0&&Z<=65535){let Y=_.topicAliasRecv.getTopicByAlias(Z);if(Y)E=Y,_.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",E,Z);else{_.log("handlePublish :: unregistered topic alias. alias: %d",Z),_.emit("error",Error("Received unregistered Topic Alias"));return}}else{_.log("handlePublish :: topic alias out of range. alias: %d",Z),_.emit("error",Error("Received Topic Alias is out of range"));return}else if(_.topicAliasRecv.put(E,Z))_.log("handlePublish :: registered topic: %s - alias: %d",E,Z);else{_.log("handlePublish :: topic alias out of range. alias: %d",Z),_.emit("error",Error("Received Topic Alias is out of range"));return}}switch(_.log("handlePublish: qos %d",J),J){case 2:{H.customHandleAcks(E,L,T,(Z,Y)=>{if(typeof Z==="number")Y=Z,Z=null;if(Z)return _.emit("error",Z);if(NK.indexOf(Y)===-1)return _.emit("error",Error("Wrong reason code for pubrec"));if(Y)_._sendPacket({cmd:"pubrec",messageId:X,reasonCode:Y},A);else _.incomingStore.put(T,()=>{_._sendPacket({cmd:"pubrec",messageId:X},A)})});break}case 1:{H.customHandleAcks(E,L,T,(Z,Y)=>{if(typeof Z==="number")Y=Z,Z=null;if(Z)return _.emit("error",Z);if(NK.indexOf(Y)===-1)return _.emit("error",Error("Wrong reason code for puback"));if(!Y)_.emit("message",E,L,T);_.handleMessage(T,(K)=>{if(K)return A&&A(K);_._sendPacket({cmd:"puback",messageId:X,reasonCode:Y},A)})});break}case 0:_.emit("message",E,L,T),_.handleMessage(T,A);break;default:_.log("handlePublish: unknown QoS. Doing nothing.");break}};QK.default=Gj});var VK=W((Yg,Uj)=>{Uj.exports={name:"mqtt",description:"A library for the MQTT protocol",version:"5.14.1",contributors:["Adam Rudd <adamvrr@gmail.com>","Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)","Siarhei Buntsevich <scarry0506@gmail.com> (https://github.com/scarry1992)","Yoseph Maguire <yomaguir@microsoft.com> (https://github.com/YoDaMa)","Daniel Lando <daniel.sorridi@gmail.com> (https://github.com/robertsLando)"],keywords:["mqtt","publish/subscribe","publish","subscribe"],license:"MIT",repository:{type:"git",url:"git://github.com/mqttjs/MQTT.js.git"},main:"./build/index.js",module:"./dist/mqtt.esm.js",bin:{mqtt_pub:"./build/bin/pub.js",mqtt_sub:"./build/bin/sub.js",mqtt:"./build/bin/mqtt.js"},files:["dist/","CONTRIBUTING.md","LICENSE.md","help/","build/"],exports:{".":{"react-native":"./dist/mqtt.esm.js",browser:{import:"./dist/mqtt.esm.js",default:"./dist/mqtt.min.js"},default:"./build/index.js"},"./package.json":"./package.json","./*.map":"./build/*.js.map","./dist/*":"./dist/*.js","./*":"./build/*.js"},types:"build/index.d.ts",typesVersions:{"*":{"*":["./build/index.d.ts"]}},scripts:{lint:"eslint --ext .ts .","lint-fix":"eslint --fix --ext .ts .","build:ts":"rimraf build/ && tsc -p tsconfig.build.json","build:browser":"node esbuild.js",build:"npm run build:ts && npm run build:browser",prepare:"npm run build","unit-test:node":"node -r esbuild-register --test-concurrency 4 --test-reporter=junit --test-reporter-destination=junit.xml --test-reporter=spec --test-reporter-destination=stdout --test test/node/*.ts ","unit-test:browser":"wtr","test:node":"node_modules/.bin/nyc npm run unit-test:node","test:browser":"npm run build && npm run unit-test:browser",test:"npm run test:node",changelog:"conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md","changelog-init":"conventional-changelog -p angular -i CHANGELOG.md -s -r 0",release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it"},"release-it":{github:{release:!0},git:{tagName:"v${version}",commitMessage:"chore(release): ${version}"},hooks:{"before:init":["npm run test"]},npm:{publish:!0},plugins:{"@release-it/conventional-changelog":{preset:"angular",infile:"CHANGELOG.md"}}},publishConfig:{provenance:!0},"pre-commit":["lint"],engines:{node:">=16.0.0"},browser:{"./mqtt.js":"./dist/mqtt.js",fs:!1,tls:!1,net:!1},dependencies:{"@types/readable-stream":"^4.0.21","@types/ws":"^8.18.1",commist:"^3.2.0","concat-stream":"^2.0.0",debug:"^4.4.1","help-me":"^5.0.0","lru-cache":"^10.4.3",minimist:"^1.2.8","mqtt-packet":"^9.0.2","number-allocator":"^1.0.14","readable-stream":"^4.7.0",rfdc:"^1.4.1",socks:"^2.8.6",split2:"^4.2.0","worker-timers":"^8.0.23",ws:"^8.18.3"},devDependencies:{"@eslint/eslintrc":"^3.3.1","@eslint/js":"^9.32.0","@esm-bundle/chai":"^4.3.4","@release-it/conventional-changelog":"^10.0.1","@tsconfig/node20":"^20.1.6","@types/chai":"^5.2.2","@types/node":"^20.17.16","@types/sinon":"^17.0.4","@types/tape":"^5.8.1","@typescript-eslint/eslint-plugin":"^8.38.0","@typescript-eslint/parser":"^8.38.0","@web/test-runner":"^0.20.2","@web/test-runner-playwright":"^0.11.1","aedes-cli":"^0.8.0",chai:"^5.2.1",chokidar:"^4.0.3","conventional-changelog-cli":"^5.0.0","end-of-stream":"^1.4.5",esbuild:"^0.25.8","esbuild-plugin-polyfill-node":"^0.3.0","esbuild-register":"^3.6.0",eslint:"^9.32.0","eslint-config-prettier":"^10.1.8","eslint-plugin-import":"^2.32.0","eslint-plugin-prettier":"^5.5.3",global:"^4.4.0",globals:"^16.3.0","leaked-handles":"^5.2.0",mkdirp:"^3.0.1","mqtt-connection":"^4.1.0","mqtt-level-store":"^3.1.0",nyc:"^17.1.0","pre-commit":"^1.2.2",prettier:"^3.6.2","release-it":"^19.0.4",rimraf:"^6.0.1",should:"^13.2.3",sinon:"^17.0.2",snazzy:"^9.0.0",tape:"^5.9.0","ts-node":"^10.9.2",typescript:"^5.8.3"}}});var BT=W((zK)=>{Object.defineProperty(zK,"__esModule",{value:!0});zK.MQTTJS_VERSION=zK.nextTick=zK.ErrorWithSubackPacket=zK.ErrorWithReasonCode=void 0;zK.applyMixin=Wj;class cE extends Error{code;constructor(_,T){super(_);this.code=T,Object.setPrototypeOf(this,cE.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}zK.ErrorWithReasonCode=cE;class pE extends Error{packet;constructor(_,T){super(_);this.packet=T,Object.setPrototypeOf(this,pE.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}zK.ErrorWithSubackPacket=pE;function Wj(_,T,A=!1){let E=[T];while(!0){let L=E[0],J=Object.getPrototypeOf(L);if(J?.prototype)E.unshift(J);else break}for(let L of E)for(let J of Object.getOwnPropertyNames(L.prototype))if(A||J!=="constructor")Object.defineProperty(_.prototype,J,Object.getOwnPropertyDescriptor(L.prototype,J)??Object.create(null))}zK.nextTick=typeof process?.nextTick==="function"?process.nextTick:(_)=>{setTimeout(_,0)};zK.MQTTJS_VERSION=VK().version});var e4=W((OK)=>{Object.defineProperty(OK,"__esModule",{value:!0});OK.ReasonCodes=void 0;var CK=BT();OK.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var zj=(_,T)=>{let{messageId:A}=T,E=T.cmd,L=null,J=_.outgoing[A]?_.outgoing[A].cb:null,X=null;if(!J){_.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(_.log("_handleAck :: packet type",E),E){case"pubcomp":case"puback":{let H=T.reasonCode;if(H&&H>0&&H!==16)X=new CK.ErrorWithReasonCode(`Publish error: ${OK.ReasonCodes[H]}`,H),_._removeOutgoingAndStoreMessage(A,()=>{J(X,T)});else _._removeOutgoingAndStoreMessage(A,J);break}case"pubrec":{L={cmd:"pubrel",qos:2,messageId:A};let H=T.reasonCode;if(H&&H>0&&H!==16)X=new CK.ErrorWithReasonCode(`Publish error: ${OK.ReasonCodes[H]}`,H),_._removeOutgoingAndStoreMessage(A,()=>{J(X,T)});else _._sendPacket(L);break}case"suback":{delete _.outgoing[A],_.messageIdProvider.deallocate(A);let H=T.granted;for(let Z=0;Z<H.length;Z++){let Y=H[Z];if((Y&128)!==0){X=Error(`Subscribe error: ${OK.ReasonCodes[Y]}`),X.code=Y;let K=_.messageIdToTopic[A];if(K)K.forEach((G)=>{delete _._resubscribeTopics[G]})}}delete _.messageIdToTopic[A],_._invokeStoreProcessingQueue(),J(X,T);break}case"unsuback":{delete _.outgoing[A],_.messageIdProvider.deallocate(A),_._invokeStoreProcessingQueue(),J(null,T);break}default:_.emit("error",Error("unrecognized packet type"))}if(_.disconnecting&&Object.keys(_.outgoing).length===0)_.emit("outgoingEmpty")};OK.default=zj});var BK=W((DK)=>{Object.defineProperty(DK,"__esModule",{value:!0});var RK=BT(),Cj=e4(),Oj=(_,T)=>{let{options:A}=_,E=A.protocolVersion,L=E===5?T.reasonCode:T.returnCode;if(E!==5){let J=new RK.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${E}`,L);_.emit("error",J);return}_.handleAuth(T,(J,X)=>{if(J){_.emit("error",J);return}if(L===24)_.reconnecting=!1,_._sendPacket(X);else{let H=new RK.ErrorWithReasonCode(`Connection refused: ${Cj.ReasonCodes[L]}`,L);_.emit("error",H)}})};DK.default=Oj});var SK=W((xK)=>{Object.defineProperty(xK,"__esModule",{value:!0});xK.LRUCache=void 0;var Z4=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,IK=new Set,lE=typeof process==="object"&&!!process?process:{},PK=(_,T,A,E)=>{typeof lE.emitWarning==="function"?lE.emitWarning(_,T,A,E):console.error(`[${A}] ${T}: ${_}`)},uA=globalThis.AbortController,qK=globalThis.AbortSignal;if(typeof uA>"u"){qK=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(E,L){this._onabort.push(L)}},uA=class{constructor(){T()}signal=new qK;abort(E){if(this.signal.aborted)return;this.signal.reason=E,this.signal.aborted=!0;for(let L of this.signal._onabort)L(E);this.signal.onabort?.(E)}};let _=lE.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",T=()=>{if(!_)return;_=!1,PK("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 Dj=(_)=>!IK.has(_),Ug=Symbol("type"),s0=(_)=>_&&_===Math.floor(_)&&_>0&&isFinite(_),jK=(_)=>!s0(_)?null:_<=Math.pow(2,8)?Uint8Array:_<=Math.pow(2,16)?Uint16Array:_<=Math.pow(2,32)?Uint32Array:_<=Number.MAX_SAFE_INTEGER?_8:null;class _8 extends Array{constructor(_){super(_);this.fill(0)}}class Y4{heap;length;static#J=!1;static create(_){let T=jK(_);if(!T)return[];Y4.#J=!0;let A=new Y4(_,T);return Y4.#J=!1,A}constructor(_,T){if(!Y4.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new T(_),this.length=0}push(_){this.heap[this.length++]=_}pop(){return this.heap[--this.length]}}class nE{#J;#L;#Y;#K;#N;#z;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#A;#W;#X;#E;#_;#$;#Q;#G;#H;#F;#Z;#C;#O;#M;#R;#P;#U;static unsafeExposeInternals(_){return{starts:_.#O,ttls:_.#M,sizes:_.#C,keyMap:_.#X,keyList:_.#E,valList:_.#_,next:_.#$,prev:_.#Q,get head(){return _.#G},get tail(){return _.#H},free:_.#F,isBackgroundFetch:(T)=>_.#T(T),backgroundFetch:(T,A,E,L)=>_.#v(T,A,E,L),moveToTail:(T)=>_.#w(T),indexes:(T)=>_.#D(T),rindexes:(T)=>_.#B(T),isStale:(T)=>_.#V(T)}}get max(){return this.#J}get maxSize(){return this.#L}get calculatedSize(){return this.#W}get size(){return this.#A}get fetchMethod(){return this.#N}get memoMethod(){return this.#z}get dispose(){return this.#Y}get disposeAfter(){return this.#K}constructor(_){let{max:T=0,ttl:A,ttlResolution:E=1,ttlAutopurge:L,updateAgeOnGet:J,updateAgeOnHas:X,allowStale:H,dispose:Z,disposeAfter:Y,noDisposeOnSet:K,noUpdateTTL:G,maxSize:$=0,maxEntrySize:U=0,sizeCalculation:V,fetchMethod:N,memoMethod:z,noDeleteOnFetchRejection:Q,noDeleteOnStaleGet:F,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:q,ignoreFetchAbort:f}=_;if(T!==0&&!s0(T))throw TypeError("max option must be a nonnegative integer");let h=T?jK(T):Array;if(!h)throw Error("invalid max value: "+T);if(this.#J=T,this.#L=$,this.maxEntrySize=U||this.#L,this.sizeCalculation=V,this.sizeCalculation){if(!this.#L&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(z!==void 0&&typeof z!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#z=z,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#N=N,this.#P=!!N,this.#X=new Map,this.#E=Array(T).fill(void 0),this.#_=Array(T).fill(void 0),this.#$=new h(T),this.#Q=new h(T),this.#G=0,this.#H=0,this.#F=Y4.create(T),this.#A=0,this.#W=0,typeof Z==="function")this.#Y=Z;if(typeof Y==="function")this.#K=Y,this.#Z=[];else this.#K=void 0,this.#Z=void 0;if(this.#R=!!this.#Y,this.#U=!!this.#K,this.noDisposeOnSet=!!K,this.noUpdateTTL=!!G,this.noDeleteOnFetchRejection=!!Q,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!q,this.ignoreFetchAbort=!!f,this.maxEntrySize!==0){if(this.#L!==0){if(!s0(this.#L))throw TypeError("maxSize must be a positive integer if specified")}if(!s0(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#u()}if(this.allowStale=!!H,this.noDeleteOnStaleGet=!!F,this.updateAgeOnGet=!!J,this.updateAgeOnHas=!!X,this.ttlResolution=s0(E)||E===0?E:1,this.ttlAutopurge=!!L,this.ttl=A||0,this.ttl){if(!s0(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#h()}if(this.#J===0&&this.ttl===0&&this.#L===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#L){if(Dj("LRU_CACHE_UNBOUNDED"))IK.add("LRU_CACHE_UNBOUNDED"),PK("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",nE)}}getRemainingTTL(_){return this.#X.has(_)?1/0:0}#h(){let _=new _8(this.#J),T=new _8(this.#J);this.#M=_,this.#O=T,this.#k=(L,J,X=Z4.now())=>{if(T[L]=J!==0?X:0,_[L]=J,J!==0&&this.ttlAutopurge){let H=setTimeout(()=>{if(this.#V(L))this.#q(this.#E[L],"expire")},J+1);if(H.unref)H.unref()}},this.#j=(L)=>{T[L]=_[L]!==0?Z4.now():0},this.#I=(L,J)=>{if(_[J]){let X=_[J],H=T[J];if(!X||!H)return;L.ttl=X,L.start=H,L.now=A||E();let Z=L.now-H;L.remainingTTL=X-Z}};let A=0,E=()=>{let L=Z4.now();if(this.ttlResolution>0){A=L;let J=setTimeout(()=>A=0,this.ttlResolution);if(J.unref)J.unref()}return L};this.getRemainingTTL=(L)=>{let J=this.#X.get(L);if(J===void 0)return 0;let X=_[J],H=T[J];if(!X||!H)return 1/0;let Z=(A||E())-H;return X-Z},this.#V=(L)=>{let J=T[L],X=_[L];return!!X&&!!J&&(A||E())-J>X}}#j=()=>{};#I=()=>{};#k=()=>{};#V=()=>!1;#u(){let _=new _8(this.#J);this.#W=0,this.#C=_,this.#x=(T)=>{this.#W-=_[T],_[T]=0},this.#f=(T,A,E,L)=>{if(this.#T(A))return 0;if(!s0(E))if(L){if(typeof L!=="function")throw TypeError("sizeCalculation must be a function");if(E=L(A,T),!s0(E))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return E},this.#S=(T,A,E)=>{if(_[T]=A,this.#L){let L=this.#L-_[T];while(this.#W>L)this.#y(!0)}if(this.#W+=_[T],E)E.entrySize=A,E.totalCalculatedSize=this.#W}}#x=(_)=>{};#S=(_,T,A)=>{};#f=(_,T,A,E)=>{if(A||E)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#D({allowStale:_=this.allowStale}={}){if(this.#A)for(let T=this.#H;;){if(!this.#b(T))break;if(_||!this.#V(T))yield T;if(T===this.#G)break;else T=this.#Q[T]}}*#B({allowStale:_=this.allowStale}={}){if(this.#A)for(let T=this.#G;;){if(!this.#b(T))break;if(_||!this.#V(T))yield T;if(T===this.#H)break;else T=this.#$[T]}}#b(_){return _!==void 0&&this.#X.get(this.#E[_])===_}*entries(){for(let _ of this.#D())if(this.#_[_]!==void 0&&this.#E[_]!==void 0&&!this.#T(this.#_[_]))yield[this.#E[_],this.#_[_]]}*rentries(){for(let _ of this.#B())if(this.#_[_]!==void 0&&this.#E[_]!==void 0&&!this.#T(this.#_[_]))yield[this.#E[_],this.#_[_]]}*keys(){for(let _ of this.#D()){let T=this.#E[_];if(T!==void 0&&!this.#T(this.#_[_]))yield T}}*rkeys(){for(let _ of this.#B()){let T=this.#E[_];if(T!==void 0&&!this.#T(this.#_[_]))yield T}}*values(){for(let _ of this.#D())if(this.#_[_]!==void 0&&!this.#T(this.#_[_]))yield this.#_[_]}*rvalues(){for(let _ of this.#B())if(this.#_[_]!==void 0&&!this.#T(this.#_[_]))yield this.#_[_]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(_,T={}){for(let A of this.#D()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;if(_(L,this.#E[A],this))return this.get(this.#E[A],T)}}forEach(_,T=this){for(let A of this.#D()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;_.call(T,L,this.#E[A],this)}}rforEach(_,T=this){for(let A of this.#B()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;_.call(T,L,this.#E[A],this)}}purgeStale(){let _=!1;for(let T of this.#B({allowStale:!0}))if(this.#V(T))this.#q(this.#E[T],"expire"),_=!0;return _}info(_){let T=this.#X.get(_);if(T===void 0)return;let A=this.#_[T],E=this.#T(A)?A.__staleWhileFetching:A;if(E===void 0)return;let L={value:E};if(this.#M&&this.#O){let J=this.#M[T],X=this.#O[T];if(J&&X){let H=J-(Z4.now()-X);L.ttl=H,L.start=Date.now()}}if(this.#C)L.size=this.#C[T];return L}dump(){let _=[];for(let T of this.#D({allowStale:!0})){let A=this.#E[T],E=this.#_[T],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0||A===void 0)continue;let J={value:L};if(this.#M&&this.#O){J.ttl=this.#M[T];let X=Z4.now()-this.#O[T];J.start=Math.floor(Date.now()-X)}if(this.#C)J.size=this.#C[T];_.unshift([A,J])}return _}load(_){this.clear();for(let[T,A]of _){if(A.start){let E=Date.now()-A.start;A.start=Z4.now()-E}this.set(T,A.value,A)}}set(_,T,A={}){if(T===void 0)return this.delete(_),this;let{ttl:E=this.ttl,start:L,noDisposeOnSet:J=this.noDisposeOnSet,sizeCalculation:X=this.sizeCalculation,status:H}=A,{noUpdateTTL:Z=this.noUpdateTTL}=A,Y=this.#f(_,T,A.size||0,X);if(this.maxEntrySize&&Y>this.maxEntrySize){if(H)H.set="miss",H.maxEntrySizeExceeded=!0;return this.#q(_,"set"),this}let K=this.#A===0?void 0:this.#X.get(_);if(K===void 0){if(K=this.#A===0?this.#H:this.#F.length!==0?this.#F.pop():this.#A===this.#J?this.#y(!1):this.#A,this.#E[K]=_,this.#_[K]=T,this.#X.set(_,K),this.#$[this.#H]=K,this.#Q[K]=this.#H,this.#H=K,this.#A++,this.#S(K,Y,H),H)H.set="add";Z=!1}else{this.#w(K);let G=this.#_[K];if(T!==G){if(this.#P&&this.#T(G)){G.__abortController.abort(Error("replaced"));let{__staleWhileFetching:$}=G;if($!==void 0&&!J){if(this.#R)this.#Y?.($,_,"set");if(this.#U)this.#Z?.push([$,_,"set"])}}else if(!J){if(this.#R)this.#Y?.(G,_,"set");if(this.#U)this.#Z?.push([G,_,"set"])}if(this.#x(K),this.#S(K,Y,H),this.#_[K]=T,H){H.set="replace";let $=G&&this.#T(G)?G.__staleWhileFetching:G;if($!==void 0)H.oldValue=$}}else if(H)H.set="update"}if(E!==0&&!this.#M)this.#h();if(this.#M){if(!Z)this.#k(K,E,L);if(H)this.#I(H,K)}if(!J&&this.#U&&this.#Z){let G=this.#Z,$;while($=G?.shift())this.#K?.(...$)}return this}pop(){try{while(this.#A){let _=this.#_[this.#G];if(this.#y(!0),this.#T(_)){if(_.__staleWhileFetching)return _.__staleWhileFetching}else if(_!==void 0)return _}}finally{if(this.#U&&this.#Z){let _=this.#Z,T;while(T=_?.shift())this.#K?.(...T)}}}#y(_){let T=this.#G,A=this.#E[T],E=this.#_[T];if(this.#P&&this.#T(E))E.__abortController.abort(Error("evicted"));else if(this.#R||this.#U){if(this.#R)this.#Y?.(E,A,"evict");if(this.#U)this.#Z?.push([E,A,"evict"])}if(this.#x(T),_)this.#E[T]=void 0,this.#_[T]=void 0,this.#F.push(T);if(this.#A===1)this.#G=this.#H=0,this.#F.length=0;else this.#G=this.#$[T];return this.#X.delete(A),this.#A--,T}has(_,T={}){let{updateAgeOnHas:A=this.updateAgeOnHas,status:E}=T,L=this.#X.get(_);if(L!==void 0){let J=this.#_[L];if(this.#T(J)&&J.__staleWhileFetching===void 0)return!1;if(!this.#V(L)){if(A)this.#j(L);if(E)E.has="hit",this.#I(E,L);return!0}else if(E)E.has="stale",this.#I(E,L)}else if(E)E.has="miss";return!1}peek(_,T={}){let{allowStale:A=this.allowStale}=T,E=this.#X.get(_);if(E===void 0||!A&&this.#V(E))return;let L=this.#_[E];return this.#T(L)?L.__staleWhileFetching:L}#v(_,T,A,E){let L=T===void 0?void 0:this.#_[T];if(this.#T(L))return L;let J=new uA,{signal:X}=A;X?.addEventListener("abort",()=>J.abort(X.reason),{signal:J.signal});let H={signal:J.signal,options:A,context:E},Z=(V,N=!1)=>{let{aborted:z}=J.signal,Q=A.ignoreFetchAbort&&V!==void 0;if(A.status)if(z&&!N){if(A.status.fetchAborted=!0,A.status.fetchError=J.signal.reason,Q)A.status.fetchAbortIgnored=!0}else A.status.fetchResolved=!0;if(z&&!Q&&!N)return K(J.signal.reason);let F=$;if(this.#_[T]===$)if(V===void 0)if(F.__staleWhileFetching)this.#_[T]=F.__staleWhileFetching;else this.#q(_,"fetch");else{if(A.status)A.status.fetchUpdated=!0;this.set(_,V,H.options)}return V},Y=(V)=>{if(A.status)A.status.fetchRejected=!0,A.status.fetchError=V;return K(V)},K=(V)=>{let{aborted:N}=J.signal,z=N&&A.allowStaleOnFetchAbort,Q=z||A.allowStaleOnFetchRejection,F=Q||A.noDeleteOnFetchRejection,R=$;if(this.#_[T]===$){if(!F||R.__staleWhileFetching===void 0)this.#q(_,"fetch");else if(!z)this.#_[T]=R.__staleWhileFetching}if(Q){if(A.status&&R.__staleWhileFetching!==void 0)A.status.returnedStale=!0;return R.__staleWhileFetching}else if(R.__returned===R)throw V},G=(V,N)=>{let z=this.#N?.(_,L,H);if(z&&z instanceof Promise)z.then((Q)=>V(Q===void 0?void 0:Q),N);J.signal.addEventListener("abort",()=>{if(!A.ignoreFetchAbort||A.allowStaleOnFetchAbort){if(V(void 0),A.allowStaleOnFetchAbort)V=(Q)=>Z(Q,!0)}})};if(A.status)A.status.fetchDispatched=!0;let $=new Promise(G).then(Z,Y),U=Object.assign($,{__abortController:J,__staleWhileFetching:L,__returned:void 0});if(T===void 0)this.set(_,U,{...H.options,status:void 0}),T=this.#X.get(_);else this.#_[T]=U;return U}#T(_){if(!this.#P)return!1;let T=_;return!!T&&T instanceof Promise&&T.hasOwnProperty("__staleWhileFetching")&&T.__abortController instanceof uA}async fetch(_,T={}){let{allowStale:A=this.allowStale,updateAgeOnGet:E=this.updateAgeOnGet,noDeleteOnStaleGet:L=this.noDeleteOnStaleGet,ttl:J=this.ttl,noDisposeOnSet:X=this.noDisposeOnSet,size:H=0,sizeCalculation:Z=this.sizeCalculation,noUpdateTTL:Y=this.noUpdateTTL,noDeleteOnFetchRejection:K=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:G=this.allowStaleOnFetchRejection,ignoreFetchAbort:$=this.ignoreFetchAbort,allowStaleOnFetchAbort:U=this.allowStaleOnFetchAbort,context:V,forceRefresh:N=!1,status:z,signal:Q}=T;if(!this.#P){if(z)z.fetch="get";return this.get(_,{allowStale:A,updateAgeOnGet:E,noDeleteOnStaleGet:L,status:z})}let F={allowStale:A,updateAgeOnGet:E,noDeleteOnStaleGet:L,ttl:J,noDisposeOnSet:X,size:H,sizeCalculation:Z,noUpdateTTL:Y,noDeleteOnFetchRejection:K,allowStaleOnFetchRejection:G,allowStaleOnFetchAbort:U,ignoreFetchAbort:$,status:z,signal:Q},R=this.#X.get(_);if(R===void 0){if(z)z.fetch="miss";let q=this.#v(_,R,F,V);return q.__returned=q}else{let q=this.#_[R];if(this.#T(q)){let c=A&&q.__staleWhileFetching!==void 0;if(z){if(z.fetch="inflight",c)z.returnedStale=!0}return c?q.__staleWhileFetching:q.__returned=q}let f=this.#V(R);if(!N&&!f){if(z)z.fetch="hit";if(this.#w(R),E)this.#j(R);if(z)this.#I(z,R);return q}let h=this.#v(_,R,F,V),l=h.__staleWhileFetching!==void 0&&A;if(z){if(z.fetch=f?"stale":"refresh",l&&f)z.returnedStale=!0}return l?h.__staleWhileFetching:h.__returned=h}}async forceFetch(_,T={}){let A=await this.fetch(_,T);if(A===void 0)throw Error("fetch() returned undefined");return A}memo(_,T={}){let A=this.#z;if(!A)throw Error("no memoMethod provided to constructor");let{context:E,forceRefresh:L,...J}=T,X=this.get(_,J);if(!L&&X!==void 0)return X;let H=A(_,X,{options:J,context:E});return this.set(_,H,J),H}get(_,T={}){let{allowStale:A=this.allowStale,updateAgeOnGet:E=this.updateAgeOnGet,noDeleteOnStaleGet:L=this.noDeleteOnStaleGet,status:J}=T,X=this.#X.get(_);if(X!==void 0){let H=this.#_[X],Z=this.#T(H);if(J)this.#I(J,X);if(this.#V(X)){if(J)J.get="stale";if(!Z){if(!L)this.#q(_,"expire");if(J&&A)J.returnedStale=!0;return A?H:void 0}else{if(J&&A&&H.__staleWhileFetching!==void 0)J.returnedStale=!0;return A?H.__staleWhileFetching:void 0}}else{if(J)J.get="hit";if(Z)return H.__staleWhileFetching;if(this.#w(X),E)this.#j(X);return H}}else if(J)J.get="miss"}#g(_,T){this.#Q[T]=_,this.#$[_]=T}#w(_){if(_!==this.#H){if(_===this.#G)this.#G=this.#$[_];else this.#g(this.#Q[_],this.#$[_]);this.#g(this.#H,_),this.#H=_}}delete(_){return this.#q(_,"delete")}#q(_,T){let A=!1;if(this.#A!==0){let E=this.#X.get(_);if(E!==void 0)if(A=!0,this.#A===1)this.#m(T);else{this.#x(E);let L=this.#_[E];if(this.#T(L))L.__abortController.abort(Error("deleted"));else if(this.#R||this.#U){if(this.#R)this.#Y?.(L,_,T);if(this.#U)this.#Z?.push([L,_,T])}if(this.#X.delete(_),this.#E[E]=void 0,this.#_[E]=void 0,E===this.#H)this.#H=this.#Q[E];else if(E===this.#G)this.#G=this.#$[E];else{let J=this.#Q[E];this.#$[J]=this.#$[E];let X=this.#$[E];this.#Q[X]=this.#Q[E]}this.#A--,this.#F.push(E)}}if(this.#U&&this.#Z?.length){let E=this.#Z,L;while(L=E?.shift())this.#K?.(...L)}return A}clear(){return this.#m("delete")}#m(_){for(let T of this.#B({allowStale:!0})){let A=this.#_[T];if(this.#T(A))A.__abortController.abort(Error("deleted"));else{let E=this.#E[T];if(this.#R)this.#Y?.(A,E,_);if(this.#U)this.#Z?.push([A,E,_])}}if(this.#X.clear(),this.#_.fill(void 0),this.#E.fill(void 0),this.#M&&this.#O)this.#M.fill(0),this.#O.fill(0);if(this.#C)this.#C.fill(0);if(this.#G=0,this.#H=0,this.#F.length=0,this.#W=0,this.#A=0,this.#U&&this.#Z){let T=this.#Z,A;while(A=T?.shift())this.#K?.(...A)}}}xK.LRUCache=nE});var Y0=W((hK)=>{Object.defineProperty(hK,"t",{value:!0});hK.ContainerIterator=hK.Container=hK.Base=void 0;class yK{constructor(_=0){this.iteratorType=_}equals(_){return this.o===_.o}}hK.ContainerIterator=yK;class iE{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}}hK.Base=iE;class vK extends iE{}hK.Container=vK});var mK=W((bK)=>{Object.defineProperty(bK,"t",{value:!0});bK.default=void 0;var Ij=Y0();class fK extends Ij.Base{constructor(_=[]){super();this.S=[];let T=this;_.forEach(function(A){T.push(A)})}clear(){this.i=0,this.S=[]}push(_){return this.S.push(_),this.i+=1,this.i}pop(){if(this.i===0)return;return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}}var Pj=fK;bK.default=Pj});var pK=W((dK)=>{Object.defineProperty(dK,"t",{value:!0});dK.default=void 0;var jj=Y0();class uK extends jj.Base{constructor(_=[]){super();this.j=0,this.q=[];let T=this;_.forEach(function(A){T.push(A)})}clear(){this.q=[],this.i=this.j=0}push(_){let T=this.q.length;if(this.j/T>0.5&&this.j+this.i>=T&&T>4096){let A=this.i;for(let E=0;E<A;++E)this.q[E]=this.q[this.j+E];this.j=0,this.q[this.i]=_}else this.q[this.j+this.i]=_;return++this.i}pop(){if(this.i===0)return;let _=this.q[this.j++];return this.i-=1,_}front(){if(this.i===0)return;return this.q[this.j]}}var xj=uK;dK.default=xj});var aK=W((nK)=>{Object.defineProperty(nK,"t",{value:!0});nK.default=void 0;var wj=Y0();class lK extends wj.Base{constructor(_=[],T=function(E,L){if(E>L)return-1;if(E<L)return 1;return 0},A=!0){super();if(this.v=T,Array.isArray(_))this.C=A?[..._]:_;else{this.C=[];let L=this;_.forEach(function(J){L.C.push(J)})}this.i=this.C.length;let E=this.i>>1;for(let L=this.i-1>>1;L>=0;--L)this.k(L,E)}m(_){let T=this.C[_];while(_>0){let A=_-1>>1,E=this.C[A];if(this.v(E,T)<=0)break;this.C[_]=E,_=A}this.C[_]=T}k(_,T){let A=this.C[_];while(_<T){let E=_<<1|1,L=E+1,J=this.C[E];if(L<this.i&&this.v(J,this.C[L])>0)E=L,J=this.C[L];if(this.v(J,A)>=0)break;this.C[_]=J,_=E}this.C[_]=A}clear(){this.i=0,this.C.length=0}push(_){this.C.push(_),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let _=this.C[0],T=this.C.pop();if(this.i-=1,this.i)this.C[0]=T,this.k(0,this.i>>1);return _}top(){return this.C[0]}find(_){return this.C.indexOf(_)>=0}remove(_){let T=this.C.indexOf(_);if(T<0)return!1;if(T===0)this.pop();else if(T===this.i-1)this.C.pop(),this.i-=1;else this.C.splice(T,1,this.C.pop()),this.i-=1,this.m(T),this.k(T,this.i>>1);return!0}updateItem(_){let T=this.C.indexOf(_);if(T<0)return!1;return this.m(T),this.k(T,this.i>>1),!0}toArray(){return[...this.C]}}var Sj=lK;nK.default=Sj});var dA=W((rK)=>{Object.defineProperty(rK,"t",{value:!0});rK.default=void 0;var yj=Y0();class oK extends yj.Container{}var vj=oK;rK.default=vj});var K0=W((tK)=>{Object.defineProperty(tK,"t",{value:!0});tK.throwIteratorAccessError=hj;function hj(){throw RangeError("Iterator access denied!")}});var aE=W((_3)=>{Object.defineProperty(_3,"t",{value:!0});_3.RandomIterator=void 0;var fj=Y0(),cA=K0();class eK extends fj.ContainerIterator{constructor(_,T){super(T);if(this.o=_,this.iteratorType===0)this.pre=function(){if(this.o===0)(0,cA.throwIteratorAccessError)();return this.o-=1,this},this.next=function(){if(this.o===this.container.size())(0,cA.throwIteratorAccessError)();return this.o+=1,this};else this.pre=function(){if(this.o===this.container.size()-1)(0,cA.throwIteratorAccessError)();return this.o+=1,this},this.next=function(){if(this.o===-1)(0,cA.throwIteratorAccessError)();return this.o-=1,this}}get pointer(){return this.container.getElementByPos(this.o)}set pointer(_){this.container.setElementByPos(this.o,_)}}_3.RandomIterator=eK});var J3=W((E3)=>{Object.defineProperty(E3,"t",{value:!0});E3.default=void 0;var bj=mj(dA()),gj=aE();function mj(_){return _&&_.t?_:{default:_}}class qT extends gj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new qT(this.o,this.container,this.iteratorType)}}class A3 extends bj.default{constructor(_=[],T=!0){super();if(Array.isArray(_))this.J=T?[..._]:_,this.i=_.length;else{this.J=[];let A=this;_.forEach(function(E){A.pushBack(E)})}}clear(){this.i=0,this.J.length=0}begin(){return new qT(0,this)}end(){return new qT(this.i,this)}rBegin(){return new qT(this.i-1,this,1)}rEnd(){return new qT(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();return this.J[_]}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();return this.J.splice(_,1),this.i-=1,this.i}eraseElementByValue(_){let T=0;for(let A=0;A<this.i;++A)if(this.J[A]!==_)this.J[T++]=this.J[A];return this.i=this.J.length=T,this.i}eraseElementByIterator(_){let T=_.o;return _=_.next(),this.eraseElementByPos(T),_}pushBack(_){return this.J.push(_),this.i+=1,this.i}popBack(){if(this.i===0)return;return this.i-=1,this.J.pop()}setElementByPos(_,T){if(_<0||_>this.i-1)throw RangeError();this.J[_]=T}insert(_,T,A=1){if(_<0||_>this.i)throw RangeError();return this.J.splice(_,0,...Array(A).fill(T)),this.i+=A,this.i}find(_){for(let T=0;T<this.i;++T)if(this.J[T]===_)return new qT(T,this);return this.end()}reverse(){this.J.reverse()}unique(){let _=1;for(let T=1;T<this.i;++T)if(this.J[T]!==this.J[T-1])this.J[_++]=this.J[T];return this.i=this.J.length=_,this.i}sort(_){this.J.sort(_)}forEach(_){for(let T=0;T<this.i;++T)_(this.J[T],T,this)}[Symbol.iterator](){return function*(){yield*this.J}.bind(this)()}}var uj=A3;E3.default=uj});var Y3=W((H3)=>{Object.defineProperty(H3,"t",{value:!0});H3.default=void 0;var dj=pj(dA()),cj=Y0(),IT=K0();function pj(_){return _&&_.t?_:{default:_}}class PT extends cj.ContainerIterator{constructor(_,T,A,E){super(E);if(this.o=_,this.h=T,this.container=A,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,IT.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,IT.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,IT.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,IT.throwIteratorAccessError)();return this.o=this.o.L,this}}get pointer(){if(this.o===this.h)(0,IT.throwIteratorAccessError)();return this.o.l}set pointer(_){if(this.o===this.h)(0,IT.throwIteratorAccessError)();this.o.l=_}copy(){return new PT(this.o,this.h,this.container,this.iteratorType)}}class X3 extends dj.default{constructor(_=[]){super();this.h={},this.p=this._=this.h.L=this.h.B=this.h;let T=this;_.forEach(function(A){T.pushBack(A)})}V(_){let{L:T,B:A}=_;if(T.B=A,A.L=T,_===this.p)this.p=A;if(_===this._)this._=T;this.i-=1}G(_,T){let A=T.B,E={l:_,L:T,B:A};if(T.B=E,A.L=E,T===this.h)this.p=E;if(A===this.h)this._=E;this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new PT(this.p,this.h,this)}end(){return new PT(this.h,this.h,this)}rBegin(){return new PT(this._,this.h,this,1)}rEnd(){return new PT(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return T.l}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return this.V(T),this.i}eraseElementByValue(_){let T=this.p;while(T!==this.h){if(T.l===_)this.V(T);T=T.B}return this.i}eraseElementByIterator(_){let T=_.o;if(T===this.h)(0,IT.throwIteratorAccessError)();return _=_.next(),this.V(T),_}pushBack(_){return this.G(_,this._),this.i}popBack(){if(this.i===0)return;let _=this._.l;return this.V(this._),_}pushFront(_){return this.G(_,this.h),this.i}popFront(){if(this.i===0)return;let _=this.p.l;return this.V(this.p),_}setElementByPos(_,T){if(_<0||_>this.i-1)throw RangeError();let A=this.p;while(_--)A=A.B;A.l=T}insert(_,T,A=1){if(_<0||_>this.i)throw RangeError();if(A<=0)return this.i;if(_===0)while(A--)this.pushFront(T);else if(_===this.i)while(A--)this.pushBack(T);else{let E=this.p;for(let J=1;J<_;++J)E=E.B;let L=E.B;this.i+=A;while(A--)E.B={l:T,L:E},E.B.L=E,E=E.B;E.B=L,L.L=E}return this.i}find(_){let T=this.p;while(T!==this.h){if(T.l===_)return new PT(T,this.h,this);T=T.B}return this.end()}reverse(){if(this.i<=1)return;let _=this.p,T=this._,A=0;while(A<<1<this.i){let E=_.l;_.l=T.l,T.l=E,_=_.B,T=T.L,A+=1}}unique(){if(this.i<=1)return this.i;let _=this.p;while(_!==this.h){let T=_;while(T.B!==this.h&&T.l===T.B.l)T=T.B,this.i-=1;_.B=T.B,_.B.L=_,_=_.B}return this.i}sort(_){if(this.i<=1)return;let T=[];this.forEach(function(E){T.push(E)}),T.sort(_);let A=this.p;T.forEach(function(E){A.l=E,A=A.B})}merge(_){let T=this;if(this.i===0)_.forEach(function(A){T.pushBack(A)});else{let A=this.p;_.forEach(function(E){while(A!==T.h&&A.l<=E)A=A.B;T.G(E,A.L)})}return this.i}forEach(_){let T=this.p,A=0;while(T!==this.h)_(T.l,A++,this),T=T.B}[Symbol.iterator](){return function*(){if(this.i===0)return;let _=this.p;while(_!==this.h)yield _.l,_=_.B}.bind(this)()}}var lj=X3;H3.default=lj});var U3=W((G3)=>{Object.defineProperty(G3,"t",{value:!0});G3.default=void 0;var nj=aj(dA()),ij=aE();function aj(_){return _&&_.t?_:{default:_}}class jT extends ij.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new jT(this.o,this.container,this.iteratorType)}}class K3 extends nj.default{constructor(_=[],T=4096){super();this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let A=(()=>{if(typeof _.length==="number")return _.length;if(typeof _.size==="number")return _.size;if(typeof _.size==="function")return _.size();throw TypeError("Cannot get the length or size of the container")})();this.F=T,this.P=Math.max(Math.ceil(A/this.F),1);for(let J=0;J<this.P;++J)this.A.push(Array(this.F));let E=Math.ceil(A/this.F);this.j=this.R=(this.P>>1)-(E>>1),this.D=this.N=this.F-A%this.F>>1;let L=this;_.forEach(function(J){L.pushBack(J)})}T(){let _=[],T=Math.max(this.P>>1,1);for(let A=0;A<T;++A)_[A]=Array(this.F);for(let A=this.j;A<this.P;++A)_[_.length]=this.A[A];for(let A=0;A<this.R;++A)_[_.length]=this.A[A];_[_.length]=[...this.A[this.R]],this.j=T,this.R=_.length-1;for(let A=0;A<T;++A)_[_.length]=Array(this.F);this.A=_,this.P=_.length}O(_){let T=this.D+_+1,A=T%this.F,E=A-1,L=this.j+(T-A)/this.F;if(A===0)L-=1;if(L%=this.P,E<0)E+=this.F;return{curNodeBucketIndex:L,curNodePointerIndex:E}}clear(){this.A=[Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new jT(0,this)}end(){return new jT(this.i,this)}rBegin(){return new jT(this.i-1,this,1)}rEnd(){return new jT(-1,this,1)}front(){if(this.i===0)return;return this.A[this.j][this.D]}back(){if(this.i===0)return;return this.A[this.R][this.N]}pushBack(_){if(this.i){if(this.N<this.F-1)this.N+=1;else if(this.R<this.P-1)this.R+=1,this.N=0;else this.R=0,this.N=0;if(this.R===this.j&&this.N===this.D)this.T()}return this.i+=1,this.A[this.R][this.N]=_,this.i}popBack(){if(this.i===0)return;let _=this.A[this.R][this.N];if(this.i!==1)if(this.N>0)this.N-=1;else if(this.R>0)this.R-=1,this.N=this.F-1;else this.R=this.P-1,this.N=this.F-1;return this.i-=1,_}pushFront(_){if(this.i){if(this.D>0)this.D-=1;else if(this.j>0)this.j-=1,this.D=this.F-1;else this.j=this.P-1,this.D=this.F-1;if(this.j===this.R&&this.D===this.N)this.T()}return this.i+=1,this.A[this.j][this.D]=_,this.i}popFront(){if(this.i===0)return;let _=this.A[this.j][this.D];if(this.i!==1)if(this.D<this.F-1)this.D+=1;else if(this.j<this.P-1)this.j+=1,this.D=0;else this.j=0,this.D=0;return this.i-=1,_}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let{curNodeBucketIndex:T,curNodePointerIndex:A}=this.O(_);return this.A[T][A]}setElementByPos(_,T){if(_<0||_>this.i-1)throw RangeError();let{curNodeBucketIndex:A,curNodePointerIndex:E}=this.O(_);this.A[A][E]=T}insert(_,T,A=1){if(_<0||_>this.i)throw RangeError();if(_===0)while(A--)this.pushFront(T);else if(_===this.i)while(A--)this.pushBack(T);else{let E=[];for(let L=_;L<this.i;++L)E.push(this.getElementByPos(L));this.cut(_-1);for(let L=0;L<A;++L)this.pushBack(T);for(let L=0;L<E.length;++L)this.pushBack(E[L])}return this.i}cut(_){if(_<0)return this.clear(),0;let{curNodeBucketIndex:T,curNodePointerIndex:A}=this.O(_);return this.R=T,this.N=A,this.i=_+1,this.i}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();if(_===0)this.popFront();else if(_===this.i-1)this.popBack();else{let T=[];for(let E=_+1;E<this.i;++E)T.push(this.getElementByPos(E));this.cut(_),this.popBack();let A=this;T.forEach(function(E){A.pushBack(E)})}return this.i}eraseElementByValue(_){if(this.i===0)return 0;let T=[];for(let E=0;E<this.i;++E){let L=this.getElementByPos(E);if(L!==_)T.push(L)}let A=T.length;for(let E=0;E<A;++E)this.setElementByPos(E,T[E]);return this.cut(A-1)}eraseElementByIterator(_){let T=_.o;return this.eraseElementByPos(T),_=_.next(),_}find(_){for(let T=0;T<this.i;++T)if(this.getElementByPos(T)===_)return new jT(T,this);return this.end()}reverse(){let _=0,T=this.i-1;while(_<T){let A=this.getElementByPos(_);this.setElementByPos(_,this.getElementByPos(T)),this.setElementByPos(T,A),_+=1,T-=1}}unique(){if(this.i<=1)return this.i;let _=1,T=this.getElementByPos(0);for(let A=1;A<this.i;++A){let E=this.getElementByPos(A);if(E!==T)T=E,this.setElementByPos(_++,E)}while(this.i>_)this.popBack();return this.i}sort(_){let T=[];for(let A=0;A<this.i;++A)T.push(this.getElementByPos(A));T.sort(_);for(let A=0;A<this.i;++A)this.setElementByPos(A,T[A])}shrinkToFit(){if(this.i===0)return;let _=[];this.forEach(function(T){_.push(T)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let T=0;T<this.P;++T)this.A.push(Array(this.F));for(let T=0;T<_.length;++T)this.pushBack(_[T])}forEach(_){for(let T=0;T<this.i;++T)_(this.getElementByPos(T),T,this)}[Symbol.iterator](){return function*(){for(let _=0;_<this.i;++_)yield this.getElementByPos(_)}.bind(this)()}}var oj=K3;G3.default=oj});var M3=W((N3)=>{Object.defineProperty(N3,"t",{value:!0});N3.TreeNodeEnableIndex=N3.TreeNode=void 0;class oE{constructor(_,T){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=_,this.l=T}L(){let _=this;if(_.ee===1&&_.tt.tt===_)_=_.W;else if(_.U){_=_.U;while(_.W)_=_.W}else{let T=_.tt;while(T.U===_)_=T,T=_.tt;_=T}return _}B(){let _=this;if(_.W){_=_.W;while(_.U)_=_.U;return _}else{let T=_.tt;while(T.W===_)_=T,T=_.tt;if(_.W!==T)return T;else return _}}te(){let _=this.tt,T=this.W,A=T.U;if(_.tt===this)_.tt=T;else if(_.U===this)_.U=T;else _.W=T;if(T.tt=_,T.U=this,this.tt=T,this.W=A,A)A.tt=this;return T}se(){let _=this.tt,T=this.U,A=T.W;if(_.tt===this)_.tt=T;else if(_.U===this)_.U=T;else _.W=T;if(T.tt=_,T.W=this,this.tt=T,this.U=A,A)A.tt=this;return T}}N3.TreeNode=oE;class W3 extends oE{constructor(){super(...arguments);this.rt=1}te(){let _=super.te();return this.ie(),_.ie(),_}se(){let _=super.se();return this.ie(),_.ie(),_}ie(){if(this.rt=1,this.U)this.rt+=this.U.rt;if(this.W)this.rt+=this.W.rt}}N3.TreeNodeEnableIndex=W3});var rE=W((C3)=>{Object.defineProperty(C3,"t",{value:!0});C3.default=void 0;var V3=M3(),sj=Y0(),z3=K0();class F3 extends sj.Container{constructor(_=function(A,E){if(A<E)return-1;if(A>E)return 1;return 0},T=!1){super();if(this.Y=void 0,this.v=_,T)this.re=V3.TreeNodeEnableIndex,this.M=function(A,E,L){let J=this.ne(A,E,L);if(J){let X=J.tt;while(X!==this.h)X.rt+=1,X=X.tt;let H=this.he(J);if(H){let{parentNode:Z,grandParent:Y,curNode:K}=H;Z.ie(),Y.ie(),K.ie()}}return this.i},this.V=function(A){let E=this.fe(A);while(E!==this.h)E.rt-=1,E=E.tt};else this.re=V3.TreeNode,this.M=function(A,E,L){let J=this.ne(A,E,L);if(J)this.he(J);return this.i},this.V=this.fe;this.h=new this.re}X(_,T){let A=this.h;while(_){let E=this.v(_.u,T);if(E<0)_=_.W;else if(E>0)A=_,_=_.U;else return _}return A}Z(_,T){let A=this.h;while(_)if(this.v(_.u,T)<=0)_=_.W;else A=_,_=_.U;return A}$(_,T){let A=this.h;while(_){let E=this.v(_.u,T);if(E<0)A=_,_=_.W;else if(E>0)_=_.U;else return _}return A}rr(_,T){let A=this.h;while(_)if(this.v(_.u,T)<0)A=_,_=_.W;else _=_.U;return A}ue(_){while(!0){let T=_.tt;if(T===this.h)return;if(_.ee===1){_.ee=0;return}if(_===T.U){let A=T.W;if(A.ee===1)if(A.ee=0,T.ee=1,T===this.Y)this.Y=T.te();else T.te();else if(A.W&&A.W.ee===1){if(A.ee=T.ee,T.ee=0,A.W.ee=0,T===this.Y)this.Y=T.te();else T.te();return}else if(A.U&&A.U.ee===1)A.ee=1,A.U.ee=0,A.se();else A.ee=1,_=T}else{let A=T.U;if(A.ee===1)if(A.ee=0,T.ee=1,T===this.Y)this.Y=T.se();else T.se();else if(A.U&&A.U.ee===1){if(A.ee=T.ee,T.ee=0,A.U.ee=0,T===this.Y)this.Y=T.se();else T.se();return}else if(A.W&&A.W.ee===1)A.ee=1,A.W.ee=0,A.te();else A.ee=1,_=T}}}fe(_){if(this.i===1)return this.clear(),this.h;let T=_;while(T.U||T.W){if(T.W){T=T.W;while(T.U)T=T.U}else T=T.U;[_.u,T.u]=[T.u,_.u],[_.l,T.l]=[T.l,_.l],_=T}if(this.h.U===T)this.h.U=T.tt;else if(this.h.W===T)this.h.W=T.tt;this.ue(T);let A=T.tt;if(T===A.U)A.U=void 0;else A.W=void 0;return this.i-=1,this.Y.ee=0,A}oe(_,T){if(_===void 0)return!1;if(this.oe(_.U,T))return!0;if(T(_))return!0;return this.oe(_.W,T)}he(_){while(!0){let T=_.tt;if(T.ee===0)return;let A=T.tt;if(T===A.U){let E=A.W;if(E&&E.ee===1){if(E.ee=T.ee=0,A===this.Y)return;A.ee=1,_=A;continue}else if(_===T.W){if(_.ee=0,_.U)_.U.tt=T;if(_.W)_.W.tt=A;if(T.W=_.U,A.U=_.W,_.U=T,_.W=A,A===this.Y)this.Y=_,this.h.tt=_;else{let L=A.tt;if(L.U===A)L.U=_;else L.W=_}return _.tt=A.tt,T.tt=_,A.tt=_,A.ee=1,{parentNode:T,grandParent:A,curNode:_}}else{if(T.ee=0,A===this.Y)this.Y=A.se();else A.se();A.ee=1}}else{let E=A.U;if(E&&E.ee===1){if(E.ee=T.ee=0,A===this.Y)return;A.ee=1,_=A;continue}else if(_===T.U){if(_.ee=0,_.U)_.U.tt=A;if(_.W)_.W.tt=T;if(A.W=_.U,T.U=_.W,_.U=A,_.W=T,A===this.Y)this.Y=_,this.h.tt=_;else{let L=A.tt;if(L.U===A)L.U=_;else L.W=_}return _.tt=A.tt,T.tt=_,A.tt=_,A.ee=1,{parentNode:T,grandParent:A,curNode:_}}else{if(T.ee=0,A===this.Y)this.Y=A.te();else A.te();A.ee=1}}return}}ne(_,T,A){if(this.Y===void 0){this.i+=1,this.Y=new this.re(_,T),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let E,L=this.h.U,J=this.v(L.u,_);if(J===0){L.l=T;return}else if(J>0)L.U=new this.re(_,T),L.U.tt=L,E=L.U,this.h.U=E;else{let X=this.h.W,H=this.v(X.u,_);if(H===0){X.l=T;return}else if(H<0)X.W=new this.re(_,T),X.W.tt=X,E=X.W,this.h.W=E;else{if(A!==void 0){let Z=A.o;if(Z!==this.h){let Y=this.v(Z.u,_);if(Y===0){Z.l=T;return}else if(Y>0){let K=Z.L(),G=this.v(K.u,_);if(G===0){K.l=T;return}else if(G<0)if(E=new this.re(_,T),K.W===void 0)K.W=E,E.tt=K;else Z.U=E,E.tt=Z}}}if(E===void 0){E=this.Y;while(!0){let Z=this.v(E.u,_);if(Z>0){if(E.U===void 0){E.U=new this.re(_,T),E.U.tt=E,E=E.U;break}E=E.U}else if(Z<0){if(E.W===void 0){E.W=new this.re(_,T),E.W.tt=E,E=E.W;break}E=E.W}else{E.l=T;return}}}}}return this.i+=1,E}I(_,T){while(_){let A=this.v(_.u,T);if(A<0)_=_.W;else if(A>0)_=_.U;else return _}return _||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(_,T){let A=_.o;if(A===this.h)(0,z3.throwIteratorAccessError)();if(this.i===1)return A.u=T,!0;if(A===this.h.U){if(this.v(A.B().u,T)>0)return A.u=T,!0;return!1}if(A===this.h.W){if(this.v(A.L().u,T)<0)return A.u=T,!0;return!1}let E=A.L().u;if(this.v(E,T)>=0)return!1;let L=A.B().u;if(this.v(L,T)<=0)return!1;return A.u=T,!0}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=0,A=this;return this.oe(this.Y,function(E){if(_===T)return A.V(E),!0;return T+=1,!1}),this.i}eraseElementByKey(_){if(this.i===0)return!1;let T=this.I(this.Y,_);if(T===this.h)return!1;return this.V(T),!0}eraseElementByIterator(_){let T=_.o;if(T===this.h)(0,z3.throwIteratorAccessError)();let A=T.W===void 0;if(_.iteratorType===0){if(A)_.next()}else if(!A||T.U===void 0)_.next();return this.V(T),_}forEach(_){let T=0;for(let A of this)_(A,T++,this)}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T,A=0;for(let E of this){if(A===_){T=E;break}A+=1}return T}getHeight(){if(this.i===0)return 0;let _=function(T){if(!T)return 0;return Math.max(_(T.U),_(T.W))+1};return _(this.Y)}}var tj=F3;C3.default=tj});var sE=W((D3)=>{Object.defineProperty(D3,"t",{value:!0});D3.default=void 0;var ej=Y0(),pA=K0();class R3 extends ej.ContainerIterator{constructor(_,T,A){super(A);if(this.o=_,this.h=T,this.iteratorType===0)this.pre=function(){if(this.o===this.h.U)(0,pA.throwIteratorAccessError)();return this.o=this.o.L(),this},this.next=function(){if(this.o===this.h)(0,pA.throwIteratorAccessError)();return this.o=this.o.B(),this};else this.pre=function(){if(this.o===this.h.W)(0,pA.throwIteratorAccessError)();return this.o=this.o.B(),this},this.next=function(){if(this.o===this.h)(0,pA.throwIteratorAccessError)();return this.o=this.o.L(),this}}get index(){let _=this.o,T=this.h.tt;if(_===this.h){if(T)return T.rt-1;return 0}let A=0;if(_.U)A+=_.U.rt;while(_!==T){let E=_.tt;if(_===E.W){if(A+=1,E.U)A+=E.U.rt}_=E}return A}}var _x=R3;D3.default=_x});var x3=W((P3)=>{Object.defineProperty(P3,"t",{value:!0});P3.default=void 0;var Tx=q3(rE()),Ax=q3(sE()),Ex=K0();function q3(_){return _&&_.t?_:{default:_}}class c1 extends Ax.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Ex.throwIteratorAccessError)();return this.o.u}copy(){return new c1(this.o,this.h,this.container,this.iteratorType)}}class I3 extends Tx.default{constructor(_=[],T,A){super(T,A);let E=this;_.forEach(function(L){E.insert(L)})}*K(_){if(_===void 0)return;yield*this.K(_.U),yield _.u,yield*this.K(_.W)}begin(){return new c1(this.h.U||this.h,this.h,this)}end(){return new c1(this.h,this.h,this)}rBegin(){return new c1(this.h.W||this.h,this.h,this,1)}rEnd(){return new c1(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(_,T){return this.M(_,void 0,T)}find(_){let T=this.I(this.Y,_);return new c1(T,this.h,this)}lowerBound(_){let T=this.X(this.Y,_);return new c1(T,this.h,this)}upperBound(_){let T=this.Z(this.Y,_);return new c1(T,this.h,this)}reverseLowerBound(_){let T=this.$(this.Y,_);return new c1(T,this.h,this)}reverseUpperBound(_){let T=this.rr(this.Y,_);return new c1(T,this.h,this)}union(_){let T=this;return _.forEach(function(A){T.insert(A)}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var Lx=I3;P3.default=Lx});var h3=W((y3)=>{Object.defineProperty(y3,"t",{value:!0});y3.default=void 0;var Jx=w3(rE()),Xx=w3(sE()),Hx=K0();function w3(_){return _&&_.t?_:{default:_}}class p1 extends Xx.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Hx.throwIteratorAccessError)();let _=this;return new Proxy([],{get(T,A){if(A==="0")return _.o.u;else if(A==="1")return _.o.l},set(T,A,E){if(A!=="1")throw TypeError("props must be 1");return _.o.l=E,!0}})}copy(){return new p1(this.o,this.h,this.container,this.iteratorType)}}class S3 extends Jx.default{constructor(_=[],T,A){super(T,A);let E=this;_.forEach(function(L){E.setElement(L[0],L[1])})}*K(_){if(_===void 0)return;yield*this.K(_.U),yield[_.u,_.l],yield*this.K(_.W)}begin(){return new p1(this.h.U||this.h,this.h,this)}end(){return new p1(this.h,this.h,this)}rBegin(){return new p1(this.h.W||this.h,this.h,this,1)}rEnd(){return new p1(this.h,this.h,this,1)}front(){if(this.i===0)return;let _=this.h.U;return[_.u,_.l]}back(){if(this.i===0)return;let _=this.h.W;return[_.u,_.l]}lowerBound(_){let T=this.X(this.Y,_);return new p1(T,this.h,this)}upperBound(_){let T=this.Z(this.Y,_);return new p1(T,this.h,this)}reverseLowerBound(_){let T=this.$(this.Y,_);return new p1(T,this.h,this)}reverseUpperBound(_){let T=this.rr(this.Y,_);return new p1(T,this.h,this)}setElement(_,T,A){return this.M(_,T,A)}find(_){let T=this.I(this.Y,_);return new p1(T,this.h,this)}getElementByKey(_){return this.I(this.Y,_).l}union(_){let T=this;return _.forEach(function(A){T.setElement(A[0],A[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var Zx=S3;y3.default=Zx});var tE=W((k3)=>{Object.defineProperty(k3,"t",{value:!0});k3.default=Yx;function Yx(_){let T=typeof _;return T==="object"&&_!==null||T==="function"}});var _L=W((m3)=>{Object.defineProperty(m3,"t",{value:!0});m3.HashContainerIterator=m3.HashContainer=void 0;var f3=Y0(),eE=Gx(tE()),T8=K0();function Gx(_){return _&&_.t?_:{default:_}}class b3 extends f3.ContainerIterator{constructor(_,T,A){super(A);if(this.o=_,this.h=T,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,T8.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,T8.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,T8.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,T8.throwIteratorAccessError)();return this.o=this.o.L,this}}}m3.HashContainerIterator=b3;class g3 extends f3.Container{constructor(){super();this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(_){let{L:T,B:A}=_;if(T.B=A,A.L=T,_===this.p)this.p=A;if(_===this._)this._=T;this.i-=1}M(_,T,A){if(A===void 0)A=(0,eE.default)(_);let E;if(A){let L=_[this.HASH_TAG];if(L!==void 0)return this.H[L].l=T,this.i;Object.defineProperty(_,this.HASH_TAG,{value:this.H.length,configurable:!0}),E={u:_,l:T,L:this._,B:this.h},this.H.push(E)}else{let L=this.g[_];if(L)return L.l=T,this.i;E={u:_,l:T,L:this._,B:this.h},this.g[_]=E}if(this.i===0)this.p=E,this.h.B=E;else this._.B=E;return this._=E,this.h.L=E,++this.i}I(_,T){if(T===void 0)T=(0,eE.default)(_);if(T){let A=_[this.HASH_TAG];if(A===void 0)return this.h;return this.H[A]}else return this.g[_]||this.h}clear(){let _=this.HASH_TAG;this.H.forEach(function(T){delete T.u[_]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(_,T){let A;if(T===void 0)T=(0,eE.default)(_);if(T){let E=_[this.HASH_TAG];if(E===void 0)return!1;delete _[this.HASH_TAG],A=this.H[E],delete this.H[E]}else{if(A=this.g[_],A===void 0)return!1;delete this.g[_]}return this.V(A),!0}eraseElementByIterator(_){let T=_.o;if(T===this.h)(0,T8.throwIteratorAccessError)();return this.V(T),_.next()}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return this.V(T),this.i}}m3.HashContainer=g3});var n3=W((p3)=>{Object.defineProperty(p3,"t",{value:!0});p3.default=void 0;var d3=_L(),Ux=K0();class xT extends d3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Ux.throwIteratorAccessError)();return this.o.u}copy(){return new xT(this.o,this.h,this.container,this.iteratorType)}}class c3 extends d3.HashContainer{constructor(_=[]){super();let T=this;_.forEach(function(A){T.insert(A)})}begin(){return new xT(this.p,this.h,this)}end(){return new xT(this.h,this.h,this)}rBegin(){return new xT(this._,this.h,this,1)}rEnd(){return new xT(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(_,T){return this.M(_,void 0,T)}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return T.u}find(_,T){let A=this.I(_,T);return new xT(A,this.h,this)}forEach(_){let T=0,A=this.p;while(A!==this.h)_(A.u,T++,this),A=A.B}[Symbol.iterator](){return function*(){let _=this.p;while(_!==this.h)yield _.u,_=_.B}.bind(this)()}}var Wx=c3;p3.default=Wx});var s3=W((o3)=>{Object.defineProperty(o3,"t",{value:!0});o3.default=void 0;var i3=_L(),Nx=Mx(tE()),Qx=K0();function Mx(_){return _&&_.t?_:{default:_}}class wT extends i3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Qx.throwIteratorAccessError)();let _=this;return new Proxy([],{get(T,A){if(A==="0")return _.o.u;else if(A==="1")return _.o.l},set(T,A,E){if(A!=="1")throw TypeError("props must be 1");return _.o.l=E,!0}})}copy(){return new wT(this.o,this.h,this.container,this.iteratorType)}}class a3 extends i3.HashContainer{constructor(_=[]){super();let T=this;_.forEach(function(A){T.setElement(A[0],A[1])})}begin(){return new wT(this.p,this.h,this)}end(){return new wT(this.h,this.h,this)}rBegin(){return new wT(this._,this.h,this,1)}rEnd(){return new wT(this.h,this.h,this,1)}front(){if(this.i===0)return;return[this.p.u,this.p.l]}back(){if(this.i===0)return;return[this._.u,this._.l]}setElement(_,T,A){return this.M(_,T,A)}getElementByKey(_,T){if(T===void 0)T=(0,Nx.default)(_);if(T){let E=_[this.HASH_TAG];return E!==void 0?this.H[E].l:void 0}let A=this.g[_];return A?A.l:void 0}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return[T.u,T.l]}find(_,T){let A=this.I(_,T);return new wT(A,this.h,this)}forEach(_){let T=0,A=this.p;while(A!==this.h)_([A.u,A.l],T++,this),A=A.B}[Symbol.iterator](){return function*(){let _=this.p;while(_!==this.h)yield[_.u,_.l],_=_.B}.bind(this)()}}var Vx=a3;o3.default=Vx});var t3=W((B1)=>{Object.defineProperty(B1,"t",{value:!0});Object.defineProperty(B1,"Deque",{enumerable:!0,get:function(){return Dx.default}});Object.defineProperty(B1,"HashMap",{enumerable:!0,get:function(){return Px.default}});Object.defineProperty(B1,"HashSet",{enumerable:!0,get:function(){return Ix.default}});Object.defineProperty(B1,"LinkList",{enumerable:!0,get:function(){return Rx.default}});Object.defineProperty(B1,"OrderedMap",{enumerable:!0,get:function(){return qx.default}});Object.defineProperty(B1,"OrderedSet",{enumerable:!0,get:function(){return Bx.default}});Object.defineProperty(B1,"PriorityQueue",{enumerable:!0,get:function(){return Cx.default}});Object.defineProperty(B1,"Queue",{enumerable:!0,get:function(){return Fx.default}});Object.defineProperty(B1,"Stack",{enumerable:!0,get:function(){return zx.default}});Object.defineProperty(B1,"Vector",{enumerable:!0,get:function(){return Ox.default}});var zx=G0(mK()),Fx=G0(pK()),Cx=G0(aK()),Ox=G0(J3()),Rx=G0(Y3()),Dx=G0(U3()),Bx=G0(x3()),qx=G0(h3()),Ix=G0(n3()),Px=G0(s3());function G0(_){return _&&_.t?_:{default:_}}});var _G=W((hg,e3)=>{var jx=t3().OrderedSet,$0=u1()("number-allocator:trace"),xx=u1()("number-allocator:error");function e_(_,T){this.low=_,this.high=T}e_.prototype.equals=function(_){return this.low===_.low&&this.high===_.high};e_.prototype.compare=function(_){if(this.low<_.low&&this.high<_.low)return-1;if(_.low<this.low&&_.high<this.low)return 1;return 0};function U0(_,T){if(!(this instanceof U0))return new U0(_,T);this.min=_,this.max=T,this.ss=new jx([],(A,E)=>{return A.compare(E)}),$0("Create"),this.clear()}U0.prototype.firstVacant=function(){if(this.ss.size()===0)return null;return this.ss.front().low};U0.prototype.alloc=function(){if(this.ss.size()===0)return $0("alloc():empty"),null;let _=this.ss.begin(),T=_.pointer.low,A=_.pointer.high,E=T;if(E+1<=A)this.ss.updateKeyByIterator(_,new e_(T+1,A));else this.ss.eraseElementByPos(0);return $0("alloc():"+E),E};U0.prototype.use=function(_){let T=new e_(_,_),A=this.ss.lowerBound(T);if(!A.equals(this.ss.end())){let E=A.pointer.low,L=A.pointer.high;if(A.pointer.equals(T))return this.ss.eraseElementByIterator(A),$0("use():"+_),!0;if(E>_)return!1;if(E===_)return this.ss.updateKeyByIterator(A,new e_(E+1,L)),$0("use():"+_),!0;if(L===_)return this.ss.updateKeyByIterator(A,new e_(E,L-1)),$0("use():"+_),!0;return this.ss.updateKeyByIterator(A,new e_(_+1,L)),this.ss.insert(new e_(E,_-1)),$0("use():"+_),!0}return $0("use():failed"),!1};U0.prototype.free=function(_){if(_<this.min||_>this.max){xx("free():"+_+" is out of range");return}let T=new e_(_,_),A=this.ss.upperBound(T);if(A.equals(this.ss.end())){if(A.equals(this.ss.begin())){this.ss.insert(T);return}A.pre();let E=A.pointer.high;if(A.pointer.high+1===_)this.ss.updateKeyByIterator(A,new e_(E,_));else this.ss.insert(T)}else if(A.equals(this.ss.begin()))if(_+1===A.pointer.low){let E=A.pointer.high;this.ss.updateKeyByIterator(A,new e_(_,E))}else this.ss.insert(T);else{let E=A.pointer.low,L=A.pointer.high;A.pre();let J=A.pointer.low;if(A.pointer.high+1===_)if(_+1===E)this.ss.eraseElementByIterator(A),this.ss.updateKeyByIterator(A,new e_(J,L));else this.ss.updateKeyByIterator(A,new e_(J,_));else if(_+1===E)this.ss.eraseElementByIterator(A.next()),this.ss.insert(new e_(_,L));else this.ss.insert(T)}$0("free():"+_)};U0.prototype.clear=function(){$0("clear()"),this.ss.clear(),this.ss.insert(new e_(this.min,this.max))};U0.prototype.intervalCount=function(){return this.ss.size()};U0.prototype.dump=function(){console.log("length:"+this.ss.size());for(let _ of this.ss)console.log(_)};e3.exports=U0});var TL=W((yx,TG)=>{var Sx=_G();yx.NumberAllocator=Sx});var LG=W((EG)=>{Object.defineProperty(EG,"__esModule",{value:!0});var hx=SK(),kx=TL();class AG{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(_){if(_>0)this.aliasToTopic=new hx.LRUCache({max:_}),this.topicToAlias={},this.numberAllocator=new kx.NumberAllocator(1,_),this.max=_,this.length=0}put(_,T){if(T===0||T>this.max)return!1;let A=this.aliasToTopic.get(T);if(A)delete this.topicToAlias[A];return this.aliasToTopic.set(T,_),this.topicToAlias[_]=T,this.numberAllocator.use(T),this.length=this.aliasToTopic.size,!0}getTopicByAlias(_){return this.aliasToTopic.get(_)}getAliasByTopic(_){let T=this.topicToAlias[_];if(typeof T<"u")this.aliasToTopic.get(T);return T}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){let _=this.numberAllocator.firstVacant();if(_)return _;return[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}}EG.default=AG});var JG=W((A8)=>{var bx=A8&&A8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(A8,"__esModule",{value:!0});var gx=e4(),mx=bx(LG()),ux=BT(),dx=(_,T)=>{_.log("_handleConnack");let{options:A}=_,L=A.protocolVersion===5?T.reasonCode:T.returnCode;if(clearTimeout(_.connackTimer),delete _.topicAliasSend,T.properties){if(T.properties.topicAliasMaximum){if(T.properties.topicAliasMaximum>65535){_.emit("error",Error("topicAliasMaximum from broker is out of range"));return}if(T.properties.topicAliasMaximum>0)_.topicAliasSend=new mx.default(T.properties.topicAliasMaximum)}if(T.properties.serverKeepAlive&&A.keepalive)A.keepalive=T.properties.serverKeepAlive;if(T.properties.maximumPacketSize){if(!A.properties)A.properties={};A.properties.maximumPacketSize=T.properties.maximumPacketSize}}if(L===0)_.reconnecting=!1,_._onConnect(T);else if(L>0){let J=new ux.ErrorWithReasonCode(`Connection refused: ${gx.ReasonCodes[L]}`,L);if(_.emit("error",J),_.options.reconnectOnConnackError)_._cleanUp(!0)}};A8.default=dx});var HG=W((XG)=>{Object.defineProperty(XG,"__esModule",{value:!0});var cx=(_,T,A)=>{_.log("handling pubrel packet");let E=typeof A<"u"?A:_.noop,{messageId:L}=T,J={cmd:"pubcomp",messageId:L};_.incomingStore.get(T,(X,H)=>{if(!X)_.emit("message",H.topic,H.payload,H),_.handleMessage(H,(Z)=>{if(Z)return E(Z);_.incomingStore.del(H,_.noop),_._sendPacket(J,E)});else _._sendPacket(J,E)})};XG.default=cx});var ZG=W((E8)=>{var L8=E8&&E8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(E8,"__esModule",{value:!0});var lx=L8(MK()),nx=L8(BK()),ix=L8(JG()),ax=L8(e4()),ox=L8(HG()),rx=(_,T,A)=>{let{options:E}=_;if(E.protocolVersion===5&&E.properties&&E.properties.maximumPacketSize&&E.properties.maximumPacketSize<T.length)return _.emit("error",Error(`exceeding packets size ${T.cmd}`)),_.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),_;switch(_.log("_handlePacket :: emitting packetreceive"),_.emit("packetreceive",T),T.cmd){case"publish":(0,lx.default)(_,T,A);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":_.reschedulePing(),(0,ax.default)(_,T),A();break;case"pubrel":_.reschedulePing(),(0,ox.default)(_,T,A);break;case"connack":(0,ix.default)(_,T),A();break;case"auth":_.reschedulePing(),(0,nx.default)(_,T),A();break;case"pingresp":_.log("_handlePacket :: received pingresp"),_.reschedulePing(!0),A();break;case"disconnect":_.emit("disconnect",T),A();break;default:_.log("_handlePacket :: unknown command"),A();break}};E8.default=rx});var AL=W((KG)=>{Object.defineProperty(KG,"__esModule",{value:!0});class YG{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let _=this.nextId++;if(this.nextId===65536)this.nextId=1;return _}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(_){return!0}deallocate(_){}clear(){}}KG.default=YG});var UG=W(($G)=>{Object.defineProperty($G,"__esModule",{value:!0});class GG{aliasToTopic;max;length;constructor(_){this.aliasToTopic={},this.max=_}put(_,T){if(T===0||T>this.max)return!1;return this.aliasToTopic[T]=_,this.length=Object.keys(this.aliasToTopic).length,!0}getTopicByAlias(_){return this.aliasToTopic[_]}clear(){this.aliasToTopic={}}}$G.default=GG});var WG=W((K4)=>{var ex=K4&&K4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(K4,"__esModule",{value:!0});K4.TypedEventEmitter=void 0;var _w=ex(j("events")),Tw=BT();class EL{}K4.TypedEventEmitter=EL;(0,Tw.applyMixin)(EL,_w.default)});var J8=W((cg,S0)=>{function LL(_){return S0.exports=LL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(T){return typeof T}:function(T){return T&&typeof Symbol=="function"&&T.constructor===Symbol&&T!==Symbol.prototype?"symbol":typeof T},S0.exports.__esModule=!0,S0.exports.default=S0.exports,LL(_)}S0.exports=LL,S0.exports.__esModule=!0,S0.exports.default=S0.exports});var QG=W((pg,X8)=>{var NG=J8().default;function Aw(_,T){if(NG(_)!="object"||!_)return _;var A=_[Symbol.toPrimitive];if(A!==void 0){var E=A.call(_,T||"default");if(NG(E)!="object")return E;throw TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(_)}X8.exports=Aw,X8.exports.__esModule=!0,X8.exports.default=X8.exports});var MG=W((lg,H8)=>{var Ew=J8().default,Lw=QG();function Jw(_){var T=Lw(_,"string");return Ew(T)=="symbol"?T:T+""}H8.exports=Jw,H8.exports.__esModule=!0,H8.exports.default=H8.exports});var VG=W((ng,Z8)=>{var Xw=MG();function Hw(_,T,A){return(T=Xw(T))in _?Object.defineProperty(_,T,{value:A,enumerable:!0,configurable:!0,writable:!0}):_[T]=A,_}Z8.exports=Hw,Z8.exports.__esModule=!0,Z8.exports.default=Z8.exports});var zG=W((ig,Y8)=>{function Zw(_){if(Array.isArray(_))return _}Y8.exports=Zw,Y8.exports.__esModule=!0,Y8.exports.default=Y8.exports});var FG=W((ag,K8)=>{function Yw(_,T){var A=_==null?null:typeof Symbol<"u"&&_[Symbol.iterator]||_["@@iterator"];if(A!=null){var E,L,J,X,H=[],Z=!0,Y=!1;try{if(J=(A=A.call(_)).next,T===0){if(Object(A)!==A)return;Z=!1}else for(;!(Z=(E=J.call(A)).done)&&(H.push(E.value),H.length!==T);Z=!0);}catch(K){Y=!0,L=K}finally{try{if(!Z&&A.return!=null&&(X=A.return(),Object(X)!==X))return}finally{if(Y)throw L}}return H}}K8.exports=Yw,K8.exports.__esModule=!0,K8.exports.default=K8.exports});var CG=W((og,G8)=>{function Kw(_,T){(T==null||T>_.length)&&(T=_.length);for(var A=0,E=Array(T);A<T;A++)E[A]=_[A];return E}G8.exports=Kw,G8.exports.__esModule=!0,G8.exports.default=G8.exports});var RG=W((rg,$8)=>{var OG=CG();function Gw(_,T){if(_){if(typeof _=="string")return OG(_,T);var A={}.toString.call(_).slice(8,-1);return A==="Object"&&_.constructor&&(A=_.constructor.name),A==="Map"||A==="Set"?Array.from(_):A==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(A)?OG(_,T):void 0}}$8.exports=Gw,$8.exports.__esModule=!0,$8.exports.default=$8.exports});var DG=W((sg,U8)=>{function $w(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
14
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}U8.exports=$w,U8.exports.__esModule=!0,U8.exports.default=U8.exports});var BG=W((tg,W8)=>{var Uw=zG(),Ww=FG(),Nw=RG(),Qw=DG();function Mw(_,T){return Uw(_)||Ww(_,T)||Nw(_,T)||Qw()}W8.exports=Mw,W8.exports.__esModule=!0,W8.exports.default=W8.exports});var PG=W((qG)=>{Object.defineProperty(qG,"__esModule",{value:!0});qG.createAddUniqueNumber=void 0;var Vw=(_)=>{return(T)=>{let A=_(T);return T.add(A),A}};qG.createAddUniqueNumber=Vw});var wG=W((jG)=>{Object.defineProperty(jG,"__esModule",{value:!0});jG.createCache=void 0;var zw=(_)=>{return(T,A)=>{return _.set(T,A),A}};jG.createCache=zw});var fG=W((hG)=>{Object.defineProperty(hG,"__esModule",{value:!0});hG.createGenerateUniqueNumber=void 0;var SG=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,vG=536870912,yG=vG*2,Fw=(_,T)=>{return(A)=>{let E=T.get(A),L=E===void 0?A.size:E<yG?E+1:0;if(!A.has(L))return _(A,L);if(A.size<vG){while(A.has(L))L=Math.floor(Math.random()*yG);return _(A,L)}if(A.size>SG)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(A.has(L))L=Math.floor(Math.random()*SG);return _(A,L)}};hG.createGenerateUniqueNumber=Fw});var JL=W((gG)=>{Object.defineProperty(gG,"__esModule",{value:!0});gG.generateUniqueNumber=gG.addUniqueNumber=void 0;var Cw=PG(),Ow=wG(),Rw=fG(),bG=new WeakMap,Dw=(0,Ow.createCache)(bG),Bw=gG.generateUniqueNumber=(0,Rw.createGenerateUniqueNumber)(Dw,bG),Am=gG.addUniqueNumber=(0,Cw.createAddUniqueNumber)(Bw)});var dG=W((Lm,N8)=>{function uG(_,T,A,E,L,J,X){try{var H=_[J](X),Z=H.value}catch(Y){return void A(Y)}H.done?T(Z):Promise.resolve(Z).then(E,L)}function Iw(_){return function(){var T=this,A=arguments;return new Promise(function(E,L){var J=_.apply(T,A);function X(Z){uG(J,E,L,X,H,"next",Z)}function H(Z){uG(J,E,L,X,H,"throw",Z)}X(void 0)})}}N8.exports=Iw,N8.exports.__esModule=!0,N8.exports.default=N8.exports});var XL=W((Jm,Q8)=>{function Pw(_,T){this.v=_,this.k=T}Q8.exports=Pw,Q8.exports.__esModule=!0,Q8.exports.default=Q8.exports});var HL=W((Xm,y0)=>{function lA(_,T,A,E){var L=Object.defineProperty;try{L({},"",{})}catch(J){L=0}y0.exports=lA=function(X,H,Z,Y){function K(G,$){lA(X,G,function(U){return this._invoke(G,$,U)})}H?L?L(X,H,{value:Z,enumerable:!Y,configurable:!Y,writable:!Y}):X[H]=Z:(K("next",0),K("throw",1),K("return",2))},y0.exports.__esModule=!0,y0.exports.default=y0.exports,lA(_,T,A,E)}y0.exports=lA,y0.exports.__esModule=!0,y0.exports.default=y0.exports});var ZL=W((Hm,v0)=>{var W0=HL();function cG(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var _,T,A=typeof Symbol=="function"?Symbol:{},E=A.iterator||"@@iterator",L=A.toStringTag||"@@toStringTag";function J(U,V,N,z){var Q=V&&V.prototype instanceof H?V:H,F=Object.create(Q.prototype);return W0(F,"_invoke",function(R,q,f){var h,b,l,c=0,W_=f||[],c_=!1,B_={p:0,n:0,v:_,a:C_,f:C_.bind(_,4),d:function(M_,q_){return h=M_,b=0,l=_,B_.n=q_,X}};function C_(K_,M_){for(b=K_,l=M_,T=0;!c_&&c&&!q_&&T<W_.length;T++){var q_,P_=W_[T],O0=B_.p,S1=P_[2];K_>3?(q_=S1===M_)&&(l=P_[(b=P_[4])?5:(b=3,3)],P_[4]=P_[5]=_):P_[0]<=O0&&((q_=K_<2&&O0<P_[1])?(b=0,B_.v=M_,B_.n=P_[1]):O0<S1&&(q_=K_<3||P_[0]>M_||M_>S1)&&(P_[4]=K_,P_[5]=M_,B_.n=S1,b=0))}if(q_||K_>1)return X;throw c_=!0,M_}return function(K_,M_,q_){if(c>1)throw TypeError("Generator is already running");for(c_&&M_===1&&C_(M_,q_),b=M_,l=q_;(T=b<2?_:l)||!c_;){h||(b?b<3?(b>1&&(B_.n=-1),C_(b,l)):B_.n=l:B_.v=l);try{if(c=2,h){if(b||(K_="next"),T=h[K_]){if(!(T=T.call(h,l)))throw TypeError("iterator result is not an object");if(!T.done)return T;l=T.value,b<2&&(b=0)}else b===1&&(T=h.return)&&T.call(h),b<2&&(l=TypeError("The iterator does not provide a '"+K_+"' method"),b=1);h=_}else if((T=(c_=B_.n<0)?l:R.call(q,B_))!==X)break}catch(P_){h=_,b=1,l=P_}finally{c=1}}return{value:T,done:c_}}}(U,N,z),!0),F}var X={};function H(){}function Z(){}function Y(){}T=Object.getPrototypeOf;var K=[][E]?T(T([][E]())):(W0(T={},E,function(){return this}),T),G=Y.prototype=H.prototype=Object.create(K);function $(U){return Object.setPrototypeOf?Object.setPrototypeOf(U,Y):(U.__proto__=Y,W0(U,L,"GeneratorFunction")),U.prototype=Object.create(G),U}return Z.prototype=Y,W0(G,"constructor",Y),W0(Y,"constructor",Z),Z.displayName="GeneratorFunction",W0(Y,L,"GeneratorFunction"),W0(G),W0(G,L,"Generator"),W0(G,E,function(){return this}),W0(G,"toString",function(){return"[object Generator]"}),(v0.exports=cG=function(){return{w:J,m:$}},v0.exports.__esModule=!0,v0.exports.default=v0.exports)()}v0.exports=cG,v0.exports.__esModule=!0,v0.exports.default=v0.exports});var GL=W((Zm,M8)=>{var jw=XL(),YL=HL();function KL(_,T){function A(L,J,X,H){try{var Z=_[L](J),Y=Z.value;return Y instanceof jw?T.resolve(Y.v).then(function(K){A("next",K,X,H)},function(K){A("throw",K,X,H)}):T.resolve(Y).then(function(K){Z.value=K,X(Z)},function(K){return A("throw",K,X,H)})}catch(K){H(K)}}var E;this.next||(YL(KL.prototype),YL(KL.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),YL(this,"_invoke",function(L,J,X){function H(){return new T(function(Z,Y){A(L,X,Z,Y)})}return E=E?E.then(H,H):H()},!0)}M8.exports=KL,M8.exports.__esModule=!0,M8.exports.default=M8.exports});var $L=W((Ym,V8)=>{var xw=ZL(),ww=GL();function Sw(_,T,A,E,L){return new ww(xw().w(_,T,A,E),L||Promise)}V8.exports=Sw,V8.exports.__esModule=!0,V8.exports.default=V8.exports});var pG=W((Km,z8)=>{var yw=$L();function vw(_,T,A,E,L){var J=yw(_,T,A,E,L);return J.next().then(function(X){return X.done?X.value:J.next()})}z8.exports=vw,z8.exports.__esModule=!0,z8.exports.default=z8.exports});var lG=W((Gm,F8)=>{function hw(_){var T=Object(_),A=[];for(var E in T)A.unshift(E);return function L(){for(;A.length;)if((E=A.pop())in T)return L.value=E,L.done=!1,L;return L.done=!0,L}}F8.exports=hw,F8.exports.__esModule=!0,F8.exports.default=F8.exports});var nG=W(($m,C8)=>{var kw=J8().default;function fw(_){if(_!=null){var T=_[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],A=0;if(T)return T.call(_);if(typeof _.next=="function")return _;if(!isNaN(_.length))return{next:function(){return _&&A>=_.length&&(_=void 0),{value:_&&_[A++],done:!_}}}}throw TypeError(kw(_)+" is not iterable")}C8.exports=fw,C8.exports.__esModule=!0,C8.exports.default=C8.exports});var aG=W((Um,h0)=>{var bw=XL(),gw=ZL(),mw=pG(),uw=$L(),dw=GL(),cw=lG(),iG=nG();function UL(){var _=gw(),T=_.m(UL),A=(Object.getPrototypeOf?Object.getPrototypeOf(T):T.__proto__).constructor;function E(X){var H=typeof X=="function"&&X.constructor;return!!H&&(H===A||(H.displayName||H.name)==="GeneratorFunction")}var L={throw:1,return:2,break:3,continue:3};function J(X){var H,Z;return function(Y){H||(H={stop:function(){return Z(Y.a,2)},catch:function(){return Y.v},abrupt:function(G,$){return Z(Y.a,L[G],$)},delegateYield:function(G,$,U){return H.resultName=$,Z(Y.d,iG(G),U)},finish:function(G){return Z(Y.f,G)}},Z=function(G,$,U){Y.p=H.prev,Y.n=H.next;try{return G($,U)}finally{H.next=Y.n}}),H.resultName&&(H[H.resultName]=Y.v,H.resultName=void 0),H.sent=Y.v,H.next=Y.n;try{return X.call(this,H)}finally{Y.p=H.prev,Y.n=H.next}}}return(h0.exports=UL=function(){return{wrap:function(Z,Y,K,G){return _.w(J(Z),Y,K,G&&G.reverse())},isGeneratorFunction:E,mark:_.m,awrap:function(Z,Y){return new bw(Z,Y)},AsyncIterator:dw,async:function(Z,Y,K,G,$){return(E(Y)?uw:mw)(J(Z),Y,K,G,$)},keys:cw,values:iG}},h0.exports.__esModule=!0,h0.exports.default=h0.exports)()}h0.exports=UL,h0.exports.__esModule=!0,h0.exports.default=h0.exports});var rG=W((Wm,oG)=>{var nA=aG()();oG.exports=nA;try{regeneratorRuntime=nA}catch(_){if(typeof globalThis==="object")globalThis.regeneratorRuntime=nA;else Function("r","regeneratorRuntime = r")(nA)}});var tG=W((iA,sG)=>{(function(_,T){typeof iA==="object"&&typeof sG<"u"?T(iA,VG(),BG(),JL(),dG(),rG()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.brokerFactory={},_._defineProperty,_._slicedToArray,_.fastUniqueNumbers,_._asyncToGenerator,_._regeneratorRuntime))})(iA,function(_,T,A,E,L,J){var X=function(Q){return typeof Q.start==="function"},H=new WeakMap;function Z(z,Q){var F=Object.keys(z);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(z);Q&&(R=R.filter(function(q){return Object.getOwnPropertyDescriptor(z,q).enumerable})),F.push.apply(F,R)}return F}function Y(z){for(var Q=1;Q<arguments.length;Q++){var F=arguments[Q]!=null?arguments[Q]:{};Q%2?Z(Object(F),!0).forEach(function(R){T(z,R,F[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(z,Object.getOwnPropertyDescriptors(F)):Z(Object(F)).forEach(function(R){Object.defineProperty(z,R,Object.getOwnPropertyDescriptor(F,R))})}return z}var K=function(Q){return Y(Y({},Q),{},{connect:function(R){var q=R.call;return L(J.mark(function f(){var h,b,l,c;return J.wrap(function(W_){while(!0)switch(W_.prev=W_.next){case 0:return h=new MessageChannel,b=h.port1,l=h.port2,W_.next=1,q("connect",{port:b},[b]);case 1:return c=W_.sent,H.set(l,c),W_.abrupt("return",l);case 2:case"end":return W_.stop()}},f)}))},disconnect:function(R){var q=R.call;return function(){var f=L(J.mark(function h(b){var l;return J.wrap(function(c){while(!0)switch(c.prev=c.next){case 0:if(l=H.get(b),l!==void 0){c.next=1;break}throw Error("The given port is not connected.");case 1:return c.next=2,q("disconnect",{portId:l});case 2:case"end":return c.stop()}},h)}));return function(h){return f.apply(this,arguments)}}()},isSupported:function(R){var q=R.call;return function(){return q("isSupported")}}})};function G(z,Q){var F=Object.keys(z);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(z);Q&&(R=R.filter(function(q){return Object.getOwnPropertyDescriptor(z,q).enumerable})),F.push.apply(F,R)}return F}function $(z){for(var Q=1;Q<arguments.length;Q++){var F=arguments[Q]!=null?arguments[Q]:{};Q%2?G(Object(F),!0).forEach(function(R){T(z,R,F[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(z,Object.getOwnPropertyDescriptors(F)):G(Object(F)).forEach(function(R){Object.defineProperty(z,R,Object.getOwnPropertyDescriptor(F,R))})}return z}var U=new WeakMap,V=function(Q){if(U.has(Q))return U.get(Q);var F=new Map;return U.set(Q,F),F},N=function(Q){var F=K(Q);return function(R){var q=V(R);if(R.addEventListener("message",function(C_){var K_=C_.data,M_=K_.id;if(M_!==null&&q.has(M_)){var q_=q.get(M_),P_=q_.reject,O0=q_.resolve;if(q.delete(M_),K_.error===void 0)O0(K_.result);else P_(Error(K_.error.message))}}),X(R))R.start();var f=function(K_){var M_=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,q_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(P_,O0){var S1=E.generateUniqueNumber(q);if(q.set(S1,{reject:O0,resolve:P_}),M_===null)R.postMessage({id:S1,method:K_},q_);else R.postMessage({id:S1,method:K_,params:M_},q_)})},h=function(K_,M_){var q_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];R.postMessage({id:null,method:K_,params:M_},q_)},b={};for(var l=0,c=Object.entries(F);l<c.length;l++){var W_=A(c[l],2),c_=W_[0],B_=W_[1];b=$($({},b),{},T({},c_,B_({call:f,notify:h})))}return $({},b)}};_.createBroker=N})});var _$=W((aA,eG)=>{(function(_,T){typeof aA==="object"&&typeof eG<"u"?T(aA,J8(),tG(),JL()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.workerTimersBroker={},_._typeof,_.brokerFactory,_.fastUniqueNumbers))})(aA,function(_,T,A,E){var L=new Map([[0,null]]),J=new Map([[0,null]]),X=A.createBroker({clearInterval:function(Y){var K=Y.call;return function(G){if(T(L.get(G))==="symbol")L.set(G,null),K("clear",{timerId:G,timerType:"interval"}).then(function(){L.delete(G)})}},clearTimeout:function(Y){var K=Y.call;return function(G){if(T(J.get(G))==="symbol")J.set(G,null),K("clear",{timerId:G,timerType:"timeout"}).then(function(){J.delete(G)})}},setInterval:function(Y){var K=Y.call;return function(G){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var U=arguments.length,V=Array(U>2?U-2:0),N=2;N<U;N++)V[N-2]=arguments[N];var z=Symbol(),Q=E.generateUniqueNumber(L);L.set(Q,z);var F=function(){return K("set",{delay:$,now:performance.timeOrigin+performance.now(),timerId:Q,timerType:"interval"}).then(function(){var q=L.get(Q);if(q===void 0)throw Error("The timer is in an undefined state.");if(q===z){if(G.apply(void 0,V),L.get(Q)===z)F()}})};return F(),Q}},setTimeout:function(Y){var K=Y.call;return function(G){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var U=arguments.length,V=Array(U>2?U-2:0),N=2;N<U;N++)V[N-2]=arguments[N];var z=Symbol(),Q=E.generateUniqueNumber(J);return J.set(Q,z),K("set",{delay:$,now:performance.timeOrigin+performance.now(),timerId:Q,timerType:"timeout"}).then(function(){var F=J.get(Q);if(F===void 0)throw Error("The timer is in an undefined state.");if(F===z)J.delete(Q),G.apply(void 0,V)}),Q}}}),H=function(Y){var K=new Worker(Y);return X(K)};_.load=H,_.wrap=X})});var A$=W((oA,T$)=>{(function(_,T){typeof oA==="object"&&typeof T$<"u"?T(oA,_$()):typeof define==="function"&&define.amd?define(["exports","worker-timers-broker"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.workerTimers={},_.workerTimersBroker))})(oA,function(_,T){var A=function(K,G){var $=null;return function(){if($!==null)return $;var U=new Blob([G],{type:"application/javascript; charset=utf-8"}),V=URL.createObjectURL(U);return $=K(V),setTimeout(function(){return URL.revokeObjectURL(V)}),$}},E='(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise(function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)})}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise(function(t){e.set(a,[r(n,s,i,e,t,a),t])})}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark(function e(r){var n,o,u;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark(function e(r){var n,o,u,a,i;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){function u(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n:(u("next",0),u("throw",1),u("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a(\'The requested method called "\'.concat(e,\'" is not supported.\'),u.METHOD_NOT_FOUND)},s=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned no required result.\'),u.INTERNAL_ERROR)},c=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned an unexpected result.\'),u.INTERNAL_ERROR)},f=function(e){return a(\'The specified parameter called "portId" with the given value "\'.concat(e,\'" does not identify a port connected to this worker.\'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark(function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}},t,null,[[1,11]])}));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise(function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])})};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach(function(t){n(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,function(){u(),r.close(),x.delete(a)}),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark(function e(){var t,n,o;return r.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}},e)}));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then(function(e){u("next",e,a,i)},function(e){u("throw",e,a,i)}):r.resolve(c).then(function(e){s.value=e,a(s)},function(e){return u("throw",e,a,i)})}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),o(this,"_invoke",function(e,t,n){function o(){return new r(function(t,r){u(e,n,t,r)})}return a=a?a.then(o,o):o()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a \'"+o+"\' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,function(){return this}),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,function(){return this}),n(v,"toString",function(){return"[object Generator]"}),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();',L=A(T.load,E),J=function(K){return L().clearInterval(K)},X=function(K){return L().clearTimeout(K)},H=function(){var K;return(K=L()).setInterval.apply(K,arguments)},Z=function(){var K;return(K=L()).setTimeout.apply(K,arguments)};_.clearInterval=J,_.clearTimeout=X,_.setInterval=H,_.setTimeout=Z})});var O8=W((J$)=>{Object.defineProperty(J$,"__esModule",{value:!0});J$.isReactNativeBrowser=J$.isWebWorker=void 0;var pw=()=>{if(typeof window<"u"){if(typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&process?.versions)return!Object.prototype.hasOwnProperty.call(process.versions,"electron");return typeof window.document<"u"}return!1},E$=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),L$=()=>typeof navigator<"u"&&navigator.product==="ReactNative",lw=pw()||E$()||L$();J$.isWebWorker=E$();J$.isReactNativeBrowser=L$();J$.default=lw});var K$=W((k0)=>{var aw=k0&&k0.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),ow=k0&&k0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),rw=k0&&k0.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")aw(A,T,E[L])}return ow(A,T),A}}();Object.defineProperty(k0,"__esModule",{value:!0});var H$=A$(),WL=rw(O8()),Z$={set:H$.setInterval,clear:H$.clearInterval},Y$={set:(_,T)=>setInterval(_,T),clear:(_)=>clearInterval(_)},sw=(_)=>{switch(_){case"native":return Y$;case"worker":return Z$;case"auto":default:return WL.default&&!WL.isWebWorker&&!WL.isReactNativeBrowser?Z$:Y$}};k0.default=sw});var NL=W((R8)=>{var tw=R8&&R8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(R8,"__esModule",{value:!0});var ew=tw(K$());class G${_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(_,T){this.client=_,this.timer=typeof T==="object"&&"set"in T&&"clear"in T?T:(0,ew.default)(T),this.setKeepalive(_.options.keepalive)}clear(){if(this.timerId)this.timer.clear(this.timerId),this.timerId=null}setKeepalive(_){if(_*=1000,isNaN(_)||_<=0||_>2147483647)throw Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${_}`);this._keepalive=_,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${_}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let _=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+_,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{if(this.destroyed)return;if(this.counter+=1,this.counter===2)this.client.sendPing();else if(this.counter>2)this.client.onKeepaliveTimeout()},this._intervalEvery)}}R8.default=G$});var sA=W((l1)=>{var _S=l1&&l1.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),TS=l1&&l1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Q$=l1&&l1.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")_S(A,T,E[L])}return TS(A,T),A}}(),t0=l1&&l1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(l1,"__esModule",{value:!0});var QL=t0(wA()),AS=n0(),$$=t0(YK()),ES=t0(u1()),U$=Q$($K()),G4=t0(dE()),LS=t0(ZG()),JS=t0(AL()),XS=t0(UG()),D8=BT(),HS=WG(),ZS=t0(NL()),W$=Q$(O8()),ML=globalThis.setImmediate||((..._)=>{let T=_.shift();(0,D8.nextTick)(()=>{T(..._)})}),N$={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1000,connectTimeout:30000,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class rA extends HS.TypedEventEmitter{static VERSION=D8.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(_,T){super();this.options=T||{};for(let A in N$)if(typeof this.options[A]>"u")this.options[A]=N$[A];else this.options[A]=T[A];if(this.log=this.options.log||(0,ES.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",rA.VERSION),W$.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",W$.default?"browser":"node");if(this.log("MqttClient :: options.protocol",T.protocol),this.log("MqttClient :: options.protocolVersion",T.protocolVersion),this.log("MqttClient :: options.username",T.username),this.log("MqttClient :: options.keepalive",T.keepalive),this.log("MqttClient :: options.reconnectPeriod",T.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",T.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",T.properties?T.properties.topicAliasMaximum:void 0),this.options.clientId=typeof T.clientId==="string"?T.clientId:rA.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=T.protocolVersion===5&&T.customHandleAcks?T.customHandleAcks:(...A)=>{A[3](null,0)},!this.options.writeCache)QL.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=_,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new JS.default:this.options.messageIdProvider,this.outgoingStore=T.outgoingStore||new G4.default,this.incomingStore=T.incomingStore||new G4.default,this.queueQoSZero=T.queueQoSZero===void 0?!0:T.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,T.properties&&T.properties.topicAliasMaximum>0)if(T.properties.topicAliasMaximum>65535)this.log("MqttClient :: options.properties.topicAliasMaximum is out of range");else this.topicAliasRecv=new XS.default(T.properties.topicAliasMaximum);if(this.on("connect",()=>{let{queue:A}=this,E=()=>{let L=A.shift();this.log("deliver :: entry %o",L);let J=null;if(!L){this._resubscribe();return}J=L.packet,this.log("deliver :: call _sendPacket for %o",J);let X=!0;if(J.messageId&&J.messageId!==0){if(!this.messageIdProvider.register(J.messageId))X=!1}if(X)this._sendPacket(J,(H)=>{if(L.cb)L.cb(H);E()});else this.log("messageId: %d has already used. The message is skipped and removed.",J.messageId),E()};this.log("connect :: sending queued packets"),E()}),this.on("close",()=>{if(this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv)this.topicAliasRecv.clear();this.log("close :: calling _setupReconnect"),this._setupReconnect()}),!this.options.manualConnect)this.log("MqttClient :: setting up stream"),this.connect()}handleAuth(_,T){T()}handleMessage(_,T){T()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let _=new AS.Writable,T=QL.default.parser(this.options),A=null,E=[];if(this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting)this.incomingStore=this.options.incomingStore||new G4.default,this.outgoingStore=this.options.outgoingStore||new G4.default,this.disconnecting=!1,this.disconnected=!1;this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),T.on("packet",(Z)=>{this.log("parser :: on packet push to packets array."),E.push(Z)});let L=()=>{this.log("work :: getting next packet in queue");let Z=E.shift();if(Z)this.log("work :: packet pulled from queue"),(0,LS.default)(this,Z,J);else{this.log("work :: no packets in queue");let Y=A;if(A=null,this.log("work :: done flag is %s",!!Y),Y)Y()}},J=()=>{if(E.length)(0,D8.nextTick)(L);else{let Z=A;A=null,Z()}};_._write=(Z,Y,K)=>{A=K,this.log("writable stream :: parsing buffer"),T.parse(Z),L()};let X=(Z)=>{if(this.log("streamErrorHandler :: error",Z.message),Z.code)this.log("streamErrorHandler :: emitting error"),this.emit("error",Z);else this.noop(Z)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(_),this.stream.on("error",X),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let H={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will)H.will={...this.options.will,payload:this.options.will?.payload};if(this.topicAliasRecv){if(!H.properties)H.properties={};if(this.topicAliasRecv)H.properties.topicAliasMaximum=this.topicAliasRecv.max}if(this._writePacket(H),T.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket==="object"){let Z={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(Z)}}return this.stream.setMaxListeners(1000),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(_,T,A,E){this.log("publish :: message `%s` to topic `%s`",T,_);let{options:L}=this;if(typeof A==="function")E=A,A=null;A=A||{},A={...{qos:0,retain:!1,dup:!1},...A};let{qos:X,retain:H,dup:Z,properties:Y,cbStorePut:K}=A;if(this._checkDisconnecting(E))return this;let G=()=>{let $=0;if(X===1||X===2){if($=this._nextId(),$===null)return this.log("No messageId left"),!1}let U={cmd:"publish",topic:_,payload:T,qos:X,retain:H,messageId:$,dup:Z};if(L.protocolVersion===5)U.properties=Y;switch(this.log("publish :: qos",X),X){case 1:case 2:this.outgoing[U.messageId]={volatile:!1,cb:E||this.noop},this.log("MqttClient:publish: packet cmd: %s",U.cmd),this._sendPacket(U,void 0,K);break;default:this.log("MqttClient:publish: packet cmd: %s",U.cmd),this._sendPacket(U,E,K);break}return!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!G())this._storeProcessingQueue.push({invoke:G,cbStorePut:A.cbStorePut,callback:E});return this}publishAsync(_,T,A){return new Promise((E,L)=>{this.publish(_,T,A,(J,X)=>{if(J)L(J);else E(X)})})}subscribe(_,T,A){let E=this.options.protocolVersion;if(typeof T==="function")A=T;A=A||this.noop;let L=!1,J=[];if(typeof _==="string")_=[_],J=_;else if(Array.isArray(_))J=_;else if(typeof _==="object")L=_.resubscribe,delete _.resubscribe,J=Object.keys(_);let X=U$.validateTopics(J);if(X!==null)return ML(A,Error(`Invalid topic ${X}`)),this;if(this._checkDisconnecting(A))return this.log("subscribe: discconecting true"),this;let H={qos:0};if(E===5)H.nl=!1,H.rap=!1,H.rh=0;T={...H,...T};let{properties:Z}=T,Y=[],K=(U,V)=>{if(V=V||T,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,U)||this._resubscribeTopics[U].qos<V.qos||L){let N={topic:U,qos:V.qos};if(E===5)N.nl=V.nl,N.rap=V.rap,N.rh=V.rh,N.properties=Z;this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",N.topic,N.qos),Y.push(N)}};if(Array.isArray(_))_.forEach((U)=>{this.log("subscribe: array topic %s",U),K(U)});else Object.keys(_).forEach((U)=>{this.log("subscribe: object topic %s, %o",U,_[U]),K(U,_[U])});if(!Y.length)return A(null,[]),this;let G=(U,V)=>{let N={cmd:"subscribe",subscriptions:U,messageId:V};if(Z)N.properties=Z;if(this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];U.forEach((F)=>{if(this.options.reconnectPeriod>0){let R={qos:F.qos};if(E===5)R.nl=F.nl||!1,R.rap=F.rap||!1,R.rh=F.rh||0,R.properties=F.properties;this._resubscribeTopics[F.topic]=R,Q.push(F.topic)}}),this.messageIdToTopic[N.messageId]=Q}let z=new Promise((Q,F)=>{this.outgoing[N.messageId]={volatile:!0,cb(R,q){if(!R){let{granted:f}=q;for(let h=0;h<f.length;h+=1)U[h].qos=f[h]}if(!R)Q(q);else F(new D8.ErrorWithSubackPacket(R.message,q))}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(N),z},$=()=>{let U=this.options.subscribeBatchSize??Y.length,V=[];for(let N=0;N<Y.length;N+=U){let z=Y.slice(N,N+U),Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;V.push(G(z,Q))}return Promise.all(V).then((N)=>{A(null,Y,N.at(-1))}).catch((N)=>{A(N,Y,N.packet)}),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!$())this._storeProcessingQueue.push({invoke:$,callback:A});return this}subscribeAsync(_,T){return new Promise((A,E)=>{this.subscribe(_,T,(L,J)=>{if(L)E(L);else A(J)})})}unsubscribe(_,T,A){if(typeof _==="string")_=[_];if(typeof T==="function")A=T;A=A||this.noop;let E=U$.validateTopics(_);if(E!==null)return ML(A,Error(`Invalid topic ${E}`)),this;if(this._checkDisconnecting(A))return this;let L=()=>{let J=this._nextId();if(J===null)return this.log("No messageId left"),!1;let X={cmd:"unsubscribe",messageId:J,unsubscriptions:[]};if(typeof _==="string")X.unsubscriptions=[_];else if(Array.isArray(_))X.unsubscriptions=_;if(this.options.resubscribe)X.unsubscriptions.forEach((H)=>{delete this._resubscribeTopics[H]});if(typeof T==="object"&&T.properties)X.properties=T.properties;return this.outgoing[X.messageId]={volatile:!0,cb:A},this.log("unsubscribe: call _sendPacket"),this._sendPacket(X),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!L())this._storeProcessingQueue.push({invoke:L,callback:A});return this}unsubscribeAsync(_,T){return new Promise((A,E)=>{this.unsubscribe(_,T,(L,J)=>{if(L)E(L);else A(J)})})}end(_,T,A){if(this.log("end :: (%s)",this.options.clientId),_==null||typeof _!=="boolean")A=A||T,T=_,_=!1;if(typeof T!=="object")A=A||T,T=null;if(this.log("end :: cb? %s",!!A),!A||typeof A!=="function")A=this.noop;let E=()=>{if(this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close((J)=>{this.outgoingStore.close((X)=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),A){let H=J||X;this.log("end :: closeStores: invoking callback with args"),A(H)}})}),this._deferredReconnect)this._deferredReconnect();else if(this.options.reconnectPeriod===0||this.options.manualConnect)this.disconnecting=!1},L=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,_),this._cleanUp(_,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,D8.nextTick)(E)},T)};if(this.disconnecting)return A(),this;if(this._clearReconnect(),this.disconnecting=!0,!_&&Object.keys(this.outgoing).length>0)this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,L,10));else this.log("end :: (%s) :: immediately calling finish",this.options.clientId),L();return this}endAsync(_,T){return new Promise((A,E)=>{this.end(_,T,(L)=>{if(L)E(L);else A()})})}removeOutgoingMessage(_){if(this.outgoing[_]){let{cb:T}=this.outgoing[_];this._removeOutgoingAndStoreMessage(_,()=>{T(Error("Message removed"))})}return this}reconnect(_){this.log("client reconnect");let T=()=>{if(_)this.options.incomingStore=_.incomingStore,this.options.outgoingStore=_.outgoingStore;else this.options.incomingStore=null,this.options.outgoingStore=null;this.incomingStore=this.options.incomingStore||new G4.default,this.outgoingStore=this.options.outgoingStore||new G4.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};if(this.disconnecting&&!this.disconnected)this._deferredReconnect=T;else T();return this}_flushVolatile(){if(this.outgoing)this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach((_)=>{if(this.outgoing[_].volatile&&typeof this.outgoing[_].cb==="function")this.outgoing[_].cb(Error("Connection closed")),delete this.outgoing[_]})}_flush(){if(this.outgoing)this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach((_)=>{if(typeof this.outgoing[_].cb==="function")this.outgoing[_].cb(Error("Connection closed")),delete this.outgoing[_]})}_removeTopicAliasAndRecoverTopicName(_){let T;if(_.properties)T=_.properties.topicAlias;let A=_.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",T,A),A.length===0){if(typeof T>"u")return Error("Unregistered Topic Alias");if(A=this.topicAliasSend.getTopicByAlias(T),typeof A>"u")return Error("Unregistered Topic Alias");_.topic=A}if(T)delete _.properties.topicAlias}_checkDisconnecting(_){if(this.disconnecting)if(_&&_!==this.noop)_(Error("client disconnecting"));else this.emit("error",Error("client disconnecting"));return this.disconnecting}_reconnect(){if(this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected)this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.");else this.log("_reconnect: calling connect"),this.connect()}_setupReconnect(){if(!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0){if(!this.reconnecting)this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0;this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)}else this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){if(this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer)clearInterval(this.reconnectTimer),this.reconnectTimer=null}_cleanUp(_,T,A={}){if(T)this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",T);if(this.log("_cleanUp :: forced? %s",_),_){if(this.options.reconnectPeriod===0&&this.options.clean)this._flush();this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy()}else{let E={cmd:"disconnect",...A};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(E,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),ML(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}if(!this.disconnecting&&!this.reconnecting)this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect();if(this._destroyKeepaliveManager(),T&&!this.connected)this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",T),T()}_storeAndSend(_,T,A){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",_.cmd);let E=_,L;if(E.cmd==="publish"){if(E=(0,$$.default)(_),L=this._removeTopicAliasAndRecoverTopicName(E),L)return T&&T(L)}this.outgoingStore.put(E,(J)=>{if(J)return T&&T(J);A(),this._writePacket(_,T)})}_applyTopicAlias(_){if(this.options.protocolVersion===5){if(_.cmd==="publish"){let T;if(_.properties)T=_.properties.topicAlias;let A=_.topic.toString();if(this.topicAliasSend){if(T){if(A.length!==0){if(this.log("applyTopicAlias :: register topic: %s - alias: %d",A,T),!this.topicAliasSend.put(A,T))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,T),Error("Sending Topic Alias out of range")}}else if(A.length!==0){if(this.options.autoAssignTopicAlias)if(T=this.topicAliasSend.getAliasByTopic(A),T)_.topic="",_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",A,T);else T=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(A,T),_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",A,T);else if(this.options.autoUseTopicAlias){if(T=this.topicAliasSend.getAliasByTopic(A),T)_.topic="",_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",A,T)}}}else if(T)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,T),Error("Sending Topic Alias out of range")}}}_noop(_){this.log("noop ::",_)}_writePacket(_,T){this.log("_writePacket :: packet: %O",_),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",_),this.log("_writePacket :: writing to stream");let A=QL.default.writeToStream(_,this.stream,this.options);if(this.log("_writePacket :: writeToStream result %s",A),!A&&T&&T!==this.noop)this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",T);else if(T)this.log("_writePacket :: invoking cb"),T()}_sendPacket(_,T,A,E){this.log("_sendPacket :: (%s) :: start",this.options.clientId),A=A||this.noop,T=T||this.noop;let L=this._applyTopicAlias(_);if(L){T(L);return}if(!this.connected){if(_.cmd==="auth"){this._writePacket(_,T);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(_,T,A);return}if(E){this._writePacket(_,T);return}switch(_.cmd){case"publish":break;case"pubrel":this._storeAndSend(_,T,A);return;default:this._writePacket(_,T);return}switch(_.qos){case 2:case 1:this._storeAndSend(_,T,A);break;case 0:default:this._writePacket(_,T);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(_,T,A){this.log("_storePacket :: packet: %o",_),this.log("_storePacket :: cb? %s",!!T),A=A||this.noop;let E=_;if(E.cmd==="publish"){E=(0,$$.default)(_);let J=this._removeTopicAliasAndRecoverTopicName(E);if(J)return T&&T(J)}let L=E.qos||0;if(L===0&&this.queueQoSZero||E.cmd!=="publish")this.queue.push({packet:E,cb:T});else if(L>0)T=this.outgoing[E.messageId]?this.outgoing[E.messageId].cb:null,this.outgoingStore.put(E,(J)=>{if(J)return T&&T(J);A()});else if(T)T(Error("No connection to broker"))}_setupKeepaliveManager(){if(this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive)this.keepaliveManager=new ZS.default(this,this.options.timerVariant)}_destroyKeepaliveManager(){if(this.keepaliveManager)this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null}reschedulePing(_=!1){if(this.keepaliveManager&&this.options.keepalive&&(_||this.options.reschedulePings))this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let _=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&_.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let T=0;T<_.length;T++){let A={};A[_[T]]=this._resubscribeTopics[_[T]],A.resubscribe=!0,this.subscribe(A,{properties:A[_[T]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(_){if(this.disconnected){this.emit("connect",_);return}this.connackPacket=_,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let T=()=>{let A=this.outgoingStore.createStream(),E=()=>{A.destroy(),A=null,this._flushStoreProcessingQueue(),L()},L=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",E),A.on("error",(X)=>{L(),this._flushStoreProcessingQueue(),this.removeListener("close",E),this.emit("error",X)});let J=()=>{if(!A)return;let X=A.read(1),H;if(!X){A.once("readable",J);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[X.messageId]){J();return}if(!this.disconnecting&&!this.reconnectTimer)if(H=this.outgoing[X.messageId]?this.outgoing[X.messageId].cb:null,this.outgoing[X.messageId]={volatile:!1,cb(Z,Y){if(H)H(Z,Y);J()}},this._packetIdsDuringStoreProcessing[X.messageId]=!0,this.messageIdProvider.register(X.messageId))this._sendPacket(X,void 0,void 0,!0);else this.log("messageId: %d has already used.",X.messageId);else if(A.destroy)A.destroy()};A.on("end",()=>{let X=!0;for(let H in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[H]){X=!1;break}if(this.removeListener("close",E),X)L(),this._invokeAllStoreProcessingQueue(),this.emit("connect",_);else T()}),J()};T()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let _=this._storeProcessingQueue[0];if(_&&_.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){while(this._invokeStoreProcessingQueue());}_flushStoreProcessingQueue(){for(let _ of this._storeProcessingQueue){if(_.cbStorePut)_.cbStorePut(Error("Connection closed"));if(_.callback)_.callback(Error("Connection closed"))}this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(_,T){delete this.outgoing[_],this.outgoingStore.del({messageId:_},(A,E)=>{T(A,E),this.messageIdProvider.deallocate(_),this._invokeStoreProcessingQueue()})}}l1.default=rA});var z$=W((V$)=>{Object.defineProperty(V$,"__esModule",{value:!0});var YS=TL();class M${numberAllocator;lastId;constructor(){this.numberAllocator=new YS.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(_){return this.numberAllocator.use(_)}deallocate(_){this.numberAllocator.free(_)}clear(){this.numberAllocator.clear()}}V$.default=M$});var tA=W((R$)=>{Object.defineProperty(R$,"__esModule",{value:!0});R$.BufferedDuplex=void 0;R$.writev=C$;var GS=n0(),F$=j("buffer");function C$(_,T){let A=Array(_.length);for(let E=0;E<_.length;E++)if(typeof _[E].chunk==="string")A[E]=F$.Buffer.from(_[E].chunk,"utf8");else A[E]=_[E].chunk;this._write(F$.Buffer.concat(A),"binary",T)}class O$ extends GS.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(_,T,A){super({objectMode:!0});if(this.proxy=T,this.socket=A,this.writeQueue=[],!_.objectMode)this._writev=C$.bind(this);this.isSocketOpen=!1,this.proxy.on("data",(E)=>{if(!this.destroyed&&this.readable)this.push(E)})}_read(_){this.proxy.read(_)}_write(_,T,A){if(!this.isSocketOpen)this.writeQueue.push({chunk:_,encoding:T,cb:A});else this.writeToProxy(_,T,A)}_final(_){this.writeQueue=[],this.proxy.end(_)}_destroy(_,T){this.writeQueue=[],this.proxy.destroy(),T(_)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(_,T,A){if(this.proxy.write(_,T)===!1)this.proxy.once("drain",A);else A()}processWriteQueue(){while(this.writeQueue.length>0){let{chunk:_,encoding:T,cb:A}=this.writeQueue.shift();this.writeToProxy(_,T,A)}}}R$.BufferedDuplex=O$});var B8=W((_T)=>{var zL=_T&&_T.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(_T,"__esModule",{value:!0});_T.streamBuilder=_T.browserStreamBuilder=void 0;var eA=j("buffer"),B$=zL(j("ws")),US=zL(u1()),WS=n0(),NS=zL(O8()),VL=tA(),e0=(0,US.default)("mqttjs:ws"),QS=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function q$(_,T){let A=`${_.protocol}://${_.hostname}:${_.port}${_.path}`;if(typeof _.transformWsUrl==="function")A=_.transformWsUrl(A,_,T);return A}function I$(_){let T=_;if(!_.port)if(_.protocol==="wss")T.port=443;else T.port=80;if(!_.path)T.path="/";if(!_.wsOptions)T.wsOptions={};if(!NS.default&&!_.forceNativeWebSocket&&_.protocol==="wss")QS.forEach((A)=>{if(Object.prototype.hasOwnProperty.call(_,A)&&!Object.prototype.hasOwnProperty.call(_.wsOptions,A))T.wsOptions[A]=_[A]});return T}function MS(_){let T=I$(_);if(!T.hostname)T.hostname=T.host;if(!T.hostname){if(typeof document>"u")throw Error("Could not determine host. Specify host manually.");let A=new URL(document.URL);if(T.hostname=A.hostname,!T.port)T.port=Number(A.port)}if(T.objectMode===void 0)T.objectMode=!(T.binary===!0||T.binary===void 0);return T}function VS(_,T,A){e0("createWebSocket"),e0(`protocol: ${A.protocolId} ${A.protocolVersion}`);let E=A.protocolId==="MQIsdp"&&A.protocolVersion===3?"mqttv3.1":"mqtt";e0(`creating new Websocket for url: ${T} and protocol: ${E}`);let L;if(A.createWebsocket)L=A.createWebsocket(T,[E],A);else L=new B$.default(T,[E],A.wsOptions);return L}function zS(_,T){let A=T.protocolId==="MQIsdp"&&T.protocolVersion===3?"mqttv3.1":"mqtt",E=q$(T,_),L;if(T.createWebsocket)L=T.createWebsocket(E,[A],T);else L=new WebSocket(E,[A]);return L.binaryType="arraybuffer",L}var FS=(_,T)=>{e0("streamBuilder");let A=I$(T);A.hostname=A.hostname||A.host||"localhost";let E=q$(A,_),L=VS(_,E,A),J=B$.default.createWebSocketStream(L,A.wsOptions);return J.url=E,L.on("close",()=>{J.destroy()}),J};_T.streamBuilder=FS;var CS=(_,T)=>{e0("browserStreamBuilder");let A,L=MS(T).browserBufferSize||524288,J=T.browserBufferTimeout||1000,X=!T.objectMode,H=zS(_,T),Z=K(T,N,z);if(!T.objectMode)Z._writev=VL.writev.bind(Z);Z.on("close",()=>{H.close()});let Y=typeof H.addEventListener<"u";if(H.readyState===H.OPEN)A=Z,A.socket=H;else if(A=new VL.BufferedDuplex(T,Z,H),Y)H.addEventListener("open",G);else H.onopen=G;if(Y)H.addEventListener("close",$),H.addEventListener("error",U),H.addEventListener("message",V);else H.onclose=$,H.onerror=U,H.onmessage=V;function K(Q,F,R){let q=new WS.Transform({objectMode:Q.objectMode});return q._write=F,q._flush=R,q}function G(){if(e0("WebSocket onOpen"),A instanceof VL.BufferedDuplex)A.socketReady()}function $(Q){e0("WebSocket onClose",Q),A.end(),A.destroy()}function U(Q){e0("WebSocket onError",Q);let F=Error("WebSocket error");F.event=Q,A.destroy(F)}async function V(Q){if(!Z||!Z.readable||!Z.writable)return;let{data:F}=Q;if(F instanceof ArrayBuffer)F=eA.Buffer.from(F);else if(F instanceof Blob)F=eA.Buffer.from(await new Response(F).arrayBuffer());else F=eA.Buffer.from(F,"utf8");Z.push(F)}function N(Q,F,R){if(H.bufferedAmount>L){setTimeout(N,J,Q,F,R);return}if(X&&typeof Q==="string")Q=eA.Buffer.from(Q,"utf8");try{H.send(Q)}catch(q){return R(q)}R()}function z(Q){H.close(),Q()}return A};_T.browserStreamBuilder=CS});var S$=W((w$)=>{Object.defineProperty(w$,"__esModule",{value:!0});var P$=j("buffer"),ST={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};w$.ERRORS=ST;function OS(_){if(!P$.Buffer.isEncoding(_))throw Error(ST.INVALID_ENCODING)}w$.checkEncoding=OS;function j$(_){return typeof _==="number"&&isFinite(_)&&qS(_)}w$.isFiniteInteger=j$;function x$(_,T){if(typeof _==="number"){if(!j$(_)||_<0)throw Error(T?ST.INVALID_OFFSET:ST.INVALID_LENGTH)}else throw Error(T?ST.INVALID_OFFSET_NON_NUMBER:ST.INVALID_LENGTH_NON_NUMBER)}function RS(_){x$(_,!1)}w$.checkLengthValue=RS;function DS(_){x$(_,!0)}w$.checkOffsetValue=DS;function BS(_,T){if(_<0||_>T.length)throw Error(ST.INVALID_TARGET_OFFSET)}w$.checkTargetOffset=BS;function qS(_){return typeof _==="number"&&isFinite(_)&&Math.floor(_)===_}function IS(_){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof P$.Buffer.prototype[_]>"u")throw Error(`Platform does not support Buffer.prototype.${_}.`)}w$.bigIntAndBufferInt64Check=IS});var h$=W((v$)=>{Object.defineProperty(v$,"__esModule",{value:!0});var t=S$(),y$=4096,hS="utf8";class FL{constructor(_){if(this.length=0,this._encoding=hS,this._writeOffset=0,this._readOffset=0,FL.isSmartBufferOptions(_)){if(_.encoding)t.checkEncoding(_.encoding),this._encoding=_.encoding;if(_.size)if(t.isFiniteInteger(_.size)&&_.size>0)this._buff=Buffer.allocUnsafe(_.size);else throw Error(t.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(_.buff)if(Buffer.isBuffer(_.buff))this._buff=_.buff,this.length=_.buff.length;else throw Error(t.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(y$)}else{if(typeof _<"u")throw Error(t.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(y$)}}static fromSize(_,T){return new this({size:_,encoding:T})}static fromBuffer(_,T){return new this({buff:_,encoding:T})}static fromOptions(_){return new this(_)}static isSmartBufferOptions(_){let T=_;return T&&(T.encoding!==void 0||T.size!==void 0||T.buff!==void 0)}readInt8(_){return this._readNumberValue(Buffer.prototype.readInt8,1,_)}readInt16BE(_){return this._readNumberValue(Buffer.prototype.readInt16BE,2,_)}readInt16LE(_){return this._readNumberValue(Buffer.prototype.readInt16LE,2,_)}readInt32BE(_){return this._readNumberValue(Buffer.prototype.readInt32BE,4,_)}readInt32LE(_){return this._readNumberValue(Buffer.prototype.readInt32LE,4,_)}readBigInt64BE(_){return t.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,_)}readBigInt64LE(_){return t.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,_)}writeInt8(_,T){return this._writeNumberValue(Buffer.prototype.writeInt8,1,_,T),this}insertInt8(_,T){return this._insertNumberValue(Buffer.prototype.writeInt8,1,_,T)}writeInt16BE(_,T){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,_,T)}insertInt16BE(_,T){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,_,T)}writeInt16LE(_,T){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,_,T)}insertInt16LE(_,T){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,_,T)}writeInt32BE(_,T){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,_,T)}insertInt32BE(_,T){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,_,T)}writeInt32LE(_,T){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,_,T)}insertInt32LE(_,T){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,_,T)}writeBigInt64BE(_,T){return t.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,_,T)}insertBigInt64BE(_,T){return t.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,_,T)}writeBigInt64LE(_,T){return t.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,_,T)}insertBigInt64LE(_,T){return t.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,_,T)}readUInt8(_){return this._readNumberValue(Buffer.prototype.readUInt8,1,_)}readUInt16BE(_){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,_)}readUInt16LE(_){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,_)}readUInt32BE(_){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,_)}readUInt32LE(_){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,_)}readBigUInt64BE(_){return t.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,_)}readBigUInt64LE(_){return t.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,_)}writeUInt8(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,_,T)}insertUInt8(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,_,T)}writeUInt16BE(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,_,T)}insertUInt16BE(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,_,T)}writeUInt16LE(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,_,T)}insertUInt16LE(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,_,T)}writeUInt32BE(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,_,T)}insertUInt32BE(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,_,T)}writeUInt32LE(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,_,T)}insertUInt32LE(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,_,T)}writeBigUInt64BE(_,T){return t.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,_,T)}insertBigUInt64BE(_,T){return t.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,_,T)}writeBigUInt64LE(_,T){return t.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,_,T)}insertBigUInt64LE(_,T){return t.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,_,T)}readFloatBE(_){return this._readNumberValue(Buffer.prototype.readFloatBE,4,_)}readFloatLE(_){return this._readNumberValue(Buffer.prototype.readFloatLE,4,_)}writeFloatBE(_,T){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,_,T)}insertFloatBE(_,T){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,_,T)}writeFloatLE(_,T){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,_,T)}insertFloatLE(_,T){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,_,T)}readDoubleBE(_){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,_)}readDoubleLE(_){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,_)}writeDoubleBE(_,T){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,_,T)}insertDoubleBE(_,T){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,_,T)}writeDoubleLE(_,T){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,_,T)}insertDoubleLE(_,T){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,_,T)}readString(_,T){let A;if(typeof _==="number")t.checkLengthValue(_),A=Math.min(_,this.length-this._readOffset);else T=_,A=this.length-this._readOffset;if(typeof T<"u")t.checkEncoding(T);let E=this._buff.slice(this._readOffset,this._readOffset+A).toString(T||this._encoding);return this._readOffset+=A,E}insertString(_,T,A){return t.checkOffsetValue(T),this._handleString(_,!0,T,A)}writeString(_,T,A){return this._handleString(_,!1,T,A)}readStringNT(_){if(typeof _<"u")t.checkEncoding(_);let T=this.length;for(let E=this._readOffset;E<this.length;E++)if(this._buff[E]===0){T=E;break}let A=this._buff.slice(this._readOffset,T);return this._readOffset=T+1,A.toString(_||this._encoding)}insertStringNT(_,T,A){return t.checkOffsetValue(T),this.insertString(_,T,A),this.insertUInt8(0,T+_.length),this}writeStringNT(_,T,A){return this.writeString(_,T,A),this.writeUInt8(0,typeof T==="number"?T+_.length:this.writeOffset),this}readBuffer(_){if(typeof _<"u")t.checkLengthValue(_);let T=typeof _==="number"?_:this.length,A=Math.min(this.length,this._readOffset+T),E=this._buff.slice(this._readOffset,A);return this._readOffset=A,E}insertBuffer(_,T){return t.checkOffsetValue(T),this._handleBuffer(_,!0,T)}writeBuffer(_,T){return this._handleBuffer(_,!1,T)}readBufferNT(){let _=this.length;for(let A=this._readOffset;A<this.length;A++)if(this._buff[A]===0){_=A;break}let T=this._buff.slice(this._readOffset,_);return this._readOffset=_+1,T}insertBufferNT(_,T){return t.checkOffsetValue(T),this.insertBuffer(_,T),this.insertUInt8(0,T+_.length),this}writeBufferNT(_,T){if(typeof T<"u")t.checkOffsetValue(T);return this.writeBuffer(_,T),this.writeUInt8(0,typeof T==="number"?T+_.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(_){t.checkOffsetValue(_),t.checkTargetOffset(_,this),this._readOffset=_}get writeOffset(){return this._writeOffset}set writeOffset(_){t.checkOffsetValue(_),t.checkTargetOffset(_,this),this._writeOffset=_}get encoding(){return this._encoding}set encoding(_){t.checkEncoding(_),this._encoding=_}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(_){let T=typeof _==="string"?_:this._encoding;return t.checkEncoding(T),this._buff.toString(T,0,this.length)}destroy(){return this.clear(),this}_handleString(_,T,A,E){let L=this._writeOffset,J=this._encoding;if(typeof A==="number")L=A;else if(typeof A==="string")t.checkEncoding(A),J=A;if(typeof E==="string")t.checkEncoding(E),J=E;let X=Buffer.byteLength(_,J);if(T)this.ensureInsertable(X,L);else this._ensureWriteable(X,L);if(this._buff.write(_,L,X,J),T)this._writeOffset+=X;else if(typeof A==="number")this._writeOffset=Math.max(this._writeOffset,L+X);else this._writeOffset+=X;return this}_handleBuffer(_,T,A){let E=typeof A==="number"?A:this._writeOffset;if(T)this.ensureInsertable(_.length,E);else this._ensureWriteable(_.length,E);if(_.copy(this._buff,E),T)this._writeOffset+=_.length;else if(typeof A==="number")this._writeOffset=Math.max(this._writeOffset,E+_.length);else this._writeOffset+=_.length;return this}ensureReadable(_,T){let A=this._readOffset;if(typeof T<"u")t.checkOffsetValue(T),A=T;if(A<0||A+_>this.length)throw Error(t.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(_,T){if(t.checkOffsetValue(T),this._ensureCapacity(this.length+_),T<this.length)this._buff.copy(this._buff,T+_,T,this._buff.length);if(T+_>this.length)this.length=T+_;else this.length+=_}_ensureWriteable(_,T){let A=typeof T==="number"?T:this._writeOffset;if(this._ensureCapacity(A+_),A+_>this.length)this.length=A+_}_ensureCapacity(_){let T=this._buff.length;if(_>T){let A=this._buff,E=T*3/2+1;if(E<_)E=_;this._buff=Buffer.allocUnsafe(E),A.copy(this._buff,0,0,T)}}_readNumberValue(_,T,A){this.ensureReadable(T,A);let E=_.call(this._buff,typeof A==="number"?A:this._readOffset);if(typeof A>"u")this._readOffset+=T;return E}_insertNumberValue(_,T,A,E){return t.checkOffsetValue(E),this.ensureInsertable(T,E),_.call(this._buff,A,E),this._writeOffset+=T,this}_writeNumberValue(_,T,A,E){if(typeof E==="number"){if(E<0)throw Error(t.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);t.checkOffsetValue(E)}let L=typeof E==="number"?E:this._writeOffset;if(this._ensureWriteable(T,L),_.call(this._buff,A,L),typeof E==="number")this._writeOffset=Math.max(this._writeOffset,L+T);else this._writeOffset+=T;return this}}v$.SmartBuffer=FL});var CL=W((d$)=>{Object.defineProperty(d$,"__esModule",{value:!0});d$.SOCKS5_NO_ACCEPTABLE_AUTH=d$.SOCKS5_CUSTOM_AUTH_END=d$.SOCKS5_CUSTOM_AUTH_START=d$.SOCKS_INCOMING_PACKET_SIZES=d$.SocksClientState=d$.Socks5Response=d$.Socks5HostType=d$.Socks5Auth=d$.Socks4Response=d$.SocksCommand=d$.ERRORS=d$.DEFAULT_TIMEOUT=void 0;var fS=30000;d$.DEFAULT_TIMEOUT=fS;var bS={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};d$.ERRORS=bS;var gS={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(_)=>_+7,Socks4Response:8};d$.SOCKS_INCOMING_PACKET_SIZES=gS;var k$;(function(_){_[_.connect=1]="connect",_[_.bind=2]="bind",_[_.associate=3]="associate"})(k$||(d$.SocksCommand=k$={}));var f$;(function(_){_[_.Granted=90]="Granted",_[_.Failed=91]="Failed",_[_.Rejected=92]="Rejected",_[_.RejectedIdent=93]="RejectedIdent"})(f$||(d$.Socks4Response=f$={}));var b$;(function(_){_[_.NoAuth=0]="NoAuth",_[_.GSSApi=1]="GSSApi",_[_.UserPass=2]="UserPass"})(b$||(d$.Socks5Auth=b$={}));var mS=128;d$.SOCKS5_CUSTOM_AUTH_START=mS;var uS=254;d$.SOCKS5_CUSTOM_AUTH_END=uS;var dS=255;d$.SOCKS5_NO_ACCEPTABLE_AUTH=dS;var g$;(function(_){_[_.Granted=0]="Granted",_[_.Failure=1]="Failure",_[_.NotAllowed=2]="NotAllowed",_[_.NetworkUnreachable=3]="NetworkUnreachable",_[_.HostUnreachable=4]="HostUnreachable",_[_.ConnectionRefused=5]="ConnectionRefused",_[_.TTLExpired=6]="TTLExpired",_[_.CommandNotSupported=7]="CommandNotSupported",_[_.AddressNotSupported=8]="AddressNotSupported"})(g$||(d$.Socks5Response=g$={}));var m$;(function(_){_[_.IPv4=1]="IPv4",_[_.Hostname=3]="Hostname",_[_.IPv6=4]="IPv6"})(m$||(d$.Socks5HostType=m$={}));var u$;(function(_){_[_.Created=0]="Created",_[_.Connecting=1]="Connecting",_[_.Connected=2]="Connected",_[_.SentInitialHandshake=3]="SentInitialHandshake",_[_.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",_[_.SentAuthentication=5]="SentAuthentication",_[_.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",_[_.SentFinalHandshake=7]="SentFinalHandshake",_[_.ReceivedFinalResponse=8]="ReceivedFinalResponse",_[_.BoundWaitingForConnection=9]="BoundWaitingForConnection",_[_.Established=10]="Established",_[_.Disconnected=11]="Disconnected",_[_.Error=99]="Error"})(u$||(d$.SocksClientState=u$={}))});var OL=W((l$)=>{Object.defineProperty(l$,"__esModule",{value:!0});l$.shuffleArray=l$.SocksClientError=void 0;class p$ extends Error{constructor(_,T){super(_);this.options=T}}l$.SocksClientError=p$;function _y(_){for(let T=_.length-1;T>0;T--){let A=Math.floor(Math.random()*(T+1));[_[T],_[A]]=[_[A],_[T]]}}l$.shuffleArray=_y});var _5=W((a$)=>{Object.defineProperty(a$,"__esModule",{value:!0});a$.isInSubnet=Ay;a$.isCorrect=Ey;a$.numberToPaddedHex=i$;a$.stringToPaddedHex=Ly;a$.testBit=Jy;function Ay(_){if(this.subnetMask<_.subnetMask)return!1;if(this.mask(_.subnetMask)===_.mask())return!0;return!1}function Ey(_){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===_&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function i$(_){return _.toString(16).padStart(2,"0")}function Ly(_){return i$(parseInt(_,10))}function Jy(_,T){let{length:A}=_;if(T>A)return!1;let E=A-T;return _.substring(E,E+1)==="1"}});var RL=W((o$)=>{Object.defineProperty(o$,"__esModule",{value:!0});o$.RE_SUBNET_STRING=o$.RE_ADDRESS=o$.GROUPS=o$.BITS=void 0;o$.BITS=32;o$.GROUPS=4;o$.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;o$.RE_SUBNET_STRING=/\/\d{1,2}$/});var T5=W((t$)=>{Object.defineProperty(t$,"__esModule",{value:!0});t$.AddressError=void 0;class s$ extends Error{constructor(_,T){super(_);this.name="AddressError",this.parseMessage=T}}t$.AddressError=s$});var DL=W((N0)=>{var Wy=N0&&N0.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),Ny=N0&&N0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),_U=N0&&N0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))Wy(T,_,A)}return Ny(T,_),T};Object.defineProperty(N0,"__esModule",{value:!0});N0.Address4=void 0;var $4=_U(_5()),n1=_U(RL()),q8=T5();class $1{constructor(_){this.groups=n1.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=$4.isCorrect(n1.BITS),this.isInSubnet=$4.isInSubnet,this.address=_;let T=n1.RE_SUBNET_STRING.exec(_);if(T){if(this.parsedSubnet=T[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>n1.BITS)throw new q8.AddressError("Invalid subnet mask.");_=_.replace(n1.RE_SUBNET_STRING,"")}this.addressMinusSuffix=_,this.parsedAddress=this.parse(_)}static isValid(_){try{return new $1(_),!0}catch(T){return!1}}parse(_){let T=_.split(".");if(!_.match(n1.RE_ADDRESS))throw new q8.AddressError("Invalid IPv4 address.");return T}correctForm(){return this.parsedAddress.map((_)=>parseInt(_,10)).join(".")}static fromHex(_){let T=_.replace(/:/g,"").padStart(8,"0"),A=[],E;for(E=0;E<8;E+=2){let L=T.slice(E,E+2);A.push(parseInt(L,16))}return new $1(A.join("."))}static fromInteger(_){return $1.fromHex(_.toString(16))}static fromArpa(_){let A=_.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new $1(A)}toHex(){return this.parsedAddress.map((_)=>$4.stringToPaddedHex(_)).join(":")}toArray(){return this.parsedAddress.map((_)=>parseInt(_,10))}toGroup6(){let _=[],T;for(T=0;T<n1.GROUPS;T+=2)_.push(`${$4.stringToPaddedHex(this.parsedAddress[T])}${$4.stringToPaddedHex(this.parsedAddress[T+1])}`);return _.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map((_)=>$4.stringToPaddedHex(_)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(n1.BITS-this.subnetMask)}`)}startAddress(){return $1.fromBigInt(this._startAddress())}startAddressExclusive(){let _=BigInt("1");return $1.fromBigInt(this._startAddress()+_)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(n1.BITS-this.subnetMask)}`)}endAddress(){return $1.fromBigInt(this._endAddress())}endAddressExclusive(){let _=BigInt("1");return $1.fromBigInt(this._endAddress()-_)}static fromBigInt(_){return $1.fromHex(_.toString(16))}static fromByteArray(_){if(_.length!==4)throw new q8.AddressError("IPv4 addresses require exactly 4 bytes");for(let T=0;T<_.length;T++)if(!Number.isInteger(_[T])||_[T]<0||_[T]>255)throw new q8.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(_)}static fromUnsignedByteArray(_){if(_.length!==4)throw new q8.AddressError("IPv4 addresses require exactly 4 bytes");let T=_.join(".");return new $1(T)}mask(_){if(_===void 0)_=this.subnetMask;return this.getBitsBase2(0,_)}getBitsBase2(_,T){return this.binaryZeroPad().slice(_,T)}reverseForm(_){if(!_)_={};let T=this.correctForm().split(".").reverse().join(".");if(_.omitSuffix)return T;return`${T}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new $1("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(n1.BITS,"0")}groupForV6(){let _=this.parsedAddress;return this.address.replace(n1.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${_.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${_.slice(2,4).join(".")}</span>`)}}N0.Address4=$1});var BL=W((TU)=>{Object.defineProperty(TU,"__esModule",{value:!0});TU.RE_URL_WITH_PORT=TU.RE_URL=TU.RE_ZONE_STRING=TU.RE_SUBNET_STRING=TU.RE_BAD_ADDRESS=TU.RE_BAD_CHARACTERS=TU.TYPES=TU.SCOPES=TU.GROUPS=TU.BITS=void 0;TU.BITS=128;TU.GROUPS=8;TU.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};TU.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"};TU.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;TU.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;TU.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;TU.RE_ZONE_STRING=/%.*$/;TU.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;TU.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var qL=W((JU)=>{Object.defineProperty(JU,"__esModule",{value:!0});JU.spanAllZeroes=EU;JU.spanAll=By;JU.spanLeadingZeroes=qy;JU.simpleGroup=Iy;function EU(_){return _.replace(/(0+)/g,'<span class="zero">$1</span>')}function By(_,T=0){return _.split("").map((E,L)=>`<span class="digit value-${E} position-${L+T}">${EU(E)}</span>`).join("")}function LU(_){return _.replace(/^(0+)/,'<span class="zero">$1</span>')}function qy(_){return _.split(":").map((A)=>LU(A)).join(":")}function Iy(_,T=0){return _.split(":").map((E,L)=>{if(/group-v4/.test(E))return E;return`<span class="hover-group group-${L+T}">${LU(E)}</span>`})}});var XU=W((Y1)=>{var Sy=Y1&&Y1.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),yy=Y1&&Y1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),vy=Y1&&Y1.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))Sy(T,_,A)}return yy(T,_),T};Object.defineProperty(Y1,"__esModule",{value:!0});Y1.ADDRESS_BOUNDARY=void 0;Y1.groupPossibilities=E5;Y1.padGroup=A5;Y1.simpleRegularExpression=ky;Y1.possibleElisions=fy;var hy=vy(BL());function E5(_){return`(${_.join("|")})`}function A5(_){if(_.length<4)return`0{0,${4-_.length}}${_}`;return _}Y1.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function ky(_){let T=[];_.forEach((E,L)=>{if(parseInt(E,16)===0)T.push(L)});let A=T.map((E)=>_.map((L,J)=>{if(J===E){let X=J===0||J===hy.GROUPS-1?":":"";return E5([A5(L),X])}return A5(L)}).join(":"));return A.push(_.map(A5).join(":")),E5(A)}function fy(_,T,A){let E=T?"":":",L=A?"":":",J=[];if(!T&&!A)J.push("::");if(T&&A)J.push("");if(A&&!T||!A&&T)J.push(":");J.push(`${E}(:0{1,4}){1,${_-1}}`),J.push(`(0{1,4}:){1,${_-1}}${L}`),J.push(`(0{1,4}:){${_-1}}0{1,4}`);for(let X=1;X<_-1;X++)for(let H=1;H<_-X;H++)J.push(`(0{1,4}:){${H}}:(0{1,4}:){${_-H-X-1}}0{1,4}`);return E5(J)}});var KU=W((Q0)=>{var by=Q0&&Q0.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),gy=Q0&&Q0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),X5=Q0&&Q0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))by(T,_,A)}return gy(T,_),T};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.Address6=void 0;var HU=X5(_5()),IL=X5(RL()),N_=X5(BL()),PL=X5(qL()),yT=DL(),vT=XU(),f0=T5(),L5=_5();function J5(_){if(!_)throw Error("Assertion failed.")}function my(_){let T=/(\d+)(\d{3})/;while(T.test(_))_=_.replace(T,"$1,$2");return _}function uy(_){return _=_.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),_=_.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),_}function dy(_,T){let A=[],E=[],L;for(L=0;L<_.length;L++)if(L<T[0])A.push(_[L]);else if(L>T[1])E.push(_[L]);return A.concat(["compact"]).concat(E)}function ZU(_){return parseInt(_,16).toString(16).padStart(4,"0")}function YU(_){return _&255}class k_{constructor(_,T){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=HU.isInSubnet,this.isCorrect=HU.isCorrect(N_.BITS),T===void 0)this.groups=N_.GROUPS;else this.groups=T;this.address=_;let A=N_.RE_SUBNET_STRING.exec(_);if(A){if(this.parsedSubnet=A[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>N_.BITS)throw new f0.AddressError("Invalid subnet mask.");_=_.replace(N_.RE_SUBNET_STRING,"")}else if(/\//.test(_))throw new f0.AddressError("Invalid subnet mask.");let E=N_.RE_ZONE_STRING.exec(_);if(E)this.zone=E[0],_=_.replace(N_.RE_ZONE_STRING,"");this.addressMinusSuffix=_,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(_){try{return new k_(_),!0}catch(T){return!1}}static fromBigInt(_){let T=_.toString(16).padStart(32,"0"),A=[],E;for(E=0;E<N_.GROUPS;E++)A.push(T.slice(E*4,(E+1)*4));return new k_(A.join(":"))}static fromURL(_){let T,A=null,E;if(_.indexOf("[")!==-1&&_.indexOf("]:")!==-1){if(E=N_.RE_URL_WITH_PORT.exec(_),E===null)return{error:"failed to parse address with port",address:null,port:null};T=E[1],A=E[2]}else if(_.indexOf("/")!==-1){if(_=_.replace(/^[a-z0-9]+:\/\//,""),E=N_.RE_URL.exec(_),E===null)return{error:"failed to parse address from URL",address:null,port:null};T=E[1]}else T=_;if(A){if(A=parseInt(A,10),A<0||A>65536)A=null}else A=null;return{address:new k_(T),port:A}}static fromAddress4(_){let T=new yT.Address4(_),A=N_.BITS-(IL.BITS-T.subnetMask);return new k_(`::ffff:${T.correctForm()}/${A}`)}static fromArpa(_){let T=_.replace(/(\.ip6\.arpa)?\.$/,""),A=7;if(T.length!==63)throw new f0.AddressError("Invalid 'ip6.arpa' form.");let E=T.split(".").reverse();for(let L=A;L>0;L--){let J=L*4;E.splice(J,0,":")}return T=E.join(""),new k_(T)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(_=this.subnetMask){return this.getBitsBase2(0,_)}possibleSubnets(_=128){let T=N_.BITS-this.subnetMask,A=Math.abs(_-N_.BITS),E=T-A;if(E<0)return"0";return my((BigInt("2")**BigInt(E)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(N_.BITS-this.subnetMask)}`)}startAddress(){return k_.fromBigInt(this._startAddress())}startAddressExclusive(){let _=BigInt("1");return k_.fromBigInt(this._startAddress()+_)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(N_.BITS-this.subnetMask)}`)}endAddress(){return k_.fromBigInt(this._endAddress())}endAddressExclusive(){let _=BigInt("1");return k_.fromBigInt(this._endAddress()-_)}getScope(){let _=N_.SCOPES[parseInt(this.getBits(12,16).toString(10),10)];if(this.getType()==="Global unicast"&&_!=="Link local")_="Global";return _||"Unknown"}getType(){for(let _ of Object.keys(N_.TYPES))if(this.isInSubnet(new k_(_)))return N_.TYPES[_];return"Global unicast"}getBits(_,T){return BigInt(`0b${this.getBitsBase2(_,T)}`)}getBitsBase2(_,T){return this.binaryZeroPad().slice(_,T)}getBitsBase16(_,T){let A=T-_;if(A%4!==0)throw Error("Length of bits to retrieve must be divisible by four");return this.getBits(_,T).toString(16).padStart(A/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,N_.BITS)}reverseForm(_){if(!_)_={};let T=Math.floor(this.subnetMask/4),A=this.canonicalForm().replace(/:/g,"").split("").slice(0,T).reverse().join(".");if(T>0){if(_.omitSuffix)return A;return`${A}.ip6.arpa.`}if(_.omitSuffix)return"";return"ip6.arpa."}correctForm(){let _,T=[],A=0,E=[];for(_=0;_<this.parsedAddress.length;_++){let X=parseInt(this.parsedAddress[_],16);if(X===0)A++;if(X!==0&&A>0){if(A>1)E.push([_-A,_-1]);A=0}}if(A>1)E.push([this.parsedAddress.length-A,this.parsedAddress.length-1]);let L=E.map((X)=>X[1]-X[0]+1);if(E.length>0){let X=L.indexOf(Math.max(...L));T=dy(this.parsedAddress,E[X])}else T=this.parsedAddress;for(_=0;_<T.length;_++)if(T[_]!=="compact")T[_]=parseInt(T[_],16).toString(16);let J=T.join(":");return J=J.replace(/^compact$/,"::"),J=J.replace(/(^compact)|(compact$)/,":"),J=J.replace(/compact/,""),J}binaryZeroPad(){return this.bigInt().toString(2).padStart(N_.BITS,"0")}parse4in6(_){let T=_.split(":"),E=T.slice(-1)[0].match(IL.RE_ADDRESS);if(E){this.parsedAddress4=E[0],this.address4=new yT.Address4(this.parsedAddress4);for(let L=0;L<this.address4.groups;L++)if(/^0[0-9]+/.test(this.address4.parsedAddress[L]))throw new f0.AddressError("IPv4 addresses can't have leading zeroes.",_.replace(IL.RE_ADDRESS,this.address4.parsedAddress.map(uy).join(".")));this.v4=!0,T[T.length-1]=this.address4.toGroup6(),_=T.join(":")}return _}parse(_){_=this.parse4in6(_);let T=_.match(N_.RE_BAD_CHARACTERS);if(T)throw new f0.AddressError(`Bad character${T.length>1?"s":""} detected in address: ${T.join("")}`,_.replace(N_.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let A=_.match(N_.RE_BAD_ADDRESS);if(A)throw new f0.AddressError(`Address failed regex: ${A.join("")}`,_.replace(N_.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let E=[],L=_.split("::");if(L.length===2){let J=L[0].split(":"),X=L[1].split(":");if(J.length===1&&J[0]==="")J=[];if(X.length===1&&X[0]==="")X=[];let H=this.groups-(J.length+X.length);if(!H)throw new f0.AddressError("Error parsing groups");this.elidedGroups=H,this.elisionBegin=J.length,this.elisionEnd=J.length+this.elidedGroups,E=E.concat(J);for(let Z=0;Z<H;Z++)E.push("0");E=E.concat(X)}else if(L.length===1)E=_.split(":"),this.elidedGroups=0;else throw new f0.AddressError("Too many :: groups found");if(E=E.map((J)=>parseInt(J,16).toString(16)),E.length!==this.groups)throw new f0.AddressError("Incorrect number of groups found");return E}canonicalForm(){return this.parsedAddress.map(ZU).join(":")}decimal(){return this.parsedAddress.map((_)=>parseInt(_,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(ZU).join("")}`)}to4(){let _=this.binaryZeroPad().split("");return yT.Address4.fromHex(BigInt(`0b${_.slice(96,128).join("")}`).toString(16))}to4in6(){let _=this.to4(),A=new k_(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),E="";if(!/:$/.test(A))E=":";return A+E+_.address}inspectTeredo(){let _=this.getBitsBase16(0,32),A=(this.getBits(80,96)^BigInt("0xffff")).toString(),E=yT.Address4.fromHex(this.getBitsBase16(32,64)),L=this.getBits(96,128),J=yT.Address4.fromHex((L^BigInt("0xffffffff")).toString(16)),X=this.getBitsBase2(64,80),H=(0,L5.testBit)(X,15),Z=(0,L5.testBit)(X,14),Y=(0,L5.testBit)(X,8),K=(0,L5.testBit)(X,9),G=BigInt(`0b${X.slice(2,6)+X.slice(8,16)}`).toString(10);return{prefix:`${_.slice(0,4)}:${_.slice(4,8)}`,server4:E.address,client4:J.address,flags:X,coneNat:H,microsoft:{reserved:Z,universalLocal:K,groupIndividual:Y,nonce:G},udpPort:A}}inspect6to4(){let _=this.getBitsBase16(0,16),T=yT.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:_.slice(0,4),gateway:T.address}}to6to4(){if(!this.is4())return null;let _=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new k_(_)}toByteArray(){let _=this.bigInt().toString(16),A=`${"0".repeat(_.length%2)}${_}`,E=[];for(let L=0,J=A.length;L<J;L+=2)E.push(parseInt(A.substring(L,L+2),16));return E}toUnsignedByteArray(){return this.toByteArray().map(YU)}static fromByteArray(_){return this.fromUnsignedByteArray(_.map(YU))}static fromUnsignedByteArray(_){let T=BigInt("256"),A=BigInt("0"),E=BigInt("1");for(let L=_.length-1;L>=0;L--)A+=E*BigInt(_[L].toString(10)),E*=T;return k_.fromBigInt(A)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){if(this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000")return!0;return!1}isMulticast(){return this.getType()==="Multicast"}is4(){return this.v4}isTeredo(){return this.isInSubnet(new k_("2001::/32"))}is6to4(){return this.isInSubnet(new k_("2002::/16"))}isLoopback(){return this.getType()==="Loopback"}href(_){if(_===void 0)_="";else _=`:${_}`;return`http://[${this.correctForm()}]${_}/`}link(_){if(!_)_={};if(_.className===void 0)_.className="";if(_.prefix===void 0)_.prefix="/#address=";if(_.v4===void 0)_.v4=!1;let T=this.correctForm;if(_.v4)T=this.to4in6;let A=T.call(this);if(_.className)return`<a href="${_.prefix}${A}" class="${_.className}">${A}</a>`;return`<a href="${_.prefix}${A}">${A}</a>`}group(){if(this.elidedGroups===0)return PL.simpleGroup(this.address).join(":");J5(typeof this.elidedGroups==="number"),J5(typeof this.elisionBegin==="number");let _=[],[T,A]=this.address.split("::");if(T.length)_.push(...PL.simpleGroup(T));else _.push("");let E=["hover-group"];for(let L=this.elisionBegin;L<this.elisionBegin+this.elidedGroups;L++)E.push(`group-${L}`);if(_.push(`<span class="${E.join(" ")}"></span>`),A.length)_.push(...PL.simpleGroup(A,this.elisionEnd));else _.push("");if(this.is4())J5(this.address4 instanceof yT.Address4),_.pop(),_.push(this.address4.groupForV6());return _.join(":")}regularExpressionString(_=!1){let T=[],A=new k_(this.correctForm());if(A.elidedGroups===0)T.push((0,vT.simpleRegularExpression)(A.parsedAddress));else if(A.elidedGroups===N_.GROUPS)T.push((0,vT.possibleElisions)(N_.GROUPS));else{let E=A.address.split("::");if(E[0].length)T.push((0,vT.simpleRegularExpression)(E[0].split(":")));if(J5(typeof A.elidedGroups==="number"),T.push((0,vT.possibleElisions)(A.elidedGroups,E[0].length!==0,E[1].length!==0)),E[1].length)T.push((0,vT.simpleRegularExpression)(E[1].split(":")));T=[T.join(":")]}if(!_)T=["(?=^|",vT.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...T,")(?=[^\\w\\:]|",vT.ADDRESS_BOUNDARY,"|$)"];return T.join("")}regularExpression(_=!1){return new RegExp(this.regularExpressionString(_),"i")}}Q0.Address6=k_});var jL=W((a_)=>{var cy=a_&&a_.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),py=a_&&a_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),ly=a_&&a_.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))cy(T,_,A)}return py(T,_),T};Object.defineProperty(a_,"__esModule",{value:!0});a_.v6=a_.AddressError=a_.Address6=a_.Address4=void 0;var ny=DL();Object.defineProperty(a_,"Address4",{enumerable:!0,get:function(){return ny.Address4}});var iy=KU();Object.defineProperty(a_,"Address6",{enumerable:!0,get:function(){return iy.Address6}});var ay=T5();Object.defineProperty(a_,"AddressError",{enumerable:!0,get:function(){return ay.AddressError}});var oy=ly(qL());a_.v6={helpers:oy}});var VU=W((QU)=>{Object.defineProperty(QU,"__esModule",{value:!0});QU.ipToBuffer=QU.int32ToIpv4=QU.ipv4ToInt32=QU.validateSocksClientChainOptions=QU.validateSocksClientOptions=void 0;var _1=OL(),f_=CL(),ry=j("stream"),xL=jL(),GU=j("net");function sy(_,T=["connect","bind","associate"]){if(!f_.SocksCommand[_.command])throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommand,_);if(T.indexOf(_.command)===-1)throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommandForOperation,_);if(!UU(_.destination))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsDestination,_);if(!WU(_.proxy))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);if($U(_.proxy,_),_.timeout&&!NU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_);if(_.existing_socket&&!(_.existing_socket instanceof ry.Duplex))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsExistingSocket,_)}QU.validateSocksClientOptions=sy;function ty(_){if(_.command!=="connect")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommandChain,_);if(!UU(_.destination))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsDestination,_);if(!(_.proxies&&Array.isArray(_.proxies)&&_.proxies.length>=2))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxiesLength,_);if(_.proxies.forEach((T)=>{if(!WU(T))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);$U(T,_)}),_.timeout&&!NU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_)}QU.validateSocksClientChainOptions=ty;function $U(_,T){if(_.custom_auth_method!==void 0){if(_.custom_auth_method<f_.SOCKS5_CUSTOM_AUTH_START||_.custom_auth_method>f_.SOCKS5_CUSTOM_AUTH_END)throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsCustomAuthRange,T);if(_.custom_auth_request_handler===void 0||typeof _.custom_auth_request_handler!=="function")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,T);if(_.custom_auth_response_size===void 0)throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,T);if(_.custom_auth_response_handler===void 0||typeof _.custom_auth_response_handler!=="function")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,T)}}function UU(_){return _&&typeof _.host==="string"&&Buffer.byteLength(_.host)<256&&typeof _.port==="number"&&_.port>=0&&_.port<=65535}function WU(_){return _&&(typeof _.host==="string"||typeof _.ipaddress==="string")&&typeof _.port==="number"&&_.port>=0&&_.port<=65535&&(_.type===4||_.type===5)}function NU(_){return typeof _==="number"&&_>0}function ey(_){return new xL.Address4(_).toArray().reduce((A,E)=>(A<<8)+E,0)>>>0}QU.ipv4ToInt32=ey;function _v(_){let T=_>>>24&255,A=_>>>16&255,E=_>>>8&255,L=_&255;return[T,A,E,L].join(".")}QU.int32ToIpv4=_v;function Tv(_){if(GU.isIPv4(_)){let T=new xL.Address4(_);return Buffer.from(T.toArray())}else if(GU.isIPv6(_)){let T=new xL.Address6(_);return Buffer.from(T.canonicalForm().split(":").map((A)=>A.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}QU.ipToBuffer=Tv});var OU=W((FU)=>{Object.defineProperty(FU,"__esModule",{value:!0});FU.ReceiveBuffer=void 0;class zU{constructor(_=4096){this.buffer=Buffer.allocUnsafe(_),this.offset=0,this.originalSize=_}get length(){return this.offset}append(_){if(!Buffer.isBuffer(_))throw Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+_.length>=this.buffer.length){let T=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+_.length)),T.copy(this.buffer)}return _.copy(this.buffer,this.offset),this.offset+=_.length}peek(_){if(_>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,_)}get(_){if(_>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");let T=Buffer.allocUnsafe(_);return this.buffer.slice(0,_).copy(T),this.buffer.copyWithin(0,_,_+this.offset-_),this.offset-=_,T}}FU.ReceiveBuffer=zU});var RU=W((TT)=>{var U4=TT&&TT.__awaiter||function(_,T,A,E){function L(J){return J instanceof A?J:new A(function(X){X(J)})}return new(A||(A=Promise))(function(J,X){function H(K){try{Y(E.next(K))}catch(G){X(G)}}function Z(K){try{Y(E.throw(K))}catch(G){X(G)}}function Y(K){K.done?J(K.value):L(K.value).then(H,Z)}Y((E=E.apply(_,T||[])).next())})};Object.defineProperty(TT,"__esModule",{value:!0});TT.SocksClientError=TT.SocksClient=void 0;var Xv=j("events"),W4=j("net"),K1=h$(),I=CL(),U1=VU(),Hv=OU(),SL=OL();Object.defineProperty(TT,"SocksClientError",{enumerable:!0,get:function(){return SL.SocksClientError}});var wL=jL();class H5 extends Xv.EventEmitter{constructor(_){super();this.options=Object.assign({},_),(0,U1.validateSocksClientOptions)(_),this.setState(I.SocksClientState.Created)}static createConnection(_,T){return new Promise((A,E)=>{try{(0,U1.validateSocksClientOptions)(_,["connect"])}catch(J){if(typeof T==="function")return T(J),A(J);else return E(J)}let L=new H5(_);L.connect(_.existing_socket),L.once("established",(J)=>{if(L.removeAllListeners(),typeof T==="function")T(null,J),A(J);else A(J)}),L.once("error",(J)=>{if(L.removeAllListeners(),typeof T==="function")T(J),A(J);else E(J)})})}static createConnectionChain(_,T){return new Promise((A,E)=>U4(this,void 0,void 0,function*(){try{(0,U1.validateSocksClientChainOptions)(_)}catch(L){if(typeof T==="function")return T(L),A(L);else return E(L)}if(_.randomizeChain)(0,SL.shuffleArray)(_.proxies);try{let L;for(let J=0;J<_.proxies.length;J++){let X=_.proxies[J],H=J===_.proxies.length-1?_.destination:{host:_.proxies[J+1].host||_.proxies[J+1].ipaddress,port:_.proxies[J+1].port},Z=yield H5.createConnection({command:"connect",proxy:X,destination:H,existing_socket:L});L=L||Z.socket}if(typeof T==="function")T(null,{socket:L}),A({socket:L});else A({socket:L})}catch(L){if(typeof T==="function")T(L),A(L);else E(L)}}))}static createUDPFrame(_){let T=new K1.SmartBuffer;if(T.writeUInt16BE(0),T.writeUInt8(_.frameNumber||0),W4.isIPv4(_.remoteHost.host))T.writeUInt8(I.Socks5HostType.IPv4),T.writeUInt32BE((0,U1.ipv4ToInt32)(_.remoteHost.host));else if(W4.isIPv6(_.remoteHost.host))T.writeUInt8(I.Socks5HostType.IPv6),T.writeBuffer((0,U1.ipToBuffer)(_.remoteHost.host));else T.writeUInt8(I.Socks5HostType.Hostname),T.writeUInt8(Buffer.byteLength(_.remoteHost.host)),T.writeString(_.remoteHost.host);return T.writeUInt16BE(_.remoteHost.port),T.writeBuffer(_.data),T.toBuffer()}static parseUDPFrame(_){let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A=T.readUInt8(),E=T.readUInt8(),L;if(E===I.Socks5HostType.IPv4)L=(0,U1.int32ToIpv4)(T.readUInt32BE());else if(E===I.Socks5HostType.IPv6)L=wL.Address6.fromByteArray(Array.from(T.readBuffer(16))).canonicalForm();else L=T.readString(T.readUInt8());let J=T.readUInt16BE();return{frameNumber:A,remoteHost:{host:L,port:J},data:T.readBuffer()}}setState(_){if(this.state!==I.SocksClientState.Error)this.state=_}connect(_){this.onDataReceived=(A)=>this.onDataReceivedHandler(A),this.onClose=()=>this.onCloseHandler(),this.onError=(A)=>this.onErrorHandler(A),this.onConnect=()=>this.onConnectHandler();let T=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||I.DEFAULT_TIMEOUT);if(T.unref&&typeof T.unref==="function")T.unref();if(_)this.socket=_;else this.socket=new W4.Socket;if(this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(I.SocksClientState.Connecting),this.receiveBuffer=new Hv.ReceiveBuffer,_)this.socket.emit("connect");else if(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null)this.socket.setNoDelay(!!this.options.set_tcp_nodelay);this.prependOnceListener("established",(A)=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let E=this.receiveBuffer.get(this.receiveBuffer.length);A.socket.emit("data",E)}A.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){if(this.state!==I.SocksClientState.Established&&this.state!==I.SocksClientState.BoundWaitingForConnection)this.closeSocket(I.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){if(this.setState(I.SocksClientState.Connected),this.options.proxy.type===4)this.sendSocks4InitialHandshake();else this.sendSocks5InitialHandshake();this.setState(I.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(_){this.receiveBuffer.append(_),this.processData()}processData(){while(this.state!==I.SocksClientState.Established&&this.state!==I.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize)if(this.state===I.SocksClientState.SentInitialHandshake)if(this.options.proxy.type===4)this.handleSocks4FinalHandshakeResponse();else this.handleInitialSocks5HandshakeResponse();else if(this.state===I.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===I.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===I.SocksClientState.BoundWaitingForConnection)if(this.options.proxy.type===4)this.handleSocks4IncomingConnectionResponse();else this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(I.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(I.ERRORS.SocketClosed)}onErrorHandler(_){this.closeSocket(_.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(_){if(this.state!==I.SocksClientState.Error)this.setState(I.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new SL.SocksClientError(_,this.options))}sendSocks4InitialHandshake(){let _=this.options.proxy.userId||"",T=new K1.SmartBuffer;if(T.writeUInt8(4),T.writeUInt8(I.SocksCommand[this.options.command]),T.writeUInt16BE(this.options.destination.port),W4.isIPv4(this.options.destination.host))T.writeBuffer((0,U1.ipToBuffer)(this.options.destination.host)),T.writeStringNT(_);else T.writeUInt8(0),T.writeUInt8(0),T.writeUInt8(0),T.writeUInt8(1),T.writeStringNT(_),T.writeStringNT(this.options.destination.host);this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(T.toBuffer())}handleSocks4FinalHandshakeResponse(){let _=this.receiveBuffer.get(8);if(_[1]!==I.Socks4Response.Granted)this.closeSocket(`${I.ERRORS.Socks4ProxyRejectedConnection} - (${I.Socks4Response[_[1]]})`);else if(I.SocksCommand[this.options.command]===I.SocksCommand.bind){let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A={port:T.readUInt16BE(),host:(0,U1.int32ToIpv4)(T.readUInt32BE())};if(A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress;this.setState(I.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:A,socket:this.socket})}else this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let _=this.receiveBuffer.get(8);if(_[1]!==I.Socks4Response.Granted)this.closeSocket(`${I.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${I.Socks4Response[_[1]]})`);else{let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A={port:T.readUInt16BE(),host:(0,U1.int32ToIpv4)(T.readUInt32BE())};this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}sendSocks5InitialHandshake(){let _=new K1.SmartBuffer,T=[I.Socks5Auth.NoAuth];if(this.options.proxy.userId||this.options.proxy.password)T.push(I.Socks5Auth.UserPass);if(this.options.proxy.custom_auth_method!==void 0)T.push(this.options.proxy.custom_auth_method);_.writeUInt8(5),_.writeUInt8(T.length);for(let A of T)_.writeUInt8(A);this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(_.toBuffer()),this.setState(I.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let _=this.receiveBuffer.get(2);if(_[0]!==5)this.closeSocket(I.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);else if(_[1]===I.SOCKS5_NO_ACCEPTABLE_AUTH)this.closeSocket(I.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);else if(_[1]===I.Socks5Auth.NoAuth)this.socks5ChosenAuthType=I.Socks5Auth.NoAuth,this.sendSocks5CommandRequest();else if(_[1]===I.Socks5Auth.UserPass)this.socks5ChosenAuthType=I.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication();else if(_[1]===this.options.proxy.custom_auth_method)this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication();else this.closeSocket(I.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let _=this.options.proxy.userId||"",T=this.options.proxy.password||"",A=new K1.SmartBuffer;A.writeUInt8(1),A.writeUInt8(Buffer.byteLength(_)),A.writeString(_),A.writeUInt8(Buffer.byteLength(T)),A.writeString(T),this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(A.toBuffer()),this.setState(I.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return U4(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(I.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(_)})}handleSocks5AuthenticationNoAuthHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return _[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return _[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return U4(this,void 0,void 0,function*(){this.setState(I.SocksClientState.ReceivedAuthenticationResponse);let _=!1;if(this.socks5ChosenAuthType===I.Socks5Auth.NoAuth)_=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===I.Socks5Auth.UserPass)_=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===this.options.proxy.custom_auth_method)_=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));if(!_)this.closeSocket(I.ERRORS.Socks5AuthenticationFailed);else this.sendSocks5CommandRequest()})}sendSocks5CommandRequest(){let _=new K1.SmartBuffer;if(_.writeUInt8(5),_.writeUInt8(I.SocksCommand[this.options.command]),_.writeUInt8(0),W4.isIPv4(this.options.destination.host))_.writeUInt8(I.Socks5HostType.IPv4),_.writeBuffer((0,U1.ipToBuffer)(this.options.destination.host));else if(W4.isIPv6(this.options.destination.host))_.writeUInt8(I.Socks5HostType.IPv6),_.writeBuffer((0,U1.ipToBuffer)(this.options.destination.host));else _.writeUInt8(I.Socks5HostType.Hostname),_.writeUInt8(this.options.destination.host.length),_.writeString(this.options.destination.host);_.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(_.toBuffer()),this.setState(I.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let _=this.receiveBuffer.peek(5);if(_[0]!==5||_[1]!==I.Socks5Response.Granted)this.closeSocket(`${I.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${I.Socks5Response[_[1]]}`);else{let T=_[3],A,E;if(T===I.Socks5HostType.IPv4){let L=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}if(E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:(0,U1.int32ToIpv4)(E.readUInt32BE()),port:E.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if(T===I.Socks5HostType.Hostname){let L=_[4],J=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(L);if(this.receiveBuffer.length<J){this.nextRequiredPacketBufferSize=J;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(J).slice(5)),A={host:E.readString(L),port:E.readUInt16BE()}}else if(T===I.Socks5HostType.IPv6){let L=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:wL.Address6.fromByteArray(Array.from(E.readBuffer(16))).canonicalForm(),port:E.readUInt16BE()}}if(this.setState(I.SocksClientState.ReceivedFinalResponse),I.SocksCommand[this.options.command]===I.SocksCommand.connect)this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket});else if(I.SocksCommand[this.options.command]===I.SocksCommand.bind)this.setState(I.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:A,socket:this.socket});else if(I.SocksCommand[this.options.command]===I.SocksCommand.associate)this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}handleSocks5IncomingConnectionResponse(){let _=this.receiveBuffer.peek(5);if(_[0]!==5||_[1]!==I.Socks5Response.Granted)this.closeSocket(`${I.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${I.Socks5Response[_[1]]}`);else{let T=_[3],A,E;if(T===I.Socks5HostType.IPv4){let L=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}if(E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:(0,U1.int32ToIpv4)(E.readUInt32BE()),port:E.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if(T===I.Socks5HostType.Hostname){let L=_[4],J=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(L);if(this.receiveBuffer.length<J){this.nextRequiredPacketBufferSize=J;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(J).slice(5)),A={host:E.readString(L),port:E.readUInt16BE()}}else if(T===I.Socks5HostType.IPv6){let L=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:wL.Address6.fromByteArray(Array.from(E.readBuffer(16))).canonicalForm(),port:E.readUInt16BE()}}this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}TT.SocksClient=H5});var DU=W((hT)=>{var Zv=hT&&hT.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),Yv=hT&&hT.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))Zv(T,_,A)};Object.defineProperty(hT,"__esModule",{value:!0});Yv(RU(),hT)});var vL=W((i1)=>{var Kv=i1&&i1.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),Gv=i1&&i1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),$v=i1&&i1.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")Kv(A,T,E[L])}return Gv(A,T),A}}(),BU=i1&&i1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(i1,"__esModule",{value:!0});i1.default=Cv;var Uv=BU(u1()),Wv=j("stream"),Nv=DU(),Qv=$v(j("dns")),Mv=j("util"),yL=BU(j("assert")),b0=(0,Uv.default)("mqttjs:socks");class qU extends Wv.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(_){if(b0("proxy stream started"),(0,yL.default)(!this._socket),this.destroyed){_.destroy(this.errored);return}if(this._socket=_,!this._flowing)_.pause();_.on("data",this._onData),_.on("end",this._onEnd),_.on("error",this._onError),_.on("close",this._onClose),_.emit("connect"),this.uncork()}_write(_,T,A){(0,yL.default)(this._socket),this._socket.write(_,A)}_read(_){this._flowing=!0,this._socket?.resume?.()}_destroy(_,T){this._socket?.destroy?.(_),T(_)}_onData=(_)=>{if((0,yL.default)(this._socket),this._flowing=this.push(_),!this._flowing)this._socket.pause()};_onEnd=()=>{b0("proxy stream received EOF"),this.push(null)};_onClose=()=>{b0("proxy stream closed"),this.destroy()};_onError=(_)=>{b0("proxy stream died with error %s",_),this.destroy(_)}}function Z5(_){try{if(_.code===void 0)_.code="SOCKS";return _}catch{return _}}function Vv(_){switch(_){case"socks5h:":return[5,!0];case"socks4a:":return[4,!0];case"socks5:":return[5,!1];case"socks4:":return[4,!1];default:return[void 0,!1]}}function zv(_){let T=new URL(_);if(T.pathname||T.hash||T.search)throw Z5(Error("bad SOCKS URL"));let[A,E]=Vv(T.protocol);if(!A)throw Z5(Error("bad SOCKS URL: invalid protocol"));let L=parseInt(T.port,10);if(Number.isNaN(L))throw Z5(Error("bad SOCKS URL: invalid port"));return[{host:T.hostname,port:L,type:A},E]}async function Fv(_,T,A,E,L={}){let J=L.lookup??(0,Mv.promisify)(Qv.lookup),[X,H]=zv(A);if(!H)b0("resolving %s locally",_),_=(await J(_,{family:X.type===4?4:0})).address;b0("establishing SOCKS%d connection to %s:%d via %s:%d",X.type,_,T,X.host,X.port);let Z=new Nv.SocksClient({command:"connect",destination:{host:_,port:T},proxy:{...X},timeout:L.timeout});Z.connect(),Z.on("established",({socket:Y})=>E._start(Y)),Z.on("error",(Y)=>{b0("SOCKS failed: %s",Y),E.destroy(Z5(Y))})}function Cv(_,T,A,E){b0("SOCKS connection to %s:%d via %s",_,T,A);let L=new qU;return Fv(_,T,A,L,E).catch((J)=>{b0("SOCKS failed: %s",J),L.destroy(J)}),L}});var kL=W((I8)=>{var hL=I8&&I8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(I8,"__esModule",{value:!0});var Ov=hL(j("net")),Rv=hL(u1()),Dv=hL(vL()),Bv=(0,Rv.default)("mqttjs:tcp"),qv=(_,T)=>{if(T.port=T.port||1883,T.hostname=T.hostname||T.host||"localhost",T.socksProxy)return(0,Dv.default)(T.hostname,T.port,T.socksProxy,{timeout:T.socksTimeout});let{port:A,path:E}=T,L=T.hostname;return Bv("port %d and host %s",A,L),Ov.default.createConnection({port:A,host:L,path:E})};I8.default=qv});var bL=W((P8)=>{var fL=P8&&P8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(P8,"__esModule",{value:!0});var IU=j("tls"),Iv=fL(j("net")),Pv=fL(u1()),jv=fL(vL()),xv=(0,Pv.default)("mqttjs:tls");function wv(_){let{host:T,port:A,socksProxy:E,...L}=_;if(E!==void 0){let J=(0,jv.default)(T,A,E,{timeout:_.socksTimeout});return(0,IU.connect)({...L,socket:J})}return(0,IU.connect)(_)}var Sv=(_,T)=>{if(T.port=T.port||8883,T.host=T.hostname||T.host||"localhost",Iv.default.isIP(T.host)===0)T.servername=T.host;T.rejectUnauthorized=T.rejectUnauthorized!==!1,delete T.path,xv("port %d host %s rejectUnauthorized %b",T.port,T.host,T.rejectUnauthorized);let A=wv(T);A.on("secureConnect",()=>{if(T.rejectUnauthorized&&!A.authorized)A.emit("error",Error("TLS not authorized"));else A.removeListener("error",E)});function E(L){if(T.rejectUnauthorized)_.emit("error",L);A.end()}return A.on("error",E),A};P8.default=Sv});var mL=W((jU)=>{Object.defineProperty(jU,"__esModule",{value:!0});var PU=j("buffer"),yv=n0(),vv=tA(),M0,gL,W1;function hv(){let _=new yv.Transform;return _._write=(T,A,E)=>{M0.send({data:T.buffer,success(){E()},fail(L){E(Error(L))}})},_._flush=(T)=>{M0.close({success(){T()}})},_}function kv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function fv(_,T){let A=_.protocol==="wxs"?"wss":"ws",E=`${A}://${_.hostname}${_.path}`;if(_.port&&_.port!==80&&_.port!==443)E=`${A}://${_.hostname}:${_.port}${_.path}`;if(typeof _.transformWsUrl==="function")E=_.transformWsUrl(E,_,T);return E}function bv(){M0.onOpen(()=>{W1.socketReady()}),M0.onMessage((_)=>{let{data:T}=_;if(T instanceof ArrayBuffer)T=PU.Buffer.from(T);else T=PU.Buffer.from(T,"utf8");gL.push(T)}),M0.onClose(()=>{W1.emit("close"),W1.end(),W1.destroy()}),M0.onError((_)=>{let T=Error(_.errMsg);W1.destroy(T)})}var gv=(_,T)=>{if(T.hostname=T.hostname||T.host,!T.hostname)throw Error("Could not determine host. Specify host manually.");let A=T.protocolId==="MQIsdp"&&T.protocolVersion===3?"mqttv3.1":"mqtt";kv(T);let E=fv(T,_);M0=wx.connectSocket({url:E,protocols:[A]}),gL=hv(),W1=new vv.BufferedDuplex(T,gL,M0),W1._destroy=(J,X)=>{M0.close({success(){if(X)X(J)}})};let L=W1.destroy;return W1.destroy=(J,X)=>{return W1.destroy=L,setTimeout(()=>{M0.close({fail(){W1._destroy(J,X)}})},0),W1},bv(),W1};jU.default=gv});var dL=W((wU)=>{Object.defineProperty(wU,"__esModule",{value:!0});var uL=j("buffer"),uv=n0(),dv=tA(),g0,j8,N4,xU=!1;function cv(){let _=new uv.Transform;return _._write=(T,A,E)=>{g0.sendSocketMessage({data:T.buffer,success(){E()},fail(){E(Error())}})},_._flush=(T)=>{g0.closeSocket({success(){T()}})},_}function pv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function lv(_,T){let A=_.protocol==="alis"?"wss":"ws",E=`${A}://${_.hostname}${_.path}`;if(_.port&&_.port!==80&&_.port!==443)E=`${A}://${_.hostname}:${_.port}${_.path}`;if(typeof _.transformWsUrl==="function")E=_.transformWsUrl(E,_,T);return E}function nv(){if(xU)return;xU=!0,g0.onSocketOpen(()=>{N4.socketReady()}),g0.onSocketMessage((_)=>{if(typeof _.data==="string"){let T=uL.Buffer.from(_.data,"base64");j8.push(T)}else{let T=new FileReader;T.addEventListener("load",()=>{if(T.result instanceof ArrayBuffer){j8.push(uL.Buffer.from(T.result));return}j8.push(uL.Buffer.from(T.result,"utf-8"))}),T.readAsArrayBuffer(_.data)}}),g0.onSocketClose(()=>{N4.end(),N4.destroy()}),g0.onSocketError((_)=>{N4.destroy(_)})}var iv=(_,T)=>{if(T.hostname=T.hostname||T.host,!T.hostname)throw Error("Could not determine host. Specify host manually.");let A=T.protocolId==="MQIsdp"&&T.protocolVersion===3?"mqttv3.1":"mqtt";pv(T);let E=lv(T,_);return g0=T.my,g0.connectSocket({url:E,protocols:A}),j8=cv(),N4=new dv.BufferedDuplex(T,j8,g0),nv(),N4};wU.default=iv});var hU=W((Q4)=>{var Y5=Q4&&Q4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(Q4,"__esModule",{value:!0});Q4.connectAsync=ev;var ov=Y5(u1()),rv=Y5(j("url")),sv=Y5(sA()),SU=Y5(O8());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var yU=(0,ov.default)("mqttjs"),S_=null;function tv(_){let T;if(_.auth)if(T=_.auth.match(/^(.+):(.+)$/),T){let[,A,E]=T;_.username=A,_.password=E}else _.username=_.auth}function vU(_,T){if(yU("connecting to an MQTT broker..."),typeof _==="object"&&!T)T=_,_="";if(T=T||{},_&&typeof _==="string"){let L=rv.default.parse(_,!0),J={};if(L.port!=null)J.port=Number(L.port);if(J.host=L.hostname,J.query=L.query,J.auth=L.auth,J.protocol=L.protocol,J.path=L.path,T={...J,...T},!T.protocol)throw Error("Missing protocol");T.protocol=T.protocol.replace(/:$/,"")}if(T.unixSocket=T.unixSocket||T.protocol?.includes("+unix"),T.unixSocket)T.protocol=T.protocol.replace("+unix","");else if(!T.protocol?.startsWith("ws")&&!T.protocol?.startsWith("wx"))delete T.path;if(tv(T),T.query&&typeof T.query.clientId==="string")T.clientId=T.query.clientId;if(SU.default||T.unixSocket)T.socksProxy=void 0;else if(T.socksProxy===void 0&&typeof process<"u")T.socksProxy=process.env.MQTTJS_SOCKS_PROXY;if(T.cert&&T.key)if(T.protocol){if(["mqtts","wss","wxs","alis"].indexOf(T.protocol)===-1)switch(T.protocol){case"mqtt":T.protocol="mqtts";break;case"ws":T.protocol="wss";break;case"wx":T.protocol="wxs";break;case"ali":T.protocol="alis";break;default:throw Error(`Unknown protocol for secure connection: "${T.protocol}"!`)}}else throw Error("Missing secure protocol key");if(!S_)if(S_={},!SU.default&&!T.forceNativeWebSocket)S_.ws=B8().streamBuilder,S_.wss=B8().streamBuilder,S_.mqtt=kL().default,S_.tcp=kL().default,S_.ssl=bL().default,S_.tls=S_.ssl,S_.mqtts=bL().default;else S_.ws=B8().browserStreamBuilder,S_.wss=B8().browserStreamBuilder,S_.wx=mL().default,S_.wxs=mL().default,S_.ali=dL().default,S_.alis=dL().default;if(!S_[T.protocol]){let L=["mqtts","wss"].indexOf(T.protocol)!==-1;T.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((J,X)=>{if(L&&X%2===0)return!1;return typeof S_[J]==="function"})[0]}if(T.clean===!1&&!T.clientId)throw Error("Missing clientId for unclean clients");if(T.protocol)T.defaultProtocol=T.protocol;function A(L){if(T.servers){if(!L._reconnectCount||L._reconnectCount===T.servers.length)L._reconnectCount=0;T.host=T.servers[L._reconnectCount].host,T.port=T.servers[L._reconnectCount].port,T.protocol=!T.servers[L._reconnectCount].protocol?T.defaultProtocol:T.servers[L._reconnectCount].protocol,T.hostname=T.host,L._reconnectCount++}return yU("calling streambuilder for",T.protocol),S_[T.protocol](L,T)}let E=new sv.default(A,T);return E.on("error",()=>{}),E}function ev(_,T,A=!0){return new Promise((E,L)=>{let J=vU(_,T),X={connect:(Z)=>{H(),E(J)},end:()=>{H(),E(J)},error:(Z)=>{H(),J.end(),L(Z)}};if(A===!1)X.close=()=>{X.error(Error("Couldn't connect to server"))};function H(){Object.keys(X).forEach((Z)=>{J.off(Z,X[Z])})}Object.keys(X).forEach((Z)=>{J.on(Z,X[Z])})})}Q4.default=vU});var cL=W((Z_)=>{var kU=Z_&&Z_.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),_h=Z_&&Z_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Th=Z_&&Z_.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")kU(A,T,E[L])}return _h(A,T),A}}(),fU=Z_&&Z_.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))kU(T,_,A)},x8=Z_&&Z_.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(Z_,"__esModule",{value:!0});Z_.ReasonCodes=Z_.KeepaliveManager=Z_.UniqueMessageIdProvider=Z_.DefaultMessageIdProvider=Z_.Store=Z_.MqttClient=Z_.connectAsync=Z_.connect=Z_.Client=void 0;var bU=x8(sA());Z_.MqttClient=bU.default;var Ah=x8(AL());Z_.DefaultMessageIdProvider=Ah.default;var Eh=x8(z$());Z_.UniqueMessageIdProvider=Eh.default;var Lh=x8(dE());Z_.Store=Lh.default;var gU=Th(hU());Z_.connect=gU.default;Object.defineProperty(Z_,"connectAsync",{enumerable:!0,get:function(){return gU.connectAsync}});var Jh=x8(NL());Z_.KeepaliveManager=Jh.default;Z_.Client=bU.default;fU(sA(),Z_);fU(BT(),Z_);var Xh=e4();Object.defineProperty(Z_,"ReasonCodes",{enumerable:!0,get:function(){return Xh.ReasonCodes}})});var uU=W((q1)=>{var mU=q1&&q1.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),Hh=q1&&q1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Zh=q1&&q1.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")mU(A,T,E[L])}return Hh(A,T),A}}(),Yh=q1&&q1.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))mU(T,_,A)};Object.defineProperty(q1,"__esModule",{value:!0});var Kh=Zh(cL());q1.default=Kh;Yh(cL(),q1)});var nL=W((Du,aU)=>{aU.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var sU=W((Bu,rU)=>{var Mh=nL();function oU(_){this.mode=Mh.MODE_8BIT_BYTE,this.data=_}oU.prototype={getLength:function(){return this.data.length},write:function(_){for(var T=0;T<this.data.length;T++)_.put(this.data.charCodeAt(T),8)}};rU.exports=oU});var iL=W((qu,tU)=>{var a1={glog:function(_){if(_<1)throw Error("glog("+_+")");return a1.LOG_TABLE[_]},gexp:function(_){while(_<0)_+=255;while(_>=256)_-=255;return a1.EXP_TABLE[_]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(R_=0;R_<8;R_++)a1.EXP_TABLE[R_]=1<<R_;var R_;for(R_=8;R_<256;R_++)a1.EXP_TABLE[R_]=a1.EXP_TABLE[R_-4]^a1.EXP_TABLE[R_-5]^a1.EXP_TABLE[R_-6]^a1.EXP_TABLE[R_-8];var R_;for(R_=0;R_<255;R_++)a1.LOG_TABLE[a1.EXP_TABLE[R_]]=R_;var R_;tU.exports=a1});var aL=W((Iu,eU)=>{var kT=iL();function N5(_,T){if(_.length===void 0)throw Error(_.length+"/"+T);var A=0;while(A<_.length&&_[A]===0)A++;this.num=Array(_.length-A+T);for(var E=0;E<_.length-A;E++)this.num[E]=_[E+A]}N5.prototype={get:function(_){return this.num[_]},getLength:function(){return this.num.length},multiply:function(_){var T=Array(this.getLength()+_.getLength()-1);for(var A=0;A<this.getLength();A++)for(var E=0;E<_.getLength();E++)T[A+E]^=kT.gexp(kT.glog(this.get(A))+kT.glog(_.get(E)));return new N5(T,0)},mod:function(_){if(this.getLength()-_.getLength()<0)return this;var T=kT.glog(this.get(0))-kT.glog(_.get(0)),A=Array(this.getLength());for(var E=0;E<this.getLength();E++)A[E]=this.get(E);for(var L=0;L<_.getLength();L++)A[L]^=kT.gexp(kT.glog(_.get(L))+T);return new N5(A,0).mod(_)}};eU.exports=N5});var TW=W((Pu,_W)=>{_W.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var LW=W((ju,EW)=>{var P1=nL(),AW=aL(),Vh=iL(),AT=TW(),u_={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(_){var T=_<<10;while(u_.getBCHDigit(T)-u_.getBCHDigit(u_.G15)>=0)T^=u_.G15<<u_.getBCHDigit(T)-u_.getBCHDigit(u_.G15);return(_<<10|T)^u_.G15_MASK},getBCHTypeNumber:function(_){var T=_<<12;while(u_.getBCHDigit(T)-u_.getBCHDigit(u_.G18)>=0)T^=u_.G18<<u_.getBCHDigit(T)-u_.getBCHDigit(u_.G18);return _<<12|T},getBCHDigit:function(_){var T=0;while(_!==0)T++,_>>>=1;return T},getPatternPosition:function(_){return u_.PATTERN_POSITION_TABLE[_-1]},getMask:function(_,T,A){switch(_){case AT.PATTERN000:return(T+A)%2===0;case AT.PATTERN001:return T%2===0;case AT.PATTERN010:return A%3===0;case AT.PATTERN011:return(T+A)%3===0;case AT.PATTERN100:return(Math.floor(T/2)+Math.floor(A/3))%2===0;case AT.PATTERN101:return T*A%2+T*A%3===0;case AT.PATTERN110:return(T*A%2+T*A%3)%2===0;case AT.PATTERN111:return(T*A%3+(T+A)%2)%2===0;default:throw Error("bad maskPattern:"+_)}},getErrorCorrectPolynomial:function(_){var T=new AW([1],0);for(var A=0;A<_;A++)T=T.multiply(new AW([1,Vh.gexp(A)],0));return T},getLengthInBits:function(_,T){if(1<=T&&T<10)switch(_){case P1.MODE_NUMBER:return 10;case P1.MODE_ALPHA_NUM:return 9;case P1.MODE_8BIT_BYTE:return 8;case P1.MODE_KANJI:return 8;default:throw Error("mode:"+_)}else if(T<27)switch(_){case P1.MODE_NUMBER:return 12;case P1.MODE_ALPHA_NUM:return 11;case P1.MODE_8BIT_BYTE:return 16;case P1.MODE_KANJI:return 10;default:throw Error("mode:"+_)}else if(T<41)switch(_){case P1.MODE_NUMBER:return 14;case P1.MODE_ALPHA_NUM:return 13;case P1.MODE_8BIT_BYTE:return 16;case P1.MODE_KANJI:return 12;default:throw Error("mode:"+_)}else throw Error("type:"+T)},getLostPoint:function(_){var T=_.getModuleCount(),A=0,E=0,L=0;for(E=0;E<T;E++)for(L=0;L<T;L++){var J=0,X=_.isDark(E,L);for(var H=-1;H<=1;H++){if(E+H<0||T<=E+H)continue;for(var Z=-1;Z<=1;Z++){if(L+Z<0||T<=L+Z)continue;if(H===0&&Z===0)continue;if(X===_.isDark(E+H,L+Z))J++}}if(J>5)A+=3+J-5}for(E=0;E<T-1;E++)for(L=0;L<T-1;L++){var Y=0;if(_.isDark(E,L))Y++;if(_.isDark(E+1,L))Y++;if(_.isDark(E,L+1))Y++;if(_.isDark(E+1,L+1))Y++;if(Y===0||Y===4)A+=3}for(E=0;E<T;E++)for(L=0;L<T-6;L++)if(_.isDark(E,L)&&!_.isDark(E,L+1)&&_.isDark(E,L+2)&&_.isDark(E,L+3)&&_.isDark(E,L+4)&&!_.isDark(E,L+5)&&_.isDark(E,L+6))A+=40;for(L=0;L<T;L++)for(E=0;E<T-6;E++)if(_.isDark(E,L)&&!_.isDark(E+1,L)&&_.isDark(E+2,L)&&_.isDark(E+3,L)&&_.isDark(E+4,L)&&!_.isDark(E+5,L)&&_.isDark(E+6,L))A+=40;var K=0;for(L=0;L<T;L++)for(E=0;E<T;E++)if(_.isDark(E,L))K++;var G=Math.abs(100*K/T/T-50)/5;return A+=G*10,A}};EW.exports=u_});var oL=W((xu,JW)=>{JW.exports={L:1,M:0,Q:3,H:2}});var HW=W((wu,XW)=>{var Q5=oL();function V0(_,T){this.totalCount=_,this.dataCount=T}V0.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];V0.getRSBlocks=function(_,T){var A=V0.getRsBlockTable(_,T);if(A===void 0)throw Error("bad rs block @ typeNumber:"+_+"/errorCorrectLevel:"+T);var E=A.length/3,L=[];for(var J=0;J<E;J++){var X=A[J*3+0],H=A[J*3+1],Z=A[J*3+2];for(var Y=0;Y<X;Y++)L.push(new V0(H,Z))}return L};V0.getRsBlockTable=function(_,T){switch(T){case Q5.L:return V0.RS_BLOCK_TABLE[(_-1)*4+0];case Q5.M:return V0.RS_BLOCK_TABLE[(_-1)*4+1];case Q5.Q:return V0.RS_BLOCK_TABLE[(_-1)*4+2];case Q5.H:return V0.RS_BLOCK_TABLE[(_-1)*4+3];default:return}};XW.exports=V0});var KW=W((Su,YW)=>{function ZW(){this.buffer=[],this.length=0}ZW.prototype={get:function(_){var T=Math.floor(_/8);return(this.buffer[T]>>>7-_%8&1)==1},put:function(_,T){for(var A=0;A<T;A++)this.putBit((_>>>T-A-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(_){var T=Math.floor(this.length/8);if(this.buffer.length<=T)this.buffer.push(0);if(_)this.buffer[T]|=128>>>this.length%8;this.length++}};YW.exports=ZW});var WW=W((yu,UW)=>{var zh=sU(),ET=LW(),Fh=aL(),GW=HW(),$W=KW();function z0(_,T){this.typeNumber=_,this.errorCorrectLevel=T,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}z0.prototype={addData:function(_){var T=new zh(_);this.dataList.push(T),this.dataCache=null},isDark:function(_,T){if(_<0||this.moduleCount<=_||T<0||this.moduleCount<=T)throw Error(_+","+T);return this.modules[_][T]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var _=1;for(_=1;_<40;_++){var T=GW.getRSBlocks(_,this.errorCorrectLevel),A=new $W,E=0;for(var L=0;L<T.length;L++)E+=T[L].dataCount;for(var J=0;J<this.dataList.length;J++){var X=this.dataList[J];A.put(X.mode,4),A.put(X.getLength(),ET.getLengthInBits(X.mode,_)),X.write(A)}if(A.getLengthInBits()<=E*8)break}this.typeNumber=_}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(_,T){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var A=0;A<this.moduleCount;A++){this.modules[A]=Array(this.moduleCount);for(var E=0;E<this.moduleCount;E++)this.modules[A][E]=null}if(this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(_,T),this.typeNumber>=7)this.setupTypeNumber(_);if(this.dataCache===null)this.dataCache=z0.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);this.mapData(this.dataCache,T)},setupPositionProbePattern:function(_,T){for(var A=-1;A<=7;A++){if(_+A<=-1||this.moduleCount<=_+A)continue;for(var E=-1;E<=7;E++){if(T+E<=-1||this.moduleCount<=T+E)continue;if(0<=A&&A<=6&&(E===0||E===6)||0<=E&&E<=6&&(A===0||A===6)||2<=A&&A<=4&&2<=E&&E<=4)this.modules[_+A][T+E]=!0;else this.modules[_+A][T+E]=!1}}},getBestMaskPattern:function(){var _=0,T=0;for(var A=0;A<8;A++){this.makeImpl(!0,A);var E=ET.getLostPoint(this);if(A===0||_>E)_=E,T=A}return T},createMovieClip:function(_,T,A){var E=_.createEmptyMovieClip(T,A),L=1;this.make();for(var J=0;J<this.modules.length;J++){var X=J*L;for(var H=0;H<this.modules[J].length;H++){var Z=H*L,Y=this.modules[J][H];if(Y)E.beginFill(0,100),E.moveTo(Z,X),E.lineTo(Z+L,X),E.lineTo(Z+L,X+L),E.lineTo(Z,X+L),E.endFill()}}return E},setupTimingPattern:function(){for(var _=8;_<this.moduleCount-8;_++){if(this.modules[_][6]!==null)continue;this.modules[_][6]=_%2===0}for(var T=8;T<this.moduleCount-8;T++){if(this.modules[6][T]!==null)continue;this.modules[6][T]=T%2===0}},setupPositionAdjustPattern:function(){var _=ET.getPatternPosition(this.typeNumber);for(var T=0;T<_.length;T++)for(var A=0;A<_.length;A++){var E=_[T],L=_[A];if(this.modules[E][L]!==null)continue;for(var J=-2;J<=2;J++)for(var X=-2;X<=2;X++)if(Math.abs(J)===2||Math.abs(X)===2||J===0&&X===0)this.modules[E+J][L+X]=!0;else this.modules[E+J][L+X]=!1}},setupTypeNumber:function(_){var T=ET.getBCHTypeNumber(this.typeNumber),A;for(var E=0;E<18;E++)A=!_&&(T>>E&1)===1,this.modules[Math.floor(E/3)][E%3+this.moduleCount-8-3]=A;for(var L=0;L<18;L++)A=!_&&(T>>L&1)===1,this.modules[L%3+this.moduleCount-8-3][Math.floor(L/3)]=A},setupTypeInfo:function(_,T){var A=this.errorCorrectLevel<<3|T,E=ET.getBCHTypeInfo(A),L;for(var J=0;J<15;J++)if(L=!_&&(E>>J&1)===1,J<6)this.modules[J][8]=L;else if(J<8)this.modules[J+1][8]=L;else this.modules[this.moduleCount-15+J][8]=L;for(var X=0;X<15;X++)if(L=!_&&(E>>X&1)===1,X<8)this.modules[8][this.moduleCount-X-1]=L;else if(X<9)this.modules[8][15-X-1+1]=L;else this.modules[8][15-X-1]=L;this.modules[this.moduleCount-8][8]=!_},mapData:function(_,T){var A=-1,E=this.moduleCount-1,L=7,J=0;for(var X=this.moduleCount-1;X>0;X-=2){if(X===6)X--;while(!0){for(var H=0;H<2;H++)if(this.modules[E][X-H]===null){var Z=!1;if(J<_.length)Z=(_[J]>>>L&1)===1;var Y=ET.getMask(T,E,X-H);if(Y)Z=!Z;if(this.modules[E][X-H]=Z,L--,L===-1)J++,L=7}if(E+=A,E<0||this.moduleCount<=E){E-=A,A=-A;break}}}}};z0.PAD0=236;z0.PAD1=17;z0.createData=function(_,T,A){var E=GW.getRSBlocks(_,T),L=new $W;for(var J=0;J<A.length;J++){var X=A[J];L.put(X.mode,4),L.put(X.getLength(),ET.getLengthInBits(X.mode,_)),X.write(L)}var H=0;for(var Z=0;Z<E.length;Z++)H+=E[Z].dataCount;if(L.getLengthInBits()>H*8)throw Error("code length overflow. ("+L.getLengthInBits()+">"+H*8+")");if(L.getLengthInBits()+4<=H*8)L.put(0,4);while(L.getLengthInBits()%8!==0)L.putBit(!1);while(!0){if(L.getLengthInBits()>=H*8)break;if(L.put(z0.PAD0,8),L.getLengthInBits()>=H*8)break;L.put(z0.PAD1,8)}return z0.createBytes(L,E)};z0.createBytes=function(_,T){var A=0,E=0,L=0,J=Array(T.length),X=Array(T.length);for(var H=0;H<T.length;H++){var Z=T[H].dataCount,Y=T[H].totalCount-Z;E=Math.max(E,Z),L=Math.max(L,Y),J[H]=Array(Z);for(var K=0;K<J[H].length;K++)J[H][K]=255&_.buffer[K+A];A+=Z;var G=ET.getErrorCorrectPolynomial(Y),$=new Fh(J[H],G.getLength()-1),U=$.mod(G);X[H]=Array(G.getLength()-1);for(var V=0;V<X[H].length;V++){var N=V+U.getLength()-X[H].length;X[H][V]=N>=0?U.get(N):0}}var z=0;for(var Q=0;Q<T.length;Q++)z+=T[Q].totalCount;var F=Array(z),R=0;for(var q=0;q<E;q++)for(var f=0;f<T.length;f++)if(q<J[f].length)F[R++]=J[f][q];for(var h=0;h<L;h++)for(var b=0;b<T.length;b++)if(h<X[b].length)F[R++]=X[b][h];return F};UW.exports=z0});var MW=W((vu,QW)=>{var Ch=WW(),NW=oL(),Oh="\x1B[40m \x1B[0m",M5="\x1B[47m \x1B[0m",Rh=function(_){return _?Oh:M5},rL=function(_){return{times:function(T){return Array(T).join(_)}}},Dh=function(_,T){var A=Array(_);for(var E=0;E<_;E++)A[E]=T;return A};QW.exports={error:NW.L,generate:function(_,T,A){if(typeof T==="function")A=T,T={};var E=new Ch(-1,this.error);E.addData(_),E.make();var L="";if(T&&T.small){var J=!0,X=!1,H=E.getModuleCount(),Z=E.modules.slice(),Y=H%2===1;if(Y)Z.push(Dh(H,X));var K={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},G=rL(K.BLACK_WHITE).times(H+3),$=rL(K.WHITE_BLACK).times(H+3);L+=G+`
|
|
15
|
+
`;for(var U=0;U<H;U+=2){L+=K.WHITE_ALL;for(var V=0;V<H;V++)if(Z[U][V]===X&&Z[U+1][V]===X)L+=K.WHITE_ALL;else if(Z[U][V]===X&&Z[U+1][V]===J)L+=K.WHITE_BLACK;else if(Z[U][V]===J&&Z[U+1][V]===X)L+=K.BLACK_WHITE;else L+=K.BLACK_ALL;L+=K.WHITE_ALL+`
|
|
16
|
+
`}if(!Y)L+=$}else{var N=rL(M5).times(E.getModuleCount()+3);L+=N+`
|
|
17
|
+
`,E.modules.forEach(function(z){L+=M5,L+=z.map(Rh).join(""),L+=M5+`
|
|
18
|
+
`}),L+=N}if(A)A(L);else console.log(L)},setErrorLevel:function(_){this.error=NW[_]||this.error}}});import{parseArgs as CN}from"util";var ON={debug:{type:"boolean",short:"d",default:!1,description:"Enable debug logging"},"mqtt-port":{type:"string",default:"8884",description:"MQTT broker port"},"terminal-port":{type:"string",default:"3001",description:"Terminal server port"},"router-port":{type:"string",default:"8883",description:"Router port"},username:{type:"string",description:"MQTT broker username (optional)"},password:{type:"string",description:"MQTT broker password (optional)"},"ngrok-token":{type:"string",description:"ngrok authentication token (optional)"},"ngrok-domain":{type:"string",description:"ngrok static domain (optional, paid plan)"},"no-auto-update":{type:"boolean",default:!1,description:"Disable auto-update checking"},"auto-update-check-interval":{type:"string",default:"60",description:"Auto-update check interval in minutes (default: 60)"},help:{type:"boolean",short:"h",default:!1,description:"Show help message"}};function U9(){let _=CN({options:ON,allowPositionals:!1,strict:!0});if(_.values.help)RN(),process.exit(0);return{debug:_.values.debug,mqttPort:parseInt(_.values["mqtt-port"],10),terminalPort:parseInt(_.values["terminal-port"],10),routerPort:parseInt(_.values["router-port"],10),username:_.values.username,password:_.values.password,ngrokToken:_.values["ngrok-token"],ngrokDomain:_.values["ngrok-domain"],autoUpdate:!_.values["no-auto-update"],autoUpdateCheckInterval:parseInt(_.values["auto-update-check-interval"],10)}}function RN(){console.log(`
|
|
19
19
|
Backend v2 - Clean modular architecture
|
|
20
20
|
|
|
21
21
|
Usage:
|
|
@@ -33,15 +33,15 @@ Options:
|
|
|
33
33
|
--no-auto-update Disable auto-update checking (default: enabled)
|
|
34
34
|
--auto-update-check-interval <min> Check interval in minutes (default: 60)
|
|
35
35
|
-h, --help Show this help message
|
|
36
|
-
`)}class aD extends Error{code;statusCode;constructor(H,$="SERVICE_ERROR",A=500){super(H);this.code=$;this.statusCode=A;this.name="ServiceError"}}class lD extends Error{constructor(H){super(H);this.name="ConfigError"}}class vf extends aD{constructor(H){super(H,"MQTT_BROKER_ERROR",500);this.name="MQTTBrokerError"}}class pL extends aD{constructor(H){super(H,"TERMINAL_SERVER_ERROR",500);this.name="TerminalServerError"}}class YE extends aD{constructor(H){super(H,"ROUTER_ERROR",500);this.name="RouterError"}}class Yf extends aD{constructor(H="Authentication failed"){super(H,"AUTH_ERROR",401);this.name="AuthenticationError"}}function bU(H){return fS(H),ES(H),{debug:H.debug,mqtt:{port:H.mqttPort,heartbeatInterval:30000,connectTimeout:30000,debug:H.debug,...H.username&&H.password&&{auth:{username:H.username,password:H.password}}},terminal:{port:H.terminalPort,debug:H.debug},router:{port:H.routerPort,debug:H.debug},...H.ngrokToken&&{ngrok:{authToken:H.ngrokToken,routerPort:H.routerPort,...H.ngrokDomain&&{domain:H.ngrokDomain},debug:H.debug}},qrcode:{username:H.username,password:H.password,profileName:"",debug:H.debug},autoUpdate:{enabled:H.autoUpdate,packageName:"@naarang/ccc",checkIntervalMinutes:H.autoUpdateCheckInterval,debug:H.debug},claudeAgent:{maxConcurrentSessions:10,sessionTimeoutMs:1800000}}}function fS(H){let $={"MQTT port":H.mqttPort,"Terminal port":H.terminalPort,"Router port":H.routerPort};for(let[D,f]of Object.entries($))if(isNaN(f)||f<1024||f>65535)throw new lD(`Invalid ${D}: ${f}. Must be between 1024 and 65535`);let A=Object.values($);if(new Set(A).size!==A.length)throw new lD("Port conflict: Each service must use a different port")}function ES(H){if(H.ngrokToken&&(!H.username||!H.password))throw new lD("Error: MQTT authentication (--username and --password) is required when using ngrok tunnels for security.")}class qE{isDev;constructor(H=!1){this.isDev=H}debug(H,$){if(this.isDev)console.log(`[DEBUG] ${H}`,$||"")}info(H,$){console.log(`[INFO] ${H}`,$||"")}warn(H,$){console.warn(`[WARN] ${H}`,$||"")}error(H,$){console.error(`[ERROR] ${H}`,$||"")}}var yD=null;function NU(H=!1){return yD=new qE(H),yD}function l(){if(!yD)yD=new qE(!1);return yD}import*as YA from"fs";import*as gL from"path";var IS={FULL_WIDTH:0,FITTING:1,SMUSHING:2,CONTROLLED_SMUSHING:3};class kU{constructor(){this.comment="",this.numChars=0,this.options={}}}var ZE=["1Row","3-D","3D Diagonal","3D-ASCII","3x5","4Max","5 Line Oblique","AMC 3 Line","AMC 3 Liv1","AMC AAA01","AMC Neko","AMC Razor","AMC Razor2","AMC Slash","AMC Slider","AMC Thin","AMC Tubes","AMC Untitled","ANSI Regular","ANSI Shadow","ANSI-Compact","ASCII 12","ASCII 9","ASCII New Roman","Acrobatic","Alligator","Alligator2","Alpha","Alphabet","Arrows","Avatar","B1FF","Babyface Lame","Babyface Leet","Banner","Banner3-D","Banner3","Banner4","Barbwire","Basic","Bear","Bell","Benjamin","Big ASCII 12","Big ASCII 9","Big Chief","Big Money-ne","Big Money-nw","Big Money-se","Big Money-sw","Big Mono 12","Big Mono 9","Big","Bigfig","Binary","Block","Blocks","Bloody","BlurVision ASCII","Bolger","Braced","Bright","Broadway KB","Broadway","Bubble","Bulbhead","Caligraphy","Caligraphy2","Calvin S","Cards","Catwalk","Chiseled","Chunky","Circle","Coinstak","Cola","Colossal","Computer","Contessa","Contrast","Cosmike","Cosmike2","Crawford","Crawford2","Crazy","Cricket","Cursive","Cyberlarge","Cybermedium","Cybersmall","Cygnet","DANC4","DOS Rebel","DWhistled","Dancing Font","Decimal","Def Leppard","Delta Corps Priest 1","DiamFont","Diamond","Diet Cola","Digital","Doh","Doom","Dot Matrix","Double Shorts","Double","Dr Pepper","Efti Chess","Efti Font","Efti Italic","Efti Piti","Efti Robot","Efti Wall","Efti Water","Electronic","Elite","Emboss 2","Emboss","Epic","Fender","Filter","Fire Font-k","Fire Font-s","Flipped","Flower Power","Four Tops","Fraktur","Fun Face","Fun Faces","Future","Fuzzy","Georgi16","Georgia11","Ghost","Ghoulish","Glenyn","Goofy","Gothic","Graceful","Gradient","Graffiti","Greek","Heart Left","Heart Right","Henry 3D","Hex","Hieroglyphs","Hollywood","Horizontal Left","Horizontal Right","ICL-1900","Impossible","Invita","Isometric1","Isometric2","Isometric3","Isometric4","Italic","Ivrit","JS Block Letters","JS Bracket Letters","JS Capital Curves","JS Cursive","JS Stick Letters","Jacky","Jazmine","Jerusalem","Katakana","Kban","Keyboard","Knob","Konto Slant","Konto","LCD","Larry 3D 2","Larry 3D","Lean","Letter","Letters","Lil Devil","Line Blocks","Linux","Lockergnome","Madrid","Marquee","Maxfour","Merlin1","Merlin2","Mike","Mini","Mirror","Mnemonic","Modular","Mono 12","Mono 9","Morse","Morse2","Moscow","Mshebrew210","Muzzle","NScript","NT Greek","NV Script","Nancyj-Fancy","Nancyj-Improved","Nancyj-Underlined","Nancyj","Nipples","O8","OS2","Octal","Ogre","Old Banner","Pagga","Patorjk's Cheese","Patorjk-HeX","Pawp","Peaks Slant","Peaks","Pebbles","Pepper","Poison","Puffy","Puzzle","Pyramid","Rammstein","Rebel","Rectangles","Red Phoenix","Relief","Relief2","Reverse","Roman","Rot13","Rotated","Rounded","Rowan Cap","Rozzo","RubiFont","Runic","Runyc","S Blood","SL Script","Santa Clara","Script","Serifcap","Shaded Blocky","Shadow","Shimrod","Short","Slant Relief","Slant","Slide","Small ASCII 12","Small ASCII 9","Small Block","Small Braille","Small Caps","Small Isometric1","Small Keyboard","Small Mono 12","Small Mono 9","Small Poison","Small Script","Small Shadow","Small Slant","Small Tengwar","Small","Soft","Speed","Spliff","Stacey","Stampate","Stampatello","Standard","Star Strips","Star Wars","Stellar","Stforek","Stick Letters","Stop","Straight","Stronger Than All","Sub-Zero","Swamp Land","Swan","Sweet","THIS","Tanja","Tengwar","Term","Terrace","Test1","The Edge","Thick","Thin","Thorned","Three Point","Ticks Slant","Ticks","Tiles","Tinker-Toy","Tmplr","Tombstone","Train","Trek","Tsalagi","Tubular","Twisted","Two Point","USA Flag","Univers","Upside Down Text","Varsity","Wavescape","Wavy","Weird","Wet Letter","Whimsy","WideTerm","Wow","miniwi"];function PS(H){return/[.*+?^${}()|[\]\\]/.test(H)?"\\"+H:H}var RU=(()=>{let{FULL_WIDTH:H=0,FITTING:$,SMUSHING:A,CONTROLLED_SMUSHING:L}=IS,D={},f={font:"Standard",fontPath:"./fonts",fetchFontIfMissing:!0};function E(S,n,u){let X=PS(S.trim().slice(-1))||"@",C=n===u-1?new RegExp(X+X+"?\\s*$"):new RegExp(X+"\\s*$");return S.replace(C,"")}function I(S=-1,n=null){let u={},X,C=[[16384,"vLayout",A],[8192,"vLayout",$],[4096,"vRule5",!0],[2048,"vRule4",!0],[1024,"vRule3",!0],[512,"vRule2",!0],[256,"vRule1",!0],[128,"hLayout",A],[64,"hLayout",$],[32,"hRule6",!0],[16,"hRule5",!0],[8,"hRule4",!0],[4,"hRule3",!0],[2,"hRule2",!0],[1,"hRule1",!0]];X=n!==null?n:S;for(let[G,a,d]of C)if(X>=G){if(X-=G,u[a]===void 0)u[a]=d}else if(a!=="vLayout"&&a!=="hLayout")u[a]=!1;if(typeof u.hLayout>"u")if(S===0)u.hLayout=$;else if(S===-1)u.hLayout=H;else if(u.hRule1||u.hRule2||u.hRule3||u.hRule4||u.hRule5||u.hRule6)u.hLayout=L;else u.hLayout=A;else if(u.hLayout===A){if(u.hRule1||u.hRule2||u.hRule3||u.hRule4||u.hRule5||u.hRule6)u.hLayout=L}if(typeof u.vLayout>"u")if(u.vRule1||u.vRule2||u.vRule3||u.vRule4||u.vRule5)u.vLayout=L;else u.vLayout=H;else if(u.vLayout===A){if(u.vRule1||u.vRule2||u.vRule3||u.vRule4||u.vRule5)u.vLayout=L}return u}function P(S,n,u=""){if(S===n&&S!==u)return S;return!1}function T(S,n){let u="|/\\[]{}()<>";if(S==="_"){if(u.indexOf(n)!==-1)return n}else if(n==="_"){if(u.indexOf(S)!==-1)return S}return!1}function U(S,n){let u="| /\\ [] {} () <>",X=u.indexOf(S),C=u.indexOf(n);if(X!==-1&&C!==-1){if(X!==C&&Math.abs(X-C)!==1){let G=Math.max(X,C),a=G+1;return u.substring(G,a)}}return!1}function M(S,n){let u="[] {} ()",X=u.indexOf(S),C=u.indexOf(n);if(X!==-1&&C!==-1){if(Math.abs(X-C)<=1)return"|"}return!1}function t(S,n){return{"/\\":"|","\\/":"Y","><":"X"}[S+n]||!1}function _(S,n,u=""){if(S===u&&n===u)return u;return!1}function x(S,n){if(S===n)return S;return!1}function V(S,n){return T(S,n)}function h(S,n){return U(S,n)}function W(S,n){if(S==="-"&&n==="_"||S==="_"&&n==="-")return"=";return!1}function c(S,n){if(S==="|"&&n==="|")return"|";return!1}function r(S,n,u){if(n===" "||n==="")return S;else if(n===u&&S!==" ")return S;else return n}function F(S,n,u){if(u.fittingRules&&u.fittingRules.vLayout===H)return"invalid";let X,C=Math.min(S.length,n.length),G,a,d=!1,b;if(C===0)return"invalid";for(X=0;X<C;X++)if(G=S.substring(X,X+1),a=n.substring(X,X+1),G!==" "&&a!==" ")if(u.fittingRules&&u.fittingRules.vLayout===$)return"invalid";else if(u.fittingRules&&u.fittingRules.vLayout===A)return"end";else{if(c(G,a)){d=d||!1;continue}if(b=!1,b=u.fittingRules&&u.fittingRules.vRule1?x(G,a):b,b=!b&&u.fittingRules&&u.fittingRules.vRule2?V(G,a):b,b=!b&&u.fittingRules&&u.fittingRules.vRule3?h(G,a):b,b=!b&&u.fittingRules&&u.fittingRules.vRule4?W(G,a):b,d=!0,!b)return"invalid"}if(d)return"end";else return"valid"}function N(S,n,u){let{length:X,length:C}=S,G,a,d,b=1,w,v,g;while(b<=X){G=S.slice(Math.max(0,C-b),C),a=n.slice(0,Math.min(X,b)),d=a.length,g="";for(w=0;w<d;w++)if(v=F(G[w],a[w],u),v==="end")g=v;else if(v==="invalid"){g=v;break}else if(g==="")g="valid";if(g==="invalid"){b--;break}if(g==="end")break;if(g==="valid")b++}return Math.min(X,b)}function y(S,n,u){let X,C=Math.min(S.length,n.length),G,a,d="",b,w=u.fittingRules||{};for(X=0;X<C;X++)if(G=S.substring(X,X+1),a=n.substring(X,X+1),G!==" "&&a!==" ")if(w.vLayout===$)d+=r(G,a);else if(w.vLayout===A)d+=r(G,a);else b=!1,b=w.vRule5?c(G,a):b,b=!b&&w.vRule1?x(G,a):b,b=!b&&w.vRule2?V(G,a):b,b=!b&&w.vRule3?h(G,a):b,b=!b&&w.vRule4?W(G,a):b,d+=b;else d+=r(G,a);return d}function k(S,n,u,X){let C=S.length,G=n.length,a=S.slice(0,Math.max(0,C-u)),d=S.slice(Math.max(0,C-u),C),b=n.slice(0,Math.min(u,G)),w,v,g,Y=[],AH;v=d.length;for(w=0;w<v;w++){if(w>=G)g=d[w];else g=y(d[w],b[w],X);Y.push(g)}return AH=n.slice(Math.min(u,G),G),[...a,...Y,...AH]}function J(S,n){let u=" ".repeat(n);return S.map((X)=>X+u)}function e(S,n,u){let X=S[0].length,C=n[0].length,G;if(X>C)n=J(n,X-C);else if(C>X)S=J(S,C-X);return G=N(S,n,u),k(S,n,G,u)}function WH(S,n,u){let X=u.fittingRules||{};if(X.hLayout===H)return 0;let C,G=S.length,a=n.length,d=G,b=1,w=!1,v,g,Y,AH;if(G===0)return 0;H:while(b<=d){let R$=G-b;v=S.substring(R$,R$+b),g=n.substring(0,Math.min(b,a));for(C=0;C<Math.min(b,a);C++)if(Y=v.substring(C,C+1),AH=g.substring(C,C+1),Y!==" "&&AH!==" "){if(X.hLayout===$){b=b-1;break H}else if(X.hLayout===A){if(Y===u.hardBlank||AH===u.hardBlank)b=b-1;break H}else if(w=!0,!(X.hRule1&&P(Y,AH,u.hardBlank)||X.hRule2&&T(Y,AH)||X.hRule3&&U(Y,AH)||X.hRule4&&M(Y,AH)||X.hRule5&&t(Y,AH)||X.hRule6&&_(Y,AH,u.hardBlank))){b=b-1;break H}}if(w)break;b++}return Math.min(d,b)}function vH(S,n,u,X){let C,G,a=[],d,b,w,v,g,Y,AH,R$,T$=X.fittingRules||{};if(typeof X.height!=="number")throw Error("height is not defined.");for(C=0;C<X.height;C++){AH=S[C],R$=n[C],g=AH.length,Y=R$.length,d=g-u,b=AH.slice(0,Math.max(0,d)),w="";let dD=Math.max(0,g-u),O$=AH.substring(dD,dD+u),_L=R$.substring(0,Math.min(u,Y));for(G=0;G<u;G++){let S$=G<g?O$.substring(G,G+1):" ",U$=G<Y?_L.substring(G,G+1):" ";if(S$!==" "&&U$!==" ")if(T$.hLayout===$||T$.hLayout===A)w+=r(S$,U$,X.hardBlank);else{let qX=T$.hRule1&&P(S$,U$,X.hardBlank)||T$.hRule2&&T(S$,U$)||T$.hRule3&&U(S$,U$)||T$.hRule4&&M(S$,U$)||T$.hRule5&&t(S$,U$)||T$.hRule6&&_(S$,U$,X.hardBlank)||r(S$,U$,X.hardBlank);w+=qX}else w+=r(S$,U$,X.hardBlank)}if(u>=Y)v="";else v=R$.substring(u,u+Math.max(0,Y-u));a[C]=b+w+v}return a}function sH(S){return Array(S).fill("")}let rH=function(S){return Math.max(...S.map((n)=>n.length))};function tH(S,n,u){return S.reduce(function(X,C){return vH(X,C.fig,C.overlap||0,u)},sH(n))}function hH(S,n,u){for(let X=S.length-1;X>0;X--){let C=tH(S.slice(0,X),n,u);if(rH(C)<=u.width)return{outputFigText:C,chars:S.slice(X)}}return{outputFigText:sH(n),chars:S}}function CH(S,n,u){let X,C,G=0,a,d,b,w=u.height,v=[],g,Y={chars:[],overlap:G},AH=[],R$,T$,dD,O$,_L;if(typeof w!=="number")throw Error("height is not defined.");d=sH(w);let S$=u.fittingRules||{};if(u.printDirection===1)S=S.split("").reverse().join("");b=S.length;for(X=0;X<b;X++)if(R$=S.substring(X,X+1),T$=R$.match(/\s/),C=n[R$.charCodeAt(0)],O$=null,C){if(S$.hLayout!==H){G=1e4;for(a=0;a<w;a++)G=Math.min(G,WH(d[a],C[a],u));G=G===1e4?0:G}if(u.width>0){if(u.whitespaceBreak)dD=tH(Y.chars.concat([{fig:C,overlap:G}]),w,u),O$=tH(AH.concat([{fig:dD,overlap:Y.overlap}]),w,u),g=rH(O$);else O$=vH(d,C,G,u),g=rH(O$);if(g>=u.width&&X>0)if(u.whitespaceBreak){if(d=tH(AH.slice(0,-1),w,u),AH.length>1)v.push(d),d=sH(w);AH=[]}else v.push(d),d=sH(w)}if(u.width>0&&u.whitespaceBreak){if(!T$||X===b-1)Y.chars.push({fig:C,overlap:G});if(T$||X===b-1){_L=null;while(!0)if(O$=tH(Y.chars,w,u),g=rH(O$),g>=u.width)_L=hH(Y.chars,w,u),Y={chars:_L.chars},v.push(_L.outputFigText);else break;if(g>0)if(_L)AH.push({fig:O$,overlap:1});else AH.push({fig:O$,overlap:Y.overlap});if(T$)AH.push({fig:C,overlap:G}),d=sH(w);if(X===b-1)d=tH(AH,w,u);Y={chars:[],overlap:G};continue}}d=vH(d,C,G,u)}if(rH(d)>0)v.push(d);if(!u.showHardBlanks)v.forEach(function(U$){b=U$.length;for(a=0;a<b;a++)U$[a]=U$[a].replace(new RegExp("\\"+u.hardBlank,"g")," ")});if(S===""&&v.length===0)v.push(Array(w).fill(""));return v}let GH=function(S,n){let u,X=n.fittingRules||{};if(S==="default")u={hLayout:X.hLayout,hRule1:X.hRule1,hRule2:X.hRule2,hRule3:X.hRule3,hRule4:X.hRule4,hRule5:X.hRule5,hRule6:X.hRule6};else if(S==="full")u={hLayout:H,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else if(S==="fitted")u={hLayout:$,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else if(S==="controlled smushing")u={hLayout:L,hRule1:!0,hRule2:!0,hRule3:!0,hRule4:!0,hRule5:!0,hRule6:!0};else if(S==="universal smushing")u={hLayout:A,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else return;return u},CA=function(S,n){let u={},X=n.fittingRules||{};if(S==="default")u={vLayout:X.vLayout,vRule1:X.vRule1,vRule2:X.vRule2,vRule3:X.vRule3,vRule4:X.vRule4,vRule5:X.vRule5};else if(S==="full")u={vLayout:H,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else if(S==="fitted")u={vLayout:$,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else if(S==="controlled smushing")u={vLayout:L,vRule1:!0,vRule2:!0,vRule3:!0,vRule4:!0,vRule5:!0};else if(S==="universal smushing")u={vLayout:A,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else return;return u},k$=function(S,n,u){u=u.replace(/\r\n/g,`
|
|
36
|
+
`)}class B4 extends Error{code;statusCode;constructor(_,T="SERVICE_ERROR",A=500){super(_);this.code=T;this.statusCode=A;this.name="ServiceError"}}class q4 extends Error{constructor(_){super(_);this.name="ConfigError"}}class v8 extends B4{constructor(_){super(_,"MQTT_BROKER_ERROR",500);this.name="MQTTBrokerError"}}class XT extends B4{constructor(_){super(_,"TERMINAL_SERVER_ERROR",500);this.name="TerminalServerError"}}class S5 extends B4{constructor(_){super(_,"ROUTER_ERROR",500);this.name="RouterError"}}class h8 extends B4{constructor(_="Authentication failed"){super(_,"AUTH_ERROR",401);this.name="AuthenticationError"}}function W9(_){return DN(_),BN(_),{debug:_.debug,mqtt:{port:_.mqttPort,heartbeatInterval:30000,connectTimeout:30000,debug:_.debug,..._.username&&_.password&&{auth:{username:_.username,password:_.password}}},terminal:{port:_.terminalPort,debug:_.debug},router:{port:_.routerPort,debug:_.debug},..._.ngrokToken&&{ngrok:{authToken:_.ngrokToken,routerPort:_.routerPort,..._.ngrokDomain&&{domain:_.ngrokDomain},debug:_.debug}},qrcode:{username:_.username,password:_.password,profileName:"",debug:_.debug},autoUpdate:{enabled:_.autoUpdate,packageName:"@naarang/ccc",checkIntervalMinutes:_.autoUpdateCheckInterval,debug:_.debug},claudeAgent:{maxConcurrentSessions:10,sessionTimeoutMs:1800000}}}function DN(_){let T={"MQTT port":_.mqttPort,"Terminal port":_.terminalPort,"Router port":_.routerPort};for(let[L,J]of Object.entries(T))if(isNaN(J)||J<1024||J>65535)throw new q4(`Invalid ${L}: ${J}. Must be between 1024 and 65535`);let A=Object.values(T);if(new Set(A).size!==A.length)throw new q4("Port conflict: Each service must use a different port")}function BN(_){if(_.ngrokToken&&(!_.username||!_.password))throw new q4("Error: MQTT authentication (--username and --password) is required when using ngrok tunnels for security.")}class y5{isDev;constructor(_=!1){this.isDev=_}debug(_,T){if(this.isDev)console.log(`[DEBUG] ${_}`,T||"")}info(_,T){console.log(`[INFO] ${_}`,T||"")}warn(_,T){console.warn(`[WARN] ${_}`,T||"")}error(_,T){console.error(`[ERROR] ${_}`,T||"")}}var I4=null;function N9(_=!1){return I4=new y5(_),I4}function v(){if(!I4)I4=new y5(!1);return I4}import*as d0 from"fs";import*as mT from"path";var qN={FULL_WIDTH:0,FITTING:1,SMUSHING:2,CONTROLLED_SMUSHING:3};class Q9{constructor(){this.comment="",this.numChars=0,this.options={}}}var v5=["1Row","3-D","3D Diagonal","3D-ASCII","3x5","4Max","5 Line Oblique","AMC 3 Line","AMC 3 Liv1","AMC AAA01","AMC Neko","AMC Razor","AMC Razor2","AMC Slash","AMC Slider","AMC Thin","AMC Tubes","AMC Untitled","ANSI Regular","ANSI Shadow","ANSI-Compact","ASCII 12","ASCII 9","ASCII New Roman","Acrobatic","Alligator","Alligator2","Alpha","Alphabet","Arrows","Avatar","B1FF","Babyface Lame","Babyface Leet","Banner","Banner3-D","Banner3","Banner4","Barbwire","Basic","Bear","Bell","Benjamin","Big ASCII 12","Big ASCII 9","Big Chief","Big Money-ne","Big Money-nw","Big Money-se","Big Money-sw","Big Mono 12","Big Mono 9","Big","Bigfig","Binary","Block","Blocks","Bloody","BlurVision ASCII","Bolger","Braced","Bright","Broadway KB","Broadway","Bubble","Bulbhead","Caligraphy","Caligraphy2","Calvin S","Cards","Catwalk","Chiseled","Chunky","Circle","Coinstak","Cola","Colossal","Computer","Contessa","Contrast","Cosmike","Cosmike2","Crawford","Crawford2","Crazy","Cricket","Cursive","Cyberlarge","Cybermedium","Cybersmall","Cygnet","DANC4","DOS Rebel","DWhistled","Dancing Font","Decimal","Def Leppard","Delta Corps Priest 1","DiamFont","Diamond","Diet Cola","Digital","Doh","Doom","Dot Matrix","Double Shorts","Double","Dr Pepper","Efti Chess","Efti Font","Efti Italic","Efti Piti","Efti Robot","Efti Wall","Efti Water","Electronic","Elite","Emboss 2","Emboss","Epic","Fender","Filter","Fire Font-k","Fire Font-s","Flipped","Flower Power","Four Tops","Fraktur","Fun Face","Fun Faces","Future","Fuzzy","Georgi16","Georgia11","Ghost","Ghoulish","Glenyn","Goofy","Gothic","Graceful","Gradient","Graffiti","Greek","Heart Left","Heart Right","Henry 3D","Hex","Hieroglyphs","Hollywood","Horizontal Left","Horizontal Right","ICL-1900","Impossible","Invita","Isometric1","Isometric2","Isometric3","Isometric4","Italic","Ivrit","JS Block Letters","JS Bracket Letters","JS Capital Curves","JS Cursive","JS Stick Letters","Jacky","Jazmine","Jerusalem","Katakana","Kban","Keyboard","Knob","Konto Slant","Konto","LCD","Larry 3D 2","Larry 3D","Lean","Letter","Letters","Lil Devil","Line Blocks","Linux","Lockergnome","Madrid","Marquee","Maxfour","Merlin1","Merlin2","Mike","Mini","Mirror","Mnemonic","Modular","Mono 12","Mono 9","Morse","Morse2","Moscow","Mshebrew210","Muzzle","NScript","NT Greek","NV Script","Nancyj-Fancy","Nancyj-Improved","Nancyj-Underlined","Nancyj","Nipples","O8","OS2","Octal","Ogre","Old Banner","Pagga","Patorjk's Cheese","Patorjk-HeX","Pawp","Peaks Slant","Peaks","Pebbles","Pepper","Poison","Puffy","Puzzle","Pyramid","Rammstein","Rebel","Rectangles","Red Phoenix","Relief","Relief2","Reverse","Roman","Rot13","Rotated","Rounded","Rowan Cap","Rozzo","RubiFont","Runic","Runyc","S Blood","SL Script","Santa Clara","Script","Serifcap","Shaded Blocky","Shadow","Shimrod","Short","Slant Relief","Slant","Slide","Small ASCII 12","Small ASCII 9","Small Block","Small Braille","Small Caps","Small Isometric1","Small Keyboard","Small Mono 12","Small Mono 9","Small Poison","Small Script","Small Shadow","Small Slant","Small Tengwar","Small","Soft","Speed","Spliff","Stacey","Stampate","Stampatello","Standard","Star Strips","Star Wars","Stellar","Stforek","Stick Letters","Stop","Straight","Stronger Than All","Sub-Zero","Swamp Land","Swan","Sweet","THIS","Tanja","Tengwar","Term","Terrace","Test1","The Edge","Thick","Thin","Thorned","Three Point","Ticks Slant","Ticks","Tiles","Tinker-Toy","Tmplr","Tombstone","Train","Trek","Tsalagi","Tubular","Twisted","Two Point","USA Flag","Univers","Upside Down Text","Varsity","Wavescape","Wavy","Weird","Wet Letter","Whimsy","WideTerm","Wow","miniwi"];function IN(_){return/[.*+?^${}()|[\]\\]/.test(_)?"\\"+_:_}var M9=(()=>{let{FULL_WIDTH:_=0,FITTING:T,SMUSHING:A,CONTROLLED_SMUSHING:E}=qN,L={},J={font:"Standard",fontPath:"./fonts",fetchFontIfMissing:!0};function X(O,D,M){let C=IN(O.trim().slice(-1))||"@",P=D===M-1?new RegExp(C+C+"?\\s*$"):new RegExp(C+"\\s*$");return O.replace(P,"")}function H(O=-1,D=null){let M={},C,P=[[16384,"vLayout",A],[8192,"vLayout",T],[4096,"vRule5",!0],[2048,"vRule4",!0],[1024,"vRule3",!0],[512,"vRule2",!0],[256,"vRule1",!0],[128,"hLayout",A],[64,"hLayout",T],[32,"hRule6",!0],[16,"hRule5",!0],[8,"hRule4",!0],[4,"hRule3",!0],[2,"hRule2",!0],[1,"hRule1",!0]];C=D!==null?D:O;for(let[w,y,S]of P)if(C>=w){if(C-=w,M[y]===void 0)M[y]=S}else if(y!=="vLayout"&&y!=="hLayout")M[y]=!1;if(typeof M.hLayout>"u")if(O===0)M.hLayout=T;else if(O===-1)M.hLayout=_;else if(M.hRule1||M.hRule2||M.hRule3||M.hRule4||M.hRule5||M.hRule6)M.hLayout=E;else M.hLayout=A;else if(M.hLayout===A){if(M.hRule1||M.hRule2||M.hRule3||M.hRule4||M.hRule5||M.hRule6)M.hLayout=E}if(typeof M.vLayout>"u")if(M.vRule1||M.vRule2||M.vRule3||M.vRule4||M.vRule5)M.vLayout=E;else M.vLayout=_;else if(M.vLayout===A){if(M.vRule1||M.vRule2||M.vRule3||M.vRule4||M.vRule5)M.vLayout=E}return M}function Z(O,D,M=""){if(O===D&&O!==M)return O;return!1}function Y(O,D){let M="|/\\[]{}()<>";if(O==="_"){if(M.indexOf(D)!==-1)return D}else if(D==="_"){if(M.indexOf(O)!==-1)return O}return!1}function K(O,D){let M="| /\\ [] {} () <>",C=M.indexOf(O),P=M.indexOf(D);if(C!==-1&&P!==-1){if(C!==P&&Math.abs(C-P)!==1){let w=Math.max(C,P),y=w+1;return M.substring(w,y)}}return!1}function G(O,D){let M="[] {} ()",C=M.indexOf(O),P=M.indexOf(D);if(C!==-1&&P!==-1){if(Math.abs(C-P)<=1)return"|"}return!1}function $(O,D){return{"/\\":"|","\\/":"Y","><":"X"}[O+D]||!1}function U(O,D,M=""){if(O===M&&D===M)return M;return!1}function V(O,D){if(O===D)return O;return!1}function N(O,D){return Y(O,D)}function z(O,D){return K(O,D)}function Q(O,D){if(O==="-"&&D==="_"||O==="_"&&D==="-")return"=";return!1}function F(O,D){if(O==="|"&&D==="|")return"|";return!1}function R(O,D,M){if(D===" "||D==="")return O;else if(D===M&&O!==" ")return O;else return D}function q(O,D,M){if(M.fittingRules&&M.fittingRules.vLayout===_)return"invalid";let C,P=Math.min(O.length,D.length),w,y,S=!1,k;if(P===0)return"invalid";for(C=0;C<P;C++)if(w=O.substring(C,C+1),y=D.substring(C,C+1),w!==" "&&y!==" ")if(M.fittingRules&&M.fittingRules.vLayout===T)return"invalid";else if(M.fittingRules&&M.fittingRules.vLayout===A)return"end";else{if(F(w,y)){S=S||!1;continue}if(k=!1,k=M.fittingRules&&M.fittingRules.vRule1?V(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule2?N(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule3?z(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule4?Q(w,y):k,S=!0,!k)return"invalid"}if(S)return"end";else return"valid"}function f(O,D,M){let{length:C,length:P}=O,w,y,S,k=1,d,o,a;while(k<=C){w=O.slice(Math.max(0,P-k),P),y=D.slice(0,Math.min(C,k)),S=y.length,a="";for(d=0;d<S;d++)if(o=q(w[d],y[d],M),o==="end")a=o;else if(o==="invalid"){a=o;break}else if(a==="")a="valid";if(a==="invalid"){k--;break}if(a==="end")break;if(a==="valid")k++}return Math.min(C,k)}function h(O,D,M){let C,P=Math.min(O.length,D.length),w,y,S="",k,d=M.fittingRules||{};for(C=0;C<P;C++)if(w=O.substring(C,C+1),y=D.substring(C,C+1),w!==" "&&y!==" ")if(d.vLayout===T)S+=R(w,y);else if(d.vLayout===A)S+=R(w,y);else k=!1,k=d.vRule5?F(w,y):k,k=!k&&d.vRule1?V(w,y):k,k=!k&&d.vRule2?N(w,y):k,k=!k&&d.vRule3?z(w,y):k,k=!k&&d.vRule4?Q(w,y):k,S+=k;else S+=R(w,y);return S}function b(O,D,M,C){let P=O.length,w=D.length,y=O.slice(0,Math.max(0,P-M)),S=O.slice(Math.max(0,P-M),P),k=D.slice(0,Math.min(M,w)),d,o,a,r=[],T_;o=S.length;for(d=0;d<o;d++){if(d>=w)a=S[d];else a=h(S[d],k[d],C);r.push(a)}return T_=D.slice(Math.min(M,w),w),[...y,...r,...T_]}function l(O,D){let M=" ".repeat(D);return O.map((C)=>C+M)}function c(O,D,M){let C=O[0].length,P=D[0].length,w;if(C>P)D=l(D,C-P);else if(P>C)O=l(O,P-C);return w=f(O,D,M),b(O,D,w,M)}function W_(O,D,M){let C=M.fittingRules||{};if(C.hLayout===_)return 0;let P,w=O.length,y=D.length,S=w,k=1,d=!1,o,a,r,T_;if(w===0)return 0;_:while(k<=S){let y1=w-k;o=O.substring(y1,y1+k),a=D.substring(0,Math.min(k,y));for(P=0;P<Math.min(k,y);P++)if(r=o.substring(P,P+1),T_=a.substring(P,P+1),r!==" "&&T_!==" "){if(C.hLayout===T){k=k-1;break _}else if(C.hLayout===A){if(r===M.hardBlank||T_===M.hardBlank)k=k-1;break _}else if(d=!0,!(C.hRule1&&Z(r,T_,M.hardBlank)||C.hRule2&&Y(r,T_)||C.hRule3&&K(r,T_)||C.hRule4&&G(r,T_)||C.hRule5&&$(r,T_)||C.hRule6&&U(r,T_,M.hardBlank))){k=k-1;break _}}if(d)break;k++}return Math.min(S,k)}function c_(O,D,M,C){let P,w,y=[],S,k,d,o,a,r,T_,y1,E1=C.fittingRules||{};if(typeof C.height!=="number")throw Error("height is not defined.");for(P=0;P<C.height;P++){T_=O[P],y1=D[P],a=T_.length,r=y1.length,S=a-M,k=T_.slice(0,Math.max(0,S)),d="";let D4=Math.max(0,a-M),v1=T_.substring(D4,D4+M),JT=y1.substring(0,Math.min(M,r));for(w=0;w<M;w++){let Q1=w<a?v1.substring(w,w+1):" ",L1=w<r?JT.substring(w,w+1):" ";if(Q1!==" "&&L1!==" ")if(E1.hLayout===T||E1.hLayout===A)d+=R(Q1,L1,C.hardBlank);else{let QN=E1.hRule1&&Z(Q1,L1,C.hardBlank)||E1.hRule2&&Y(Q1,L1)||E1.hRule3&&K(Q1,L1)||E1.hRule4&&G(Q1,L1)||E1.hRule5&&$(Q1,L1)||E1.hRule6&&U(Q1,L1,C.hardBlank)||R(Q1,L1,C.hardBlank);d+=QN}else d+=R(Q1,L1,C.hardBlank)}if(M>=r)o="";else o=y1.substring(M,M+Math.max(0,r-M));y[P]=k+d+o}return y}function B_(O){return Array(O).fill("")}let C_=function(O){return Math.max(...O.map((D)=>D.length))};function K_(O,D,M){return O.reduce(function(C,P){return c_(C,P.fig,P.overlap||0,M)},B_(D))}function M_(O,D,M){for(let C=O.length-1;C>0;C--){let P=K_(O.slice(0,C),D,M);if(C_(P)<=M.width)return{outputFigText:P,chars:O.slice(C)}}return{outputFigText:B_(D),chars:O}}function q_(O,D,M){let C,P,w=0,y,S,k,d=M.height,o=[],a,r={chars:[],overlap:w},T_=[],y1,E1,D4,v1,JT;if(typeof d!=="number")throw Error("height is not defined.");S=B_(d);let Q1=M.fittingRules||{};if(M.printDirection===1)O=O.split("").reverse().join("");k=O.length;for(C=0;C<k;C++)if(y1=O.substring(C,C+1),E1=y1.match(/\s/),P=D[y1.charCodeAt(0)],v1=null,P){if(Q1.hLayout!==_){w=1e4;for(y=0;y<d;y++)w=Math.min(w,W_(S[y],P[y],M));w=w===1e4?0:w}if(M.width>0){if(M.whitespaceBreak)D4=K_(r.chars.concat([{fig:P,overlap:w}]),d,M),v1=K_(T_.concat([{fig:D4,overlap:r.overlap}]),d,M),a=C_(v1);else v1=c_(S,P,w,M),a=C_(v1);if(a>=M.width&&C>0)if(M.whitespaceBreak){if(S=K_(T_.slice(0,-1),d,M),T_.length>1)o.push(S),S=B_(d);T_=[]}else o.push(S),S=B_(d)}if(M.width>0&&M.whitespaceBreak){if(!E1||C===k-1)r.chars.push({fig:P,overlap:w});if(E1||C===k-1){JT=null;while(!0)if(v1=K_(r.chars,d,M),a=C_(v1),a>=M.width)JT=M_(r.chars,d,M),r={chars:JT.chars},o.push(JT.outputFigText);else break;if(a>0)if(JT)T_.push({fig:v1,overlap:1});else T_.push({fig:v1,overlap:r.overlap});if(E1)T_.push({fig:P,overlap:w}),S=B_(d);if(C===k-1)S=K_(T_,d,M);r={chars:[],overlap:w};continue}}S=c_(S,P,w,M)}if(C_(S)>0)o.push(S);if(!M.showHardBlanks)o.forEach(function(L1){k=L1.length;for(y=0;y<k;y++)L1[y]=L1[y].replace(new RegExp("\\"+M.hardBlank,"g")," ")});if(O===""&&o.length===0)o.push(Array(d).fill(""));return o}let P_=function(O,D){let M,C=D.fittingRules||{};if(O==="default")M={hLayout:C.hLayout,hRule1:C.hRule1,hRule2:C.hRule2,hRule3:C.hRule3,hRule4:C.hRule4,hRule5:C.hRule5,hRule6:C.hRule6};else if(O==="full")M={hLayout:_,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else if(O==="fitted")M={hLayout:T,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else if(O==="controlled smushing")M={hLayout:E,hRule1:!0,hRule2:!0,hRule3:!0,hRule4:!0,hRule5:!0,hRule6:!0};else if(O==="universal smushing")M={hLayout:A,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else return;return M},O0=function(O,D){let M={},C=D.fittingRules||{};if(O==="default")M={vLayout:C.vLayout,vRule1:C.vRule1,vRule2:C.vRule2,vRule3:C.vRule3,vRule4:C.vRule4,vRule5:C.vRule5};else if(O==="full")M={vLayout:_,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else if(O==="fitted")M={vLayout:T,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else if(O==="controlled smushing")M={vLayout:E,vRule1:!0,vRule2:!0,vRule3:!0,vRule4:!0,vRule5:!0};else if(O==="universal smushing")M={vLayout:A,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else return;return M},S1=function(O,D,M){M=M.replace(/\r\n/g,`
|
|
37
37
|
`).replace(/\r/g,`
|
|
38
|
-
`);let
|
|
39
|
-
`),
|
|
40
|
-
`):""};function
|
|
38
|
+
`);let C=M.split(`
|
|
39
|
+
`),P=[],w,y,S;y=C.length;for(w=0;w<y;w++)P=P.concat(q_(C[w],L[O],D));y=P.length,S=P[0];for(w=1;w<y;w++)S=c(S,P[w],D);return S?S.join(`
|
|
40
|
+
`):""};function G9(O,D){let M;if(typeof structuredClone<"u")M=structuredClone(O);else M=JSON.parse(JSON.stringify(O));if(M.showHardBlanks=D.showHardBlanks||!1,M.width=D.width||-1,M.whitespaceBreak=D.whitespaceBreak||!1,D.horizontalLayout){let C=P_(D.horizontalLayout,O);if(C)Object.assign(M.fittingRules,C)}if(D.verticalLayout){let C=O0(D.verticalLayout,O);if(C)Object.assign(M.fittingRules,C)}return M.printDirection=D.printDirection!==null&&D.printDirection!==void 0?D.printDirection:O.printDirection,M}let I_=async function(O,D,M){return I_.text(O,D,M)};return I_.text=async function(O,D,M){O=O+"";let C,P;if(typeof D==="function")P=D,C={font:J.font};else if(typeof D==="string")C={font:D},P=M;else if(D)C=D,P=M;else C={font:J.font},P=M;let w=C.font||J.font;try{let y=await I_.loadFont(w),S=y?S1(w,G9(y,C),O):"";if(P)P(null,S);return S}catch(y){let S=y instanceof Error?y:Error(String(y));if(P)return P(S),"";throw S}},I_.textSync=function(O,D){if(O=O+"",typeof D==="string")D={font:D};else D=D||{};let M=D.font||J.font,C=G9(I_.loadFontSync(M),D);return S1(M,C,O)},I_.metadata=async function(O,D){O=O+"";try{let M=await I_.loadFont(O);if(!M)throw Error("Error loading font.");let C=L[O]||{},P=[M,C.comment||""];if(D)D(null,M,C.comment);return P}catch(M){let C=M instanceof Error?M:Error(String(M));if(D)return D(C),null;throw C}},I_.defaults=function(O){if(O&&typeof O==="object")Object.assign(J,O);if(typeof structuredClone<"u")return structuredClone(J);else return JSON.parse(JSON.stringify(J))},I_.parseFont=function(O,D,M=!0){if(L[O]&&!M)return L[O].options;D=D.replace(/\r\n/g,`
|
|
41
41
|
`).replace(/\r/g,`
|
|
42
|
-
`);let
|
|
43
|
-
`),
|
|
44
|
-
`),
|
|
42
|
+
`);let C=new Q9,P=D.split(`
|
|
43
|
+
`),w=P.shift();if(!w)throw Error("Invalid font file: missing header");let y=w.split(" "),S={hardBlank:y[0].substring(5,6),height:parseInt(y[1],10),baseline:parseInt(y[2],10),maxLength:parseInt(y[3],10),oldLayout:parseInt(y[4],10),numCommentLines:parseInt(y[5],10),printDirection:y[6]?parseInt(y[6],10):0,fullLayout:y[7]?parseInt(y[7],10):null,codeTagCount:y[8]?parseInt(y[8],10):null};if((S.hardBlank||"").length!==1||[S.height,S.baseline,S.maxLength,S.oldLayout,S.numCommentLines].some((o)=>o===null||o===void 0||isNaN(o)))throw Error("FIGlet header contains invalid values.");if(S.height==null||S.numCommentLines==null)throw Error("FIGlet header contains invalid values.");S.fittingRules=H(S.oldLayout,S.fullLayout),C.options=S;let d=[];for(let o=32;o<=126;o++)d.push(o);if(d.push(196,214,220,228,246,252,223),P.length<S.numCommentLines+S.height*d.length)throw Error(`FIGlet file is missing data. Line length: ${P.length}. Comment lines: ${S.numCommentLines}. Height: ${S.height}. Num chars: ${d.length}.`);C.comment=P.splice(0,S.numCommentLines).join(`
|
|
44
|
+
`),C.numChars=0;while(P.length>0&&C.numChars<d.length){let o=d[C.numChars];C[o]=P.splice(0,S.height);for(let a=0;a<S.height;a++)if(typeof C[o][a]>"u")C[o][a]="";else C[o][a]=X(C[o][a],a,S.height);C.numChars++}while(P.length>0){let o=P.shift();if(!o||o.trim()==="")break;let a=o.split(" ")[0],r;if(/^-?0[xX][0-9a-fA-F]+$/.test(a))r=parseInt(a,16);else if(/^-?0[0-7]+$/.test(a))r=parseInt(a,8);else if(/^-?[0-9]+$/.test(a))r=parseInt(a,10);else throw Error(`Error parsing data. Invalid data: ${a}`);if(r===-1||r<-2147483648||r>2147483647){let T_=r===-1?"The char code -1 is not permitted.":`The char code cannot be ${r<-2147483648?"less than -2147483648":"greater than 2147483647"}.`;throw Error(`Error parsing data. ${T_}`)}C[r]=P.splice(0,S.height);for(let T_=0;T_<S.height;T_++)if(typeof C[r][T_]>"u")C[r][T_]="";else C[r][T_]=X(C[r][T_],T_,S.height);C.numChars++}return L[O]=C,S},I_.loadedFonts=()=>{return Object.keys(L)},I_.clearLoadedFonts=()=>{Object.keys(L).forEach((O)=>{delete L[O]})},I_.loadFont=async function(O,D){if(L[O]){let M=L[O].options;if(D)D(null,M);return Promise.resolve(M)}try{if(!J.fetchFontIfMissing)throw Error(`Font is not loaded: ${O}`);let M=await fetch(`${J.fontPath}/${O}.flf`);if(!M.ok)throw Error(`Network response was not ok: ${M.status}`);let C=await M.text(),P=I_.parseFont(O,C);if(D)D(null,P);return P}catch(M){let C=M instanceof Error?M:Error(String(M));if(D)return D(C),null;throw C}},I_.loadFontSync=function(O){if(L[O])return L[O].options;throw Error("Synchronous font loading is not implemented for the browser, it will only work for fonts already loaded.")},I_.preloadFonts=async function(O,D){try{for(let M of O){let C=await fetch(`${J.fontPath}/${M}.flf`);if(!C.ok)throw Error(`Failed to preload fonts. Error fetching font: ${M}, status code: ${C.statusText}`);let P=await C.text();I_.parseFont(M,P)}if(D)D()}catch(M){let C=M instanceof Error?M:Error(String(M));if(D){D(C);return}throw M}},I_.fonts=function(O){return new Promise(function(D,M){if(D(v5),O)O(null,v5)})},I_.fontsSync=function(){return v5},I_.figFonts=L,I_})();import{fileURLToPath as PN}from"url";var jN=PN(import.meta.url),xN=mT.dirname(jN),wN=mT.join(xN,"/../fonts/"),j_=M9;j_.defaults({fontPath:wN});j_.loadFont=function(_,T){return new Promise((A,E)=>{if(j_.figFonts[_]){if(T)T(null,j_.figFonts[_].options);A(j_.figFonts[_].options);return}d0.readFile(mT.join(j_.defaults().fontPath,_+".flf"),{encoding:"utf-8"},(L,J)=>{if(L){if(T)T(L);E(L);return}J=J+"";try{let X=j_.parseFont(_,J);if(T)T(null,X);A(X)}catch(X){let H=X instanceof Error?X:Error(String(X));if(T)T(H);E(H)}})})};j_.loadFontSync=function(_){if(j_.figFonts[_])return j_.figFonts[_].options;let T=d0.readFileSync(mT.join(j_.defaults().fontPath,_+".flf"),{encoding:"utf-8"})+"";return j_.parseFont(_,T)};j_.fonts=function(_){return new Promise((T,A)=>{let E=[];d0.readdir(j_.defaults().fontPath,(L,J)=>{if(L){_&&_(L),A(L);return}J.forEach((X)=>{if(/\.flf$/.test(X))E.push(X.replace(/\.flf$/,""))}),_&&_(null,E),T(E)})})};j_.fontsSync=function(){let _=[];return d0.readdirSync(j_.defaults().fontPath).forEach((T)=>{if(/\.flf$/.test(T))_.push(T.replace(/\.flf$/,""))}),_};var V9=`flf2a$ 6 5 16 15 13 0 24463 229
|
|
45
45
|
Standard by Glenn Chappell & Ian Chai 3/93 -- based on Frank's .sig
|
|
46
46
|
Includes ISO Latin-1
|
|
47
47
|
figlet release 2.1 -- 12 Aug 1994
|
|
@@ -2277,9 +2277,9 @@ Font modified May 20, 2012 by patorjk to add the 0xCA0 character
|
|
|
2277
2277
|
| (_) | @
|
|
2278
2278
|
$\\___/$ @
|
|
2279
2279
|
@@
|
|
2280
|
-
`;
|
|
2281
|
-
`),console.log(
|
|
2282
|
-
`)}var F1=dH(n1(),1);import{Duplex as k4}from"stream";async function o1(H,$,A){let L=null,D=await import("net"),f=new Set;return L=D.createServer((E)=>{A.debug("[MQTT TCP] Client socket connected"),f.add(E);let I=new k4({read(){},write(P,T,U){E.write(P,T,U)}});E.on("data",(P)=>{I.push(P)}),E.on("end",()=>{I.push(null),f.delete(E)}),E.on("error",(P)=>{A.debug("[MQTT TCP] Socket error",{error:P.message}),I.destroy(P),f.delete(E)}),E.on("close",()=>{f.delete(E)}),I.on("error",(P)=>{A.debug("[MQTT TCP] Stream error",{error:P.message}),E.destroy()});try{H.handle(I)}catch(P){A.error("[MQTT TCP] Error handling connection",{error:P}),E.destroy()}}),{server:null,tcpServer:L,listen:async(E,I)=>{return new Promise((P,T)=>{let U=(t)=>{A.error("[MQTT TCP] Server error",{error:t.message,code:t.code,port:E,hostname:I}),T(t)},M=()=>{A.debug("[MQTT TCP] Server listening",{port:E,hostname:I}),L.removeListener("error",U),P()};L.once("error",U),L.once("listening",M),L.listen(E,I)})},close:async()=>{return new Promise((E)=>{if(L){for(let P of f)try{P.destroy()}catch(T){A.debug("[MQTT TCP] Error destroying socket",{error:T})}f.clear();let I=setTimeout(()=>{A.warn("[MQTT TCP] Server close timeout, forcing shutdown"),E()},500);L.close(()=>{clearTimeout(I),A.debug("[MQTT] TCP server closed"),E()})}else E()})}}}class $E{servers=null;broker=null;running=!1;startedAt;config;name="CCC MQTT Broker";constructor(H){this.config=H,this.createBrokerInstance()}createBrokerInstance(){this.broker=F1.default({id:"ccc-mqtt-broker",heartbeatInterval:this.config.heartbeatInterval||30000,connectTimeout:this.config.connectTimeout||30000,authenticate:this.authenticate.bind(this)}),this.setupBrokerEvents()}setupBrokerEvents(){let H=l();this.broker.on("client",($)=>{H.debug("MQTT client connected",{clientId:$.id,clean:$.clean})}),this.broker.on("clientDisconnect",($)=>{H.debug("MQTT client disconnected",{clientId:$.id})}),this.broker.on("subscribe",($,A)=>{H.debug("MQTT client subscribed",{clientId:A?.id,topics:$.map((L)=>L.topic)})}),this.broker.on("unsubscribe",($,A)=>{H.debug("MQTT client unsubscribed",{clientId:A?.id,topics:$})}),this.broker.on("publish",($,A)=>{if(A)H.debug("MQTT message published",{clientId:A.id,topic:$.topic,qos:$.qos,size:$.payload?.length||0})}),this.broker.on("clientError",($,A)=>{H.error("MQTT client error",{clientId:$?.id,error:A.message})}),this.broker.on("connectionError",($,A)=>{H.error("MQTT connection error",{clientId:$?.id,error:A.message})})}async start(){try{let H=l();this.servers=await o1(this.broker,{port:this.config.port,hostname:"localhost"},H),await this.servers.listen(this.config.port,"localhost"),this.running=!0,this.startedAt=new Date,H.debug("MQTT Broker started (TCP only)",{tcpPort:this.config.port,protocols:["mqtt/tcp"]})}catch(H){throw new vf(`Failed to start MQTT broker: ${H instanceof Error?H.message:String(H)}`)}}async stop(){try{let H=l();if(!this.running)return;if(H.debug("Stopping MQTT Broker"),this.broker?.clients)for(let $ of Object.keys(this.broker.clients)){let A=this.broker.clients[$];try{A.close()}catch(L){H.debug("Error closing MQTT client",{clientId:$,error:L})}}if(this.servers)try{await this.servers.close()}catch($){H.error("Error closing servers",{error:$})}try{await new Promise(($)=>{let A=setTimeout(()=>{H.debug("MQTT broker close timeout, forcing shutdown"),$()},1000);if(this.broker)this.broker.close(()=>{clearTimeout(A),H.debug("MQTT broker closed"),$()});else clearTimeout(A),$()})}catch($){H.error("Error closing MQTT broker",{error:$})}this.running=!1,H.info("\u2713 MQTT Broker stopped")}catch(H){throw this.running=!1,new vf(`Failed to stop MQTT broker: ${H instanceof Error?H.message:String(H)}`)}}getStatus(){return{name:"MQTT Broker",running:this.running,port:this.config.port,startedAt:this.startedAt,clientCount:this.broker?.clients?Object.keys(this.broker.clients).length:0}}authenticate(H,$,A,L){let D=l();if(!this.config.auth){D.debug("No authentication configured, allowing MQTT connection",{clientId:H.id}),L(null,!0);return}let f=A?.toString();if($===this.config.auth.username&&f===this.config.auth.password)D.debug("MQTT client authenticated successfully",{clientId:H.id,username:$}),L(null,!0);else D.warn("MQTT client authentication failed",{clientId:H.id,username:$}),L(Error("Invalid credentials"),!1)}}var Mc=dH(Uc(),1);var a$=l();class nE{name="Backend MQTT Client";client=null;running=!1;connected=!1;startedAt;config;subscriptions=new Map;constructor(H){this.config=H}async start(){return new Promise((H,$)=>{try{let A=`mqtt://${this.config.host}:${this.config.port}`;this.client=Mc.default.connect(A,{clientId:"backend-client",clean:!0,connectTimeout:5000,username:this.config.username,password:this.config.password}),this.client.on("connect",()=>{this.connected=!0,this.running=!0,this.startedAt=new Date,a$.info("[BackendClient] Connected to MQTT broker"),H()}),this.client.on("error",(L)=>{if(a$.error("[BackendClient] MQTT error",{error:L.message}),!this.connected)$(L)}),this.client.on("close",()=>{this.connected=!1,a$.debug("[BackendClient] Disconnected from MQTT broker")}),this.client.on("message",(L,D)=>{this.handleMessage(L,D)})}catch(A){a$.error("[BackendClient] Failed to start",A),$(A)}})}async stop(){return new Promise((H)=>{if(!this.client){this.running=!1,H();return}this.client.end(!1,{},()=>{this.running=!1,this.connected=!1,this.subscriptions.clear(),a$.info("[BackendClient] Stopped"),H()})})}subscribe(H,$){if(!this.client)throw Error("MQTT client not initialized");if(!this.subscriptions.has(H))this.subscriptions.set(H,new Set),this.client.subscribe(H,{qos:1},(A)=>{if(A)a$.error(`[BackendClient] Failed to subscribe to ${H}`,{error:A.message});else a$.debug(`[BackendClient] Subscribed to ${H}`)});this.subscriptions.get(H).add($)}unsubscribe(H,$){if(!this.client)return;let A=this.subscriptions.get(H);if(!A)return;if(A.delete($),A.size===0)this.subscriptions.delete(H),this.client.unsubscribe(H,(L)=>{if(L)a$.error(`[BackendClient] Failed to unsubscribe from ${H}`,{error:L.message});else a$.debug(`[BackendClient] Unsubscribed from ${H}`)})}publish(H,$,A){return new Promise((L,D)=>{if(!this.client){D(Error("MQTT client not initialized"));return}this.client.publish(H,$,{qos:A?.qos||1},(f)=>{if(f)a$.error(`[BackendClient] Failed to publish to ${H}`,{error:f.message}),D(f);else a$.debug(`[BackendClient] Published to ${H}`),L()})})}topicToRegex(H){let $=H.replace(/[.\\^${}|[\]()]/g,"\\$&").replace(/\+/g,"[^/]+").replace(/#/g,".*");return new RegExp(`^${$}$`)}handleMessage(H,$){this.subscriptions.forEach((A,L)=>{if(this.topicToRegex(L).test(H))A.forEach((f)=>{try{f(H,$)}catch(E){a$.error(`[BackendClient] Error in message handler for ${H}`,{error:E instanceof Error?E.message:"Unknown error"})}})})}getStatus(){return{name:this.name,running:this.running,connected:this.connected,startedAt:this.startedAt}}}var tc=5,KN=900000;class PU{credentials;failedAttempts=new Map;blockedIPs=new Map;logger=l();constructor(){this.credentials=this.generateCredentials(),this.logger.debug("Terminal credentials generated",{username:this.credentials.username})}getCredentials(){return this.credentials}authenticate(H,$,A){let L=this.blockedIPs.get(A);if(L&&L>Date.now())throw new Yf("IP temporarily blocked due to too many failed attempts");if(H===this.credentials.username&&$===this.credentials.password)return this.failedAttempts.delete(A),this.blockedIPs.delete(A),!0;let D=(this.failedAttempts.get(A)||0)+1;if(this.failedAttempts.set(A,D),D>=tc)this.blockedIPs.set(A,Date.now()+KN),this.failedAttempts.delete(A),this.logger.warn(`IP blocked after ${tc} failed attempts`,{ip:A});throw new Yf("Invalid credentials")}generateCredentials(){let H=this.generateRandomString(32),$=this.generateRandomString(480);return{username:H,password:$}}generateRandomString(H){let A="",L=new Uint8Array(H);crypto.getRandomValues(L);for(let D=0;D<H;D++){let f=L[D]??0;A+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;,.<>?"[f%87]}return A}}import{spawn as gN}from"bun-pty";var _c=5,vN=300000,YN=102400;class TU{sessions=new Map;projectPath=process.cwd();logger=l();createSession(H,$=80,A=24){if(Array.from(this.sessions.values()).filter((D)=>!D.disconnectedAt).length>=_c)throw new pL(`Maximum concurrent sessions (${_c}) reached`);try{let D=process.platform==="win32"?"powershell.exe":"bash",f=gN(D,[],{name:"xterm-256color",cols:$,rows:A,cwd:this.projectPath,env:process.env}),E={id:H,createdAt:new Date,lastActivityAt:new Date};this.sessions.set(H,{pty:f,session:E,cwd:this.projectPath,outputBuffer:[]}),this.logger.debug(`PTY session created: ${H}`,{cols:$,rows:A,cwd:this.projectPath,pid:f.pid})}catch(D){throw this.logger.error("Failed to create PTY session",D),new pL(`Failed to create PTY session: ${D instanceof Error?D.message:String(D)}`)}}getSession(H){let $=this.sessions.get(H);if($)return $.session.lastActivityAt=new Date,$.pty;return null}writeToSession(H,$){let A=this.sessions.get(H);if(!A)return!1;try{return A.pty.write($),!0}catch(L){return this.logger.debug("PTY write failed (session may be closing)",{sessionId:H,error:L instanceof Error?L.message:String(L)}),!1}}setupDataHandler(H,$){let A=this.sessions.get(H);if(A)A.dataHandler=$,A.pty.onData((L)=>{let D=this.sessions.get(H);if(!D)return;if(D.disconnectedAt){if(D.outputBuffer.reduce((E,I)=>E+I.length,0)<YN)D.outputBuffer.push(L)}else D.dataHandler?.(L)})}updateDataHandler(H,$){let A=this.sessions.get(H);if(A)A.dataHandler=$}disconnectSession(H){let $=this.sessions.get(H);if($){if($.disconnectTimeout)clearTimeout($.disconnectTimeout);$.disconnectedAt=new Date,$.outputBuffer=[],$.disconnectTimeout=setTimeout(()=>{this.logger.debug(`Session timeout - closing: ${H}`),this.closeSession(H)},vN),this.logger.debug(`PTY session disconnected: ${H}`)}}resumeSession(H,$,A){let L=this.sessions.get(H);if(!L)return this.logger.warn(`Cannot resume - session not found: ${H}`),null;if(L.disconnectTimeout)clearTimeout(L.disconnectTimeout),L.disconnectTimeout=void 0;L.disconnectedAt=void 0,L.session.lastActivityAt=new Date;try{L.pty.resize($,A)}catch(f){this.logger.debug(`Resize on resume failed: ${H}`,{error:f})}let D=L.outputBuffer;return L.outputBuffer=[],this.logger.debug(`PTY session resumed: ${H}`),D}canResumeSession(H){return this.sessions.get(H)!==void 0}findSessionByCwd(H){for(let[$,A]of this.sessions.entries())if(A.cwd===H)return $;return null}getSessionInfo(H){let $=this.sessions.get(H);if(!$)return null;return{id:H,cwd:$.cwd,disconnected:!!$.disconnectedAt,createdAt:$.session.createdAt}}closeSession(H){let $=this.sessions.get(H);if($){if($.disconnectTimeout)clearTimeout($.disconnectTimeout);this.sessions.delete(H);try{$.pty.kill(),this.logger.debug(`PTY session closed: ${H}`)}catch(A){this.logger.debug(`PTY cleanup (may be expected): ${H}`,{error:A instanceof Error?A.message:String(A)})}}}closeAllSessions(){for(let H of this.sessions.keys())this.closeSession(H)}setProjectPath(H){this.projectPath=H,this.logger.debug(`Terminal project path set to: ${H}`)}getActiveSessionCount(){return this.sessions.size}resizeSession(H,$,A){let L=this.sessions.get(H);if(L)try{L.pty.resize($,A)}catch(D){this.logger.error(`Error resizing session ${H}`,D)}}}function pc(H){return`<!DOCTYPE html>
|
|
2280
|
+
`;j_.parseFont("Standard",V9);function z9(){let _=j_.textSync("ccc",{font:"Standard",horizontalLayout:"default",verticalLayout:"default"});console.log(`
|
|
2281
|
+
`),console.log(_),console.log("Code Chat Connect - v2.0.0"),console.log("Mobile IDE to code on the go!"),console.log(`
|
|
2282
|
+
`)}var JK=v_(EK(),1);import{Duplex as Tj}from"stream";async function LK(_,T,A){let E=null,L=await import("net"),J=new Set;return E=L.createServer((X)=>{A.debug("[MQTT TCP] Client socket connected"),J.add(X);let H=new Tj({read(){},write(Z,Y,K){X.write(Z,Y,K)}});X.on("data",(Z)=>{H.push(Z)}),X.on("end",()=>{H.push(null),J.delete(X)}),X.on("error",(Z)=>{A.debug("[MQTT TCP] Socket error",{error:Z.message}),H.destroy(Z),J.delete(X)}),X.on("close",()=>{J.delete(X)}),H.on("error",(Z)=>{A.debug("[MQTT TCP] Stream error",{error:Z.message}),X.destroy()});try{_.handle(H)}catch(Z){A.error("[MQTT TCP] Error handling connection",{error:Z}),X.destroy()}}),{server:null,tcpServer:E,listen:async(X,H)=>{return new Promise((Z,Y)=>{let K=($)=>{A.error("[MQTT TCP] Server error",{error:$.message,code:$.code,port:X,hostname:H}),Y($)},G=()=>{A.debug("[MQTT TCP] Server listening",{port:X,hostname:H}),E.removeListener("error",K),Z()};E.once("error",K),E.once("listening",G),E.listen(X,H)})},close:async()=>{return new Promise((X)=>{if(E){for(let Z of J)try{Z.destroy()}catch(Y){A.debug("[MQTT TCP] Error destroying socket",{error:Y})}J.clear();let H=setTimeout(()=>{A.warn("[MQTT TCP] Server close timeout, forcing shutdown"),X()},500);E.close(()=>{clearTimeout(H),A.debug("[MQTT] TCP server closed"),X()})}else X()})}}}class mA{servers=null;broker=null;running=!1;startedAt;config;name="CCC MQTT Broker";constructor(_){this.config=_,this.createBrokerInstance()}createBrokerInstance(){this.broker=JK.default({id:"ccc-mqtt-broker",heartbeatInterval:this.config.heartbeatInterval||30000,connectTimeout:this.config.connectTimeout||30000,authenticate:this.authenticate.bind(this)}),this.setupBrokerEvents()}setupBrokerEvents(){let _=v();this.broker.on("client",(T)=>{_.debug("MQTT client connected",{clientId:T.id,clean:T.clean})}),this.broker.on("clientDisconnect",(T)=>{_.debug("MQTT client disconnected",{clientId:T.id})}),this.broker.on("subscribe",(T,A)=>{_.debug("MQTT client subscribed",{clientId:A?.id,topics:T.map((E)=>E.topic)})}),this.broker.on("unsubscribe",(T,A)=>{_.debug("MQTT client unsubscribed",{clientId:A?.id,topics:T})}),this.broker.on("publish",(T,A)=>{if(A)_.debug("MQTT message published",{clientId:A.id,topic:T.topic,qos:T.qos,size:T.payload?.length||0})}),this.broker.on("clientError",(T,A)=>{_.error("MQTT client error",{clientId:T?.id,error:A.message})}),this.broker.on("connectionError",(T,A)=>{_.error("MQTT connection error",{clientId:T?.id,error:A.message})})}async start(){try{let _=v();this.servers=await LK(this.broker,{port:this.config.port,hostname:"localhost"},_),await this.servers.listen(this.config.port,"localhost"),this.running=!0,this.startedAt=new Date,_.debug("MQTT Broker started (TCP only)",{tcpPort:this.config.port,protocols:["mqtt/tcp"]})}catch(_){throw new v8(`Failed to start MQTT broker: ${_ instanceof Error?_.message:String(_)}`)}}async stop(){try{let _=v();if(!this.running)return;if(_.debug("Stopping MQTT Broker"),this.broker?.clients)for(let T of Object.keys(this.broker.clients)){let A=this.broker.clients[T];try{A.close()}catch(E){_.debug("Error closing MQTT client",{clientId:T,error:E})}}if(this.servers)try{await this.servers.close()}catch(T){_.error("Error closing servers",{error:T})}try{await new Promise((T)=>{let A=setTimeout(()=>{_.debug("MQTT broker close timeout, forcing shutdown"),T()},1000);if(this.broker)this.broker.close(()=>{clearTimeout(A),_.debug("MQTT broker closed"),T()});else clearTimeout(A),T()})}catch(T){_.error("Error closing MQTT broker",{error:T})}this.running=!1,_.info("\u2713 MQTT Broker stopped")}catch(_){throw this.running=!1,new v8(`Failed to stop MQTT broker: ${_ instanceof Error?_.message:String(_)}`)}}getStatus(){return{name:"MQTT Broker",running:this.running,port:this.config.port,startedAt:this.startedAt,clientCount:this.broker?.clients?Object.keys(this.broker.clients).length:0}}authenticate(_,T,A,E){let L=v();if(!this.config.auth){L.debug("No authentication configured, allowing MQTT connection",{clientId:_.id}),E(null,!0);return}let J=A?.toString();if(T===this.config.auth.username&&J===this.config.auth.password)L.debug("MQTT client authenticated successfully",{clientId:_.id,username:T}),E(null,!0);else L.warn("MQTT client authentication failed",{clientId:_.id,username:T}),E(Error("Invalid credentials"),!1)}}var dU=v_(uU(),1);var I1=v();class K5{name="Backend MQTT Client";client=null;running=!1;connected=!1;startedAt;config;subscriptions=new Map;constructor(_){this.config=_}async start(){return new Promise((_,T)=>{try{let A=`mqtt://${this.config.host}:${this.config.port}`;this.client=dU.default.connect(A,{clientId:"backend-client",clean:!0,connectTimeout:5000,username:this.config.username,password:this.config.password}),this.client.on("connect",()=>{this.connected=!0,this.running=!0,this.startedAt=new Date,I1.info("[BackendClient] Connected to MQTT broker"),_()}),this.client.on("error",(E)=>{if(I1.error("[BackendClient] MQTT error",{error:E.message}),!this.connected)T(E)}),this.client.on("close",()=>{this.connected=!1,I1.debug("[BackendClient] Disconnected from MQTT broker")}),this.client.on("message",(E,L)=>{this.handleMessage(E,L)})}catch(A){I1.error("[BackendClient] Failed to start",A),T(A)}})}async stop(){return new Promise((_)=>{if(!this.client){this.running=!1,_();return}this.client.end(!1,{},()=>{this.running=!1,this.connected=!1,this.subscriptions.clear(),I1.info("[BackendClient] Stopped"),_()})})}subscribe(_,T){if(!this.client)throw Error("MQTT client not initialized");if(!this.subscriptions.has(_))this.subscriptions.set(_,new Set),this.client.subscribe(_,{qos:1},(A)=>{if(A)I1.error(`[BackendClient] Failed to subscribe to ${_}`,{error:A.message});else I1.debug(`[BackendClient] Subscribed to ${_}`)});this.subscriptions.get(_).add(T)}unsubscribe(_,T){if(!this.client)return;let A=this.subscriptions.get(_);if(!A)return;if(A.delete(T),A.size===0)this.subscriptions.delete(_),this.client.unsubscribe(_,(E)=>{if(E)I1.error(`[BackendClient] Failed to unsubscribe from ${_}`,{error:E.message});else I1.debug(`[BackendClient] Unsubscribed from ${_}`)})}publish(_,T,A){return new Promise((E,L)=>{if(!this.client){L(Error("MQTT client not initialized"));return}this.client.publish(_,T,{qos:A?.qos||1},(J)=>{if(J)I1.error(`[BackendClient] Failed to publish to ${_}`,{error:J.message}),L(J);else I1.debug(`[BackendClient] Published to ${_}`),E()})})}topicToRegex(_){let T=_.replace(/[.\\^${}|[\]()]/g,"\\$&").replace(/\+/g,"[^/]+").replace(/#/g,".*");return new RegExp(`^${T}$`)}handleMessage(_,T){this.subscriptions.forEach((A,E)=>{if(this.topicToRegex(E).test(_))A.forEach((J)=>{try{J(_,T)}catch(X){I1.error(`[BackendClient] Error in message handler for ${_}`,{error:X instanceof Error?X.message:"Unknown error"})}})})}getStatus(){return{name:this.name,running:this.running,connected:this.connected,startedAt:this.startedAt}}}var cU=5,Gh=900000;class pL{credentials;failedAttempts=new Map;blockedIPs=new Map;logger=v();constructor(){this.credentials=this.generateCredentials(),this.logger.debug("Terminal credentials generated",{username:this.credentials.username})}getCredentials(){return this.credentials}authenticate(_,T,A){let E=this.blockedIPs.get(A);if(E&&E>Date.now())throw new h8("IP temporarily blocked due to too many failed attempts");if(_===this.credentials.username&&T===this.credentials.password)return this.failedAttempts.delete(A),this.blockedIPs.delete(A),!0;let L=(this.failedAttempts.get(A)||0)+1;if(this.failedAttempts.set(A,L),L>=cU)this.blockedIPs.set(A,Date.now()+Gh),this.failedAttempts.delete(A),this.logger.warn(`IP blocked after ${cU} failed attempts`,{ip:A});throw new h8("Invalid credentials")}generateCredentials(){let _=this.generateRandomString(32),T=this.generateRandomString(480);return{username:_,password:T}}generateRandomString(_){let A="",E=new Uint8Array(_);crypto.getRandomValues(E);for(let L=0;L<_;L++){let J=E[L]??0;A+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;,.<>?"[J%87]}return A}}import{spawn as $h}from"bun-pty";var pU=5,Uh=300000,Wh=102400;class lL{sessions=new Map;projectPath=process.cwd();logger=v();createSession(_,T=80,A=24){if(Array.from(this.sessions.values()).filter((L)=>!L.disconnectedAt).length>=pU)throw new XT(`Maximum concurrent sessions (${pU}) reached`);try{let L=process.platform==="win32"?"powershell.exe":"bash",J=$h(L,[],{name:"xterm-256color",cols:T,rows:A,cwd:this.projectPath,env:process.env}),X={id:_,createdAt:new Date,lastActivityAt:new Date};this.sessions.set(_,{pty:J,session:X,cwd:this.projectPath,outputBuffer:[]}),this.logger.debug(`PTY session created: ${_}`,{cols:T,rows:A,cwd:this.projectPath,pid:J.pid})}catch(L){throw this.logger.error("Failed to create PTY session",L),new XT(`Failed to create PTY session: ${L instanceof Error?L.message:String(L)}`)}}getSession(_){let T=this.sessions.get(_);if(T)return T.session.lastActivityAt=new Date,T.pty;return null}writeToSession(_,T){let A=this.sessions.get(_);if(!A)return!1;try{return A.pty.write(T),!0}catch(E){return this.logger.debug("PTY write failed (session may be closing)",{sessionId:_,error:E instanceof Error?E.message:String(E)}),!1}}setupDataHandler(_,T){let A=this.sessions.get(_);if(A)A.dataHandler=T,A.pty.onData((E)=>{let L=this.sessions.get(_);if(!L)return;if(L.disconnectedAt){if(L.outputBuffer.reduce((X,H)=>X+H.length,0)<Wh)L.outputBuffer.push(E)}else L.dataHandler?.(E)})}updateDataHandler(_,T){let A=this.sessions.get(_);if(A)A.dataHandler=T}disconnectSession(_){let T=this.sessions.get(_);if(T){if(T.disconnectTimeout)clearTimeout(T.disconnectTimeout);T.disconnectedAt=new Date,T.outputBuffer=[],T.disconnectTimeout=setTimeout(()=>{this.logger.debug(`Session timeout - closing: ${_}`),this.closeSession(_)},Uh),this.logger.debug(`PTY session disconnected: ${_}`)}}resumeSession(_,T,A){let E=this.sessions.get(_);if(!E)return this.logger.warn(`Cannot resume - session not found: ${_}`),null;if(E.disconnectTimeout)clearTimeout(E.disconnectTimeout),E.disconnectTimeout=void 0;E.disconnectedAt=void 0,E.session.lastActivityAt=new Date;try{E.pty.resize(T,A)}catch(J){this.logger.debug(`Resize on resume failed: ${_}`,{error:J})}let L=E.outputBuffer;return E.outputBuffer=[],this.logger.debug(`PTY session resumed: ${_}`),L}canResumeSession(_){return this.sessions.get(_)!==void 0}findSessionByCwd(_){for(let[T,A]of this.sessions.entries())if(A.cwd===_)return T;return null}getSessionInfo(_){let T=this.sessions.get(_);if(!T)return null;return{id:_,cwd:T.cwd,disconnected:!!T.disconnectedAt,createdAt:T.session.createdAt}}closeSession(_){let T=this.sessions.get(_);if(T){if(T.disconnectTimeout)clearTimeout(T.disconnectTimeout);this.sessions.delete(_);try{T.pty.kill(),this.logger.debug(`PTY session closed: ${_}`)}catch(A){this.logger.debug(`PTY cleanup (may be expected): ${_}`,{error:A instanceof Error?A.message:String(A)})}}}closeAllSessions(){for(let _ of this.sessions.keys())this.closeSession(_)}setProjectPath(_){this.projectPath=_,this.logger.debug(`Terminal project path set to: ${_}`)}getActiveSessionCount(){return this.sessions.size}resizeSession(_,T,A){let E=this.sessions.get(_);if(E)try{E.pty.resize(T,A)}catch(L){this.logger.error(`Error resizing session ${_}`,L)}}}function lU(_){return`<!DOCTYPE html>
|
|
2283
2283
|
<html lang="en">
|
|
2284
2284
|
<head>
|
|
2285
2285
|
<meta charset="UTF-8">
|
|
@@ -2605,36 +2605,36 @@ Font modified May 20, 2012 by patorjk to add the 0xCA0 character
|
|
|
2605
2605
|
})();
|
|
2606
2606
|
</script>
|
|
2607
2607
|
</body>
|
|
2608
|
-
</html>`}class
|
|
2609
|
-
`)}else this.logger.debug(`Session not found for resume: ${
|
|
2608
|
+
</html>`}class G5{server=null;authenticator;ptyManager;running=!1;startedAt;config;logger=v();sessionMap=new Map;name="CCC Terminal Service";constructor(_){this.config=_,this.authenticator=new pL,this.ptyManager=new lL}async start(){try{this.server=Bun.serve({hostname:"localhost",port:this.config.port,fetch:(_,T)=>this.handleRequest(_,T),websocket:{open:(_)=>this.handleWebSocketOpen(_),message:(_,T)=>this.handleWebSocketMessage(_,T),close:(_)=>this.handleWebSocketClose(_)}}),this.running=!0,this.startedAt=new Date,this.logger.debug(`Terminal Server started on localhost:${this.config.port}`)}catch(_){throw new XT(`Failed to start terminal server: ${_ instanceof Error?_.message:String(_)}`)}}async stop(){try{if(!this.running)return;if(this.ptyManager.closeAllSessions(),this.server)this.server.stop();this.running=!1,this.logger.debug("Terminal Server stopped")}catch(_){throw new XT(`Failed to stop terminal server: ${_ instanceof Error?_.message:String(_)}`)}}getStatus(){return{name:"Terminal Server",running:this.running,port:this.config.port,startedAt:this.startedAt,credentials:this.authenticator.getCredentials(),activeSessions:this.ptyManager.getActiveSessionCount()}}setProjectPath(_){this.ptyManager.setProjectPath(_)}findSessionByProjectPath(_){return this.ptyManager.findSessionByCwd(_)}getSessionInfo(_){return this.ptyManager.getSessionInfo(_)}authenticateRequest(_){let T=new URL(_.url),A="unknown",E=T.searchParams.get("auth");if(E)try{let J=Buffer.from(E,"base64").toString("utf-8"),X=J.indexOf(":");if(X===-1)return this.logger.debug("Auth param missing colon delimiter"),!1;let H=J.substring(0,X),Z=J.substring(X+1);return this.logger.debug("Auth via query param",{username:H.substring(0,8)+"..."}),this.authenticator.authenticate(H,Z,"unknown")}catch(J){return this.logger.debug("Auth param error",{error:String(J)}),!1}let L=_.headers.get("authorization");if(L?.startsWith("Basic "))try{let J=L.slice(6),X=Buffer.from(J,"base64").toString("utf-8"),H=X.indexOf(":");if(H===-1)return this.logger.debug("Auth header missing colon delimiter"),!1;let Z=X.substring(0,H),Y=X.substring(H+1);return this.logger.debug("Auth via header",{username:Z.substring(0,8)+"..."}),this.authenticator.authenticate(Z,Y,"unknown")}catch(J){return this.logger.debug("Auth header error",{error:String(J)}),!1}return this.logger.debug("No auth credentials provided",{hasAuthParam:!!E,hasAuthHeader:!!L}),!1}handleRequest(_,T){let A=new URL(_.url);if(A.pathname==="/terminal/ws"||A.pathname==="/terminal"){if(_.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!this.authenticateRequest(_))return new Response("Unauthorized",{status:401});if(T.upgrade(_,{data:{type:"terminal-ws",url:A.toString(),authenticated:!0}}))return new Response;return new Response("WebSocket upgrade failed",{status:400})}}if(A.pathname==="/terminal"&&_.method==="GET"){if(!this.authenticateRequest(_))return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":'Basic realm="Terminal"',"Content-Type":"text/plain"}});let E=this.authenticator.getCredentials(),L=lU(E);return new Response(L,{headers:{"Content-Type":"text/html; charset=utf-8","Content-Length":Buffer.byteLength(L).toString(),"Cache-Control":"no-cache, no-store, must-revalidate"}})}return new Response("Not Found",{status:404})}handleWebSocketOpen(_){this.logger.debug("WebSocket connection opened (authenticated)")}handleWebSocketMessage(_,T){try{let A;if(typeof T==="string")A=T;else if(T instanceof ArrayBuffer)A=new TextDecoder().decode(T);else if(T instanceof Uint8Array)A=new TextDecoder().decode(T);else return;let E=this.sessionMap.get(_);if(A.startsWith("INIT:")||A.startsWith("RESIZE:")||A.startsWith("RESUME:")){let L=A.startsWith("INIT:")?"INIT:":A.startsWith("RESUME:")?"RESUME:":"RESIZE:",J=JSON.parse(A.substring(L.length)),{cols:X,rows:H,cwd:Z,sessionId:Y}=J;if(!X||!H){this.logger.warn("Invalid dimensions received",{cols:X,rows:H});return}if(L==="RESUME:"&&Y){if(this.ptyManager.canResumeSession(Y)){this.logger.debug(`Resuming session: ${Y}`),this.sessionMap.set(_,Y),this.ptyManager.updateDataHandler(Y,(G)=>{try{if(_.readyState===1)_.send(G)}catch($){}});let K=this.ptyManager.resumeSession(Y,X,H);if(_.send(`SESSION:${Y}`),K&&K.length>0)for(let G of K)try{if(_.readyState===1)_.send(G)}catch($){break}_.send(`\x1B[38;5;209m\u2713 Session resumed\x1B[0m\r
|
|
2609
|
+
`)}else this.logger.debug(`Session not found for resume: ${Y}`),_.send("SESSION_NOT_FOUND");return}if(!E&&L==="INIT:"){if(Z)this.ptyManager.setProjectPath(Z),this.logger.debug(`Terminal working directory set to: ${Z}`);let K=crypto.randomUUID();this.ptyManager.createSession(K,X,H),this.sessionMap.set(_,K),this.ptyManager.setupDataHandler(K,(G)=>{try{if(_.readyState===1)_.send(G)}catch($){}}),_.send(`SESSION:${K}`),_.send(`\x1B[38;5;209m\u2713 Connected to CCC Terminal\x1B[0m\r
|
|
2610
2610
|
\r
|
|
2611
|
-
`)}else if(L
|
|
2612
|
-
`)}),
|
|
2613
|
-
`),this.config.mdnsUrl)this.displayQRCode(this.config.mdnsUrl,this.config.username,this.config.password,!1,this.config.profileName),this.codesGenerated++,console.log("");if(this.config.ipBasedUrl&&this.config.ipBasedUrl!==this.config.mdnsUrl)this.displayQRCode(this.config.ipBasedUrl,this.config.username,this.config.password,!1,this.config.profileName),this.codesGenerated++,console.log("");if(this.config.ngrokUrl)this.displayQRCode(this.config.ngrokUrl,this.config.username,this.config.password,!0,this.config.profileName),this.codesGenerated++,console.log("");if(this.codesGenerated===0)
|
|
2614
|
-
`)}catch(
|
|
2615
|
-
`),
|
|
2616
|
-
`).filter((
|
|
2617
|
-
`),
|
|
2618
|
-
`),D=null,f=0,E=0;for(let r of L){if(!r.trim())continue;try{let F=JSON.parse(r);E++;let N=null;if(F.type==="assistant"){if(F.message?.usage)N=F.message.usage;else if(F.usage)N=F.usage}if(F.type==="result"&&F.usage)N=F.usage;if(N&&(N.input_tokens!==void 0||N.output_tokens!==void 0))D=N,f++}catch{continue}}if(SH.debug("[SessionManager] Context calculation stats:",{sessionFile:$$.basename(H),totalMessages:E,messagesWithUsage:f,hasUsage:!!D,mostRecentUsage:D?{input:D.input_tokens,output:D.output_tokens,cacheCreate:D.cache_creation_input_tokens,cacheRead:D.cache_read_input_tokens}:null}),!D)return SH.warn("[SessionManager] No usage data found in session file:",H),this.getEmptyContextBreakdown();let I=D.input_tokens||0,P=D.output_tokens||0,T=D.cache_creation_input_tokens||0,U=D.cache_read_input_tokens||0,M=I+T+U,t=X$.SYSTEM_PROMPT,_=X$.TOOLS_TOTAL,x=0,V=X$.AUTOCOMPACT_BUFFER,h=Math.max(0,M-t-_-x),W=M+V,c=X$.CONTEXT_LIMIT_STANDARD;return SH.info("[SessionManager] Context breakdown calculated:",{total:W,apiTokens:M,inputTokens:I,cacheCreation:T,cacheRead:U,percentage:Math.round(W/c*100),breakdown:{systemPrompt:t,tools:_,mcpServers:x,messages:h,autocompactBuffer:V,remaining:Math.max(0,c-W)}}),{total:W,inputTokens:I,outputTokens:P,cacheCreation:T,cacheRead:U,systemPrompt:t,tools:_,mcpServers:x,messages:h,autocompactBuffer:V,contextLimit:c,remaining:Math.max(0,c-W),percentage:Math.round(W/c*100),lastUpdated:Date.now()}}catch($){return SH.error("[SessionManager] Error calculating context breakdown:",$),this.getEmptyContextBreakdown()}}getEmptyContextBreakdown(){let H=X$.SYSTEM_PROMPT+X$.TOOLS_TOTAL+X$.AUTOCOMPACT_BUFFER;return{total:H,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:X$.SYSTEM_PROMPT,tools:X$.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:X$.AUTOCOMPACT_BUFFER,contextLimit:X$.CONTEXT_LIMIT_STANDARD,remaining:X$.CONTEXT_LIMIT_STANDARD-H,percentage:Math.round(H/X$.CONTEXT_LIMIT_STANDARD*100),lastUpdated:Date.now()}}}var QL=new EX;var PH=l(),$6="worktrees";class SU{watches=new Map;registeredProjects=[];mqttClient;claudeProjectsDir;cccDir;constructor(H){this.mqttClient=H,this.claudeProjectsDir=KL(PX(),".claude","projects"),this.cccDir=KL(PX(),".ccc")}getWorktreePathsForProject(H){let $=H6(H),A=KL(this.cccDir,`${$}-${$6}`);if(!z7(A))return[];try{let L=Z7(A,{withFileTypes:!0}),D=[];for(let f of L)if(f.isDirectory()){let E=KL(A,f.name);D.push(E)}return D}catch(L){return PH.warn("[SessionWatcher] Error reading worktrees directory:",L),[]}}sanitizeProjectPath(H){let $=H.replace(/[\\/]+$/,"");return $=$.replace(/:[\\/]+/g,"--"),$=$.replace(/:/g,"--"),$=$.replace(/[\\/]+/g,"-"),$=$.replace(/\./g,"-"),$=$.replace(/_/g,"-"),$}async registerProjects(H){PH.info(`[SessionWatcher] Registering ${H.length} projects`),this.registeredProjects=H,this.stopAll();for(let $ of H)await this.fetchAndPublishLatestSession($.id,$.directory_path),await this.watchProject($.id,$.directory_path);PH.info(`[SessionWatcher] Now watching ${this.watches.size} projects`)}async fetchAndPublishLatestSession(H,$){try{let A=await QL.getLatestSession($),D=(await import("fs")).existsSync($);if(A)PH.info(`[SessionWatcher] Found latest session for project ${H}: ${A.sessionId} (${A.title})`),this.publishSessionUpdate(H,A,D);else PH.debug(`[SessionWatcher] No sessions found for project ${H}`),this.publishSessionUpdate(H,null,D)}catch(A){PH.error(`[SessionWatcher] Error fetching latest session for project ${H}:`,A),this.publishSessionUpdate(H,null,!0)}}async watchProject(H,$){try{let A=!0;try{await IX($)}catch{PH.warn(`[SessionWatcher] Project directory not found: ${$}`),A=!1}let L={projectId:H,directoryPath:$,mainWatcher:null,worktreeWatchers:[],pathExists:A};this.watches.set(H,L);let D=KL(this.claudeProjectsDir,this.sanitizeProjectPath($));PH.debug(`[SessionWatcher] Main sessions dir: ${$} \u2192 ${D}`);let f=await this.setupDirectoryWatcher(H,D,A);if(f)L.mainWatcher=f,PH.info(`[SessionWatcher] Started watching main sessions: ${D}`);let E=this.getWorktreePathsForProject($);PH.debug(`[SessionWatcher] Found ${E.length} worktrees for project ${H}`);for(let P of E){let T=KL(this.claudeProjectsDir,this.sanitizeProjectPath(P)),U=await this.setupDirectoryWatcher(H,T,A);if(U)L.worktreeWatchers.push({path:T,watcher:U}),PH.info(`[SessionWatcher] Started watching worktree sessions: ${T}`)}this.watches.set(H,L);let I=(L.mainWatcher?1:0)+L.worktreeWatchers.length;PH.info(`[SessionWatcher] Project ${H}: watching ${I} directories`)}catch(A){PH.error(`[SessionWatcher] Error watching project ${H}:`,A)}}async setupDirectoryWatcher(H,$,A){try{await IX($)}catch{return PH.debug(`[SessionWatcher] Sessions directory not found: ${$}`),null}return q7($,{recursive:!0},async(D,f)=>{if(!f||!f.endsWith(".jsonl"))return;PH.debug(`[SessionWatcher] File ${D} detected in project ${H}: ${f}`),await this.handleSessionChange(H,$,A)})}async handleSessionChange(H,$,A=!0){try{let L=this.watches.get(H);if(!L){PH.warn(`[SessionWatcher] No watch found for project ${H}`);return}let D=await QL.getLatestSession(L.directoryPath);if(D)PH.debug(`[SessionWatcher] Session change for project ${H}: ${D.sessionId}`),this.publishSessionUpdate(H,D,A);else PH.debug(`[SessionWatcher] No sessions found for project ${H}`),this.publishSessionUpdate(H,null,A)}catch(L){PH.error(`[SessionWatcher] Error handling session change for project ${H}:`,L)}}publishSessionUpdate(H,$,A=!0){if(!this.mqttClient){PH.warn("[SessionWatcher] MQTT client not available");return}let L=`sessions/update/${H}`,D=JSON.stringify($?{...$,pathExists:A}:{pathExists:A});this.mqttClient.publish(L,D).catch((f)=>{PH.error(`[SessionWatcher] Failed to publish to ${L}`,{error:f.message})}),PH.debug(`[SessionWatcher] Published update to ${L}: ${$?.sessionId||"null"}, pathExists: ${A}`)}stopProject(H){let $=this.watches.get(H);if($){if($.mainWatcher)$.mainWatcher.close();for(let L of $.worktreeWatchers)L.watcher.close();this.watches.delete(H);let A=($.mainWatcher?1:0)+$.worktreeWatchers.length;PH.info(`[SessionWatcher] Stopped watching project ${H} (${A} watchers closed)`)}}stopAll(){PH.info(`[SessionWatcher] Stopping all watches (${this.watches.size} projects)`);for(let[H]of this.watches)this.stopProject(H)}async resumeAll(){if(this.registeredProjects.length===0){PH.debug("[SessionWatcher] No registered projects to resume");return}PH.info(`[SessionWatcher] Resuming watches for ${this.registeredProjects.length} projects`);for(let H of this.registeredProjects)await this.watchProject(H.id,H.directory_path);PH.info(`[SessionWatcher] Resumed ${this.watches.size} watches`)}async notifySessionCreated(H,$){let A=null;for(let L of this.registeredProjects)if(L.directory_path===H){A=L.id;break}if(!A){PH.warn(`[SessionWatcher] notifySessionCreated - project not registered: ${H}`);return}PH.info(`[SessionWatcher] Session created notification for project ${A}`,{projectPath:H,workingDirectory:$}),await new Promise((L)=>setTimeout(L,500)),await this.fetchAndPublishLatestSession(A,H),await this.ensureWatcherForPath(A,$)}async ensureWatcherForPath(H,$){let A=this.watches.get(H);if(!A){PH.warn(`[SessionWatcher] Cannot ensure watcher - project not in watches: ${H}`);return}let L=KL(this.claudeProjectsDir,this.sanitizeProjectPath($));if($===A.directoryPath){if(A.mainWatcher){PH.debug(`[SessionWatcher] Main watcher already exists for project ${H}`);return}let f=await this.setupDirectoryWatcher(H,L,A.pathExists);if(f)A.mainWatcher=f,PH.info(`[SessionWatcher] Added main watcher for project ${H}: ${L}`)}else{if(A.worktreeWatchers.find((I)=>I.path===L)){PH.debug(`[SessionWatcher] Worktree watcher already exists: ${L}`);return}let E=await this.setupDirectoryWatcher(H,L,A.pathExists);if(E)A.worktreeWatchers.push({path:L,watcher:E}),PH.info(`[SessionWatcher] Added worktree watcher for project ${H}: ${L}`)}}}var _H=l();class kE{name="Sessions Service";running=!1;startedAt;mqttClient=null;watcher;claudeAgentService=null;constructor(){}setMQTTClient(H){this.mqttClient=H,this.watcher=new SU(H)}setClaudeAgentService(H){this.claudeAgentService=H}async notifySessionCreated(H,$){if(this.watcher)await this.watcher.notifySessionCreated(H,$);this.broadcastActiveSessionCounts()}notifySessionStopped(){this.broadcastActiveSessionCounts()}broadcastActiveSessionCounts(){if(!this.mqttClient||!this.claudeAgentService)return;let H=this.claudeAgentService.getActiveSessions(),$={activeSessions:H,timestamp:Date.now()};this.mqttClient.publish("sessions/active/broadcast",JSON.stringify($)),_H.debug(`[Sessions] Broadcast ${H.length} active sessions to all clients`)}async start(){try{if(this.running=!0,this.startedAt=new Date,_H.info("[Sessions] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(H){throw _H.error("[Sessions] Failed to start",H),this.running=!1,H}}async stop(){if(this.running=!1,this.watcher)this.watcher.stopAll();_H.info("[Sessions] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("projects/register",(H,$)=>{this.handleProjectRegistration(H,$)}),this.mqttClient.subscribe("app/lifecycle",(H,$)=>{this.handleAppLifecycle(H,$)}),this.mqttClient.subscribe("sessions/list/request",(H,$)=>{this.handleSessionListRequest(H,$)}),this.mqttClient.subscribe("sessions/messages/request",(H,$)=>{this.handleSessionMessagesRequest(H,$)}),this.mqttClient.subscribe("sessions/latest/request",(H,$)=>{this.handleLatestSessionsRequest(H,$)}),this.mqttClient.subscribe("sessions/active/request",(H,$)=>{this.handleActiveSessionsRequest(H,$)}),_H.info("[Sessions] MQTT handlers registered for projects/register, app/lifecycle, sessions/list, sessions/messages, sessions/latest, sessions/active")}async handleProjectRegistration(H,$){try{let A=JSON.parse($.toString()),L=A.projects;if(!Array.isArray(L)){_H.warn("[Sessions] Invalid projects payload:",A);return}if(_H.info(`[Sessions] Received registration for ${L.length} projects`),this.watcher)await this.watcher.registerProjects(L)}catch(A){_H.error("[Sessions] Error handling project registration:",A)}}async handleAppLifecycle(H,$){try{let L=JSON.parse($.toString()).state;if(_H.info(`[Sessions] App lifecycle changed to: ${L}`),L==="background"||L==="terminated"){if(this.watcher)this.watcher.stopAll(),_H.info(`[Sessions] Stopped all watchers (app state: ${L})`)}else if(L==="active"){if(this.watcher)await this.watcher.resumeAll(),_H.info(`[Sessions] Resumed all watchers (app state: ${L})`)}}catch(A){_H.error("[Sessions] Error handling app lifecycle:",A)}}async handleSessionListRequest(H,$){try{let A=JSON.parse($.toString()),{projectPath:L,clientId:D,timestamp:f}=A;if(!L||!D){_H.warn("[Sessions] Invalid session list request:",A);return}_H.info(`[Sessions] Session list request from ${D} for ${L}`);let E=await QL.listSessions(L),I=this.claudeAgentService?.getActiveSessions()||[],P=new Map(I.filter((t)=>t.projectPath===L).map((t)=>[t.sessionId,{status:t.status,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch}])),U={sessions:E.sessions.map((t)=>{let _=P.get(t.sessionId);return{...t,status:_?.status,worktreePath:_?.worktreePath||t.worktreePath,worktreeBranch:_?.worktreeBranch||t.worktreeBranch}}),projectPath:E.projectPath,pathExists:E.pathExists,timestamp:Date.now()},M=`sessions/list/${D}/response`;await this.mqttClient?.publish(M,JSON.stringify(U)),_H.info(`[Sessions] Sent ${E.sessions.length} sessions to ${D}`)}catch(A){_H.error("[Sessions] Error handling session list request:",A)}}async handleSessionMessagesRequest(H,$){try{let A=JSON.parse($.toString()),{projectPath:L,sessionId:D,lastKnownUuid:f,limit:E=50,clientId:I,timestamp:P}=A;if(!L||!D||!I){_H.warn("[Sessions] Invalid session messages request:",A);return}_H.info(`[Sessions] Messages request from ${I} for session ${D}${f?` (from ${f})`:""}`);let T=await QL.getSessionMessages(L,D,f,E),U={...T,timestamp:Date.now()},M=`sessions/messages/${I}/response`;await this.mqttClient?.publish(M,JSON.stringify(U)),_H.info(`[Sessions] Sent ${T.messages.length} messages to ${I} (hasMore: ${T.hasMore})`)}catch(A){_H.error("[Sessions] Error handling session messages request:",A)}}async handleLatestSessionsRequest(H,$){try{let A=JSON.parse($.toString()),{projectPaths:L,clientId:D,timestamp:f}=A;if(!Array.isArray(L)||!D){_H.warn("[Sessions] Invalid latest sessions request:",A);return}_H.info(`[Sessions] Latest sessions request from ${D} for ${L.length} projects`);let E=await QL.getLatestSessions(L),I={projects:E,timestamp:Date.now()},P=`sessions/latest/${D}/response`;await this.mqttClient?.publish(P,JSON.stringify(I)),_H.info(`[Sessions] Sent latest sessions for ${E.length} projects to ${D}`)}catch(A){_H.error("[Sessions] Error handling latest sessions request:",A)}}async handleActiveSessionsRequest(H,$){try{let A=JSON.parse($.toString()),{clientId:L,timestamp:D}=A;if(!L){_H.warn("[Sessions] Invalid active sessions request:",A);return}_H.info(`[Sessions] Active sessions request from ${L}`);let f=this.claudeAgentService?.getActiveSessions()||[],E={activeSessions:f,timestamp:Date.now()},I=`sessions/active/${L}/response`;await this.mqttClient?.publish(I,JSON.stringify(E)),_H.info(`[Sessions] Sent ${f.length} active sessions to ${L}`)}catch(A){_H.error("[Sessions] Error handling active sessions request:",A)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt}}}import TX from"os";var I$=l(),A6="1.0.0";class RE{name="System Info Service";running=!1;startedAt;mqttClient=null;requestsHandled=0;messageHandler;versionCheckHandler;constructor(){}setMQTTClient(H){this.mqttClient=H}async start(){try{if(this.running=!0,this.startedAt=new Date,I$.info("[SystemInfo] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(H){throw I$.error("[SystemInfo] Failed to start",H),this.running=!1,H}}async stop(){if(this.running=!1,this.mqttClient){if(this.messageHandler)this.mqttClient.unsubscribe("system/os-info/request",this.messageHandler),I$.debug("[SystemInfo] Unsubscribed from system/os-info/request"),this.messageHandler=void 0;if(this.versionCheckHandler)this.mqttClient.unsubscribe("version/check/request",this.versionCheckHandler),I$.debug("[SystemInfo] Unsubscribed from version/check/request"),this.versionCheckHandler=void 0}I$.info("[SystemInfo] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(H,$)=>{this.handleSystemInfoRequest(H,$)},this.mqttClient.subscribe("system/os-info/request",this.messageHandler),I$.info("[SystemInfo] MQTT handler registered for system/os-info/request"),this.versionCheckHandler=(H,$)=>{this.handleVersionCheckRequest(H,$)},this.mqttClient.subscribe("version/check/request",this.versionCheckHandler),I$.info("[SystemInfo] MQTT handler registered for version/check/request")}async handleSystemInfoRequest(H,$){try{let A=JSON.parse($.toString());I$.debug("[SystemInfo] Received system info request",{clientId:A.clientId});let L=TX.platform(),D=TX.homedir(),f;if(L==="win32")f=`${D}\\projects\\my-project`;else if(L==="darwin")f=`${D}/projects/my-project`;else f=`${D}/projects/my-project`;let E=`system/os-info/${A.clientId}/response`,I={platform:L,homedir:D,suggestedPath:f,timestamp:Date.now()};if(this.mqttClient)await this.mqttClient.publish(E,JSON.stringify(I),{qos:1}),this.requestsHandled++,I$.debug("[SystemInfo] Sent system info response",{clientId:A.clientId,platform:L,responseTopic:E});else I$.error("[SystemInfo] MQTT client not available for publishing")}catch(A){I$.error("[SystemInfo] Error handling system info request",{error:A instanceof Error?A.message:"Unknown error"})}}async handleVersionCheckRequest(H,$){try{let A=JSON.parse($.toString());I$.debug("[SystemInfo] Received version check request",{clientId:A.clientId,appVersion:A.appVersion,platform:A.platform});let L=gA(),D=JL(L),f={backendVersion:L,latestBackendVersion:L,backendUpdateAvailable:!1,backendChannel:D==="beta"?"beta":"latest",minAppVersion:A6,currentAppVersion:A.appVersion,updateRequired:!1,updateAvailable:!1,timestamp:Date.now()},E=`version/check/${A.clientId}/response`;if(this.mqttClient)await this.mqttClient.publish(E,JSON.stringify(f),{qos:1}),this.requestsHandled++,I$.debug("[SystemInfo] Sent version check response",{clientId:A.clientId,backendVersion:L,responseTopic:E});else I$.error("[SystemInfo] MQTT client not available for publishing version response")}catch(A){I$.error("[SystemInfo] Error handling version check request",{error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}}var FA=l();class OE{name="Terminal Config Service";running=!1;startedAt;mqttClient=null;terminalServer;requestsHandled=0;messageHandler;constructor(H){this.terminalServer=H}setMQTTClient(H){this.mqttClient=H}async start(){try{if(this.running=!0,this.startedAt=new Date,FA.info("[TerminalConfig] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(H){throw FA.error("[TerminalConfig] Failed to start",H),this.running=!1,H}}async stop(){if(this.running=!1,this.mqttClient&&this.messageHandler)this.mqttClient.unsubscribe("system/terminal-config/request",this.messageHandler),FA.debug("[TerminalConfig] Unsubscribed from system/terminal-config/request"),this.messageHandler=void 0;FA.info("[TerminalConfig] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(H,$)=>{this.handleTerminalConfigRequest(H,$)},this.mqttClient.subscribe("system/terminal-config/request",this.messageHandler),FA.info("[TerminalConfig] MQTT handler registered for system/terminal-config/request")}async handleTerminalConfigRequest(H,$){try{let A=JSON.parse($.toString());FA.debug("[TerminalConfig] Received terminal config request",{clientId:A.clientId,projectPath:A.projectPath});let L=this.terminalServer.getStatus(),D;if(A.projectPath){let I=this.terminalServer.findSessionByProjectPath(A.projectPath);if(I)D=I,FA.debug("[TerminalConfig] Found existing session for project",{projectPath:A.projectPath,sessionId:I})}let f={enabled:L.running,path:"/terminal",port:L.port,username:L.credentials?.username||"",password:L.credentials?.password||"",timestamp:Date.now(),existingSessionId:D},E=`system/terminal-config/${A.clientId}/response`;if(this.mqttClient)await this.mqttClient.publish(E,JSON.stringify(f),{qos:1}),this.requestsHandled++,FA.debug("[TerminalConfig] Sent terminal config response",{clientId:A.clientId,enabled:f.enabled,port:f.port,responseTopic:E});else FA.error("[TerminalConfig] MQTT client not available for publishing")}catch(A){FA.error("[TerminalConfig] Error handling terminal config request",{error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}}import kX from"path";var AA={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};var z=l();class rU{sessions=new Map;tempSessions=new Map;config;callbacks;resolvedClaudePath=null;constructor(H,$={}){this.config=H,this.callbacks=$}async resolveClaudePath(){if(this.resolvedClaudePath)return this.resolvedClaudePath;if(process.platform==="win32"&&process.env.APPDATA){let H=`${process.env.APPDATA}\\npm\\claude.cmd`;try{if(await Bun.file(H).exists())return this.resolvedClaudePath=H,z.info(`[ClaudeProcessManager] Using claude at ${H}`),H}catch($){z.debug(`[ClaudeProcessManager] claude.cmd not found at ${H}`)}}try{if(await Bun.spawn(["claude","--version"],{stdout:"pipe",stderr:"pipe"}).exited===0)return this.resolvedClaudePath="claude",z.info("[ClaudeProcessManager] Found claude in PATH"),"claude"}catch(H){z.debug("[ClaudeProcessManager] claude not found in PATH")}return z.warn("[ClaudeProcessManager] Claude CLI not found. Please install: npm install -g @anthropic-ai/claude-code"),this.resolvedClaudePath="claude","claude"}async spawnSession(H,$,A,L,D,f,E,I,P){if(z.info(`[ClaudeProcessManager] Spawning session for project ${A} in ${L}`,{resumeSessionId:f||"new session",permissionMode:E||"default",selectedModel:I||"sonnet"}),this.sessions.size+this.tempSessions.size>=this.config.maxConcurrentSessions)throw Error("Maximum concurrent sessions reached");let T=this.config.claudeCodePath||await this.resolveClaudePath(),t=["-p","--output-format","stream-json","--input-format","stream-json","--permission-prompt-tool","stdio","--permission-mode",E||"default","--model",I||"sonnet","--verbose"];if(f)t.push("--resume",f),z.info(`[ClaudeProcessManager] Resuming session: ${f}`);z.info(`[ClaudeProcessManager] Spawning: ${T} ${t.join(" ")}`,{cwd:L,claudePath:T});try{if((await Bun.$`test -d ${L}`.quiet().nothrow()).exitCode!==0){if(z.info(`[ClaudeProcessManager] Directory does not exist, creating: ${L}`),(await Bun.$`mkdir -p ${L}`.quiet().nothrow()).exitCode!==0)throw Error(`Failed to create directory: ${L}`);z.info(`[ClaudeProcessManager] Directory created successfully: ${L}`)}}catch(V){throw z.error(`[ClaudeProcessManager] Failed to ensure directory exists: ${L}`,{error:V}),Error(`Cannot start session: failed to create directory ${L}`)}let _=Bun.spawn([T,...t],{cwd:L,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:{...process.env,CI:"1",CLAUDE_HEADLESS:"1"}}),x={tempId:H,userId:$,projectId:A,directoryPath:L,process:_,status:"initializing",permissionMode:E||"default",createdAt:new Date,lastActivity:new Date,messageCount:0};return this.tempSessions.set(H,x),this.setupProcessHandlers(x,_),setTimeout(()=>{this.sendUserMessage(x,D,P)},100),x}setupProcessHandlers(H,$){let{tempId:A}=H;this.readStdoutLines($.stdout,H),this.readStderrLines($.stderr,H),$.exited.then((L)=>{z.info("[ClaudeProcessManager] Claude process exited",{tempId:A,sessionId:H.sessionId,exitCode:L});let D=`exited with code ${L}`;this.handleSessionStopped(H,D)}).catch((L)=>{z.error("[ClaudeProcessManager] Claude process error:",{tempId:A,sessionId:H.sessionId,error:L.message}),this.handleSessionError(H,L.message)})}readStdoutLines(H,$){(async()=>{try{let A=H.pipeThrough(new TextDecoderStream).getReader(),L="";while(!0){let{done:D,value:f}=await A.read();if(D)break;L+=f;let E=L.split(`
|
|
2619
|
-
`);
|
|
2620
|
-
`);
|
|
2621
|
-
`);if(!A?.content||!Array.isArray(A.content)||A.content.length===0)return
|
|
2622
|
-
`;
|
|
2623
|
-
`;A.process.stdin.write(
|
|
2624
|
-
`).filter((
|
|
2625
|
-
`).filter((
|
|
2626
|
-
`))if(
|
|
2627
|
-
`)){if(!
|
|
2628
|
-
`);if(
|
|
2629
|
-
`),isBinary:!1}}}}}return{diff:
|
|
2630
|
-
`),
|
|
2631
|
-
`).filter((
|
|
2632
|
-
`),
|
|
2633
|
-
`),
|
|
2634
|
-
`).trim(),
|
|
2635
|
-
`)){if(!
|
|
2636
|
-
`)){if(!
|
|
2637
|
-
`).filter((
|
|
2638
|
-
`).map((D)=>D.trim()).filter((D)=>D&&!D.includes("HEAD")&&!D.includes("->")).map((D)=>D.replace(/^origin\//,"")),L=await FU(H);return{branches:A,defaultBranch:L}}catch($){return VH.error("[GitExecutor] Failed to get remote branches",{error:$,path:H}),{branches:[],defaultBranch:null}}}import*as A$ from"path";import*as FH from"fs";import*as CU from"os";var pH=l();function CD(H){return A$.normalize(H).toLowerCase()}var M6="worktrees",t6="sessions";function sU(){return A$.join(CU.homedir(),".ccc",t6)}function _6(){let H=new Date,$=H.getFullYear(),A=String(H.getMonth()+1).padStart(2,"0"),L=String(H.getDate()).padStart(2,"0"),D=String(H.getHours()).padStart(2,"0"),f=String(H.getMinutes()).padStart(2,"0");return`${$}${A}${L}-${D}${f}`}class iD{worktreeCache=new Map;saveSessionMapping(H,$){try{let A=sU();if(!FH.existsSync(A))FH.mkdirSync(A,{recursive:!0});let L=A$.join(A,H);FH.writeFileSync(L,$,"utf-8"),pH.debug("[WorktreeManager] Saved session mapping",{sessionId:H,worktreePath:$})}catch(A){pH.error("[WorktreeManager] Failed to save session mapping",{error:A,sessionId:H,worktreePath:$})}}loadSessionMapping(H){try{let $=A$.join(sU(),H);if(FH.existsSync($)){let A=FH.readFileSync($,"utf-8").trim();if(FH.existsSync(A))return A;else FH.unlinkSync($),pH.debug("[WorktreeManager] Removed stale session mapping",{sessionId:H,worktreePath:A})}}catch($){pH.error("[WorktreeManager] Failed to load session mapping",{error:$,sessionId:H})}return null}deleteSessionMapping(H){try{let $=A$.join(sU(),H);if(FH.existsSync($))FH.unlinkSync($),pH.debug("[WorktreeManager] Deleted session mapping",{sessionId:H})}catch($){pH.error("[WorktreeManager] Failed to delete session mapping",{error:$,sessionId:H})}}getWorktreesBasePath(H){let $=A$.basename(H),A=A$.join(CU.homedir(),".ccc");return A$.join(A,`${$}-${M6}`)}getWorktreePath(H,$){let A=this.getWorktreesBasePath(H),L=$.replace(/[^a-zA-Z0-9_-]/g,"_");return A$.join(A,L)}generateBranchName(H){return`session/${H.replace(/[^a-zA-Z0-9_-]/g,"_")}`}async getOrCreateForSession(H,$){pH.debug("[WorktreeManager] getOrCreateForSession",{sessionId:H,repoPath:$});let A=this.worktreeCache.get(H);if(A)if(FH.existsSync(A.path))return pH.debug("[WorktreeManager] Returning cached worktree",{sessionId:H,path:A.path}),{worktree:A,isNew:!1};else this.worktreeCache.delete(H);let L=this.loadSessionMapping(H);if(L&&FH.existsSync(L)){let x=await sA($);if(x){let V=await Qf(x),h=CD(L),W=V.find((c)=>CD(c.path)===h);if(W)return W.sessionId=H,this.worktreeCache.set(H,W),pH.debug("[WorktreeManager] Found worktree from session mapping",{sessionId:H,path:L}),{worktree:W,isNew:!1};else pH.warn("[WorktreeManager] Worktree path exists on disk but not found in git worktree list",{mappedWorktreePath:L})}}if(!await FD($))throw Error(`Not a git repository: ${$}`);let f=await sA($);if(!f)throw Error(`Could not determine repository root for: ${$}`);let E=await wE(f,H);if(E)return E.sessionId=H,this.worktreeCache.set(H,E),this.saveSessionMapping(H,E.path),pH.debug("[WorktreeManager] Found existing worktree (legacy)",{sessionId:H,path:E.path}),{worktree:E,isNew:!1};let I=this.getWorktreePath(f,H);if(FH.existsSync(I)){pH.warn("[WorktreeManager] Worktree path exists but not in git worktree list",{expectedPath:I});let x=await Qf(f),V=CD(I),h=x.find((W)=>CD(W.path)===V);if(h)return h.sessionId=H,this.worktreeCache.set(H,h),{worktree:h,isNew:!1}}let P=_6(),T=this.getWorktreesBasePath(f),U=A$.join(T,P),M=`session/${P}`,t=0;while(FH.existsSync(U)){t++;let x=`${P}-${t}`;U=A$.join(T,x),M=`session/${x}`}if(!FH.existsSync(T))FH.mkdirSync(T,{recursive:!0}),pH.debug("[WorktreeManager] Created worktrees base directory",{basePath:T});let _=await xX(f,U,M);return _.sessionId=H,this.saveSessionMapping(H,U),this.worktreeCache.set(H,_),pH.info("[WorktreeManager] Created new worktree",{sessionId:H,worktreeName:A$.basename(U),path:_.path,branch:_.branch}),{worktree:_,isNew:!0}}async getWorktreeForSession(H,$){pH.debug("[WorktreeManager] getWorktreeForSession",{sessionId:H,repoPath:$});let A=this.worktreeCache.get(H);if(A)if(FH.existsSync(A.path))return A;else this.worktreeCache.delete(H);let L=await sA($);if(!L)return null;let D=await wE(L,H);if(D)D.sessionId=H,this.worktreeCache.set(H,D);return D}async listWorktreesForRepo(H){pH.debug("[WorktreeManager] listWorktreesForRepo",{repoPath:H});let $=await sA(H);if(!$)throw Error(`Could not determine repository root for: ${H}`);let A=await Qf($);for(let L of A)if(!L.isMain)if(L.branch?.startsWith("session/"))L.sessionId=L.branch.substring(8);else{let D=this.getWorktreesBasePath($);if(CD(L.path).startsWith(CD(D))){let f=A$.basename(L.path);L.sessionId=f}}for(let L of A)if(L.sessionId)this.worktreeCache.set(L.sessionId,L);return A}getActiveWorktreeCount(){return this.worktreeCache.size}clearCache(){this.worktreeCache.clear()}removeFromCache(H){this.worktreeCache.delete(H)}updateSessionId(H,$,A){try{this.deleteSessionMapping($),this.saveSessionMapping(A,H);let L=this.worktreeCache.get($);if(L)this.worktreeCache.delete($),L.sessionId=A,this.worktreeCache.set(A,L);pH.info("[WorktreeManager] Updated session ID mapping",{worktreePath:H,oldSessionId:$,newSessionId:A})}catch(L){pH.error("[WorktreeManager] Failed to update session ID",{error:L,worktreePath:H,oldSessionId:$,newSessionId:A})}}async renameWorktreeForSession(H,$,A){pH.info("[WorktreeManager] Renaming worktree for session",{oldSessionId:H,newSessionId:$,repoPath:A});try{let L=await sA(A);if(!L)return pH.error("[WorktreeManager] Could not determine repo root for rename"),null;let D=this.worktreeCache.get(H);if(!D){if(pH.warn("[WorktreeManager] No cached worktree found for old session ID",{oldSessionId:H}),!await wE(L,H))return pH.error("[WorktreeManager] Could not find worktree for old session ID"),null}let f=this.getWorktreePath(L,H),E=this.getWorktreePath(L,$),I=this.generateBranchName(H),P=this.generateBranchName($);if(!FH.existsSync(f))return pH.warn("[WorktreeManager] Old worktree path does not exist",{oldPath:f}),null;if(FH.existsSync(E)){pH.warn("[WorktreeManager] New worktree path already exists",{newPath:E});let U={path:E,branch:P,head:D?.head||"",sessionId:$,isMain:!1};return this.worktreeCache.delete(H),this.worktreeCache.set($,U),U}await BX(L,f,E),pH.debug("[WorktreeManager] Moved worktree",{from:f,to:E}),await rX(E,I,P),pH.debug("[WorktreeManager] Renamed branch",{from:I,to:P}),this.worktreeCache.delete(H);let T={path:E,branch:P,head:D?.head||"",sessionId:$,isMain:!1,createdAt:D?.createdAt};return this.worktreeCache.set($,T),pH.info("[WorktreeManager] Successfully renamed worktree",{oldSessionId:H,newSessionId:$,oldPath:f,newPath:E,oldBranch:I,newBranch:P}),T}catch(L){return pH.error("[WorktreeManager] Failed to rename worktree",{error:L,oldSessionId:H,newSessionId:$}),null}}}import*as iU from"path";import*as bX from"os";var b$=l(),eE=iU.join(bX.homedir(),".ccc"),yX=iU.join(eE,"pending-permissions.json");class NX{cache=null;async ensureDirectory(){try{let H=await import("fs");if(!H.existsSync(eE))H.mkdirSync(eE,{recursive:!0}),b$.debug("[PendingPermissions] Created .ccc directory:",eE)}catch(H){throw b$.error("[PendingPermissions] Error ensuring directory:",H),H}}async load(){if(this.cache)return this.cache;try{let H=Bun.file(yX);if(await H.exists()){let $=await H.text();return this.cache=JSON.parse($),b$.debug("[PendingPermissions] Loaded permissions:",{count:this.cache?.permissions?.length||0}),this.cache}}catch(H){b$.warn("[PendingPermissions] Error loading, starting fresh:",H)}return this.cache={permissions:[],lastUpdated:new Date().toISOString()},this.cache}async save(H){try{await this.ensureDirectory(),H.lastUpdated=new Date().toISOString(),await Bun.write(yX,JSON.stringify(H,null,2)),this.cache=H,b$.debug("[PendingPermissions] Saved permissions:",{count:H.permissions.length})}catch($){throw b$.error("[PendingPermissions] Error saving:",$),$}}async addPermission(H){let $=await this.load(),A=$.permissions.findIndex((L)=>L.requestId===H.requestId);if(A>=0)$.permissions[A]=H,b$.debug("[PendingPermissions] Updated existing permission:",{requestId:H.requestId,sessionId:H.sessionId});else $.permissions.push(H),b$.info("[PendingPermissions] Added new pending permission:",{requestId:H.requestId,sessionId:H.sessionId,action:H.action});await this.save($)}async removePermission(H){let $=await this.load(),A=$.permissions.length;if($.permissions=$.permissions.filter((L)=>L.requestId!==H),$.permissions.length<A)return await this.save($),b$.info("[PendingPermissions] Removed permission:",{requestId:H}),!0;return!1}async removePermissionsForSession(H){let $=await this.load(),A=$.permissions.length;$.permissions=$.permissions.filter((D)=>D.sessionId!==H);let L=A-$.permissions.length;if(L>0)await this.save($),b$.info("[PendingPermissions] Removed permissions for session:",{sessionId:H,removedCount:L});return L}async getPermissionsForSession(H){return(await this.load()).permissions.filter((A)=>A.sessionId===H)}async getPermissionsForProject(H){return(await this.load()).permissions.filter((A)=>A.projectPath===H)}async getAllPermissions(){return(await this.load()).permissions}async getPermission(H){return(await this.load()).permissions.find((A)=>A.requestId===H)}async clearAll(){this.cache={permissions:[],lastUpdated:new Date().toISOString()},await this.save(this.cache),b$.info("[PendingPermissions] Cleared all pending permissions")}clearCache(){this.cache=null,b$.debug("[PendingPermissions] Cleared cache")}}var tL=new NX;var O=l();class jE{name="Claude Agent Service";running=!1;startedAt;mqttClient=null;sessionsService=null;processManager;worktreeManager;config;totalSessionsCreated=0;totalMessagesProcessed=0;pendingPermissions=new Map;cleanupInterval;constructor(H){this.config=H,this.worktreeManager=new iD,this.processManager=new rU(H,{onSessionInitialized:this.handleSessionInitialized.bind(this),onTitleGenerated:this.handleTitleGenerated.bind(this),onAssistantMessage:this.handleAssistantMessage.bind(this),onPermissionRequest:this.handlePermissionRequest.bind(this),onSessionError:this.handleSessionError.bind(this),onSessionStopped:this.handleSessionStopped.bind(this),onProcessingStarted:this.handleProcessingStarted.bind(this),onProcessingComplete:this.handleProcessingComplete.bind(this),onContextUpdate:this.handleContextUpdate.bind(this)})}async determineWorkingDirectory(H,$,A){try{if(!await FD($))return O.debug("[ClaudeAgent] Not a git repo, using project path",{projectId:H,directoryPath:$}),{path:$,isWorktree:!1};let D=await sA($);if(!D)return O.warn("[ClaudeAgent] Could not determine repo root, using project path",{directoryPath:$}),{path:$,isWorktree:!1};O.info("[ClaudeAgent] Git repo detected, creating worktree",{projectId:H,sessionId:A,repoRoot:D});let{worktree:f,isNew:E}=await this.worktreeManager.getOrCreateForSession(A,D);return O.info("[ClaudeAgent] Worktree ready",{sessionId:A,worktreePath:f.path,branch:f.branch,isNew:E}),{path:f.path,isWorktree:!0,branch:f.branch}}catch(L){return O.error("[ClaudeAgent] Worktree creation failed, falling back to project path",{projectId:H,sessionId:A,error:L instanceof Error?L.message:"Unknown error"}),{path:$,isWorktree:!1}}}setMQTTClient(H){this.mqttClient=H}setSessionsService(H){this.sessionsService=H}async start(){try{if(this.running=!0,this.startedAt=new Date,O.info("[ClaudeAgent] Service started"),this.mqttClient)this.registerMQTTHandlers();else O.warn("[ClaudeAgent] MQTT client not set - handlers will not be registered");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions()},300000),O.info("[ClaudeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions,sessionTimeoutMs:this.config.sessionTimeoutMs})}catch(H){throw O.error("[ClaudeAgent] Failed to start",H),this.running=!1,H}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval);this.processManager.stopAll(),O.info("[ClaudeAgent] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("claude/+/session/start",(H,$)=>{let A=this.extractUserIdFromTopic(H);this.handleSessionStart(A,H,$)}),this.mqttClient.subscribe("claude/+/input/+",(H,$)=>{let{userId:A,sessionId:L}=this.extractIdsFromInputTopic(H);this.handleUserInput(A,L,H,$)}),this.mqttClient.subscribe("claude/+/permission/response/+",(H,$)=>{let{userId:A,sessionId:L}=this.extractIdsFromPermissionTopic(H);this.handlePermissionResponse(A,L,H,$)}),this.mqttClient.subscribe("claude/+/session/stop/+",(H,$)=>{let{userId:A,sessionId:L}=this.extractIdsFromStopTopic(H);this.handleSessionStop(A,L)}),this.mqttClient.subscribe("permissions/pending/request",(H,$)=>{this.handlePendingPermissionsRequest(H,$)}),O.info("[ClaudeAgent] MQTT handlers registered")}async handleSessionStart(H,$,A){try{let L=JSON.parse(A.toString());O.info("[ClaudeAgent] Session start request:",{userId:H,tempId:L.tempId,projectId:L.projectId,directoryPath:L.directoryPath,permissionMode:L.permissionMode,selectedModel:L.selectedModel,hasAttachments:!!L.attachments,attachmentCount:L.attachments?.length||0});let{path:D,isWorktree:f,branch:E}=await this.determineWorkingDirectory(L.projectId,L.directoryPath,L.tempId),I=await this.processManager.spawnSession(L.tempId,H,L.projectId,D,L.initialMessage||"",void 0,L.permissionMode,L.selectedModel,L.attachments);if(f)I.directoryPath=L.directoryPath,I.worktreePath=D,I.worktreeBranch=E;this.totalSessionsCreated++,O.info("[ClaudeAgent] Session spawned successfully:",{userId:H,tempId:L.tempId,projectId:L.projectId,workingPath:D,isWorktree:f})}catch(L){O.error("[ClaudeAgent] Error starting session:",{userId:H,error:L instanceof Error?L.message:"Unknown error"}),this.publishStatus(H,"temp_error",{type:"error",error:L instanceof Error?L.message:"Failed to start session",timestamp:Date.now()})}}async handleUserInput(H,$,A,L){try{let D=JSON.parse(L.toString());if(!D.message&&(!D.attachments||D.attachments.length===0)){O.warn("[ClaudeAgent] Received request without message or attachments:",{userId:H,sessionId:D.sessionId,hasAttachments:!!D.attachments});return}O.info("[ClaudeAgent] User input:",{userId:H,sessionId:D.sessionId,messageLength:D.message?.length||0,permissionMode:D.permissionMode,selectedModel:D.selectedModel,hasAttachments:!!D.attachments,attachmentCount:D.attachments?.length||0,allSessions:this.processManager.getAllSessions().map((P)=>({tempId:P.tempId,sessionId:P.sessionId,status:P.status}))});let f=this.processManager.getSession(D.sessionId);if(!f){O.warn("[ClaudeAgent] Session not found, creating new session:",{userId:H,requestedSessionId:D.sessionId,projectId:D.projectId,availableSessions:this.processManager.getAllSessions().map((T)=>T.sessionId||T.tempId)});let P=D.sessionId&&!D.sessionId.startsWith("temp_")&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(D.sessionId);try{let{path:T,isWorktree:U,branch:M}=await this.determineWorkingDirectory(D.projectId,D.directoryPath,D.sessionId);if(f=await this.processManager.spawnSession(D.sessionId,H,D.projectId,T,D.message||"",P?D.sessionId:void 0,D.permissionMode,D.selectedModel,D.attachments),U)f.directoryPath=D.directoryPath,f.worktreePath=T,f.worktreeBranch=M;this.totalSessionsCreated++,O.info(`[ClaudeAgent] Session ${P?"resumed":"created"} successfully:`,{userId:H,sessionId:D.sessionId,isResume:P,workingPath:T,isWorktree:U}),this.totalMessagesProcessed++;return}catch(T){O.error("[ClaudeAgent] Failed to create session:",{userId:H,sessionId:D.sessionId,error:T instanceof Error?T.message:"Unknown error"}),this.publishStatus(H,D.sessionId,{type:"error",error:"Failed to create session",timestamp:Date.now()});return}}let E=f.permissionMode||"default",I=D.permissionMode||"default";if(I!==E&&f.sessionId)if(O.info("[ClaudeAgent] Permission mode changed, respawning session:",{userId:H,sessionId:f.sessionId,currentMode:E,requestedMode:I}),await this.processManager.respawnWithPermissionMode(f.sessionId,I,D.message||"proceed with implementation")){this.publishStatus(H,f.sessionId,{type:"session_restarted",permissionMode:I,timestamp:Date.now()}),this.totalMessagesProcessed++;return}else O.error("[ClaudeAgent] Failed to respawn session with new permission mode");this.processManager.sendUserMessage(f,D.message||"",D.attachments),this.totalMessagesProcessed++}catch(D){O.error("[ClaudeAgent] Error handling user input:",{userId:H,sessionId:$,error:D instanceof Error?D.message:"Unknown error"})}}async handlePermissionResponse(H,$,A,L){try{let D=JSON.parse(L.toString());O.info("[ClaudeAgent] Permission response:",{userId:H,sessionId:$,requestId:D.requestId,approved:D.approved,hasAnswers:!!D.answers,addToAllowedTools:D.addToAllowedTools,toolPattern:D.toolPattern,permissionMode:D.permissionMode,hardDeny:D.hardDeny,hasDenyMessage:!!D.denyMessage});let f=this.pendingPermissions.get(D.requestId);if(!f)O.warn(`[ClaudeAgent] No pending permission found for request_id: ${D.requestId}`);if(D.approved&&D.addToAllowedTools){let I=this.processManager.getSession($);if(I){let P=D.toolPattern||(f?this.generateToolPattern(f.action,f.params):null);if(P)await this.addToAllowedTools(I.directoryPath,P),O.info("[ClaudeAgent] Added tool pattern to settings.local.json:",{toolPattern:P,projectPath:I.directoryPath})}}let E=this.processManager.getSession($);if(D.permissionMode&&E?.sessionId){if(O.info("[ClaudeAgent] Permission mode change requested, will respawn session:",{sessionId:E.sessionId,newPermissionMode:D.permissionMode}),this.processManager.sendPermissionResponse($,{request_id:D.requestId,behavior:"allow",updatedInput:f?.params,message:"Permission mode is changing. Stopping current execution for session respawn."}),await new Promise((P)=>setTimeout(P,200)),await this.processManager.respawnWithPermissionMode(E.sessionId,D.permissionMode,"proceed with implementation"))this.publishStatus(E.userId,E.sessionId,{type:"session_restarted",permissionMode:D.permissionMode,timestamp:Date.now()});else this.publishStatus(E.userId,E.sessionId,{type:"error",error:"Failed to respawn session with new permission mode",timestamp:Date.now()});if(f)this.pendingPermissions.delete(D.requestId);tL.removePermission(D.requestId).catch((P)=>{O.error("[ClaudeAgent] Failed to remove pending permission from storage:",P)});return}if(D.approved&&D.answers&&Object.keys(D.answers).length>0){let I={...f?.params,answers:D.answers};O.info("[ClaudeAgent] Sending AskUserQuestion response:",{requestId:D.requestId,answerCount:Object.keys(D.answers).length}),this.processManager.sendPermissionResponse($,{request_id:D.requestId,behavior:"allow",updatedInput:I})}else if(D.approved)this.processManager.sendPermissionResponse($,{request_id:D.requestId,behavior:"allow",updatedInput:f?f.params:void 0});else{let I=D.denyMessage||"Permission denied by user",P=D.hardDeny!==!1;if(O.info("[ClaudeAgent] Sending deny response:",{requestId:D.requestId,hardDeny:P,hasDenyMessage:!!D.denyMessage}),this.processManager.sendPermissionResponse($,{request_id:D.requestId,behavior:"deny",message:I,hardDeny:P}),P)O.info("[ClaudeAgent] Hard deny - stopping session:",{sessionId:$}),setTimeout(()=>{this.processManager.stopSession($),this.publishStatus(H,$,{type:"session_stopped",reason:"permission_denied",message:I,timestamp:Date.now()})},100)}if(f)this.pendingPermissions.delete(D.requestId);tL.removePermission(D.requestId).catch((I)=>{O.error("[ClaudeAgent] Failed to remove pending permission from storage:",I)})}catch(D){O.error("[ClaudeAgent] Error handling permission response:",{userId:H,sessionId:$,error:D instanceof Error?D.message:"Unknown error"})}}handleSessionStop(H,$){O.info("[ClaudeAgent] Session stop request:",{userId:H,sessionId:$}),this.processManager.stopSession($)}async handlePendingPermissionsRequest(H,$){try{let A=JSON.parse($.toString()),{clientId:L,sessionId:D,projectPath:f}=A;if(!L){O.warn("[ClaudeAgent] Pending permissions request missing clientId");return}O.info("[ClaudeAgent] Pending permissions request:",{clientId:L,sessionId:D,projectPath:f});let E;if(D)E=await tL.getPermissionsForSession(D);else if(f)E=await tL.getPermissionsForProject(f);else E=await tL.getAllPermissions();let I=this.processManager.getAllSessions(),P=new Set(I.filter((t)=>t.status==="waiting_permission"&&t.sessionId).map((t)=>t.sessionId)),T=E.filter((t)=>P.has(t.sessionId)),U=`permissions/pending/${L}/response`,M={permissions:T,timestamp:Date.now()};await this.mqttClient?.publish(U,JSON.stringify(M)),O.info("[ClaudeAgent] Sent pending permissions response:",{clientId:L,count:T.length,totalStored:E.length})}catch(A){O.error("[ClaudeAgent] Error handling pending permissions request:",A)}}handleSessionInitialized(H,$){if(O.info("[ClaudeAgent] Session initialized callback:",{tempId:H.tempId,sessionId:H.sessionId,model:H.model}),H.worktreePath&&H.tempId&&H.sessionId)this.worktreeManager.updateSessionId(H.worktreePath,H.tempId,H.sessionId);if(this.publishStatus(H.userId,H.sessionId,{type:"session_started",sessionId:H.sessionId,tempId:H.tempId,model:H.model,worktreePath:H.worktreePath,worktreeBranch:H.worktreeBranch,timestamp:Date.now()}),this.sessionsService){let A=H.worktreePath||H.directoryPath;this.sessionsService.notifySessionCreated(H.directoryPath,A).catch((L)=>{O.warn("[ClaudeAgent] Failed to notify sessions service about new session",{error:L})})}}handleTitleGenerated(H,$){O.info("[ClaudeAgent] Title generated callback:",{sessionId:H.sessionId,title:$}),this.publishStatus(H.userId,H.sessionId,{type:"title_generated",title:$,timestamp:Date.now()})}handleAssistantMessage(H,$){if(this.totalMessagesProcessed++,H.sessionId)this.publishOutput(H.userId,H.sessionId,$)}handlePermissionRequest(H,$){if(O.info("[ClaudeAgent] Permission request callback:",{sessionId:H.sessionId,requestId:$.request_id,action:$.action}),H.sessionId)this.publishPermissionRequest(H,$)}handleSessionError(H,$){O.error("[ClaudeAgent] Session error callback:",{sessionId:H.sessionId,tempId:H.tempId,error:$}),this.publishStatus(H.userId,H.sessionId||H.tempId,{type:"error",error:$,timestamp:Date.now()})}handleSessionStopped(H,$){if(O.info("[ClaudeAgent] Session stopped callback:",{sessionId:H.sessionId,tempId:H.tempId,reason:$}),this.publishStatus(H.userId,H.sessionId||H.tempId,{type:"session_stopped",reason:$,timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifySessionStopped()}handleProcessingStarted(H){if(O.info("[ClaudeAgent] Processing started:",{sessionId:H.sessionId,tempId:H.tempId}),H.sessionId)this.publishStatus(H.userId,H.sessionId,{type:"session_processing",sessionId:H.sessionId,timestamp:Date.now()})}handleProcessingComplete(H){if(O.info("[ClaudeAgent] Processing complete:",{sessionId:H.sessionId,tempId:H.tempId}),H.sessionId)this.publishStatus(H.userId,H.sessionId,{type:"session_idle",sessionId:H.sessionId,timestamp:Date.now()})}handleContextUpdate(H,$){if(O.info(`[ClaudeAgent] Context update for session ${H.sessionId}:`,{total:$.total,percentage:$.percentage,inputTokens:$.inputTokens,cacheCreation:$.cacheCreation,cacheRead:$.cacheRead,breakdown:{systemPrompt:$.systemPrompt,tools:$.tools,messages:$.messages,remaining:$.remaining}}),H.sessionId)this.publishContextUpdate(H.userId,H.sessionId,$);else O.warn("[ClaudeAgent] Cannot publish context update - no sessionId yet")}publishStatus(H,$,A){if(!this.mqttClient){O.warn("[ClaudeAgent] Cannot publish status - MQTT client not available");return}let L=`claude/${H}/status/${$}`,D=JSON.stringify(A);this.mqttClient.publish(L,D).catch((f)=>{O.error(`[ClaudeAgent] Failed to publish status to ${L}`,{error:f.message})})}publishOutput(H,$,A){if(!this.mqttClient){O.warn("[ClaudeAgent] Cannot publish output - MQTT client not available");return}let L=`claude/${H}/output/${$}`,D=JSON.stringify(A);this.mqttClient.publish(L,D).catch((f)=>{O.error(`[ClaudeAgent] Failed to publish output to ${L}`,{error:f.message})})}publishContextUpdate(H,$,A){if(!this.mqttClient){O.warn("[ClaudeAgent] Cannot publish context update - MQTT client not available");return}let L=`claude/${H}/context/${$}`,D=JSON.stringify(A);this.mqttClient.publish(L,D).catch((f)=>{O.error(`[ClaudeAgent] Failed to publish context to ${L}`,{error:f.message})})}publishPermissionRequest(H,$){if(!this.mqttClient){O.warn("[ClaudeAgent] Cannot publish permission request - MQTT client not available");return}let{userId:A,sessionId:L}=H;O.info("[ClaudeAgent] Raw permission request structure:",{fullRequest:JSON.stringify($)});let D=$,f=D.request||{},E=f.tool_name||D.tool_name||D.action||"unknown_tool",I=f.input||D.tool_input||D.params||{},P=f.permission_suggestions||[],T=f.decision_reason||"",U=f.blocked_path||"";this.pendingPermissions.set(D.request_id,{requestId:D.request_id,action:E,params:I}),tL.addPermission({requestId:D.request_id,sessionId:L,projectPath:H.directoryPath,action:E,params:I,permissionSuggestions:P.length>0?P:void 0,decisionReason:T||void 0,blockedPath:U||void 0,createdAt:new Date().toISOString()}).catch((x)=>{O.error("[ClaudeAgent] Failed to persist pending permission:",x)});let M={request_id:D.request_id,action:E,params:I,permission_suggestions:P,decision_reason:T,blocked_path:U},t=`claude/${A}/permission/request/${L}`,_=JSON.stringify(M);O.info("[ClaudeAgent] Publishing transformed permission request:",{topic:t,request_id:M.request_id,action:M.action}),this.mqttClient.publish(t,_).catch((x)=>{O.error(`[ClaudeAgent] Failed to publish permission request to ${t}`,{error:x.message})})}extractUserIdFromTopic(H){return H.split("/")[1]||""}extractIdsFromInputTopic(H){let $=H.split("/");return{userId:$[1]||"",sessionId:$[3]||""}}extractIdsFromPermissionTopic(H){let $=H.split("/");return{userId:$[1]||"",sessionId:$[4]||""}}extractIdsFromStopTopic(H){let $=H.split("/");return{userId:$[1]||"",sessionId:$[4]||""}}generateToolPattern(H,$){switch(H){case"Bash":case"bash":case"execute_command":return`Bash(${$.command})`;case"Read":case"read":case"read_file":return`Read(${$.file_path})`;case"Write":case"write":case"write_file":return`Write(${$.file_path})`;case"Edit":case"edit":return`Edit(${$.file_path})`;default:return H}}async addToAllowedTools(H,$){try{let A=kX.join(H,".claude"),L=kX.join(A,"settings.local.json"),D=Bun.file(A);if(!await Bun.$`test -d ${A}`.quiet().nothrow())await Bun.$`mkdir -p ${A}`.quiet();let f={},E=Bun.file(L);if(await E.exists())try{let I=await E.text();f=JSON.parse(I)}catch{f={}}if(f.permissions=f.permissions||{},f.permissions.allow=f.permissions.allow||[],!f.permissions.allow.includes($))f.permissions.allow.push($);await Bun.write(L,JSON.stringify(f,null,2)),O.info("[ClaudeAgent] Updated settings.local.json with allowed tool:",{settingsPath:L,toolPattern:$,totalAllowed:f.permissions.allow.length})}catch(A){O.error("[ClaudeAgent] Failed to update settings.local.json:",{projectPath:H,toolPattern:$,error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.processManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessions(){return this.processManager.getAllSessions().filter((H)=>H.sessionId).map((H)=>({sessionId:H.sessionId,projectPath:H.directoryPath,status:H.status,worktreePath:H.worktreePath,worktreeBranch:H.worktreeBranch}))}}import*as MH from"fs/promises";import*as kH from"path";var vA=l();class JE{validatePath(H,$){try{let A=kH.resolve(H),L=kH.resolve(A,$);if(!(L===A||L.startsWith(A+kH.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};return{valid:!0,fullPath:L}}catch(A){return{valid:!1,fullPath:"",error:`Path validation error: ${A instanceof Error?A.message:"Unknown error"}`}}}async listDirectory(H,$){let A=this.validatePath(H,$);if(!A.valid)return{entries:[],error:A.error};try{if(!(await MH.stat(A.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let D=await MH.readdir(A.fullPath,{withFileTypes:!0}),f=await Promise.all(D.map(async(E)=>{let I=kH.join(A.fullPath,E.name);try{let P=await MH.stat(I);return{name:E.name,type:E.isDirectory()?"directory":"file",size:E.isFile()?P.size:void 0,modified:P.mtime.toISOString()}}catch{return{name:E.name,type:E.isDirectory()?"directory":"file"}}}));return f.sort((E,I)=>{if(E.type!==I.type)return E.type==="directory"?-1:1;return E.name.localeCompare(I.name,void 0,{sensitivity:"base"})}),{entries:f}}catch(L){let D=L instanceof Error?L.message:"Unknown error";return vA.error("[FileManager] listDirectory error",{error:D,path:A.fullPath}),{entries:[],error:`Failed to list directory: ${D}`}}}async readFile(H,$){let A=this.validatePath(H,$);if(!A.valid)return{content:"",size:0,error:A.error};try{let L=await MH.stat(A.fullPath);if(!L.isFile())return{content:"",size:0,error:"Path is not a file"};return{content:await MH.readFile(A.fullPath,"utf-8"),size:L.size}}catch(L){let D=L instanceof Error?L.message:"Unknown error";return vA.error("[FileManager] readFile error",{error:D,path:A.fullPath}),{content:"",size:0,error:`Failed to read file: ${D}`}}}async writeFile(H,$,A){let L=this.validatePath(H,$);if(!L.valid)return{success:!1,error:L.error};try{let D=kH.dirname(L.fullPath);return await MH.mkdir(D,{recursive:!0}),await MH.writeFile(L.fullPath,A,"utf-8"),{success:!0}}catch(D){let f=D instanceof Error?D.message:"Unknown error";return vA.error("[FileManager] writeFile error",{error:f,path:L.fullPath}),{success:!1,error:`Failed to write file: ${f}`}}}async createFile(H,$){let A=this.validatePath(H,$);if(!A.valid)return{success:!1,error:A.error};try{try{return await MH.access(A.fullPath),{success:!1,error:"File already exists"}}catch{}let L=kH.basename($);if(!this.isValidFilename(L))return{success:!1,error:"Invalid filename"};let D=kH.dirname(A.fullPath);return await MH.mkdir(D,{recursive:!0}),await MH.writeFile(A.fullPath,"","utf-8"),{success:!0}}catch(L){let D=L instanceof Error?L.message:"Unknown error";return vA.error("[FileManager] createFile error",{error:D,path:A.fullPath}),{success:!1,error:`Failed to create file: ${D}`}}}async createDirectory(H,$){let A=this.validatePath(H,$);if(!A.valid)return{success:!1,error:A.error};try{let L=kH.basename($);if(!this.isValidFilename(L))return{success:!1,error:"Invalid directory name"};try{if((await MH.stat(A.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await MH.mkdir(A.fullPath,{recursive:!0}),{success:!0}}catch(L){let D=L instanceof Error?L.message:"Unknown error";return vA.error("[FileManager] createDirectory error",{error:D,path:A.fullPath}),{success:!1,error:`Failed to create directory: ${D}`}}}async deleteFile(H,$){let A=this.validatePath(H,$);if(!A.valid)return{success:!1,error:A.error};try{if(!(await MH.stat(A.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await MH.unlink(A.fullPath),{success:!0}}catch(L){let D=L instanceof Error?L.message:"Unknown error";return vA.error("[FileManager] deleteFile error",{error:D,path:A.fullPath}),{success:!1,error:`Failed to delete file: ${D}`}}}async deleteDirectory(H,$){let A=this.validatePath(H,$);if(!A.valid)return{success:!1,error:A.error};if(A.fullPath===kH.resolve(H))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await MH.stat(A.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await MH.rm(A.fullPath,{recursive:!0,force:!0}),{success:!0}}catch(L){let D=L instanceof Error?L.message:"Unknown error";return vA.error("[FileManager] deleteDirectory error",{error:D,path:A.fullPath}),{success:!1,error:`Failed to delete directory: ${D}`}}}async pathExists(H,$){let A=this.validatePath(H,$);if(!A.valid)return!1;try{return await MH.access(A.fullPath),!0}catch{return!1}}async getStats(H,$){let A=this.validatePath(H,$);if(!A.valid)return null;try{let L=await MH.stat(A.fullPath);return{isFile:L.isFile(),isDirectory:L.isDirectory(),size:L.size,modified:L.mtime.toISOString()}}catch{return null}}async readFileBinary(H,$){let A=this.validatePath(H,$);if(!A.valid)return{content:Buffer.alloc(0),size:0,mimeType:"",error:A.error};try{let L=await MH.stat(A.fullPath);if(!L.isFile())return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Path is not a file"};let D=52428800;if(L.size>D)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"File exceeds maximum size of 50MB"};let f=await MH.readFile(A.fullPath),E=this.getMimeType(kH.basename($));return{content:f,size:L.size,mimeType:E}}catch(L){let D=L instanceof Error?L.message:"Unknown error";return vA.error("[FileManager] readFileBinary error",{error:D,path:A.fullPath}),{content:Buffer.alloc(0),size:0,mimeType:"",error:`Failed to read file: ${D}`}}}async writeFileBinary(H,$,A){let L=this.validatePath(H,$);if(!L.valid)return{success:!1,error:L.error};try{let D=kH.basename($);if(!this.isValidFilename(D))return{success:!1,error:"Invalid filename"};let f=kH.dirname(L.fullPath);return await MH.mkdir(f,{recursive:!0}),await MH.writeFile(L.fullPath,A),{success:!0}}catch(D){let f=D instanceof Error?D.message:"Unknown error";return vA.error("[FileManager] writeFileBinary error",{error:f,path:L.fullPath}),{success:!1,error:`Failed to write file: ${f}`}}}getMimeType(H){let $=kH.extname(H).toLowerCase();return{".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".tiff":"image/tiff",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".txt":"text/plain",".json":"application/json",".xml":"application/xml",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".tsx":"application/typescript",".jsx":"application/javascript",".md":"text/markdown",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".7z":"application/x-7z-compressed",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".m4a":"audio/mp4",".flac":"audio/flac",".aac":"audio/aac",".mp4":"video/mp4",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".webm":"video/webm",".wmv":"video/x-ms-wmv",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".apk":"application/vnd.android.package-archive",".ipa":"application/octet-stream",".exe":"application/x-msdownload",".dmg":"application/x-apple-diskimage",".deb":"application/x-deb",".rpm":"application/x-rpm"}[$]||"application/octet-stream"}isValidFilename(H){if(!H||H.length===0)return!1;if(H.includes("/")||H.includes("\\"))return!1;let $=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],A=(H.split(".")[0]||"").toUpperCase();if($.includes(A))return!1;if(/[<>:"|?*\x00-\x1f]/.test(H))return!1;if(H==="."||H==="..")return!1;return!0}}import*as GU from"path";var P$=l(),GD=51200,RX=50;class QE{name="File Browser Service";running=!1;startedAt;mqttClient=null;fileManager;requestsHandled=0;messageHandlers=new Map;fileSaveOperations=new Map;binaryUploadOperations=new Map;constructor(){this.fileManager=new JE}setMQTTClient(H){this.mqttClient=H}async start(){try{if(this.running=!0,this.startedAt=new Date,P$.info("[FileBrowser] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(H){throw P$.error("[FileBrowser] Failed to start",H),this.running=!1,H}}async stop(){if(this.running=!1,this.mqttClient){for(let[H,$]of this.messageHandlers)this.mqttClient.unsubscribe(H,$);this.messageHandlers.clear()}this.fileSaveOperations.clear(),this.binaryUploadOperations.clear(),P$.info("[FileBrowser] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("files/list/request",(H,$)=>{this.handleDirectoryListRequest($)}),this.registerHandler("files/content/request",(H,$)=>{this.handleFileContentRequest($)}),this.registerHandler("files/save/request",(H,$)=>{this.handleFileSaveRequest($)}),this.registerHandler("files/create/request",(H,$)=>{this.handleFileCreateRequest($)}),this.registerHandler("files/delete/request",(H,$)=>{this.handleFileDeleteRequest($)}),this.registerHandler("files/upload/request",(H,$)=>{this.handleBinaryUploadRequest($)}),this.registerHandler("files/download/request",(H,$)=>{this.handleBinaryDownloadRequest($)}),P$.info("[FileBrowser] MQTT handlers registered")}registerHandler(H,$){if(!this.mqttClient)return;this.messageHandlers.set(H,$),this.mqttClient.subscribe(H,$)}async handleDirectoryListRequest(H){try{let $=JSON.parse(H.toString()),A=await this.fileManager.listDirectory($.projectPath,$.relativePath),L={path:$.relativePath,entries:A.entries,timestamp:Date.now(),error:A.error};await this.publishResponse(`files/list/${$.clientId}/response`,L),this.requestsHandled++}catch($){P$.error("[FileBrowser] Error handling directory list request",{error:$ instanceof Error?$.message:"Unknown error"})}}async handleFileContentRequest(H){try{let $=JSON.parse(H.toString()),A=await this.fileManager.readFile($.projectPath,$.relativePath),L=`files/content/${$.clientId}/response`;if(A.error){let f={path:$.relativePath,chunk:{chunkIndex:0,totalChunks:1,content:""},totalSize:0,timestamp:Date.now(),error:A.error};await this.publishResponse(L,f);return}let D=Math.max(1,Math.ceil(A.content.length/GD));for(let f=0;f<D;f++){let E=f*GD,I=Math.min(E+GD,A.content.length),P=A.content.slice(E,I),T={path:$.relativePath,chunk:{chunkIndex:f,totalChunks:D,content:P},totalSize:A.size,timestamp:Date.now()};if(await this.publishResponse(L,T),f<D-1)await this.delay(RX)}this.requestsHandled++}catch($){P$.error("[FileBrowser] Error handling file content request",{error:$ instanceof Error?$.message:"Unknown error"})}}async handleFileSaveRequest(H){try{let $=JSON.parse(H.toString()),A=`${$.clientId}:${$.relativePath}`;if($.chunk.chunkIndex===0)this.fileSaveOperations.set(A,{chunks:new Map,totalChunks:$.chunk.totalChunks,totalSize:$.totalSize});let L=this.fileSaveOperations.get(A);if(!L){await this.sendSaveResponse($,!1,"Save operation not initialized");return}if(L.chunks.set($.chunk.chunkIndex,$.chunk.content),await this.sendSaveResponse($,!0),L.chunks.size===L.totalChunks){let D=[];for(let I=0;I<L.totalChunks;I++){let P=L.chunks.get(I);if(P!==void 0)D.push(P)}let f=D.join(""),E=await this.fileManager.writeFile($.projectPath,$.relativePath,f);if(this.fileSaveOperations.delete(A),!E.error)this.requestsHandled++}}catch($){P$.error("[FileBrowser] Error handling file save request",{error:$ instanceof Error?$.message:"Unknown error"})}}async handleFileCreateRequest(H){try{let $=JSON.parse(H.toString()),A;if($.type==="directory")A=await this.fileManager.createDirectory($.projectPath,$.relativePath);else A=await this.fileManager.createFile($.projectPath,$.relativePath);let L={path:$.relativePath,success:A.success,type:$.type,timestamp:Date.now(),error:A.error};if(await this.publishResponse(`files/create/${$.clientId}/response`,L),A.success)this.requestsHandled++}catch($){P$.error("[FileBrowser] Error handling file create request",{error:$ instanceof Error?$.message:"Unknown error"})}}async handleFileDeleteRequest(H){try{let $=JSON.parse(H.toString()),A=await this.fileManager.getStats($.projectPath,$.relativePath),L;if(!A)L={success:!1,error:"Path does not exist"};else if(A.isDirectory)L=await this.fileManager.deleteDirectory($.projectPath,$.relativePath);else L=await this.fileManager.deleteFile($.projectPath,$.relativePath);let D={path:$.relativePath,success:L.success,timestamp:Date.now(),error:L.error};if(await this.publishResponse(`files/delete/${$.clientId}/response`,D),L.success)this.requestsHandled++}catch($){P$.error("[FileBrowser] Error handling file delete request",{error:$ instanceof Error?$.message:"Unknown error"})}}async sendSaveResponse(H,$,A){let L={path:H.relativePath,success:$,chunkIndex:H.chunk.chunkIndex,totalChunks:H.chunk.totalChunks,timestamp:Date.now(),error:A};await this.publishResponse(`files/save/${H.clientId}/response`,L)}async publishResponse(H,$){if(!this.mqttClient){P$.error("[FileBrowser] MQTT client not available");return}await this.mqttClient.publish(H,JSON.stringify($),{qos:1})}delay(H){return new Promise(($)=>setTimeout($,H))}async handleBinaryUploadRequest(H){try{let $=JSON.parse(H.toString()),A=`${$.clientId}:${$.relativePath}`;if($.chunk.chunkIndex===0){if($.totalSize>52428800){await this.sendBinaryUploadResponse($,!1,"File exceeds 50MB limit",0);return}this.binaryUploadOperations.set(A,{chunks:new Map,totalChunks:$.chunk.totalChunks,totalSize:$.totalSize,filename:$.filename,mimeType:$.mimeType,receivedBytes:0})}let L=this.binaryUploadOperations.get(A);if(!L){await this.sendBinaryUploadResponse($,!1,"Upload operation not initialized",0);return}let D=Buffer.from($.chunk.data,"base64");if(L.chunks.set($.chunk.chunkIndex,D),L.receivedBytes+=D.length,await this.sendBinaryUploadResponse($,!0,void 0,L.receivedBytes),L.chunks.size===L.totalChunks){let f=[];for(let P=0;P<L.totalChunks;P++){let T=L.chunks.get(P);if(T)f.push(T)}let E=Buffer.concat(f),I=await this.fileManager.writeFileBinary($.projectPath,$.relativePath,E);if(this.binaryUploadOperations.delete(A),I.error)P$.error("[FileBrowser] Binary upload write failed",{error:I.error});else this.requestsHandled++,P$.info("[FileBrowser] Binary upload completed",{path:$.relativePath,size:E.length})}}catch($){P$.error("[FileBrowser] Error handling binary upload",{error:$ instanceof Error?$.message:"Unknown error"})}}async sendBinaryUploadResponse(H,$,A,L){let D={path:H.relativePath,success:$,chunkIndex:H.chunk.chunkIndex,totalChunks:H.chunk.totalChunks,bytesReceived:L||0,timestamp:Date.now(),error:A};await this.publishResponse(`files/upload/${H.clientId}/response`,D)}async handleBinaryDownloadRequest(H){try{let $=JSON.parse(H.toString()),A=`files/download/${$.clientId}/response`,L=await this.fileManager.readFileBinary($.projectPath,$.relativePath);if(L.error){let I={path:$.relativePath,filename:GU.basename($.relativePath),mimeType:"",chunk:{chunkIndex:0,totalChunks:1,data:""},totalSize:0,timestamp:Date.now(),error:L.error};await this.publishResponse(A,I);return}let D=L.content.toString("base64"),f=Math.max(1,Math.ceil(D.length/GD)),E=GU.basename($.relativePath);for(let I=0;I<f;I++){let P=I*GD,T=Math.min(P+GD,D.length),U=D.slice(P,T),M={path:$.relativePath,filename:E,mimeType:L.mimeType,chunk:{chunkIndex:I,totalChunks:f,data:U},totalSize:L.size,timestamp:Date.now()};if(await this.publishResponse(A,M),I<f-1)await this.delay(RX)}this.requestsHandled++,P$.info("[FileBrowser] Binary download completed",{path:$.relativePath,size:L.size,chunks:f})}catch($){P$.error("[FileBrowser] Error handling binary download",{error:$ instanceof Error?$.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,pendingSaveOperations:this.fileSaveOperations.size}}}var R=l();class KE{name="Git Service";running=!1;startedAt;mqttClient=null;worktreeManager;requestsHandled=0;messageHandlers=new Map;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){this.worktreeManager=new iD}setMQTTClient(H){this.mqttClient=H}async start(){try{if(this.running=!0,this.startedAt=new Date,this.ghAuthResult=await pX(),!this.ghAuthResult.authenticated)R.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else R.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username});if(this.mqttClient)this.registerMQTTHandlers();R.info("[GitService] Service started")}catch(H){throw R.error("[GitService] Failed to start",H),this.running=!1,H}}async stop(){if(this.running=!1,this.mqttClient){for(let[H,$]of this.messageHandlers)this.mqttClient.unsubscribe(H,$),R.debug(`[GitService] Unsubscribed from ${H}`);this.messageHandlers.clear()}this.worktreeManager.clearCache(),R.info("[GitService] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("git/orgs/request",(H,$)=>{this.handleOrgsRequest($)}),this.registerHandler("git/repos/request",(H,$)=>{this.handleReposRequest($)}),this.registerHandler("git/repos/search/request",(H,$)=>{this.handleSearchReposRequest($)}),this.registerHandler("git/branches/request",(H,$)=>{this.handleBranchesRequest($)}),this.registerHandler("git/clone/request",(H,$)=>{this.handleCloneRequest($)}),this.registerHandler("git/is-repo/request",(H,$)=>{this.handleIsRepoRequest($)}),this.registerHandler("git/worktree/get-or-create/request",(H,$)=>{this.handleWorktreeGetOrCreateRequest($)}),this.registerHandler("git/worktree/get/request",(H,$)=>{this.handleWorktreeGetRequest($)}),this.registerHandler("git/worktree/list/request",(H,$)=>{this.handleWorktreeListRequest($)}),this.registerHandler("git/status/request",(H,$)=>{this.handleStatusRequest($)}),this.registerHandler("git/diff/request",(H,$)=>{this.handleDiffRequest($)}),this.registerHandler("git/changes/all/request",(H,$)=>{this.handleChangesAllRequest($)}),this.registerHandler("git/stage/request",(H,$)=>{this.handleStageRequest($)}),this.registerHandler("git/unstage/request",(H,$)=>{this.handleUnstageRequest($)}),this.registerHandler("git/commit/request",(H,$)=>{this.handleCommitRequest($)}),this.registerHandler("git/unpushed/request",(H,$)=>{this.handleUnpushedCommitsRequest($)}),this.registerHandler("git/push/request",(H,$)=>{this.handlePushRequest($)}),this.registerHandler("git/history/request",(H,$)=>{this.handleHistoryRequest($)}),this.registerHandler("git/commit-details/request",(H,$)=>{this.handleCommitDetailsRequest($)}),this.registerHandler("git/commit-file-diff/request",(H,$)=>{this.handleCommitFileDiffRequest($)}),this.registerHandler("git/sync/request",(H,$)=>{this.handleSyncRequest($)}),this.registerHandler("git/create-pr/request",(H,$)=>{this.handleCreatePRRequest($)}),this.registerHandler("git/default-branch/request",(H,$)=>{this.handleDefaultBranchRequest($)}),this.registerHandler("git/existing-pr/request",(H,$)=>{this.handleExistingPRRequest($)}),this.registerHandler("git/remote-branches/request",(H,$)=>{this.handleRemoteBranchesRequest($)}),R.info("[GitService] MQTT handlers registered")}registerHandler(H,$){if(!this.mqttClient)return;this.messageHandlers.set(H,$),this.mqttClient.subscribe(H,$),R.debug(`[GitService] Subscribed to ${H}`)}async publishResponse(H,$){if(!this.mqttClient){R.error("[GitService] MQTT client not available");return}await this.mqttClient.publish(H,JSON.stringify($),{qos:1})}async handleOrgsRequest(H){try{let $=JSON.parse(H.toString());if(R.debug("[GitService] Orgs request",{clientId:$.clientId}),!this.ghAuthResult.authenticated){let D={orgs:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/orgs/${$.clientId}/response`,D);return}let L={orgs:await nU(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling orgs request",{error:$})}}async handleReposRequest(H){try{let $=JSON.parse(H.toString()),A=$.requestId||$.clientId;if(R.debug("[GitService] Repos request",{clientId:$.clientId,requestId:$.requestId,org:$.org,limit:$.limit}),!this.ghAuthResult.authenticated){let f={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,f);return}let D={repos:await mE($.org,$.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,D),this.requestsHandled++}catch($){R.error("[GitService] Error handling repos request",{error:$})}}async handleSearchReposRequest(H){try{let $=JSON.parse(H.toString());if(R.debug("[GitService] Search repos request",{clientId:$.clientId,query:$.query,limit:$.limit}),!this.ghAuthResult.authenticated){let A={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/search/${$.clientId}/response`,A);return}await VX($.query,async(A,L,D)=>{let f={repos:A,timestamp:Date.now(),source:L,isComplete:D};await this.publishResponse(`git/repos/search/${$.clientId}/response`,f),R.debug("[GitService] Sent search results",{source:L,count:A.length,isComplete:D})},$.limit||50),this.requestsHandled++}catch($){R.error("[GitService] Error handling search repos request",{error:$})}}async handleBranchesRequest(H){try{let $=JSON.parse(H.toString());if(R.debug("[GitService] Branches request",{clientId:$.clientId,owner:$.owner,repo:$.repo}),!this.ghAuthResult.authenticated){let D={branches:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/branches/${$.clientId}/response`,D);return}let A=await WX($.owner,$.repo),L={branches:A.branches,defaultBranch:A.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/branches/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling branches request",{error:$})}}async handleCloneRequest(H){try{let $=JSON.parse(H.toString());if(R.info("[GitService] Clone request",{clientId:$.clientId,repoUrl:$.repoUrl,targetPath:$.targetPath,branch:$.branch}),!this.ghAuthResult.authenticated){let D={success:!1,error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/clone/${$.clientId}/response`,D);return}let A=await uX($.repoUrl,$.targetPath,$.branch),L=A.success?{success:!0,path:A.path,defaultBranch:A.defaultBranch,timestamp:Date.now()}:{success:!1,error:A.error||"Clone failed",timestamp:Date.now()};await this.publishResponse(`git/clone/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling clone request",{error:$})}}async handleIsRepoRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Is-repo request",{clientId:$.clientId,path:$.path});let A=await FD($.path),L;if(A){let[D,f,E]=await Promise.all([sA($.path),sD($.path),nX($.path)]);L={isGitRepo:!0,repoRoot:D||void 0,defaultBranch:f||void 0,remoteUrl:E||void 0,timestamp:Date.now()}}else L={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling is-repo request",{error:$});let A=JSON.parse(H.toString()),L={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${A.clientId}/response`,L)}}async handleWorktreeGetOrCreateRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Worktree get-or-create request",{clientId:$.clientId,repoPath:$.repoPath,sessionId:$.sessionId});let{worktree:A,isNew:L}=await this.worktreeManager.getOrCreateForSession($.sessionId,$.repoPath),D={success:!0,worktreePath:A.path,branch:A.branch,isNew:L,timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${$.clientId}/response`,D),this.requestsHandled++}catch($){R.error("[GitService] Error handling worktree get-or-create request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${A.clientId}/response`,L)}}async handleWorktreeGetRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Worktree get request",{clientId:$.clientId,repoPath:$.repoPath,sessionId:$.sessionId});let A=await this.worktreeManager.getWorktreeForSession($.sessionId,$.repoPath),L=A?{exists:!0,worktreePath:A.path,branch:A.branch,timestamp:Date.now()}:{exists:!1,timestamp:Date.now()};await this.publishResponse(`git/worktree/get/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling worktree get request",{error:$})}}async handleWorktreeListRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Worktree list request",{clientId:$.clientId,repoPath:$.repoPath});let L={worktrees:await this.worktreeManager.listWorktreesForRepo($.repoPath),timestamp:Date.now()};await this.publishResponse(`git/worktree/list/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling worktree list request",{error:$})}}async handleStatusRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Status request",{clientId:$.clientId,path:$.path});let L={success:!0,status:await oU($.path),timestamp:Date.now()};await this.publishResponse(`git/status/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling status request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/status/${A.clientId}/response`,L)}}async handleDiffRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Diff request",{clientId:$.clientId,path:$.path,file:$.file,staged:$.staged});let A=await hX($.path,$.file,$.staged),L={success:!0,diff:A.diff,isBinary:A.isBinary,timestamp:Date.now()};await this.publishResponse(`git/diff/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling diff request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/diff/${A.clientId}/response`,L)}}async handleChangesAllRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Changes all request",{clientId:$.clientId,repoPath:$.repoPath});let A=await this.worktreeManager.listWorktreesForRepo($.repoPath),L={repoPath:$.repoPath,worktrees:[],totalChanges:0};for(let f of A)try{let E=await oU(f.path);L.worktrees.push({worktreePath:f.path,branch:f.branch,sessionId:f.sessionId,changes:E.files,totalCount:E.files.length}),L.totalChanges+=E.files.length}catch(E){R.warn("[GitService] Failed to get status for worktree",{path:f.path,error:E})}let D={success:!0,changes:L,timestamp:Date.now()};await this.publishResponse(`git/changes/all/${$.clientId}/response`,D),this.requestsHandled++}catch($){R.error("[GitService] Error handling changes all request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/changes/all/${A.clientId}/response`,L)}}async handleStageRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Stage request",{clientId:$.clientId,path:$.path,files:$.files}),await cX($.path,$.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${$.clientId}/response`,A),this.requestsHandled++}catch($){R.error("[GitService] Error handling stage request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/stage/${A.clientId}/response`,L)}}async handleUnstageRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Unstage request",{clientId:$.clientId,path:$.path,files:$.files}),await XX($.path,$.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${$.clientId}/response`,A),this.requestsHandled++}catch($){R.error("[GitService] Error handling unstage request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unstage/${A.clientId}/response`,L)}}async handleCommitRequest(H){try{let $=JSON.parse(H.toString());R.info("[GitService] Commit request",{clientId:$.clientId,path:$.path,signoff:$.signoff});let L={success:!0,commit:await SX($.path,$.message,$.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling commit request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit/${A.clientId}/response`,L)}}async handleUnpushedCommitsRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Unpushed commits request",{clientId:$.clientId,path:$.path});let A=await oD($.path),L={success:!0,commits:A.commits,upstream:A.upstream,ahead:A.ahead,timestamp:Date.now()};await this.publishResponse(`git/unpushed/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling unpushed commits request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unpushed/${A.clientId}/response`,L)}}async handlePushRequest(H){try{let $=JSON.parse(H.toString());R.info("[GitService] Push request",{clientId:$.clientId,path:$.path,force:$.force});let A=await oX($.path,$.force),L={success:!0,commitsPushed:A.commitsPushed,remote:A.remote,branch:A.branch,timestamp:Date.now()};await this.publishResponse(`git/push/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling push request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/push/${A.clientId}/response`,L)}}async handleHistoryRequest(H){try{let $=JSON.parse(H.toString());R.info("[GitService] History request",{clientId:$.clientId,path:$.path,limit:$.limit});let A=await FX($.path,$.limit||50),L={success:!0,commits:A.commits,totalCount:A.totalCount,timestamp:Date.now()};await this.publishResponse(`git/history/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling history request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/history/${A.clientId}/response`,L)}}async handleCommitDetailsRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Commit details request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash});let L={success:!0,commit:await sX($.path,$.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling commit details request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-details/${A.clientId}/response`,L)}}async handleCommitFileDiffRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Commit file diff request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash,filePath:$.filePath});let A=await iX($.path,$.commitHash,$.filePath),L={success:!0,diff:A.diff,isBinary:A.isBinary,timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling commit file diff request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${A.clientId}/response`,L)}}async handleSyncRequest(H){try{let $=JSON.parse(H.toString());R.info("[GitService] Sync request",{clientId:$.clientId,path:$.path});let A=await CX($.path),L=A.success?{success:!0,action:A.action,commitsPulled:A.commitsPulled,commitsPushed:A.commitsPushed,timestamp:Date.now()}:{success:!1,action:A.action,commitsPulled:A.commitsPulled,commitsPushed:A.commitsPushed,error:A.error||"Sync failed",conflictedFiles:A.conflictedFiles,timestamp:Date.now()};await this.publishResponse(`git/sync/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling sync request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/sync/${A.clientId}/response`,L)}}async handleCreatePRRequest(H){try{let $=JSON.parse(H.toString());R.info("[GitService] Create PR request",{clientId:$.clientId,path:$.path,title:$.title,baseBranch:$.baseBranch,draft:$.draft});let A=await GX($.path,$.title,$.body,$.baseBranch,$.draft),L=A.success?{success:!0,prNumber:A.prNumber,prUrl:A.prUrl,timestamp:Date.now()}:{success:!1,error:A.error||"Failed to create pull request",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling create PR request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${A.clientId}/response`,L)}}async handleDefaultBranchRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Default branch request",{clientId:$.clientId,path:$.path});let A=await FU($.path),L=A?{success:!0,defaultBranch:A,timestamp:Date.now()}:{success:!1,error:"Could not determine default branch",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling default branch request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${A.clientId}/response`,L)}}async handleExistingPRRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Existing PR request",{clientId:$.clientId,path:$.path});let A=await dX($.path),L={exists:A.exists,prNumber:A.prNumber,prUrl:A.prUrl,title:A.title,state:A.state,draft:A.draft,error:A.error,timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling existing PR request",{error:$});let A=JSON.parse(H.toString()),L={exists:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${A.clientId}/response`,L)}}async handleRemoteBranchesRequest(H){try{let $=JSON.parse(H.toString());R.debug("[GitService] Remote branches request",{clientId:$.clientId,path:$.path});let A=await aX($.path),L={success:!0,branches:A.branches,defaultBranch:A.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${$.clientId}/response`,L),this.requestsHandled++}catch($){R.error("[GitService] Error handling remote branches request",{error:$});let A=JSON.parse(H.toString()),L={success:!1,error:$ instanceof Error?$.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${A.clientId}/response`,L)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,activeWorktrees:this.worktreeManager.getActiveWorktreeCount(),ghAuthenticated:this.ghAuthResult.authenticated,ghInstalled:this.ghAuthResult.installed,ghInPath:this.ghAuthResult.inPath,ghError:this.ghAuthResult.error,ghUsername:this.ghAuthResult.username}}}import*as KX from"path";import*as gE from"path";import*as wX from"os";var gH=l(),Kf=gE.join(wX.homedir(),".ccc"),OX=gE.join(Kf,"device-tokens.json"),mX=gE.join(Kf,"notification-preferences.json");class eX{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if((await Bun.$`test -d ${Kf}`.quiet().nothrow()).exitCode!==0)await Bun.$`mkdir -p ${Kf}`.quiet(),gH.debug("[NotificationStorage] Created .ccc directory:",Kf)}catch(H){throw gH.error("[NotificationStorage] Error ensuring directory:",H),H}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let H=Bun.file(OX);if(await H.exists()){let $=await H.text();return this.tokensCache=JSON.parse($),gH.debug("[NotificationStorage] Loaded tokens:",{count:this.tokensCache?.tokens?.length||0}),this.tokensCache}}catch(H){gH.warn("[NotificationStorage] Error loading tokens, starting fresh:",H)}return this.tokensCache={tokens:[]},this.tokensCache}async saveTokens(H){try{await this.ensureDirectory(),await Bun.write(OX,JSON.stringify(H,null,2)),this.tokensCache=H,gH.debug("[NotificationStorage] Saved tokens:",{count:H.tokens.length})}catch($){throw gH.error("[NotificationStorage] Error saving tokens:",$),$}}async registerToken(H,$,A,L,D){let f=await this.loadTokens(),E=new Date().toISOString(),I=f.tokens.findIndex((T)=>T.deviceId===H),P={deviceId:H,fcmToken:$,expoPushToken:A,platform:L,deviceInfo:D,createdAt:I>=0?f.tokens[I].createdAt:E,lastUsed:E};if(I>=0)f.tokens[I]=P,gH.info("[NotificationStorage] Updated device token:",{deviceId:H,platform:L,hasExpoPushToken:!!A});else f.tokens.push(P),gH.info("[NotificationStorage] Registered new device token:",{deviceId:H,platform:L,hasExpoPushToken:!!A});return await this.saveTokens(f),P}async unregisterToken(H){let $=await this.loadTokens(),A=$.tokens.length;if($.tokens=$.tokens.filter((L)=>L.deviceId!==H),$.tokens.length<A)return await this.saveTokens($),gH.info("[NotificationStorage] Unregistered device token:",{deviceId:H}),!0;return!1}async getToken(H){return(await this.loadTokens()).tokens.find((A)=>A.deviceId===H)}async getAllTokens(){return(await this.loadTokens()).tokens}async getDeviceCount(){return(await this.loadTokens()).tokens.length}async updateLastUsed(H){let $=await this.loadTokens(),A=$.tokens.find((L)=>L.deviceId===H);if(A)A.lastUsed=new Date().toISOString(),await this.saveTokens($)}async cleanupOldTokens(H=90){let $=await this.loadTokens(),A=new Date;A.setDate(A.getDate()-H);let L=A.toISOString(),D=$.tokens.length;$.tokens=$.tokens.filter((E)=>E.lastUsed>L);let f=D-$.tokens.length;if(f>0)await this.saveTokens($),gH.info("[NotificationStorage] Cleaned up old tokens:",{removed:f,remaining:$.tokens.length});return f}async loadPreferences(){if(this.preferencesCache)return this.preferencesCache;try{let H=Bun.file(mX);if(await H.exists()){let $=await H.text();return this.preferencesCache=JSON.parse($),gH.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys(this.preferencesCache?.preferences||{}).length}),this.preferencesCache}}catch(H){gH.warn("[NotificationStorage] Error loading preferences, starting fresh:",H)}return this.preferencesCache={preferences:{}},this.preferencesCache}async savePreferences(H){try{await this.ensureDirectory(),await Bun.write(mX,JSON.stringify(H,null,2)),this.preferencesCache=H,gH.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(H.preferences).length})}catch($){throw gH.error("[NotificationStorage] Error saving preferences:",$),$}}getDefaultPreferences(H){return{deviceId:H,allMessages:!0,needsAttention:!0,updatedAt:new Date().toISOString()}}async getPreferences(H){let $=await this.loadPreferences();if(!$.preferences[H])$.preferences[H]=this.getDefaultPreferences(H),await this.savePreferences($),gH.info("[NotificationStorage] Created default preferences for device:",{deviceId:H});return $.preferences[H]}async updatePreferences(H,$){let A=await this.loadPreferences(),L=await this.getPreferences(H);return A.preferences[H]={...L,...$,deviceId:H,updatedAt:new Date().toISOString()},await this.savePreferences(A),gH.info("[NotificationStorage] Updated preferences:",{deviceId:H,updates:$}),A.preferences[H]}async isNotificationEnabled(H,$){return(await this.getPreferences(H))[$]}clearCache(){this.tokensCache=null,this.preferencesCache=null,gH.debug("[NotificationStorage] Cleared cache")}}var N$=new eX;import jX from"expo-server-sdk";var u$=l();class JX{expo;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;constructor(){this.expo=new jX}isValidToken(H){return jX.isExpoPushToken(H)}async sendNotification(H,$){if(!this.isValidToken(H))return u$.warn("[ExpoPushClient] Invalid Expo push token:",{token:H.substring(0,20)+"..."}),null;let A={to:H,title:$.title,body:$.body,data:$.data,sound:$.sound||"default",channelId:$.channelId||"default",priority:$.priority||"high",badge:$.badge};try{let D=(await this.expo.sendPushNotificationsAsync([A]))[0];if(this.notificationsSent++,this.lastNotificationAt=new Date,D.id){let f=D;this.pendingTickets.set(f.id,{ticketId:f.id,token:H,createdAt:new Date})}if(D.status==="error"){let f=D;await this.handleTicketError(f,H)}return u$.debug("[ExpoPushClient] Sent notification:",{token:H.substring(0,20)+"...",status:D.status}),D}catch(L){return u$.error("[ExpoPushClient] Error sending notification:",L),null}}async sendBatchNotifications(H,$){let A=H.filter((E)=>{let I=this.isValidToken(E);if(!I)u$.warn("[ExpoPushClient] Skipping invalid token:",{token:E.substring(0,20)+"..."});return I});if(A.length===0)return u$.warn("[ExpoPushClient] No valid tokens to send to"),[];let L=A.map((E)=>({to:E,title:$.title,body:$.body,data:$.data,sound:$.sound||"default",channelId:$.channelId||"default",priority:$.priority||"high",badge:$.badge})),D=this.expo.chunkPushNotifications(L),f=[];for(let E of D)try{let I=await this.expo.sendPushNotificationsAsync(E);f.push(...I);for(let P=0;P<I.length;P++){let T=I[P],U=A[f.length-I.length+P];if(T.id){let M=T;this.pendingTickets.set(M.id,{ticketId:M.id,token:U,createdAt:new Date})}if(T.status==="error")await this.handleTicketError(T,U)}this.notificationsSent+=I.length,this.lastNotificationAt=new Date}catch(I){u$.error("[ExpoPushClient] Error sending batch chunk:",I)}return u$.info("[ExpoPushClient] Sent batch notifications:",{total:A.length,successful:f.filter((E)=>E.status==="ok").length,failed:f.filter((E)=>E.status==="error").length}),f}async handleTicketError(H,$){if(u$.warn("[ExpoPushClient] Ticket error:",{message:H.message,details:H.details}),H.details?.error==="DeviceNotRegistered"){u$.info("[ExpoPushClient] Removing invalid token:",{token:$.substring(0,20)+"..."});let L=(await N$.getAllTokens()).find((D)=>D.expoPushToken===$);if(L)await N$.unregisterToken(L.deviceId)}}async checkReceipts(){let H=new Date;H.setMinutes(H.getMinutes()-15);let $=[];for(let[D,f]of this.pendingTickets.entries())if(f.createdAt<H)$.push(D);if($.length===0)return;u$.debug("[ExpoPushClient] Checking receipts:",{count:$.length});let A=this.expo.chunkPushNotificationReceiptIds($);for(let D of A)try{let f=await this.expo.getPushNotificationReceiptsAsync(D);for(let[E,I]of Object.entries(f)){let P=this.pendingTickets.get(E);if(I.status==="ok")u$.debug("[ExpoPushClient] Receipt OK:",{ticketId:E});else if(I.status==="error"){let T=I;if(u$.warn("[ExpoPushClient] Receipt error:",{ticketId:E,message:T.message,details:T.details}),T.details?.error==="DeviceNotRegistered"&&P){let M=(await N$.getAllTokens()).find((t)=>t.expoPushToken===P.token);if(M)u$.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:M.deviceId}),await N$.unregisterToken(M.deviceId)}}this.pendingTickets.delete(E)}}catch(f){u$.error("[ExpoPushClient] Error checking receipts:",f)}let L=new Date;L.setHours(L.getHours()-24);for(let[D,f]of this.pendingTickets.entries())if(f.createdAt<L)this.pendingTickets.delete(D)}getStats(){return{notificationsSent:this.notificationsSent,lastNotificationAt:this.lastNotificationAt,pendingReceipts:this.pendingTickets.size}}}var gf=new JX;var xH=l(),QX=200,p6=900000;class vE{name="Notification Service";running=!1;startedAt;mqttClient=null;claudeAgentService=null;receiptCheckInterval;constructor(){}setMQTTClient(H){this.mqttClient=H}setClaudeAgentService(H){this.claudeAgentService=H}async start(){try{if(this.running=!0,this.startedAt=new Date,xH.info("[Notification] Service started"),this.mqttClient)this.registerMQTTHandlers();else xH.warn("[Notification] MQTT client not set - handlers will not be registered");this.receiptCheckInterval=setInterval(()=>{gf.checkReceipts().catch((H)=>{xH.error("[Notification] Error checking receipts:",H)})},p6),xH.info("[Notification] Ready to send notifications")}catch(H){throw xH.error("[Notification] Failed to start",H),this.running=!1,H}}async stop(){if(this.running=!1,this.receiptCheckInterval)clearInterval(this.receiptCheckInterval);xH.info("[Notification] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("notifications/register/request",this.handleRegisterToken.bind(this)),this.mqttClient.subscribe("notifications/preferences/get/request",this.handleGetPreferences.bind(this)),this.mqttClient.subscribe("notifications/preferences/update/request",this.handleUpdatePreferences.bind(this)),this.mqttClient.subscribe("claude/+/output/+",this.handleClaudeOutput.bind(this)),this.mqttClient.subscribe("claude/+/permission/request/+",this.handlePermissionRequest.bind(this)),xH.info("[Notification] MQTT handlers registered")}async handleRegisterToken(H,$){try{let A=JSON.parse($.toString());xH.info("[Notification] Register token request:",{deviceId:A.deviceId,platform:A.platform,hasExpoPushToken:!!A.expoPushToken,hasFcmToken:!!A.fcmToken}),await N$.registerToken(A.deviceId,A.fcmToken,A.expoPushToken,A.platform,A.deviceInfo);let L={requestId:A.requestId,success:!0};await this.mqttClient?.publish("notifications/register/response",JSON.stringify(L)),xH.info("[Notification] Token registered successfully:",{deviceId:A.deviceId})}catch(A){xH.error("[Notification] Error registering token:",A);try{let L=$.toString(),f={requestId:JSON.parse(L).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/register/response",JSON.stringify(f))}catch{}}}async handleGetPreferences(H,$){try{let A=JSON.parse($.toString());xH.debug("[Notification] Get preferences request:",{deviceId:A.deviceId});let L=await N$.getPreferences(A.deviceId),D={requestId:A.requestId,success:!0,preferences:L};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(D)),xH.debug("[Notification] Sent preferences:",{deviceId:A.deviceId})}catch(A){xH.error("[Notification] Error getting preferences:",A);try{let D={requestId:JSON.parse($.toString()).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(D))}catch{}}}async handleUpdatePreferences(H,$){try{let A=JSON.parse($.toString());xH.info("[Notification] Update preferences request:",{deviceId:A.deviceId,preferences:A.preferences});let L=await N$.updatePreferences(A.deviceId,A.preferences),D={requestId:A.requestId,success:!0,preferences:L};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(D)),xH.info("[Notification] Preferences updated:",{deviceId:A.deviceId})}catch(A){xH.error("[Notification] Error updating preferences:",A);try{let D={requestId:JSON.parse($.toString()).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(D))}catch{}}}async handleClaudeOutput(H,$){try{let A=H.split("/"),L=A[1],D=A[3],f=JSON.parse($.toString());if(f.type!=="assistant")return;let E=this.getSessionInfo(D);if(!E){xH.debug("[Notification] Session not found for notification:",{sessionId:D});return}let I=this.buildNotificationTitle(E),P=this.extractMessageBody(f);if(!P)return;let T={type:"message",projectId:E.projectPath,sessionId:D};await this.sendToDevicesWithPreference("allMessages",{title:I,body:P,data:T,priority:"high",channelId:"messages"}),xH.debug("[Notification] Sent message notification:",{sessionId:D,title:I})}catch(A){xH.error("[Notification] Error handling Claude output:",A)}}async handlePermissionRequest(H,$){try{let A=H.split("/"),L=A[1],D=A[4],f=JSON.parse($.toString()),E=this.getSessionInfo(D);if(!E){xH.debug("[Notification] Session not found for permission notification:",{sessionId:D});return}let I=this.buildNotificationTitle(E),P=this.buildPermissionBody(f),T={type:"permission",projectId:E.projectPath,sessionId:D,requestId:f.request_id,action:f.action};await this.sendToDevicesWithPreference("needsAttention",{title:I,body:P,data:T,priority:"high",channelId:"default"}),xH.info("[Notification] Sent permission notification:",{sessionId:D,action:f.action})}catch(A){xH.error("[Notification] Error handling permission request:",A)}}getSessionInfo(H){if(!this.claudeAgentService)return null;let A=this.claudeAgentService.getActiveSessions().find((L)=>L.sessionId===H);if(!A)return null;return{sessionId:A.sessionId,projectPath:A.projectPath,worktreeBranch:A.worktreeBranch}}buildNotificationTitle(H){let $=KX.basename(H.projectPath);if(H.worktreeBranch){let A=H.worktreeBranch.replace("session/","");return`${$} (${A})`}return $}extractMessageBody(H){let $="",A=H.message;if(A?.content&&Array.isArray(A.content))$=A.content.filter((D)=>D.type==="text").map((D)=>D.text).filter(Boolean).join(`
|
|
2639
|
-
`);else if(
|
|
2640
|
-
`)}if(
|
|
2611
|
+
`)}else if(E&&L==="RESIZE:")this.ptyManager.resizeSession(E,X,H);return}if(E)if(this.ptyManager.getSession(E))this.ptyManager.writeToSession(E,A);else this.logger.warn("PTY session not found",{sessionId:E})}catch(A){this.logger.error("Error handling WebSocket message",A)}}handleWebSocketClose(_){let T=this.sessionMap.get(_);if(T)this.sessionMap.delete(_),this.ptyManager.disconnectSession(T)}}import*as $5 from"http";import*as iU from"net";import{WebSocketServer as Nh,WebSocket as nU}from"ws";class U5{server=null;wss=null;running=!1;startedAt;config;logger=v();routes=[{path:"/mqtt",target:"localhost:8884"},{path:"/terminal",target:"localhost:3001"}];activeBrokerSockets=new Set;name="CCC Router Service";constructor(_){this.config=_}async start(){return new Promise((_,T)=>{try{this.server=$5.createServer((A,E)=>{this.handleHttpRequest(A,E)}),this.wss=new Nh({noServer:!0}),this.server.on("upgrade",(A,E,L)=>{this.handleWebSocketUpgrade(A,E,L)}),this.server.on("error",(A)=>{this.logger.error("Router error",{error:A instanceof Error?A.message:String(A)}),T(A)}),this.server.listen(this.config.port,"0.0.0.0",()=>{this.running=!0,this.startedAt=new Date,this.logger.debug(`Router started on 0.0.0.0:${this.config.port}`),this.logger.debug(`Routes: ${this.routes.map((A)=>`${A.path} -> ${A.target}`).join(", ")}`),_()})}catch(A){T(new S5(`Failed to start router: ${A instanceof Error?A.message:String(A)}`))}})}handleHttpRequest(_,T){let A=_.url||"/",E=this.findRoute(A);if(!E){T.writeHead(404,{"Content-Type":"text/plain"}),T.end("Not Found");return}this.forwardHttpRequest(_,T,E)}forwardHttpRequest(_,T,A){let[E,L]=A.target.split(":"),J=parseInt(L||"8883",10),X={hostname:E||"localhost",port:J,path:_.url,method:_.method,headers:_.headers},H=$5.request(X,(Z)=>{T.writeHead(Z.statusCode||200,Z.headers),Z.pipe(T)});H.on("error",(Z)=>{this.logger.error("HTTP proxy error",{error:Z instanceof Error?Z.message:String(Z),target:A.target,path:_.url,method:_.method,code:Z.code}),T.writeHead(502,{"Content-Type":"text/plain"}),T.end(`Bad Gateway - Unable to connect to backend service
|
|
2612
|
+
`)}),_.pipe(H)}async stop(){if(!this.server&&!this.wss)return;return new Promise((_)=>{for(let T of this.activeBrokerSockets)try{T.destroy()}catch(A){this.logger.debug("Error destroying broker socket",{error:A})}if(this.activeBrokerSockets.clear(),this.wss)this.wss.clients?.forEach((T)=>{T.close(1000,"Server shutting down")}),this.wss.close(),this.wss=null;if(this.server){let T=setTimeout(()=>{this.logger.warn("Server close timeout, forcing shutdown"),this.running=!1,this.server=null,_()},500);this.server.close(()=>{clearTimeout(T),this.logger.debug("Router stopped"),this.running=!1,this.server=null,_()})}else _()})}getStatus(){return{name:"Router",running:this.running,port:this.config.port,startedAt:this.startedAt,routes:this.routes}}addRoute(_,T){let A=this.routes.findIndex((E)=>E.path===_);if(A>=0&&this.routes[A])this.routes[A].target=T;else this.routes.push({path:_,target:T});if(this.config.debug)this.logger.debug(`Route added: ${_} -> ${T}`)}handleWebSocketUpgrade(_,T,A){let E=_.url||"/";this.logger.debug("WebSocket upgrade request",{url:E});let L=this.findRoute(E);if(!L){this.logger.warn("WebSocket upgrade to unknown path",{url:E}),T.destroy();return}this.wss?.handleUpgrade(_,T,A,(J)=>{if(E.startsWith("/mqtt"))this.bridgeWebSocketToTcp(J,L);else this.bridgeWebSocketToWebSocket(J,L,E)})}bridgeWebSocketToTcp(_,T){let[A,E]=T.target.split(":"),L=parseInt(E||"8883",10);this.logger.debug("WebSocket-to-TCP bridge established",{target:T.target});let J=iU.connect(L,A||"localhost",()=>{this.logger.debug("Connected to MQTT broker",{target:T.target})});this.activeBrokerSockets.add(J),_.on("message",(X)=>{if(!J.destroyed&&J.writable)J.write(X);else this.logger.warn("Broker socket not writable")}),J.on("data",(X)=>{_.send(X,(H)=>{if(H)this.logger.error("Error sending WebSocket message",{error:H instanceof Error?H.message:String(H)})})}),_.on("close",()=>{this.logger.debug("WebSocket client closed"),J.destroy()}),_.on("error",(X)=>{this.logger.error("WebSocket error",{error:X.message}),J.destroy()}),J.on("close",()=>{this.logger.debug("MQTT broker connection closed"),this.activeBrokerSockets.delete(J),_.close()}),J.on("error",(X)=>{this.logger.error("MQTT broker error",{error:X.message,target:T.target}),this.activeBrokerSockets.delete(J),_.close()})}bridgeWebSocketToWebSocket(_,T,A){let[E,L]=T.target.split(":"),J=parseInt(L||"3001",10),H=`ws://${E||"localhost"}:${J}${A}`;this.logger.debug("WebSocket-to-WebSocket bridge connecting",{target:H});let Z=new nU(H),Y=[],K=!1;Z.on("open",()=>{K=!0;while(Y.length>0){let G=Y.shift();Z.send(G)}}),_.on("message",(G)=>{let $=typeof G==="string"?G:G.toString("utf-8");if(K&&Z.readyState===nU.OPEN)Z.send($);else Y.push($)}),Z.on("message",(G)=>{let $=typeof G==="string"?G:G.toString("utf-8");if(_.readyState===1)_.send($)}),_.on("close",()=>{Z.close()}),_.on("error",(G)=>{this.logger.error("Client WebSocket error",{error:G.message}),Z.close()}),Z.on("close",()=>{_.close()}),Z.on("error",(G)=>{this.logger.error("Target WebSocket error",{error:G.message}),_.close()})}findRoute(_){let T=_.split("?")[0]||_,A=this.routes.find((E)=>E.path===T);if(A)return A;return this.routes.find((E)=>T.startsWith(E.path+"/")||T===E.path)}}import Qh from"@ngrok/ngrok";class W5{listener;tunnelUrl=null;running=!1;startedAt;config;name="CCC Ngrok Service";constructor(_){this.config=_}async start(){try{let _=v();_.debug("Starting ngrok tunnel",{port:this.config.routerPort,domain:this.config.domain||"(auto)"});let T={authtoken:this.config.authToken,addr:`localhost:${this.config.routerPort}`};if(this.config.domain)T.domain=this.config.domain;this.listener=await Qh.forward(T),this.tunnelUrl=this.listener.url(),this.running=!0,this.startedAt=new Date;let A=this.tunnelUrl?.replace(/^https?:\/\//,"");_.debug("ngrok tunnel established",{url:A,fullUrl:this.tunnelUrl})}catch(_){let T=v(),A=_ instanceof Error?_.message:String(_);throw T.error("Failed to start ngrok tunnel",_),Error(`ngrok tunnel failed: ${A}`)}}async stop(){try{let _=v();if(!this.running)return;if(_.debug("Stopping ngrok tunnel"),this.listener)await Promise.race([this.listener.close(),new Promise((T)=>{setTimeout(()=>{_.warn("ngrok listener close timeout, forcing shutdown"),T()},3000)})]);this.running=!1,this.tunnelUrl=null,_.debug("ngrok tunnel closed")}catch(_){v().error("Error stopping ngrok tunnel",_)}}getStatus(){return{name:this.name,running:this.running,active:this.isActive(),tunnelUrl:this.tunnelUrl?this.tunnelUrl.replace(/^https?:\/\//,""):void 0,routerPort:this.config.routerPort,startedAt:this.startedAt}}getUrl(){return this.tunnelUrl}isActive(){return!!this.listener&&!!this.tunnelUrl}}var VW=v_(MW(),1);class V5{running=!1;startedAt;config;codesGenerated=0;name="CCC QR Code Service";constructor(_){this.config=_}async start(){try{let _=v();_.debug("QR Code Service starting"),this.running=!0,this.startedAt=new Date,this.display(),_.debug("QR Code Service started")}catch(_){throw v().error("Failed to start QR Code service",_),this.running=!1,_}}async stop(){try{let _=v();if(!this.running)return;this.running=!1,_.debug("QR Code Service stopped")}catch(_){v().error("Error stopping QR Code service",_)}}getStatus(){return{name:this.name,running:this.running,codesGenerated:this.codesGenerated,urls:{mdns:this.config.mdnsUrl,ipBased:this.config.ipBasedUrl,ngrok:this.config.ngrokUrl},startedAt:this.startedAt}}display(){let _=v();try{if(this.codesGenerated=0,console.log(`
|
|
2613
|
+
`),this.config.mdnsUrl)this.displayQRCode(this.config.mdnsUrl,this.config.username,this.config.password,!1,this.config.profileName),this.codesGenerated++,console.log("");if(this.config.ipBasedUrl&&this.config.ipBasedUrl!==this.config.mdnsUrl)this.displayQRCode(this.config.ipBasedUrl,this.config.username,this.config.password,!1,this.config.profileName),this.codesGenerated++,console.log("");if(this.config.ngrokUrl)this.displayQRCode(this.config.ngrokUrl,this.config.username,this.config.password,!0,this.config.profileName),this.codesGenerated++,console.log("");if(this.codesGenerated===0)_.warn("No connection URLs available for QR codes");else _.debug(`Displayed ${this.codesGenerated} QR code(s)`);console.log(`Press "q" to redisplay QR codes
|
|
2614
|
+
`)}catch(T){_.error("Error displaying QR codes",T)}}updateConfig(_){if(this.config={...this.config,..._},this.running)this.display()}displayQRCode(_,T,A,E,L){let J={serverUrl:_,useSSL:E,profileName:L};if(T)J.username=T;if(A)J.password=A;let X=JSON.stringify(J);VW.default.generate(X,{small:!0});let H=this.getLabel(_,E);console.log(`${H}`),console.log(` Server: ${_}`),console.log(` Profile: ${L}`),console.log(` Username: ${T?`${T.substring(0,8)}...`:"(none)"}`),console.log(` Password: ${A?"***":"(none)"}`),console.log(` SSL/TLS: ${E?"Yes (wss)":"No (ws)"}`)}getLabel(_,T){if(_.includes("ngrok"))return"\uD83C\uDF10 REMOTE CONNECTION (ngrok)";if(_.includes(".")){let A=_?.split(":")[0]?.split(".")||[];if(A.length===4&&A.every((E)=>!isNaN(Number(E))))return"\uD83D\uDD04 IP-BASED CONNECTION"}return"\uD83D\uDCF1 LOCAL NETWORK CONNECTION (mDNS)"}}import{readFileSync as zW}from"fs";import{join as FW}from"path";function m0(){try{let _=FW(import.meta.dir,"..","..","package.json");return JSON.parse(zW(_,"utf-8")).version||"unknown"}catch(_){try{let T=FW(process.cwd(),"package.json");return JSON.parse(zW(T,"utf-8")).version||"unknown"}catch{return"unknown"}}}function sL(_){let[T,A]=_.split("-"),E=(T||"0.0.0").split(".").map(Number);return{major:E[0]||0,minor:E[1]||0,patch:E[2]||0,preRelease:A||null}}function fT(_){return sL(_).preRelease?"beta":"stable"}function tL(_,T){try{let A=sL(_),E=sL(T);if(A.major>E.major)return!1;if(A.major<E.major)return!1;if(E.preRelease&&!A.preRelease)return!1;if(!E.preRelease&&A.preRelease)return!1;if(E.preRelease&&A.preRelease){if(A.minor<E.minor)return!1;if(A.minor===E.minor&&A.patch===E.patch)return A.preRelease>E.preRelease;if(A.minor>E.minor||A.patch>E.patch)return!0;return!1}if(A.minor>E.minor)return!0;if(A.minor<E.minor)return!1;if(A.patch>E.patch)return!0;return!1}catch(A){return!1}}var j1=v();async function CW(_){let T=m0(),A=fT(T);j1.debug("Checking for updates",{currentVersion:T,releaseChannel:A,packageName:_});try{let E=A==="beta"?"beta":"latest",L=await fetch(`https://registry.npmjs.org/${_}`,{headers:{Accept:"application/json"}});if(!L.ok)return j1.warn("Failed to check for updates",{status:L.status,statusText:L.statusText}),{updateAvailable:!1,currentVersion:T,latestVersion:T,releaseChannel:A};let J=await L.json(),X=J["dist-tags"]?.[E]||J["dist-tags"]?.latest;if(j1.debug("NPM registry response",{distTags:J["dist-tags"],requestedTag:E,latestVersion:X}),!X)return j1.warn("Could not determine latest version from npm registry"),{updateAvailable:!1,currentVersion:T,latestVersion:T,releaseChannel:A};let H=tL(X,T);return j1.debug("Version comparison result",{currentVersion:T,latestVersion:X,updateAvailable:H,isNewer:tL(X,T)}),j1.debug("Update check completed",{currentVersion:T,latestVersion:X,updateAvailable:H,releaseChannel:A,distTag:E}),{updateAvailable:H,currentVersion:T,latestVersion:X,releaseChannel:A}}catch(E){return j1.error("Error checking for updates",{error:E}),{updateAvailable:!1,currentVersion:T,latestVersion:T,releaseChannel:A}}}async function OW(_){let T=m0(),E=fT(T)==="beta"?"beta":"latest";j1.debug("Starting package update",{packageName:_,currentVersion:T,distTag:E});try{let L=Bun.spawn(["bun","install","-g",`${_}@${E}`],{stdout:"pipe",stderr:"pipe"}),J=await new Response(L.stdout).text(),X=await new Response(L.stderr).text(),H=await L.exited;if(H!==0)return j1.error("Package update failed",{error:X,packageName:_,exitCode:H}),!1;if(j1.debug("Package updated successfully",{packageName:_,distTag:E}),J)j1.debug("bun install output",{output:J.trim()});return!0}catch(L){return j1.error("Package update error",{error:L}),!1}}class z5{name="CCC Auto-Update Service";config;running=!1;enabled=!1;logger=v();checkInterval=null;lastCheckTime;nextCheckTime;updateAvailable=!1;latestVersion;startedAt;constructor(_){this.config={checkIntervalMinutes:60,..._},this.enabled=_.enabled}async start(){try{if(this.logger.debug("Starting Auto-Update Service",{enabled:this.enabled,packageName:this.config.packageName,checkIntervalMinutes:this.config.checkIntervalMinutes}),!this.enabled){this.logger.info("Auto-Update Service disabled"),this.running=!1;return}this.running=!0,this.startedAt=new Date,this.logger.info("Performing initial update check"),await this.performUpdateCheck(),this.scheduleNextCheck(),this.logger.info("Auto-Update Service started",{nextCheckTime:this.nextCheckTime})}catch(_){throw this.logger.error("Failed to start Auto-Update Service",_),_}}async stop(){try{if(!this.running)return;if(this.checkInterval)clearInterval(this.checkInterval),this.checkInterval=null;this.running=!1,this.logger.debug("Auto-Update Service stopped")}catch(_){throw this.logger.error("Failed to stop Auto-Update Service",_),_}}getStatus(){return{name:this.name,running:this.running,enabled:this.enabled,lastCheckTime:this.lastCheckTime,nextCheckTime:this.nextCheckTime,currentVersion:m0(),updateAvailable:this.updateAvailable,latestVersion:this.latestVersion,releaseChannel:fT(m0()),startedAt:this.startedAt}}scheduleNextCheck(){if(!this.enabled)return;let _=(this.config.checkIntervalMinutes||60)*60*1000;if(this.nextCheckTime=new Date(Date.now()+_),this.checkInterval)clearInterval(this.checkInterval);this.checkInterval=setInterval(async()=>{try{await this.performUpdateCheck(),this.scheduleNextCheck()}catch(T){this.logger.error("Error in scheduled update check",T)}},_),this.logger.debug("Next update check scheduled",{nextCheckTime:this.nextCheckTime,intervalMinutes:this.config.checkIntervalMinutes})}async performUpdateCheck(){this.lastCheckTime=new Date;try{this.logger.debug("Performing update check",{packageName:this.config.packageName,currentVersion:m0()});let{updateAvailable:_,latestVersion:T,currentVersion:A,releaseChannel:E}=await CW(this.config.packageName);if(this.updateAvailable=_,this.latestVersion=T,_)this.logger.info("Update available",{current:A,latest:T,channel:E}),await this.performAutoUpdate();else this.logger.debug("Already running latest version",{version:A,channel:E})}catch(_){this.logger.error("Error during update check",_)}}async performAutoUpdate(){try{if(this.logger.info("Starting auto-update",{packageName:this.config.packageName}),await OW(this.config.packageName))this.logger.info("Package update installed successfully",{newVersion:this.latestVersion,packageName:this.config.packageName});else this.logger.warn("Package update failed",{packageName:this.config.packageName})}catch(_){this.logger.error("Error during auto-update",_)}}}import{watch as Ih,readdirSync as Ph,existsSync as jh}from"fs";import{stat as qW}from"fs/promises";import{join as gT,basename as xh}from"path";import{homedir as IW}from"os";import*as o_ from"path";import*as eL from"os";var M4=v();class RW{async parseSessionFile(_,T,A=50){let E=!1;try{let L=Bun.file(_);if(!await L.exists())return M4.warn("[SessionMessageParser] Session file not found:",_),{messages:[],hasMore:!1};let H=(await L.text()).trim().split(`
|
|
2615
|
+
`),Z=[];for(let K of H)try{if(!K.trim())continue;let G=JSON.parse(K),$=this.parseEntry(G);if($)Z.push($)}catch(G){M4.warn("[SessionMessageParser] Failed to parse line:",G)}let Y;if(T){let K=Z.findIndex((G)=>G.uuid===T);if(K===-1)M4.warn("[SessionMessageParser] lastKnownUuid not found, returning latest messages"),Y=Z.slice(-A),E=Z.length>A;else{let G=Z.slice(K+1);Y=G.slice(0,A),E=G.length>A}}else if(Z.length>A)Y=Z.slice(-A),E=!0;else Y=Z,E=!1;return M4.debug("[SessionMessageParser] Parsed session file:",{filePath:_,totalMessages:Z.length,returnedMessages:Y.length,lastKnownUuid:T,hasMore:E,limit:A}),{messages:Y,hasMore:E}}catch(L){throw M4.error("[SessionMessageParser] Error parsing session file:",L),L}}parseEntry(_){try{let T=_.uuid;if(!T)return null;if(_.isMeta)return null;let A={uuid:T,parentUuid:_.parentUuid||null,timestamp:_.timestamp||new Date().toISOString(),type:this.determineMessageType(_),role:_.message?.role,content:_.message?.content||_.content||"",metadata:{sessionId:_.sessionId,version:_.version,gitBranch:_.gitBranch,cwd:_.cwd,requestId:_.requestId,isSidechain:_.isSidechain,message:_.message}};if(_.message?.content&&Array.isArray(_.message.content)){let E=_.message.content.find((L)=>L.type==="tool_use");if(E)A.toolName=E.name,A.toolInput=E.input,A.toolUseId=E.id}if(_.toolUseResult)A.toolOutput=_.toolUseResult.stdout||_.toolUseResult.content||"",A.isError=_.toolUseResult.isError||_.is_error||!1;if(_.type==="summary"&&_.summary)A.content=_.summary;return A}catch(T){return M4.warn("[SessionMessageParser] Failed to parse entry:",T),null}}determineMessageType(_){if(_.type==="summary")return"summary";if(_.type==="user"){if(_.message?.content&&Array.isArray(_.message.content)){if(_.message.content.some((A)=>A.type==="tool_result"))return"tool"}return"user"}if(_.type==="assistant")return"assistant";if(_.message?.role==="user")return"user";if(_.message?.role==="assistant")return"assistant";return"user"}}var DW=new RW;var N1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6},Bh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qh="worktrees",F_=v();class BW{claudeProjectsDir;cccDir;constructor(){this.claudeProjectsDir=o_.join(eL.homedir(),".claude","projects"),this.cccDir=o_.join(eL.homedir(),".ccc")}async getWorktreePathsForProject(_){let T=await import("fs"),A=o_.basename(_),E=o_.join(this.cccDir,`${A}-${qh}`);if(F_.info("[SessionManager] Looking for worktrees:",{projectPath:_,repoName:A,cccDir:this.cccDir,worktreesDir:E}),!T.existsSync(E))return F_.info("[SessionManager] Worktrees directory does not exist:",E),[];try{let L=T.readdirSync(E,{withFileTypes:!0}),J=[];for(let X of L)if(X.isDirectory()){let H=o_.join(E,X.name);J.push(H)}return F_.info("[SessionManager] Found worktree paths:",J),J}catch(L){return F_.warn("[SessionManager] Error reading worktrees directory:",L),[]}}sanitizeProjectPath(_){let T=_.replace(/[\\/]+$/,"");return T=T.replace(/:[\\/]+/g,"--"),T=T.replace(/:/g,"--"),T=T.replace(/[\\/]+/g,"-"),T=T.replace(/\./g,"-"),T=T.replace(/_/g,"-"),T}getProjectSessionsDir(_){let T=this.sanitizeProjectPath(_);return o_.join(this.claudeProjectsDir,T)}async pathExists(_){try{return await Bun.file(_).exists()}catch{return!1}}async dirExists(_){try{return await Bun.file(_).stat()!==null}catch{try{let T=await import("fs");return T.existsSync(_)&&T.statSync(_).isDirectory()}catch{return!1}}}async readDir(_){try{return(await import("fs")).readdirSync(_)}catch{return[]}}async countLines(_){try{return(await Bun.file(_).text()).trim().split(`
|
|
2616
|
+
`).filter((E)=>E.trim()).length}catch(T){return F_.warn("[SessionManager] Error counting lines:",T),0}}async extractTitle(_){try{let E=(await Bun.file(_).text()).trim().split(`
|
|
2617
|
+
`),L=null,J=null;for(let H of E){if(!H.trim())continue;try{let Z=JSON.parse(H);if(Z.type==="summary"&&Z.summary)L=Z.summary;if(Z.isMeta)continue;if(!Z.message)continue;let Y=Z.type==="user"||Z.message?.role==="user",K=Array.isArray(Z.message?.content)&&Z.message.content.some((G)=>G.type==="tool_result");if(!J&&Y&&!K){let G=Z.message?.content,$=null;if(typeof G==="string")$=G;else if(Array.isArray(G)){let V=G.find((N)=>N.type==="text");if(V?.text)$=V.text}let U=$?.trim();if(U&&U!=="Warmup"&&!U.startsWith("<command-name>")&&!U.startsWith("<local-command-stdout>"))J=U}}catch{}}return(L||J||"Untitled Session").substring(0,100)}catch(T){return F_.warn("[SessionManager] Error extracting title:",T),"Untitled Session"}}async getFileModTime(_){try{return(await import("fs")).statSync(_).mtime}catch{return null}}async extractSessionMetadata(_,T){try{let A=await this.extractTitle(_),E=await this.getFileModTime(_),L=E?E.toISOString():new Date().toISOString(),J=await this.countLines(_);return{sessionId:T,title:A,lastActivity:L,messageCount:J}}catch(A){return F_.warn(`[SessionManager] Error extracting metadata for session ${T}`,A),null}}async listSessionsFromDir(_,T){if(!(await import("fs")).existsSync(_))return[];try{let J=(await this.readDir(_)).filter((H)=>{if(!H.endsWith(".jsonl"))return!1;let Z=o_.basename(H,".jsonl");return Bh.test(Z)}).map(async(H)=>{let Z=o_.basename(H,".jsonl"),Y=o_.join(_,H),K=await this.extractSessionMetadata(Y,Z);if(K&&T)K.worktreePath=T.path,K.worktreeBranch=T.branch;return K});return(await Promise.all(J)).filter((H)=>H!==null).filter((H)=>H.messageCount>0)}catch(E){return F_.warn(`[SessionManager] Error listing sessions from ${_}`,E),[]}}async listSessions(_){if(!(await import("fs")).existsSync(_))return F_.warn("[SessionManager] Project path does not exist:",_),{sessions:[],projectPath:_,pathExists:!1};try{let E=this.getProjectSessionsDir(_);F_.info("[SessionManager] Main sessions dir:",E);let L=await this.listSessionsFromDir(E);F_.info("[SessionManager] Main sessions count:",L.length);let J=await this.getWorktreePathsForProject(_);F_.info("[SessionManager] Worktree paths to check:",J.length);let X=J.map(async(G)=>{let $=this.getProjectSessionsDir(G);F_.info("[SessionManager] Checking worktree sessions dir:",$);let U=o_.basename(G),V={path:G,branch:`session/${U}`},N=await this.listSessionsFromDir($,V);return F_.info("[SessionManager] Found sessions in worktree:",{worktreePath:G,count:N.length,worktreeInfo:V}),N}),Z=(await Promise.all(X)).flat();F_.info("[SessionManager] Total worktree sessions:",Z.length);let Y=new Map;for(let G of L)Y.set(G.sessionId,G);for(let G of Z){let $=Y.get(G.sessionId);if(!$||new Date(G.lastActivity)>new Date($.lastActivity)||G.messageCount>$.messageCount)Y.set(G.sessionId,G)}let K=Array.from(Y.values()).sort((G,$)=>new Date($.lastActivity).getTime()-new Date(G.lastActivity).getTime());return F_.debug(`[SessionManager] Found ${K.length} sessions for ${_} (${L.length} main, ${Z.length} worktree)`),{sessions:K,projectPath:_,pathExists:!0}}catch(E){return F_.error(`[SessionManager] Error listing sessions for ${_}`,E),{sessions:[],projectPath:_,pathExists:!0}}}async getLatestSession(_){let T=await this.listSessions(_);if(T.sessions.length===0)return null;return T.sessions[0]??null}async getLatestSessions(_){let T=await import("fs");return await Promise.all(_.map(async(E)=>{if(!T.existsSync(E))return F_.warn("[SessionManager] Project path does not exist:",E),{projectPath:E,latestSession:null,pathExists:!1};let J=await this.getLatestSession(E);return{projectPath:E,latestSession:J,pathExists:!0}}))}async getSessionCounts(_){return await Promise.all(_.map(async(A)=>{let E=await this.listSessions(A);return{projectPath:A,sessionCount:E.sessions.length}}))}async findSessionFilePath(_,T){let A=await import("fs"),E=this.getProjectSessionsDir(_),L=o_.join(E,`${T}.jsonl`);if(A.existsSync(L))return{filePath:L};let J=await this.getWorktreePathsForProject(_);for(let X of J){let H=this.getProjectSessionsDir(X),Z=o_.join(H,`${T}.jsonl`);if(A.existsSync(Z)){let Y=o_.basename(X);return{filePath:Z,worktreePath:X,worktreeBranch:`session/${Y}`}}}return{filePath:null}}async getSessionMessages(_,T,A,E=50){let{filePath:L,worktreePath:J,worktreeBranch:X}=await this.findSessionFilePath(_,T);try{if(!L)return F_.warn("[SessionManager] Session file not found for:",{projectPath:_,sessionId:T}),{messages:[],hasMore:!1,sessionId:T,projectPath:_,timestamp:Date.now()};let H=await DW.parseSessionFile(L,A,E),Z=await this.extractTitle(L),Y=await this.calculateContextBreakdown(L),K={totalInputTokens:Y.inputTokens,totalOutputTokens:Y.outputTokens,totalCacheCreationTokens:Y.cacheCreation,totalCacheReadTokens:Y.cacheRead,totalTokens:Y.total};return{...H,sessionId:T,projectPath:_,title:Z,context:Y,totalUsage:K,timestamp:Date.now(),worktreePath:J,worktreeBranch:X}}catch(H){throw F_.error(`[SessionManager] Error getting session messages for ${T}`,H),H}}async calculateContextBreakdown(_){try{let E=(await Bun.file(_).text()).trim().split(`
|
|
2618
|
+
`),L=null,J=0,X=0;for(let R of E){if(!R.trim())continue;try{let q=JSON.parse(R);X++;let f=null;if(q.type==="assistant"){if(q.message?.usage)f=q.message.usage;else if(q.usage)f=q.usage}if(q.type==="result"&&q.usage)f=q.usage;if(f&&(f.input_tokens!==void 0||f.output_tokens!==void 0))L=f,J++}catch{continue}}if(F_.debug("[SessionManager] Context calculation stats:",{sessionFile:o_.basename(_),totalMessages:X,messagesWithUsage:J,hasUsage:!!L,mostRecentUsage:L?{input:L.input_tokens,output:L.output_tokens,cacheCreate:L.cache_creation_input_tokens,cacheRead:L.cache_read_input_tokens}:null}),!L)return F_.warn("[SessionManager] No usage data found in session file:",_),this.getEmptyContextBreakdown();let H=L.input_tokens||0,Z=L.output_tokens||0,Y=L.cache_creation_input_tokens||0,K=L.cache_read_input_tokens||0,G=H+Y+K,$=N1.SYSTEM_PROMPT,U=N1.TOOLS_TOTAL,V=0,N=N1.AUTOCOMPACT_BUFFER,z=Math.max(0,G-$-U-V),Q=G+N,F=N1.CONTEXT_LIMIT_STANDARD;return F_.info("[SessionManager] Context breakdown calculated:",{total:Q,apiTokens:G,inputTokens:H,cacheCreation:Y,cacheRead:K,percentage:Math.round(Q/F*100),breakdown:{systemPrompt:$,tools:U,mcpServers:V,messages:z,autocompactBuffer:N,remaining:Math.max(0,F-Q)}}),{total:Q,inputTokens:H,outputTokens:Z,cacheCreation:Y,cacheRead:K,systemPrompt:$,tools:U,mcpServers:V,messages:z,autocompactBuffer:N,contextLimit:F,remaining:Math.max(0,F-Q),percentage:Math.round(Q/F*100),lastUpdated:Date.now()}}catch(T){return F_.error("[SessionManager] Error calculating context breakdown:",T),this.getEmptyContextBreakdown()}}getEmptyContextBreakdown(){let _=N1.SYSTEM_PROMPT+N1.TOOLS_TOTAL+N1.AUTOCOMPACT_BUFFER;return{total:_,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:N1.SYSTEM_PROMPT,tools:N1.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:N1.AUTOCOMPACT_BUFFER,contextLimit:N1.CONTEXT_LIMIT_STANDARD,remaining:N1.CONTEXT_LIMIT_STANDARD-_,percentage:Math.round(_/N1.CONTEXT_LIMIT_STANDARD*100),lastUpdated:Date.now()}}}var bT=new BW;var X_=v(),wh="worktrees";class _9{watches=new Map;registeredProjects=[];mqttClient;claudeProjectsDir;cccDir;constructor(_){this.mqttClient=_,this.claudeProjectsDir=gT(IW(),".claude","projects"),this.cccDir=gT(IW(),".ccc")}getWorktreePathsForProject(_){let T=xh(_),A=gT(this.cccDir,`${T}-${wh}`);if(!jh(A))return[];try{let E=Ph(A,{withFileTypes:!0}),L=[];for(let J of E)if(J.isDirectory()){let X=gT(A,J.name);L.push(X)}return L}catch(E){return X_.warn("[SessionWatcher] Error reading worktrees directory:",E),[]}}sanitizeProjectPath(_){let T=_.replace(/[\\/]+$/,"");return T=T.replace(/:[\\/]+/g,"--"),T=T.replace(/:/g,"--"),T=T.replace(/[\\/]+/g,"-"),T=T.replace(/\./g,"-"),T=T.replace(/_/g,"-"),T}async registerProjects(_){X_.info(`[SessionWatcher] Registering ${_.length} projects`),this.registeredProjects=_,this.stopAll();for(let T of _)await this.fetchAndPublishLatestSession(T.id,T.directory_path),await this.watchProject(T.id,T.directory_path);X_.info(`[SessionWatcher] Now watching ${this.watches.size} projects`)}async fetchAndPublishLatestSession(_,T){try{let A=await bT.getLatestSession(T),L=(await import("fs")).existsSync(T);if(A)X_.info(`[SessionWatcher] Found latest session for project ${_}: ${A.sessionId} (${A.title})`),this.publishSessionUpdate(_,A,L);else X_.debug(`[SessionWatcher] No sessions found for project ${_}`),this.publishSessionUpdate(_,null,L)}catch(A){X_.error(`[SessionWatcher] Error fetching latest session for project ${_}:`,A),this.publishSessionUpdate(_,null,!0)}}async watchProject(_,T){try{let A=!0;try{await qW(T)}catch{X_.warn(`[SessionWatcher] Project directory not found: ${T}`),A=!1}let E={projectId:_,directoryPath:T,mainWatcher:null,worktreeWatchers:[],pathExists:A};this.watches.set(_,E);let L=gT(this.claudeProjectsDir,this.sanitizeProjectPath(T));X_.debug(`[SessionWatcher] Main sessions dir: ${T} \u2192 ${L}`);let J=await this.setupDirectoryWatcher(_,L,A);if(J)E.mainWatcher=J,X_.info(`[SessionWatcher] Started watching main sessions: ${L}`);let X=this.getWorktreePathsForProject(T);X_.debug(`[SessionWatcher] Found ${X.length} worktrees for project ${_}`);for(let Z of X){let Y=gT(this.claudeProjectsDir,this.sanitizeProjectPath(Z)),K=await this.setupDirectoryWatcher(_,Y,A);if(K)E.worktreeWatchers.push({path:Y,watcher:K}),X_.info(`[SessionWatcher] Started watching worktree sessions: ${Y}`)}this.watches.set(_,E);let H=(E.mainWatcher?1:0)+E.worktreeWatchers.length;X_.info(`[SessionWatcher] Project ${_}: watching ${H} directories`)}catch(A){X_.error(`[SessionWatcher] Error watching project ${_}:`,A)}}async setupDirectoryWatcher(_,T,A){try{await qW(T)}catch{return X_.debug(`[SessionWatcher] Sessions directory not found: ${T}`),null}return Ih(T,{recursive:!0},async(L,J)=>{if(!J||!J.endsWith(".jsonl"))return;X_.debug(`[SessionWatcher] File ${L} detected in project ${_}: ${J}`),await this.handleSessionChange(_,T,A)})}async handleSessionChange(_,T,A=!0){try{let E=this.watches.get(_);if(!E){X_.warn(`[SessionWatcher] No watch found for project ${_}`);return}let L=await bT.getLatestSession(E.directoryPath);if(L)X_.debug(`[SessionWatcher] Session change for project ${_}: ${L.sessionId}`),this.publishSessionUpdate(_,L,A);else X_.debug(`[SessionWatcher] No sessions found for project ${_}`),this.publishSessionUpdate(_,null,A)}catch(E){X_.error(`[SessionWatcher] Error handling session change for project ${_}:`,E)}}publishSessionUpdate(_,T,A=!0){if(!this.mqttClient){X_.warn("[SessionWatcher] MQTT client not available");return}let E=`sessions/update/${_}`,L=JSON.stringify(T?{...T,pathExists:A}:{pathExists:A});this.mqttClient.publish(E,L).catch((J)=>{X_.error(`[SessionWatcher] Failed to publish to ${E}`,{error:J.message})}),X_.debug(`[SessionWatcher] Published update to ${E}: ${T?.sessionId||"null"}, pathExists: ${A}`)}stopProject(_){let T=this.watches.get(_);if(T){if(T.mainWatcher)T.mainWatcher.close();for(let E of T.worktreeWatchers)E.watcher.close();this.watches.delete(_);let A=(T.mainWatcher?1:0)+T.worktreeWatchers.length;X_.info(`[SessionWatcher] Stopped watching project ${_} (${A} watchers closed)`)}}stopAll(){X_.info(`[SessionWatcher] Stopping all watches (${this.watches.size} projects)`);for(let[_]of this.watches)this.stopProject(_)}async resumeAll(){if(this.registeredProjects.length===0){X_.debug("[SessionWatcher] No registered projects to resume");return}X_.info(`[SessionWatcher] Resuming watches for ${this.registeredProjects.length} projects`);for(let _ of this.registeredProjects)await this.watchProject(_.id,_.directory_path);X_.info(`[SessionWatcher] Resumed ${this.watches.size} watches`)}async notifySessionCreated(_,T){let A=null;for(let E of this.registeredProjects)if(E.directory_path===_){A=E.id;break}if(!A){X_.warn(`[SessionWatcher] notifySessionCreated - project not registered: ${_}`);return}X_.info(`[SessionWatcher] Session created notification for project ${A}`,{projectPath:_,workingDirectory:T}),await new Promise((E)=>setTimeout(E,500)),await this.fetchAndPublishLatestSession(A,_),await this.ensureWatcherForPath(A,T)}async ensureWatcherForPath(_,T){let A=this.watches.get(_);if(!A){X_.warn(`[SessionWatcher] Cannot ensure watcher - project not in watches: ${_}`);return}let E=gT(this.claudeProjectsDir,this.sanitizeProjectPath(T));if(T===A.directoryPath){if(A.mainWatcher){X_.debug(`[SessionWatcher] Main watcher already exists for project ${_}`);return}let J=await this.setupDirectoryWatcher(_,E,A.pathExists);if(J)A.mainWatcher=J,X_.info(`[SessionWatcher] Added main watcher for project ${_}: ${E}`)}else{if(A.worktreeWatchers.find((H)=>H.path===E)){X_.debug(`[SessionWatcher] Worktree watcher already exists: ${E}`);return}let X=await this.setupDirectoryWatcher(_,E,A.pathExists);if(X)A.worktreeWatchers.push({path:E,watcher:X}),X_.info(`[SessionWatcher] Added worktree watcher for project ${_}: ${E}`)}}}var G_=v();class F5{name="Sessions Service";running=!1;startedAt;mqttClient=null;watcher;claudeAgentService=null;constructor(){}setMQTTClient(_){this.mqttClient=_,this.watcher=new _9(_)}setClaudeAgentService(_){this.claudeAgentService=_}async notifySessionCreated(_,T){if(this.watcher)await this.watcher.notifySessionCreated(_,T);this.broadcastActiveSessionCounts()}notifySessionStopped(){this.broadcastActiveSessionCounts()}broadcastActiveSessionCounts(){if(!this.mqttClient||!this.claudeAgentService)return;let _=this.claudeAgentService.getActiveSessions(),T={activeSessions:_,timestamp:Date.now()};this.mqttClient.publish("sessions/active/broadcast",JSON.stringify(T)),G_.debug(`[Sessions] Broadcast ${_.length} active sessions to all clients`)}async start(){try{if(this.running=!0,this.startedAt=new Date,G_.info("[Sessions] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw G_.error("[Sessions] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.watcher)this.watcher.stopAll();G_.info("[Sessions] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("projects/register",(_,T)=>{this.handleProjectRegistration(_,T)}),this.mqttClient.subscribe("app/lifecycle",(_,T)=>{this.handleAppLifecycle(_,T)}),this.mqttClient.subscribe("sessions/list/request",(_,T)=>{this.handleSessionListRequest(_,T)}),this.mqttClient.subscribe("sessions/messages/request",(_,T)=>{this.handleSessionMessagesRequest(_,T)}),this.mqttClient.subscribe("sessions/latest/request",(_,T)=>{this.handleLatestSessionsRequest(_,T)}),this.mqttClient.subscribe("sessions/active/request",(_,T)=>{this.handleActiveSessionsRequest(_,T)}),G_.info("[Sessions] MQTT handlers registered for projects/register, app/lifecycle, sessions/list, sessions/messages, sessions/latest, sessions/active")}async handleProjectRegistration(_,T){try{let A=JSON.parse(T.toString()),E=A.projects;if(!Array.isArray(E)){G_.warn("[Sessions] Invalid projects payload:",A);return}if(G_.info(`[Sessions] Received registration for ${E.length} projects`),this.watcher)await this.watcher.registerProjects(E)}catch(A){G_.error("[Sessions] Error handling project registration:",A)}}async handleAppLifecycle(_,T){try{let E=JSON.parse(T.toString()).state;if(G_.info(`[Sessions] App lifecycle changed to: ${E}`),E==="background"||E==="terminated"){if(this.watcher)this.watcher.stopAll(),G_.info(`[Sessions] Stopped all watchers (app state: ${E})`)}else if(E==="active"){if(this.watcher)await this.watcher.resumeAll(),G_.info(`[Sessions] Resumed all watchers (app state: ${E})`)}}catch(A){G_.error("[Sessions] Error handling app lifecycle:",A)}}async handleSessionListRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPath:E,clientId:L,timestamp:J}=A;if(!E||!L){G_.warn("[Sessions] Invalid session list request:",A);return}G_.info(`[Sessions] Session list request from ${L} for ${E}`);let X=await bT.listSessions(E),H=this.claudeAgentService?.getActiveSessions()||[],Z=new Map(H.filter(($)=>$.projectPath===E).map(($)=>[$.sessionId,{status:$.status,worktreePath:$.worktreePath,worktreeBranch:$.worktreeBranch}])),K={sessions:X.sessions.map(($)=>{let U=Z.get($.sessionId);return{...$,status:U?.status,worktreePath:U?.worktreePath||$.worktreePath,worktreeBranch:U?.worktreeBranch||$.worktreeBranch}}),projectPath:X.projectPath,pathExists:X.pathExists,timestamp:Date.now()},G=`sessions/list/${L}/response`;await this.mqttClient?.publish(G,JSON.stringify(K)),G_.info(`[Sessions] Sent ${X.sessions.length} sessions to ${L}`)}catch(A){G_.error("[Sessions] Error handling session list request:",A)}}async handleSessionMessagesRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPath:E,sessionId:L,lastKnownUuid:J,limit:X=50,clientId:H,timestamp:Z}=A;if(!E||!L||!H){G_.warn("[Sessions] Invalid session messages request:",A);return}G_.info(`[Sessions] Messages request from ${H} for session ${L}${J?` (from ${J})`:""}`);let Y=await bT.getSessionMessages(E,L,J,X),K={...Y,timestamp:Date.now()},G=`sessions/messages/${H}/response`;await this.mqttClient?.publish(G,JSON.stringify(K)),G_.info(`[Sessions] Sent ${Y.messages.length} messages to ${H} (hasMore: ${Y.hasMore})`)}catch(A){G_.error("[Sessions] Error handling session messages request:",A)}}async handleLatestSessionsRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPaths:E,clientId:L,timestamp:J}=A;if(!Array.isArray(E)||!L){G_.warn("[Sessions] Invalid latest sessions request:",A);return}G_.info(`[Sessions] Latest sessions request from ${L} for ${E.length} projects`);let X=await bT.getLatestSessions(E),H={projects:X,timestamp:Date.now()},Z=`sessions/latest/${L}/response`;await this.mqttClient?.publish(Z,JSON.stringify(H)),G_.info(`[Sessions] Sent latest sessions for ${X.length} projects to ${L}`)}catch(A){G_.error("[Sessions] Error handling latest sessions request:",A)}}async handleActiveSessionsRequest(_,T){try{let A=JSON.parse(T.toString()),{clientId:E,timestamp:L}=A;if(!E){G_.warn("[Sessions] Invalid active sessions request:",A);return}G_.info(`[Sessions] Active sessions request from ${E}`);let J=this.claudeAgentService?.getActiveSessions()||[],X={activeSessions:J,timestamp:Date.now()},H=`sessions/active/${E}/response`;await this.mqttClient?.publish(H,JSON.stringify(X)),G_.info(`[Sessions] Sent ${J.length} active sessions to ${E}`)}catch(A){G_.error("[Sessions] Error handling active sessions request:",A)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt}}}import PW from"os";var T1=v(),Sh="1.0.0";class C5{name="System Info Service";running=!1;startedAt;mqttClient=null;requestsHandled=0;messageHandler;versionCheckHandler;constructor(){}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,T1.info("[SystemInfo] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw T1.error("[SystemInfo] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){if(this.messageHandler)this.mqttClient.unsubscribe("system/os-info/request",this.messageHandler),T1.debug("[SystemInfo] Unsubscribed from system/os-info/request"),this.messageHandler=void 0;if(this.versionCheckHandler)this.mqttClient.unsubscribe("version/check/request",this.versionCheckHandler),T1.debug("[SystemInfo] Unsubscribed from version/check/request"),this.versionCheckHandler=void 0}T1.info("[SystemInfo] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(_,T)=>{this.handleSystemInfoRequest(_,T)},this.mqttClient.subscribe("system/os-info/request",this.messageHandler),T1.info("[SystemInfo] MQTT handler registered for system/os-info/request"),this.versionCheckHandler=(_,T)=>{this.handleVersionCheckRequest(_,T)},this.mqttClient.subscribe("version/check/request",this.versionCheckHandler),T1.info("[SystemInfo] MQTT handler registered for version/check/request")}async handleSystemInfoRequest(_,T){try{let A=JSON.parse(T.toString());T1.debug("[SystemInfo] Received system info request",{clientId:A.clientId});let E=PW.platform(),L=PW.homedir(),J;if(E==="win32")J=`${L}\\projects\\my-project`;else if(E==="darwin")J=`${L}/projects/my-project`;else J=`${L}/projects/my-project`;let X=`system/os-info/${A.clientId}/response`,H={platform:E,homedir:L,suggestedPath:J,timestamp:Date.now()};if(this.mqttClient)await this.mqttClient.publish(X,JSON.stringify(H),{qos:1}),this.requestsHandled++,T1.debug("[SystemInfo] Sent system info response",{clientId:A.clientId,platform:E,responseTopic:X});else T1.error("[SystemInfo] MQTT client not available for publishing")}catch(A){T1.error("[SystemInfo] Error handling system info request",{error:A instanceof Error?A.message:"Unknown error"})}}async handleVersionCheckRequest(_,T){try{let A=JSON.parse(T.toString());T1.debug("[SystemInfo] Received version check request",{clientId:A.clientId,appVersion:A.appVersion,platform:A.platform});let E=m0(),L=fT(E),J={backendVersion:E,latestBackendVersion:E,backendUpdateAvailable:!1,backendChannel:L==="beta"?"beta":"latest",minAppVersion:Sh,currentAppVersion:A.appVersion,updateRequired:!1,updateAvailable:!1,timestamp:Date.now()},X=`version/check/${A.clientId}/response`;if(this.mqttClient)await this.mqttClient.publish(X,JSON.stringify(J),{qos:1}),this.requestsHandled++,T1.debug("[SystemInfo] Sent version check response",{clientId:A.clientId,backendVersion:E,responseTopic:X});else T1.error("[SystemInfo] MQTT client not available for publishing version response")}catch(A){T1.error("[SystemInfo] Error handling version check request",{error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}}var F0=v();class O5{name="Terminal Config Service";running=!1;startedAt;mqttClient=null;terminalServer;requestsHandled=0;messageHandler;constructor(_){this.terminalServer=_}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,F0.info("[TerminalConfig] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw F0.error("[TerminalConfig] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient&&this.messageHandler)this.mqttClient.unsubscribe("system/terminal-config/request",this.messageHandler),F0.debug("[TerminalConfig] Unsubscribed from system/terminal-config/request"),this.messageHandler=void 0;F0.info("[TerminalConfig] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(_,T)=>{this.handleTerminalConfigRequest(_,T)},this.mqttClient.subscribe("system/terminal-config/request",this.messageHandler),F0.info("[TerminalConfig] MQTT handler registered for system/terminal-config/request")}async handleTerminalConfigRequest(_,T){try{let A=JSON.parse(T.toString());F0.debug("[TerminalConfig] Received terminal config request",{clientId:A.clientId,projectPath:A.projectPath});let E=this.terminalServer.getStatus(),L;if(A.projectPath){let H=this.terminalServer.findSessionByProjectPath(A.projectPath);if(H)L=H,F0.debug("[TerminalConfig] Found existing session for project",{projectPath:A.projectPath,sessionId:H})}let J={enabled:E.running,path:"/terminal",port:E.port,username:E.credentials?.username||"",password:E.credentials?.password||"",timestamp:Date.now(),existingSessionId:L},X=`system/terminal-config/${A.clientId}/response`;if(this.mqttClient)await this.mqttClient.publish(X,JSON.stringify(J),{qos:1}),this.requestsHandled++,F0.debug("[TerminalConfig] Sent terminal config response",{clientId:A.clientId,enabled:J.enabled,port:J.port,responseTopic:X});else F0.error("[TerminalConfig] MQTT client not available for publishing")}catch(A){F0.error("[TerminalConfig] Error handling terminal config request",{error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}}import EN from"path";var o1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};var e=v();class T9{sessions=new Map;tempSessions=new Map;config;callbacks;resolvedClaudePath=null;constructor(_,T={}){this.config=_,this.callbacks=T}async resolveClaudePath(){if(this.resolvedClaudePath)return this.resolvedClaudePath;if(process.platform==="win32"&&process.env.APPDATA){let _=`${process.env.APPDATA}\\npm\\claude.cmd`;try{if(await Bun.file(_).exists())return this.resolvedClaudePath=_,e.info(`[ClaudeProcessManager] Using claude at ${_}`),_}catch(T){e.debug(`[ClaudeProcessManager] claude.cmd not found at ${_}`)}}try{if(await Bun.spawn(["claude","--version"],{stdout:"pipe",stderr:"pipe"}).exited===0)return this.resolvedClaudePath="claude",e.info("[ClaudeProcessManager] Found claude in PATH"),"claude"}catch(_){e.debug("[ClaudeProcessManager] claude not found in PATH")}return e.warn("[ClaudeProcessManager] Claude CLI not found. Please install: npm install -g @anthropic-ai/claude-code"),this.resolvedClaudePath="claude","claude"}async spawnSession(_,T,A,E,L,J,X,H,Z){if(e.info(`[ClaudeProcessManager] Spawning session for project ${A} in ${E}`,{resumeSessionId:J||"new session",permissionMode:X||"default",selectedModel:H||"sonnet"}),this.sessions.size+this.tempSessions.size>=this.config.maxConcurrentSessions)throw Error("Maximum concurrent sessions reached");let Y=this.config.claudeCodePath||await this.resolveClaudePath(),$=["-p","--output-format","stream-json","--input-format","stream-json","--permission-prompt-tool","stdio","--permission-mode",X||"default","--model",H||"sonnet","--verbose"];if(J)$.push("--resume",J),e.info(`[ClaudeProcessManager] Resuming session: ${J}`);e.info(`[ClaudeProcessManager] Spawning: ${Y} ${$.join(" ")}`,{cwd:E,claudePath:Y});try{if((await Bun.$`test -d ${E}`.quiet().nothrow()).exitCode!==0){if(e.info(`[ClaudeProcessManager] Directory does not exist, creating: ${E}`),(await Bun.$`mkdir -p ${E}`.quiet().nothrow()).exitCode!==0)throw Error(`Failed to create directory: ${E}`);e.info(`[ClaudeProcessManager] Directory created successfully: ${E}`)}}catch(N){throw e.error(`[ClaudeProcessManager] Failed to ensure directory exists: ${E}`,{error:N}),Error(`Cannot start session: failed to create directory ${E}`)}let U=Bun.spawn([Y,...$],{cwd:E,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:{...process.env,CI:"1",CLAUDE_HEADLESS:"1"}}),V={tempId:_,userId:T,projectId:A,directoryPath:E,process:U,status:"initializing",permissionMode:X||"default",createdAt:new Date,lastActivity:new Date,messageCount:0};return this.tempSessions.set(_,V),this.setupProcessHandlers(V,U),setTimeout(()=>{this.sendUserMessage(V,L,Z)},100),V}setupProcessHandlers(_,T){let{tempId:A}=_;this.readStdoutLines(T.stdout,_),this.readStderrLines(T.stderr,_),T.exited.then((E)=>{e.info("[ClaudeProcessManager] Claude process exited",{tempId:A,sessionId:_.sessionId,exitCode:E});let L=`exited with code ${E}`;this.handleSessionStopped(_,L)}).catch((E)=>{e.error("[ClaudeProcessManager] Claude process error:",{tempId:A,sessionId:_.sessionId,error:E.message}),this.handleSessionError(_,E.message)})}readStdoutLines(_,T){(async()=>{try{let A=_.pipeThrough(new TextDecoderStream).getReader(),E="";while(!0){let{done:L,value:J}=await A.read();if(L)break;E+=J;let X=E.split(`
|
|
2619
|
+
`);E=X.pop()||"";for(let H of X)if(H.trim())try{let Z=JSON.parse(H);this.handleClaudeMessage(T,Z)}catch(Z){e.error("[ClaudeProcessManager] Failed to parse JSON from Claude:",{tempId:T.tempId,sessionId:T.sessionId,line:H,error:Z instanceof Error?Z.message:"Unknown error"})}}if(E.trim())try{let L=JSON.parse(E);this.handleClaudeMessage(T,L)}catch(L){e.error("[ClaudeProcessManager] Failed to parse final JSON from Claude:",{tempId:T.tempId,sessionId:T.sessionId,buffer:E})}}catch(A){e.error("[ClaudeProcessManager] Error reading stdout:",{tempId:T.tempId,sessionId:T.sessionId,error:A instanceof Error?A.message:"Unknown error"})}})()}readStderrLines(_,T){(async()=>{try{let A=_.pipeThrough(new TextDecoderStream).getReader(),E="";while(!0){let{done:L,value:J}=await A.read();if(L)break;E+=J;let X=E.split(`
|
|
2620
|
+
`);E=X.pop()||"";for(let H of X)if(H.trim())e.warn("[ClaudeProcessManager] Claude stderr:",{tempId:T.tempId,sessionId:T.sessionId,line:H})}if(E.trim())e.warn("[ClaudeProcessManager] Claude stderr (final):",{tempId:T.tempId,sessionId:T.sessionId,line:E})}catch(A){e.error("[ClaudeProcessManager] Error reading stderr:",{tempId:T.tempId,sessionId:T.sessionId,error:A instanceof Error?A.message:"Unknown error"})}})()}handleClaudeMessage(_,T){if(_.stopped)return;switch(_.lastActivity=new Date,T.type){case"system":if(T.subtype==="init")this.handleInitMessage(_,T);break;case"user":this.handleUserMessage(_,T);break;case"assistant":this.handleAssistantMessage(_,T);break;case"result":this.handleResultMessage(_,T);break;case"summary":this.handleSummaryMessage(_,T);break;case"control_request":this.handlePermissionRequest(_,T);break;case"error":this.handleSessionError(_,T.content||"Unknown error");break;default:}}handleInitMessage(_,T){if(!T.session_id){e.error("[ClaudeProcessManager] Init message missing session_id",{tempId:_.tempId}),this.handleSessionError(_,"Init message missing session_id");return}_.sessionId=T.session_id,_.model=T.model,_.status="idle",e.info("[ClaudeProcessManager] Session initialized",{tempId:_.tempId,sessionId:_.sessionId,model:_.model}),this.tempSessions.delete(_.tempId),this.sessions.set(_.sessionId,_),this.callbacks.onSessionInitialized?.(_,T)}handleUserMessage(_,T){let A=T.message;if(!_.firstUserMessage&&A?.content&&Array.isArray(A.content)){let E=A.content.find((L)=>L.type==="text");if(E?.text&&E.text.trim())_.firstUserMessage=E.text.trim()}if(A?.content&&Array.isArray(A.content)){if(A.content.some((L)=>L.type==="tool_result"))e.info("[ClaudeProcessManager] Forwarding tool results from Claude:",{sessionId:_.sessionId,resultCount:A.content.filter((L)=>L.type==="tool_result").length}),this.callbacks.onAssistantMessage?.(_,T)}}handleAssistantMessage(_,T){_.messageCount++;let A=T.message,E=A?.usage;if(E){let J=this.calculateContextBreakdown(E,_.model);_.contextUsage=J,this.callbacks.onContextUpdate?.(_,J)}let L="";if(A?.content&&Array.isArray(A.content))L=A.content.filter((X)=>X.type==="text").map((X)=>X.text).filter(Boolean).join(`
|
|
2621
|
+
`);if(!A?.content||!Array.isArray(A.content)||A.content.length===0)return;T.content=L,this.callbacks.onAssistantMessage?.(_,T)}calculateContextBreakdown(_,T){let A=_.input_tokens||0,E=_.output_tokens||0,L=_.cache_creation_input_tokens||0,J=_.cache_read_input_tokens||0,X=A+L+J,H=o1.SYSTEM_PROMPT,Z=o1.TOOLS_TOTAL,Y=0,K=o1.AUTOCOMPACT_BUFFER,G=Math.max(0,X-H-Z-0),$=X+K,U=this.getContextLimit(T);return{total:$,inputTokens:A,outputTokens:E,cacheCreation:L,cacheRead:J,systemPrompt:H,tools:Z,mcpServers:0,messages:G,autocompactBuffer:K,contextLimit:U,remaining:Math.max(0,U-$),percentage:Math.round($/U*100),lastUpdated:Date.now()}}getContextLimit(_){if(_?.includes("sonnet-4")||_?.includes("claude-sonnet-4"))return o1.CONTEXT_LIMIT_STANDARD;return o1.CONTEXT_LIMIT_STANDARD}getEmptyContextBreakdown(){return{total:0,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:o1.SYSTEM_PROMPT,tools:o1.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:o1.AUTOCOMPACT_BUFFER,contextLimit:o1.CONTEXT_LIMIT_STANDARD,remaining:o1.CONTEXT_LIMIT_STANDARD,percentage:0,lastUpdated:Date.now()}}handleSummaryMessage(_,T){let A=T.summary;if(A&&typeof A==="string"){let E=A.substring(0,100);_.title=E,e.info("[ClaudeProcessManager] Title from summary:",{sessionId:_.sessionId,title:E}),this.callbacks.onTitleGenerated?.(_,E)}}handleResultMessage(_,T){if(e.info("[ClaudeProcessManager] Result message received:",{sessionId:_.sessionId,subtype:T.subtype,isError:T.is_error}),T.subtype==="success"&&!T.is_error){if(_.status="idle",_.lastActivity=new Date,!_.title&&_.firstUserMessage){let A=_.firstUserMessage.substring(0,50)+(_.firstUserMessage.length>50?"...":"");_.title=A,e.info("[ClaudeProcessManager] Fallback title from first message:",{sessionId:_.sessionId,title:A}),this.callbacks.onTitleGenerated?.(_,A)}this.callbacks.onProcessingComplete?.(_)}else if(T.is_error){let A=T.result||"Unknown error";this.handleSessionError(_,A)}}handlePermissionRequest(_,T){_.status="waiting_permission",e.info("[ClaudeProcessManager] Permission request:",{sessionId:_.sessionId,fullRequest:JSON.stringify(T),requestId:T.request_id,action:T.action}),this.callbacks.onPermissionRequest?.(_,T)}handleSessionError(_,T){_.status="error",e.error("[ClaudeProcessManager] Session error:",{tempId:_.tempId,sessionId:_.sessionId,error:T}),this.callbacks.onSessionError?.(_,T);let A=_.sessionId??_.tempId;this.stopSession(A)}handleSessionStopped(_,T){if(_.respawning){e.info("[ClaudeProcessManager] Skipping session_stopped - session is respawning:",{tempId:_.tempId,sessionId:_.sessionId});return}if(_.status="stopped",e.info("[ClaudeProcessManager] Session stopped:",{tempId:_.tempId,sessionId:_.sessionId,reason:T}),this.callbacks.onSessionStopped?.(_,T),_.sessionId)this.sessions.delete(_.sessionId);this.tempSessions.delete(_.tempId)}sendUserMessage(_,T,A){if(!_.process)throw e.error("[ClaudeProcessManager] Cannot send message - process not found:",{tempId:_.tempId,sessionId:_.sessionId,status:_.status}),Error("Session process not found or has been terminated");let E=[];if(T&&T.trim())E.push({type:"text",text:T});if(A&&A.length>0)for(let H of A)E.push({type:"image",source:{type:"base64",media_type:H.mimeType,data:H.data}});let J=JSON.stringify({type:"user",message:{role:"user",content:E}})+`
|
|
2622
|
+
`;_.process.stdin.write(J),_.lastActivity=new Date,_.messageCount++,_.status="processing",this.callbacks.onProcessingStarted?.(_)}sendPermissionResponse(_,T){let A=this.sessions.get(_);if(!A){e.warn(`[ClaudeProcessManager] Session not found for permission response: ${_}`);return}let E;if(T.behavior==="allow")E={behavior:"allow",updatedInput:T.updatedInput||{}};else if(E={behavior:"deny",message:T.message||"Permission denied by user"},T.hardDeny===!0)E.continue=!1;let L={type:"control_response",response:{subtype:"success",request_id:T.request_id,response:E}},J=JSON.stringify(L)+`
|
|
2623
|
+
`;A.process.stdin.write(J),e.info("[ClaudeProcessManager] Sent permission response:",{sessionId:_,request_id:T.request_id,behavior:T.behavior,hardDeny:T.hardDeny,hasMessage:!!T.message,fullResponse:J.trim()}),A.lastActivity=new Date,A.status="idle"}async respawnWithPermissionMode(_,T,A="proceed with implementation"){let E=this.sessions.get(_);if(!E)return e.warn(`[ClaudeProcessManager] Cannot respawn - session not found: ${_}`),null;let{tempId:L,userId:J,projectId:X,directoryPath:H,model:Z}=E;e.info("[ClaudeProcessManager] Respawning session with new permission mode:",{sessionId:_,newPermissionMode:T,continuationMessage:A}),E.respawning=!0;let Y=E.process;if(Y&&!Y.killed)Y.kill();this.sessions.delete(_);try{let K=await this.spawnSession(L,J,X,H,A,_,T,Z);return e.info("[ClaudeProcessManager] Session respawned successfully:",{sessionId:_,newPermissionMode:T,newTempId:K.tempId}),K}catch(K){return e.error("[ClaudeProcessManager] Failed to respawn session:",{sessionId:_,newPermissionMode:T,error:K instanceof Error?K.message:"Unknown error"}),null}}stopSession(_){let T=this.sessions.get(_)||this.tempSessions.get(_);if(!T){e.warn(`[ClaudeProcessManager] Session not found: ${_}`);return}e.info("[ClaudeProcessManager] Stopping session:",{tempId:T.tempId,sessionId:T.sessionId}),T.stopped=!0;let A=T.process;if(A&&!A.killed){try{A.stdin?.end?.()}catch{}A.kill("SIGKILL")}this.sessions.delete(T.sessionId),this.tempSessions.delete(T.tempId)}stopAll(){e.info(`[ClaudeProcessManager] Stopping all sessions (${this.sessions.size+this.tempSessions.size} total)`);for(let[_]of this.sessions)this.stopSession(_);for(let[_]of this.tempSessions)this.stopSession(_)}getSession(_){return this.sessions.get(_)||this.tempSessions.get(_)}getAllSessions(){return[...this.sessions.values(),...this.tempSessions.values()]}getSessionCount(){return this.sessions.size+this.tempSessions.size}cleanupInactiveSessions(){let _=Date.now(),T=this.config.sessionTimeoutMs;for(let A of this.getAllSessions()){let E=_-A.lastActivity.getTime();if(E>T)e.info("[ClaudeProcessManager] Cleaning up inactive session:",{sessionId:A.sessionId,tempId:A.tempId,inactiveMs:E}),this.stopSession(A.sessionId||A.tempId)}}}var{$:u}=globalThis.Bun;var U_=v(),yh=300000,wW=new Map,A9=null;function SW(_){if(!_)return!1;return Date.now()-_.timestamp<yh}function vh(_){let T=wW.get(_);if(SW(T))return T.data;return null}function jW(_,T){wW.set(_,{data:T,timestamp:Date.now()})}function hh(){if(SW(A9))return A9.data;return null}function xW(_){A9={data:_,timestamp:Date.now()}}function kh(){let _=process.platform,T=process.env.HOME||process.env.USERPROFILE||"";if(_==="win32")return["C:\\Program Files\\GitHub CLI\\gh.exe","C:\\Program Files (x86)\\GitHub CLI\\gh.exe",`${process.env.USERPROFILE}\\scoop\\shims\\gh.exe`,`${process.env.USERPROFILE}\\scoop\\apps\\gh\\current\\bin\\gh.exe`,"C:\\ProgramData\\chocolatey\\bin\\gh.exe",`${process.env.LOCALAPPDATA}\\GitHub CLI\\gh.exe`];else if(_==="darwin")return["/opt/homebrew/bin/gh","/usr/local/bin/gh","/usr/bin/gh",`${T}/.local/bin/gh`];else return["/usr/bin/gh","/usr/local/bin/gh","/snap/bin/gh",`${T}/.local/bin/gh`,"/home/linuxbrew/.linuxbrew/bin/gh"]}async function fh(){let _=kh();for(let T of _)try{if(await Bun.file(T).exists())return T}catch{}return null}async function yW(){try{if((await u`gh --version`.quiet()).exitCode===0)return await bh("gh")}catch{}let _=await fh();if(_)try{if((await u`${_} --version`.quiet()).exitCode===0)return{authenticated:!1,installed:!0,inPath:!1,ghPath:_,error:`GitHub CLI (gh) is installed at "${_}" but not in your system PATH. Add its directory to your system PATH environment variable and restart the backend.`}}catch{}return{authenticated:!1,installed:!1,inPath:!1,error:"GitHub CLI (gh) is not installed. Install it from https://cli.github.com and ensure it is added to your system PATH."}}async function bh(_){try{let T=await u`${_} auth status`,A=T.stdout.toString(),E=T.stderr.toString();if(T.exitCode===0)return{authenticated:!0,installed:!0,inPath:!0,username:(A.match(/Logged in to .* as (\S+)/)||E.match(/Logged in to .* as (\S+)/))?.[1]};else return{authenticated:!1,installed:!0,inPath:!0,error:'GitHub CLI is installed but not authenticated. Run "gh auth login" in your terminal to authenticate.'}}catch(T){return{authenticated:!1,installed:!0,inPath:!0,error:'GitHub CLI is installed but authentication check failed. Try running "gh auth login" in your terminal.'}}}async function E9(){let _=hh();if(_)return _;try{let T=await u`gh api /user/orgs --jq '.[] | {login, id, description, avatar_url}'`.text();if(!T.trim())return xW([]),[];let A=T.trim().split(`
|
|
2624
|
+
`).filter((E)=>E.trim()).map((E)=>{let L=JSON.parse(E);return{login:L.login,id:L.id,description:L.description||void 0,avatarUrl:L.avatar_url||void 0}});return xW(A),A}catch(T){throw U_.error("[GitExecutor] Failed to fetch orgs",{error:T}),Error(`Failed to fetch organizations: ${T instanceof Error?T.message:"Unknown error"}`)}}async function R5(_,T=20){let A=`${_||"personal"}_${T}`,E=vh(A);if(E)return E;try{let J=await(_?u`gh repo list ${_} --json id,name,nameWithOwner,description,url,sshUrl,defaultBranchRef,isPrivate,owner --limit ${T}`:u`gh repo list --json id,name,nameWithOwner,description,url,sshUrl,defaultBranchRef,isPrivate,owner --limit ${T} --source`).text();if(!J.trim())return jW(A,[]),[];let H=JSON.parse(J).map((Y)=>{let K=Y.nameWithOwner?.split("/")[0]||"",G=Y.owner?.login||K;return{id:Y.id||0,name:Y.name,fullName:Y.nameWithOwner,description:Y.description||void 0,cloneUrl:Y.url?`${Y.url}.git`:"",sshUrl:Y.sshUrl||"",defaultBranch:Y.defaultBranchRef?.name||"main",private:Y.isPrivate||!1,owner:{login:G,avatarUrl:Y.owner?.avatarUrl||void 0}}}),Z=H;if(_)Z=H.filter((Y)=>Y.owner.login.toLowerCase()===_.toLowerCase());return jW(A,Z),Z}catch(L){throw U_.error("[GitExecutor] Failed to fetch repos",{error:L,org:_}),Error(`Failed to fetch repositories: ${L instanceof Error?L.message:"Unknown error"}`)}}async function vW(_,T,A=50){if(!_.trim()){await T([],"none",!0);return}let E=_.toLowerCase(),L=(J)=>{return J.filter((X)=>X.name.toLowerCase().includes(E)||X.fullName.toLowerCase().includes(E)||X.description?.toLowerCase().includes(E)).slice(0,A)};try{let[J,X]=await Promise.all([R5(void 0,100),E9()]),H=L(J);if(H.length>0)await T(H,"personal",X.length===0);if(X.length===0){if(H.length===0)await T([],"none",!0);return}let Z=await Promise.all(X.map(async(K)=>{try{let G=await R5(K.login,100);return{org:K.login,repos:L(G),error:null}}catch(G){return U_.warn("[GitExecutor] Failed to search org repos",{org:K.login,error:G}),{org:K.login,repos:[],error:G}}})),Y=[];for(let K of Z)Y.push(...K.repos);await T(Y,"organizations",!0)}catch(J){U_.error("[GitExecutor] Failed to search repos",{error:J,query:_}),await T([],"error",!0)}}async function hW(_,T){try{let E=(await u`gh api repos/${_}/${T}/branches --paginate --jq '.[].name'`.text()).trim().split(`
|
|
2625
|
+
`).filter((X)=>X.trim()),J=(await u`gh api repos/${_}/${T} --jq '.default_branch'`.text()).trim()||"main";return{branches:E,defaultBranch:J}}catch(A){throw U_.error("[GitExecutor] Failed to fetch branches",{error:A,owner:_,repo:T}),Error(`Failed to fetch branches: ${A instanceof Error?A.message:"Unknown error"}`)}}async function kW(_,T,A,E){try{E?.({phase:"receiving",percent:0,message:"Starting clone..."});let J=await u`gh repo clone ${A?[_,T,"--","-b",A]:[_,T]}`.quiet();if(J.exitCode!==0){let Z=J.stderr.toString();throw Error(Z||"Clone failed")}E?.({phase:"done",percent:100,message:"Clone complete"});let H=(await u`git -C ${T} symbolic-ref --short HEAD`.text()).trim()||A||"main";return{success:!0,path:T,defaultBranch:H}}catch(L){return U_.error("[GitExecutor] Clone failed",{error:L,repoUrl:_,targetPath:T}),{success:!1,error:L instanceof Error?L.message:"Clone failed"}}}async function fW(_,T,A){try{let E=await u`git -C ${_} worktree add ${T} -b ${A}`.quiet();if(E.exitCode!==0){let X=E.stderr.toString();throw Error(X||"Failed to create worktree")}let J=(await u`git -C ${T} rev-parse HEAD`.text()).trim();return{path:T,branch:A,head:J,isMain:!1,createdAt:new Date}}catch(E){throw U_.error("[GitExecutor] Failed to create worktree",{error:E,repoPath:_,worktreePath:T}),Error(`Failed to create worktree: ${E instanceof Error?E.message:"Unknown error"}`)}}async function w8(_){try{let T=await u`git -C ${_} worktree list --porcelain`.text(),A=[],E={};for(let L of T.split(`
|
|
2626
|
+
`))if(L.startsWith("worktree ")){if(E.path)A.push(E);E={path:L.substring(9),isMain:!1}}else if(L.startsWith("HEAD "))E.head=L.substring(5);else if(L.startsWith("branch ")){let J=L.substring(7);E.branch=J.replace("refs/heads/","")}else if(L==="bare")E.isMain=!0;else if(L===""){if(E.path){if(A.length===0&&!E.isMain)E.isMain=!0;A.push(E),E={}}}if(E.path){if(A.length===0)E.isMain=!0;A.push(E)}return A}catch(T){throw U_.error("[GitExecutor] Failed to list worktrees",{error:T,repoPath:_}),Error(`Failed to list worktrees: ${T instanceof Error?T.message:"Unknown error"}`)}}async function D5(_,T){try{let E=(await w8(_)).find((L)=>L.path.includes(T)||L.branch?.includes(T));if(E)return E.sessionId=T,E;return null}catch(A){return U_.error("[GitExecutor] Failed to find worktree by session ID",{error:A,repoPath:_,sessionId:T}),null}}async function L9(_){try{let A=(await u`git -C ${_} branch --show-current`.text()).trim()||"HEAD",E=0,L=0,J;try{if(J=(await u`git -C ${_} rev-parse --abbrev-ref @{upstream}`.text()).trim(),J){let K=(await u`git -C ${_} rev-list --left-right --count HEAD...@{upstream}`.text()).trim().split(/\s+/);E=parseInt(K[0]||"0",10)||0,L=parseInt(K[1]||"0",10)||0}}catch{}let X=await u`git -C ${_} status --porcelain=v2`.text(),H=[];for(let Z of X.split(`
|
|
2627
|
+
`)){if(!Z.trim())continue;let Y=gh(Z);if(Y)H.push(Y)}return{branch:A,ahead:E,behind:L,upstream:J,files:H,hasChanges:H.length>0}}catch(T){throw U_.error("[GitExecutor] Failed to get status",{error:T,path:_}),Error(`Failed to get git status: ${T instanceof Error?T.message:"Unknown error"}`)}}function gh(_){if(_.startsWith("?"))return{path:_.substring(2),status:"untracked",staged:!1};if(_.startsWith("!"))return{path:_.substring(2),status:"ignored",staged:!1};if(_.startsWith("1 ")||_.startsWith("2 ")){let T=_.split(" ");if(T.length<9)return null;let A=T[1]||"",E=A[0]||".",L=A[1]||".",X=T.slice(8).join(" ").split("\t"),H=X[0]||"",Z=X[1],Y=mh(E,L,_.startsWith("2 "));return{path:H,status:Y,staged:E!=="."&&E!=="?",oldPath:Z||void 0}}return null}function mh(_,T,A){if(A)return"renamed";if(_==="A")return"added";if(_==="D")return"deleted";if(_==="M")return"modified";if(_==="C")return"copied";if(T==="A")return"added";if(T==="D")return"deleted";if(T==="M")return"modified";return"modified"}async function bW(_,T,A=!1){try{let E=["-C",_,"diff"];if(A)E.push("--staged");if(T)E.push("--",T);let L=await u`git ${E}`.text(),J=L.includes("Binary files")||L.includes("GIT binary patch");if(!L.trim()&&T){if((await u`git -C ${_} status --porcelain -- ${T}`.text()).trim().startsWith("??")){let Z=await import("fs"),K=(await import("path")).default.join(_,T);if(Z.existsSync(K)){let G=Z.statSync(K);if(G.isDirectory())return{diff:"__DIRECTORY__",isBinary:!1};if(G.isFile()){let $=Z.readFileSync(K,"utf-8"),U=$.split(`
|
|
2628
|
+
`);if($.includes("\x00"))return{diff:`Binary file: ${T}`,isBinary:!0};return{diff:[`diff --git a/${T} b/${T}`,"new file mode 100644","--- /dev/null",`+++ b/${T}`,`@@ -0,0 +1,${U.length} @@`,...U.map((Q)=>`+${Q}`)].join(`
|
|
2629
|
+
`),isBinary:!1}}}}}return{diff:L,isBinary:J}}catch(E){throw U_.error("[GitExecutor] Failed to get diff",{error:E,path:_,file:T,staged:A}),Error(`Failed to get diff: ${E instanceof Error?E.message:"Unknown error"}`)}}async function gW(_,T){try{if(T.length===0)return;let A=await u`git -C ${_} add ${T}`.quiet();if(A.exitCode!==0){let E=A.stderr.toString();throw Error(E||"Failed to stage files")}}catch(A){throw U_.error("[GitExecutor] Failed to stage files",{error:A,path:_,files:T}),Error(`Failed to stage files: ${A instanceof Error?A.message:"Unknown error"}`)}}async function mW(_,T){try{if(T.length===0)return;let A=await u`git -C ${_} reset HEAD -- ${T}`.quiet();if(A.exitCode!==0){let E=A.stderr.toString();throw Error(E||"Failed to unstage files")}}catch(A){throw U_.error("[GitExecutor] Failed to unstage files",{error:A,path:_,files:T}),Error(`Failed to unstage files: ${A instanceof Error?A.message:"Unknown error"}`)}}async function uW(_,T,A=!1){try{let E=["-C",_,"commit","-m",T];if(A)E.push("--signoff");let L=await u`git ${E}`.quiet();if(L.exitCode!==0){let R=L.stderr.toString();throw Error(R||"Commit failed")}let H=(await u`git -C ${_} log -1 --format=${"%H%n%h%n%s%n%an%n%ae%n%aI"}`.text()).trim().split(`
|
|
2630
|
+
`),Z=H[0]||"",Y=H[1]||"",K=H[2]||"",G=H[3]||"",$=H[4]||"",U=H[5]||"",N=(await u`git -C ${_} diff-tree --no-commit-id --shortstat HEAD`.text()).match(/(\d+) files? changed(?:, (\d+) insertions?)?(?:, (\d+) deletions?)?/),z=N?.[1]?parseInt(N[1],10):0,Q=N?.[2]?parseInt(N[2],10):0,F=N?.[3]?parseInt(N[3],10):0;return{hash:Z,shortHash:Y,message:K,author:G,authorEmail:$,timestamp:U,filesChanged:z,insertions:Q,deletions:F}}catch(E){throw U_.error("[GitExecutor] Failed to create commit",{error:E,path:_}),Error(`Failed to create commit: ${E instanceof Error?E.message:"Unknown error"}`)}}async function dW(_,T,A){try{let E=await u`git -C ${_} branch -m ${T} ${A}`.quiet();if(E.exitCode!==0){let L=E.stderr.toString();throw Error(L||"Failed to rename branch")}}catch(E){throw U_.error("[GitExecutor] Failed to rename branch",{error:E,repoPath:_,oldBranch:T,newBranch:A}),Error(`Failed to rename branch: ${E instanceof Error?E.message:"Unknown error"}`)}}async function cW(_,T,A){try{let E=await u`git -C ${_} worktree move ${T} ${A}`.quiet();if(E.exitCode!==0){let L=E.stderr.toString();throw Error(L||"Failed to move worktree")}}catch(E){throw U_.error("[GitExecutor] Failed to move worktree",{error:E,repoPath:_,oldPath:T,newPath:A}),Error(`Failed to move worktree: ${E instanceof Error?E.message:"Unknown error"}`)}}async function z4(_){try{return(await u`git -C ${_} rev-parse --is-inside-work-tree`.quiet()).exitCode===0}catch{return!1}}async function C0(_){try{return(await u`git -C ${_} rev-parse --show-toplevel`.text()).trim()||null}catch{return null}}async function pW(_,T="origin"){try{return(await u`git -C ${_} remote get-url ${T}`.text()).trim()||null}catch{return null}}async function F4(_){try{return(await u`git -C ${_} symbolic-ref --short HEAD`.text()).trim()||null}catch{return null}}async function V4(_){try{let T;try{T=(await u`git -C ${_} rev-parse --abbrev-ref @{upstream}`.text()).trim()}catch{return{commits:[],ahead:0}}if(!T)return{commits:[],ahead:0};let E=await u`git -C ${_} log @{upstream}..HEAD --format=${"%H|%h|%s|%an|%aI"}`.text();if(!E.trim())return{commits:[],upstream:T,ahead:0};let L=E.trim().split(`
|
|
2631
|
+
`).filter((J)=>J.trim()).map((J)=>{let X=J.split("|");return{hash:X[0]||"",shortHash:X[1]||"",message:X[2]||"",author:X[3]||"",timestamp:X[4]||""}});return{commits:L,upstream:T,ahead:L.length}}catch(T){throw U_.error("[GitExecutor] Failed to get unpushed commits",{error:T,path:_}),Error(`Failed to get unpushed commits: ${T instanceof Error?T.message:"Unknown error"}`)}}async function lW(_,T=!1){try{let A=await F4(_);if(!A)throw Error("Not on a branch");let{ahead:E}=await V4(_),L=["-C",_,"push"];if(T)L.push("--force-with-lease");L.push("-u","origin",A);let J=await u`git ${L}`.quiet();if(J.exitCode!==0){let X=J.stderr.toString();throw Error(X||"Push failed")}return{commitsPushed:E,remote:"origin",branch:A}}catch(A){throw U_.error("[GitExecutor] Failed to push commits",{error:A,path:_}),Error(`Failed to push: ${A instanceof Error?A.message:"Unknown error"}`)}}async function nW(_,T=50){try{let E=await u`git -C ${_} log -n ${T} --format=${"%H|%h|%s|%an|%aI"} --shortstat`.text();if(!E.trim())return{commits:[],totalCount:0};let L=[],J=E.trim().split(`
|
|
2632
|
+
`),X=0;while(X<J.length){let Z=J[X]?.trim();if(!Z){X++;continue}if(Z.includes("|")){let Y=Z.split("|"),K=Y[0]||"",G=Y[1]||"",$=Y[2]||"",U=Y[3]||"",V=Y[4]||"",N=0,z=0,Q=0,F=X+1;while(F<J.length&&!J[F]?.includes("|")){let R=J[F]?.trim();if(R){let q=R.match(/(\d+) files? changed/),f=R.match(/(\d+) insertions?\(\+\)/),h=R.match(/(\d+) deletions?\(-\)/);if(q?.[1])N=parseInt(q[1],10);if(f?.[1])z=parseInt(f[1],10);if(h?.[1])Q=parseInt(h[1],10);break}F++}L.push({hash:K,shortHash:G,message:$,author:U,timestamp:V,filesChanged:N,insertions:z,deletions:Q})}X++}let H=L.length;try{let Z=await u`git -C ${_} rev-list --count HEAD`.text();H=parseInt(Z.trim(),10)||L.length}catch{}return{commits:L,totalCount:H}}catch(A){throw U_.error("[GitExecutor] Failed to get commit history",{error:A,path:_}),Error(`Failed to get commit history: ${A instanceof Error?A.message:"Unknown error"}`)}}async function iW(_,T){try{let L=(await u`git -C ${_} log -1 --format=${"%H%n%h%n%s%n%b%n%an%n%ae%n%aI"} ${T}`.text()).trim().split(`
|
|
2633
|
+
`),J=L[0]||"",X=L[1]||"",H=L[2]||"",Z=L.length-3,Y=L.slice(3,Z).join(`
|
|
2634
|
+
`).trim(),K=L[Z]||"",G=L[Z+1]||"",$=L[Z+2]||"",U=await u`git -C ${_} diff-tree --no-commit-id --numstat -r -M -C ${T}`.text(),V=[],N=0,z=0;for(let F of U.trim().split(`
|
|
2635
|
+
`)){if(!F.trim())continue;let R=F.split("\t");if(R.length<3)continue;let q=R[0]==="-"?0:parseInt(R[0]||"0",10),f=R[1]==="-"?0:parseInt(R[1]||"0",10),h=R.slice(2).join("\t");if(N+=q,z+=f,h.includes(" => ")){let[b,l]=h.split(" => ").map((c)=>c.trim().replace(/[{}]/g,""));V.push({path:l||"",oldPath:b||"",status:"renamed",insertions:q,deletions:f})}else V.push({path:h,status:"modified",insertions:q,deletions:f})}let Q=await u`git -C ${_} diff-tree --no-commit-id --name-status -r -M -C ${T}`.text();for(let F of Q.trim().split(`
|
|
2636
|
+
`)){if(!F.trim())continue;let R=F.split("\t");if(R.length<2)continue;let q=R[0]?.[0]||"M",f=R.length>2?R[2]:R[1],h=V.find((b)=>b.path===f||b.oldPath===R[1]);if(h)switch(q){case"A":h.status="added";break;case"D":h.status="deleted";break;case"R":h.status="renamed";break;case"C":h.status="copied";break;default:h.status="modified"}}return{hash:J,shortHash:X,message:H,body:Y,author:K,authorEmail:G,timestamp:$,files:V,totalInsertions:N,totalDeletions:z}}catch(A){throw U_.error("[GitExecutor] Failed to get commit details",{error:A,path:_,commitHash:T}),Error(`Failed to get commit details: ${A instanceof Error?A.message:"Unknown error"}`)}}async function aW(_){try{let T=await F4(_);if(!T)return{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:"Not on a branch"};let A;try{A=(await u`git -C ${_} rev-parse --abbrev-ref @{upstream}`.text()).trim()}catch{U_.info("[GitExecutor] No upstream set, setting up tracking",{path:_,branch:T});try{await u`git -C ${_} branch --set-upstream-to=origin/${T} ${T}`.quiet(),A=`origin/${T}`}catch{return{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:`No upstream branch configured. Push your branch first with: git push -u origin ${T}`}}}let{ahead:E}=await V4(_),L=await u`git -C ${_} fetch origin`.quiet();if(L.exitCode!==0)return{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:`Fetch failed: ${L.stderr.toString()}`};let J=0;try{let H=await u`git -C ${_} rev-list --count HEAD..@{upstream}`.text();J=parseInt(H.trim(),10)||0}catch{}if(J===0&&E===0)return{success:!0,action:"up-to-date",commitsPulled:0,commitsPushed:0};if(J>0){if((await u`git -C ${_} rebase @{upstream}`.quiet()).exitCode!==0){let Y=(await u`git -C ${_} diff --name-only --diff-filter=U`.text()).trim().split(`
|
|
2637
|
+
`).filter((K)=>K.trim());return await u`git -C ${_} rebase --abort`.quiet(),{success:!1,action:"conflict",commitsPulled:0,commitsPushed:0,conflictedFiles:Y,error:`Rebase failed due to conflicts in ${Y.length} file(s). Please resolve conflicts on desktop.`}}}let{ahead:X}=await V4(_);if(X>0){let H=await u`git -C ${_} push origin ${T}`.quiet();if(H.exitCode!==0){let Z=H.stderr.toString();if(Z.includes("rejected")||Z.includes("non-fast-forward"))return{success:!1,action:"diverged",commitsPulled:J,commitsPushed:0,error:"Push rejected. Remote has new changes. Please sync again."};return{success:!1,action:"error",commitsPulled:J,commitsPushed:0,error:`Push failed: ${Z}`}}}return{success:!0,action:"synced",commitsPulled:J,commitsPushed:X}}catch(T){return U_.error("[GitExecutor] Sync failed",{error:T,path:_}),{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:T instanceof Error?T.message:"Sync failed"}}}async function oW(_,T,A){try{let E,L=!1;try{E=await u`git -C ${_} diff ${T}^..${T} -- ${A}`.text()}catch{E=await u`git -C ${_} diff ${"4b825dc642cb6eb9a060e54bf8d69288fbee4904"}..${T} -- ${A}`.text()}if(E.includes("Binary files")||E.includes("GIT binary patch"))L=!0;return{diff:E,isBinary:L}}catch(E){throw U_.error("[GitExecutor] Failed to get commit file diff",{error:E,path:_,commitHash:T,filePath:A}),Error(`Failed to get file diff: ${E instanceof Error?E.message:"Unknown error"}`)}}async function rW(_,T,A,E,L=!1){try{let J=await F4(_);if(!J)return{success:!1,error:"Not on a branch"};let{ahead:X}=await V4(_);if(X>0){let $=await u`git -C ${_} push -u origin ${J}`.quiet();if($.exitCode!==0)return{success:!1,error:`Failed to push branch: ${$.stderr.toString()}`}}let H=["pr","create","--title",T];if(A)H.push("--body",A);else H.push("--body","");if(E)H.push("--base",E);if(L)H.push("--draft");let Y=(await u`gh ${H}`.cwd(_).text()).trim(),K=Y.match(/\/pull\/(\d+)$/);return{success:!0,prNumber:K&&K[1]?parseInt(K[1],10):void 0,prUrl:Y}}catch(J){U_.error("[GitExecutor] Failed to create pull request",{error:J,path:_});let X=J instanceof Error?J.message:"Unknown error";if(X.includes("already exists")||X.includes("A pull request for branch"))return{success:!1,error:"A pull request for this branch already exists"};return{success:!1,error:`Failed to create pull request: ${X}`}}}async function sW(_){try{if(!await F4(_))return{exists:!1,error:"Not on a branch"};let A=await u`gh pr view --json number,url,title,state,isDraft`.cwd(_).quiet();if(A.exitCode!==0){let L=A.stderr.toString();if(L.includes("no pull requests found")||L.includes("Could not resolve"))return{exists:!1};return{exists:!1,error:L}}let E=JSON.parse(A.stdout.toString());return{exists:!0,prNumber:E.number,prUrl:E.url,title:E.title,state:E.state.toLowerCase(),draft:E.isDraft}}catch(T){U_.error("[GitExecutor] Failed to check for existing PR",{error:T,path:_});let A=T instanceof Error?T.message:String(T);if(A.includes("no pull requests found")||A.includes("Could not resolve"))return{exists:!1};return{exists:!1,error:`Failed to check for existing PR: ${A}`}}}async function J9(_){try{let A=(await u`gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name'`.cwd(_).text()).trim();if(A)return A;let E=await u`git -C ${_} branch -r`.text();if(E.includes("origin/main"))return"main";if(E.includes("origin/master"))return"master";return null}catch(T){return U_.error("[GitExecutor] Failed to get default branch",{error:T,path:_}),null}}async function tW(_){try{await u`git -C ${_} fetch --prune`.quiet();let A=(await u`git -C ${_} branch -r`.text()).split(`
|
|
2638
|
+
`).map((L)=>L.trim()).filter((L)=>L&&!L.includes("HEAD")&&!L.includes("->")).map((L)=>L.replace(/^origin\//,"")),E=await J9(_);return{branches:A,defaultBranch:E}}catch(T){return U_.error("[GitExecutor] Failed to get remote branches",{error:T,path:_}),{branches:[],defaultBranch:null}}}import*as r_ from"path";import*as D_ from"fs";import*as H9 from"os";var $_=v();function C4(_){return r_.normalize(_).toLowerCase()}var uh="worktrees",dh="sessions";function X9(){return r_.join(H9.homedir(),".ccc",dh)}function ch(){let _=new Date,T=_.getFullYear(),A=String(_.getMonth()+1).padStart(2,"0"),E=String(_.getDate()).padStart(2,"0"),L=String(_.getHours()).padStart(2,"0"),J=String(_.getMinutes()).padStart(2,"0");return`${T}${A}${E}-${L}${J}`}class O4{worktreeCache=new Map;saveSessionMapping(_,T){try{let A=X9();if(!D_.existsSync(A))D_.mkdirSync(A,{recursive:!0});let E=r_.join(A,_);D_.writeFileSync(E,T,"utf-8"),$_.debug("[WorktreeManager] Saved session mapping",{sessionId:_,worktreePath:T})}catch(A){$_.error("[WorktreeManager] Failed to save session mapping",{error:A,sessionId:_,worktreePath:T})}}loadSessionMapping(_){try{let T=r_.join(X9(),_);if(D_.existsSync(T)){let A=D_.readFileSync(T,"utf-8").trim();if(D_.existsSync(A))return A;else D_.unlinkSync(T),$_.debug("[WorktreeManager] Removed stale session mapping",{sessionId:_,worktreePath:A})}}catch(T){$_.error("[WorktreeManager] Failed to load session mapping",{error:T,sessionId:_})}return null}deleteSessionMapping(_){try{let T=r_.join(X9(),_);if(D_.existsSync(T))D_.unlinkSync(T),$_.debug("[WorktreeManager] Deleted session mapping",{sessionId:_})}catch(T){$_.error("[WorktreeManager] Failed to delete session mapping",{error:T,sessionId:_})}}getWorktreesBasePath(_){let T=r_.basename(_),A=r_.join(H9.homedir(),".ccc");return r_.join(A,`${T}-${uh}`)}getWorktreePath(_,T){let A=this.getWorktreesBasePath(_),E=T.replace(/[^a-zA-Z0-9_-]/g,"_");return r_.join(A,E)}generateBranchName(_){return`session/${_.replace(/[^a-zA-Z0-9_-]/g,"_")}`}async getOrCreateForSession(_,T){$_.debug("[WorktreeManager] getOrCreateForSession",{sessionId:_,repoPath:T});let A=this.worktreeCache.get(_);if(A)if(D_.existsSync(A.path))return $_.debug("[WorktreeManager] Returning cached worktree",{sessionId:_,path:A.path}),{worktree:A,isNew:!1};else this.worktreeCache.delete(_);let E=this.loadSessionMapping(_);if(E&&D_.existsSync(E)){let V=await C0(T);if(V){let N=await w8(V),z=C4(E),Q=N.find((F)=>C4(F.path)===z);if(Q)return Q.sessionId=_,this.worktreeCache.set(_,Q),$_.debug("[WorktreeManager] Found worktree from session mapping",{sessionId:_,path:E}),{worktree:Q,isNew:!1};else $_.warn("[WorktreeManager] Worktree path exists on disk but not found in git worktree list",{mappedWorktreePath:E})}}if(!await z4(T))throw Error(`Not a git repository: ${T}`);let J=await C0(T);if(!J)throw Error(`Could not determine repository root for: ${T}`);let X=await D5(J,_);if(X)return X.sessionId=_,this.worktreeCache.set(_,X),this.saveSessionMapping(_,X.path),$_.debug("[WorktreeManager] Found existing worktree (legacy)",{sessionId:_,path:X.path}),{worktree:X,isNew:!1};let H=this.getWorktreePath(J,_);if(D_.existsSync(H)){$_.warn("[WorktreeManager] Worktree path exists but not in git worktree list",{expectedPath:H});let V=await w8(J),N=C4(H),z=V.find((Q)=>C4(Q.path)===N);if(z)return z.sessionId=_,this.worktreeCache.set(_,z),{worktree:z,isNew:!1}}let Z=ch(),Y=this.getWorktreesBasePath(J),K=r_.join(Y,Z),G=`session/${Z}`,$=0;while(D_.existsSync(K)){$++;let V=`${Z}-${$}`;K=r_.join(Y,V),G=`session/${V}`}if(!D_.existsSync(Y))D_.mkdirSync(Y,{recursive:!0}),$_.debug("[WorktreeManager] Created worktrees base directory",{basePath:Y});let U=await fW(J,K,G);return U.sessionId=_,this.saveSessionMapping(_,K),this.worktreeCache.set(_,U),$_.info("[WorktreeManager] Created new worktree",{sessionId:_,worktreeName:r_.basename(K),path:U.path,branch:U.branch}),{worktree:U,isNew:!0}}async getWorktreeForSession(_,T){$_.debug("[WorktreeManager] getWorktreeForSession",{sessionId:_,repoPath:T});let A=this.worktreeCache.get(_);if(A)if(D_.existsSync(A.path))return A;else this.worktreeCache.delete(_);let E=await C0(T);if(!E)return null;let L=await D5(E,_);if(L)L.sessionId=_,this.worktreeCache.set(_,L);return L}async listWorktreesForRepo(_){$_.debug("[WorktreeManager] listWorktreesForRepo",{repoPath:_});let T=await C0(_);if(!T)throw Error(`Could not determine repository root for: ${_}`);let A=await w8(T);for(let E of A)if(!E.isMain)if(E.branch?.startsWith("session/"))E.sessionId=E.branch.substring(8);else{let L=this.getWorktreesBasePath(T);if(C4(E.path).startsWith(C4(L))){let J=r_.basename(E.path);E.sessionId=J}}for(let E of A)if(E.sessionId)this.worktreeCache.set(E.sessionId,E);return A}getActiveWorktreeCount(){return this.worktreeCache.size}clearCache(){this.worktreeCache.clear()}removeFromCache(_){this.worktreeCache.delete(_)}updateSessionId(_,T,A){try{this.deleteSessionMapping(T),this.saveSessionMapping(A,_);let E=this.worktreeCache.get(T);if(E)this.worktreeCache.delete(T),E.sessionId=A,this.worktreeCache.set(A,E);$_.info("[WorktreeManager] Updated session ID mapping",{worktreePath:_,oldSessionId:T,newSessionId:A})}catch(E){$_.error("[WorktreeManager] Failed to update session ID",{error:E,worktreePath:_,oldSessionId:T,newSessionId:A})}}async renameWorktreeForSession(_,T,A){$_.info("[WorktreeManager] Renaming worktree for session",{oldSessionId:_,newSessionId:T,repoPath:A});try{let E=await C0(A);if(!E)return $_.error("[WorktreeManager] Could not determine repo root for rename"),null;let L=this.worktreeCache.get(_);if(!L){if($_.warn("[WorktreeManager] No cached worktree found for old session ID",{oldSessionId:_}),!await D5(E,_))return $_.error("[WorktreeManager] Could not find worktree for old session ID"),null}let J=this.getWorktreePath(E,_),X=this.getWorktreePath(E,T),H=this.generateBranchName(_),Z=this.generateBranchName(T);if(!D_.existsSync(J))return $_.warn("[WorktreeManager] Old worktree path does not exist",{oldPath:J}),null;if(D_.existsSync(X)){$_.warn("[WorktreeManager] New worktree path already exists",{newPath:X});let K={path:X,branch:Z,head:L?.head||"",sessionId:T,isMain:!1};return this.worktreeCache.delete(_),this.worktreeCache.set(T,K),K}await cW(E,J,X),$_.debug("[WorktreeManager] Moved worktree",{from:J,to:X}),await dW(X,H,Z),$_.debug("[WorktreeManager] Renamed branch",{from:H,to:Z}),this.worktreeCache.delete(_);let Y={path:X,branch:Z,head:L?.head||"",sessionId:T,isMain:!1,createdAt:L?.createdAt};return this.worktreeCache.set(T,Y),$_.info("[WorktreeManager] Successfully renamed worktree",{oldSessionId:_,newSessionId:T,oldPath:J,newPath:X,oldBranch:H,newBranch:Z}),Y}catch(E){return $_.error("[WorktreeManager] Failed to rename worktree",{error:E,oldSessionId:_,newSessionId:T}),null}}}import*as Z9 from"path";import*as TN from"os";var x1=v(),B5=Z9.join(TN.homedir(),".ccc"),_N=Z9.join(B5,"pending-permissions.json");class AN{cache=null;async ensureDirectory(){try{let _=await import("fs");if(!_.existsSync(B5))_.mkdirSync(B5,{recursive:!0}),x1.debug("[PendingPermissions] Created .ccc directory:",B5)}catch(_){throw x1.error("[PendingPermissions] Error ensuring directory:",_),_}}async load(){if(this.cache)return this.cache;try{let _=Bun.file(_N);if(await _.exists()){let T=await _.text();return this.cache=JSON.parse(T),x1.debug("[PendingPermissions] Loaded permissions:",{count:this.cache?.permissions?.length||0}),this.cache}}catch(_){x1.warn("[PendingPermissions] Error loading, starting fresh:",_)}return this.cache={permissions:[],lastUpdated:new Date().toISOString()},this.cache}async save(_){try{await this.ensureDirectory(),_.lastUpdated=new Date().toISOString(),await Bun.write(_N,JSON.stringify(_,null,2)),this.cache=_,x1.debug("[PendingPermissions] Saved permissions:",{count:_.permissions.length})}catch(T){throw x1.error("[PendingPermissions] Error saving:",T),T}}async addPermission(_){let T=await this.load(),A=T.permissions.findIndex((E)=>E.requestId===_.requestId);if(A>=0)T.permissions[A]=_,x1.debug("[PendingPermissions] Updated existing permission:",{requestId:_.requestId,sessionId:_.sessionId});else T.permissions.push(_),x1.info("[PendingPermissions] Added new pending permission:",{requestId:_.requestId,sessionId:_.sessionId,action:_.action});await this.save(T)}async removePermission(_){let T=await this.load(),A=T.permissions.length;if(T.permissions=T.permissions.filter((E)=>E.requestId!==_),T.permissions.length<A)return await this.save(T),x1.info("[PendingPermissions] Removed permission:",{requestId:_}),!0;return!1}async removePermissionsForSession(_){let T=await this.load(),A=T.permissions.length;T.permissions=T.permissions.filter((L)=>L.sessionId!==_);let E=A-T.permissions.length;if(E>0)await this.save(T),x1.info("[PendingPermissions] Removed permissions for session:",{sessionId:_,removedCount:E});return E}async getPermissionsForSession(_){return(await this.load()).permissions.filter((A)=>A.sessionId===_)}async getPermissionsForProject(_){return(await this.load()).permissions.filter((A)=>A.projectPath===_)}async getAllPermissions(){return(await this.load()).permissions}async getPermission(_){return(await this.load()).permissions.find((A)=>A.requestId===_)}async clearAll(){this.cache={permissions:[],lastUpdated:new Date().toISOString()},await this.save(this.cache),x1.info("[PendingPermissions] Cleared all pending permissions")}clearCache(){this.cache=null,x1.debug("[PendingPermissions] Cleared cache")}}var LT=new AN;var m=v();class q5{name="Claude Agent Service";running=!1;startedAt;mqttClient=null;sessionsService=null;processManager;worktreeManager;config;totalSessionsCreated=0;totalMessagesProcessed=0;pendingPermissions=new Map;cleanupInterval;constructor(_){this.config=_,this.worktreeManager=new O4,this.processManager=new T9(_,{onSessionInitialized:this.handleSessionInitialized.bind(this),onTitleGenerated:this.handleTitleGenerated.bind(this),onAssistantMessage:this.handleAssistantMessage.bind(this),onPermissionRequest:this.handlePermissionRequest.bind(this),onSessionError:this.handleSessionError.bind(this),onSessionStopped:this.handleSessionStopped.bind(this),onProcessingStarted:this.handleProcessingStarted.bind(this),onProcessingComplete:this.handleProcessingComplete.bind(this),onContextUpdate:this.handleContextUpdate.bind(this)})}async determineWorkingDirectory(_,T,A){try{if(!await z4(T))return m.debug("[ClaudeAgent] Not a git repo, using project path",{projectId:_,directoryPath:T}),{path:T,isWorktree:!1};let L=await C0(T);if(!L)return m.warn("[ClaudeAgent] Could not determine repo root, using project path",{directoryPath:T}),{path:T,isWorktree:!1};m.info("[ClaudeAgent] Git repo detected, creating worktree",{projectId:_,sessionId:A,repoRoot:L});let{worktree:J,isNew:X}=await this.worktreeManager.getOrCreateForSession(A,L);return m.info("[ClaudeAgent] Worktree ready",{sessionId:A,worktreePath:J.path,branch:J.branch,isNew:X}),{path:J.path,isWorktree:!0,branch:J.branch}}catch(E){return m.error("[ClaudeAgent] Worktree creation failed, falling back to project path",{projectId:_,sessionId:A,error:E instanceof Error?E.message:"Unknown error"}),{path:T,isWorktree:!1}}}setMQTTClient(_){this.mqttClient=_}setSessionsService(_){this.sessionsService=_}async start(){try{if(this.running=!0,this.startedAt=new Date,m.info("[ClaudeAgent] Service started"),this.mqttClient)this.registerMQTTHandlers();else m.warn("[ClaudeAgent] MQTT client not set - handlers will not be registered");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions()},300000),m.info("[ClaudeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions,sessionTimeoutMs:this.config.sessionTimeoutMs})}catch(_){throw m.error("[ClaudeAgent] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval);this.processManager.stopAll(),m.info("[ClaudeAgent] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("claude/+/session/start",(_,T)=>{let A=this.extractUserIdFromTopic(_);this.handleSessionStart(A,_,T)}),this.mqttClient.subscribe("claude/+/input/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromInputTopic(_);this.handleUserInput(A,E,_,T)}),this.mqttClient.subscribe("claude/+/permission/response/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromPermissionTopic(_);this.handlePermissionResponse(A,E,_,T)}),this.mqttClient.subscribe("claude/+/session/stop/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromStopTopic(_);this.handleSessionStop(A,E)}),this.mqttClient.subscribe("permissions/pending/request",(_,T)=>{this.handlePendingPermissionsRequest(_,T)}),m.info("[ClaudeAgent] MQTT handlers registered")}async handleSessionStart(_,T,A){try{let E=JSON.parse(A.toString());m.info("[ClaudeAgent] Session start request:",{userId:_,tempId:E.tempId,projectId:E.projectId,directoryPath:E.directoryPath,permissionMode:E.permissionMode,selectedModel:E.selectedModel,hasAttachments:!!E.attachments,attachmentCount:E.attachments?.length||0});let{path:L,isWorktree:J,branch:X}=await this.determineWorkingDirectory(E.projectId,E.directoryPath,E.tempId),H=await this.processManager.spawnSession(E.tempId,_,E.projectId,L,E.initialMessage||"",void 0,E.permissionMode,E.selectedModel,E.attachments);if(J)H.directoryPath=E.directoryPath,H.worktreePath=L,H.worktreeBranch=X;this.totalSessionsCreated++,m.info("[ClaudeAgent] Session spawned successfully:",{userId:_,tempId:E.tempId,projectId:E.projectId,workingPath:L,isWorktree:J})}catch(E){m.error("[ClaudeAgent] Error starting session:",{userId:_,error:E instanceof Error?E.message:"Unknown error"}),this.publishStatus(_,"temp_error",{type:"error",error:E instanceof Error?E.message:"Failed to start session",timestamp:Date.now()})}}async handleUserInput(_,T,A,E){try{let L=JSON.parse(E.toString());if(!L.message&&(!L.attachments||L.attachments.length===0)){m.warn("[ClaudeAgent] Received request without message or attachments:",{userId:_,sessionId:L.sessionId,hasAttachments:!!L.attachments});return}m.info("[ClaudeAgent] User input:",{userId:_,sessionId:L.sessionId,messageLength:L.message?.length||0,permissionMode:L.permissionMode,selectedModel:L.selectedModel,hasAttachments:!!L.attachments,attachmentCount:L.attachments?.length||0,allSessions:this.processManager.getAllSessions().map((Z)=>({tempId:Z.tempId,sessionId:Z.sessionId,status:Z.status}))});let J=this.processManager.getSession(L.sessionId);if(!J){m.warn("[ClaudeAgent] Session not found, creating new session:",{userId:_,requestedSessionId:L.sessionId,projectId:L.projectId,availableSessions:this.processManager.getAllSessions().map((Y)=>Y.sessionId||Y.tempId)});let Z=L.sessionId&&!L.sessionId.startsWith("temp_")&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(L.sessionId);try{let{path:Y,isWorktree:K,branch:G}=await this.determineWorkingDirectory(L.projectId,L.directoryPath,L.sessionId);if(J=await this.processManager.spawnSession(L.sessionId,_,L.projectId,Y,L.message||"",Z?L.sessionId:void 0,L.permissionMode,L.selectedModel,L.attachments),K)J.directoryPath=L.directoryPath,J.worktreePath=Y,J.worktreeBranch=G;this.totalSessionsCreated++,m.info(`[ClaudeAgent] Session ${Z?"resumed":"created"} successfully:`,{userId:_,sessionId:L.sessionId,isResume:Z,workingPath:Y,isWorktree:K}),this.totalMessagesProcessed++;return}catch(Y){m.error("[ClaudeAgent] Failed to create session:",{userId:_,sessionId:L.sessionId,error:Y instanceof Error?Y.message:"Unknown error"}),this.publishStatus(_,L.sessionId,{type:"error",error:"Failed to create session",timestamp:Date.now()});return}}let X=J.permissionMode||"default",H=L.permissionMode||"default";if(H!==X&&J.sessionId)if(m.info("[ClaudeAgent] Permission mode changed, respawning session:",{userId:_,sessionId:J.sessionId,currentMode:X,requestedMode:H}),await this.processManager.respawnWithPermissionMode(J.sessionId,H,L.message||"proceed with implementation")){this.publishStatus(_,J.sessionId,{type:"session_restarted",permissionMode:H,timestamp:Date.now()}),this.totalMessagesProcessed++;return}else m.error("[ClaudeAgent] Failed to respawn session with new permission mode");this.processManager.sendUserMessage(J,L.message||"",L.attachments),this.totalMessagesProcessed++}catch(L){m.error("[ClaudeAgent] Error handling user input:",{userId:_,sessionId:T,error:L instanceof Error?L.message:"Unknown error"})}}async handlePermissionResponse(_,T,A,E){try{let L=JSON.parse(E.toString());m.info("[ClaudeAgent] Permission response:",{userId:_,sessionId:T,requestId:L.requestId,approved:L.approved,hasAnswers:!!L.answers,addToAllowedTools:L.addToAllowedTools,toolPattern:L.toolPattern,permissionMode:L.permissionMode,hardDeny:L.hardDeny,hasDenyMessage:!!L.denyMessage});let J=this.pendingPermissions.get(L.requestId);if(!J)m.warn(`[ClaudeAgent] No pending permission found for request_id: ${L.requestId}`);if(L.approved&&L.addToAllowedTools){let H=this.processManager.getSession(T);if(H){let Z=L.toolPattern||(J?this.generateToolPattern(J.action,J.params):null);if(Z)await this.addToAllowedTools(H.directoryPath,Z),m.info("[ClaudeAgent] Added tool pattern to settings.local.json:",{toolPattern:Z,projectPath:H.directoryPath})}}let X=this.processManager.getSession(T);if(L.permissionMode&&X?.sessionId){if(m.info("[ClaudeAgent] Permission mode change requested, will respawn session:",{sessionId:X.sessionId,newPermissionMode:L.permissionMode}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:J?.params,message:"Permission mode is changing. Stopping current execution for session respawn."}),await new Promise((Z)=>setTimeout(Z,200)),await this.processManager.respawnWithPermissionMode(X.sessionId,L.permissionMode,"proceed with implementation"))this.publishStatus(X.userId,X.sessionId,{type:"session_restarted",permissionMode:L.permissionMode,timestamp:Date.now()});else this.publishStatus(X.userId,X.sessionId,{type:"error",error:"Failed to respawn session with new permission mode",timestamp:Date.now()});if(J)this.pendingPermissions.delete(L.requestId);LT.removePermission(L.requestId).catch((Z)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",Z)});return}if(L.approved&&L.answers&&Object.keys(L.answers).length>0){let H={...J?.params,answers:L.answers};m.info("[ClaudeAgent] Sending AskUserQuestion response:",{requestId:L.requestId,answerCount:Object.keys(L.answers).length}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:H})}else if(L.approved)this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:J?J.params:void 0});else{let H=L.denyMessage||"Permission denied by user",Z=L.hardDeny!==!1;if(m.info("[ClaudeAgent] Sending deny response:",{requestId:L.requestId,hardDeny:Z,hasDenyMessage:!!L.denyMessage}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"deny",message:H,hardDeny:Z}),Z)m.info("[ClaudeAgent] Hard deny - stopping session:",{sessionId:T}),setTimeout(()=>{this.processManager.stopSession(T),this.publishStatus(_,T,{type:"session_stopped",reason:"permission_denied",message:H,timestamp:Date.now()})},100)}if(J)this.pendingPermissions.delete(L.requestId);LT.removePermission(L.requestId).catch((H)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",H)})}catch(L){m.error("[ClaudeAgent] Error handling permission response:",{userId:_,sessionId:T,error:L instanceof Error?L.message:"Unknown error"})}}handleSessionStop(_,T){m.info("[ClaudeAgent] Session stop request:",{userId:_,sessionId:T}),this.processManager.stopSession(T)}async handlePendingPermissionsRequest(_,T){try{let A=JSON.parse(T.toString()),{clientId:E,sessionId:L,projectPath:J}=A;if(!E){m.warn("[ClaudeAgent] Pending permissions request missing clientId");return}m.info("[ClaudeAgent] Pending permissions request:",{clientId:E,sessionId:L,projectPath:J});let X;if(L)X=await LT.getPermissionsForSession(L);else if(J)X=await LT.getPermissionsForProject(J);else X=await LT.getAllPermissions();let H=this.processManager.getAllSessions(),Z=new Set(H.filter(($)=>$.status==="waiting_permission"&&$.sessionId).map(($)=>$.sessionId)),Y=X.filter(($)=>Z.has($.sessionId)),K=`permissions/pending/${E}/response`,G={permissions:Y,timestamp:Date.now()};await this.mqttClient?.publish(K,JSON.stringify(G)),m.info("[ClaudeAgent] Sent pending permissions response:",{clientId:E,count:Y.length,totalStored:X.length})}catch(A){m.error("[ClaudeAgent] Error handling pending permissions request:",A)}}handleSessionInitialized(_,T){if(m.info("[ClaudeAgent] Session initialized callback:",{tempId:_.tempId,sessionId:_.sessionId,model:_.model}),_.worktreePath&&_.tempId&&_.sessionId)this.worktreeManager.updateSessionId(_.worktreePath,_.tempId,_.sessionId);if(this.publishStatus(_.userId,_.sessionId,{type:"session_started",sessionId:_.sessionId,tempId:_.tempId,model:_.model,worktreePath:_.worktreePath,worktreeBranch:_.worktreeBranch,timestamp:Date.now()}),this.sessionsService){let A=_.worktreePath||_.directoryPath;this.sessionsService.notifySessionCreated(_.directoryPath,A).catch((E)=>{m.warn("[ClaudeAgent] Failed to notify sessions service about new session",{error:E})})}}handleTitleGenerated(_,T){m.info("[ClaudeAgent] Title generated callback:",{sessionId:_.sessionId,title:T}),this.publishStatus(_.userId,_.sessionId,{type:"title_generated",title:T,timestamp:Date.now()})}handleAssistantMessage(_,T){if(this.totalMessagesProcessed++,_.sessionId)this.publishOutput(_.userId,_.sessionId,T)}handlePermissionRequest(_,T){if(m.info("[ClaudeAgent] Permission request callback:",{sessionId:_.sessionId,requestId:T.request_id,action:T.action}),_.sessionId)this.publishPermissionRequest(_,T)}handleSessionError(_,T){m.error("[ClaudeAgent] Session error callback:",{sessionId:_.sessionId,tempId:_.tempId,error:T}),this.publishStatus(_.userId,_.sessionId||_.tempId,{type:"error",error:T,timestamp:Date.now()})}handleSessionStopped(_,T){if(m.info("[ClaudeAgent] Session stopped callback:",{sessionId:_.sessionId,tempId:_.tempId,reason:T}),this.publishStatus(_.userId,_.sessionId||_.tempId,{type:"session_stopped",reason:T,timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifySessionStopped()}handleProcessingStarted(_){if(m.info("[ClaudeAgent] Processing started:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_processing",sessionId:_.sessionId,timestamp:Date.now()})}handleProcessingComplete(_){if(m.info("[ClaudeAgent] Processing complete:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_idle",sessionId:_.sessionId,timestamp:Date.now()})}handleContextUpdate(_,T){if(m.info(`[ClaudeAgent] Context update for session ${_.sessionId}:`,{total:T.total,percentage:T.percentage,inputTokens:T.inputTokens,cacheCreation:T.cacheCreation,cacheRead:T.cacheRead,breakdown:{systemPrompt:T.systemPrompt,tools:T.tools,messages:T.messages,remaining:T.remaining}}),_.sessionId)this.publishContextUpdate(_.userId,_.sessionId,T);else m.warn("[ClaudeAgent] Cannot publish context update - no sessionId yet")}publishStatus(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish status - MQTT client not available");return}let E=`claude/${_}/status/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish status to ${E}`,{error:J.message})})}publishOutput(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish output - MQTT client not available");return}let E=`claude/${_}/output/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish output to ${E}`,{error:J.message})})}publishContextUpdate(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish context update - MQTT client not available");return}let E=`claude/${_}/context/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish context to ${E}`,{error:J.message})})}publishPermissionRequest(_,T){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish permission request - MQTT client not available");return}let{userId:A,sessionId:E}=_;m.info("[ClaudeAgent] Raw permission request structure:",{fullRequest:JSON.stringify(T)});let L=T,J=L.request||{},X=J.tool_name||L.tool_name||L.action||"unknown_tool",H=J.input||L.tool_input||L.params||{},Z=J.permission_suggestions||[],Y=J.decision_reason||"",K=J.blocked_path||"";this.pendingPermissions.set(L.request_id,{requestId:L.request_id,action:X,params:H}),LT.addPermission({requestId:L.request_id,sessionId:E,projectPath:_.directoryPath,action:X,params:H,permissionSuggestions:Z.length>0?Z:void 0,decisionReason:Y||void 0,blockedPath:K||void 0,createdAt:new Date().toISOString()}).catch((V)=>{m.error("[ClaudeAgent] Failed to persist pending permission:",V)});let G={request_id:L.request_id,action:X,params:H,permission_suggestions:Z,decision_reason:Y,blocked_path:K},$=`claude/${A}/permission/request/${E}`,U=JSON.stringify(G);m.info("[ClaudeAgent] Publishing transformed permission request:",{topic:$,request_id:G.request_id,action:G.action}),this.mqttClient.publish($,U).catch((V)=>{m.error(`[ClaudeAgent] Failed to publish permission request to ${$}`,{error:V.message})})}extractUserIdFromTopic(_){return _.split("/")[1]||""}extractIdsFromInputTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[3]||""}}extractIdsFromPermissionTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[4]||""}}extractIdsFromStopTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[4]||""}}generateToolPattern(_,T){switch(_){case"Bash":case"bash":case"execute_command":return`Bash(${T.command})`;case"Read":case"read":case"read_file":return`Read(${T.file_path})`;case"Write":case"write":case"write_file":return`Write(${T.file_path})`;case"Edit":case"edit":return`Edit(${T.file_path})`;default:return _}}async addToAllowedTools(_,T){try{let A=EN.join(_,".claude"),E=EN.join(A,"settings.local.json"),L=Bun.file(A);if(!await Bun.$`test -d ${A}`.quiet().nothrow())await Bun.$`mkdir -p ${A}`.quiet();let J={},X=Bun.file(E);if(await X.exists())try{let H=await X.text();J=JSON.parse(H)}catch{J={}}if(J.permissions=J.permissions||{},J.permissions.allow=J.permissions.allow||[],!J.permissions.allow.includes(T))J.permissions.allow.push(T);await Bun.write(E,JSON.stringify(J,null,2)),m.info("[ClaudeAgent] Updated settings.local.json with allowed tool:",{settingsPath:E,toolPattern:T,totalAllowed:J.permissions.allow.length})}catch(A){m.error("[ClaudeAgent] Failed to update settings.local.json:",{projectPath:_,toolPattern:T,error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.processManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessions(){return this.processManager.getAllSessions().filter((_)=>_.sessionId).map((_)=>({sessionId:_.sessionId,projectPath:_.directoryPath,status:_.status,worktreePath:_.worktreePath,worktreeBranch:_.worktreeBranch}))}}import*as Y_ from"fs/promises";import*as y_ from"path";var u0=v();class I5{validatePath(_,T){try{let A=y_.resolve(_),E=y_.resolve(A,T);if(!(E===A||E.startsWith(A+y_.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};return{valid:!0,fullPath:E}}catch(A){return{valid:!1,fullPath:"",error:`Path validation error: ${A instanceof Error?A.message:"Unknown error"}`}}}async listDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{entries:[],error:A.error};try{if(!(await Y_.stat(A.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let L=await Y_.readdir(A.fullPath,{withFileTypes:!0}),J=await Promise.all(L.map(async(X)=>{let H=y_.join(A.fullPath,X.name);try{let Z=await Y_.stat(H);return{name:X.name,type:X.isDirectory()?"directory":"file",size:X.isFile()?Z.size:void 0,modified:Z.mtime.toISOString()}}catch{return{name:X.name,type:X.isDirectory()?"directory":"file"}}}));return J.sort((X,H)=>{if(X.type!==H.type)return X.type==="directory"?-1:1;return X.name.localeCompare(H.name,void 0,{sensitivity:"base"})}),{entries:J}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] listDirectory error",{error:L,path:A.fullPath}),{entries:[],error:`Failed to list directory: ${L}`}}}async readFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{content:"",size:0,error:A.error};try{let E=await Y_.stat(A.fullPath);if(!E.isFile())return{content:"",size:0,error:"Path is not a file"};return{content:await Y_.readFile(A.fullPath,"utf-8"),size:E.size}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] readFile error",{error:L,path:A.fullPath}),{content:"",size:0,error:`Failed to read file: ${L}`}}}async writeFile(_,T,A){let E=this.validatePath(_,T);if(!E.valid)return{success:!1,error:E.error};try{let L=y_.dirname(E.fullPath);return await Y_.mkdir(L,{recursive:!0}),await Y_.writeFile(E.fullPath,A,"utf-8"),{success:!0}}catch(L){let J=L instanceof Error?L.message:"Unknown error";return u0.error("[FileManager] writeFile error",{error:J,path:E.fullPath}),{success:!1,error:`Failed to write file: ${J}`}}}async createFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{try{return await Y_.access(A.fullPath),{success:!1,error:"File already exists"}}catch{}let E=y_.basename(T);if(!this.isValidFilename(E))return{success:!1,error:"Invalid filename"};let L=y_.dirname(A.fullPath);return await Y_.mkdir(L,{recursive:!0}),await Y_.writeFile(A.fullPath,"","utf-8"),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] createFile error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to create file: ${L}`}}}async createDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{let E=y_.basename(T);if(!this.isValidFilename(E))return{success:!1,error:"Invalid directory name"};try{if((await Y_.stat(A.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await Y_.mkdir(A.fullPath,{recursive:!0}),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] createDirectory error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to create directory: ${L}`}}}async deleteFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{if(!(await Y_.stat(A.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await Y_.unlink(A.fullPath),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] deleteFile error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to delete file: ${L}`}}}async deleteDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};if(A.fullPath===y_.resolve(_))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await Y_.stat(A.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await Y_.rm(A.fullPath,{recursive:!0,force:!0}),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] deleteDirectory error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to delete directory: ${L}`}}}async pathExists(_,T){let A=this.validatePath(_,T);if(!A.valid)return!1;try{return await Y_.access(A.fullPath),!0}catch{return!1}}async getStats(_,T){let A=this.validatePath(_,T);if(!A.valid)return null;try{let E=await Y_.stat(A.fullPath);return{isFile:E.isFile(),isDirectory:E.isDirectory(),size:E.size,modified:E.mtime.toISOString()}}catch{return null}}async readFileBinary(_,T){let A=this.validatePath(_,T);if(!A.valid)return{content:Buffer.alloc(0),size:0,mimeType:"",error:A.error};try{let E=await Y_.stat(A.fullPath);if(!E.isFile())return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Path is not a file"};let L=52428800;if(E.size>L)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"File exceeds maximum size of 50MB"};let J=await Y_.readFile(A.fullPath),X=this.getMimeType(y_.basename(T));return{content:J,size:E.size,mimeType:X}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] readFileBinary error",{error:L,path:A.fullPath}),{content:Buffer.alloc(0),size:0,mimeType:"",error:`Failed to read file: ${L}`}}}async writeFileBinary(_,T,A){let E=this.validatePath(_,T);if(!E.valid)return{success:!1,error:E.error};try{let L=y_.basename(T);if(!this.isValidFilename(L))return{success:!1,error:"Invalid filename"};let J=y_.dirname(E.fullPath);return await Y_.mkdir(J,{recursive:!0}),await Y_.writeFile(E.fullPath,A),{success:!0}}catch(L){let J=L instanceof Error?L.message:"Unknown error";return u0.error("[FileManager] writeFileBinary error",{error:J,path:E.fullPath}),{success:!1,error:`Failed to write file: ${J}`}}}getMimeType(_){let T=y_.extname(_).toLowerCase();return{".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".tiff":"image/tiff",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".txt":"text/plain",".json":"application/json",".xml":"application/xml",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".tsx":"application/typescript",".jsx":"application/javascript",".md":"text/markdown",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".7z":"application/x-7z-compressed",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".m4a":"audio/mp4",".flac":"audio/flac",".aac":"audio/aac",".mp4":"video/mp4",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".webm":"video/webm",".wmv":"video/x-ms-wmv",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".apk":"application/vnd.android.package-archive",".ipa":"application/octet-stream",".exe":"application/x-msdownload",".dmg":"application/x-apple-diskimage",".deb":"application/x-deb",".rpm":"application/x-rpm"}[T]||"application/octet-stream"}isValidFilename(_){if(!_||_.length===0)return!1;if(_.includes("/")||_.includes("\\"))return!1;let T=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],A=(_.split(".")[0]||"").toUpperCase();if(T.includes(A))return!1;if(/[<>:"|?*\x00-\x1f]/.test(_))return!1;if(_==="."||_==="..")return!1;return!0}}import*as Y9 from"path";var A1=v(),R4=51200,LN=50;class P5{name="File Browser Service";running=!1;startedAt;mqttClient=null;fileManager;requestsHandled=0;messageHandlers=new Map;fileSaveOperations=new Map;binaryUploadOperations=new Map;constructor(){this.fileManager=new I5}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,A1.info("[FileBrowser] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw A1.error("[FileBrowser] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){for(let[_,T]of this.messageHandlers)this.mqttClient.unsubscribe(_,T);this.messageHandlers.clear()}this.fileSaveOperations.clear(),this.binaryUploadOperations.clear(),A1.info("[FileBrowser] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("files/list/request",(_,T)=>{this.handleDirectoryListRequest(T)}),this.registerHandler("files/content/request",(_,T)=>{this.handleFileContentRequest(T)}),this.registerHandler("files/save/request",(_,T)=>{this.handleFileSaveRequest(T)}),this.registerHandler("files/create/request",(_,T)=>{this.handleFileCreateRequest(T)}),this.registerHandler("files/delete/request",(_,T)=>{this.handleFileDeleteRequest(T)}),this.registerHandler("files/upload/request",(_,T)=>{this.handleBinaryUploadRequest(T)}),this.registerHandler("files/download/request",(_,T)=>{this.handleBinaryDownloadRequest(T)}),A1.info("[FileBrowser] MQTT handlers registered")}registerHandler(_,T){if(!this.mqttClient)return;this.messageHandlers.set(_,T),this.mqttClient.subscribe(_,T)}async handleDirectoryListRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.listDirectory(T.projectPath,T.relativePath),E={path:T.relativePath,entries:A.entries,timestamp:Date.now(),error:A.error};await this.publishResponse(`files/list/${T.clientId}/response`,E),this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling directory list request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileContentRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.readFile(T.projectPath,T.relativePath),E=`files/content/${T.clientId}/response`;if(A.error){let J={path:T.relativePath,chunk:{chunkIndex:0,totalChunks:1,content:""},totalSize:0,timestamp:Date.now(),error:A.error};await this.publishResponse(E,J);return}let L=Math.max(1,Math.ceil(A.content.length/R4));for(let J=0;J<L;J++){let X=J*R4,H=Math.min(X+R4,A.content.length),Z=A.content.slice(X,H),Y={path:T.relativePath,chunk:{chunkIndex:J,totalChunks:L,content:Z},totalSize:A.size,timestamp:Date.now()};if(await this.publishResponse(E,Y),J<L-1)await this.delay(LN)}this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file content request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileSaveRequest(_){try{let T=JSON.parse(_.toString()),A=`${T.clientId}:${T.relativePath}`;if(T.chunk.chunkIndex===0)this.fileSaveOperations.set(A,{chunks:new Map,totalChunks:T.chunk.totalChunks,totalSize:T.totalSize});let E=this.fileSaveOperations.get(A);if(!E){await this.sendSaveResponse(T,!1,"Save operation not initialized");return}if(E.chunks.set(T.chunk.chunkIndex,T.chunk.content),await this.sendSaveResponse(T,!0),E.chunks.size===E.totalChunks){let L=[];for(let H=0;H<E.totalChunks;H++){let Z=E.chunks.get(H);if(Z!==void 0)L.push(Z)}let J=L.join(""),X=await this.fileManager.writeFile(T.projectPath,T.relativePath,J);if(this.fileSaveOperations.delete(A),!X.error)this.requestsHandled++}}catch(T){A1.error("[FileBrowser] Error handling file save request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileCreateRequest(_){try{let T=JSON.parse(_.toString()),A;if(T.type==="directory")A=await this.fileManager.createDirectory(T.projectPath,T.relativePath);else A=await this.fileManager.createFile(T.projectPath,T.relativePath);let E={path:T.relativePath,success:A.success,type:T.type,timestamp:Date.now(),error:A.error};if(await this.publishResponse(`files/create/${T.clientId}/response`,E),A.success)this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file create request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileDeleteRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.getStats(T.projectPath,T.relativePath),E;if(!A)E={success:!1,error:"Path does not exist"};else if(A.isDirectory)E=await this.fileManager.deleteDirectory(T.projectPath,T.relativePath);else E=await this.fileManager.deleteFile(T.projectPath,T.relativePath);let L={path:T.relativePath,success:E.success,timestamp:Date.now(),error:E.error};if(await this.publishResponse(`files/delete/${T.clientId}/response`,L),E.success)this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file delete request",{error:T instanceof Error?T.message:"Unknown error"})}}async sendSaveResponse(_,T,A){let E={path:_.relativePath,success:T,chunkIndex:_.chunk.chunkIndex,totalChunks:_.chunk.totalChunks,timestamp:Date.now(),error:A};await this.publishResponse(`files/save/${_.clientId}/response`,E)}async publishResponse(_,T){if(!this.mqttClient){A1.error("[FileBrowser] MQTT client not available");return}await this.mqttClient.publish(_,JSON.stringify(T),{qos:1})}delay(_){return new Promise((T)=>setTimeout(T,_))}async handleBinaryUploadRequest(_){try{let T=JSON.parse(_.toString()),A=`${T.clientId}:${T.relativePath}`;if(T.chunk.chunkIndex===0){if(T.totalSize>52428800){await this.sendBinaryUploadResponse(T,!1,"File exceeds 50MB limit",0);return}this.binaryUploadOperations.set(A,{chunks:new Map,totalChunks:T.chunk.totalChunks,totalSize:T.totalSize,filename:T.filename,mimeType:T.mimeType,receivedBytes:0})}let E=this.binaryUploadOperations.get(A);if(!E){await this.sendBinaryUploadResponse(T,!1,"Upload operation not initialized",0);return}let L=Buffer.from(T.chunk.data,"base64");if(E.chunks.set(T.chunk.chunkIndex,L),E.receivedBytes+=L.length,await this.sendBinaryUploadResponse(T,!0,void 0,E.receivedBytes),E.chunks.size===E.totalChunks){let J=[];for(let Z=0;Z<E.totalChunks;Z++){let Y=E.chunks.get(Z);if(Y)J.push(Y)}let X=Buffer.concat(J),H=await this.fileManager.writeFileBinary(T.projectPath,T.relativePath,X);if(this.binaryUploadOperations.delete(A),H.error)A1.error("[FileBrowser] Binary upload write failed",{error:H.error});else this.requestsHandled++,A1.info("[FileBrowser] Binary upload completed",{path:T.relativePath,size:X.length})}}catch(T){A1.error("[FileBrowser] Error handling binary upload",{error:T instanceof Error?T.message:"Unknown error"})}}async sendBinaryUploadResponse(_,T,A,E){let L={path:_.relativePath,success:T,chunkIndex:_.chunk.chunkIndex,totalChunks:_.chunk.totalChunks,bytesReceived:E||0,timestamp:Date.now(),error:A};await this.publishResponse(`files/upload/${_.clientId}/response`,L)}async handleBinaryDownloadRequest(_){try{let T=JSON.parse(_.toString()),A=`files/download/${T.clientId}/response`,E=await this.fileManager.readFileBinary(T.projectPath,T.relativePath);if(E.error){let H={path:T.relativePath,filename:Y9.basename(T.relativePath),mimeType:"",chunk:{chunkIndex:0,totalChunks:1,data:""},totalSize:0,timestamp:Date.now(),error:E.error};await this.publishResponse(A,H);return}let L=E.content.toString("base64"),J=Math.max(1,Math.ceil(L.length/R4)),X=Y9.basename(T.relativePath);for(let H=0;H<J;H++){let Z=H*R4,Y=Math.min(Z+R4,L.length),K=L.slice(Z,Y),G={path:T.relativePath,filename:X,mimeType:E.mimeType,chunk:{chunkIndex:H,totalChunks:J,data:K},totalSize:E.size,timestamp:Date.now()};if(await this.publishResponse(A,G),H<J-1)await this.delay(LN)}this.requestsHandled++,A1.info("[FileBrowser] Binary download completed",{path:T.relativePath,size:E.size,chunks:J})}catch(T){A1.error("[FileBrowser] Error handling binary download",{error:T instanceof Error?T.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,pendingSaveOperations:this.fileSaveOperations.size}}}var g=v();class j5{name="Git Service";running=!1;startedAt;mqttClient=null;worktreeManager;requestsHandled=0;messageHandlers=new Map;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){this.worktreeManager=new O4}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,this.ghAuthResult=await yW(),!this.ghAuthResult.authenticated)g.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else g.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username});if(this.mqttClient)this.registerMQTTHandlers();g.info("[GitService] Service started")}catch(_){throw g.error("[GitService] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){for(let[_,T]of this.messageHandlers)this.mqttClient.unsubscribe(_,T),g.debug(`[GitService] Unsubscribed from ${_}`);this.messageHandlers.clear()}this.worktreeManager.clearCache(),g.info("[GitService] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("git/orgs/request",(_,T)=>{this.handleOrgsRequest(T)}),this.registerHandler("git/repos/request",(_,T)=>{this.handleReposRequest(T)}),this.registerHandler("git/repos/search/request",(_,T)=>{this.handleSearchReposRequest(T)}),this.registerHandler("git/branches/request",(_,T)=>{this.handleBranchesRequest(T)}),this.registerHandler("git/clone/request",(_,T)=>{this.handleCloneRequest(T)}),this.registerHandler("git/is-repo/request",(_,T)=>{this.handleIsRepoRequest(T)}),this.registerHandler("git/worktree/get-or-create/request",(_,T)=>{this.handleWorktreeGetOrCreateRequest(T)}),this.registerHandler("git/worktree/get/request",(_,T)=>{this.handleWorktreeGetRequest(T)}),this.registerHandler("git/worktree/list/request",(_,T)=>{this.handleWorktreeListRequest(T)}),this.registerHandler("git/status/request",(_,T)=>{this.handleStatusRequest(T)}),this.registerHandler("git/diff/request",(_,T)=>{this.handleDiffRequest(T)}),this.registerHandler("git/changes/all/request",(_,T)=>{this.handleChangesAllRequest(T)}),this.registerHandler("git/stage/request",(_,T)=>{this.handleStageRequest(T)}),this.registerHandler("git/unstage/request",(_,T)=>{this.handleUnstageRequest(T)}),this.registerHandler("git/commit/request",(_,T)=>{this.handleCommitRequest(T)}),this.registerHandler("git/unpushed/request",(_,T)=>{this.handleUnpushedCommitsRequest(T)}),this.registerHandler("git/push/request",(_,T)=>{this.handlePushRequest(T)}),this.registerHandler("git/history/request",(_,T)=>{this.handleHistoryRequest(T)}),this.registerHandler("git/commit-details/request",(_,T)=>{this.handleCommitDetailsRequest(T)}),this.registerHandler("git/commit-file-diff/request",(_,T)=>{this.handleCommitFileDiffRequest(T)}),this.registerHandler("git/sync/request",(_,T)=>{this.handleSyncRequest(T)}),this.registerHandler("git/create-pr/request",(_,T)=>{this.handleCreatePRRequest(T)}),this.registerHandler("git/default-branch/request",(_,T)=>{this.handleDefaultBranchRequest(T)}),this.registerHandler("git/existing-pr/request",(_,T)=>{this.handleExistingPRRequest(T)}),this.registerHandler("git/remote-branches/request",(_,T)=>{this.handleRemoteBranchesRequest(T)}),g.info("[GitService] MQTT handlers registered")}registerHandler(_,T){if(!this.mqttClient)return;this.messageHandlers.set(_,T),this.mqttClient.subscribe(_,T),g.debug(`[GitService] Subscribed to ${_}`)}async publishResponse(_,T){if(!this.mqttClient){g.error("[GitService] MQTT client not available");return}await this.mqttClient.publish(_,JSON.stringify(T),{qos:1})}async handleOrgsRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Orgs request",{clientId:T.clientId}),!this.ghAuthResult.authenticated){let L={orgs:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/orgs/${T.clientId}/response`,L);return}let E={orgs:await E9(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling orgs request",{error:T})}}async handleReposRequest(_){try{let T=JSON.parse(_.toString()),A=T.requestId||T.clientId;if(g.debug("[GitService] Repos request",{clientId:T.clientId,requestId:T.requestId,org:T.org,limit:T.limit}),!this.ghAuthResult.authenticated){let J={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,J);return}let L={repos:await R5(T.org,T.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling repos request",{error:T})}}async handleSearchReposRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Search repos request",{clientId:T.clientId,query:T.query,limit:T.limit}),!this.ghAuthResult.authenticated){let A={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/search/${T.clientId}/response`,A);return}await vW(T.query,async(A,E,L)=>{let J={repos:A,timestamp:Date.now(),source:E,isComplete:L};await this.publishResponse(`git/repos/search/${T.clientId}/response`,J),g.debug("[GitService] Sent search results",{source:E,count:A.length,isComplete:L})},T.limit||50),this.requestsHandled++}catch(T){g.error("[GitService] Error handling search repos request",{error:T})}}async handleBranchesRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Branches request",{clientId:T.clientId,owner:T.owner,repo:T.repo}),!this.ghAuthResult.authenticated){let L={branches:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/branches/${T.clientId}/response`,L);return}let A=await hW(T.owner,T.repo),E={branches:A.branches,defaultBranch:A.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/branches/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling branches request",{error:T})}}async handleCloneRequest(_){try{let T=JSON.parse(_.toString());if(g.info("[GitService] Clone request",{clientId:T.clientId,repoUrl:T.repoUrl,targetPath:T.targetPath,branch:T.branch}),!this.ghAuthResult.authenticated){let L={success:!1,error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/clone/${T.clientId}/response`,L);return}let A=await kW(T.repoUrl,T.targetPath,T.branch),E=A.success?{success:!0,path:A.path,defaultBranch:A.defaultBranch,timestamp:Date.now()}:{success:!1,error:A.error||"Clone failed",timestamp:Date.now()};await this.publishResponse(`git/clone/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling clone request",{error:T})}}async handleIsRepoRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Is-repo request",{clientId:T.clientId,path:T.path});let A=await z4(T.path),E;if(A){let[L,J,X]=await Promise.all([C0(T.path),F4(T.path),pW(T.path)]);E={isGitRepo:!0,repoRoot:L||void 0,defaultBranch:J||void 0,remoteUrl:X||void 0,timestamp:Date.now()}}else E={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling is-repo request",{error:T});let A=JSON.parse(_.toString()),E={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${A.clientId}/response`,E)}}async handleWorktreeGetOrCreateRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree get-or-create request",{clientId:T.clientId,repoPath:T.repoPath,sessionId:T.sessionId});let{worktree:A,isNew:E}=await this.worktreeManager.getOrCreateForSession(T.sessionId,T.repoPath),L={success:!0,worktreePath:A.path,branch:A.branch,isNew:E,timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${T.clientId}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree get-or-create request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${A.clientId}/response`,E)}}async handleWorktreeGetRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree get request",{clientId:T.clientId,repoPath:T.repoPath,sessionId:T.sessionId});let A=await this.worktreeManager.getWorktreeForSession(T.sessionId,T.repoPath),E=A?{exists:!0,worktreePath:A.path,branch:A.branch,timestamp:Date.now()}:{exists:!1,timestamp:Date.now()};await this.publishResponse(`git/worktree/get/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree get request",{error:T})}}async handleWorktreeListRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree list request",{clientId:T.clientId,repoPath:T.repoPath});let E={worktrees:await this.worktreeManager.listWorktreesForRepo(T.repoPath),timestamp:Date.now()};await this.publishResponse(`git/worktree/list/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree list request",{error:T})}}async handleStatusRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Status request",{clientId:T.clientId,path:T.path});let E={success:!0,status:await L9(T.path),timestamp:Date.now()};await this.publishResponse(`git/status/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling status request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/status/${A.clientId}/response`,E)}}async handleDiffRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Diff request",{clientId:T.clientId,path:T.path,file:T.file,staged:T.staged});let A=await bW(T.path,T.file,T.staged),E={success:!0,diff:A.diff,isBinary:A.isBinary,timestamp:Date.now()};await this.publishResponse(`git/diff/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling diff request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/diff/${A.clientId}/response`,E)}}async handleChangesAllRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Changes all request",{clientId:T.clientId,repoPath:T.repoPath});let A=await this.worktreeManager.listWorktreesForRepo(T.repoPath),E={repoPath:T.repoPath,worktrees:[],totalChanges:0};for(let J of A)try{let X=await L9(J.path);E.worktrees.push({worktreePath:J.path,branch:J.branch,sessionId:J.sessionId,changes:X.files,totalCount:X.files.length}),E.totalChanges+=X.files.length}catch(X){g.warn("[GitService] Failed to get status for worktree",{path:J.path,error:X})}let L={success:!0,changes:E,timestamp:Date.now()};await this.publishResponse(`git/changes/all/${T.clientId}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling changes all request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/changes/all/${A.clientId}/response`,E)}}async handleStageRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Stage request",{clientId:T.clientId,path:T.path,files:T.files}),await gW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){g.error("[GitService] Error handling stage request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/stage/${A.clientId}/response`,E)}}async handleUnstageRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Unstage request",{clientId:T.clientId,path:T.path,files:T.files}),await mW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){g.error("[GitService] Error handling unstage request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unstage/${A.clientId}/response`,E)}}async handleCommitRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Commit request",{clientId:T.clientId,path:T.path,signoff:T.signoff});let E={success:!0,commit:await uW(T.path,T.message,T.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit/${A.clientId}/response`,E)}}async handleUnpushedCommitsRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Unpushed commits request",{clientId:T.clientId,path:T.path});let A=await V4(T.path),E={success:!0,commits:A.commits,upstream:A.upstream,ahead:A.ahead,timestamp:Date.now()};await this.publishResponse(`git/unpushed/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling unpushed commits request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unpushed/${A.clientId}/response`,E)}}async handlePushRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Push request",{clientId:T.clientId,path:T.path,force:T.force});let A=await lW(T.path,T.force),E={success:!0,commitsPushed:A.commitsPushed,remote:A.remote,branch:A.branch,timestamp:Date.now()};await this.publishResponse(`git/push/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling push request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/push/${A.clientId}/response`,E)}}async handleHistoryRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] History request",{clientId:T.clientId,path:T.path,limit:T.limit});let A=await nW(T.path,T.limit||50),E={success:!0,commits:A.commits,totalCount:A.totalCount,timestamp:Date.now()};await this.publishResponse(`git/history/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling history request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/history/${A.clientId}/response`,E)}}async handleCommitDetailsRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Commit details request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash});let E={success:!0,commit:await iW(T.path,T.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit details request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-details/${A.clientId}/response`,E)}}async handleCommitFileDiffRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Commit file diff request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash,filePath:T.filePath});let A=await oW(T.path,T.commitHash,T.filePath),E={success:!0,diff:A.diff,isBinary:A.isBinary,timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit file diff request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${A.clientId}/response`,E)}}async handleSyncRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Sync request",{clientId:T.clientId,path:T.path});let A=await aW(T.path),E=A.success?{success:!0,action:A.action,commitsPulled:A.commitsPulled,commitsPushed:A.commitsPushed,timestamp:Date.now()}:{success:!1,action:A.action,commitsPulled:A.commitsPulled,commitsPushed:A.commitsPushed,error:A.error||"Sync failed",conflictedFiles:A.conflictedFiles,timestamp:Date.now()};await this.publishResponse(`git/sync/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling sync request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/sync/${A.clientId}/response`,E)}}async handleCreatePRRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Create PR request",{clientId:T.clientId,path:T.path,title:T.title,baseBranch:T.baseBranch,draft:T.draft});let A=await rW(T.path,T.title,T.body,T.baseBranch,T.draft),E=A.success?{success:!0,prNumber:A.prNumber,prUrl:A.prUrl,timestamp:Date.now()}:{success:!1,error:A.error||"Failed to create pull request",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling create PR request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${A.clientId}/response`,E)}}async handleDefaultBranchRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Default branch request",{clientId:T.clientId,path:T.path});let A=await J9(T.path),E=A?{success:!0,defaultBranch:A,timestamp:Date.now()}:{success:!1,error:"Could not determine default branch",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling default branch request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${A.clientId}/response`,E)}}async handleExistingPRRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Existing PR request",{clientId:T.clientId,path:T.path});let A=await sW(T.path),E={exists:A.exists,prNumber:A.prNumber,prUrl:A.prUrl,title:A.title,state:A.state,draft:A.draft,error:A.error,timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling existing PR request",{error:T});let A=JSON.parse(_.toString()),E={exists:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${A.clientId}/response`,E)}}async handleRemoteBranchesRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Remote branches request",{clientId:T.clientId,path:T.path});let A=await tW(T.path),E={success:!0,branches:A.branches,defaultBranch:A.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling remote branches request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${A.clientId}/response`,E)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,activeWorktrees:this.worktreeManager.getActiveWorktreeCount(),ghAuthenticated:this.ghAuthResult.authenticated,ghInstalled:this.ghAuthResult.installed,ghInPath:this.ghAuthResult.inPath,ghError:this.ghAuthResult.error,ghUsername:this.ghAuthResult.username}}}import*as $N from"path";import*as x5 from"path";import*as HN from"os";var d_=v(),S8=x5.join(HN.homedir(),".ccc"),JN=x5.join(S8,"device-tokens.json"),XN=x5.join(S8,"notification-preferences.json");class ZN{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if((await Bun.$`test -d ${S8}`.quiet().nothrow()).exitCode!==0)await Bun.$`mkdir -p ${S8}`.quiet(),d_.debug("[NotificationStorage] Created .ccc directory:",S8)}catch(_){throw d_.error("[NotificationStorage] Error ensuring directory:",_),_}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let _=Bun.file(JN);if(await _.exists()){let T=await _.text();return this.tokensCache=JSON.parse(T),d_.debug("[NotificationStorage] Loaded tokens:",{count:this.tokensCache?.tokens?.length||0}),this.tokensCache}}catch(_){d_.warn("[NotificationStorage] Error loading tokens, starting fresh:",_)}return this.tokensCache={tokens:[]},this.tokensCache}async saveTokens(_){try{await this.ensureDirectory(),await Bun.write(JN,JSON.stringify(_,null,2)),this.tokensCache=_,d_.debug("[NotificationStorage] Saved tokens:",{count:_.tokens.length})}catch(T){throw d_.error("[NotificationStorage] Error saving tokens:",T),T}}async registerToken(_,T,A,E,L){let J=await this.loadTokens(),X=new Date().toISOString(),H=J.tokens.findIndex((Y)=>Y.deviceId===_),Z={deviceId:_,fcmToken:T,expoPushToken:A,platform:E,deviceInfo:L,createdAt:H>=0?J.tokens[H].createdAt:X,lastUsed:X};if(H>=0)J.tokens[H]=Z,d_.info("[NotificationStorage] Updated device token:",{deviceId:_,platform:E,hasExpoPushToken:!!A});else J.tokens.push(Z),d_.info("[NotificationStorage] Registered new device token:",{deviceId:_,platform:E,hasExpoPushToken:!!A});return await this.saveTokens(J),Z}async unregisterToken(_){let T=await this.loadTokens(),A=T.tokens.length;if(T.tokens=T.tokens.filter((E)=>E.deviceId!==_),T.tokens.length<A)return await this.saveTokens(T),d_.info("[NotificationStorage] Unregistered device token:",{deviceId:_}),!0;return!1}async getToken(_){return(await this.loadTokens()).tokens.find((A)=>A.deviceId===_)}async getAllTokens(){return(await this.loadTokens()).tokens}async getDeviceCount(){return(await this.loadTokens()).tokens.length}async updateLastUsed(_){let T=await this.loadTokens(),A=T.tokens.find((E)=>E.deviceId===_);if(A)A.lastUsed=new Date().toISOString(),await this.saveTokens(T)}async cleanupOldTokens(_=90){let T=await this.loadTokens(),A=new Date;A.setDate(A.getDate()-_);let E=A.toISOString(),L=T.tokens.length;T.tokens=T.tokens.filter((X)=>X.lastUsed>E);let J=L-T.tokens.length;if(J>0)await this.saveTokens(T),d_.info("[NotificationStorage] Cleaned up old tokens:",{removed:J,remaining:T.tokens.length});return J}async loadPreferences(){if(this.preferencesCache)return this.preferencesCache;try{let _=Bun.file(XN);if(await _.exists()){let T=await _.text();return this.preferencesCache=JSON.parse(T),d_.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys(this.preferencesCache?.preferences||{}).length}),this.preferencesCache}}catch(_){d_.warn("[NotificationStorage] Error loading preferences, starting fresh:",_)}return this.preferencesCache={preferences:{}},this.preferencesCache}async savePreferences(_){try{await this.ensureDirectory(),await Bun.write(XN,JSON.stringify(_,null,2)),this.preferencesCache=_,d_.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(_.preferences).length})}catch(T){throw d_.error("[NotificationStorage] Error saving preferences:",T),T}}getDefaultPreferences(_){return{deviceId:_,allMessages:!0,needsAttention:!0,updatedAt:new Date().toISOString()}}async getPreferences(_){let T=await this.loadPreferences();if(!T.preferences[_])T.preferences[_]=this.getDefaultPreferences(_),await this.savePreferences(T),d_.info("[NotificationStorage] Created default preferences for device:",{deviceId:_});return T.preferences[_]}async updatePreferences(_,T){let A=await this.loadPreferences(),E=await this.getPreferences(_);return A.preferences[_]={...E,...T,deviceId:_,updatedAt:new Date().toISOString()},await this.savePreferences(A),d_.info("[NotificationStorage] Updated preferences:",{deviceId:_,updates:T}),A.preferences[_]}async isNotificationEnabled(_,T){return(await this.getPreferences(_))[T]}clearCache(){this.tokensCache=null,this.preferencesCache=null,d_.debug("[NotificationStorage] Cleared cache")}}var w1=new ZN;import YN from"expo-server-sdk";var G1=v();class KN{expo;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;constructor(){this.expo=new YN}isValidToken(_){return YN.isExpoPushToken(_)}async sendNotification(_,T){if(!this.isValidToken(_))return G1.warn("[ExpoPushClient] Invalid Expo push token:",{token:_.substring(0,20)+"..."}),null;let A={to:_,title:T.title,body:T.body,data:T.data,sound:T.sound||"default",channelId:T.channelId||"default",priority:T.priority||"high",badge:T.badge};try{let L=(await this.expo.sendPushNotificationsAsync([A]))[0];if(this.notificationsSent++,this.lastNotificationAt=new Date,L.id){let J=L;this.pendingTickets.set(J.id,{ticketId:J.id,token:_,createdAt:new Date})}if(L.status==="error"){let J=L;await this.handleTicketError(J,_)}return G1.debug("[ExpoPushClient] Sent notification:",{token:_.substring(0,20)+"...",status:L.status}),L}catch(E){return G1.error("[ExpoPushClient] Error sending notification:",E),null}}async sendBatchNotifications(_,T){let A=_.filter((X)=>{let H=this.isValidToken(X);if(!H)G1.warn("[ExpoPushClient] Skipping invalid token:",{token:X.substring(0,20)+"..."});return H});if(A.length===0)return G1.warn("[ExpoPushClient] No valid tokens to send to"),[];let E=A.map((X)=>({to:X,title:T.title,body:T.body,data:T.data,sound:T.sound||"default",channelId:T.channelId||"default",priority:T.priority||"high",badge:T.badge})),L=this.expo.chunkPushNotifications(E),J=[];for(let X of L)try{let H=await this.expo.sendPushNotificationsAsync(X);J.push(...H);for(let Z=0;Z<H.length;Z++){let Y=H[Z],K=A[J.length-H.length+Z];if(Y.id){let G=Y;this.pendingTickets.set(G.id,{ticketId:G.id,token:K,createdAt:new Date})}if(Y.status==="error")await this.handleTicketError(Y,K)}this.notificationsSent+=H.length,this.lastNotificationAt=new Date}catch(H){G1.error("[ExpoPushClient] Error sending batch chunk:",H)}return G1.info("[ExpoPushClient] Sent batch notifications:",{total:A.length,successful:J.filter((X)=>X.status==="ok").length,failed:J.filter((X)=>X.status==="error").length}),J}async handleTicketError(_,T){if(G1.warn("[ExpoPushClient] Ticket error:",{message:_.message,details:_.details}),_.details?.error==="DeviceNotRegistered"){G1.info("[ExpoPushClient] Removing invalid token:",{token:T.substring(0,20)+"..."});let E=(await w1.getAllTokens()).find((L)=>L.expoPushToken===T);if(E)await w1.unregisterToken(E.deviceId)}}async checkReceipts(){let _=new Date;_.setMinutes(_.getMinutes()-15);let T=[];for(let[L,J]of this.pendingTickets.entries())if(J.createdAt<_)T.push(L);if(T.length===0)return;G1.debug("[ExpoPushClient] Checking receipts:",{count:T.length});let A=this.expo.chunkPushNotificationReceiptIds(T);for(let L of A)try{let J=await this.expo.getPushNotificationReceiptsAsync(L);for(let[X,H]of Object.entries(J)){let Z=this.pendingTickets.get(X);if(H.status==="ok")G1.debug("[ExpoPushClient] Receipt OK:",{ticketId:X});else if(H.status==="error"){let Y=H;if(G1.warn("[ExpoPushClient] Receipt error:",{ticketId:X,message:Y.message,details:Y.details}),Y.details?.error==="DeviceNotRegistered"&&Z){let G=(await w1.getAllTokens()).find(($)=>$.expoPushToken===Z.token);if(G)G1.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:G.deviceId}),await w1.unregisterToken(G.deviceId)}}this.pendingTickets.delete(X)}}catch(J){G1.error("[ExpoPushClient] Error checking receipts:",J)}let E=new Date;E.setHours(E.getHours()-24);for(let[L,J]of this.pendingTickets.entries())if(J.createdAt<E)this.pendingTickets.delete(L)}getStats(){return{notificationsSent:this.notificationsSent,lastNotificationAt:this.lastNotificationAt,pendingReceipts:this.pendingTickets.size}}}var y8=new KN;var Q_=v(),GN=200,ph=900000;class w5{name="Notification Service";running=!1;startedAt;mqttClient=null;claudeAgentService=null;receiptCheckInterval;constructor(){}setMQTTClient(_){this.mqttClient=_}setClaudeAgentService(_){this.claudeAgentService=_}async start(){try{if(this.running=!0,this.startedAt=new Date,Q_.info("[Notification] Service started"),this.mqttClient)this.registerMQTTHandlers();else Q_.warn("[Notification] MQTT client not set - handlers will not be registered");this.receiptCheckInterval=setInterval(()=>{y8.checkReceipts().catch((_)=>{Q_.error("[Notification] Error checking receipts:",_)})},ph),Q_.info("[Notification] Ready to send notifications")}catch(_){throw Q_.error("[Notification] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.receiptCheckInterval)clearInterval(this.receiptCheckInterval);Q_.info("[Notification] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("notifications/register/request",this.handleRegisterToken.bind(this)),this.mqttClient.subscribe("notifications/preferences/get/request",this.handleGetPreferences.bind(this)),this.mqttClient.subscribe("notifications/preferences/update/request",this.handleUpdatePreferences.bind(this)),this.mqttClient.subscribe("claude/+/output/+",this.handleClaudeOutput.bind(this)),this.mqttClient.subscribe("claude/+/permission/request/+",this.handlePermissionRequest.bind(this)),Q_.info("[Notification] MQTT handlers registered")}async handleRegisterToken(_,T){try{let A=JSON.parse(T.toString());Q_.info("[Notification] Register token request:",{deviceId:A.deviceId,platform:A.platform,hasExpoPushToken:!!A.expoPushToken,hasFcmToken:!!A.fcmToken}),await w1.registerToken(A.deviceId,A.fcmToken,A.expoPushToken,A.platform,A.deviceInfo);let E={requestId:A.requestId,success:!0};await this.mqttClient?.publish("notifications/register/response",JSON.stringify(E)),Q_.info("[Notification] Token registered successfully:",{deviceId:A.deviceId})}catch(A){Q_.error("[Notification] Error registering token:",A);try{let E=T.toString(),J={requestId:JSON.parse(E).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/register/response",JSON.stringify(J))}catch{}}}async handleGetPreferences(_,T){try{let A=JSON.parse(T.toString());Q_.debug("[Notification] Get preferences request:",{deviceId:A.deviceId});let E=await w1.getPreferences(A.deviceId),L={requestId:A.requestId,success:!0,preferences:E};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(L)),Q_.debug("[Notification] Sent preferences:",{deviceId:A.deviceId})}catch(A){Q_.error("[Notification] Error getting preferences:",A);try{let L={requestId:JSON.parse(T.toString()).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(L))}catch{}}}async handleUpdatePreferences(_,T){try{let A=JSON.parse(T.toString());Q_.info("[Notification] Update preferences request:",{deviceId:A.deviceId,preferences:A.preferences});let E=await w1.updatePreferences(A.deviceId,A.preferences),L={requestId:A.requestId,success:!0,preferences:E};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(L)),Q_.info("[Notification] Preferences updated:",{deviceId:A.deviceId})}catch(A){Q_.error("[Notification] Error updating preferences:",A);try{let L={requestId:JSON.parse(T.toString()).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(L))}catch{}}}async handleClaudeOutput(_,T){try{let A=_.split("/"),E=A[1],L=A[3],J=JSON.parse(T.toString());if(J.type!=="assistant")return;let X=this.getSessionInfo(L);if(!X){Q_.debug("[Notification] Session not found for notification:",{sessionId:L});return}let H=this.buildNotificationTitle(X),Z=this.extractMessageBody(J);if(!Z)return;let Y={type:"message",projectId:X.projectPath,sessionId:L};await this.sendToDevicesWithPreference("allMessages",{title:H,body:Z,data:Y,priority:"high",channelId:"messages"}),Q_.debug("[Notification] Sent message notification:",{sessionId:L,title:H})}catch(A){Q_.error("[Notification] Error handling Claude output:",A)}}async handlePermissionRequest(_,T){try{let A=_.split("/"),E=A[1],L=A[4],J=JSON.parse(T.toString()),X=this.getSessionInfo(L);if(!X){Q_.debug("[Notification] Session not found for permission notification:",{sessionId:L});return}let H=this.buildNotificationTitle(X),Z=this.buildPermissionBody(J),Y={type:"permission",projectId:X.projectPath,sessionId:L,requestId:J.request_id,action:J.action};await this.sendToDevicesWithPreference("needsAttention",{title:H,body:Z,data:Y,priority:"high",channelId:"default"}),Q_.info("[Notification] Sent permission notification:",{sessionId:L,action:J.action})}catch(A){Q_.error("[Notification] Error handling permission request:",A)}}getSessionInfo(_){if(!this.claudeAgentService)return null;let A=this.claudeAgentService.getActiveSessions().find((E)=>E.sessionId===_);if(!A)return null;return{sessionId:A.sessionId,projectPath:A.projectPath,worktreeBranch:A.worktreeBranch}}buildNotificationTitle(_){let T=$N.basename(_.projectPath);if(_.worktreeBranch){let A=_.worktreeBranch.replace("session/","");return`${T} (${A})`}return T}extractMessageBody(_){let T="",A=_.message;if(A?.content&&Array.isArray(A.content))T=A.content.filter((L)=>L.type==="text").map((L)=>L.text).filter(Boolean).join(`
|
|
2639
|
+
`);else if(_.content){if(typeof _.content==="string")T=_.content;else if(Array.isArray(_.content))T=_.content.filter((L)=>L.type==="text").map((L)=>L.text).filter(Boolean).join(`
|
|
2640
|
+
`)}if(!T.trim())return null;if(T.length>GN)T=T.substring(0,GN)+"...";return T}buildPermissionBody(_){let T=_.action||"Unknown tool",A=_.params||{},E="";switch(T.toLowerCase()){case"bash":case"execute_command":E=A.command||"";break;case"read":case"read_file":E=A.file_path||"";break;case"write":case"write_file":E=A.file_path||"";break;case"edit":E=A.file_path||"";break;case"webfetch":E=A.url||"";break;case"websearch":E=A.query||"";break;default:E=A.file_path||A.command||A.path||""}if(E.length>100)E=E.substring(0,100)+"...";if(E)return`Permission requested: ${T}: ${E}`;return`Permission requested: ${T}`}async sendToDevicesWithPreference(_,T){try{let A=await w1.getAllTokens();if(A.length===0){Q_.debug("[Notification] No registered devices");return}let E=[];for(let L of A){if(!L.expoPushToken)continue;if((await w1.getPreferences(L.deviceId))[_])E.push(L.expoPushToken)}if(E.length===0){Q_.debug("[Notification] No devices with preference enabled:",{preferenceType:_});return}await y8.sendBatchNotifications(E,T),Q_.debug("[Notification] Sent to devices:",{count:E.length,preferenceType:_})}catch(A){Q_.error("[Notification] Error sending to devices:",A)}}getStatus(){let _=y8.getStats();return{name:this.name,running:this.running,startedAt:this.startedAt,registeredDevices:0,notificationsSent:_.notificationsSent,lastNotificationAt:_.lastNotificationAt}}}class K9{services=[];startedServices=[];logger=v();addService(_){this.services.push(_)}addOptionalService(_,T){if(T)this.services.push(_)}getServiceByName(_){return this.services.find((T)=>T.name===_)}async startAll(){for(let _ of this.services)try{this.logger.debug(`Starting ${_.name}...`),await _.start(),this.startedServices.push(_)}catch(T){throw this.logger.error(`Failed to start ${_.name}`,T),await this.stopAll(),T}this.logger.info("All services started successfully")}async stopAll(){for(let _=this.startedServices.length-1;_>=0;_--){let T=this.startedServices[_];try{this.logger.debug(`Stopping ${T?.name}...`),await T?.stop()}catch(A){this.logger.error(`Failed to stop ${T?.name}`,A)}}this.startedServices=[],this.logger.info("All services stopped")}getStatus(){return this.services.map((_)=>_.getStatus())}printStatus(){let _=this.getStatus();this.logger.info("=== Backend Status ===");for(let T of _){let A=T.running?"\u2713":"\u2717";if(this.logger.info(`${A} ${T.name}`),"port"in T&&T.port)this.logger.info(` Port: ${T.port}`);if("routes"in T&&T.routes)this.logger.info(` Routes: ${T.routes.map((E)=>`${E.path}->${E.target}`).join(", ")}`);if(T.startedAt)this.logger.info(` Started: ${T.startedAt.toISOString()}`);if(T.error)this.logger.info(` Error: ${T.error}`)}this.logger.info("=====================")}}import UN from"os";function WN(){let _=UN.networkInterfaces(),T=/^(wlan|wlp|wifi|wi-fi|en0)/i,A=/^(eth|enp|en1|ethernet)/i;for(let[E,L]of Object.entries(_))if(T.test(E)&&L){let J=L.find((X)=>X.family==="IPv4"&&!X.internal);if(J)return J.address}for(let[E,L]of Object.entries(_))if(A.test(E)&&L){let J=L.find((X)=>X.family==="IPv4"&&!X.internal);if(J)return J.address}for(let E of Object.values(_))if(E){let L=E.find((J)=>J.family==="IPv4"&&!J.internal);if(L)return L.address}return null}function NN(){let _=UN.hostname().toLowerCase();if(_.endsWith(".local"))_=_.slice(0,-6);return _=_.replace(/\./g,"-"),_||"ccc-server"}function lh(_){let T=v();try{if(process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",(A)=>{let E=A.toString().toLowerCase();if(E==="q")_.display();if(E==="\x03")process.emit("SIGINT")}),T.debug('Keypress listener enabled (press "q" to redisplay QR codes)')}catch(A){T.warn("Could not setup keypress listener",A)}}async function nh(){try{z9();let _=U9();N9(_.debug);let T=v();T.info("Backend v2 starting...");let A=W9(_);if(_.debug)T.debug("Configuration",A);let E=new mA(A.mqtt),L=new K5({host:"localhost",port:A.mqtt.port,username:A.mqtt.auth?.username,password:A.mqtt.auth?.password}),J=new G5(A.terminal),X=new U5(A.router),H=new z5(A.autoUpdate),Z=new F5,Y=new C5,K=new O5(J),G=new q5(A.claudeAgent),$=new P5,U=new j5,V=new w5,N=new K9;if(N.addService(E),N.addService(L),N.addService(J),N.addService(X),N.addService(H),N.addService(Z),N.addService(Y),N.addService(K),N.addService(G),N.addService($),N.addService(U),N.addService(V),A.ngrok){let c=new W5(A.ngrok);N.addOptionalService(c,!0)}Z.setMQTTClient(L),Z.setClaudeAgentService(G),Y.setMQTTClient(L),K.setMQTTClient(L),G.setMQTTClient(L),G.setSessionsService(Z),$.setMQTTClient(L),U.setMQTTClient(L),V.setMQTTClient(L),V.setClaudeAgentService(G),await N.startAll();let z=N.getServiceByName("CCC Ngrok Service"),Q,F=WN(),R=F?`${F}:${A.router.port}`:void 0;if(z&&z.getStatus().active)Q=z.getUrl()||void 0;let q=NN(),f={...A.qrcode,profileName:q,ipBasedUrl:R,ngrokUrl:Q},h=new V5(f);N.addService(h),await h.start(),N.printStatus(),T.info("Backend v2 is ready"),lh(h);let b=!1,l=async(c)=>{if(b){T.warn("Shutdown already in progress, ignoring signal");return}b=!0,T.info(`Received ${c}, shutting down...`);try{await N.stopAll(),process.exit(0)}catch(W_){T.error("Error during shutdown",W_),process.exit(1)}};process.once("SIGINT",()=>l("SIGINT")),process.once("SIGTERM",()=>l("SIGTERM")),process.on("uncaughtException",(c)=>{if(c&&c.code==="ERR_SOCKET_CLOSED"){T.debug("Ignoring socket closed error (expected during PTY cleanup)");return}T.error("Uncaught exception",c)}),process.on("unhandledRejection",(c)=>{T.error("Unhandled rejection",c)})}catch(_){v().error("Fatal error",_),process.exit(1)}}nh();
|