@naarang/ccc 2.0.0-alpha.2 → 2.0.0-alpha.4

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 CHANGED
@@ -1,21 +1,21 @@
1
1
  // @bun
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(`
2
+ var CN=Object.create;var{getPrototypeOf:ON,defineProperty:N9,getOwnPropertyNames:RN}=Object;var DN=Object.prototype.hasOwnProperty;var q_=(_,T,A)=>{A=_!=null?CN(ON(_)):{};let E=T||!_||!_.__esModule?N9(A,"default",{value:_,enumerable:!0}):A;for(let L of RN(_))if(!DN.call(E,L))N9(E,L,{get:()=>_[L],enumerable:!0});return E};var W=(_,T)=>()=>(T||_((T={exports:{}}).exports,T),T.exports);var I=import.meta.require;var q9=W((Qk,B9)=>{B9.exports=fN;var kN=Object.prototype.hasOwnProperty;function fN(){var _={};for(var T=0;T<arguments.length;T++){var A=arguments[T];for(var E in A)if(kN.call(A,E))_[E]=A[E]}return _}});var k8=W((Mk,I9)=>{function bN(_){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}}I9.exports=bN});var f5=W((Vk,j9)=>{var gN=q9(),P9=k8(),mN={released:D0,results:!0};function uN(_){_=gN(mN,_);var T=_.released,A=P9(_.results?pN:dN),E=P9(cN),L=_.results?K:G,J=_.results?Y:$;return X;function X(U,V,N,z){var Q=A.get();if(z=z||D0,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=D0;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 $(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 G(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 dN(){this._count=-1,this._callback=D0,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=D0,_._callThat=null,T=0,_._release(_)}}}function cN(){this.pos=-1,this._release=D0,this.parent=null,this.next=null;var _=this;this.release=function(T,A){_.parent.release(T,_.pos,A),_.pos=-1,_.parent=null,_._release(_)}}function pN(){this._count=-1,this._callback=D0,this._results=null,this._err=null,this._callThat=null,this._release=D0,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=D0,_._results=null,_._err=null,_._callThat=null,T=0,_._release(_)}}}function D0(){}j9.exports=uN});var S9=W((zk,w9)=>{var lN={results:!0};function nN(_){_=Object.assign({},lN,_);var T,A;if(_.results)T=oN,A=rN;else T=iN,A=aN;return E;function E(L,J,X,H){if(H=(H||sN).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 iN(_,T,A){var E=0,L=T.length;J();function J(){if(E<L)f8(_,T[E++],J);else A()}}function aN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=x9;else J=f8;X();function X(){if(E<L)J(_[E++],T,X);else A()}}function oN(_,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 rN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=x9;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 x9(_,T,A){_(A)}function f8(_,T,A){_(T,A)}function sN(){}w9.exports=nN});var h9=W((y9)=>{Object.defineProperty(y9,"__esModule",{value:!0});y9.default=void 0;var Fk=y9.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var b9=W((k9)=>{Object.defineProperty(k9,"__esModule",{value:!0});k9.default=void 0;var Ok=k9.default="00000000-0000-0000-0000-000000000000"});var u9=W((g9)=>{Object.defineProperty(g9,"__esModule",{value:!0});g9.default=void 0;var Dk=g9.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((d9)=>{Object.defineProperty(d9,"__esModule",{value:!0});d9.default=void 0;var tN=eN(u9());function eN(_){return _&&_.__esModule?_:{default:_}}function _Q(_){return typeof _==="string"&&tN.default.test(_)}var qk=d9.default=_Q});var j4=W((p9)=>{Object.defineProperty(p9,"__esModule",{value:!0});p9.default=void 0;var TQ=AQ(P4());function AQ(_){return _&&_.__esModule?_:{default:_}}function EQ(_){if(!(0,TQ.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 Pk=p9.default=EQ});var B0=W((i9)=>{Object.defineProperty(i9,"__esModule",{value:!0});i9.default=void 0;i9.unsafeStringify=n9;var LQ=JQ(P4());function JQ(_){return _&&_.__esModule?_:{default:_}}var b_=[];for(let _=0;_<256;++_)b_.push((_+256).toString(16).slice(1));function n9(_,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 XQ(_,T=0){let A=n9(_,T);if(!(0,LQ.default)(A))throw TypeError("Stringified UUID is invalid");return A}var xk=i9.default=XQ});var m8=W((o9)=>{Object.defineProperty(o9,"__esModule",{value:!0});o9.default=KQ;var ZQ=YQ(I("crypto"));function YQ(_){return _&&_.__esModule?_:{default:_}}var g8=new Uint8Array(256),b8=g8.length;function KQ(){if(b8>g8.length-16)ZQ.default.randomFillSync(g8),b8=0;return g8.slice(b8,b8+=16)}});var u5=W((r9)=>{Object.defineProperty(r9,"__esModule",{value:!0});r9.default=void 0;var GQ=WQ(m8()),UQ=B0();function WQ(_){return _&&_.__esModule?_:{default:_}}var b5,u8,g5=0,m5=0;function NQ(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let{node:J,clockseq:X}=_;if(!_._v6){if(!J)J=b5;if(X==null)X=u8}if(J==null||X==null){let G=_.random||(_.rng||GQ.default)();if(J==null){if(J=[G[0],G[1],G[2],G[3],G[4],G[5]],!b5&&!_._v6)J[0]|=1,b5=J}if(X==null){if(X=(G[6]<<8|G[7])&16383,u8===void 0&&!_._v6)u8=X}}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:m5+1,Y=H-g5+(Z-m5)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>g5)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");g5=H,m5=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 $=H/4294967296*1e4&268435455;L[E++]=$>>>8&255,L[E++]=$&255,L[E++]=$>>>24&15|16,L[E++]=$>>>16&255,L[E++]=X>>>8|128,L[E++]=X&255;for(let G=0;G<6;++G)L[E+G]=J[G];return T||(0,UQ.unsafeStringify)(L)}var yk=r9.default=NQ});var d5=W((t9)=>{Object.defineProperty(t9,"__esModule",{value:!0});t9.default=zQ;var QQ=VQ(j4()),MQ=B0();function VQ(_){return _&&_.__esModule?_:{default:_}}function zQ(_){let T=typeof _==="string"?(0,QQ.default)(_):_,A=FQ(T);return typeof _==="string"?(0,MQ.unsafeStringify)(A):A}function FQ(_,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 c5=W((e9)=>{Object.defineProperty(e9,"__esModule",{value:!0});e9.URL=e9.DNS=void 0;e9.default=PQ;var OQ=B0(),RQ=DQ(j4());function DQ(_){return _&&_.__esModule?_:{default:_}}function BQ(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var qQ=e9.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",IQ=e9.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function PQ(_,T,A){function E(L,J,X,H){var Z;if(typeof L==="string")L=BQ(L);if(typeof J==="string")J=(0,RQ.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,OQ.unsafeStringify)(Y)}try{E.name=_}catch(L){}return E.DNS=qQ,E.URL=IQ,E}});var E7=W((T7)=>{Object.defineProperty(T7,"__esModule",{value:!0});T7.default=void 0;var wQ=SQ(I("crypto"));function SQ(_){return _&&_.__esModule?_:{default:_}}function yQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return wQ.default.createHash("md5").update(_).digest()}var fk=T7.default=yQ});var H7=W((J7)=>{Object.defineProperty(J7,"__esModule",{value:!0});J7.default=void 0;var vQ=L7(c5()),hQ=L7(E7());function L7(_){return _&&_.__esModule?_:{default:_}}var kQ=(0,vQ.default)("v3",48,hQ.default),gk=J7.default=kQ});var K7=W((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});Z7.default=void 0;var fQ=bQ(I("crypto"));function bQ(_){return _&&_.__esModule?_:{default:_}}var uk=Z7.default={randomUUID:fQ.default.randomUUID}});var N7=W((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});U7.default=void 0;var $7=G7(K7()),gQ=G7(m8()),mQ=B0();function G7(_){return _&&_.__esModule?_:{default:_}}function uQ(_,T,A){if($7.default.randomUUID&&!T&&!_)return $7.default.randomUUID();_=_||{};let E=_.random||(_.rng||gQ.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,mQ.unsafeStringify)(E)}var ck=U7.default=uQ});var V7=W((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});Q7.default=void 0;var dQ=cQ(I("crypto"));function cQ(_){return _&&_.__esModule?_:{default:_}}function pQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return dQ.default.createHash("sha1").update(_).digest()}var lk=Q7.default=pQ});var O7=W((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});F7.default=void 0;var lQ=z7(c5()),nQ=z7(V7());function z7(_){return _&&_.__esModule?_:{default:_}}var iQ=(0,lQ.default)("v5",80,nQ.default),ik=F7.default=iQ});var B7=W((D7)=>{Object.defineProperty(D7,"__esModule",{value:!0});D7.default=sQ;var aQ=B0(),oQ=R7(u5()),rQ=R7(d5());function R7(_){return _&&_.__esModule?_:{default:_}}function sQ(_={},T,A=0){let E=(0,oQ.default)({..._,_v6:!0},new Uint8Array(16));if(E=(0,rQ.default)(E),T){for(let L=0;L<16;L++)T[A+L]=E[L];return T}return(0,aQ.unsafeStringify)(E)}});var I7=W((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});q7.default=AM;var eQ=TM(j4()),_M=B0();function TM(_){return _&&_.__esModule?_:{default:_}}function AM(_){let T=typeof _==="string"?(0,eQ.default)(_):_,A=EM(T);return typeof _==="string"?(0,_M.unsafeStringify)(A):A}function EM(_){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 S7=W((x7)=>{Object.defineProperty(x7,"__esModule",{value:!0});x7.default=void 0;var JM=HM(m8()),XM=B0();function HM(_){return _&&_.__esModule?_:{default:_}}var P7=null,j7=null,k1=0;function ZM(_,T,A){_=_||{};let E=T&&A||0,L=T||new Uint8Array(16),J=_.random||(_.rng||JM.default)(),X=_.msecs!==void 0?_.msecs:Date.now(),H=_.seq!==void 0?_.seq:null,Z=j7,Y=P7;if(X>k1&&_.msecs===void 0){if(k1=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>k1&&H===null){if(++Y>524287){if(Y=0,++Z>4095)Z=0,k1++}}else k1=X;return j7=Z,P7=Y,L[E++]=k1/1099511627776&255,L[E++]=k1/4294967296&255,L[E++]=k1/16777216&255,L[E++]=k1/65536&255,L[E++]=k1/256&255,L[E++]=k1&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,XM.unsafeStringify)(L)}var sk=x7.default=ZM});var h7=W((y7)=>{Object.defineProperty(y7,"__esModule",{value:!0});y7.default=void 0;var YM=KM(P4());function KM(_){return _&&_.__esModule?_:{default:_}}function $M(_){if(!(0,YM.default)(_))throw TypeError("Invalid UUID");return parseInt(_.slice(14,15),16)}var ek=y7.default=$M});var k7=W((p_)=>{Object.defineProperty(p_,"__esModule",{value:!0});Object.defineProperty(p_,"MAX",{enumerable:!0,get:function(){return GM.default}});Object.defineProperty(p_,"NIL",{enumerable:!0,get:function(){return UM.default}});Object.defineProperty(p_,"parse",{enumerable:!0,get:function(){return WM.default}});Object.defineProperty(p_,"stringify",{enumerable:!0,get:function(){return NM.default}});Object.defineProperty(p_,"v1",{enumerable:!0,get:function(){return QM.default}});Object.defineProperty(p_,"v1ToV6",{enumerable:!0,get:function(){return MM.default}});Object.defineProperty(p_,"v3",{enumerable:!0,get:function(){return VM.default}});Object.defineProperty(p_,"v4",{enumerable:!0,get:function(){return zM.default}});Object.defineProperty(p_,"v5",{enumerable:!0,get:function(){return FM.default}});Object.defineProperty(p_,"v6",{enumerable:!0,get:function(){return CM.default}});Object.defineProperty(p_,"v6ToV1",{enumerable:!0,get:function(){return OM.default}});Object.defineProperty(p_,"v7",{enumerable:!0,get:function(){return RM.default}});Object.defineProperty(p_,"validate",{enumerable:!0,get:function(){return DM.default}});Object.defineProperty(p_,"version",{enumerable:!0,get:function(){return BM.default}});var GM=J1(h9()),UM=J1(b9()),WM=J1(j4()),NM=J1(B0()),QM=J1(u5()),MM=J1(d5()),VM=J1(H7()),zM=J1(N7()),FM=J1(O7()),CM=J1(B7()),OM=J1(I7()),RM=J1(S7()),DM=J1(P4()),BM=J1(h7());function J1(_){return _&&_.__esModule?_:{default:_}}});var uT=W((Af,f7)=>{function qM(_,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}f7.exports=qM});var p5=W((Ef,b7)=>{var f1=I("util");b7.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 i5=W((m7)=>{var d8=I("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 V1(_){L_.call(this,_)}d8.inherits(V1,L_);V1.prototype._initial_value=function(_){return new Set().add(_)};V1.prototype._add_value=function(_,T){_.add(T)};V1.prototype._add_values=function(_,T){T.forEach(function(A){_.add(A)})};V1.prototype._remove_value=function(_,T){if(T===void 0)return!0;return _.delete(T),_.size===0};V1.prototype.test_values=function(_,T){return _.has(T)};V1.prototype.match=function(_,T){return this._match2(new Set,_,T)};function s1(_){L_.call(this,_)}d8.inherits(s1,L_);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 c8=I("stream");function l5(_){c8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}d8.inherits(l5,c8.Readable);l5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function n5(_){c8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}d8.inherits(n5,c8.Writable);n5.prototype._write=function(_,T,A){this._restorer(_),A()};var g7=null;function IM(_){if(_!==g7){let T=p5();L_.nativeString=T(_.QlobberString,L_),L_.nativeNumber=T(_.QlobberNumber,L_),V1.nativeString=T(_.QlobberDedupString,V1),V1.nativeNumber=T(_.QlobberDedupNumber,V1),s1.native=T(_.QlobberTrue,s1),g7=_}return m7}m7.Qlobber=L_;m7.QlobberDedup=V1;m7.QlobberTrue=s1;m7.VisitorStream=l5;m7.RestorerStream=n5;m7.set_native=IM});var u7=W((Jf,o5)=>{var vM=I("util"),hM=i5(),a5=hM.Qlobber;function z1(_){a5.call(this,_),this.subscriptionsCount=0}vM.inherits(z1,a5);z1.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};z1.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};z1.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})};z1.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};z1.prototype.test_values=function(_,T){var A=_.clientMap;return _.topic===T.topic&&A.size===1&&A.has(T.clientId)};z1.prototype.match=function(_,T){return this._match([],0,_.split(this._separator),this._trie,T)};z1.prototype.clear=function(){return this.subscriptionsCount=0,a5.prototype.clear.call(this)};z1.set_native=function(_){let T=p5();return z1.native=T(_.QlobberSub,z1),o5.exports};o5.exports=z1});var l7=W((Xf,s5)=>{var{Readable:x4}=I("stream"),kM=u7(),{QlobberTrue:fM}=i5(),r5=uT(),c7={wildcard_one:"+",wildcard_some:"#",separator:"/"};function*bM(_){for(let T of _)yield*T}function*d7(_,T){let A=new fM(c7);A.add(T);for(let[E,L]of _)if(A.test(E))yield L}function*gM(_,T){for(let A of _.values())if(!T[A.brokerId])yield A}function*mM(_,T){for(let[A,E]of _)if(E.has(T))yield A}class p7{#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 kM(c7)}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 d7(this.#J,A)});return x4.from(bM(T))}createRetainedStream(_){return x4.from(d7(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=ZT(this.#Y,A,[],!0);E[E.length]=new r5(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=ZT(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=ZT(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(ZT(this.#Y,_.id,[]));return x4.from(T)}incomingStorePacket(_,T,A){let E=_.id,L=ZT(this.#K,E,{},!0);L[T.messageId]=new r5(T),L[T.messageId].messageId=T.messageId,A(null)}incomingGetPacket(_,T,A){let E=_.id,L=ZT(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=ZT(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(gM(this.#N,_))}getClientList(_){return x4.from(mM(this.#L,_))}destroy(_){if(this.#J=null,_)_(null)}}function ZT(_,T,A,E=!1){let L=_.get(T);if(L===void 0&&E)_.set(T,A);return L||A}s5.exports=()=>{return new p7};s5.exports.Packet=r5});var i7=W((Hf,n7)=>{var b1=I("util");n7.exports=function(_,T){class A extends _{constructor(E){super(E);this.addP=b1.promisify(this.add_async),this.removeP=b1.promisify(this.remove_async),this.matchP=b1.promisify(this.match_async),this.testP=b1.promisify(this.test_async),this.clearP=b1.promisify(this.clear_async),this._get_visitorP=b1.promisify(this.get_visitor_async),this._visit_nextP=b1.promisify(this.visit_next_async),this._get_restorerP=b1.promisify(this.get_restorer_async),this._restore_nextP=b1.promisify(this.restore_next_async),this._match_iterP=b1.promisify(this.match_iter_async),this._match_nextP=b1.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 r7=W((o7)=>{var p8=I("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 F1(_){J_.call(this,_)}p8.inherits(F1,J_);F1.prototype._initial_value=function(_){return new Set().add(_)};F1.prototype._add_value=function(_,T){_.add(T)};F1.prototype._add_values=function(_,T){T.forEach(function(A){_.add(A)})};F1.prototype._remove_value=function(_,T){if(T===void 0)return!0;return _.delete(T),_.size===0};F1.prototype.test_values=function(_,T){return _.has(T)};F1.prototype.match=function(_,T){return this._match2(new Set,_,T)};function t1(_){J_.call(this,_)}p8.inherits(t1,J_);t1.prototype._initial_value=function(){return!0};t1.prototype._add_value=function(){};t1.prototype._remove_value=function(){return!0};t1.prototype._iter_values=function*(){yield!0};t1.prototype.test_values=function(){return!0};t1.prototype.match=function(_,T){return this.test(_,T)};var l8=I("stream");function t5(_){l8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}p8.inherits(t5,l8.Readable);t5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function e5(_){l8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}p8.inherits(e5,l8.Writable);e5.prototype._write=function(_,T,A){this._restorer(_),A()};var a7=null;function uM(_){if(_!==a7){let T=i7();J_.nativeString=T(_.QlobberString,J_),J_.nativeNumber=T(_.QlobberNumber,J_),F1.nativeString=T(_.QlobberDedupString,F1),F1.nativeNumber=T(_.QlobberDedupNumber,F1),t1.native=T(_.QlobberTrue,t1),a7=_}return o7}o7.Qlobber=J_;o7.QlobberDedup=F1;o7.QlobberTrue=t1;o7.VisitorStream=t5;o7.RestorerStream=e5;o7.set_native=uM});var t7=W((Yf,s7)=>{var{Qlobber:aM}=r7(),dT=I("assert"),oM=f5();function e1(_){if(!(this instanceof e1))return new e1(_);let T=this;_=_||{},_.matchEmptyLevels=_.matchEmptyLevels===void 0?!0:!!_.matchEmptyLevels,_.separator=_.separator||"/",_.wildcardOne=_.wildcardOne||"+",_.wildcardSome=_.wildcardSome||"#",this._messageQueue=[],this._messageCallbacks=[],this._parallel=oM({results:!1,released:A}),this.concurrency=_.concurrency||0,this.current=0,this._doing=!1,this._matcher=new aM({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(e1.prototype,"length",{get:function(){return this._messageQueue.length},enumerable:!0});e1.prototype.on=function(T,A,E){if(dT(T),dT(A),this._matcher.add(T,A),E)setImmediate(E);return this};e1.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};e1.prototype.removeAllListeners=function(T,A){if(dT(T),this._matcher.remove(T),A)setImmediate(A);return this};e1.prototype.emit=function(T,A){if(dT(T),A=A||rM,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};e1.prototype.close=function(T){return this.closed=!0,setImmediate(T),this};e1.prototype._do=function(_,T){this._doing=!0;let A=this._matcher.match(_.topic);return this.current++,this._parallel(this,A,_,T),this};function rM(){}s7.exports=e1});var z_=W((Kf,_J)=>{class e7 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=_}}_J.exports={AggregateError:e7,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 _6=W(($f,TJ)=>{TJ.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((Gf,JJ)=>{var{format:sM,inspect:n8}=_6(),{AggregateError:tM}=z_(),eM=globalThis.AggregateError||tM,_V=Symbol("kIsNodeError"),TV=["string","function","number","object","Function","Object","boolean","bigint","symbol"],AV=/^([A-Z][a-z0-9]*)+$/,i8={};function YT(_,T){if(!_)throw new i8.ERR_INTERNAL_ASSERTION(T)}function AJ(_){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 EV(_,T,A){if(typeof T==="function")return YT(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(YT(E===A.length,`Code: ${_}; The provided arguments length (${A.length}) does not match the required ones (${E}).`),A.length===0)return T;return sM(T,...A)}function g_(_,T,A){if(!A)A=Error;class E extends A{constructor(...L){super(EV(_,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[_V]=!0,i8[_]=E}function EJ(_){let T="__node_internal_"+_.name;return Object.defineProperty(_,"name",{value:T}),_}function LV(_,T){if(_&&T&&_!==T){if(Array.isArray(T.errors))return T.errors.push(_),T;let A=new eM([T,_],T.message);return A.code=T.code,A}return _||T}class LJ 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(YT(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(YT(typeof Z==="string","All expected entries have to be of type string"),TV.includes(Z))L.push(Z.toLowerCase());else if(AV.test(Z))J.push(Z);else YT(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",(..._)=>{YT(_.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)=>{YT(T,'Missing "range" argument');let E;if(Number.isInteger(A)&&Math.abs(A)>4294967296)E=AJ(String(A));else if(typeof A==="bigint"){E=String(A);let L=BigInt(2)**BigInt(32);if(A>L||A<-L)E=AJ(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);JJ.exports={AbortError:LJ,aggregateTwoErrors:EJ(LV),hideStackFrames:EJ,codes:i8}});var s_=W((Uf,A6)=>{var JV=I("buffer"),{format:XV,inspect:HV}=_6(),{codes:{ERR_INVALID_ARG_TYPE:T6}}=l_(),{kResistStopPropagation:ZV,AggregateError:YV,SymbolDispose:KV}=z_(),$V=globalThis.AbortSignal||I("abort-controller").AbortSignal,GV=globalThis.AbortController||I("abort-controller").AbortController,UV=Object.getPrototypeOf(async function(){}).constructor,XJ=globalThis.Blob||JV.Blob,WV=typeof XJ<"u"?function(T){return T instanceof XJ}:function(T){return!1},HJ=(_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new T6(T,"AbortSignal",_)},NV=(_,T)=>{if(typeof _!=="function")throw new T6(T,"Function",_)};A6.exports={AggregateError:YV,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:XV,inspect:HV,types:{isAsyncFunction(_){return _ instanceof UV},isArrayBufferView(_){return ArrayBuffer.isView(_)}},isBlob:WV,deprecate(_,T){return _},addAbortListener:I("events").addAbortListener||function(T,A){if(T===void 0)throw new T6("signal","AbortSignal",T);HJ(T,"signal"),NV(A,"listener");let E;if(T.aborted)queueMicrotask(()=>A());else T.addEventListener("abort",A,{__proto__:null,once:!0,[ZV]:!0}),E=()=>{T.removeEventListener("abort",A)};return{__proto__:null,[KV](){var L;(L=E)===null||L===void 0||L()}}},AbortSignalAny:$V.any||function(T){if(T.length===1)return T[0];let A=new GV,E=()=>A.abort();return T.forEach((L)=>{HJ(L,"signals"),L.addEventListener("abort",E,{once:!0})}),A.signal.addEventListener("abort",()=>{T.forEach((L)=>L.removeEventListener("abort",E))},{once:!0}),A.signal}};A6.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var pT=W((Wf,MJ)=>{var{ArrayIsArray:L6,ArrayPrototypeIncludes:$J,ArrayPrototypeJoin:GJ,ArrayPrototypeMap:QV,NumberIsInteger:J6,NumberIsNaN:MV,NumberMAX_SAFE_INTEGER:VV,NumberMIN_SAFE_INTEGER:zV,NumberParseInt:FV,ObjectPrototypeHasOwnProperty:CV,RegExpPrototypeExec:UJ,String:OV,StringPrototypeToUpperCase:RV,StringPrototypeTrim:DV}=z_(),{hideStackFrames:C1,codes:{ERR_SOCKET_BAD_PORT:BV,ERR_INVALID_ARG_TYPE:n_,ERR_INVALID_ARG_VALUE:cT,ERR_OUT_OF_RANGE:KT,ERR_UNKNOWN_SIGNAL:ZJ}}=l_(),{normalizeEncoding:qV}=s_(),{isAsyncFunction:IV,isArrayBufferView:PV}=s_().types,YJ={};function jV(_){return _===(_|0)}function xV(_){return _===_>>>0}var wV=/^[0-7]+$/,SV="must be a 32-bit unsigned integer or an octal string";function yV(_,T,A){if(typeof _>"u")_=A;if(typeof _==="string"){if(UJ(wV,_)===null)throw new cT(T,_,SV);_=FV(_,8)}return WJ(_,T),_}var vV=C1((_,T,A=zV,E=VV)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!J6(_))throw new KT(T,"an integer",_);if(_<A||_>E)throw new KT(T,`>= ${A} && <= ${E}`,_)}),hV=C1((_,T,A=-2147483648,E=2147483647)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!J6(_))throw new KT(T,"an integer",_);if(_<A||_>E)throw new KT(T,`>= ${A} && <= ${E}`,_)}),WJ=C1((_,T,A=!1)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!J6(_))throw new KT(T,"an integer",_);let E=A?1:0,L=4294967295;if(_<E||_>L)throw new KT(T,`>= ${E} && <= ${L}`,_)});function X6(_,T){if(typeof _!=="string")throw new n_(T,"string",_)}function kV(_,T,A=void 0,E){if(typeof _!=="number")throw new n_(T,"number",_);if(A!=null&&_<A||E!=null&&_>E||(A!=null||E!=null)&&MV(_))throw new KT(T,`${A!=null?`>= ${A}`:""}${A!=null&&E!=null?" && ":""}${E!=null?`<= ${E}`:""}`,_)}var fV=C1((_,T,A)=>{if(!$J(A,_)){let L="must be one of: "+GJ(QV(A,(J)=>typeof J==="string"?`'${J}'`:OV(J)),", ");throw new cT(T,_,L)}});function NJ(_,T){if(typeof _!=="boolean")throw new n_(T,"boolean",_)}function E6(_,T,A){return _==null||!CV(_,T)?A:_[T]}var bV=C1((_,T,A=null)=>{let E=E6(A,"allowArray",!1),L=E6(A,"allowFunction",!1);if(!E6(A,"nullable",!1)&&_===null||!E&&L6(_)||typeof _!=="object"&&(!L||typeof _!=="function"))throw new n_(T,"Object",_)}),gV=C1((_,T)=>{if(_!=null&&typeof _!=="object"&&typeof _!=="function")throw new n_(T,"a dictionary",_)}),a8=C1((_,T,A=0)=>{if(!L6(_))throw new n_(T,"Array",_);if(_.length<A){let E=`must be longer than ${A}`;throw new cT(T,_,E)}});function mV(_,T){a8(_,T);for(let A=0;A<_.length;A++)X6(_[A],`${T}[${A}]`)}function uV(_,T){a8(_,T);for(let A=0;A<_.length;A++)NJ(_[A],`${T}[${A}]`)}function dV(_,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);QJ(E,L)}}function cV(_,T="signal"){if(X6(_,T),YJ[_]===void 0){if(YJ[RV(_)]!==void 0)throw new ZJ(_+" (signals must use all capital letters)");throw new ZJ(_)}}var pV=C1((_,T="buffer")=>{if(!PV(_))throw new n_(T,["Buffer","TypedArray","DataView"],_)});function lV(_,T){let A=qV(T),E=_.length;if(A==="hex"&&E%2!==0)throw new cT("encoding",T,`is invalid for data of length ${E}`)}function nV(_,T="Port",A=!0){if(typeof _!=="number"&&typeof _!=="string"||typeof _==="string"&&DV(_).length===0||+_!==+_>>>0||_>65535||_===0&&!A)throw new BV(T,_,A);return _|0}var QJ=C1((_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new n_(T,"AbortSignal",_)}),iV=C1((_,T)=>{if(typeof _!=="function")throw new n_(T,"Function",_)}),aV=C1((_,T)=>{if(typeof _!=="function"||IV(_))throw new n_(T,"Function",_)}),oV=C1((_,T)=>{if(_!==void 0)throw new n_(T,"undefined",_)});function rV(_,T,A){if(!$J(A,_))throw new n_(T,`('${GJ(A,"|")}')`,_)}var sV=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function KJ(_,T){if(typeof _>"u"||!UJ(sV,_))throw new cT(T,_,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function tV(_){if(typeof _==="string")return KJ(_,"hints"),_;else if(L6(_)){let T=_.length,A="";if(T===0)return A;for(let E=0;E<T;E++){let L=_[E];if(KJ(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"')}MJ.exports={isInt32:jV,isUint32:xV,parseFileMode:yV,validateArray:a8,validateStringArray:mV,validateBooleanArray:uV,validateAbortSignalArray:dV,validateBoolean:NJ,validateBuffer:pV,validateDictionary:gV,validateEncoding:lV,validateFunction:iV,validateInt32:hV,validateInteger:vV,validateNumber:kV,validateObject:bV,validateOneOf:fV,validatePlainFunction:aV,validatePort:nV,validateSignalName:cV,validateString:X6,validateUint32:WJ,validateUndefined:oV,validateUnion:rV,validateAbortSignal:QJ,validateLinkHeaderValue:tV}});var c0=W((Nf,VJ)=>{VJ.exports=global.process});var T0=W((Qf,yJ)=>{var{SymbolAsyncIterator:zJ,SymbolIterator:FJ,SymbolFor:$T}=z_(),CJ=$T("nodejs.stream.destroyed"),OJ=$T("nodejs.stream.errored"),H6=$T("nodejs.stream.readable"),Z6=$T("nodejs.stream.writable"),RJ=$T("nodejs.stream.disturbed"),eV=$T("nodejs.webstream.isClosedPromise"),_z=$T("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 Tz(_){return!!(_&&typeof _.pipe==="function"&&_._readableState&&typeof _.on==="function"&&typeof _.write==="function")}function _0(_){return _&&(_._readableState||_._writableState||typeof _.write==="function"&&typeof _.on==="function"||typeof _.pipe==="function"&&typeof _.on==="function")}function DJ(_){return!!(_&&!_0(_)&&typeof _.pipeThrough==="function"&&typeof _.getReader==="function"&&typeof _.cancel==="function")}function BJ(_){return!!(_&&!_0(_)&&typeof _.getWriter==="function"&&typeof _.abort==="function")}function qJ(_){return!!(_&&!_0(_)&&typeof _.readable==="object"&&typeof _.writable==="object")}function Az(_){return DJ(_)||BJ(_)||qJ(_)}function Ez(_,T){if(_==null)return!1;if(T===!0)return typeof _[zJ]==="function";if(T===!1)return typeof _[FJ]==="function";return typeof _[zJ]==="function"||typeof _[FJ]==="function"}function s8(_){if(!_0(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!!(_.destroyed||_[CJ]||E!==null&&E!==void 0&&E.destroyed)}function IJ(_){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 Lz(_,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 Jz(_){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 PJ(_,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 jJ(_){if(_&&_[H6]!=null)return _[H6];if(typeof(_===null||_===void 0?void 0:_.readable)!=="boolean")return null;if(s8(_))return!1;return o8(_)&&_.readable&&!PJ(_)}function xJ(_){if(_&&_[Z6]!=null)return _[Z6];if(typeof(_===null||_===void 0?void 0:_.writable)!=="boolean")return null;if(s8(_))return!1;return r8(_)&&_.writable&&!IJ(_)}function Xz(_,T){if(!_0(_))return null;if(s8(_))return!0;if((T===null||T===void 0?void 0:T.readable)!==!1&&jJ(_))return!1;if((T===null||T===void 0?void 0:T.writable)!==!1&&xJ(_))return!1;return!0}function Hz(_){var T,A;if(!_0(_))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 Zz(_){var T,A;if(!_0(_))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 Yz(_){if(!_0(_))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"&&wJ(_))return _._closed;return null}function wJ(_){return typeof _._closed==="boolean"&&typeof _._defaultKeepAlive==="boolean"&&typeof _._removedConnection==="boolean"&&typeof _._removedContLen==="boolean"}function SJ(_){return typeof _._sent100==="boolean"&&wJ(_)}function Kz(_){var T;return typeof _._consuming==="boolean"&&typeof _._dumped==="boolean"&&((T=_.req)===null||T===void 0?void 0:T.upgradeOrConnect)===void 0}function $z(_){if(!_0(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!E&&SJ(_)||!!(E&&E.autoDestroy&&E.emitClose&&E.closed===!1)}function Gz(_){var T;return!!(_&&((T=_[RJ])!==null&&T!==void 0?T:_.readableDidRead||_.readableAborted))}function Uz(_){var T,A,E,L,J,X,H,Z,Y,K;return!!(_&&((T=(A=(E=(L=(J=(X=_[OJ])!==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))}yJ.exports={isDestroyed:s8,kIsDestroyed:CJ,isDisturbed:Gz,kIsDisturbed:RJ,isErrored:Uz,kIsErrored:OJ,isReadable:jJ,kIsReadable:H6,kIsClosedPromise:eV,kControllerErrorFunction:_z,kIsWritable:Z6,isClosed:Yz,isDuplexNodeStream:Tz,isFinished:Xz,isIterable:Ez,isReadableNodeStream:o8,isReadableStream:DJ,isReadableEnded:Jz,isReadableFinished:PJ,isReadableErrored:Zz,isNodeStream:_0,isWebStream:Az,isWritable:xJ,isWritableNodeStream:r8,isWritableStream:BJ,isWritableEnded:IJ,isWritableFinished:Lz,isWritableErrored:Hz,isServerRequest:Kz,isServerResponse:SJ,willEmitClose:$z,isTransformStream:qJ}});var q0=W((Mf,U6)=>{var p0=c0(),{AbortError:dJ,codes:Wz}=l_(),{ERR_INVALID_ARG_TYPE:Nz,ERR_STREAM_PREMATURE_CLOSE:vJ}=Wz,{kEmptyObject:K6,once:$6}=s_(),{validateAbortSignal:Qz,validateFunction:Mz,validateObject:Vz,validateBoolean:zz}=pT(),{Promise:Fz,PromisePrototypeThen:Cz,SymbolDispose:cJ}=z_(),{isClosed:Oz,isReadable:hJ,isReadableNodeStream:Y6,isReadableStream:Rz,isReadableFinished:kJ,isReadableErrored:fJ,isWritable:bJ,isWritableNodeStream:gJ,isWritableStream:Dz,isWritableFinished:mJ,isWritableErrored:uJ,isNodeStream:Bz,willEmitClose:qz,kIsClosedPromise:Iz}=T0(),lT;function Pz(_){return _.setHeader&&typeof _.abort==="function"}var G6=()=>{};function pJ(_,T,A){var E,L;if(arguments.length===2)A=T,T=K6;else if(T==null)T=K6;else Vz(T,"options");if(Mz(A,"callback"),Qz(T.signal,"options.signal"),A=$6(A),Rz(_)||Dz(_))return jz(_,T,A);if(!Bz(_))throw new Nz("stream",["ReadableStream","WritableStream","Stream"],_);let J=(E=T.readable)!==null&&E!==void 0?E:Y6(_),X=(L=T.writable)!==null&&L!==void 0?L:gJ(_),H=_._writableState,Z=_._readableState,Y=()=>{if(!_.writable)G()},K=qz(_)&&Y6(_)===J&&gJ(_)===X,$=mJ(_,!1),G=()=>{if($=!0,_.destroyed)K=!1;if(K&&(!_.readable||J))return;if(!J||U)A.call(_)},U=kJ(_,!1),V=()=>{if(U=!0,_.destroyed)K=!1;if(K&&(!_.writable||X))return;if(!X||$)A.call(_)},N=(f)=>{A.call(_,f)},z=Oz(_),Q=()=>{z=!0;let f=uJ(_)||fJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);if(J&&!U&&Y6(_,!0)){if(!kJ(_,!1))return A.call(_,new vJ)}if(X&&!$){if(!mJ(_,!1))return A.call(_,new vJ)}A.call(_)},F=()=>{z=!0;let f=uJ(_)||fJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);A.call(_)},R=()=>{_.req.on("finish",G)};if(Pz(_)){if(_.on("complete",G),!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",G),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||hJ(_))&&($||bJ(_)===!1))p0.nextTick(F);else if(!X&&(!K||bJ(_))&&(U||hJ(_)===!1))p0.nextTick(F);else if(Z&&_.req&&_.aborted)p0.nextTick(F);let q=()=>{if(A=G6,_.removeListener("aborted",Q),_.removeListener("complete",G),_.removeListener("abort",Q),_.removeListener("request",R),_.req)_.req.removeListener("finish",G);_.removeListener("end",Y),_.removeListener("close",Y),_.removeListener("finish",G),_.removeListener("end",V),_.removeListener("error",N),_.removeListener("close",Q)};if(T.signal&&!z){let f=()=>{let h=A;q(),h.call(_,new dJ(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=$6((...l)=>{h[cJ](),b.apply(_,l)})}}return q}function jz(_,T,A){let E=!1,L=G6;if(T.signal)if(L=()=>{E=!0,A.call(_,new dJ(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=$6((...Z)=>{X[cJ](),H.apply(_,Z)})}let J=(...X)=>{if(!E)p0.nextTick(()=>A.apply(_,X))};return Cz(_[Iz].promise,J,J),G6}function xz(_,T){var A;let E=!1;if(T===null)T=K6;if((A=T)!==null&&A!==void 0&&A.cleanup)zz(T.cleanup,"cleanup"),E=T.cleanup;return new Fz((L,J)=>{let X=pJ(_,T,(H)=>{if(E)X();if(H)J(H);else L()})})}U6.exports=pJ;U6.exports.finished=xz});var GT=W((Vf,tJ)=>{var A0=c0(),{aggregateTwoErrors:wz,codes:{ERR_MULTIPLE_CALLBACK:Sz},AbortError:yz}=l_(),{Symbol:iJ}=z_(),{kIsDestroyed:vz,isDestroyed:hz,isFinished:kz,isServerRequest:fz}=T0(),aJ=iJ("kDestroy"),W6=iJ("kConstruct");function oJ(_,T,A){if(_){if(_.stack,T&&!T.errored)T.errored=_;if(A&&!A.errored)A.errored=_}}function bz(_,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(oJ(_,E,A),E)E.destroyed=!0;if(A)A.destroyed=!0;if(!L.constructed)this.once(aJ,function(J){lJ(this,wz(J,_),T)});else lJ(this,_,T);return this}function lJ(_,T,A){let E=!1;function L(J){if(E)return;E=!0;let{_readableState:X,_writableState:H}=_;if(oJ(J,H,X),H)H.closed=!0;if(X)X.closed=!0;if(typeof A==="function")A(J);if(J)A0.nextTick(gz,_,J);else A0.nextTick(rJ,_)}try{_._destroy(T||null,L)}catch(J){L(J)}}function gz(_,T){N6(_,T),rJ(_)}function rJ(_){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 N6(_,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 mz(){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 Q6(_,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)A0.nextTick(N6,_,T);else N6(_,T)}}function uz(_,T){if(typeof _._construct!=="function")return;let{_readableState:A,_writableState:E}=_;if(A)A.constructed=!1;if(E)E.constructed=!1;if(_.once(W6,T),_.listenerCount(W6)>1)return;A0.nextTick(dz,_)}function dz(_){let T=!1;function A(E){if(T){Q6(_,E!==null&&E!==void 0?E:new Sz);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(aJ,E);else if(E)Q6(_,E,!0);else A0.nextTick(cz,_)}try{_._construct((E)=>{A0.nextTick(A,E)})}catch(E){A0.nextTick(A,E)}}function cz(_){_.emit(W6)}function nJ(_){return(_===null||_===void 0?void 0:_.setHeader)&&typeof _.abort==="function"}function sJ(_){_.emit("close")}function pz(_,T){_.emit("error",T),A0.nextTick(sJ,_)}function lz(_,T){if(!_||hz(_))return;if(!T&&!kz(_))T=new yz;if(fz(_))_.socket=null,_.destroy(T);else if(nJ(_))_.abort();else if(nJ(_.req))_.req.abort();else if(typeof _.destroy==="function")_.destroy(T);else if(typeof _.close==="function")_.close();else if(T)A0.nextTick(pz,_,T);else A0.nextTick(sJ,_);if(!_.destroyed)_[vz]=!0}tJ.exports={construct:uz,destroyer:lz,destroy:bz,undestroy:mz,errorOrDestroy:Q6}});var _A=W((zf,_X)=>{var{ArrayIsArray:nz,ObjectSetPrototypeOf:eJ}=z_(),{EventEmitter:t8}=I("events");function e8(_){t8.call(this,_)}eJ(e8.prototype,t8.prototype);eJ(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)}M6(A,"error",Z),M6(_,"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 M6(_,T,A){if(typeof _.prependListener==="function")return _.prependListener(T,A);if(!_._events||!_._events[T])_.on(T,A);else if(nz(_._events[T]))_._events[T].unshift(A);else _._events[T]=[A,_._events[T]]}_X.exports={Stream:e8,prependListener:M6}});var w4=W((ez,TA)=>{var{SymbolDispose:iz}=z_(),{AbortError:TX,codes:az}=l_(),{isNodeStream:AX,isWebStream:oz,kControllerErrorFunction:rz}=T0(),sz=q0(),{ERR_INVALID_ARG_TYPE:EX}=az,V6,tz=(_,T)=>{if(typeof _!=="object"||!("aborted"in _))throw new EX(T,"AbortSignal",_)};ez.addAbortSignal=function(T,A){if(tz(T,"signal"),!AX(A)&&!oz(A))throw new EX("stream",["ReadableStream","WritableStream","Stream"],A);return ez.addAbortSignalNoValidate(T,A)};ez.addAbortSignalNoValidate=function(_,T){if(typeof _!=="object"||!("aborted"in _))return T;let A=AX(T)?()=>{T.destroy(new TX(void 0,{cause:_.reason}))}:()=>{T[rz](new TX(void 0,{cause:_.reason}))};if(_.aborted)A();else{V6=V6||s_().addAbortListener;let E=V6(_,A);sz(T,E[iz])}return T}});var XX=W((Ff,JX)=>{var{StringPrototypeSlice:LX,SymbolIterator:AF,TypedArrayPrototypeSet:AA,Uint8Array:EF}=z_(),{Buffer:z6}=I("buffer"),{inspect:LF}=s_();JX.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 z6.alloc(0);let A=z6.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}*[AF](){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+=LX(J,0,T),this.head=E,E.data=LX(J,T);break}++L}while((E=E.next)!==null);return this.length-=L,A}_getBuffer(T){let A=z6.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 EF(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 LF(this,{...A,depth:0,customInspect:!1})}}});var S4=W((Cf,KX)=>{var{MathFloor:JF,NumberIsInteger:XF}=z_(),{validateInteger:HF}=pT(),{ERR_INVALID_ARG_VALUE:ZF}=l_().codes,HX=16384,ZX=16;function YF(_,T,A){return _.highWaterMark!=null?_.highWaterMark:T?_[A]:null}function YX(_){return _?ZX:HX}function KF(_,T){if(HF(T,"value",0),_)ZX=T;else HX=T}function $F(_,T,A,E){let L=YF(T,E,A);if(L!=null){if(!XF(L)||L<0){let J=E?`options.${A}`:"options.highWaterMark";throw new ZF(J,L)}return JF(L)}return YX(_.objectMode)}KX.exports={getHighWaterMark:$F,getDefaultHighWaterMark:YX,setDefaultHighWaterMark:KF}});var UX=W((F6,GX)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var EA=I("buffer"),E0=EA.Buffer;function $X(_,T){for(var A in _)T[A]=_[A]}if(E0.from&&E0.alloc&&E0.allocUnsafe&&E0.allocUnsafeSlow)GX.exports=EA;else $X(EA,F6),F6.Buffer=UT;function UT(_,T,A){return E0(_,T,A)}UT.prototype=Object.create(E0.prototype);$X(E0,UT);UT.from=function(_,T,A){if(typeof _==="number")throw TypeError("Argument must not be a number");return E0(_,T,A)};UT.alloc=function(_,T,A){if(typeof _!=="number")throw TypeError("Argument must be a number");var E=E0(_);if(T!==void 0)if(typeof A==="string")E.fill(T,A);else E.fill(T);else E.fill(0);return E};UT.allocUnsafe=function(_){if(typeof _!=="number")throw TypeError("Argument must be a number");return E0(_)};UT.allocUnsafeSlow=function(_){if(typeof _!=="number")throw TypeError("Argument must be a number");return EA.SlowBuffer(_)}});var NX=W((BF)=>{var O6=UX().Buffer,WX=O6.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 GF(_){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 UF(_){var T=GF(_);if(typeof T!=="string"&&(O6.isEncoding===WX||!WX(_)))throw Error("Unknown encoding: "+_);return T||_}BF.StringDecoder=y4;function y4(_){this.encoding=UF(_);var T;switch(this.encoding){case"utf16le":this.text=zF,this.end=FF,T=4;break;case"utf8":this.fillLast=QF,T=4;break;case"base64":this.text=CF,this.end=OF,T=3;break;default:this.write=RF,this.end=DF;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=O6.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=VF;y4.prototype.text=MF;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 C6(_){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 WF(_,T,A){var E=T.length-1;if(E<A)return 0;var L=C6(T[E]);if(L>=0){if(L>0)_.lastNeed=L-1;return L}if(--E<A||L===-2)return 0;if(L=C6(T[E]),L>=0){if(L>0)_.lastNeed=L-2;return L}if(--E<A||L===-2)return 0;if(L=C6(T[E]),L>=0){if(L>0)if(L===2)L=0;else _.lastNeed=L-3;return L}return 0}function NF(_,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 QF(_){var T=this.lastTotal-this.lastNeed,A=NF(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 MF(_,T){var A=WF(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 VF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+"\uFFFD";return T}function zF(_,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 FF(_){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 CF(_,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 OF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+this.lastChar.toString("base64",0,3-this.lastNeed);return T}function RF(_){return _.toString(this.encoding)}function DF(_){return _&&_.length?this.write(_):""}});var R6=W((Rf,zX)=>{var QX=c0(),{PromisePrototypeThen:IF,SymbolAsyncIterator:MX,SymbolIterator:VX}=z_(),{Buffer:PF}=I("buffer"),{ERR_INVALID_ARG_TYPE:jF,ERR_STREAM_NULL_VALUES:xF}=l_().codes;function wF(_,T,A){let E;if(typeof T==="string"||T instanceof PF)return new _({objectMode:!0,...A,read(){this.push(T),this.push(null)}});let L;if(T&&T[MX])L=!0,E=T[MX]();else if(T&&T[VX])L=!1,E=T[VX]();else throw new jF("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){IF(H(Y),()=>QX.nextTick(K,Y),($)=>QX.nextTick(K,$||Y))};async function H(Y){let K=Y!==void 0&&Y!==null,$=typeof E.throw==="function";if(K&&$){let{value:G,done:U}=await E.throw(Y);if(await G,U)return}if(typeof E.return==="function"){let{value:G}=await E.return();await G}}async function Z(){for(;;){try{let{value:Y,done:K}=L?await E.next():E.next();if(K)J.push(null);else{let $=Y&&typeof Y.then==="function"?await Y:Y;if($===null)throw X=!1,new xF;else if(J.push($))continue;else X=!1}}catch(Y){J.destroy(Y)}break}}return J}zX.exports=wF});var h4=W((Df,fX)=>{var g1=c0(),{ArrayPrototypeIndexOf:SF,NumberIsInteger:yF,NumberIsNaN:vF,NumberParseInt:hF,ObjectDefineProperties:w6,ObjectKeys:kF,ObjectSetPrototypeOf:OX,Promise:RX,SafeSet:fF,SymbolAsyncDispose:bF,SymbolAsyncIterator:gF,Symbol:mF}=z_();fX.exports=s;s.ReadableState=HA;var{EventEmitter:uF}=I("events"),{Stream:l0,prependListener:dF}=_A(),{Buffer:D6}=I("buffer"),{addAbortSignal:cF}=w4(),DX=q0(),A_=s_().debuglog("stream",(_)=>{A_=_}),pF=XX(),aT=GT(),{getHighWaterMark:lF,getDefaultHighWaterMark:nF}=S4(),{aggregateTwoErrors:FX,codes:{ERR_INVALID_ARG_TYPE:iF,ERR_METHOD_NOT_IMPLEMENTED:aF,ERR_OUT_OF_RANGE:oF,ERR_STREAM_PUSH_AFTER_EOF:rF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:sF},AbortError:tF}=l_(),{validateObject:eF}=pT(),WT=mF("kPaused"),{StringDecoder:BX}=NX(),_C=R6();OX(s.prototype,l0.prototype);OX(s,l0);var B6=()=>{},{errorOrDestroy:nT}=aT,iT=1,TC=2,qX=4,v4=8,IX=16,LA=32,JA=64,PX=128,AC=256,EC=512,LC=1024,j6=2048,x6=4096,JC=8192,XC=16384,HC=32768,jX=65536,ZC=131072,YC=262144;function w_(_){return{enumerable:!1,get(){return(this.state&_)!==0},set(T){if(T)this.state|=_;else this.state&=~_}}}w6(HA.prototype,{objectMode:w_(iT),ended:w_(TC),endEmitted:w_(qX),reading:w_(v4),constructed:w_(IX),sync:w_(LA),needReadable:w_(JA),emittedReadable:w_(PX),readableListening:w_(AC),resumeScheduled:w_(EC),errorEmitted:w_(LC),emitClose:w_(j6),autoDestroy:w_(x6),destroyed:w_(JC),closed:w_(XC),closeEmitted:w_(HC),multiAwaitDrain:w_(jX),readingMore:w_(ZC),dataEmitted:w_(YC)});function HA(_,T,A){if(typeof A!=="boolean")A=T instanceof L0();if(this.state=j6|x6|IX|LA,_&&_.objectMode)this.state|=iT;if(A&&_&&_.readableObjectMode)this.state|=iT;if(this.highWaterMark=_?lF(this,_,"readableHighWaterMark",A):nF(!1),this.buffer=new pF,this.length=0,this.pipes=[],this.flowing=null,this[WT]=null,_&&_.emitClose===!1)this.state&=~j6;if(_&&_.autoDestroy===!1)this.state&=~x6;if(this.errored=null,this.defaultEncoding=_&&_.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,_&&_.encoding)this.decoder=new BX(_.encoding),this.encoding=_.encoding}function s(_){if(!(this instanceof s))return new s(_);let T=this instanceof L0();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)cF(_.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[uF.captureRejectionSymbol]=function(_){this.destroy(_)};s.prototype[bF]=function(){let _;if(!this.destroyed)_=this.readableEnded?null:new tF,this.destroy(_);return new RX((T,A)=>DX(this,(E)=>E&&E!==_?A(E):T(null)))};s.prototype.push=function(_,T){return xX(this,_,T,!1)};s.prototype.unshift=function(_,T){return xX(this,_,T,!0)};function xX(_,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=D6.from(T,A).toString(L.encoding);else T=D6.from(T,A),A=""}else if(T instanceof D6)A="";else if(l0._isUint8Array(T))T=l0._uint8ArrayToBuffer(T),A="";else if(T!=null)J=new iF("chunk",["string","Buffer","Uint8Array"],T)}if(J)nT(_,J);else if(T===null)L.state&=~v4,GC(_,L);else if((L.state&iT)!==0||T&&T.length>0)if(E)if((L.state&qX)!==0)nT(_,new sF);else if(L.destroyed||L.errored)return!1;else q6(_,L,T,!0);else if(L.ended)nT(_,new rF);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)q6(_,L,T,!1);else XA(_,L);else q6(_,L,T,!1);else if(!E)L.state&=~v4,XA(_,L);return!L.ended&&(L.length<L.highWaterMark||L.length===0)}function q6(_,T,A,E){if(T.flowing&&T.length===0&&!T.sync&&_.listenerCount("data")>0){if((T.state&jX)!==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 _[WT]===!0||_.flowing===!1};s.prototype.setEncoding=function(_){let T=new BX(_);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 KC=1073741824;function $C(_){if(_>KC)throw new oF("size","<= 1GiB",_);else _--,_|=_>>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++;return _}function CX(_,T){if(_<=0||T.length===0&&T.ended)return 0;if((T.state&iT)!==0)return 1;if(vF(_)){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(!yF(_))_=hF(_,10);let T=this._readableState,A=_;if(_>T.highWaterMark)T.highWaterMark=$C(_);if(_!==0)T.state&=~PX;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)I6(this);else ZA(this);return null}if(_=CX(_,T),_===0&&T.ended){if(T.length===0)I6(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)_=CX(A,T)}let L;if(_>0)L=hX(_,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)I6(this)}if(L!==null&&!T.errorEmitted&&!T.closeEmitted)T.dataEmitted=!0,this.emit("data",L);return L};function GC(_,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,wX(_)}function ZA(_){let T=_._readableState;if(A_("emitReadable",T.needReadable,T.emittedReadable),T.needReadable=!1,!T.emittedReadable)A_("emitReadable",T.flowing),T.emittedReadable=!0,g1.nextTick(wX,_)}function wX(_){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,yX(_)}function XA(_,T){if(!T.readingMore&&T.constructed)T.readingMore=!0,g1.nextTick(UC,_,T)}function UC(_,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 aF("_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 fF(E.awaitDrainWriters?[E.awaitDrainWriters]:[])}E.pipes.push(_),A_("pipe count=%d opts=%j",E.pipes.length,T);let J=(!T||T.end!==!1)&&_!==g1.stdout&&_!==g1.stderr?H:z;if(E.endEmitted)g1.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",G),Y=!0,Z&&E.awaitDrainWriters&&(!_._writableState||_._writableState.needDrain))Z()}function $(){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=WC(A,_),_.on("drain",Z)}A.on("data",G);function G(Q){A_("ondata");let F=_.write(Q);if(A_("dest.write",F),F===!1)$()}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)}}dF(_,"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)$();else if(!E.flowing)A_("pipe resume"),A.resume();return _};function WC(_,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=SF(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)g1.nextTick(NC,this)}}return A};s.prototype.addListener=s.prototype.on;s.prototype.removeListener=function(_,T){let A=l0.prototype.removeListener.call(this,_,T);if(_==="readable")g1.nextTick(SX,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)g1.nextTick(SX,this);return T};function SX(_){let T=_._readableState;if(T.readableListening=_.listenerCount("readable")>0,T.resumeScheduled&&T[WT]===!1)T.flowing=!0;else if(_.listenerCount("data")>0)_.resume();else if(!T.readableListening)T.flowing=null}function NC(_){A_("readable nexttick read 0"),_.read(0)}s.prototype.resume=function(){let _=this._readableState;if(!_.flowing)A_("resume"),_.flowing=!_.readableListening,QC(this,_);return _[WT]=!1,this};function QC(_,T){if(!T.resumeScheduled)T.resumeScheduled=!0,g1.nextTick(MC,_,T)}function MC(_,T){if(A_("resume",T.reading),!T.reading)_.read(0);if(T.resumeScheduled=!1,_.emit("resume"),yX(_),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[WT]=!0,this};function yX(_){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=kF(_);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[gF]=function(){return vX(this)};s.prototype.iterator=function(_){if(_!==void 0)eF(_,"options");return vX(this,_)};function vX(_,T){if(typeof _.read!=="function")_=s.wrap(_,{objectMode:!0});let A=VC(_,T);return A.stream=_,A}async function*VC(_,T){let A=B6;function E(X){if(this===_)A(),A=B6;else A=X}_.on("readable",E);let L,J=DX(_,{writable:!1},(X)=>{L=X?FX(L,X):null,A(),A=B6});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 RX(E)}}catch(X){throw L=FX(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()}}w6(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}}});w6(HA.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[WT]!==!1},set(_){this[WT]=!!_}}});s._fromList=hX;function hX(_,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 I6(_){let T=_._readableState;if(A_("endReadable",T.endEmitted),!T.endEmitted)T.ended=!0,g1.nextTick(zC,T,_)}function zC(_,T){if(A_("endReadableNT",_.endEmitted,_.length),!_.errored&&!_.closeEmitted&&!_.endEmitted&&_.length===0){if(_.endEmitted=!0,T.emit("end"),T.writable&&T.allowHalfOpen===!1)g1.nextTick(FC,T);else if(_.autoDestroy){let A=T._writableState;if(!A||A.autoDestroy&&(A.finished||A.writable===!1))T.destroy()}}}function FC(_){if(_.writable&&!_.writableEnded&&!_.destroyed)_.end()}s.from=function(_,T){return _C(s,_,T)};var P6;function kX(){if(P6===void 0)P6={};return P6}s.fromWeb=function(_,T){return kX().newStreamReadableFromReadableStream(_,T)};s.toWeb=function(_,T){return kX().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((Bf,oX)=>{var NT=c0(),{ArrayPrototypeSlice:mX,Error:CC,FunctionPrototypeSymbolHasInstance:uX,ObjectDefineProperty:dX,ObjectDefineProperties:OC,ObjectSetPrototypeOf:cX,StringPrototypeToLowerCase:RC,Symbol:DC,SymbolHasInstance:BC}=z_();oX.exports=O_;O_.WritableState=b4;var{EventEmitter:qC}=I("events"),k4=_A().Stream,{Buffer:YA}=I("buffer"),GA=GT(),{addAbortSignal:IC}=w4(),{getHighWaterMark:PC,getDefaultHighWaterMark:jC}=S4(),{ERR_INVALID_ARG_TYPE:xC,ERR_METHOD_NOT_IMPLEMENTED:wC,ERR_MULTIPLE_CALLBACK:pX,ERR_STREAM_CANNOT_PIPE:SC,ERR_STREAM_DESTROYED:f4,ERR_STREAM_ALREADY_FINISHED:yC,ERR_STREAM_NULL_VALUES:vC,ERR_STREAM_WRITE_AFTER_END:hC,ERR_UNKNOWN_ENCODING:lX}=l_().codes,{errorOrDestroy:oT}=GA;cX(O_.prototype,k4.prototype);cX(O_,k4);function v6(){}var rT=DC("kOnFinished");function b4(_,T,A){if(typeof A!=="boolean")A=T instanceof L0();if(this.objectMode=!!(_&&_.objectMode),A)this.objectMode=this.objectMode||!!(_&&_.writableObjectMode);this.highWaterMark=_?PC(this,_,"writableHighWaterMark",A):jC(!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=fC.bind(void 0,T),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,$A(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 $A(_){_.buffered=[],_.bufferedIndex=0,_.allBuffers=!0,_.allNoop=!0}b4.prototype.getBuffer=function(){return mX(this.buffered,this.bufferedIndex)};dX(b4.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function O_(_){let T=this instanceof L0();if(!T&&!uX(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)IC(_.signal,this)}k4.call(this,_),GA.construct(this,()=>{let A=this._writableState;if(!A.writing)k6(this,A);f6(this,A)})}dX(O_,BC,{__proto__:null,value:function(_){if(uX(this,_))return!0;if(this!==O_)return!1;return _&&_._writableState instanceof b4}});O_.prototype.pipe=function(){oT(this,new SC)};function nX(_,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 lX(A);if(typeof E!=="function")E=v6}if(T===null)throw new vC;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 xC("chunk",["string","Buffer","Uint8Array"],T);let J;if(L.ending)J=new hC;else if(L.destroyed)J=new f4("write");if(J)return NT.nextTick(E,J),oT(_,J,!0),J;return L.pendingcb++,kC(_,L,T,A,E)}O_.prototype.write=function(_,T,A){return nX(this,_,T,A)===!0};O_.prototype.cork=function(){this._writableState.corked++};O_.prototype.uncork=function(){let _=this._writableState;if(_.corked){if(_.corked--,!_.writing)k6(this,_)}};O_.prototype.setDefaultEncoding=function(T){if(typeof T==="string")T=RC(T);if(!YA.isEncoding(T))throw new lX(T);return this._writableState.defaultEncoding=T,this};function kC(_,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!==v6)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 bX(_,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 gX(_,T,A,E){--T.pendingcb,E(A),h6(T),oT(_,A)}function fC(_,T){let A=_._writableState,E=A.sync,L=A.writecb;if(typeof L!=="function"){oT(_,new pX);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)NT.nextTick(gX,_,A,T,L);else gX(_,A,T,L)}else{if(A.buffered.length>A.bufferedIndex)k6(_,A);if(E)if(A.afterWriteTickInfo!==null&&A.afterWriteTickInfo.cb===L)A.afterWriteTickInfo.count++;else A.afterWriteTickInfo={count:1,cb:L,stream:_,state:A},NT.nextTick(bC,A.afterWriteTickInfo);else iX(_,A,1,L)}}function bC({stream:_,state:T,count:A,cb:E}){return T.afterWriteTickInfo=null,iX(_,T,A,E)}function iX(_,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)h6(T);f6(_,T)}function h6(_){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"))}$A(_)}function k6(_,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?v6:(Y)=>{for(let K=X;K<A.length;++K)A[K].callback(Y)},Z=T.allNoop&&X===0?A:mX(A,X);Z.allBuffers=T.allBuffers,bX(_,T,!0,T.length,Z,"",H),$A(T)}else{do{let{chunk:H,encoding:Z,callback:Y}=A[X];A[X++]=null;let K=L?1:H.length;bX(_,T,!1,K,H,Z,Y)}while(X<A.length&&!T.writing);if(X===A.length)$A(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 wC("_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=nX(this,_,T);if(J instanceof CC)L=J}if(E.corked)E.corked=1,this.uncork();if(L);else if(!E.errored&&!E.ending)E.ending=!0,f6(this,E,!0),E.ended=!0;else if(E.finished)L=new yC("end");else if(E.destroyed)L=new f4("end");if(typeof A==="function")if(L||E.finished)NT.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 gC(_,T){let A=!1;function E(L){if(A){oT(_,L!==null&&L!==void 0?L:pX());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++,NT.nextTick(y6,_,T)}T.sync=!0,T.pendingcb++;try{_._final(E)}catch(L){E(L)}T.sync=!1}function mC(_,T){if(!T.prefinished&&!T.finalCalled)if(typeof _._final==="function"&&!T.destroyed)T.finalCalled=!0,gC(_,T);else T.prefinished=!0,_.emit("prefinish")}function f6(_,T,A){if(KA(T)){if(mC(_,T),T.pendingcb===0){if(A)T.pendingcb++,NT.nextTick((E,L)=>{if(KA(L))y6(E,L);else L.pendingcb--},_,T);else if(KA(T))T.pendingcb++,y6(_,T)}}}function y6(_,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()}}OC(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 uC=GA.destroy;O_.prototype.destroy=function(_,T){let A=this._writableState;if(!A.destroyed&&(A.bufferedIndex<A.buffered.length||A[rT].length))NT.nextTick(h6,A);return uC.call(this,_,T),this};O_.prototype._undestroy=GA.undestroy;O_.prototype._destroy=function(_,T){T(_)};O_.prototype[qC.captureRejectionSymbol]=function(_){this.destroy(_)};var S6;function aX(){if(S6===void 0)S6={};return S6}O_.fromWeb=function(_,T){return aX().newStreamWritableFromWritableStream(_,T)};O_.toWeb=function(_){return aX().newWritableStreamFromStreamWritable(_)}});var KH=W((qf,YH)=>{var b6=c0(),dC=I("buffer"),{isReadable:cC,isWritable:pC,isIterable:rX,isNodeStream:lC,isReadableNodeStream:sX,isWritableNodeStream:tX,isDuplexNodeStream:nC,isReadableStream:eX,isWritableStream:_H}=T0(),TH=q0(),{AbortError:HH,codes:{ERR_INVALID_ARG_TYPE:iC,ERR_INVALID_RETURN_VALUE:AH}}=l_(),{destroyer:tT}=GT(),aC=L0(),ZH=h4(),oC=UA(),{createDeferredPromise:EH}=s_(),LH=R6(),JH=globalThis.Blob||dC.Blob,rC=typeof JH<"u"?function(T){return T instanceof JH}:function(T){return!1},sC=globalThis.AbortController||I("abort-controller").AbortController,{FunctionPrototypeCall:XH}=z_();class QT extends aC{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}}YH.exports=function _(T,A){if(nC(T))return T;if(sX(T))return sT({readable:T});if(tX(T))return sT({writable:T});if(lC(T))return sT({writable:!1,readable:!1});if(eX(T))return sT({readable:ZH.fromWeb(T)});if(_H(T))return sT({writable:oC.fromWeb(T)});if(typeof T==="function"){let{value:L,write:J,final:X,destroy:H}=tC(T);if(rX(L))return LH(QT,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=XH(Z,L,($)=>{if($!=null)throw new AH("nully","body",$)},($)=>{tT(Y,$)});return Y=new QT({objectMode:!0,readable:!1,write:J,final($){X(async()=>{try{await K,b6.nextTick($,null)}catch(G){b6.nextTick($,G)}})},destroy:H})}throw new AH("Iterable, AsyncIterable or AsyncFunction",A,L)}if(rC(T))return _(T.arrayBuffer());if(rX(T))return LH(QT,T,{objectMode:!0,writable:!1});if(eX(T===null||T===void 0?void 0:T.readable)&&_H(T===null||T===void 0?void 0:T.writable))return QT.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?sX(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?tX(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 XH(E,T,(J)=>{if(J!=null)L.push(J);L.push(null)},(J)=>{tT(L,J)}),L=new QT({objectMode:!0,writable:!1,read(){}})}throw new iC(A,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],T)};function tC(_){let{promise:T,resolve:A}=EH(),E=new sC,L=E.signal;return{value:_(async function*(){while(!0){let X=T;T=null;let{chunk:H,done:Z,cb:Y}=await X;if(b6.nextTick(Y),Z)return;if(L.aborted)throw new HH(void 0,{cause:L.reason});({promise:T,resolve:A}=EH()),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"?ZH.wrap(_.readable):_.readable,A=_.writable,E=!!cC(T),L=!!pC(A),J,X,H,Z,Y;function K($){let G=Z;if(Z=null,G)G($);else if($)Y.destroy($)}if(Y=new QT({readableObjectMode:!!(T!==null&&T!==void 0&&T.readableObjectMode),writableObjectMode:!!(A!==null&&A!==void 0&&A.writableObjectMode),readable:E,writable:L}),L)TH(A,($)=>{if(L=!1,$)tT(T,$);K($)}),Y._write=function($,G,U){if(A.write($,G))U();else J=U},Y._final=function($){A.end(),X=$},A.on("drain",function(){if(J){let $=J;J=null,$()}}),A.on("finish",function(){if(X){let $=X;X=null,$()}});if(E)TH(T,($)=>{if(E=!1,$)tT(T,$);K($)}),T.on("readable",function(){if(H){let $=H;H=null,$()}}),T.on("end",function(){Y.push(null)}),Y._read=function(){while(!0){let $=T.read();if($===null){H=Y._read;return}if(!Y.push($))return}};return Y._destroy=function($,G){if(!$&&Z!==null)$=new HH;if(H=null,J=null,X=null,Z===null)G($);else Z=G,tT(A,$),tT(T,$)},Y}});var L0=W((If,UH)=>{var{ObjectDefineProperties:eC,ObjectGetOwnPropertyDescriptor:I0,ObjectKeys:_O,ObjectSetPrototypeOf:$H}=z_();UH.exports=m1;var u6=h4(),O1=UA();$H(m1.prototype,u6.prototype);$H(m1,u6);{let _=_O(O1.prototype);for(let T=0;T<_.length;T++){let A=_[T];if(!m1.prototype[A])m1.prototype[A]=O1.prototype[A]}}function m1(_){if(!(this instanceof m1))return new m1(_);if(u6.call(this,_),O1.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}eC(m1.prototype,{writable:{__proto__:null,...I0(O1.prototype,"writable")},writableHighWaterMark:{__proto__:null,...I0(O1.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...I0(O1.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...I0(O1.prototype,"writableBuffer")},writableLength:{__proto__:null,...I0(O1.prototype,"writableLength")},writableFinished:{__proto__:null,...I0(O1.prototype,"writableFinished")},writableCorked:{__proto__:null,...I0(O1.prototype,"writableCorked")},writableEnded:{__proto__:null,...I0(O1.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...I0(O1.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 g6;function GH(){if(g6===void 0)g6={};return g6}m1.fromWeb=function(_,T){return GH().newStreamDuplexFromReadableWritablePair(_,T)};m1.toWeb=function(_){return GH().newReadableWritablePairFromDuplex(_)};var m6;m1.from=function(_){if(!m6)m6=KH();return m6(_,"body")}});var p6=W((Pf,NH)=>{var{ObjectSetPrototypeOf:WH,Symbol:TO}=z_();NH.exports=P0;var{ERR_METHOD_NOT_IMPLEMENTED:AO}=l_().codes,c6=L0(),{getHighWaterMark:EO}=S4();WH(P0.prototype,c6.prototype);WH(P0,c6);var g4=TO("kCallback");function P0(_){if(!(this instanceof P0))return new P0(_);let T=_?EO(this,_,"readableHighWaterMark",!0):null;if(T===0)_={..._,highWaterMark:null,readableHighWaterMark:T,writableHighWaterMark:_.writableHighWaterMark||0};if(c6.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",LO)}function d6(_){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 LO(){if(this._final!==d6)d6.call(this)}P0.prototype._final=d6;P0.prototype._transform=function(_,T,A){throw new AO("_transform()")};P0.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})};P0.prototype._read=function(){if(this[g4]){let _=this[g4];this[g4]=null,_()}}});var n6=W((jf,MH)=>{var{ObjectSetPrototypeOf:QH}=z_();MH.exports=eT;var l6=p6();QH(eT.prototype,l6.prototype);QH(eT,l6);function eT(_){if(!(this instanceof eT))return new eT(_);l6.call(this,_)}eT.prototype._transform=function(_,T,A){A(null,_)}});var MA=W((xf,OH)=>{var m4=c0(),{ArrayIsArray:JO,Promise:XO,SymbolAsyncIterator:HO,SymbolDispose:ZO}=z_(),QA=q0(),{once:YO}=s_(),KO=GT(),VH=L0(),{aggregateTwoErrors:$O,codes:{ERR_INVALID_ARG_TYPE:TE,ERR_INVALID_RETURN_VALUE:i6,ERR_MISSING_ARGS:GO,ERR_STREAM_DESTROYED:UO,ERR_STREAM_PREMATURE_CLOSE:WO},AbortError:NO}=l_(),{validateFunction:QO,validateAbortSignal:MO}=pT(),{isIterable:MT,isReadable:a6,isReadableNodeStream:NA,isNodeStream:zH,isTransformStream:_4,isWebStream:VO,isReadableStream:o6,isReadableFinished:zO}=T0(),FO=globalThis.AbortController||I("abort-controller").AbortController,r6,s6,t6;function FH(_,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,KO.destroyer(_,J||new UO("pipe"))},cleanup:L}}function CO(_){return QO(_[_.length-1],"streams[stream.length - 1]"),_.pop()}function e6(_){if(MT(_))return _;else if(NA(_))return OO(_);throw new TE("val",["Readable","Iterable","AsyncIterable"],_)}async function*OO(_){if(!s6)s6=h4();yield*s6.prototype[HO].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 XO((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?$O(L,Y):Y)}finally{Z(),T.off("drain",X)}}async function _E(_,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 RO(..._){return CH(_,YO(CO(_)))}function CH(_,T,A){if(_.length===1&&JO(_[0]))_=_[0];if(_.length<2)throw new GO("streams");let E=new FO,L=E.signal,J=A===null||A===void 0?void 0:A.signal,X=[];MO(J,"options.signal");function H(){V(new NO)}t6=t6||s_().addAbortListener;let Z;if(J)Z=t6(J,H);let Y,K,$=[],G=0;function U(R){V(R,--G===0)}function V(R,q){var f;if(R&&(!Y||Y.code==="ERR_STREAM_PREMATURE_CLOSE"))Y=R;if(!Y&&!q)return;while($.length)$.shift()(Y);if((f=Z)===null||f===void 0||f[ZO](),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(zH(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_}=FH(q,f,h);if($.push(W_),a6(q)&&l)X.push(c_)}if(q.on("error",c),a6(q)&&l)X.push(()=>{q.removeListener("error",c)})}if(R===0)if(typeof q==="function"){if(N=q({signal:L}),!MT(N))throw new i6("Iterable, AsyncIterable or Stream","source",N)}else if(MT(q)||NA(q)||_4(q))N=q;else N=VH.from(q);else if(typeof q==="function"){if(_4(N)){var z;N=e6((z=N)===null||z===void 0?void 0:z.readable)}else N=e6(N);if(N=q(N,{signal:L}),f){if(!MT(N,!0))throw new i6("AsyncIterable",`transform[${R-1}]`,N)}else{var Q;if(!r6)r6=n6();let c=new r6({objectMode:!0}),W_=(Q=N)===null||Q===void 0?void 0:Q.then;if(typeof W_==="function")G++,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(MT(N,!0))G++,WA(N,c,U,{end:b});else if(o6(N)||_4(N)){let C_=N.readable||N;G++,WA(C_,c,U,{end:b})}else throw new i6("AsyncIterable or Promise","destination",N);N=c;let{destroy:c_,cleanup:B_}=FH(N,!1,!0);if($.push(c_),l)X.push(B_)}}else if(zH(q)){if(NA(N)){G+=2;let c=DO(N,q,U,{end:b});if(a6(q)&&l)X.push(c)}else if(_4(N)||o6(N)){let c=N.readable||N;G++,WA(c,q,U,{end:b})}else if(MT(N))G++,WA(N,q,U,{end:b});else throw new TE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else if(VO(q)){if(NA(N))G++,_E(e6(N),q,U,{end:b});else if(o6(N)||MT(N))G++,_E(N,q,U,{end:b});else if(_4(N))G++,_E(N.readable,q,U,{end:b});else throw new TE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else N=VH.from(q)}if(L!==null&&L!==void 0&&L.aborted||J!==null&&J!==void 0&&J.aborted)m4.nextTick(H);return N}function DO(_,T,A,{end:E}){let L=!1;if(T.on("close",()=>{if(!L)A(new WO)}),_.pipe(T,{end:!1}),E){let X=function(){L=!0,T.end()};var J=X;if(zO(_))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)}OH.exports={pipelineImpl:CH,pipeline:RO}});var EE=W((wf,PH)=>{var{pipeline:BO}=MA(),VA=L0(),{destroyer:qO}=GT(),{isNodeStream:zA,isReadable:RH,isWritable:DH,isWebStream:AE,isTransformStream:VT,isWritableStream:BH,isReadableStream:qH}=T0(),{AbortError:IO,codes:{ERR_INVALID_ARG_VALUE:IH,ERR_MISSING_ARGS:PO}}=l_(),jO=q0();PH.exports=function(...T){if(T.length===0)throw new PO("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])&&!AE(T[U]))continue;if(U<T.length-1&&!(RH(T[U])||qH(T[U])||VT(T[U])))throw new IH(`streams[${U}]`,A[U],"must be readable");if(U>0&&!(DH(T[U])||BH(T[U])||VT(T[U])))throw new IH(`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=BO(T,Z),$=!!(DH(Y)||BH(Y)||VT(Y)),G=!!(RH(K)||qH(K)||VT(K));if(H=new VA({writableObjectMode:!!(Y!==null&&Y!==void 0&&Y.writableObjectMode),readableObjectMode:!!(K!==null&&K!==void 0&&K.readableObjectMode),writable:$,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(AE(Y)){let N=(VT(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=VT(K)?K.readable:K;jO(U,()=>{if(L){let V=L;L=null,V()}})}if(G){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(AE(K)){let V=(VT(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 IO;if(J=null,E=null,L=null,X===null)V(U);else if(X=V,zA(K))qO(K,U)},H}});var gH=W((ER,JE)=>{var xO=globalThis.AbortController||I("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:wO,ERR_INVALID_ARG_TYPE:u4,ERR_MISSING_ARGS:SO,ERR_OUT_OF_RANGE:yO},AbortError:J0}=l_(),{validateAbortSignal:zT,validateInteger:jH,validateObject:FT}=pT(),vO=z_().Symbol("kWeak"),hO=z_().Symbol("kResistStopPropagation"),{finished:kO}=q0(),fO=EE(),{addAbortSignalNoValidate:bO}=w4(),{isWritable:gO,isNodeStream:mO}=T0(),{deprecate:uO}=s_(),{ArrayPrototypePush:dO,Boolean:cO,MathFloor:xH,Number:pO,NumberIsNaN:lO,Promise:wH,PromiseReject:SH,PromiseResolve:nO,PromisePrototypeThen:yH,Symbol:hH}=z_(),FA=hH("kEmpty"),vH=hH("kEof");function iO(_,T){if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");if(mO(_)&&!gO(_))throw new wO("stream",_,"must be writable");let A=fO(this,_);if(T!==null&&T!==void 0&&T.signal)bO(T.signal,A);return A}function CA(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");let A=1;if((T===null||T===void 0?void 0:T.concurrency)!=null)A=xH(T.concurrency);let E=A-1;if((T===null||T===void 0?void 0:T.highWaterMark)!=null)E=xH(T.highWaterMark);return jH(A,"options.concurrency",1),jH(E,"options.highWaterMark",0),E+=A,async function*(){let J=s_().AbortSignalAny([T===null||T===void 0?void 0:T.signal].filter(cO)),X=this,H=[],Z={signal:J},Y,K,$=!1,G=0;function U(){$=!0,V()}function V(){G-=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($)return;if(J.aborted)throw new J0;try{if(Q=_(Q,Z),Q===FA)continue;Q=nO(Q)}catch(F){Q=SH(F)}if(G+=1,yH(Q,V,U),H.push(Q),Y)Y(),Y=null;if(!$&&(H.length>=E||G>=A))await new wH((F)=>{K=F})}H.push(vH)}catch(Q){let F=SH(Q);yH(F,V,U),H.push(F)}finally{if($=!0,Y)Y(),Y=null}}z();try{while(!0){while(H.length>0){let Q=await H[0];if(Q===vH)return;if(J.aborted)throw new J0;if(Q!==FA)yield Q;H.shift(),N()}await new wH((Q)=>{Y=Q})}}finally{if($=!0,K)K(),K=null}}.call(this)}function aO(_=void 0){if(_!=null)FT(_,"options");if((_===null||_===void 0?void 0:_.signal)!=null)zT(_.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 J0({cause:_.signal.reason});yield[A++,L]}}.call(this)}async function kH(_,T=void 0){for await(let A of LE.call(this,_,T))return!0;return!1}async function oO(_,T=void 0){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);return!await kH.call(this,async(...A)=>{return!await _(...A)},T)}async function rO(_,T){for await(let A of LE.call(this,_,T))return A;return}async function sO(_,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 LE(_,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 fH extends SO{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function tO(_,T,A){var E;if(typeof _!=="function")throw new u4("reducer",["Function","AsyncFunction"],_);if(A!=null)FT(A,"options");if((A===null||A===void 0?void 0:A.signal)!=null)zT(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 J0(void 0,{cause:A.signal.reason});throw this.once("error",()=>{}),await kO(this.destroy(Y)),Y}let J=new xO,X=J.signal;if(A!==null&&A!==void 0&&A.signal){let Y={once:!0,[vO]:this,[hO]:!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 J0;if(!L)T=Y,L=!0;else T=await _(T,Y,{signal:X})}if(!H&&!L)throw new fH}finally{J.abort()}return T}async function eO(_){if(_!=null)FT(_,"options");if((_===null||_===void 0?void 0:_.signal)!=null)zT(_.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 J0(void 0,{cause:_.signal.reason});dO(T,E)}return T}function _R(_,T){let A=CA.call(this,_,T);return async function*(){for await(let L of A)yield*L}.call(this)}function bH(_){if(_=pO(_),lO(_))return 0;if(_<0)throw new yO("number",">= 0",_);return _}function TR(_,T=void 0){if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");return _=bH(_),async function*(){var E;if(T!==null&&T!==void 0&&(E=T.signal)!==null&&E!==void 0&&E.aborted)throw new J0;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 J0;if(_--<=0)yield J}}.call(this)}function AR(_,T=void 0){if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");return _=bH(_),async function*(){var E;if(T!==null&&T!==void 0&&(E=T.signal)!==null&&E!==void 0&&E.aborted)throw new J0;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 J0;if(_-- >0)yield J;if(_<=0)return}}.call(this)}ER.streamReturningOperators={asIndexedPairs:uO(aO,"readable.asIndexedPairs will be removed in a future version."),drop:TR,filter:LE,flatMap:_R,map:CA,take:AR,compose:iO};ER.promiseReturningOperators={every:oO,forEach:sO,reduce:tO,toArray:eO,some:kH,find:rO}});var XE=W((Sf,mH)=>{var{ArrayPrototypePop:XR,Promise:HR}=z_(),{isIterable:ZR,isNodeStream:YR,isWebStream:KR}=T0(),{pipelineImpl:$R}=MA(),{finished:GR}=q0();HE();function UR(..._){return new HR((T,A)=>{let E,L,J=_[_.length-1];if(J&&typeof J==="object"&&!YR(J)&&!ZR(J)&&!KR(J)){let X=XR(_);E=X.signal,L=X.end}$R(_,(X,H)=>{if(X)A(X);else T(H)},{signal:E,end:L})})}mH.exports={finished:GR,pipeline:UR}});var HE=W((yf,oH)=>{var{Buffer:WR}=I("buffer"),{ObjectDefineProperty:j0,ObjectKeys:cH,ReflectApply:pH}=z_(),{promisify:{custom:lH}}=s_(),{streamReturningOperators:uH,promiseReturningOperators:dH}=gH(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:nH}}=l_(),NR=EE(),{setDefaultHighWaterMark:QR,getDefaultHighWaterMark:MR}=S4(),{pipeline:iH}=MA(),{destroyer:VR}=GT(),aH=q0(),ZE=XE(),d4=T0(),V_=oH.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 cH(uH)){let A=function(...E){if(new.target)throw nH();return V_.Readable.from(pH(T,this,E))},T=uH[_];j0(A,"name",{__proto__:null,value:T.name}),j0(A,"length",{__proto__:null,value:T.length}),j0(V_.Readable.prototype,_,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}for(let _ of cH(dH)){let A=function(...E){if(new.target)throw nH();return pH(T,this,E)},T=dH[_];j0(A,"name",{__proto__:null,value:T.name}),j0(A,"length",{__proto__:null,value:T.length}),j0(V_.Readable.prototype,_,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}V_.Writable=UA();V_.Duplex=L0();V_.Transform=p6();V_.PassThrough=n6();V_.pipeline=iH;var{addAbortSignal:zR}=w4();V_.addAbortSignal=zR;V_.finished=aH;V_.destroy=VR;V_.compose=NR;V_.setDefaultHighWaterMark=QR;V_.getDefaultHighWaterMark=MR;j0(V_,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return ZE}});j0(iH,lH,{__proto__:null,enumerable:!0,get(){return ZE.pipeline}});j0(aH,lH,{__proto__:null,enumerable:!0,get(){return ZE.finished}});V_.Stream=V_;V_._isUint8Array=function(T){return T instanceof Uint8Array};V_._uint8ArrayToBuffer=function(T){return WR.from(T.buffer,T.byteOffset,T.byteLength)}});var n0=W((vf,__)=>{var S_=I("stream");if(S_&&process.env.READABLE_STREAM==="disable"){let _=S_.promises;__.exports._uint8ArrayToBuffer=S_._uint8ArrayToBuffer,__.exports._isUint8Array=S_._isUint8Array,__.exports.isDisturbed=S_.isDisturbed,__.exports.isErrored=S_.isErrored,__.exports.isReadable=S_.isReadable,__.exports.Readable=S_.Readable,__.exports.Writable=S_.Writable,__.exports.Duplex=S_.Duplex,__.exports.Transform=S_.Transform,__.exports.PassThrough=S_.PassThrough,__.exports.addAbortSignal=S_.addAbortSignal,__.exports.finished=S_.finished,__.exports.destroy=S_.destroy,__.exports.pipeline=S_.pipeline,__.exports.compose=S_.compose,Object.defineProperty(S_,"promises",{configurable:!0,enumerable:!0,get(){return _}}),__.exports.Stream=S_.Stream}else{let _=HE(),T=XE(),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 rH=W((tf,YE)=>{if(typeof Object.create==="function")YE.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 YE.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 sH=W((ef,KE)=>{try{if(OA=I("util"),typeof OA.inherits!=="function")throw"";KE.exports=OA.inherits}catch(_){KE.exports=rH()}var OA});var _Z=W((_b,eH)=>{var{Buffer:u1}=I("buffer"),tH=Symbol.for("BufferList");function H_(_){if(!(this instanceof H_))return new H_(_);H_._init.call(this,_)}H_._init=function(T){if(Object.defineProperty(this,tH,{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||u1.alloc(0);if(L<=0)return T||u1.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]:u1.concat(this._bufs,this.length);for(let $=0;$<this._bufs.length;$++)this._bufs[$].copy(T,Y),Y+=this._bufs[$].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=u1.allocUnsafe(H);for(let $=X[0];$<this._bufs.length;$++){let G=this._bufs[$].length-K;if(Z>G)this._bufs[$].copy(T,Y,K),Y+=G;else{this._bufs[$].copy(T,Y,K,K+Z),Y+=G;break}if(Z-=G,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,u1.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,u1.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")_=u1.from([_]);else if(typeof _==="string")_=u1.from(_,A);else if(this._isBufferList(_))_=_.slice();else if(Array.isArray(_.buffer))_=u1.from(_.buffer,_.byteOffset,_.byteLength);else if(!u1.isBuffer(_))_=u1.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[tH]};eH.exports=H_});var TZ=W((Tb,RA)=>{var $E=n0().Duplex,FR=sH(),c4=_Z();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,_),$E.call(this)}FR(i_,$E);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($E.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 LZ=W((Ab,EZ)=>{class AZ{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}EZ.exports=AZ});var GE=W((Eb,JZ)=>{var x=Eb,{Buffer:X1}=I("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 HZ=W((Lb,XZ)=>{var T4=1000,A4=T4*60,E4=A4*60,CT=E4*24,CR=CT*7,OR=CT*365.25;XZ.exports=function(_,T){T=T||{};var A=typeof _;if(A==="string"&&_.length>0)return RR(_);else if(A==="number"&&isFinite(_))return T.long?BR(_):DR(_);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(_))};function RR(_){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*OR;case"weeks":case"week":case"w":return A*CR;case"days":case"day":case"d":return A*CT;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 DR(_){var T=Math.abs(_);if(T>=CT)return Math.round(_/CT)+"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 BR(_){var T=Math.abs(_);if(T>=CT)return DA(_,T,CT,"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 UE=W((Jb,ZZ)=>{function qR(_){A.debug=A,A.default=A,A.coerce=Z,A.disable=X,A.enable=L,A.enabled=H,A.humanize=HZ(),A.destroy=Y,Object.keys(_).forEach((K)=>{A[K]=_[K]}),A.names=[],A.skips=[],A.formatters={};function T(K){let $=0;for(let G=0;G<K.length;G++)$=($<<5)-$+K.charCodeAt(G),$|=0;return A.colors[Math.abs($)%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-($||F);if(Q.diff=R,Q.prev=$,Q.curr=F,$=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(G!==null)return G;if(U!==A.namespaces)U=A.namespaces,V=A.enabled(K);return V},set:(z)=>{G=z}}),typeof A.init==="function")A.init(N);return N}function E(K,$){let G=A(this.namespace+(typeof $>"u"?":":$)+K);return G.log=this.log,G}function L(K){A.save(K),A.namespaces=K,A.names=[],A.skips=[];let $=(typeof K==="string"?K:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let G of $)if(G[0]==="-")A.skips.push(G.slice(1));else A.names.push(G)}function J(K,$){let G=0,U=0,V=-1,N=0;while(G<K.length)if(U<$.length&&($[U]===K[G]||$[U]==="*"))if($[U]==="*")V=U,N=G,U++;else G++,U++;else if(V!==-1)U=V+1,N++,G=N;else return!1;while(U<$.length&&$[U]==="*")U++;return U===$.length}function X(){let K=[...A.names,...A.skips.map(($)=>"-"+$)].join(",");return A.enable(""),K}function H(K){for(let $ of A.skips)if(J(K,$))return!1;for(let $ of A.names)if(J(K,$))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}ZZ.exports=qR});var KZ=W((YZ,BA)=>{YZ.formatArgs=PR;YZ.save=jR;YZ.load=xR;YZ.useColors=IR;YZ.storage=wR();YZ.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`.")}})();YZ.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 IR(){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 PR(_){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)}YZ.log=console.debug||console.log||(()=>{});function jR(_){try{if(_)YZ.storage.setItem("debug",_);else YZ.storage.removeItem("debug")}catch(T){}}function xR(){let _;try{_=YZ.storage.getItem("debug")||YZ.storage.getItem("DEBUG")}catch(T){}if(!_&&typeof process<"u"&&"env"in process)_=process.env.DEBUG;return _}function wR(){try{return localStorage}catch(_){}}BA.exports=UE()(YZ);var{formatters:SR}=BA.exports;SR.j=function(_){try{return JSON.stringify(_)}catch(T){return"[UnexpectedJSONParseError]: "+T.message}}});var WZ=W((GZ,IA)=>{var mR=I("tty"),qA=I("util");GZ.init=iR;GZ.log=pR;GZ.formatArgs=dR;GZ.save=lR;GZ.load=nR;GZ.useColors=uR;GZ.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`.");GZ.colors=[6,2,3,4,5,1];try{let _=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(_&&(_.stderr||_).level>=2)GZ.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(_){}GZ.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 uR(){return"colors"in GZ.inspectOpts?Boolean(GZ.inspectOpts.colors):mR.isatty(process.stderr.fd)}function dR(_){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
- `+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)=>{/*!
5
+ `+J),_.push(L+"m+"+IA.exports.humanize(this.diff)+"\x1B[0m")}else _[0]=cR()+T+" "+_[0]}function cR(){if(GZ.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function pR(..._){return process.stderr.write(qA.formatWithOptions(GZ.inspectOpts,..._)+`
6
+ `)}function lR(_){if(_)process.env.DEBUG=_;else delete process.env.DEBUG}function nR(){return process.env.DEBUG}function iR(_){_.inspectOpts={};let T=Object.keys(GZ.inspectOpts);for(let A=0;A<T.length;A++)_.inspectOpts[T[A]]=GZ.inspectOpts[T[A]]}IA.exports=UE()(GZ);var{formatters:$Z}=IA.exports;$Z.o=function(_){return this.inspectOpts.colors=this.useColors,qA.inspect(_,this.inspectOpts).split(`
7
+ `).map((T)=>T.trim()).join(" ")};$Z.O=function(_){return this.inspectOpts.colors=this.useColors,qA.inspect(_,this.inspectOpts)}});var d1=W((Zb,WE)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)WE.exports=KZ();else WE.exports=WZ()});var MZ=W((Yb,QZ)=>{var TD=TZ(),{EventEmitter:AD}=I("events"),NZ=LZ(),E_=GE(),n=d1()("mqtt-packet:parser");class PA extends AD{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 NZ,this.error=null,this._list=TD(),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 NZ,this._pos=0,!0}_emitError(_){n("_emitError",_),this.error=_,this.emit("error",_)}}QZ.exports=PA});var CZ=W((Kb,FZ)=>{var{Buffer:l4}=I("buffer"),VZ={},ED=l4.isBuffer(l4.from([1,2]).subarray(0,1));function zZ(_){let T=l4.allocUnsafe(2);return T.writeUInt8(_>>8,0),T.writeUInt8(_&255,1),T}function LD(){for(let _=0;_<65536;_++)VZ[_]=zZ(_)}function JD(_){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 ED?L.subarray(0,E):L.slice(0,E)}function XD(_){let T=l4.allocUnsafe(4);return T.writeUInt32BE(_,0),T}FZ.exports={cache:VZ,generateCache:LD,generateNumber:zZ,genBufVariableByteInt:JD,generate4ByteBuffer:XD}});var OZ=W(($b,NE)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)NE.exports={nextTick:HD};else NE.exports=process;function HD(_,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 VE=W((Gb,xZ)=>{var i=GE(),{Buffer:p}=I("buffer"),ZD=p.allocUnsafe(0),YD=p.from([0]),n4=CZ(),KD=OZ().nextTick,R1=d1()("mqtt-packet:writeToStream"),jA=n4.cache,$D=n4.generateNumber,GD=n4.generateCache,QE=n4.genBufVariableByteInt,UD=n4.generate4ByteBuffer,t_=ME,xA=!0;function PZ(_,T,A){if(R1("generate called"),T.cork)T.cork(),KD(WD,T);if(xA)xA=!1,GD();switch(R1("generate: packet.cmd: %s",_.cmd),_.cmd){case"connect":return ND(_,T,A);case"connack":return QD(_,T,A);case"publish":return MD(_,T,A);case"puback":case"pubrec":case"pubrel":case"pubcomp":return VD(_,T,A);case"subscribe":return zD(_,T,A);case"suback":return FD(_,T,A);case"unsubscribe":return CD(_,T,A);case"unsuback":return OD(_,T,A);case"pingreq":case"pingresp":return RD(_,T,A);case"disconnect":return DD(_,T,A);case"auth":return BD(_,T,A);default:return T.destroy(Error("Unknown command")),!1}}Object.defineProperty(PZ,"cacheNumbers",{get(){return t_===ME},set(_){if(_){if(!jA||Object.keys(jA).length===0)xA=!0;t_=ME}else xA=!1,t_=qD}});function WD(_){_.uncork()}function ND(_,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,$=E.password,G=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,G),!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(IZ(K))z=!0,U+=p.byteLength(K)+2;else return T.destroy(Error("Invalid username")),!1;if($!=null){if(!z)return T.destroy(Error("Username is required to use password")),!1;if(IZ($))U+=jZ($)+2;else return T.destroy(Error("Invalid password")),!1}if(T.write(i.CONNECT_HEADER),D1(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|=$!=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();RT(T,X.topic),L4(T,X.payload)}if(K!=null)L4(T,K);if($!=null)L4(T,$);return!0}function QD(_,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),D1(T,H),T.write(L.sessionPresent?i.SESSIONPRESENT_HEADER:YD),T.write(p.from([J])),Z!=null)Z.write();return!0}function MD(_,T,A){R1("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||ZD,Y=L.messageId,K=L.properties,$=0;if(typeof H==="string")$+=p.byteLength(H)+2;else if(p.isBuffer(H))$+=H.length+2;else return T.destroy(Error("Invalid topic")),!1;if(!p.isBuffer(Z))$+=p.byteLength(Z);else $+=Z.length;if(J&&typeof Y!=="number")return T.destroy(Error("Invalid messageId")),!1;else if(J)$+=2;let G=null;if(E===5){if(G=a0(T,K),!G)return!1;$+=G.length}if(T.write(i.PUBLISH_HEADER[J][L.dup?1:0][X?1:0]),D1(T,$),t_(T,jZ(H)),T.write(H),J>0)t_(T,Y);if(G!=null)G.write();return R1("publish: payload: %o",Z),T.write(Z)}function VD(_,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,$=E===5?3:2;if(J==="pubrel")Z=1;if(typeof X!=="number")return T.destroy(Error("Invalid messageId")),!1;let G=null;if(E===5){if(typeof K==="object"){if(G=i4(T,K,A,$),!G)return!1;$+=G.length}}if(T.write(i.ACKS[J][Z][H][0]),$===3)$+=Y!==0?1:-1;if(D1(T,$),t_(T,X),E===5&&$!==2)T.write(p.from([Y]));if(G!==null)G.write();else if($===4)T.write(p.from([0]));return!0}function zD(_,T,A){R1("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 G=0;G<H.length;G+=1){let U=H[G].topic,V=H[G].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[G].nl||!1)!=="boolean")return T.destroy(Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(H[G].rap||!1)!=="boolean")return T.destroy(Error("Invalid subscriptions - invalid Retain as Published")),!1;let Q=H[G].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(R1("subscribe: writing to stream: %o",i.SUBSCRIBE_HEADER),T.write(i.SUBSCRIBE_HEADER[1][J?1:0][0]),D1(T,Y),t_(T,X),K!==null)K.write();let $=!0;for(let G of H){let{topic:U,qos:V}=G,N=+G.nl,z=+G.rap,Q=G.rh,F;if(RT(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;$=T.write(p.from([F]))}return $}function FD(_,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),D1(T,Z),t_(T,J),Y!==null)Y.write();return T.write(p.from(X))}function CD(_,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 G=0;G<H.length;G+=1){if(typeof H[G]!=="string")return T.destroy(Error("Invalid unsubscriptions")),!1;Y+=p.byteLength(H[G])+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]),D1(T,Y),t_(T,J),K!==null)K.write();let $=!0;for(let G=0;G<H.length;G++)$=RT(T,H[G]);return $}function OD(_,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,$=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;$+=1}else return T.destroy(Error("Invalid qos vector")),!1;let G=null;if(E===5){if(G=i4(T,Z,A,$),!G)return!1;$+=G.length}if(T.write(i.ACKS[Y][0][X][0]),D1(T,$),t_(T,J),G!==null)G.write();if(E===5)T.write(p.from(H));return!0}function RD(_,T,A){return T.write(i.EMPTY[_.cmd])}function DD(_,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])),D1(T,H),E===5)T.write(p.from([J]));if(Z!==null)Z.write();return!0}function BD(_,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])),D1(T,H),T.write(p.from([J])),Z!==null)Z.write();return!0}var RZ={};function D1(_,T){if(T>i.VARBYTEINT_MAX)return _.destroy(Error(`Invalid variable byte integer: ${T}`)),!1;let A=RZ[T];if(!A){if(A=QE(T),T<16384)RZ[T]=A}return R1("writeVarByteInt: writing to stream: %o",A),_.write(A)}function RT(_,T){let A=p.byteLength(T);return t_(_,A),R1("writeString: %s",T),_.write(T,"utf8")}function DZ(_,T,A){RT(_,T),RT(_,A)}function ME(_,T){return R1("writeNumberCached: number: %d",T),R1("writeNumberCached: %o",jA[T]),_.write(jA[T])}function qD(_,T){let A=$D(T);return R1("writeNumberGenerated: %o",A),_.write(A)}function ID(_,T){let A=UD(T);return R1("write4ByteNumber: %o",A),_.write(A)}function L4(_,T){if(typeof T==="string")RT(_,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(){qZ(_,{},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(QE(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 $=X[K];if(Array.isArray($))Y+=$.reduce((G,U)=>{return G+=3+p.byteLength(K.toString())+2+p.byteLength(U.toString()),G},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(QE(A))+A,write(){qZ(_,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 BZ(_,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]])),ID(_,A);break}case"var":{_.write(p.from([i.properties[T]])),D1(_,A);break}case"string":{_.write(p.from([i.properties[T]])),RT(_,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]])),DZ(_,L.toString(),X.toString())});else _.write(p.from([i.properties[T]])),DZ(_,L.toString(),J.toString())});break}default:return _.destroy(Error(`Invalid property ${T} value: ${A}`)),!1}}function qZ(_,T,A){D1(_,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++)BZ(_,E,L[J]);else BZ(_,E,L)}}function jZ(_){if(!_)return 0;else if(_ instanceof p)return _.length;else return p.byteLength(_)}function IZ(_){return typeof _==="string"||_ instanceof p}xZ.exports=PZ});var vZ=W((Ub,yZ)=>{var PD=VE(),{EventEmitter:jD}=I("events"),{Buffer:wZ}=I("buffer");function xD(_,T){let A=new SZ;return PD(_,A,T),A.concat()}class SZ extends jD{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]=wZ.byteLength(A[L]);_+=T[L]}let J=wZ.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",_)}}yZ.exports=xD});var wA=W((wD)=>{wD.parser=MZ().parser;wD.generate=vZ();wD.writeToStream=VE()});var fZ=W((Nb,kZ)=>{kZ.exports=hZ;function hZ(_,T){if(_&&T)return hZ(_)(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 mZ=W((Qb,zE)=>{var bZ=fZ();zE.exports=bZ(SA);zE.exports.strict=bZ(gZ);SA.proto=SA(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return SA(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return gZ(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 gZ(_){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 cZ=W((Mb,dZ)=>{var hD=mZ(),kD=function(){},fD=global.Bare?queueMicrotask:process.nextTick.bind(process),bD=function(_){return _.setHeader&&typeof _.abort==="function"},gD=function(_){return _.stdio&&Array.isArray(_.stdio)&&_.stdio.length===3},uZ=function(_,T,A){if(typeof T==="function")return uZ(_,null,T);if(!T)T={};A=hD(A||kD);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(_)},$=function(z){A.call(_,z?Error("exited with error code: "+z):null)},G=function(z){A.call(_,z)},U=function(){fD(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(bD(_))if(_.on("complete",Y),_.on("abort",U),_.req)N();else _.on("request",N);else if(X&&!E)_.on("end",Z),_.on("close",Z);if(gD(_))_.on("exit",$);if(_.on("end",K),_.on("finish",Y),T.error!==!1)_.on("error",G);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",$),_.removeListener("end",K),_.removeListener("error",G),_.removeListener("close",U)}};dZ.exports=uZ});var x0=W((Vb,pZ)=>{var mD=wA();function uD(_,T,A){let E=null;if(_.connecting||_.connected)try{if(!mD.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,_)}pZ.exports=uD});var FE=W((zb,iZ)=>{var lZ=uT(),dD=I("util");function nZ(_,T){if(lZ.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}dD.inherits(nZ,lZ);iZ.exports=nZ});var rZ=W((Fb,oZ)=>{var cD=k8(),aZ=[];function pD(_,T){if(Array.isArray(_))T=_,_=null;var A=cD(lD);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 lD(){this.list=aZ,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=aZ,_.count=0,_.release(_)}}}oZ.exports=pD});var DT=W((Cb,sZ)=>{var{Transform:nD,Writable:iD}=I("stream");function aD(_,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 oD(_){return new nD({objectMode:!0,transform:_})}function rD(_){return new iD({objectMode:!0,writev:function(T,A){_(T.map((E)=>E.chunk),A)}})}sZ.exports={validateTopic:aD,through:oD,bulk:rD,$SYS_PREFIX:"$SYS/"}});var yA=W((Ob,E2)=>{var eZ=rZ(),_2=uT(),{through:sD}=DT(),{validateTopic:tD,$SYS_PREFIX:eD}=DT(),_B=x0(),TB=eZ([T2,KB,A2]),AB=eZ([T2,A2]);function EB(_,T){this.cmd="suback",this.messageId=_.messageId,this.granted=T}function tZ(_,T,A,E,L){this.qos=_,this.func=T,this.rh=A,this.rap=E,this.nl=L}function LB(_,T,A,E){this.client=_,this.packet=T,this.actions=A?AB:TB,this.finish=E,this.subState=[]}function JB(_,T,A,E,L,J){this.client=_,this.packet=T,this.granted=A,this.rh=E,this.rap=L,this.nl=J}function XB(_){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 HB(_,T,A,E){T.subscriptions=T.subscriptions.length===1?T.subscriptions:XB(T.subscriptions),_.broker._parallel(new LB(_,T,A,E),ZB,T.subscriptions,A?E:GB)}function ZB(_,T){let A=new JB(this.client,this.packet,_.qos,_.rh,_.rap,_.nl);this.subState.push(A),this.actions.call(A,_,T)}function T2(_,T){let A=tD(_.topic,"SUBSCRIBE");if(A)return T(A);let E=this.client;E.broker.authorizeSubscribe(E,_,T)}function YB(_){return function(A,E){if(A.topic.charCodeAt(0)===36)E();else _(A,E)}}function KB(_,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 A2(_,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(G,U){if(G=new _2(G,E),G.nl=Z,!H)G.retain=!1;K(G,U)},$B(L))Y=YB(Y);if(A.closed||A.broker.closed)return;if(!A.subscriptions[L])A.subscriptions[L]=new tZ(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 tZ(J,Y,X,H,Z),E.subscribe(L,Y,T);else T()}function $B(_){let T=_.charCodeAt(0);return T===43||T===35}function GB(_){let T=this.finish;if(_)return T(_);let A=this.packet,E=this.client;if(A.messageId!==void 0)_B(E,new EB(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:eD+L.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:E.id,subs:J}),"utf8")},UB),X.length>0)L.persistence.createRetainedStreamCombi(X).pipe(sD(function(K,$,G){K=new _2({cmd:K.cmd,qos:K.qos,topic:K.topic,payload:K.payload,retain:!0},L),K.brokerId=null,E.deliverQoS(K,G)}))}function UB(){}E2.exports=HB});var OE=W((Rb,L2)=>{var WB=x0(),{validateTopic:NB,$SYS_PREFIX:QB}=DT();function MB(_){this.cmd="unsuback",this.messageId=_.messageId}function VB(_,T,A){this.client=_,this.packet=T,this.finish=A}function zB(_,T,A){let E=_.broker,L=T.unsubscriptions,J;for(let X=0;X<L.length;X++)if(J=NB(L[X],"UNSUBSCRIBE"),J)return A(J);if(T.messageId!==void 0){if(_.clean)return CE(_,T,A);E.persistence.removeSubscriptions(_,L,function(X){if(X)return A(X);CE(_,T,A)})}else CE(_,T,A)}function CE(_,T,A){_.broker._parallel(new VB(_,T,A),FB,T.unsubscriptions,CB)}function FB(_,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 CB(_){let T=this.client;if(_){T.emit("error",_);return}let A=this.packet,E=this.finish;if(A.messageId!==void 0)WB(T,new MB(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:QB+T.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:T.id,subs:A.unsubscriptions}),"utf8")},OB)}function OB(){}L2.exports=zB});var X2=W((Db,J2)=>{J2.exports=function(){let T=process.hrtime();return Math.floor(T[0]*1000+T[1]/1e6)}});var Z2=W((Bb,H2)=>{H2.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var $2=W((qb,DE)=>{var vA=X2(),{clearTimeout:Y2,setTimeout:K2}=Z2();class RE{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=K2(this._timerWrapper,T)}reschedule(_){if(!_)_=this._scheduled;let T=vA();if(T+_-(this._started+this._scheduled)<0)Y2(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=K2(this._timerWrapper,_)}clear(){Y2(this._timer)}}function RB(){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 RE(arguments[0],arguments[1],_)}DE.exports=RB;DE.exports.Retimer=RE});var BE=W((G2)=>{Object.defineProperty(G2,"__esModule",{value:!0});G2.default=qB;var DB=BB(I("crypto"));function BB(_){return _&&_.__esModule?_:{default:_}}var kA=new Uint8Array(256),hA=kA.length;function qB(){if(hA>kA.length-16)DB.default.randomFillSync(kA),hA=0;return kA.slice(hA,hA+=16)}});var N2=W((U2)=>{Object.defineProperty(U2,"__esModule",{value:!0});U2.default=void 0;var PB=/^(?:[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;U2.default=PB});var o4=W((Q2)=>{Object.defineProperty(Q2,"__esModule",{value:!0});Q2.default=void 0;var jB=xB(N2());function xB(_){return _&&_.__esModule?_:{default:_}}function wB(_){return typeof _==="string"&&jB.default.test(_)}var SB=wB;Q2.default=SB});var r4=W((V2)=>{Object.defineProperty(V2,"__esModule",{value:!0});V2.default=void 0;var yB=vB(o4());function vB(_){return _&&_.__esModule?_:{default:_}}var m_=[];for(let _=0;_<256;++_)m_.push((_+256).toString(16).substr(1));function hB(_,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,yB.default)(A))throw TypeError("Stringified UUID is invalid");return A}var kB=hB;V2.default=kB});var D2=W((O2)=>{Object.defineProperty(O2,"__esModule",{value:!0});O2.default=void 0;var fB=C2(BE()),bB=C2(r4());function C2(_){return _&&_.__esModule?_:{default:_}}var F2,qE,IE=0,PE=0;function gB(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let J=_.node||F2,X=_.clockseq!==void 0?_.clockseq:qE;if(J==null||X==null){let G=_.random||(_.rng||fB.default)();if(J==null)J=F2=[G[0]|1,G[1],G[2],G[3],G[4],G[5]];if(X==null)X=qE=(G[6]<<8|G[7])&16383}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:PE+1,Y=H-IE+(Z-PE)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>IE)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");IE=H,PE=Z,qE=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 $=H/4294967296*1e4&268435455;L[E++]=$>>>8&255,L[E++]=$&255,L[E++]=$>>>24&15|16,L[E++]=$>>>16&255,L[E++]=X>>>8|128,L[E++]=X&255;for(let G=0;G<6;++G)L[E+G]=J[G];return T||(0,bB.default)(L)}var mB=gB;O2.default=mB});var jE=W((B2)=>{Object.defineProperty(B2,"__esModule",{value:!0});B2.default=void 0;var uB=dB(o4());function dB(_){return _&&_.__esModule?_:{default:_}}function cB(_){if(!(0,uB.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 pB=cB;B2.default=pB});var xE=W((x2)=>{Object.defineProperty(x2,"__esModule",{value:!0});x2.default=aB;x2.URL=x2.DNS=void 0;var lB=I2(r4()),nB=I2(jE());function I2(_){return _&&_.__esModule?_:{default:_}}function iB(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var P2="6ba7b810-9dad-11d1-80b4-00c04fd430c8";x2.DNS=P2;var j2="6ba7b811-9dad-11d1-80b4-00c04fd430c8";x2.URL=j2;function aB(_,T,A){function E(L,J,X,H){if(typeof L==="string")L=iB(L);if(typeof J==="string")J=(0,nB.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,lB.default)(Z)}try{E.name=_}catch(L){}return E.DNS=P2,E.URL=j2,E}});var v2=W((S2)=>{Object.defineProperty(S2,"__esModule",{value:!0});S2.default=void 0;var sB=tB(I("crypto"));function tB(_){return _&&_.__esModule?_:{default:_}}function eB(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return sB.default.createHash("md5").update(_).digest()}var _q=eB;S2.default=_q});var b2=W((k2)=>{Object.defineProperty(k2,"__esModule",{value:!0});k2.default=void 0;var Tq=h2(xE()),Aq=h2(v2());function h2(_){return _&&_.__esModule?_:{default:_}}var Eq=(0,Tq.default)("v3",48,Aq.default),Lq=Eq;k2.default=Lq});var d2=W((m2)=>{Object.defineProperty(m2,"__esModule",{value:!0});m2.default=void 0;var Jq=g2(BE()),Xq=g2(r4());function g2(_){return _&&_.__esModule?_:{default:_}}function Hq(_,T,A){_=_||{};let E=_.random||(_.rng||Jq.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,Xq.default)(E)}var Zq=Hq;m2.default=Zq});var l2=W((c2)=>{Object.defineProperty(c2,"__esModule",{value:!0});c2.default=void 0;var Yq=Kq(I("crypto"));function Kq(_){return _&&_.__esModule?_:{default:_}}function $q(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return Yq.default.createHash("sha1").update(_).digest()}var Gq=$q;c2.default=Gq});var o2=W((i2)=>{Object.defineProperty(i2,"__esModule",{value:!0});i2.default=void 0;var Uq=n2(xE()),Wq=n2(l2());function n2(_){return _&&_.__esModule?_:{default:_}}var Nq=(0,Uq.default)("v5",80,Wq.default),Qq=Nq;i2.default=Qq});var t2=W((r2)=>{Object.defineProperty(r2,"__esModule",{value:!0});r2.default=void 0;var Mq="00000000-0000-0000-0000-000000000000";r2.default=Mq});var TY=W((e2)=>{Object.defineProperty(e2,"__esModule",{value:!0});e2.default=void 0;var Vq=zq(o4());function zq(_){return _&&_.__esModule?_:{default:_}}function Fq(_){if(!(0,Vq.default)(_))throw TypeError("Invalid UUID");return parseInt(_.substr(14,1),16)}var Cq=Fq;e2.default=Cq});var AY=W((c1)=>{Object.defineProperty(c1,"__esModule",{value:!0});Object.defineProperty(c1,"v1",{enumerable:!0,get:function(){return Oq.default}});Object.defineProperty(c1,"v3",{enumerable:!0,get:function(){return Rq.default}});Object.defineProperty(c1,"v4",{enumerable:!0,get:function(){return Dq.default}});Object.defineProperty(c1,"v5",{enumerable:!0,get:function(){return Bq.default}});Object.defineProperty(c1,"NIL",{enumerable:!0,get:function(){return qq.default}});Object.defineProperty(c1,"version",{enumerable:!0,get:function(){return Iq.default}});Object.defineProperty(c1,"validate",{enumerable:!0,get:function(){return Pq.default}});Object.defineProperty(c1,"stringify",{enumerable:!0,get:function(){return jq.default}});Object.defineProperty(c1,"parse",{enumerable:!0,get:function(){return xq.default}});var Oq=w0(D2()),Rq=w0(b2()),Dq=w0(d2()),Bq=w0(o2()),qq=w0(t2()),Iq=w0(TY()),Pq=w0(o4()),jq=w0(r4()),xq=w0(jE());function w0(_){return _&&_.__esModule?_:{default:_}}});var JY=W((db,LY)=>{var wq=AY(),EY=I("crypto");LY.exports=typeof EY.randomUUID==="function"?EY.randomUUID:wq.v4});var ZY=W((cb,HY)=>{var wE=[],XY={};for(o0=0;o0<256;o0++)wE[o0]=(o0+256).toString(16).substr(1),XY[wE[o0]]=o0;var o0;function Sq(_,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++]=XY[J]});while(L<16)T[E+L++]=0;return T}function yq(_,T){var A=T||0,E=wE;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++]]}HY.exports={parse:Sq,unparse:yq}});var KY=W((uq)=>{uq.byteLength=hq;uq.toByteArray=fq;uq.fromByteArray=mq;var X0=[],B1=[],vq=typeof Uint8Array<"u"?Uint8Array:Array,SE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(r0=0,yE=SE.length;r0<yE;++r0)X0[r0]=SE[r0],B1[SE.charCodeAt(r0)]=r0;var r0,yE;B1[45]=62;B1[95]=63;function YY(_){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 hq(_){var T=YY(_),A=T[0],E=T[1];return(A+E)*3/4-E}function kq(_,T,A){return(T+A)*3/4-A}function fq(_){var T,A=YY(_),E=A[0],L=A[1],J=new vq(kq(_,E,L)),X=0,H=L>0?E-4:E,Z;for(Z=0;Z<H;Z+=4)T=B1[_.charCodeAt(Z)]<<18|B1[_.charCodeAt(Z+1)]<<12|B1[_.charCodeAt(Z+2)]<<6|B1[_.charCodeAt(Z+3)],J[X++]=T>>16&255,J[X++]=T>>8&255,J[X++]=T&255;if(L===2)T=B1[_.charCodeAt(Z)]<<2|B1[_.charCodeAt(Z+1)]>>4,J[X++]=T&255;if(L===1)T=B1[_.charCodeAt(Z)]<<10|B1[_.charCodeAt(Z+1)]<<4|B1[_.charCodeAt(Z+2)]>>2,J[X++]=T>>8&255,J[X++]=T&255;return J}function bq(_){return X0[_>>18&63]+X0[_>>12&63]+X0[_>>6&63]+X0[_&63]}function gq(_,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(bq(E));return L.join("")}function mq(_){var T,A=_.length,E=A%3,L=[],J=16383;for(var X=0,H=A-E;X<H;X+=J)L.push(gq(_,X,X+J>H?H:X+J));if(E===1)T=_[A-1],L.push(X0[T>>2]+X0[T<<4&63]+"==");else if(E===2)T=(_[A-2]<<8)+_[A-1],L.push(X0[T>>10]+X0[T>>4&63]+X0[T<<2&63]+"=");return L.join("")}});var $Y=W((lq)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */lq.read=function(_,T,A,E,L){var J,X,H=L*8-E-1,Z=(1<<H)-1,Y=Z>>1,K=-7,$=A?L-1:0,G=A?-1:1,U=_[T+$];$+=G,J=U&(1<<-K)-1,U>>=-K,K+=H;for(;K>0;J=J*256+_[T+$],$+=G,K-=8);X=J&(1<<-K)-1,J>>=-K,K+=E;for(;K>0;X=X*256+_[T+$],$+=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)};lq.write=function(_,T,A,E,L,J){var X,H,Z,Y=J*8-L-1,K=(1<<Y)-1,$=K>>1,G=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+$>=1)T+=G/Z;else T+=G*Math.pow(2,1-$);if(T*Z>=2)X++,Z/=2;if(X+$>=K)H=0,X=K;else if(X+$>=1)H=(T*Z-1)*Math.pow(2,L),X=X+$;else H=T*Math.pow(2,$-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 BY=W((MI)=>{/*!
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 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+`
12
+ */var vE=KY(),J4=$Y(),GY=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;MI.Buffer=B;MI.SlowBuffer=eq;MI.INSPECT_MAX_BYTES=50;var fA=2147483647;MI.kMaxLength=fA;B.TYPED_ARRAY_SUPPORT=aq();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 aq(){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 S0(_){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 bE(_)}return NY(_,T,A)}B.poolSize=8192;function NY(_,T,A){if(typeof _==="string")return rq(_,T);if(ArrayBuffer.isView(_))return sq(_);if(_==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _);if(H0(_,ArrayBuffer)||_&&H0(_.buffer,ArrayBuffer))return kE(_,T,A);if(typeof SharedArrayBuffer<"u"&&(H0(_,SharedArrayBuffer)||_&&H0(_.buffer,SharedArrayBuffer)))return kE(_,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=tq(_);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 NY(_,T,A)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function QY(_){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 oq(_,T,A){if(QY(_),_<=0)return S0(_);if(T!==void 0)return typeof A==="string"?S0(_).fill(T,A):S0(_).fill(T);return S0(_)}B.alloc=function(_,T,A){return oq(_,T,A)};function bE(_){return QY(_),S0(_<0?0:gE(_)|0)}B.allocUnsafe=function(_){return bE(_)};B.allocUnsafeSlow=function(_){return bE(_)};function rq(_,T){if(typeof T!=="string"||T==="")T="utf8";if(!B.isEncoding(T))throw TypeError("Unknown encoding: "+T);var A=MY(_,T)|0,E=S0(A),L=E.write(_,T);if(L!==A)E=E.slice(0,L);return E}function hE(_){var T=_.length<0?0:gE(_.length)|0,A=S0(T);for(var E=0;E<T;E+=1)A[E]=_[E]&255;return A}function sq(_){if(H0(_,Uint8Array)){var T=new Uint8Array(_);return kE(T.buffer,T.byteOffset,T.byteLength)}return hE(_)}function kE(_,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 tq(_){if(B.isBuffer(_)){var T=gE(_.length)|0,A=S0(T);if(A.length===0)return A;return _.copy(A,0,0,T),A}if(_.length!==void 0){if(typeof _.length!=="number"||mE(_.length))return S0(0);return hE(_)}if(_.type==="Buffer"&&Array.isArray(_.data))return hE(_.data)}function gE(_){if(_>=fA)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+fA.toString(16)+" bytes");return _|0}function eq(_){if(+_!=_)_=0;return B.alloc(+_)}B.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==B.prototype};B.compare=function(T,A){if(H0(T,Uint8Array))T=B.from(T,T.offset,T.byteLength);if(H0(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(H0(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 MY(_,T){if(B.isBuffer(_))return _.length;if(ArrayBuffer.isView(_)||H0(_,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 fE(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return RY(_).length;default:if(L)return E?-1:fE(_).length;T=(""+T).toLowerCase(),L=!0}}B.byteLength=MY;function _I(_,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 KI(this,T,A);case"utf8":case"utf-8":return zY(this,T,A);case"ascii":return ZI(this,T,A);case"latin1":case"binary":return YI(this,T,A);case"base64":return XI(this,T,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $I(this,T,A);default:if(E)throw TypeError("Unknown encoding: "+_);_=(_+"").toLowerCase(),E=!0}}B.prototype._isBuffer=!0;function BT(_,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)BT(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)BT(this,A,A+3),BT(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)BT(this,A,A+7),BT(this,A+1,A+6),BT(this,A+2,A+5),BT(this,A+3,A+4);return this};B.prototype.toString=function(){var T=this.length;if(T===0)return"";if(arguments.length===0)return zY(this,0,T);return _I.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=MI.INSPECT_MAX_BYTES;if(T=this.toString("hex",0,A).replace(/(.{2})/g,"$1 ").trim(),this.length>A)T+=" ... ";return"<Buffer "+T+">"};if(GY)B.prototype[GY]=B.prototype.inspect;B.prototype.compare=function(T,A,E,L,J){if(H0(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 $=0;$<Z;++$)if(Y[$]!==K[$]){X=Y[$],H=K[$];break}if(X<H)return-1;if(H<X)return 1;return 0};function VY(_,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,mE(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 UY(_,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 UY(_,[T],A,E,L)}throw TypeError("val must be string, number or Buffer")}function UY(_,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 $=!0;for(var G=0;G<H;G++)if(Z(_,Y+G)!==Z(T,G)){$=!1;break}if($)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 VY(this,T,A,E,!0)};B.prototype.lastIndexOf=function(T,A,E){return VY(this,T,A,E,!1)};function TI(_,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(mE(H))return X;_[A+X]=H}return X}function AI(_,T,A,E){return bA(fE(T,_.length-A),_,A,E)}function EI(_,T,A,E){return bA(WI(T),_,A,E)}function LI(_,T,A,E){return bA(RY(T),_,A,E)}function JI(_,T,A,E){return bA(NI(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 TI(this,T,A,E);case"utf8":case"utf-8":return AI(this,T,A,E);case"ascii":case"latin1":case"binary":return EI(this,T,A,E);case"base64":return LI(this,T,A,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return JI(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 XI(_,T,A){if(T===0&&A===_.length)return vE.fromByteArray(_);else return vE.fromByteArray(_.slice(T,A))}function zY(_,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,$;switch(H){case 1:if(J<128)X=J;break;case 2:if(Z=_[L+1],(Z&192)===128){if($=(J&31)<<6|Z&63,$>127)X=$}break;case 3:if(Z=_[L+1],Y=_[L+2],(Z&192)===128&&(Y&192)===128){if($=(J&15)<<12|(Z&63)<<6|Y&63,$>2047&&($<55296||$>57343))X=$}break;case 4:if(Z=_[L+1],Y=_[L+2],K=_[L+3],(Z&192)===128&&(Y&192)===128&&(K&192)===128){if($=(J&15)<<18|(Z&63)<<12|(Y&63)<<6|K&63,$>65535&&$<1114112)X=$}}}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 HI(E)}var WY=4096;function HI(_){var T=_.length;if(T<=WY)return String.fromCharCode.apply(String,_);var A="",E=0;while(E<T)A+=String.fromCharCode.apply(String,_.slice(E,E+=WY));return A}function ZI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]&127);return E}function YI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]);return E}function KI(_,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+=QI[_[J]];return L}function $I(_,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 FY(_,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 CY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)FY(_,T,A,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return J4.write(_,T,A,E,23,4),A+4}B.prototype.writeFloatLE=function(T,A,E){return CY(this,T,A,!0,E)};B.prototype.writeFloatBE=function(T,A,E){return CY(this,T,A,!1,E)};function OY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)FY(_,T,A,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return J4.write(_,T,A,E,52,8),A+8}B.prototype.writeDoubleLE=function(T,A,E){return OY(this,T,A,!0,E)};B.prototype.writeDoubleBE=function(T,A,E){return OY(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 GI=/[^+/0-9A-Za-z-_]/g;function UI(_){if(_=_.split("=")[0],_=_.trim().replace(GI,""),_.length<2)return"";while(_.length%4!==0)_=_+"=";return _}function fE(_,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 WI(_){var T=[];for(var A=0;A<_.length;++A)T.push(_.charCodeAt(A)&255);return T}function NI(_,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 RY(_){return vE.toByteArray(UI(_))}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 H0(_,T){return _ instanceof T||_!=null&&_.constructor!=null&&_.constructor.name!=null&&_.constructor.name===T.name}function mE(_){return _!==_}var QI=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 xY=W((ib,uE)=>{var qY=JY(),PY=ZY(),gA=CI();function CI(){let _=I("buffer");return _&&_.Buffer?_.Buffer:BY().Buffer}var OI=gA.from("==","base64");function RI(_){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=qY(),X.decode=jY;let L=IY(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=qY(),L=IY(X.uuid,A),J=0;if(T)H=L+`0000000000${J}`.slice(-10);else H=L+J;return J=J+1|0,H}}function IY(_,T){let A=gA.concat([gA.from(PY.parse(_)),OI]).toString("base64");if(T)return A.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"-");return A.replace(/=+$/,"/")}function jY(_,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:PY.unparse(gA.from(L+"==","base64")),count:J}}uE.exports=RI;uE.exports.decode=jY});var yY=W((ab,SY)=>{var DI=$2(),{pipeline:BI}=I("stream"),wY=x0(),qI=FE(),{through:II}=DT(),PI=yA(),jI=xY()();function xI(_){this.cmd="connack",this.returnCode=_.returnCode,this.sessionPresent=_.sessionPresent}function wI(_,T){this.client=_,this.packet=T}var SI=[hI,kI,fI,gI,mI,uI,cE,dI],dE=["","unacceptable protocol version","identifier rejected","Server unavailable","bad user name or password","not authorized","keep alive limit exceeded"];function yI(_,T,A){clearTimeout(_._connectTimer),_._connectTimer=null,_.connecting=!0,_.broker.preConnect(_,T,E);function E(L,J){if(!L&&J===!0)setImmediate(vI,_,T,A);else _.connecting=!1,A(L)}}function vI(_,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(dE[L]);J.errorCode=L,cE({client:_,returnCode:L,sessionPresent:!1},A.bind(this,J));return}_.id=E||"aedes_"+jI(),_.clean=T.clean,_.version=T.protocolVersion,_._will=T.will,_.broker._series(new wI(_,T),SI,{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 hI(_,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=dE[_.returnCode]}else _.returnCode=5,L=Error(dE[_.returnCode]);L.errorCode=_.returnCode,_.client=A,cE(_,A.close.bind(A,T.bind(this,L)))}}function kI(_,T){if(this.packet.keepalive>0){let A=this.client;A._keepaliveInterval=this.packet.keepalive*1500+1,A._keepaliveTimer=DI(function(){A.broker.emit("keepaliveTimeout",A),A.emit("error",Error("keep alive timeout"))},A._keepaliveInterval)}T()}function fI(_,T){let A=this.client;if(!this.packet.clean){A.broker.persistence.subscriptionsByClient({id:A.id,done:T,arg:_},bI);return}_.sessionPresent=!1,A.broker.persistence.cleanSubscriptions(A,T)}function bI(_,T,A){if(_)return A.done(_);A.arg.subs=T,A.done()}function gI(_,T){if(_.subs){PI(this.client,{subscriptions:_.subs},!0,T),_.sessionPresent=!!_.subs;return}_.sessionPresent=!1,T()}function mI(_,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 uI(_,T){let A=this.client;A.broker.registerClient(A),T()}function cE(_,T){let A=_.client||this.client,E=new xI(_);wY(A,E,function(L){if(!L)A.broker.emit("connackSent",E,A),A.connackSent=!0;T(L)})}function dI(_,T){let A=this.client,E=A.broker.persistence,L=E.outgoingStream(A);A.resume(),BI(L,II(function(X,H,Z){let Y=new qI(X,A);Y.writeCallback=(K,$)=>Z(K),E.outgoingUpdate(A,Y,cI)}),T)}function cI(_,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 wY(T,A,E)}SY.exports=yI});var kY=W((ob,hY)=>{var vY=x0();function pI(_){this.cmd="puback",this.messageId=_.messageId}function lI(_){this.cmd="pubrec",this.messageId=_.messageId}var nI=[oI,aI];function iI(_,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(_,nI,T,A)}function aI(_,T){let A=this;switch(_.qos){case 2:A.broker.persistence.incomingStorePacket(A,_,function(E){if(E)return T(E);vY(A,new lI(_),T)});break;case 1:vY(A,new pI(_),function(E){if(E)return T(E);A.broker.publish(_,A,T)});break;case 0:A.broker.publish(_,A,T);break;default:}}function oI(_,T){this.broker.authorizePublish(this,_,T)}hY.exports=iI});var bY=W((rb,fY)=>{function rI(_,T,A){_.broker.persistence.outgoingClearMessageId(_,T,function(L,J){_.broker.emit("ack",J,_),A(L)})}fY.exports=rI});var mY=W((sb,gY)=>{var sI=x0();function tI(_,T){this.client=_,this.packet=T}function eI(_){this.cmd="pubcomp",this.messageId=_.messageId}var _P=[AP,EP,LP,JP];function TP(_,T,A){_.broker._series(new tI(_,T),_P,{},A)}function AP(_,T){this.client.broker.persistence.incomingGetPacket(this.client,this.packet,E);function E(L,J){_.packet=J,T(L)}}function EP(_,T){this.client.broker.publish(_.packet,this.client,T)}function LP(_,T){sI(this.client,new eI(_.packet),T)}function JP(_,T){this.client.broker.persistence.incomingDelPacket(this.client,_.packet,T)}gY.exports=TP});var cY=W((tb,dY)=>{var uY=x0();function XP(_){this.cmd="pubrel",this.messageId=_.messageId}function HP(_,T,A){let E=new XP(T);if(_.clean){uY(_,E,A);return}_.broker.persistence.outgoingUpdate(_,E,L);function L(J){if(J)A(J);else uY(_,E,A)}}dY.exports=HP});var lY=W((eb,pY)=>{var ZP=x0(),YP={cmd:"pingresp"};function KP(_,T,A){_.broker.emit("ping",T,_),ZP(_,YP,A)}pY.exports=KP});var aY=W((_g,iY)=>{var $P=yY(),GP=yA(),UP=OE(),WP=kY(),NP=bY(),QP=mY(),MP=cY(),VP=lY();function zP(_,T,A){if(T.cmd==="connect"){if(_.connecting||_.connected){nY(_.conn,T,A);return}$P(_,T,A);return}if(!_.connecting&&!_.connected){nY(_.conn,T,A);return}switch(T.cmd){case"publish":WP(_,T,A);break;case"subscribe":GP(_,T,!1,A);break;case"unsubscribe":UP(_,T,A);break;case"pubcomp":case"puback":NP(_,T,A);break;case"pubrel":QP(_,T,A);break;case"pubrec":MP(_,T,A);break;case"pingreq":VP(_,T,A);break;case"disconnect":_._disconnected=!0,_.conn.destroy(),A();return;default:_.conn.destroy(),A();return}if(_._keepaliveInterval>0)_._keepaliveTimer.reschedule(_._keepaliveInterval)}function nY(_,T,A){_.destroy();let E=Error("Invalid protocol");E.info=T,A(E)}iY.exports=zP});var AK=W((Tg,TK)=>{var FP=wA(),CP=I("events"),OP=I("util"),RP=cZ(),rY=uT(),sY=x0(),DP=FE(),BP=yA(),tY=OE(),eY=aY(),{pipeline:qP}=I("stream"),{through:IP}=DT();TK.exports=Z0;function Z0(_,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=FP.parser(),this._parser.client=this,this._parser._queue=[],this._parser.on("packet",xP),this.once("connected",wP);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",_K),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=RP(this.conn,this.close.bind(this));let J=(X)=>{if(X.clientId===E.id&&X.nl)return;return PP(E,X)&&E.broker.authorizeForward(E,X)};this.deliver0=function(H,Z){let Y=J(H);if(Y)setImmediate(()=>{let K=new rY(Y,_);K.qos=0,sY(E,K,function($){E._onError($),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 DP(Y,E),$=E.subscriptions[K.topic];if($&&($.qos||0)<K.qos)K.qos=$.qos;if(K.writeCallback=Z,E.clean||K.retain)oY(null,E,K);else _.persistence.outgoingUpdate(E,K,oY)});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 PP(_,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 oY(_,T,A){if(_)T.emit("error",_),A.writeCallback();else sY(T,A,function(E){if(E)T.emit("error",E);A.writeCallback()})}function jP(_){_.callback()}function _K(_){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(jP),this.broker.emit(this.id?"clientError":"connectionError",this,_),this.close()}OP.inherits(Z0,CP);Z0.prototype._onError=_K;Z0.prototype.publish=function(_,T){let A=new rY(_,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)};Z0.prototype.subscribe=function(_,T){if(!_.subscriptions){if(!Array.isArray(_))_=[_];_={subscriptions:_}}BP(this,_,!1,T)};Z0.prototype.unsubscribe=function(_,T){if(!_.unsubscriptions){if(!Array.isArray(_))_=[_];_={unsubscriptions:_}}tY(this,_,T)};Z0.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,tY(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")_()}};Z0.prototype.pause=function(){this._paused=!0};Z0.prototype.resume=function(){this._paused=!1,this._nextBatch()};function xP(_){let T=this.client;if(T._parsingBatch++,T.connackSent||T._parsingBatch===1)eY(T,_,T._nextBatch);else if(this._queue.length<T.broker.queueLimit)this._queue.push(_);else this.emit("error",Error("Client queue limit reached"))}function wP(){let _=this._parser._queue;if(_){for(let T=0,A=_.length;T<A;T++)eY(this,_[T],this._nextBatch);this._parser._queue=null}}Z0.prototype.emptyOutgoingQueue=function(_){let T=this,A=T.broker.persistence;function E(L,J,X){A.outgoingClearMessageId(T,L,X)}qP(A.outgoingStream(T),IP(E),_)};function X4(){}});var EK=W((Ag,SP)=>{SP.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 ZK=W((Eg,HK)=>{var yP=I("events"),vP=I("util"),hP=f5(),kP=S9(),{v4:fP}=k7(),bP=k8(),{pipeline:gP}=I("stream"),mP=uT(),uP=l7(),dP=t7(),cP=AK(),{$SYS_PREFIX:Y0,bulk:pP}=DT();HK.exports=Z1.createBroker=Z1;var lP={concurrency:100,heartbeatInterval:60000,connectTimeout:30000,decodeProtocol:null,preConnect:tP,authenticate:eP,authorizePublish:_j,authorizeSubscribe:Tj,authorizeForward:Aj,published:Ej,trustProxy:!1,trustedProxies:[],queueLimit:42,maxClientsIdLength:23,keepaliveLimit:0};function Z1(_){let T=this;if(!(this instanceof Z1))return new Z1(_);_=Object.assign({},lP,_),this.id=_.id||fP(),this.counter=0,this.queueLimit=_.queueLimit,this.connectTimeout=_.connectTimeout,this.keepaliveLimit=_.keepaliveLimit,this.maxClientsIdLength=_.maxClientsIdLength,this.mq=_.mq||dP({concurrency:_.concurrency,matchEmptyLevels:!0}),this.handle=function(K,$){return K.setMaxListeners(_.concurrency*2),new cP(T,K,$)},this.persistence=_.persistence||uP(),this.persistence.broker=this,this._parallel=hP(),this._series=kP(),this._enqueuers=bP(iP),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=Y0+T.id+"/heartbeat",E=Y0+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),gP(T.persistence.streamWill(T.brokers),pP(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(G){if(G)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(Y0+"+/heartbeat",function(K,$){T.brokers[K.payload.toString()]=Date.now(),$()}),this.mq.on(Y0+"+/birth",function(K,$){let G=K.payload.toString();if(G!==T.id)for(let U in T.clients)delete T.clients[U].duplicates[G];$()}),this.mq.on(Y0+"+/new/clients",function(K,$){let G=K.topic.split("/")[1],U=K.payload.toString();if(T.clients[U]&&G!==T.id)if(T.clients[U].closed)T.deleteClient(U),$();else T.clients[U].close($);else $()}),this.connectedClients=0,this.closed=!1}vP.inherits(Z1,yP);function LK(_,T){if(_.retain)this.broker.persistence.storeRetained(_,T);else T()}function JK(_,T){if(this.client)_.clientId=this.client.id;this.broker.mq.emit(_,T)}function nP(_,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 iP(){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(Y0)===0)E=E.filter(aP);let{packet:J,complete:X}=_;_.packet=null,_.complete=null,_.topic=null,L.persistence.outgoingEnqueueCombi(E,J,X),L._enqueuers.release(_)}}function aP(_){let T=_.topic.charCodeAt(0);return T!==43&&T!==35}function XK(_,T){this.broker.published(this.packet,this.client,T),this.broker.emit("publish",this.packet,this.client)}var oP=[LK,JK,XK],rP=[LK,nP,JK,XK];Z1.prototype.publish=function(_,T,A){if(typeof T==="function")A=T,T=null;let E=new mP(_,this),L=E.qos>0?rP:oP;this._series(new Lj(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:Y0+this.id+"/new/clients",payload:Buffer.from(_.id,"utf8")},s4)};Z1.prototype.unregisterClient=function(_){this.deleteClient(_.id),this.emit("clientDisconnect",_),this.publish({topic:Y0+this.id+"/disconnect/clients",payload:Buffer.from(_.id,"utf8")},s4)};Z1.prototype.deleteClient=function(_){this.connectedClients--,delete this.clients[_]};function sP(_,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,sP,Object.keys(this.clients),A);function A(){T.emit("closed"),T.mq.close(_)}};Z1.prototype.version=EK().version;function tP(_,T,A){A(null,!0)}function eP(_,T,A,E){E(null,!0)}function _j(_,T,A){if(T.topic.startsWith(Y0))return A(Error(Y0+" topic is reserved"));A(null)}function Tj(_,T,A){A(null,T)}function Aj(_,T){return T}function Ej(_,T,A){A(null)}function Lj(_,T,A){this.broker=_,this.client=T,this.packet=A}function s4(){}});var GK=W((Gg,$K)=>{$K.exports=Xj;function H4(_){if(_ instanceof Buffer)return Buffer.from(_);return new _.constructor(_.buffer.slice(),_.byteOffset,_.length)}function Xj(_){if(_=_||{},_.circles)return Hj(_);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 $=Z[K],G=X[$];if(typeof G!=="object"||G===null)Y[$]=G;else if(G.constructor!==Object&&(A=T.get(G.constructor)))Y[$]=A(G,H);else if(ArrayBuffer.isView(G))Y[$]=H4(G);else Y[$]=H(G)}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 Hj(_){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),$=Array(K.length);for(let G=0;G<K.length;G++){let U=K[G],V=Z[U];if(typeof V!=="object"||V===null)$[U]=V;else if(V.constructor!==Object&&(L=E.get(V.constructor)))$[U]=L(V,Y);else if(ArrayBuffer.isView(V))$[U]=H4(V);else{let N=T.indexOf(V);if(N!==-1)$[U]=A[N];else $[U]=Y(V)}}return $}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 $=Z[K];if(typeof $!=="object"||$===null)Y[K]=$;else if($.constructor!==Object&&(L=E.get($.constructor)))Y[K]=L($,X);else if(ArrayBuffer.isView($))Y[K]=H4($);else{let G=T.indexOf($);if(G!==-1)Y[K]=A[G];else Y[K]=X($)}}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 $=Z[K];if(typeof $!=="object"||$===null)Y[K]=$;else if($.constructor!==Object&&(L=E.get($.constructor)))Y[K]=L($,H);else if(ArrayBuffer.isView($))Y[K]=H4($);else{let G=T.indexOf($);if(G!==-1)Y[K]=A[G];else Y[K]=H($)}}return T.pop(),A.pop(),Y}}});var WK=W((Ug,UK)=>{UK.exports=GK()()});var MK=W((QK)=>{Object.defineProperty(QK,"__esModule",{value:!0});QK.validateTopic=NK;QK.validateTopics=Zj;function NK(_){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 Zj(_){if(_.length===0)return"empty_topic_list";for(let T=0;T<_.length;T++)if(!NK(_[T]))return _[T];return null}});var pE=W((zK)=>{Object.defineProperty(zK,"__esModule",{value:!0});var $j=n0(),Gj={objectMode:!0},Uj={clean:!0};class VK{options;_inflights;constructor(_){this.options=_||{},this.options={...Uj,..._},this._inflights=new Map}put(_,T){if(this._inflights.set(_.messageId,_),T)T();return this}createStream(){let _=new $j.Readable(Gj),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(_)_()}}zK.default=VK});var OK=W((CK)=>{Object.defineProperty(CK,"__esModule",{value:!0});var FK=[0,16,128,131,135,144,145,151,153],Nj=(_,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(FK.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(FK.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}};CK.default=Nj});var RK=W((Mg,Mj)=>{Mj.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 qT=W((DK)=>{Object.defineProperty(DK,"__esModule",{value:!0});DK.MQTTJS_VERSION=DK.nextTick=DK.ErrorWithSubackPacket=DK.ErrorWithReasonCode=void 0;DK.applyMixin=Vj;class lE extends Error{code;constructor(_,T){super(_);this.code=T,Object.setPrototypeOf(this,lE.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}DK.ErrorWithReasonCode=lE;class nE extends Error{packet;constructor(_,T){super(_);this.packet=T,Object.setPrototypeOf(this,nE.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}DK.ErrorWithSubackPacket=nE;function Vj(_,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))}DK.nextTick=typeof process?.nextTick==="function"?process.nextTick:(_)=>{setTimeout(_,0)};DK.MQTTJS_VERSION=RK().version});var e4=W((IK)=>{Object.defineProperty(IK,"__esModule",{value:!0});IK.ReasonCodes=void 0;var qK=qT();IK.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 Rj=(_,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 qK.ErrorWithReasonCode(`Publish error: ${IK.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 qK.ErrorWithReasonCode(`Publish error: ${IK.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: ${IK.ReasonCodes[Y]}`),X.code=Y;let K=_.messageIdToTopic[A];if(K)K.forEach(($)=>{delete _._resubscribeTopics[$]})}}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")};IK.default=Rj});var xK=W((jK)=>{Object.defineProperty(jK,"__esModule",{value:!0});var PK=qT(),Bj=e4(),qj=(_,T)=>{let{options:A}=_,E=A.protocolVersion,L=E===5?T.reasonCode:T.returnCode;if(E!==5){let J=new PK.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 PK.ErrorWithReasonCode(`Connection refused: ${Bj.ReasonCodes[L]}`,L);_.emit("error",H)}})};jK.default=qj});var fK=W((hK)=>{Object.defineProperty(hK,"__esModule",{value:!0});hK.LRUCache=void 0;var Z4=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,SK=new Set,iE=typeof process==="object"&&!!process?process:{},yK=(_,T,A,E)=>{typeof iE.emitWarning==="function"?iE.emitWarning(_,T,A,E):console.error(`[${A}] ${T}: ${_}`)},uA=globalThis.AbortController,wK=globalThis.AbortSignal;if(typeof uA>"u"){wK=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(E,L){this._onabort.push(L)}},uA=class{constructor(){T()}signal=new wK;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 _=iE.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",T=()=>{if(!_)return;_=!1,yK("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 Pj=(_)=>!SK.has(_),Cg=Symbol("type"),s0=(_)=>_&&_===Math.floor(_)&&_>0&&isFinite(_),vK=(_)=>!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=vK(_);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 aE{#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;#_;#G;#Q;#$;#H;#F;#Z;#C;#O;#M;#R;#P;#U;static unsafeExposeInternals(_){return{starts:_.#O,ttls:_.#M,sizes:_.#C,keyMap:_.#X,keyList:_.#E,valList:_.#_,next:_.#G,prev:_.#Q,get head(){return _.#$},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:$,maxSize:G=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?vK(T):Array;if(!h)throw Error("invalid max value: "+T);if(this.#J=T,this.#L=G,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.#G=new h(T),this.#Q=new h(T),this.#$=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=!!$,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(Pj("LRU_CACHE_UNBOUNDED"))SK.add("LRU_CACHE_UNBOUNDED"),yK("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",aE)}}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.#$)break;else T=this.#Q[T]}}*#B({allowStale:_=this.allowStale}={}){if(this.#A)for(let T=this.#$;;){if(!this.#b(T))break;if(_||!this.#V(T))yield T;if(T===this.#H)break;else T=this.#G[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.#G[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 $=this.#_[K];if(T!==$){if(this.#P&&this.#T($)){$.__abortController.abort(Error("replaced"));let{__staleWhileFetching:G}=$;if(G!==void 0&&!J){if(this.#R)this.#Y?.(G,_,"set");if(this.#U)this.#Z?.push([G,_,"set"])}}else if(!J){if(this.#R)this.#Y?.($,_,"set");if(this.#U)this.#Z?.push([$,_,"set"])}if(this.#x(K),this.#S(K,Y,H),this.#_[K]=T,H){H.set="replace";let G=$&&this.#T($)?$.__staleWhileFetching:$;if(G!==void 0)H.oldValue=G}}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 $=this.#Z,G;while(G=$?.shift())this.#K?.(...G)}return this}pop(){try{while(this.#A){let _=this.#_[this.#$];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.#$,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.#$=this.#H=0,this.#F.length=0;else this.#$=this.#G[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=G;if(this.#_[T]===G)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=G;if(this.#_[T]===G){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},$=(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 G=new Promise($).then(Z,Y),U=Object.assign(G,{__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:$=this.allowStaleOnFetchRejection,ignoreFetchAbort:G=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:$,allowStaleOnFetchAbort:U,ignoreFetchAbort:G,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.#G[_]=T}#w(_){if(_!==this.#H){if(_===this.#$)this.#$=this.#G[_];else this.#g(this.#Q[_],this.#G[_]);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.#$)this.#$=this.#G[E];else{let J=this.#Q[E];this.#G[J]=this.#G[E];let X=this.#G[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.#$=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)}}}hK.LRUCache=aE});var K0=W((mK)=>{Object.defineProperty(mK,"t",{value:!0});mK.ContainerIterator=mK.Container=mK.Base=void 0;class bK{constructor(_=0){this.iteratorType=_}equals(_){return this.o===_.o}}mK.ContainerIterator=bK;class oE{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}}mK.Base=oE;class gK extends oE{}mK.Container=gK});var lK=W((cK)=>{Object.defineProperty(cK,"t",{value:!0});cK.default=void 0;var wj=K0();class dK extends wj.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 Sj=dK;cK.default=Sj});var oK=W((iK)=>{Object.defineProperty(iK,"t",{value:!0});iK.default=void 0;var yj=K0();class nK extends yj.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 vj=nK;iK.default=vj});var eK=W((sK)=>{Object.defineProperty(sK,"t",{value:!0});sK.default=void 0;var hj=K0();class rK extends hj.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 kj=rK;sK.default=kj});var dA=W((T3)=>{Object.defineProperty(T3,"t",{value:!0});T3.default=void 0;var fj=K0();class _3 extends fj.Container{}var bj=_3;T3.default=bj});var $0=W((E3)=>{Object.defineProperty(E3,"t",{value:!0});E3.throwIteratorAccessError=gj;function gj(){throw RangeError("Iterator access denied!")}});var rE=W((J3)=>{Object.defineProperty(J3,"t",{value:!0});J3.RandomIterator=void 0;var uj=K0(),cA=$0();class L3 extends uj.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,_)}}J3.RandomIterator=L3});var K3=W((Z3)=>{Object.defineProperty(Z3,"t",{value:!0});Z3.default=void 0;var dj=pj(dA()),cj=rE();function pj(_){return _&&_.t?_:{default:_}}class IT extends cj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new IT(this.o,this.container,this.iteratorType)}}class H3 extends dj.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 IT(0,this)}end(){return new IT(this.i,this)}rBegin(){return new IT(this.i-1,this,1)}rEnd(){return new IT(-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 IT(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 lj=H3;Z3.default=lj});var W3=W((G3)=>{Object.defineProperty(G3,"t",{value:!0});G3.default=void 0;var nj=aj(dA()),ij=K0(),PT=$0();function aj(_){return _&&_.t?_:{default:_}}class jT extends ij.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,PT.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,PT.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,PT.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,PT.throwIteratorAccessError)();return this.o=this.o.L,this}}get pointer(){if(this.o===this.h)(0,PT.throwIteratorAccessError)();return this.o.l}set pointer(_){if(this.o===this.h)(0,PT.throwIteratorAccessError)();this.o.l=_}copy(){return new jT(this.o,this.h,this.container,this.iteratorType)}}class $3 extends nj.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 jT(this.p,this.h,this)}end(){return new jT(this.h,this.h,this)}rBegin(){return new jT(this._,this.h,this,1)}rEnd(){return new jT(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,PT.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 jT(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 oj=$3;G3.default=oj});var V3=W((Q3)=>{Object.defineProperty(Q3,"t",{value:!0});Q3.default=void 0;var rj=tj(dA()),sj=rE();function tj(_){return _&&_.t?_:{default:_}}class xT extends sj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new xT(this.o,this.container,this.iteratorType)}}class N3 extends rj.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 xT(0,this)}end(){return new xT(this.i,this)}rBegin(){return new xT(this.i-1,this,1)}rEnd(){return new xT(-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 xT(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 ej=N3;Q3.default=ej});var O3=W((F3)=>{Object.defineProperty(F3,"t",{value:!0});F3.TreeNodeEnableIndex=F3.TreeNode=void 0;class sE{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}}F3.TreeNode=sE;class z3 extends sE{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}}F3.TreeNodeEnableIndex=z3});var tE=W((q3)=>{Object.defineProperty(q3,"t",{value:!0});q3.default=void 0;var R3=O3(),Tx=K0(),D3=$0();class B3 extends Tx.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=R3.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=R3.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(),$=this.v(K.u,_);if($===0){K.l=T;return}else if($<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,D3.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,D3.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 Ax=B3;q3.default=Ax});var eE=W((j3)=>{Object.defineProperty(j3,"t",{value:!0});j3.default=void 0;var Ex=K0(),pA=$0();class P3 extends Ex.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 Lx=P3;j3.default=Lx});var h3=W((y3)=>{Object.defineProperty(y3,"t",{value:!0});y3.default=void 0;var Jx=w3(tE()),Xx=w3(eE()),Hx=$0();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)();return this.o.u}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.insert(L)})}*K(_){if(_===void 0)return;yield*this.K(_.U),yield _.u,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(){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 p1(T,this.h,this)}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)}union(_){let T=this;return _.forEach(function(A){T.insert(A)}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var Zx=S3;y3.default=Zx});var m3=W((b3)=>{Object.defineProperty(b3,"t",{value:!0});b3.default=void 0;var Yx=k3(tE()),Kx=k3(eE()),$x=$0();function k3(_){return _&&_.t?_:{default:_}}class l1 extends Kx.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,$x.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 l1(this.o,this.h,this.container,this.iteratorType)}}class f3 extends Yx.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 l1(this.h.U||this.h,this.h,this)}end(){return new l1(this.h,this.h,this)}rBegin(){return new l1(this.h.W||this.h,this.h,this,1)}rEnd(){return new l1(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 l1(T,this.h,this)}upperBound(_){let T=this.Z(this.Y,_);return new l1(T,this.h,this)}reverseLowerBound(_){let T=this.$(this.Y,_);return new l1(T,this.h,this)}reverseUpperBound(_){let T=this.rr(this.Y,_);return new l1(T,this.h,this)}setElement(_,T,A){return this.M(_,T,A)}find(_){let T=this.I(this.Y,_);return new l1(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 Gx=f3;b3.default=Gx});var _L=W((u3)=>{Object.defineProperty(u3,"t",{value:!0});u3.default=Ux;function Ux(_){let T=typeof _;return T==="object"&&_!==null||T==="function"}});var AL=W((l3)=>{Object.defineProperty(l3,"t",{value:!0});l3.HashContainerIterator=l3.HashContainer=void 0;var d3=K0(),TL=Nx(_L()),T8=$0();function Nx(_){return _&&_.t?_:{default:_}}class c3 extends d3.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}}}l3.HashContainerIterator=c3;class p3 extends d3.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,TL.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,TL.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,TL.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}}l3.HashContainer=p3});var s3=W((o3)=>{Object.defineProperty(o3,"t",{value:!0});o3.default=void 0;var i3=AL(),Mx=$0();class wT extends i3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Mx.throwIteratorAccessError)();return this.o.u}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.insert(A)})}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(){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 wT(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 Vx=a3;o3.default=Vx});var A$=W((_$)=>{Object.defineProperty(_$,"t",{value:!0});_$.default=void 0;var t3=AL(),zx=Cx(_L()),Fx=$0();function Cx(_){return _&&_.t?_:{default:_}}class ST extends t3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Fx.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 ST(this.o,this.h,this.container,this.iteratorType)}}class e3 extends t3.HashContainer{constructor(_=[]){super();let T=this;_.forEach(function(A){T.setElement(A[0],A[1])})}begin(){return new ST(this.p,this.h,this)}end(){return new ST(this.h,this.h,this)}rBegin(){return new ST(this._,this.h,this,1)}rEnd(){return new ST(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,zx.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 ST(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 Ox=e3;_$.default=Ox});var E$=W((q1)=>{Object.defineProperty(q1,"t",{value:!0});Object.defineProperty(q1,"Deque",{enumerable:!0,get:function(){return Px.default}});Object.defineProperty(q1,"HashMap",{enumerable:!0,get:function(){return yx.default}});Object.defineProperty(q1,"HashSet",{enumerable:!0,get:function(){return Sx.default}});Object.defineProperty(q1,"LinkList",{enumerable:!0,get:function(){return Ix.default}});Object.defineProperty(q1,"OrderedMap",{enumerable:!0,get:function(){return xx.default}});Object.defineProperty(q1,"OrderedSet",{enumerable:!0,get:function(){return jx.default}});Object.defineProperty(q1,"PriorityQueue",{enumerable:!0,get:function(){return Bx.default}});Object.defineProperty(q1,"Queue",{enumerable:!0,get:function(){return Dx.default}});Object.defineProperty(q1,"Stack",{enumerable:!0,get:function(){return Rx.default}});Object.defineProperty(q1,"Vector",{enumerable:!0,get:function(){return qx.default}});var Rx=G0(lK()),Dx=G0(oK()),Bx=G0(eK()),qx=G0(K3()),Ix=G0(W3()),Px=G0(V3()),jx=G0(h3()),xx=G0(m3()),Sx=G0(s3()),yx=G0(A$());function G0(_){return _&&_.t?_:{default:_}}});var J$=W((cg,L$)=>{var vx=E$().OrderedSet,U0=d1()("number-allocator:trace"),hx=d1()("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 W0(_,T){if(!(this instanceof W0))return new W0(_,T);this.min=_,this.max=T,this.ss=new vx([],(A,E)=>{return A.compare(E)}),U0("Create"),this.clear()}W0.prototype.firstVacant=function(){if(this.ss.size()===0)return null;return this.ss.front().low};W0.prototype.alloc=function(){if(this.ss.size()===0)return U0("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 U0("alloc():"+E),E};W0.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),U0("use():"+_),!0;if(E>_)return!1;if(E===_)return this.ss.updateKeyByIterator(A,new e_(E+1,L)),U0("use():"+_),!0;if(L===_)return this.ss.updateKeyByIterator(A,new e_(E,L-1)),U0("use():"+_),!0;return this.ss.updateKeyByIterator(A,new e_(_+1,L)),this.ss.insert(new e_(E,_-1)),U0("use():"+_),!0}return U0("use():failed"),!1};W0.prototype.free=function(_){if(_<this.min||_>this.max){hx("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)}U0("free():"+_)};W0.prototype.clear=function(){U0("clear()"),this.ss.clear(),this.ss.insert(new e_(this.min,this.max))};W0.prototype.intervalCount=function(){return this.ss.size()};W0.prototype.dump=function(){console.log("length:"+this.ss.size());for(let _ of this.ss)console.log(_)};L$.exports=W0});var EL=W((fx,X$)=>{var kx=J$();fx.NumberAllocator=kx});var Y$=W((Z$)=>{Object.defineProperty(Z$,"__esModule",{value:!0});var gx=fK(),mx=EL();class H${aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(_){if(_>0)this.aliasToTopic=new gx.LRUCache({max:_}),this.topicToAlias={},this.numberAllocator=new mx.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]}}Z$.default=H$});var K$=W((A8)=>{var dx=A8&&A8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(A8,"__esModule",{value:!0});var cx=e4(),px=dx(Y$()),lx=qT(),nx=(_,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 px.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 lx.ErrorWithReasonCode(`Connection refused: ${cx.ReasonCodes[L]}`,L);if(_.emit("error",J),_.options.reconnectOnConnackError)_._cleanUp(!0)}};A8.default=nx});var G$=W(($$)=>{Object.defineProperty($$,"__esModule",{value:!0});var ix=(_,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)})};$$.default=ix});var U$=W((E8)=>{var L8=E8&&E8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(E8,"__esModule",{value:!0});var ox=L8(OK()),rx=L8(xK()),sx=L8(K$()),tx=L8(e4()),ex=L8(G$()),_w=(_,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,ox.default)(_,T,A);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":_.reschedulePing(),(0,tx.default)(_,T),A();break;case"pubrel":_.reschedulePing(),(0,ex.default)(_,T,A);break;case"connack":(0,sx.default)(_,T),A();break;case"auth":_.reschedulePing(),(0,rx.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=_w});var LL=W((N$)=>{Object.defineProperty(N$,"__esModule",{value:!0});class W${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(){}}N$.default=W$});var V$=W((M$)=>{Object.defineProperty(M$,"__esModule",{value:!0});class Q${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={}}}M$.default=Q$});var z$=W((K4)=>{var Ew=K4&&K4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(K4,"__esModule",{value:!0});K4.TypedEventEmitter=void 0;var Lw=Ew(I("events")),Jw=qT();class JL{}K4.TypedEventEmitter=JL;(0,Jw.applyMixin)(JL,Lw.default)});var J8=W((sg,y0)=>{function XL(_){return y0.exports=XL=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},y0.exports.__esModule=!0,y0.exports.default=y0.exports,XL(_)}y0.exports=XL,y0.exports.__esModule=!0,y0.exports.default=y0.exports});var C$=W((tg,X8)=>{var F$=J8().default;function Xw(_,T){if(F$(_)!="object"||!_)return _;var A=_[Symbol.toPrimitive];if(A!==void 0){var E=A.call(_,T||"default");if(F$(E)!="object")return E;throw TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(_)}X8.exports=Xw,X8.exports.__esModule=!0,X8.exports.default=X8.exports});var O$=W((eg,H8)=>{var Hw=J8().default,Zw=C$();function Yw(_){var T=Zw(_,"string");return Hw(T)=="symbol"?T:T+""}H8.exports=Yw,H8.exports.__esModule=!0,H8.exports.default=H8.exports});var R$=W((_m,Z8)=>{var Kw=O$();function $w(_,T,A){return(T=Kw(T))in _?Object.defineProperty(_,T,{value:A,enumerable:!0,configurable:!0,writable:!0}):_[T]=A,_}Z8.exports=$w,Z8.exports.__esModule=!0,Z8.exports.default=Z8.exports});var D$=W((Tm,Y8)=>{function Gw(_){if(Array.isArray(_))return _}Y8.exports=Gw,Y8.exports.__esModule=!0,Y8.exports.default=Y8.exports});var B$=W((Am,K8)=>{function Uw(_,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=Uw,K8.exports.__esModule=!0,K8.exports.default=K8.exports});var q$=W((Em,$8)=>{function Ww(_,T){(T==null||T>_.length)&&(T=_.length);for(var A=0,E=Array(T);A<T;A++)E[A]=_[A];return E}$8.exports=Ww,$8.exports.__esModule=!0,$8.exports.default=$8.exports});var P$=W((Lm,G8)=>{var I$=q$();function Nw(_,T){if(_){if(typeof _=="string")return I$(_,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)?I$(_,T):void 0}}G8.exports=Nw,G8.exports.__esModule=!0,G8.exports.default=G8.exports});var j$=W((Jm,U8)=>{function Qw(){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=Qw,U8.exports.__esModule=!0,U8.exports.default=U8.exports});var x$=W((Xm,W8)=>{var Mw=D$(),Vw=B$(),zw=P$(),Fw=j$();function Cw(_,T){return Mw(_)||Vw(_,T)||zw(_,T)||Fw()}W8.exports=Cw,W8.exports.__esModule=!0,W8.exports.default=W8.exports});var y$=W((w$)=>{Object.defineProperty(w$,"__esModule",{value:!0});w$.createAddUniqueNumber=void 0;var Ow=(_)=>{return(T)=>{let A=_(T);return T.add(A),A}};w$.createAddUniqueNumber=Ow});var k$=W((v$)=>{Object.defineProperty(v$,"__esModule",{value:!0});v$.createCache=void 0;var Rw=(_)=>{return(T,A)=>{return _.set(T,A),A}};v$.createCache=Rw});var d$=W((m$)=>{Object.defineProperty(m$,"__esModule",{value:!0});m$.createGenerateUniqueNumber=void 0;var f$=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,g$=536870912,b$=g$*2,Dw=(_,T)=>{return(A)=>{let E=T.get(A),L=E===void 0?A.size:E<b$?E+1:0;if(!A.has(L))return _(A,L);if(A.size<g$){while(A.has(L))L=Math.floor(Math.random()*b$);return _(A,L)}if(A.size>f$)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(A.has(L))L=Math.floor(Math.random()*f$);return _(A,L)}};m$.createGenerateUniqueNumber=Dw});var HL=W((p$)=>{Object.defineProperty(p$,"__esModule",{value:!0});p$.generateUniqueNumber=p$.addUniqueNumber=void 0;var Bw=y$(),qw=k$(),Iw=d$(),c$=new WeakMap,Pw=(0,qw.createCache)(c$),jw=p$.generateUniqueNumber=(0,Iw.createGenerateUniqueNumber)(Pw,c$),Km=p$.addUniqueNumber=(0,Bw.createAddUniqueNumber)(jw)});var i$=W((Gm,N8)=>{function n$(_,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 ww(_){return function(){var T=this,A=arguments;return new Promise(function(E,L){var J=_.apply(T,A);function X(Z){n$(J,E,L,X,H,"next",Z)}function H(Z){n$(J,E,L,X,H,"throw",Z)}X(void 0)})}}N8.exports=ww,N8.exports.__esModule=!0,N8.exports.default=N8.exports});var ZL=W((Um,Q8)=>{function Sw(_,T){this.v=_,this.k=T}Q8.exports=Sw,Q8.exports.__esModule=!0,Q8.exports.default=Q8.exports});var YL=W((Wm,v0)=>{function lA(_,T,A,E){var L=Object.defineProperty;try{L({},"",{})}catch(J){L=0}v0.exports=lA=function(X,H,Z,Y){function K($,G){lA(X,$,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))},v0.exports.__esModule=!0,v0.exports.default=v0.exports,lA(_,T,A,E)}v0.exports=lA,v0.exports.__esModule=!0,v0.exports.default=v0.exports});var KL=W((Nm,h0)=>{var N0=YL();function a$(){/*! 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 N0(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_,I_){return h=M_,b=0,l=_,B_.n=I_,X}};function C_(K_,M_){for(b=K_,l=M_,T=0;!c_&&c&&!I_&&T<W_.length;T++){var I_,j_=W_[T],R0=B_.p,y1=j_[2];K_>3?(I_=y1===M_)&&(l=j_[(b=j_[4])?5:(b=3,3)],j_[4]=j_[5]=_):j_[0]<=R0&&((I_=K_<2&&R0<j_[1])?(b=0,B_.v=M_,B_.n=j_[1]):R0<y1&&(I_=K_<3||j_[0]>M_||M_>y1)&&(j_[4]=K_,j_[5]=M_,B_.n=y1,b=0))}if(I_||K_>1)return X;throw c_=!0,M_}return function(K_,M_,I_){if(c>1)throw TypeError("Generator is already running");for(c_&&M_===1&&C_(M_,I_),b=M_,l=I_;(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(j_){h=_,b=1,l=j_}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]())):(N0(T={},E,function(){return this}),T),$=Y.prototype=H.prototype=Object.create(K);function G(U){return Object.setPrototypeOf?Object.setPrototypeOf(U,Y):(U.__proto__=Y,N0(U,L,"GeneratorFunction")),U.prototype=Object.create($),U}return Z.prototype=Y,N0($,"constructor",Y),N0(Y,"constructor",Z),Z.displayName="GeneratorFunction",N0(Y,L,"GeneratorFunction"),N0($),N0($,L,"Generator"),N0($,E,function(){return this}),N0($,"toString",function(){return"[object Generator]"}),(h0.exports=a$=function(){return{w:J,m:G}},h0.exports.__esModule=!0,h0.exports.default=h0.exports)()}h0.exports=a$,h0.exports.__esModule=!0,h0.exports.default=h0.exports});var UL=W((Qm,M8)=>{var yw=ZL(),$L=YL();function GL(_,T){function A(L,J,X,H){try{var Z=_[L](J),Y=Z.value;return Y instanceof yw?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||($L(GL.prototype),$L(GL.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),$L(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=GL,M8.exports.__esModule=!0,M8.exports.default=M8.exports});var WL=W((Mm,V8)=>{var vw=KL(),hw=UL();function kw(_,T,A,E,L){return new hw(vw().w(_,T,A,E),L||Promise)}V8.exports=kw,V8.exports.__esModule=!0,V8.exports.default=V8.exports});var o$=W((Vm,z8)=>{var fw=WL();function bw(_,T,A,E,L){var J=fw(_,T,A,E,L);return J.next().then(function(X){return X.done?X.value:J.next()})}z8.exports=bw,z8.exports.__esModule=!0,z8.exports.default=z8.exports});var r$=W((zm,F8)=>{function gw(_){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=gw,F8.exports.__esModule=!0,F8.exports.default=F8.exports});var s$=W((Fm,C8)=>{var mw=J8().default;function uw(_){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(mw(_)+" is not iterable")}C8.exports=uw,C8.exports.__esModule=!0,C8.exports.default=C8.exports});var e$=W((Cm,k0)=>{var dw=ZL(),cw=KL(),pw=o$(),lw=WL(),nw=UL(),iw=r$(),t$=s$();function NL(){var _=cw(),T=_.m(NL),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=G,Z(Y.d,t$($),U)},finish:function($){return Z(Y.f,$)}},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(k0.exports=NL=function(){return{wrap:function(Z,Y,K,$){return _.w(J(Z),Y,K,$&&$.reverse())},isGeneratorFunction:E,mark:_.m,awrap:function(Z,Y){return new dw(Z,Y)},AsyncIterator:nw,async:function(Z,Y,K,$,G){return(E(Y)?lw:pw)(J(Z),Y,K,$,G)},keys:iw,values:t$}},k0.exports.__esModule=!0,k0.exports.default=k0.exports)()}k0.exports=NL,k0.exports.__esModule=!0,k0.exports.default=k0.exports});var TG=W((Om,_G)=>{var nA=e$()();_G.exports=nA;try{regeneratorRuntime=nA}catch(_){if(typeof globalThis==="object")globalThis.regeneratorRuntime=nA;else Function("r","regeneratorRuntime = r")(nA)}});var EG=W((iA,AG)=>{(function(_,T){typeof iA==="object"&&typeof AG<"u"?T(iA,R$(),x$(),HL(),i$(),TG()):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 $(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 G(z){for(var Q=1;Q<arguments.length;Q++){var F=arguments[Q]!=null?arguments[Q]:{};Q%2?$(Object(F),!0).forEach(function(R){T(z,R,F[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(z,Object.getOwnPropertyDescriptors(F)):$(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 I_=q.get(M_),j_=I_.reject,R0=I_.resolve;if(q.delete(M_),K_.error===void 0)R0(K_.result);else j_(Error(K_.error.message))}}),X(R))R.start();var f=function(K_){var M_=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,I_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(j_,R0){var y1=E.generateUniqueNumber(q);if(q.set(y1,{reject:R0,resolve:j_}),M_===null)R.postMessage({id:y1,method:K_},I_);else R.postMessage({id:y1,method:K_,params:M_},I_)})},h=function(K_,M_){var I_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];R.postMessage({id:null,method:K_,params:M_},I_)},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=G(G({},b),{},T({},c_,B_({call:f,notify:h})))}return G({},b)}};_.createBroker=N})});var JG=W((aA,LG)=>{(function(_,T){typeof aA==="object"&&typeof LG<"u"?T(aA,J8(),EG(),HL()):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($){if(T(L.get($))==="symbol")L.set($,null),K("clear",{timerId:$,timerType:"interval"}).then(function(){L.delete($)})}},clearTimeout:function(Y){var K=Y.call;return function($){if(T(J.get($))==="symbol")J.set($,null),K("clear",{timerId:$,timerType:"timeout"}).then(function(){J.delete($)})}},setInterval:function(Y){var K=Y.call;return function($){var G=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:G,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($.apply(void 0,V),L.get(Q)===z)F()}})};return F(),Q}},setTimeout:function(Y){var K=Y.call;return function($){var G=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:G,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),$.apply(void 0,V)}),Q}}}),H=function(Y){var K=new Worker(Y);return X(K)};_.load=H,_.wrap=X})});var HG=W((oA,XG)=>{(function(_,T){typeof oA==="object"&&typeof XG<"u"?T(oA,JG()):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,$){var G=null;return function(){if(G!==null)return G;var U=new Blob([$],{type:"application/javascript; charset=utf-8"}),V=URL.createObjectURL(U);return G=K(V),setTimeout(function(){return URL.revokeObjectURL(V)}),G}},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((KG)=>{Object.defineProperty(KG,"__esModule",{value:!0});KG.isReactNativeBrowser=KG.isWebWorker=void 0;var aw=()=>{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},ZG=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),YG=()=>typeof navigator<"u"&&navigator.product==="ReactNative",ow=aw()||ZG()||YG();KG.isWebWorker=ZG();KG.isReactNativeBrowser=YG();KG.default=ow});var NG=W((f0)=>{var tw=f0&&f0.__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]}),ew=f0&&f0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),_S=f0&&f0.__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")tw(A,T,E[L])}return ew(A,T),A}}();Object.defineProperty(f0,"__esModule",{value:!0});var GG=HG(),QL=_S(O8()),UG={set:GG.setInterval,clear:GG.clearInterval},WG={set:(_,T)=>setInterval(_,T),clear:(_)=>clearInterval(_)},TS=(_)=>{switch(_){case"native":return WG;case"worker":return UG;case"auto":default:return QL.default&&!QL.isWebWorker&&!QL.isReactNativeBrowser?UG:WG}};f0.default=TS});var ML=W((R8)=>{var AS=R8&&R8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(R8,"__esModule",{value:!0});var ES=AS(NG());class QG{_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,ES.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=QG});var sA=W((n1)=>{var LS=n1&&n1.__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]}),JS=n1&&n1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),CG=n1&&n1.__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")LS(A,T,E[L])}return JS(A,T),A}}(),t0=n1&&n1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(n1,"__esModule",{value:!0});var VL=t0(wA()),XS=n0(),MG=t0(WK()),HS=t0(d1()),VG=CG(MK()),$4=t0(pE()),ZS=t0(U$()),YS=t0(LL()),KS=t0(V$()),D8=qT(),$S=z$(),GS=t0(ML()),zG=CG(O8()),zL=globalThis.setImmediate||((..._)=>{let T=_.shift();(0,D8.nextTick)(()=>{T(..._)})}),FG={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 $S.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 FG)if(typeof this.options[A]>"u")this.options[A]=FG[A];else this.options[A]=T[A];if(this.log=this.options.log||(0,HS.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",rA.VERSION),zG.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",zG.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)VL.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=_,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new YS.default:this.options.messageIdProvider,this.outgoingStore=T.outgoingStore||new $4.default,this.incomingStore=T.incomingStore||new $4.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 KS.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 XS.Writable,T=VL.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 $4.default,this.outgoingStore=this.options.outgoingStore||new $4.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,ZS.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 $=()=>{let G=0;if(X===1||X===2){if(G=this._nextId(),G===null)return this.log("No messageId left"),!1}let U={cmd:"publish",topic:_,payload:T,qos:X,retain:H,messageId:G,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||!$())this._storeProcessingQueue.push({invoke:$,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=VG.validateTopics(J);if(X!==null)return zL(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 $=(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},G=()=>{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($(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||!G())this._storeProcessingQueue.push({invoke:G,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=VG.validateTopics(_);if(E!==null)return zL(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 $4.default,this.outgoingStore=this.options.outgoingStore||new $4.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),zL(()=>{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,MG.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=VL.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,MG.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 GS.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()})}}n1.default=rA});var DG=W((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});var US=EL();class OG{numberAllocator;lastId;constructor(){this.numberAllocator=new US.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()}}RG.default=OG});var tA=W((PG)=>{Object.defineProperty(PG,"__esModule",{value:!0});PG.BufferedDuplex=void 0;PG.writev=qG;var NS=n0(),BG=I("buffer");function qG(_,T){let A=Array(_.length);for(let E=0;E<_.length;E++)if(typeof _[E].chunk==="string")A[E]=BG.Buffer.from(_[E].chunk,"utf8");else A[E]=_[E].chunk;this._write(BG.Buffer.concat(A),"binary",T)}class IG extends NS.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(_,T,A){super({objectMode:!0});if(this.proxy=T,this.socket=A,this.writeQueue=[],!_.objectMode)this._writev=qG.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)}}}PG.BufferedDuplex=IG});var B8=W((_T)=>{var CL=_T&&_T.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(_T,"__esModule",{value:!0});_T.streamBuilder=_T.browserStreamBuilder=void 0;var eA=I("buffer"),xG=CL(I("ws")),MS=CL(d1()),VS=n0(),zS=CL(O8()),FL=tA(),e0=(0,MS.default)("mqttjs:ws"),FS=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function wG(_,T){let A=`${_.protocol}://${_.hostname}:${_.port}${_.path}`;if(typeof _.transformWsUrl==="function")A=_.transformWsUrl(A,_,T);return A}function SG(_){let T=_;if(!_.port)if(_.protocol==="wss")T.port=443;else T.port=80;if(!_.path)T.path="/";if(!_.wsOptions)T.wsOptions={};if(!zS.default&&!_.forceNativeWebSocket&&_.protocol==="wss")FS.forEach((A)=>{if(Object.prototype.hasOwnProperty.call(_,A)&&!Object.prototype.hasOwnProperty.call(_.wsOptions,A))T.wsOptions[A]=_[A]});return T}function CS(_){let T=SG(_);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 OS(_,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 xG.default(T,[E],A.wsOptions);return L}function RS(_,T){let A=T.protocolId==="MQIsdp"&&T.protocolVersion===3?"mqttv3.1":"mqtt",E=wG(T,_),L;if(T.createWebsocket)L=T.createWebsocket(E,[A],T);else L=new WebSocket(E,[A]);return L.binaryType="arraybuffer",L}var DS=(_,T)=>{e0("streamBuilder");let A=SG(T);A.hostname=A.hostname||A.host||"localhost";let E=wG(A,_),L=OS(_,E,A),J=xG.default.createWebSocketStream(L,A.wsOptions);return J.url=E,L.on("close",()=>{J.destroy()}),J};_T.streamBuilder=DS;var BS=(_,T)=>{e0("browserStreamBuilder");let A,L=CS(T).browserBufferSize||524288,J=T.browserBufferTimeout||1000,X=!T.objectMode,H=RS(_,T),Z=K(T,N,z);if(!T.objectMode)Z._writev=FL.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 FL.BufferedDuplex(T,Z,H),Y)H.addEventListener("open",$);else H.onopen=$;if(Y)H.addEventListener("close",G),H.addEventListener("error",U),H.addEventListener("message",V);else H.onclose=G,H.onerror=U,H.onmessage=V;function K(Q,F,R){let q=new VS.Transform({objectMode:Q.objectMode});return q._write=F,q._flush=R,q}function $(){if(e0("WebSocket onOpen"),A instanceof FL.BufferedDuplex)A.socketReady()}function G(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=BS});var fG=W((kG)=>{Object.defineProperty(kG,"__esModule",{value:!0});var yG=I("buffer"),yT={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."};kG.ERRORS=yT;function qS(_){if(!yG.Buffer.isEncoding(_))throw Error(yT.INVALID_ENCODING)}kG.checkEncoding=qS;function vG(_){return typeof _==="number"&&isFinite(_)&&xS(_)}kG.isFiniteInteger=vG;function hG(_,T){if(typeof _==="number"){if(!vG(_)||_<0)throw Error(T?yT.INVALID_OFFSET:yT.INVALID_LENGTH)}else throw Error(T?yT.INVALID_OFFSET_NON_NUMBER:yT.INVALID_LENGTH_NON_NUMBER)}function IS(_){hG(_,!1)}kG.checkLengthValue=IS;function PS(_){hG(_,!0)}kG.checkOffsetValue=PS;function jS(_,T){if(_<0||_>T.length)throw Error(yT.INVALID_TARGET_OFFSET)}kG.checkTargetOffset=jS;function xS(_){return typeof _==="number"&&isFinite(_)&&Math.floor(_)===_}function wS(_){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof yG.Buffer.prototype[_]>"u")throw Error(`Platform does not support Buffer.prototype.${_}.`)}kG.bigIntAndBufferInt64Check=wS});var mG=W((gG)=>{Object.defineProperty(gG,"__esModule",{value:!0});var t=fG(),bG=4096,gS="utf8";class OL{constructor(_){if(this.length=0,this._encoding=gS,this._writeOffset=0,this._readOffset=0,OL.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(bG)}else{if(typeof _<"u")throw Error(t.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(bG)}}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}}gG.SmartBuffer=OL});var RL=W((iG)=>{Object.defineProperty(iG,"__esModule",{value:!0});iG.SOCKS5_NO_ACCEPTABLE_AUTH=iG.SOCKS5_CUSTOM_AUTH_END=iG.SOCKS5_CUSTOM_AUTH_START=iG.SOCKS_INCOMING_PACKET_SIZES=iG.SocksClientState=iG.Socks5Response=iG.Socks5HostType=iG.Socks5Auth=iG.Socks4Response=iG.SocksCommand=iG.ERRORS=iG.DEFAULT_TIMEOUT=void 0;var uS=30000;iG.DEFAULT_TIMEOUT=uS;var dS={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"};iG.ERRORS=dS;var cS={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(_)=>_+7,Socks4Response:8};iG.SOCKS_INCOMING_PACKET_SIZES=cS;var uG;(function(_){_[_.connect=1]="connect",_[_.bind=2]="bind",_[_.associate=3]="associate"})(uG||(iG.SocksCommand=uG={}));var dG;(function(_){_[_.Granted=90]="Granted",_[_.Failed=91]="Failed",_[_.Rejected=92]="Rejected",_[_.RejectedIdent=93]="RejectedIdent"})(dG||(iG.Socks4Response=dG={}));var cG;(function(_){_[_.NoAuth=0]="NoAuth",_[_.GSSApi=1]="GSSApi",_[_.UserPass=2]="UserPass"})(cG||(iG.Socks5Auth=cG={}));var pS=128;iG.SOCKS5_CUSTOM_AUTH_START=pS;var lS=254;iG.SOCKS5_CUSTOM_AUTH_END=lS;var nS=255;iG.SOCKS5_NO_ACCEPTABLE_AUTH=nS;var pG;(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"})(pG||(iG.Socks5Response=pG={}));var lG;(function(_){_[_.IPv4=1]="IPv4",_[_.Hostname=3]="Hostname",_[_.IPv6=4]="IPv6"})(lG||(iG.Socks5HostType=lG={}));var nG;(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"})(nG||(iG.SocksClientState=nG={}))});var DL=W((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});rG.shuffleArray=rG.SocksClientError=void 0;class oG extends Error{constructor(_,T){super(_);this.options=T}}rG.SocksClientError=oG;function Ly(_){for(let T=_.length-1;T>0;T--){let A=Math.floor(Math.random()*(T+1));[_[T],_[A]]=[_[A],_[T]]}}rG.shuffleArray=Ly});var _5=W((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});eG.isInSubnet=Xy;eG.isCorrect=Hy;eG.numberToPaddedHex=tG;eG.stringToPaddedHex=Zy;eG.testBit=Yy;function Xy(_){if(this.subnetMask<_.subnetMask)return!1;if(this.mask(_.subnetMask)===_.mask())return!0;return!1}function Hy(_){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===_&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function tG(_){return _.toString(16).padStart(2,"0")}function Zy(_){return tG(parseInt(_,10))}function Yy(_,T){let{length:A}=_;if(T>A)return!1;let E=A-T;return _.substring(E,E+1)==="1"}});var BL=W((_U)=>{Object.defineProperty(_U,"__esModule",{value:!0});_U.RE_SUBNET_STRING=_U.RE_ADDRESS=_U.GROUPS=_U.BITS=void 0;_U.BITS=32;_U.GROUPS=4;_U.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;_U.RE_SUBNET_STRING=/\/\d{1,2}$/});var T5=W((EU)=>{Object.defineProperty(EU,"__esModule",{value:!0});EU.AddressError=void 0;class AU extends Error{constructor(_,T){super(_);this.name="AddressError",this.parseMessage=T}}EU.AddressError=AU});var qL=W((Q0)=>{var Vy=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]}),zy=Q0&&Q0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),JU=Q0&&Q0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))Vy(T,_,A)}return zy(T,_),T};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.Address4=void 0;var G4=JU(_5()),i1=JU(BL()),q8=T5();class U1{constructor(_){this.groups=i1.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=G4.isCorrect(i1.BITS),this.isInSubnet=G4.isInSubnet,this.address=_;let T=i1.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>i1.BITS)throw new q8.AddressError("Invalid subnet mask.");_=_.replace(i1.RE_SUBNET_STRING,"")}this.addressMinusSuffix=_,this.parsedAddress=this.parse(_)}static isValid(_){try{return new U1(_),!0}catch(T){return!1}}parse(_){let T=_.split(".");if(!_.match(i1.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 U1(A.join("."))}static fromInteger(_){return U1.fromHex(_.toString(16))}static fromArpa(_){let A=_.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new U1(A)}toHex(){return this.parsedAddress.map((_)=>G4.stringToPaddedHex(_)).join(":")}toArray(){return this.parsedAddress.map((_)=>parseInt(_,10))}toGroup6(){let _=[],T;for(T=0;T<i1.GROUPS;T+=2)_.push(`${G4.stringToPaddedHex(this.parsedAddress[T])}${G4.stringToPaddedHex(this.parsedAddress[T+1])}`);return _.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map((_)=>G4.stringToPaddedHex(_)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(i1.BITS-this.subnetMask)}`)}startAddress(){return U1.fromBigInt(this._startAddress())}startAddressExclusive(){let _=BigInt("1");return U1.fromBigInt(this._startAddress()+_)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(i1.BITS-this.subnetMask)}`)}endAddress(){return U1.fromBigInt(this._endAddress())}endAddressExclusive(){let _=BigInt("1");return U1.fromBigInt(this._endAddress()-_)}static fromBigInt(_){return U1.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 U1(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 U1("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(i1.BITS,"0")}groupForV6(){let _=this.parsedAddress;return this.address.replace(i1.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>`)}}Q0.Address4=U1});var IL=W((XU)=>{Object.defineProperty(XU,"__esModule",{value:!0});XU.RE_URL_WITH_PORT=XU.RE_URL=XU.RE_ZONE_STRING=XU.RE_SUBNET_STRING=XU.RE_BAD_ADDRESS=XU.RE_BAD_CHARACTERS=XU.TYPES=XU.SCOPES=XU.GROUPS=XU.BITS=void 0;XU.BITS=128;XU.GROUPS=8;XU.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};XU.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"};XU.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;XU.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;XU.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;XU.RE_ZONE_STRING=/%.*$/;XU.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;XU.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var PL=W((KU)=>{Object.defineProperty(KU,"__esModule",{value:!0});KU.spanAllZeroes=ZU;KU.spanAll=jy;KU.spanLeadingZeroes=xy;KU.simpleGroup=wy;function ZU(_){return _.replace(/(0+)/g,'<span class="zero">$1</span>')}function jy(_,T=0){return _.split("").map((E,L)=>`<span class="digit value-${E} position-${L+T}">${ZU(E)}</span>`).join("")}function YU(_){return _.replace(/^(0+)/,'<span class="zero">$1</span>')}function xy(_){return _.split(":").map((A)=>YU(A)).join(":")}function wy(_,T=0){return _.split(":").map((E,L)=>{if(/group-v4/.test(E))return E;return`<span class="hover-group group-${L+T}">${YU(E)}</span>`})}});var $U=W((Y1)=>{var ky=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]}),fy=Y1&&Y1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),by=Y1&&Y1.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))ky(T,_,A)}return fy(T,_),T};Object.defineProperty(Y1,"__esModule",{value:!0});Y1.ADDRESS_BOUNDARY=void 0;Y1.groupPossibilities=E5;Y1.padGroup=A5;Y1.simpleRegularExpression=my;Y1.possibleElisions=uy;var gy=by(IL());function E5(_){return`(${_.join("|")})`}function A5(_){if(_.length<4)return`0{0,${4-_.length}}${_}`;return _}Y1.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function my(_){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===gy.GROUPS-1?":":"";return E5([A5(L),X])}return A5(L)}).join(":"));return A.push(_.map(A5).join(":")),E5(A)}function uy(_,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 NU=W((M0)=>{var dy=M0&&M0.__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]}),cy=M0&&M0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),X5=M0&&M0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))dy(T,_,A)}return cy(T,_),T};Object.defineProperty(M0,"__esModule",{value:!0});M0.Address6=void 0;var GU=X5(_5()),jL=X5(BL()),N_=X5(IL()),xL=X5(PL()),vT=qL(),hT=$U(),b0=T5(),L5=_5();function J5(_){if(!_)throw Error("Assertion failed.")}function py(_){let T=/(\d+)(\d{3})/;while(T.test(_))_=_.replace(T,"$1,$2");return _}function ly(_){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 ny(_,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 UU(_){return parseInt(_,16).toString(16).padStart(4,"0")}function WU(_){return _&255}class k_{constructor(_,T){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=GU.isInSubnet,this.isCorrect=GU.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 b0.AddressError("Invalid subnet mask.");_=_.replace(N_.RE_SUBNET_STRING,"")}else if(/\//.test(_))throw new b0.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 vT.Address4(_),A=N_.BITS-(jL.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 b0.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 py((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=ny(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(jL.RE_ADDRESS);if(E){this.parsedAddress4=E[0],this.address4=new vT.Address4(this.parsedAddress4);for(let L=0;L<this.address4.groups;L++)if(/^0[0-9]+/.test(this.address4.parsedAddress[L]))throw new b0.AddressError("IPv4 addresses can't have leading zeroes.",_.replace(jL.RE_ADDRESS,this.address4.parsedAddress.map(ly).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 b0.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 b0.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 b0.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 b0.AddressError("Too many :: groups found");if(E=E.map((J)=>parseInt(J,16).toString(16)),E.length!==this.groups)throw new b0.AddressError("Incorrect number of groups found");return E}canonicalForm(){return this.parsedAddress.map(UU).join(":")}decimal(){return this.parsedAddress.map((_)=>parseInt(_,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(UU).join("")}`)}to4(){let _=this.binaryZeroPad().split("");return vT.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=vT.Address4.fromHex(this.getBitsBase16(32,64)),L=this.getBits(96,128),J=vT.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),$=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:$},udpPort:A}}inspect6to4(){let _=this.getBitsBase16(0,16),T=vT.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(WU)}static fromByteArray(_){return this.fromUnsignedByteArray(_.map(WU))}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 xL.simpleGroup(this.address).join(":");J5(typeof this.elidedGroups==="number"),J5(typeof this.elisionBegin==="number");let _=[],[T,A]=this.address.split("::");if(T.length)_.push(...xL.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(...xL.simpleGroup(A,this.elisionEnd));else _.push("");if(this.is4())J5(this.address4 instanceof vT.Address4),_.pop(),_.push(this.address4.groupForV6());return _.join(":")}regularExpressionString(_=!1){let T=[],A=new k_(this.correctForm());if(A.elidedGroups===0)T.push((0,hT.simpleRegularExpression)(A.parsedAddress));else if(A.elidedGroups===N_.GROUPS)T.push((0,hT.possibleElisions)(N_.GROUPS));else{let E=A.address.split("::");if(E[0].length)T.push((0,hT.simpleRegularExpression)(E[0].split(":")));if(J5(typeof A.elidedGroups==="number"),T.push((0,hT.possibleElisions)(A.elidedGroups,E[0].length!==0,E[1].length!==0)),E[1].length)T.push((0,hT.simpleRegularExpression)(E[1].split(":")));T=[T.join(":")]}if(!_)T=["(?=^|",hT.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...T,")(?=[^\\w\\:]|",hT.ADDRESS_BOUNDARY,"|$)"];return T.join("")}regularExpression(_=!1){return new RegExp(this.regularExpressionString(_),"i")}}M0.Address6=k_});var wL=W((a_)=>{var iy=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]}),ay=a_&&a_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),oy=a_&&a_.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))iy(T,_,A)}return ay(T,_),T};Object.defineProperty(a_,"__esModule",{value:!0});a_.v6=a_.AddressError=a_.Address6=a_.Address4=void 0;var ry=qL();Object.defineProperty(a_,"Address4",{enumerable:!0,get:function(){return ry.Address4}});var sy=NU();Object.defineProperty(a_,"Address6",{enumerable:!0,get:function(){return sy.Address6}});var ty=T5();Object.defineProperty(a_,"AddressError",{enumerable:!0,get:function(){return ty.AddressError}});var ey=oy(PL());a_.v6={helpers:ey}});var RU=W((CU)=>{Object.defineProperty(CU,"__esModule",{value:!0});CU.ipToBuffer=CU.int32ToIpv4=CU.ipv4ToInt32=CU.validateSocksClientChainOptions=CU.validateSocksClientOptions=void 0;var _1=DL(),f_=RL(),_v=I("stream"),SL=wL(),QU=I("net");function Tv(_,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(!VU(_.destination))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsDestination,_);if(!zU(_.proxy))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);if(MU(_.proxy,_),_.timeout&&!FU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_);if(_.existing_socket&&!(_.existing_socket instanceof _v.Duplex))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsExistingSocket,_)}CU.validateSocksClientOptions=Tv;function Av(_){if(_.command!=="connect")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommandChain,_);if(!VU(_.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(!zU(T))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);MU(T,_)}),_.timeout&&!FU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_)}CU.validateSocksClientChainOptions=Av;function MU(_,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 VU(_){return _&&typeof _.host==="string"&&Buffer.byteLength(_.host)<256&&typeof _.port==="number"&&_.port>=0&&_.port<=65535}function zU(_){return _&&(typeof _.host==="string"||typeof _.ipaddress==="string")&&typeof _.port==="number"&&_.port>=0&&_.port<=65535&&(_.type===4||_.type===5)}function FU(_){return typeof _==="number"&&_>0}function Ev(_){return new SL.Address4(_).toArray().reduce((A,E)=>(A<<8)+E,0)>>>0}CU.ipv4ToInt32=Ev;function Lv(_){let T=_>>>24&255,A=_>>>16&255,E=_>>>8&255,L=_&255;return[T,A,E,L].join(".")}CU.int32ToIpv4=Lv;function Jv(_){if(QU.isIPv4(_)){let T=new SL.Address4(_);return Buffer.from(T.toArray())}else if(QU.isIPv6(_)){let T=new SL.Address6(_);return Buffer.from(T.canonicalForm().split(":").map((A)=>A.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}CU.ipToBuffer=Jv});var IU=W((BU)=>{Object.defineProperty(BU,"__esModule",{value:!0});BU.ReceiveBuffer=void 0;class DU{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}}BU.ReceiveBuffer=DU});var PU=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($){X($)}}function Z(K){try{Y(E.throw(K))}catch($){X($)}}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 Kv=I("events"),W4=I("net"),K1=mG(),P=RL(),W1=RU(),$v=IU(),vL=DL();Object.defineProperty(TT,"SocksClientError",{enumerable:!0,get:function(){return vL.SocksClientError}});var yL=wL();class H5 extends Kv.EventEmitter{constructor(_){super();this.options=Object.assign({},_),(0,W1.validateSocksClientOptions)(_),this.setState(P.SocksClientState.Created)}static createConnection(_,T){return new Promise((A,E)=>{try{(0,W1.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,W1.validateSocksClientChainOptions)(_)}catch(L){if(typeof T==="function")return T(L),A(L);else return E(L)}if(_.randomizeChain)(0,vL.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(P.Socks5HostType.IPv4),T.writeUInt32BE((0,W1.ipv4ToInt32)(_.remoteHost.host));else if(W4.isIPv6(_.remoteHost.host))T.writeUInt8(P.Socks5HostType.IPv6),T.writeBuffer((0,W1.ipToBuffer)(_.remoteHost.host));else T.writeUInt8(P.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===P.Socks5HostType.IPv4)L=(0,W1.int32ToIpv4)(T.readUInt32BE());else if(E===P.Socks5HostType.IPv6)L=yL.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!==P.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||P.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(P.SocksClientState.Connecting),this.receiveBuffer=new $v.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!==P.SocksClientState.Established&&this.state!==P.SocksClientState.BoundWaitingForConnection)this.closeSocket(P.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){if(this.setState(P.SocksClientState.Connected),this.options.proxy.type===4)this.sendSocks4InitialHandshake();else this.sendSocks5InitialHandshake();this.setState(P.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(_){this.receiveBuffer.append(_),this.processData()}processData(){while(this.state!==P.SocksClientState.Established&&this.state!==P.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize)if(this.state===P.SocksClientState.SentInitialHandshake)if(this.options.proxy.type===4)this.handleSocks4FinalHandshakeResponse();else this.handleInitialSocks5HandshakeResponse();else if(this.state===P.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===P.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===P.SocksClientState.BoundWaitingForConnection)if(this.options.proxy.type===4)this.handleSocks4IncomingConnectionResponse();else this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(P.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(P.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!==P.SocksClientState.Error)this.setState(P.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new vL.SocksClientError(_,this.options))}sendSocks4InitialHandshake(){let _=this.options.proxy.userId||"",T=new K1.SmartBuffer;if(T.writeUInt8(4),T.writeUInt8(P.SocksCommand[this.options.command]),T.writeUInt16BE(this.options.destination.port),W4.isIPv4(this.options.destination.host))T.writeBuffer((0,W1.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=P.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(T.toBuffer())}handleSocks4FinalHandshakeResponse(){let _=this.receiveBuffer.get(8);if(_[1]!==P.Socks4Response.Granted)this.closeSocket(`${P.ERRORS.Socks4ProxyRejectedConnection} - (${P.Socks4Response[_[1]]})`);else if(P.SocksCommand[this.options.command]===P.SocksCommand.bind){let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A={port:T.readUInt16BE(),host:(0,W1.int32ToIpv4)(T.readUInt32BE())};if(A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress;this.setState(P.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:A,socket:this.socket})}else this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let _=this.receiveBuffer.get(8);if(_[1]!==P.Socks4Response.Granted)this.closeSocket(`${P.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${P.Socks4Response[_[1]]})`);else{let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A={port:T.readUInt16BE(),host:(0,W1.int32ToIpv4)(T.readUInt32BE())};this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}sendSocks5InitialHandshake(){let _=new K1.SmartBuffer,T=[P.Socks5Auth.NoAuth];if(this.options.proxy.userId||this.options.proxy.password)T.push(P.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=P.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(_.toBuffer()),this.setState(P.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let _=this.receiveBuffer.get(2);if(_[0]!==5)this.closeSocket(P.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);else if(_[1]===P.SOCKS5_NO_ACCEPTABLE_AUTH)this.closeSocket(P.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);else if(_[1]===P.Socks5Auth.NoAuth)this.socks5ChosenAuthType=P.Socks5Auth.NoAuth,this.sendSocks5CommandRequest();else if(_[1]===P.Socks5Auth.UserPass)this.socks5ChosenAuthType=P.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(P.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=P.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(A.toBuffer()),this.setState(P.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(P.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(P.SocksClientState.ReceivedAuthenticationResponse);let _=!1;if(this.socks5ChosenAuthType===P.Socks5Auth.NoAuth)_=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===P.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(P.ERRORS.Socks5AuthenticationFailed);else this.sendSocks5CommandRequest()})}sendSocks5CommandRequest(){let _=new K1.SmartBuffer;if(_.writeUInt8(5),_.writeUInt8(P.SocksCommand[this.options.command]),_.writeUInt8(0),W4.isIPv4(this.options.destination.host))_.writeUInt8(P.Socks5HostType.IPv4),_.writeBuffer((0,W1.ipToBuffer)(this.options.destination.host));else if(W4.isIPv6(this.options.destination.host))_.writeUInt8(P.Socks5HostType.IPv6),_.writeBuffer((0,W1.ipToBuffer)(this.options.destination.host));else _.writeUInt8(P.Socks5HostType.Hostname),_.writeUInt8(this.options.destination.host.length),_.writeString(this.options.destination.host);_.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(_.toBuffer()),this.setState(P.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let _=this.receiveBuffer.peek(5);if(_[0]!==5||_[1]!==P.Socks5Response.Granted)this.closeSocket(`${P.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${P.Socks5Response[_[1]]}`);else{let T=_[3],A,E;if(T===P.Socks5HostType.IPv4){let L=P.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,W1.int32ToIpv4)(E.readUInt32BE()),port:E.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if(T===P.Socks5HostType.Hostname){let L=_[4],J=P.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===P.Socks5HostType.IPv6){let L=P.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:yL.Address6.fromByteArray(Array.from(E.readBuffer(16))).canonicalForm(),port:E.readUInt16BE()}}if(this.setState(P.SocksClientState.ReceivedFinalResponse),P.SocksCommand[this.options.command]===P.SocksCommand.connect)this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket});else if(P.SocksCommand[this.options.command]===P.SocksCommand.bind)this.setState(P.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:A,socket:this.socket});else if(P.SocksCommand[this.options.command]===P.SocksCommand.associate)this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}handleSocks5IncomingConnectionResponse(){let _=this.receiveBuffer.peek(5);if(_[0]!==5||_[1]!==P.Socks5Response.Granted)this.closeSocket(`${P.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${P.Socks5Response[_[1]]}`);else{let T=_[3],A,E;if(T===P.Socks5HostType.IPv4){let L=P.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,W1.int32ToIpv4)(E.readUInt32BE()),port:E.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if(T===P.Socks5HostType.Hostname){let L=_[4],J=P.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===P.Socks5HostType.IPv6){let L=P.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:yL.Address6.fromByteArray(Array.from(E.readBuffer(16))).canonicalForm(),port:E.readUInt16BE()}}this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}TT.SocksClient=H5});var jU=W((kT)=>{var Gv=kT&&kT.__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]}),Uv=kT&&kT.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))Gv(T,_,A)};Object.defineProperty(kT,"__esModule",{value:!0});Uv(PU(),kT)});var kL=W((a1)=>{var Wv=a1&&a1.__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]}),Nv=a1&&a1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Qv=a1&&a1.__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")Wv(A,T,E[L])}return Nv(A,T),A}}(),xU=a1&&a1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(a1,"__esModule",{value:!0});a1.default=Bv;var Mv=xU(d1()),Vv=I("stream"),zv=jU(),Fv=Qv(I("dns")),Cv=I("util"),hL=xU(I("assert")),g0=(0,Mv.default)("mqttjs:socks");class wU extends Vv.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(_){if(g0("proxy stream started"),(0,hL.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,hL.default)(this._socket),this._socket.write(_,A)}_read(_){this._flowing=!0,this._socket?.resume?.()}_destroy(_,T){this._socket?.destroy?.(_),T(_)}_onData=(_)=>{if((0,hL.default)(this._socket),this._flowing=this.push(_),!this._flowing)this._socket.pause()};_onEnd=()=>{g0("proxy stream received EOF"),this.push(null)};_onClose=()=>{g0("proxy stream closed"),this.destroy()};_onError=(_)=>{g0("proxy stream died with error %s",_),this.destroy(_)}}function Z5(_){try{if(_.code===void 0)_.code="SOCKS";return _}catch{return _}}function Ov(_){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 Rv(_){let T=new URL(_);if(T.pathname||T.hash||T.search)throw Z5(Error("bad SOCKS URL"));let[A,E]=Ov(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 Dv(_,T,A,E,L={}){let J=L.lookup??(0,Cv.promisify)(Fv.lookup),[X,H]=Rv(A);if(!H)g0("resolving %s locally",_),_=(await J(_,{family:X.type===4?4:0})).address;g0("establishing SOCKS%d connection to %s:%d via %s:%d",X.type,_,T,X.host,X.port);let Z=new zv.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)=>{g0("SOCKS failed: %s",Y),E.destroy(Z5(Y))})}function Bv(_,T,A,E){g0("SOCKS connection to %s:%d via %s",_,T,A);let L=new wU;return Dv(_,T,A,L,E).catch((J)=>{g0("SOCKS failed: %s",J),L.destroy(J)}),L}});var bL=W((I8)=>{var fL=I8&&I8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(I8,"__esModule",{value:!0});var qv=fL(I("net")),Iv=fL(d1()),Pv=fL(kL()),jv=(0,Iv.default)("mqttjs:tcp"),xv=(_,T)=>{if(T.port=T.port||1883,T.hostname=T.hostname||T.host||"localhost",T.socksProxy)return(0,Pv.default)(T.hostname,T.port,T.socksProxy,{timeout:T.socksTimeout});let{port:A,path:E}=T,L=T.hostname;return jv("port %d and host %s",A,L),qv.default.createConnection({port:A,host:L,path:E})};I8.default=xv});var mL=W((P8)=>{var gL=P8&&P8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(P8,"__esModule",{value:!0});var SU=I("tls"),wv=gL(I("net")),Sv=gL(d1()),yv=gL(kL()),vv=(0,Sv.default)("mqttjs:tls");function hv(_){let{host:T,port:A,socksProxy:E,...L}=_;if(E!==void 0){let J=(0,yv.default)(T,A,E,{timeout:_.socksTimeout});return(0,SU.connect)({...L,socket:J})}return(0,SU.connect)(_)}var kv=(_,T)=>{if(T.port=T.port||8883,T.host=T.hostname||T.host||"localhost",wv.default.isIP(T.host)===0)T.servername=T.host;T.rejectUnauthorized=T.rejectUnauthorized!==!1,delete T.path,vv("port %d host %s rejectUnauthorized %b",T.port,T.host,T.rejectUnauthorized);let A=hv(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=kv});var dL=W((vU)=>{Object.defineProperty(vU,"__esModule",{value:!0});var yU=I("buffer"),fv=n0(),bv=tA(),V0,uL,N1;function gv(){let _=new fv.Transform;return _._write=(T,A,E)=>{V0.send({data:T.buffer,success(){E()},fail(L){E(Error(L))}})},_._flush=(T)=>{V0.close({success(){T()}})},_}function mv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function uv(_,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 dv(){V0.onOpen(()=>{N1.socketReady()}),V0.onMessage((_)=>{let{data:T}=_;if(T instanceof ArrayBuffer)T=yU.Buffer.from(T);else T=yU.Buffer.from(T,"utf8");uL.push(T)}),V0.onClose(()=>{N1.emit("close"),N1.end(),N1.destroy()}),V0.onError((_)=>{let T=Error(_.errMsg);N1.destroy(T)})}var cv=(_,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";mv(T);let E=uv(T,_);V0=wx.connectSocket({url:E,protocols:[A]}),uL=gv(),N1=new bv.BufferedDuplex(T,uL,V0),N1._destroy=(J,X)=>{V0.close({success(){if(X)X(J)}})};let L=N1.destroy;return N1.destroy=(J,X)=>{return N1.destroy=L,setTimeout(()=>{V0.close({fail(){N1._destroy(J,X)}})},0),N1},dv(),N1};vU.default=cv});var pL=W((kU)=>{Object.defineProperty(kU,"__esModule",{value:!0});var cL=I("buffer"),lv=n0(),nv=tA(),m0,j8,N4,hU=!1;function iv(){let _=new lv.Transform;return _._write=(T,A,E)=>{m0.sendSocketMessage({data:T.buffer,success(){E()},fail(){E(Error())}})},_._flush=(T)=>{m0.closeSocket({success(){T()}})},_}function av(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function ov(_,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 rv(){if(hU)return;hU=!0,m0.onSocketOpen(()=>{N4.socketReady()}),m0.onSocketMessage((_)=>{if(typeof _.data==="string"){let T=cL.Buffer.from(_.data,"base64");j8.push(T)}else{let T=new FileReader;T.addEventListener("load",()=>{if(T.result instanceof ArrayBuffer){j8.push(cL.Buffer.from(T.result));return}j8.push(cL.Buffer.from(T.result,"utf-8"))}),T.readAsArrayBuffer(_.data)}}),m0.onSocketClose(()=>{N4.end(),N4.destroy()}),m0.onSocketError((_)=>{N4.destroy(_)})}var sv=(_,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";av(T);let E=ov(T,_);return m0=T.my,m0.connectSocket({url:E,protocols:A}),j8=iv(),N4=new nv.BufferedDuplex(T,j8,m0),rv(),N4};kU.default=sv});var mU=W((Q4)=>{var Y5=Q4&&Q4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(Q4,"__esModule",{value:!0});Q4.connectAsync=Eh;var ev=Y5(d1()),_h=Y5(I("url")),Th=Y5(sA()),fU=Y5(O8());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var bU=(0,ev.default)("mqttjs"),y_=null;function Ah(_){let T;if(_.auth)if(T=_.auth.match(/^(.+):(.+)$/),T){let[,A,E]=T;_.username=A,_.password=E}else _.username=_.auth}function gU(_,T){if(bU("connecting to an MQTT broker..."),typeof _==="object"&&!T)T=_,_="";if(T=T||{},_&&typeof _==="string"){let L=_h.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(Ah(T),T.query&&typeof T.query.clientId==="string")T.clientId=T.query.clientId;if(fU.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(!y_)if(y_={},!fU.default&&!T.forceNativeWebSocket)y_.ws=B8().streamBuilder,y_.wss=B8().streamBuilder,y_.mqtt=bL().default,y_.tcp=bL().default,y_.ssl=mL().default,y_.tls=y_.ssl,y_.mqtts=mL().default;else y_.ws=B8().browserStreamBuilder,y_.wss=B8().browserStreamBuilder,y_.wx=dL().default,y_.wxs=dL().default,y_.ali=pL().default,y_.alis=pL().default;if(!y_[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 y_[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 bU("calling streambuilder for",T.protocol),y_[T.protocol](L,T)}let E=new Th.default(A,T);return E.on("error",()=>{}),E}function Eh(_,T,A=!0){return new Promise((E,L)=>{let J=gU(_,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=gU});var lL=W((Z_)=>{var uU=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]}),Lh=Z_&&Z_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Jh=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")uU(A,T,E[L])}return Lh(A,T),A}}(),dU=Z_&&Z_.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))uU(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 cU=x8(sA());Z_.MqttClient=cU.default;var Xh=x8(LL());Z_.DefaultMessageIdProvider=Xh.default;var Hh=x8(DG());Z_.UniqueMessageIdProvider=Hh.default;var Zh=x8(pE());Z_.Store=Zh.default;var pU=Jh(mU());Z_.connect=pU.default;Object.defineProperty(Z_,"connectAsync",{enumerable:!0,get:function(){return pU.connectAsync}});var Yh=x8(ML());Z_.KeepaliveManager=Yh.default;Z_.Client=cU.default;dU(sA(),Z_);dU(qT(),Z_);var Kh=e4();Object.defineProperty(Z_,"ReasonCodes",{enumerable:!0,get:function(){return Kh.ReasonCodes}})});var nU=W((I1)=>{var lU=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]}),$h=I1&&I1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Gh=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")lU(A,T,E[L])}return $h(A,T),A}}(),Uh=I1&&I1.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))lU(T,_,A)};Object.defineProperty(I1,"__esModule",{value:!0});var Wh=Gh(lL());I1.default=Wh;Uh(lL(),I1)});var rL=W((xu,eU)=>{eU.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var AW=W((wu,TW)=>{var Ch=rL();function _W(_){this.mode=Ch.MODE_8BIT_BYTE,this.data=_}_W.prototype={getLength:function(){return this.data.length},write:function(_){for(var T=0;T<this.data.length;T++)_.put(this.data.charCodeAt(T),8)}};TW.exports=_W});var sL=W((Su,EW)=>{var o1={glog:function(_){if(_<1)throw Error("glog("+_+")");return o1.LOG_TABLE[_]},gexp:function(_){while(_<0)_+=255;while(_>=256)_-=255;return o1.EXP_TABLE[_]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(R_=0;R_<8;R_++)o1.EXP_TABLE[R_]=1<<R_;var R_;for(R_=8;R_<256;R_++)o1.EXP_TABLE[R_]=o1.EXP_TABLE[R_-4]^o1.EXP_TABLE[R_-5]^o1.EXP_TABLE[R_-6]^o1.EXP_TABLE[R_-8];var R_;for(R_=0;R_<255;R_++)o1.LOG_TABLE[o1.EXP_TABLE[R_]]=R_;var R_;EW.exports=o1});var tL=W((yu,LW)=>{var fT=sL();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]^=fT.gexp(fT.glog(this.get(A))+fT.glog(_.get(E)));return new N5(T,0)},mod:function(_){if(this.getLength()-_.getLength()<0)return this;var T=fT.glog(this.get(0))-fT.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]^=fT.gexp(fT.glog(_.get(L))+T);return new N5(A,0).mod(_)}};LW.exports=N5});var XW=W((vu,JW)=>{JW.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var YW=W((hu,ZW)=>{var j1=rL(),HW=tL(),Oh=sL(),AT=XW(),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 HW([1],0);for(var A=0;A<_;A++)T=T.multiply(new HW([1,Oh.gexp(A)],0));return T},getLengthInBits:function(_,T){if(1<=T&&T<10)switch(_){case j1.MODE_NUMBER:return 10;case j1.MODE_ALPHA_NUM:return 9;case j1.MODE_8BIT_BYTE:return 8;case j1.MODE_KANJI:return 8;default:throw Error("mode:"+_)}else if(T<27)switch(_){case j1.MODE_NUMBER:return 12;case j1.MODE_ALPHA_NUM:return 11;case j1.MODE_8BIT_BYTE:return 16;case j1.MODE_KANJI:return 10;default:throw Error("mode:"+_)}else if(T<41)switch(_){case j1.MODE_NUMBER:return 14;case j1.MODE_ALPHA_NUM:return 13;case j1.MODE_8BIT_BYTE:return 16;case j1.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 $=Math.abs(100*K/T/T-50)/5;return A+=$*10,A}};ZW.exports=u_});var eL=W((ku,KW)=>{KW.exports={L:1,M:0,Q:3,H:2}});var GW=W((fu,$W)=>{var Q5=eL();function z0(_,T){this.totalCount=_,this.dataCount=T}z0.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]];z0.getRSBlocks=function(_,T){var A=z0.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 z0(H,Z))}return L};z0.getRsBlockTable=function(_,T){switch(T){case Q5.L:return z0.RS_BLOCK_TABLE[(_-1)*4+0];case Q5.M:return z0.RS_BLOCK_TABLE[(_-1)*4+1];case Q5.Q:return z0.RS_BLOCK_TABLE[(_-1)*4+2];case Q5.H:return z0.RS_BLOCK_TABLE[(_-1)*4+3];default:return}};$W.exports=z0});var NW=W((bu,WW)=>{function UW(){this.buffer=[],this.length=0}UW.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++}};WW.exports=UW});var zW=W((gu,VW)=>{var Rh=AW(),ET=YW(),Dh=tL(),QW=GW(),MW=NW();function F0(_,T){this.typeNumber=_,this.errorCorrectLevel=T,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}F0.prototype={addData:function(_){var T=new Rh(_);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=QW.getRSBlocks(_,this.errorCorrectLevel),A=new MW,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=F0.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}}}}};F0.PAD0=236;F0.PAD1=17;F0.createData=function(_,T,A){var E=QW.getRSBlocks(_,T),L=new MW;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(F0.PAD0,8),L.getLengthInBits()>=H*8)break;L.put(F0.PAD1,8)}return F0.createBytes(L,E)};F0.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 $=ET.getErrorCorrectPolynomial(Y),G=new Dh(J[H],$.getLength()-1),U=G.mod($);X[H]=Array($.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};VW.exports=F0});var OW=W((mu,CW)=>{var Bh=zW(),FW=eL(),qh="\x1B[40m \x1B[0m",M5="\x1B[47m \x1B[0m",Ih=function(_){return _?qh:M5},_9=function(_){return{times:function(T){return Array(T).join(_)}}},Ph=function(_,T){var A=Array(_);for(var E=0;E<_;E++)A[E]=T;return A};CW.exports={error:FW.L,generate:function(_,T,A){if(typeof T==="function")A=T,T={};var E=new Bh(-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(Ph(H,X));var K={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},$=_9(K.BLACK_WHITE).times(H+3),G=_9(K.WHITE_BLACK).times(H+3);L+=$+`
15
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(`
16
+ `}if(!Y)L+=G}else{var N=_9(M5).times(E.getModuleCount()+3);L+=N+`
17
+ `,E.modules.forEach(function(z){L+=M5,L+=z.map(Ih).join(""),L+=M5+`
18
+ `}),L+=N}if(A)A(L);else console.log(L)},setErrorLevel:function(_){this.error=FW[_]||this.error}}});import{readFileSync as Q9}from"fs";import{join as M9}from"path";function G1(){return"2.0.0-alpha.4"}function S5(_){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 XT(_){return S5(_).preRelease?"beta":"stable"}function y5(_,T){try{let A=S5(_),E=S5(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}}import{parseArgs as BN}from"util";var qN={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"},version:{type:"boolean",short:"v",default:!1,description:"Show version"}};function V9(){let _=BN({options:qN,allowPositionals:!1,strict:!0});if(_.values.version)console.log(`ccc v${G1()}`),process.exit(0);if(_.values.help)IN(),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 IN(){console.log(`
19
19
  Backend v2 - Clean modular architecture
20
20
 
21
21
  Usage:
@@ -32,16 +32,17 @@ Options:
32
32
  --ngrok-domain <domain> ngrok static domain (optional, paid plan)
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
+ -v, --version Show version
35
36
  -h, --help Show this help message
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
+ `)}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 HT extends B4{constructor(_){super(_,"TERMINAL_SERVER_ERROR",500);this.name="TerminalServerError"}}class v5 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 z9(_){return PN(_),jN(_),{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 PN(_){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 jN(_){if(_.ngrokToken&&(!_.username||!_.password))throw new q4("Error: MQTT authentication (--username and --password) is required when using ngrok tunnels for security.")}class h5{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 F9(_=!1){return I4=new h5(_),I4}function v(){if(!I4)I4=new h5(!1);return I4}import*as d0 from"fs";import*as mT from"path";var xN={FULL_WIDTH:0,FITTING:1,SMUSHING:2,CONTROLLED_SMUSHING:3};class C9{constructor(){this.comment="",this.numChars=0,this.options={}}}var k5=["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 wN(_){return/[.*+?^${}()|[\]\\]/.test(_)?"\\"+_:_}var O9=(()=>{let{FULL_WIDTH:_=0,FITTING:T,SMUSHING:A,CONTROLLED_SMUSHING:E}=xN,L={},J={font:"Standard",fontPath:"./fonts",fetchFontIfMissing:!0};function X(O,D,M){let C=wN(O.trim().slice(-1))||"@",j=D===M-1?new RegExp(C+C+"?\\s*$"):new RegExp(C+"\\s*$");return O.replace(j,"")}function H(O=-1,D=null){let M={},C,j=[[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 j)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),j=M.indexOf(D);if(C!==-1&&j!==-1){if(C!==j&&Math.abs(C-j)!==1){let w=Math.max(C,j),y=w+1;return M.substring(w,y)}}return!1}function $(O,D){let M="[] {} ()",C=M.indexOf(O),j=M.indexOf(D);if(C!==-1&&j!==-1){if(Math.abs(C-j)<=1)return"|"}return!1}function G(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,j=Math.min(O.length,D.length),w,y,S=!1,k;if(j===0)return"invalid";for(C=0;C<j;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:j}=O,w,y,S,k=1,d,o,a;while(k<=C){w=O.slice(Math.max(0,j-k),j),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,j=Math.min(O.length,D.length),w,y,S="",k,d=M.fittingRules||{};for(C=0;C<j;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 j=O.length,w=D.length,y=O.slice(0,Math.max(0,j-M)),S=O.slice(Math.max(0,j-M),j),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,j=D[0].length,w;if(C>j)D=l(D,C-j);else if(j>C)O=l(O,j-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 j,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 v1=w-k;o=O.substring(v1,v1+k),a=D.substring(0,Math.min(k,y));for(j=0;j<Math.min(k,y);j++)if(r=o.substring(j,j+1),T_=a.substring(j,j+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&&$(r,T_)||C.hRule5&&G(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 j,w,y=[],S,k,d,o,a,r,T_,v1,E1=C.fittingRules||{};if(typeof C.height!=="number")throw Error("height is not defined.");for(j=0;j<C.height;j++){T_=O[j],v1=D[j],a=T_.length,r=v1.length,S=a-M,k=T_.slice(0,Math.max(0,S)),d="";let D4=Math.max(0,a-M),h1=T_.substring(D4,D4+M),JT=v1.substring(0,Math.min(M,r));for(w=0;w<M;w++){let M1=w<a?h1.substring(w,w+1):" ",L1=w<r?JT.substring(w,w+1):" ";if(M1!==" "&&L1!==" ")if(E1.hLayout===T||E1.hLayout===A)d+=R(M1,L1,C.hardBlank);else{let FN=E1.hRule1&&Z(M1,L1,C.hardBlank)||E1.hRule2&&Y(M1,L1)||E1.hRule3&&K(M1,L1)||E1.hRule4&&$(M1,L1)||E1.hRule5&&G(M1,L1)||E1.hRule6&&U(M1,L1,C.hardBlank)||R(M1,L1,C.hardBlank);d+=FN}else d+=R(M1,L1,C.hardBlank)}if(M>=r)o="";else o=v1.substring(M,M+Math.max(0,r-M));y[j]=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,j){return c_(C,j.fig,j.overlap||0,M)},B_(D))}function M_(O,D,M){for(let C=O.length-1;C>0;C--){let j=K_(O.slice(0,C),D,M);if(C_(j)<=M.width)return{outputFigText:j,chars:O.slice(C)}}return{outputFigText:B_(D),chars:O}}function I_(O,D,M){let C,j,w=0,y,S,k,d=M.height,o=[],a,r={chars:[],overlap:w},T_=[],v1,E1,D4,h1,JT;if(typeof d!=="number")throw Error("height is not defined.");S=B_(d);let M1=M.fittingRules||{};if(M.printDirection===1)O=O.split("").reverse().join("");k=O.length;for(C=0;C<k;C++)if(v1=O.substring(C,C+1),E1=v1.match(/\s/),j=D[v1.charCodeAt(0)],h1=null,j){if(M1.hLayout!==_){w=1e4;for(y=0;y<d;y++)w=Math.min(w,W_(S[y],j[y],M));w=w===1e4?0:w}if(M.width>0){if(M.whitespaceBreak)D4=K_(r.chars.concat([{fig:j,overlap:w}]),d,M),h1=K_(T_.concat([{fig:D4,overlap:r.overlap}]),d,M),a=C_(h1);else h1=c_(S,j,w,M),a=C_(h1);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:j,overlap:w});if(E1||C===k-1){JT=null;while(!0)if(h1=K_(r.chars,d,M),a=C_(h1),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:h1,overlap:1});else T_.push({fig:h1,overlap:r.overlap});if(E1)T_.push({fig:j,overlap:w}),S=B_(d);if(C===k-1)S=K_(T_,d,M);r={chars:[],overlap:w};continue}}S=c_(S,j,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 j_=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},R0=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},y1=function(O,D,M){M=M.replace(/\r\n/g,`
37
38
  `).replace(/\r/g,`
38
39
  `);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,`
40
+ `),j=[],w,y,S;y=C.length;for(w=0;w<y;w++)j=j.concat(I_(C[w],L[O],D));y=j.length,S=j[0];for(w=1;w<y;w++)S=c(S,j[w],D);return S?S.join(`
41
+ `):""};function W9(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=j_(D.horizontalLayout,O);if(C)Object.assign(M.fittingRules,C)}if(D.verticalLayout){let C=R0(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 P_=async function(O,D,M){return P_.text(O,D,M)};return P_.text=async function(O,D,M){O=O+"";let C,j;if(typeof D==="function")j=D,C={font:J.font};else if(typeof D==="string")C={font:D},j=M;else if(D)C=D,j=M;else C={font:J.font},j=M;let w=C.font||J.font;try{let y=await P_.loadFont(w),S=y?y1(w,W9(y,C),O):"";if(j)j(null,S);return S}catch(y){let S=y instanceof Error?y:Error(String(y));if(j)return j(S),"";throw S}},P_.textSync=function(O,D){if(O=O+"",typeof D==="string")D={font:D};else D=D||{};let M=D.font||J.font,C=W9(P_.loadFontSync(M),D);return y1(M,C,O)},P_.metadata=async function(O,D){O=O+"";try{let M=await P_.loadFont(O);if(!M)throw Error("Error loading font.");let C=L[O]||{},j=[M,C.comment||""];if(D)D(null,M,C.comment);return j}catch(M){let C=M instanceof Error?M:Error(String(M));if(D)return D(C),null;throw C}},P_.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))},P_.parseFont=function(O,D,M=!0){if(L[O]&&!M)return L[O].options;D=D.replace(/\r\n/g,`
41
42
  `).replace(/\r/g,`
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
43
+ `);let C=new C9,j=D.split(`
44
+ `),w=j.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),j.length<S.numCommentLines+S.height*d.length)throw Error(`FIGlet file is missing data. Line length: ${j.length}. Comment lines: ${S.numCommentLines}. Height: ${S.height}. Num chars: ${d.length}.`);C.comment=j.splice(0,S.numCommentLines).join(`
45
+ `),C.numChars=0;while(j.length>0&&C.numChars<d.length){let o=d[C.numChars];C[o]=j.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(j.length>0){let o=j.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]=j.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},P_.loadedFonts=()=>{return Object.keys(L)},P_.clearLoadedFonts=()=>{Object.keys(L).forEach((O)=>{delete L[O]})},P_.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(),j=P_.parseFont(O,C);if(D)D(null,j);return j}catch(M){let C=M instanceof Error?M:Error(String(M));if(D)return D(C),null;throw C}},P_.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.")},P_.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 j=await C.text();P_.parseFont(M,j)}if(D)D()}catch(M){let C=M instanceof Error?M:Error(String(M));if(D){D(C);return}throw M}},P_.fonts=function(O){return new Promise(function(D,M){if(D(k5),O)O(null,k5)})},P_.fontsSync=function(){return k5},P_.figFonts=L,P_})();import{fileURLToPath as SN}from"url";var yN=SN(import.meta.url),vN=mT.dirname(yN),hN=mT.join(vN,"/../fonts/"),x_=O9;x_.defaults({fontPath:hN});x_.loadFont=function(_,T){return new Promise((A,E)=>{if(x_.figFonts[_]){if(T)T(null,x_.figFonts[_].options);A(x_.figFonts[_].options);return}d0.readFile(mT.join(x_.defaults().fontPath,_+".flf"),{encoding:"utf-8"},(L,J)=>{if(L){if(T)T(L);E(L);return}J=J+"";try{let X=x_.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)}})})};x_.loadFontSync=function(_){if(x_.figFonts[_])return x_.figFonts[_].options;let T=d0.readFileSync(mT.join(x_.defaults().fontPath,_+".flf"),{encoding:"utf-8"})+"";return x_.parseFont(_,T)};x_.fonts=function(_){return new Promise((T,A)=>{let E=[];d0.readdir(x_.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)})})};x_.fontsSync=function(){let _=[];return d0.readdirSync(x_.defaults().fontPath).forEach((T)=>{if(/\.flf$/.test(T))_.push(T.replace(/\.flf$/,""))}),_};var R9=`flf2a$ 6 5 16 15 13 0 24463 229
45
46
  Standard by Glenn Chappell & Ian Chai 3/93 -- based on Frank's .sig
46
47
  Includes ISO Latin-1
47
48
  figlet release 2.1 -- 12 Aug 1994
@@ -2277,9 +2278,9 @@ Font modified May 20, 2012 by patorjk to add the 0xCA0 character
2277
2278
  | (_) | @
2278
2279
  $\\___/$ @
2279
2280
  @@
2280
- `;j_.parseFont("Standard",V9);function z9(){let _=j_.textSync("ccc",{font:"Standard",horizontalLayout:"default",verticalLayout:"default"});console.log(`
2281
+ `;x_.parseFont("Standard",R9);function D9(){let _=x_.textSync("ccc",{font:"Standard",horizontalLayout:"default",verticalLayout:"default"});console.log(`
2281
2282
  `),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
+ `)}var KK=q_(ZK(),1);import{Duplex as Jj}from"stream";async function YK(_,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 Jj({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=(G)=>{A.error("[MQTT TCP] Server error",{error:G.message,code:G.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",$),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=KK.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 YK(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 iU=q_(nU(),1);var P1=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=iU.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,P1.info("[BackendClient] Connected to MQTT broker"),_()}),this.client.on("error",(E)=>{if(P1.error("[BackendClient] MQTT error",{error:E.message}),!this.connected)T(E)}),this.client.on("close",()=>{this.connected=!1,P1.debug("[BackendClient] Disconnected from MQTT broker")}),this.client.on("message",(E,L)=>{this.handleMessage(E,L)})}catch(A){P1.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(),P1.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)P1.error(`[BackendClient] Failed to subscribe to ${_}`,{error:A.message});else P1.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)P1.error(`[BackendClient] Failed to unsubscribe from ${_}`,{error:E.message});else P1.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)P1.error(`[BackendClient] Failed to publish to ${_}`,{error:J.message}),L(J);else P1.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){P1.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 aU=5,Nh=900000;class nL{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>=aU)this.blockedIPs.set(A,Date.now()+Nh),this.failedAttempts.delete(A),this.logger.warn(`IP blocked after ${aU} 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}}var iL=null;async function Qh(){if(!iL)iL=await import("bun-pty");return iL}var oU=5,Mh=300000,Vh=102400;class aL{sessions=new Map;projectPath=process.cwd();logger=v();async createSession(_,T=80,A=24){if(Array.from(this.sessions.values()).filter((L)=>!L.disconnectedAt).length>=oU)throw new HT(`Maximum concurrent sessions (${oU}) reached`);try{let{spawn:L}=await Qh(),J=process.platform==="win32"?"powershell.exe":"bash",X=L(J,[],{name:"xterm-256color",cols:T,rows:A,cwd:this.projectPath,env:process.env}),H={id:_,createdAt:new Date,lastActivityAt:new Date};this.sessions.set(_,{pty:X,session:H,cwd:this.projectPath,outputBuffer:[]}),this.logger.debug(`PTY session created: ${_}`,{cols:T,rows:A,cwd:this.projectPath,pid:X.pid})}catch(L){throw this.logger.error("Failed to create PTY session",L),new HT(`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)<Vh)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(_)},Mh),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 rU(_){return`<!DOCTYPE html>
2283
2284
  <html lang="en">
2284
2285
  <head>
2285
2286
  <meta charset="UTF-8">
@@ -2605,36 +2606,36 @@ Font modified May 20, 2012 by patorjk to add the 0xCA0 character
2605
2606
  })();
2606
2607
  </script>
2607
2608
  </body>
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
2609
+ </html>`}class $5{server=null;authenticator;ptyManager;running=!1;startedAt;config;logger=v();sessionMap=new Map;name="CCC Terminal Service";constructor(_){this.config=_,this.authenticator=new nL,this.ptyManager=new aL}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 HT(`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 HT(`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=rU(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)")}async 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,($)=>{try{if(_.readyState===1)_.send($)}catch(G){}});let K=this.ptyManager.resumeSession(Y,X,H);if(_.send(`SESSION:${Y}`),K&&K.length>0)for(let $ of K)try{if(_.readyState===1)_.send($)}catch(G){break}_.send(`\x1B[38;5;209m\u2713 Session resumed\x1B[0m\r
2610
+ `)}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();await this.ptyManager.createSession(K,X,H),this.sessionMap.set(_,K),this.ptyManager.setupDataHandler(K,($)=>{try{if(_.readyState===1)_.send($)}catch(G){}}),_.send(`SESSION:${K}`),_.send(`\x1B[38;5;209m\u2713 Connected to CCC Terminal\x1B[0m\r
2610
2611
  \r
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(`
2612
+ `)}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 G5 from"http";import*as tU from"net";import{WebSocketServer as zh,WebSocket as sU}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=G5.createServer((A,E)=>{this.handleHttpRequest(A,E)}),this.wss=new zh({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 v5(`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=G5.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
2613
+ `)}),_.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=tU.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 sU(H),Y=[],K=!1;Z.on("open",()=>{K=!0;while(Y.length>0){let $=Y.shift();Z.send($)}}),_.on("message",($)=>{let G=typeof $==="string"?$:$.toString("utf-8");if(K&&Z.readyState===sU.OPEN)Z.send(G);else Y.push(G)}),Z.on("message",($)=>{let G=typeof $==="string"?$:$.toString("utf-8");if(_.readyState===1)_.send(G)}),_.on("close",()=>{Z.close()}),_.on("error",($)=>{this.logger.error("Client WebSocket error",{error:$.message}),Z.close()}),Z.on("close",()=>{_.close()}),Z.on("error",($)=>{this.logger.error("Target WebSocket error",{error:$.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)}}var oL=null;async function Fh(){if(!oL)oL=await import("@ngrok/ngrok");return oL.default}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;let A=await Fh();this.listener=await A.forward(T),this.tunnelUrl=this.listener.url(),this.running=!0,this.startedAt=new Date;let E=this.tunnelUrl?.replace(/^https?:\/\//,"");_.debug("ngrok tunnel established",{url:E,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 RW=q_(OW(),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
2614
  `),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(`
2615
+ `)}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);RW.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)"}}var x1=v();async function DW(_){let T=G1(),A=XT(T);x1.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 x1.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(x1.debug("NPM registry response",{distTags:J["dist-tags"],requestedTag:E,latestVersion:X}),!X)return x1.warn("Could not determine latest version from npm registry"),{updateAvailable:!1,currentVersion:T,latestVersion:T,releaseChannel:A};let H=y5(X,T);return x1.debug("Version comparison result",{currentVersion:T,latestVersion:X,updateAvailable:H,isNewer:y5(X,T)}),x1.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 x1.error("Error checking for updates",{error:E}),{updateAvailable:!1,currentVersion:T,latestVersion:T,releaseChannel:A}}}async function BW(_){let T=G1(),E=XT(T)==="beta"?"beta":"latest";x1.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 x1.error("Package update failed",{error:X,packageName:_,exitCode:H}),!1;if(x1.debug("Package updated successfully",{packageName:_,distTag:E}),J)x1.debug("bun install output",{output:J.trim()});return!0}catch(L){return x1.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:G1(),updateAvailable:this.updateAvailable,latestVersion:this.latestVersion,releaseChannel:XT(G1()),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:G1()});let{updateAvailable:_,latestVersion:T,currentVersion:A,releaseChannel:E}=await DW(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 BW(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 wh,readdirSync as Sh,existsSync as yh}from"fs";import{stat as jW}from"fs/promises";import{join as gT,basename as vh}from"path";import{homedir as xW}from"os";import*as o_ from"path";import*as T9 from"os";var M4=v();class qW{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(`
2616
+ `),Z=[];for(let K of H)try{if(!K.trim())continue;let $=JSON.parse(K),G=this.parseEntry($);if(G)Z.push(G)}catch($){M4.warn("[SessionMessageParser] Failed to parse line:",$)}let Y;if(T){let K=Z.findIndex(($)=>$.uuid===T);if(K===-1)M4.warn("[SessionMessageParser] lastKnownUuid not found, returning latest messages"),Y=Z.slice(-A),E=Z.length>A;else{let $=Z.slice(K+1);Y=$.slice(0,A),E=$.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 IW=new qW;var Q1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6},jh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,xh="worktrees",F_=v();class PW{claudeProjectsDir;cccDir;constructor(){this.claudeProjectsDir=o_.join(T9.homedir(),".claude","projects"),this.cccDir=o_.join(T9.homedir(),".ccc")}async getWorktreePathsForProject(_){let T=await import("fs"),A=o_.basename(_),E=o_.join(this.cccDir,`${A}-${xh}`);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
2617
  `).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(`
2618
+ `),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(($)=>$.type==="tool_result");if(!J&&Y&&!K){let $=Z.message?.content,G=null;if(typeof $==="string")G=$;else if(Array.isArray($)){let V=$.find((N)=>N.type==="text");if(V?.text)G=V.text}let U=G?.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 jh.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($)=>{let G=this.getProjectSessionsDir($);F_.info("[SessionManager] Checking worktree sessions dir:",G);let U=o_.basename($),V={path:$,branch:`session/${U}`},N=await this.listSessionsFromDir(G,V);return F_.info("[SessionManager] Found sessions in worktree:",{worktreePath:$,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 $ of L)Y.set($.sessionId,$);for(let $ of Z){let G=Y.get($.sessionId);if(!G||new Date($.lastActivity)>new Date(G.lastActivity)||$.messageCount>G.messageCount)Y.set($.sessionId,$)}let K=Array.from(Y.values()).sort(($,G)=>new Date(G.lastActivity).getTime()-new Date($.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 IW.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(`
2619
+ `),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,$=H+Y+K,G=Q1.SYSTEM_PROMPT,U=Q1.TOOLS_TOTAL,V=0,N=Q1.AUTOCOMPACT_BUFFER,z=Math.max(0,$-G-U-V),Q=$+N,F=Q1.CONTEXT_LIMIT_STANDARD;return F_.info("[SessionManager] Context breakdown calculated:",{total:Q,apiTokens:$,inputTokens:H,cacheCreation:Y,cacheRead:K,percentage:Math.round(Q/F*100),breakdown:{systemPrompt:G,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:G,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 _=Q1.SYSTEM_PROMPT+Q1.TOOLS_TOTAL+Q1.AUTOCOMPACT_BUFFER;return{total:_,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:Q1.SYSTEM_PROMPT,tools:Q1.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:Q1.AUTOCOMPACT_BUFFER,contextLimit:Q1.CONTEXT_LIMIT_STANDARD,remaining:Q1.CONTEXT_LIMIT_STANDARD-_,percentage:Math.round(_/Q1.CONTEXT_LIMIT_STANDARD*100),lastUpdated:Date.now()}}}var bT=new PW;var X_=v(),hh="worktrees";class A9{watches=new Map;registeredProjects=[];mqttClient;claudeProjectsDir;cccDir;constructor(_){this.mqttClient=_,this.claudeProjectsDir=gT(xW(),".claude","projects"),this.cccDir=gT(xW(),".ccc")}getWorktreePathsForProject(_){let T=vh(_),A=gT(this.cccDir,`${T}-${hh}`);if(!yh(A))return[];try{let E=Sh(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 jW(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 jW(T)}catch{return X_.debug(`[SessionWatcher] Sessions directory not found: ${T}`),null}return wh(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 $_=v();class F5{name="Sessions Service";running=!1;startedAt;mqttClient=null;watcher;claudeAgentService=null;constructor(){}setMQTTClient(_){this.mqttClient=_,this.watcher=new A9(_)}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)),$_.debug(`[Sessions] Broadcast ${_.length} active sessions to all clients`)}async start(){try{if(this.running=!0,this.startedAt=new Date,$_.info("[Sessions] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw $_.error("[Sessions] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.watcher)this.watcher.stopAll();$_.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)}),$_.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)){$_.warn("[Sessions] Invalid projects payload:",A);return}if($_.info(`[Sessions] Received registration for ${E.length} projects`),this.watcher)await this.watcher.registerProjects(E)}catch(A){$_.error("[Sessions] Error handling project registration:",A)}}async handleAppLifecycle(_,T){try{let E=JSON.parse(T.toString()).state;if($_.info(`[Sessions] App lifecycle changed to: ${E}`),E==="background"||E==="terminated"){if(this.watcher)this.watcher.stopAll(),$_.info(`[Sessions] Stopped all watchers (app state: ${E})`)}else if(E==="active"){if(this.watcher)await this.watcher.resumeAll(),$_.info(`[Sessions] Resumed all watchers (app state: ${E})`)}}catch(A){$_.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){$_.warn("[Sessions] Invalid session list request:",A);return}$_.info(`[Sessions] Session list request from ${L} for ${E}`);let X=await bT.listSessions(E),H=this.claudeAgentService?.getActiveSessions()||[],Z=new Map(H.filter((G)=>G.projectPath===E).map((G)=>[G.sessionId,{status:G.status,worktreePath:G.worktreePath,worktreeBranch:G.worktreeBranch}])),K={sessions:X.sessions.map((G)=>{let U=Z.get(G.sessionId);return{...G,status:U?.status,worktreePath:U?.worktreePath||G.worktreePath,worktreeBranch:U?.worktreeBranch||G.worktreeBranch}}),projectPath:X.projectPath,pathExists:X.pathExists,timestamp:Date.now()},$=`sessions/list/${L}/response`;await this.mqttClient?.publish($,JSON.stringify(K)),$_.info(`[Sessions] Sent ${X.sessions.length} sessions to ${L}`)}catch(A){$_.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){$_.warn("[Sessions] Invalid session messages request:",A);return}$_.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()},$=`sessions/messages/${H}/response`;await this.mqttClient?.publish($,JSON.stringify(K)),$_.info(`[Sessions] Sent ${Y.messages.length} messages to ${H} (hasMore: ${Y.hasMore})`)}catch(A){$_.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){$_.warn("[Sessions] Invalid latest sessions request:",A);return}$_.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)),$_.info(`[Sessions] Sent latest sessions for ${X.length} projects to ${L}`)}catch(A){$_.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){$_.warn("[Sessions] Invalid active sessions request:",A);return}$_.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)),$_.info(`[Sessions] Sent ${J.length} active sessions to ${E}`)}catch(A){$_.error("[Sessions] Error handling active sessions request:",A)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt}}}import wW from"os";var T1=v(),kh="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=wW.platform(),L=wW.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=G1(),L=XT(E),J={backendVersion:E,latestBackendVersion:E,backendUpdateAvailable:!1,backendChannel:L==="beta"?"beta":"latest",minAppVersion:kh,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 C0=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,C0.info("[TerminalConfig] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw C0.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),C0.debug("[TerminalConfig] Unsubscribed from system/terminal-config/request"),this.messageHandler=void 0;C0.info("[TerminalConfig] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(_,T)=>{this.handleTerminalConfigRequest(_,T)},this.mqttClient.subscribe("system/terminal-config/request",this.messageHandler),C0.info("[TerminalConfig] MQTT handler registered for system/terminal-config/request")}async handleTerminalConfigRequest(_,T){try{let A=JSON.parse(T.toString());C0.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,C0.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++,C0.debug("[TerminalConfig] Sent terminal config response",{clientId:A.clientId,enabled:J.enabled,port:J.port,responseTopic:X});else C0.error("[TerminalConfig] MQTT client not available for publishing")}catch(A){C0.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 XN from"path";var r1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};var e=v();class E9{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(),G=["-p","--output-format","stream-json","--input-format","stream-json","--permission-prompt-tool","stdio","--permission-mode",X||"default","--model",H||"sonnet","--verbose"];if(J)G.push("--resume",J),e.info(`[ClaudeProcessManager] Resuming session: ${J}`);e.info(`[ClaudeProcessManager] Spawning: ${Y} ${G.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,...G],{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
2620
  `);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
2621
  `);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
+ `);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=r1.SYSTEM_PROMPT,Z=r1.TOOLS_TOTAL,Y=0,K=r1.AUTOCOMPACT_BUFFER,$=Math.max(0,X-H-Z-0),G=X+K,U=this.getContextLimit(T);return{total:G,inputTokens:A,outputTokens:E,cacheCreation:L,cacheRead:J,systemPrompt:H,tools:Z,mcpServers:0,messages:$,autocompactBuffer:K,contextLimit:U,remaining:Math.max(0,U-G),percentage:Math.round(G/U*100),lastUpdated:Date.now()}}getContextLimit(_){if(_?.includes("sonnet-4")||_?.includes("claude-sonnet-4"))return r1.CONTEXT_LIMIT_STANDARD;return r1.CONTEXT_LIMIT_STANDARD}getEmptyContextBreakdown(){return{total:0,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:r1.SYSTEM_PROMPT,tools:r1.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:r1.AUTOCOMPACT_BUFFER,contextLimit:r1.CONTEXT_LIMIT_STANDARD,remaining:r1.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
2623
  `;_.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(`
2624
+ `;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(),fh=300000,vW=new Map,L9=null;function hW(_){if(!_)return!1;return Date.now()-_.timestamp<fh}function bh(_){let T=vW.get(_);if(hW(T))return T.data;return null}function SW(_,T){vW.set(_,{data:T,timestamp:Date.now()})}function gh(){if(hW(L9))return L9.data;return null}function yW(_){L9={data:_,timestamp:Date.now()}}function mh(){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 uh(){let _=mh();for(let T of _)try{if(await Bun.file(T).exists())return T}catch{}return null}async function kW(){try{if((await u`gh --version`.quiet()).exitCode===0)return await dh("gh")}catch{}let _=await uh();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 dh(_){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 J9(){let _=gh();if(_)return _;try{let T=await u`gh api /user/orgs --jq '.[] | {login, id, description, avatar_url}'`.text();if(!T.trim())return yW([]),[];let A=T.trim().split(`
2625
+ `).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 yW(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=bh(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 SW(A,[]),[];let H=JSON.parse(J).map((Y)=>{let K=Y.nameWithOwner?.split("/")[0]||"",$=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:$,avatarUrl:Y.owner?.avatarUrl||void 0}}}),Z=H;if(_)Z=H.filter((Y)=>Y.owner.login.toLowerCase()===_.toLowerCase());return SW(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 fW(_,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),J9()]),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 $=await R5(K.login,100);return{org:K.login,repos:L($),error:null}}catch($){return U_.warn("[GitExecutor] Failed to search org repos",{org:K.login,error:$}),{org:K.login,repos:[],error:$}}})),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 bW(_,T){try{let E=(await u`gh api repos/${_}/${T}/branches --paginate --jq '.[].name'`.text()).trim().split(`
2626
+ `).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 gW(_,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 mW(_,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(`
2627
+ `))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 X9(_){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(`
2628
+ `)){if(!Z.trim())continue;let Y=ch(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 ch(_){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=ph(E,L,_.startsWith("2 "));return{path:H,status:Y,staged:E!=="."&&E!=="?",oldPath:Z||void 0}}return null}function ph(_,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 uW(_,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 $=Z.statSync(K);if($.isDirectory())return{diff:"__DIRECTORY__",isBinary:!1};if($.isFile()){let G=Z.readFileSync(K,"utf-8"),U=G.split(`
2629
+ `);if(G.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(`
2630
+ `),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 dW(_,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 cW(_,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 pW(_,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(`
2631
+ `),Z=H[0]||"",Y=H[1]||"",K=H[2]||"",$=H[3]||"",G=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:$,authorEmail:G,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 lW(_,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 nW(_,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 O0(_){try{return(await u`git -C ${_} rev-parse --show-toplevel`.text()).trim()||null}catch{return null}}async function iW(_,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(`
2632
+ `).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 aW(_,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 oW(_,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(`
2633
+ `),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]||"",$=Y[1]||"",G=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:$,message:G,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 rW(_,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
2634
  `),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
+ `).trim(),K=L[Z]||"",$=L[Z+1]||"",G=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
2636
  `)){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(`
2637
+ `)){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:$,timestamp:G,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 sW(_){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(`
2638
+ `).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 tW(_,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 eW(_,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 G=await u`git -C ${_} push -u origin ${J}`.quiet();if(G.exitCode!==0)return{success:!1,error:`Failed to push branch: ${G.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 _N(_){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 H9(_){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 TN(_){try{await u`git -C ${_} fetch --prune`.quiet();let A=(await u`git -C ${_} branch -r`.text()).split(`
2639
+ `).map((L)=>L.trim()).filter((L)=>L&&!L.includes("HEAD")&&!L.includes("->")).map((L)=>L.replace(/^origin\//,"")),E=await H9(_);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 Y9 from"os";var G_=v();function C4(_){return r_.normalize(_).toLowerCase()}var lh="worktrees",nh="sessions";function Z9(){return r_.join(Y9.homedir(),".ccc",nh)}function ih(){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=Z9();if(!D_.existsSync(A))D_.mkdirSync(A,{recursive:!0});let E=r_.join(A,_);D_.writeFileSync(E,T,"utf-8"),G_.debug("[WorktreeManager] Saved session mapping",{sessionId:_,worktreePath:T})}catch(A){G_.error("[WorktreeManager] Failed to save session mapping",{error:A,sessionId:_,worktreePath:T})}}loadSessionMapping(_){try{let T=r_.join(Z9(),_);if(D_.existsSync(T)){let A=D_.readFileSync(T,"utf-8").trim();if(D_.existsSync(A))return A;else D_.unlinkSync(T),G_.debug("[WorktreeManager] Removed stale session mapping",{sessionId:_,worktreePath:A})}}catch(T){G_.error("[WorktreeManager] Failed to load session mapping",{error:T,sessionId:_})}return null}deleteSessionMapping(_){try{let T=r_.join(Z9(),_);if(D_.existsSync(T))D_.unlinkSync(T),G_.debug("[WorktreeManager] Deleted session mapping",{sessionId:_})}catch(T){G_.error("[WorktreeManager] Failed to delete session mapping",{error:T,sessionId:_})}}getWorktreesBasePath(_){let T=r_.basename(_),A=r_.join(Y9.homedir(),".ccc");return r_.join(A,`${T}-${lh}`)}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){G_.debug("[WorktreeManager] getOrCreateForSession",{sessionId:_,repoPath:T});let A=this.worktreeCache.get(_);if(A)if(D_.existsSync(A.path))return G_.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 O0(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),G_.debug("[WorktreeManager] Found worktree from session mapping",{sessionId:_,path:E}),{worktree:Q,isNew:!1};else G_.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 O0(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),G_.debug("[WorktreeManager] Found existing worktree (legacy)",{sessionId:_,path:X.path}),{worktree:X,isNew:!1};let H=this.getWorktreePath(J,_);if(D_.existsSync(H)){G_.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=ih(),Y=this.getWorktreesBasePath(J),K=r_.join(Y,Z),$=`session/${Z}`,G=0;while(D_.existsSync(K)){G++;let V=`${Z}-${G}`;K=r_.join(Y,V),$=`session/${V}`}if(!D_.existsSync(Y))D_.mkdirSync(Y,{recursive:!0}),G_.debug("[WorktreeManager] Created worktrees base directory",{basePath:Y});let U=await mW(J,K,$);return U.sessionId=_,this.saveSessionMapping(_,K),this.worktreeCache.set(_,U),G_.info("[WorktreeManager] Created new worktree",{sessionId:_,worktreeName:r_.basename(K),path:U.path,branch:U.branch}),{worktree:U,isNew:!0}}async getWorktreeForSession(_,T){G_.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 O0(T);if(!E)return null;let L=await D5(E,_);if(L)L.sessionId=_,this.worktreeCache.set(_,L);return L}async listWorktreesForRepo(_){G_.debug("[WorktreeManager] listWorktreesForRepo",{repoPath:_});let T=await O0(_);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);G_.info("[WorktreeManager] Updated session ID mapping",{worktreePath:_,oldSessionId:T,newSessionId:A})}catch(E){G_.error("[WorktreeManager] Failed to update session ID",{error:E,worktreePath:_,oldSessionId:T,newSessionId:A})}}async renameWorktreeForSession(_,T,A){G_.info("[WorktreeManager] Renaming worktree for session",{oldSessionId:_,newSessionId:T,repoPath:A});try{let E=await O0(A);if(!E)return G_.error("[WorktreeManager] Could not determine repo root for rename"),null;let L=this.worktreeCache.get(_);if(!L){if(G_.warn("[WorktreeManager] No cached worktree found for old session ID",{oldSessionId:_}),!await D5(E,_))return G_.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 G_.warn("[WorktreeManager] Old worktree path does not exist",{oldPath:J}),null;if(D_.existsSync(X)){G_.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 nW(E,J,X),G_.debug("[WorktreeManager] Moved worktree",{from:J,to:X}),await lW(X,H,Z),G_.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),G_.info("[WorktreeManager] Successfully renamed worktree",{oldSessionId:_,newSessionId:T,oldPath:J,newPath:X,oldBranch:H,newBranch:Z}),Y}catch(E){return G_.error("[WorktreeManager] Failed to rename worktree",{error:E,oldSessionId:_,newSessionId:T}),null}}}import*as K9 from"path";import*as LN from"os";var w1=v(),B5=K9.join(LN.homedir(),".ccc"),EN=K9.join(B5,"pending-permissions.json");class JN{cache=null;async ensureDirectory(){try{let _=await import("fs");if(!_.existsSync(B5))_.mkdirSync(B5,{recursive:!0}),w1.debug("[PendingPermissions] Created .ccc directory:",B5)}catch(_){throw w1.error("[PendingPermissions] Error ensuring directory:",_),_}}async load(){if(this.cache)return this.cache;try{let _=Bun.file(EN);if(await _.exists()){let T=await _.text();return this.cache=JSON.parse(T),w1.debug("[PendingPermissions] Loaded permissions:",{count:this.cache?.permissions?.length||0}),this.cache}}catch(_){w1.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(EN,JSON.stringify(_,null,2)),this.cache=_,w1.debug("[PendingPermissions] Saved permissions:",{count:_.permissions.length})}catch(T){throw w1.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]=_,w1.debug("[PendingPermissions] Updated existing permission:",{requestId:_.requestId,sessionId:_.sessionId});else T.permissions.push(_),w1.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),w1.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),w1.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),w1.info("[PendingPermissions] Cleared all pending permissions")}clearCache(){this.cache=null,w1.debug("[PendingPermissions] Cleared cache")}}var LT=new JN;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 E9(_,{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 O0(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:$}=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=$;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((G)=>G.status==="waiting_permission"&&G.sessionId).map((G)=>G.sessionId)),Y=X.filter((G)=>Z.has(G.sessionId)),K=`permissions/pending/${E}/response`,$={permissions:Y,timestamp:Date.now()};await this.mqttClient?.publish(K,JSON.stringify($)),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 $={request_id:L.request_id,action:X,params:H,permission_suggestions:Z,decision_reason:Y,blocked_path:K},G=`claude/${A}/permission/request/${E}`,U=JSON.stringify($);m.info("[ClaudeAgent] Publishing transformed permission request:",{topic:G,request_id:$.request_id,action:$.action}),this.mqttClient.publish(G,U).catch((V)=>{m.error(`[ClaudeAgent] Failed to publish permission request to ${G}`,{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=XN.join(_,".claude"),E=XN.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 v_ from"path";var u0=v();class I5{validatePath(_,T){try{let A=v_.resolve(_),E=v_.resolve(A,T);if(!(E===A||E.startsWith(A+v_.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=v_.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=v_.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=v_.basename(T);if(!this.isValidFilename(E))return{success:!1,error:"Invalid filename"};let L=v_.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=v_.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===v_.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(v_.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=v_.basename(T);if(!this.isValidFilename(L))return{success:!1,error:"Invalid filename"};let J=v_.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=v_.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 $9 from"path";var A1=v(),R4=51200,HN=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(HN)}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:$9.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=$9.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),$={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,$),H<J-1)await this.delay(HN)}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 kW(),!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 J9(),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 fW(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 bW(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 gW(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([O0(T.path),F4(T.path),iW(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 X9(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 uW(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 X9(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 dW(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 cW(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 pW(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 aW(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 oW(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 rW(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 tW(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 sW(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 eW(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 H9(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 _N(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 TN(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 NN from"path";import*as x5 from"path";import*as KN from"os";var d_=v(),S8=x5.join(KN.homedir(),".ccc"),ZN=x5.join(S8,"device-tokens.json"),YN=x5.join(S8,"notification-preferences.json");class $N{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(ZN);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(ZN,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(YN);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(YN,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 S1=new $N;var G9=null;async function GN(){if(!G9)G9=await import("expo-server-sdk");return G9}var $1=v();class UN{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;async getExpo(){if(!this.expo){let _=await GN();this.expo=new _.default}return this.expo}async isValidToken(_){return(await GN()).default.isExpoPushToken(_)}async sendNotification(_,T){if(!await this.isValidToken(_))return $1.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 J=(await(await this.getExpo()).sendPushNotificationsAsync([A]))[0];if(this.notificationsSent++,this.lastNotificationAt=new Date,J.id){let X=J;this.pendingTickets.set(X.id,{ticketId:X.id,token:_,createdAt:new Date})}if(J.status==="error"){let X=J;await this.handleTicketError(X,_)}return $1.debug("[ExpoPushClient] Sent notification:",{token:_.substring(0,20)+"...",status:J.status}),J}catch(E){return $1.error("[ExpoPushClient] Error sending notification:",E),null}}async sendBatchNotifications(_,T){let A=[];for(let H of _)if(!await this.isValidToken(H))$1.warn("[ExpoPushClient] Skipping invalid token:",{token:H.substring(0,20)+"..."});else A.push(H);if(A.length===0)return $1.warn("[ExpoPushClient] No valid tokens to send to"),[];let E=A.map((H)=>({to:H,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=await this.getExpo(),J=L.chunkPushNotifications(E),X=[];for(let H of J)try{let Z=await L.sendPushNotificationsAsync(H);X.push(...Z);for(let Y=0;Y<Z.length;Y++){let K=Z[Y],$=A[X.length-Z.length+Y];if(K.id){let G=K;this.pendingTickets.set(G.id,{ticketId:G.id,token:$,createdAt:new Date})}if(K.status==="error")await this.handleTicketError(K,$)}this.notificationsSent+=Z.length,this.lastNotificationAt=new Date}catch(Z){$1.error("[ExpoPushClient] Error sending batch chunk:",Z)}return $1.info("[ExpoPushClient] Sent batch notifications:",{total:A.length,successful:X.filter((H)=>H.status==="ok").length,failed:X.filter((H)=>H.status==="error").length}),X}async handleTicketError(_,T){if($1.warn("[ExpoPushClient] Ticket error:",{message:_.message,details:_.details}),_.details?.error==="DeviceNotRegistered"){$1.info("[ExpoPushClient] Removing invalid token:",{token:T.substring(0,20)+"..."});let E=(await S1.getAllTokens()).find((L)=>L.expoPushToken===T);if(E)await S1.unregisterToken(E.deviceId)}}async checkReceipts(){let _=new Date;_.setMinutes(_.getMinutes()-15);let T=[];for(let[J,X]of this.pendingTickets.entries())if(X.createdAt<_)T.push(J);if(T.length===0)return;$1.debug("[ExpoPushClient] Checking receipts:",{count:T.length});let A=await this.getExpo(),E=A.chunkPushNotificationReceiptIds(T);for(let J of E)try{let X=await A.getPushNotificationReceiptsAsync(J);for(let[H,Z]of Object.entries(X)){let Y=this.pendingTickets.get(H);if(Z.status==="ok")$1.debug("[ExpoPushClient] Receipt OK:",{ticketId:H});else if(Z.status==="error"){let K=Z;if($1.warn("[ExpoPushClient] Receipt error:",{ticketId:H,message:K.message,details:K.details}),K.details?.error==="DeviceNotRegistered"&&Y){let G=(await S1.getAllTokens()).find((U)=>U.expoPushToken===Y.token);if(G)$1.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:G.deviceId}),await S1.unregisterToken(G.deviceId)}}this.pendingTickets.delete(H)}}catch(X){$1.error("[ExpoPushClient] Error checking receipts:",X)}let L=new Date;L.setHours(L.getHours()-24);for(let[J,X]of this.pendingTickets.entries())if(X.createdAt<L)this.pendingTickets.delete(J)}getStats(){return{notificationsSent:this.notificationsSent,lastNotificationAt:this.lastNotificationAt,pendingReceipts:this.pendingTickets.size}}}var y8=new UN;var Q_=v(),WN=200,ah=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:",_)})},ah),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 S1.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 S1.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 S1.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=NN.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
2640
  `);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();
2641
+ `)}if(!T.trim())return null;if(T.length>WN)T=T.substring(0,WN)+"...";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 S1.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 S1.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 U9{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 QN from"os";function MN(){let _=QN.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 VN(){let _=QN.hostname().toLowerCase();if(_.endsWith(".local"))_=_.slice(0,-6);return _=_.replace(/\./g,"-"),_||"ccc-server"}var zN=process.argv.slice(2);if(zN.includes("--version")||zN.includes("-v"))console.log(`ccc v${G1()}`),process.exit(0);function oh(_){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 rh(){try{D9();let _=V9();F9(_.debug);let T=v();T.info("Backend v2 starting...");let A=z9(_);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 $5(A.terminal),X=new U5(A.router),H=new z5(A.autoUpdate),Z=new F5,Y=new C5,K=new O5(J),$=new q5(A.claudeAgent),G=new P5,U=new j5,V=new w5,N=new U9;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($),N.addService(G),N.addService(U),N.addService(V),A.ngrok){let c=new W5(A.ngrok);N.addOptionalService(c,!0)}Z.setMQTTClient(L),Z.setClaudeAgentService($),Y.setMQTTClient(L),K.setMQTTClient(L),$.setMQTTClient(L),$.setSessionsService(Z),G.setMQTTClient(L),U.setMQTTClient(L),V.setMQTTClient(L),V.setClaudeAgentService($),await N.startAll();let z=N.getServiceByName("CCC Ngrok Service"),Q,F=MN(),R=F?`${F}:${A.router.port}`:void 0;if(z&&z.getStatus().active)Q=z.getUrl()||void 0;let q=VN(),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"),oh(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)}}rh();