@naarang/ccc 2.0.0-alpha.6 → 2.0.0-alpha.8

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.
Files changed (2) hide show
  1. package/dist/index.js +43 -43
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
1
  // @bun
2
- var RN=Object.create;var{getPrototypeOf:DN,defineProperty:Q9,getOwnPropertyNames:BN}=Object;var qN=Object.prototype.hasOwnProperty;var B_=(_,T,A)=>{A=_!=null?RN(DN(_)):{};let E=T||!_||!_.__esModule?Q9(A,"default",{value:_,enumerable:!0}):A;for(let L of BN(_))if(!qN.call(E,L))Q9(E,L,{get:()=>_[L],enumerable:!0});return E};var W=(_,T)=>()=>(T||_((T={exports:{}}).exports,T),T.exports);var I=import.meta.require;var I9=W((Vk,q9)=>{q9.exports=gN;var bN=Object.prototype.hasOwnProperty;function gN(){var _={};for(var T=0;T<arguments.length;T++){var A=arguments[T];for(var E in A)if(bN.call(A,E))_[E]=A[E]}return _}});var f8=W((zk,P9)=>{function mN(_){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}}P9.exports=mN});var g5=W((Fk,x9)=>{var uN=I9(),j9=f8(),dN={released:D0,results:!0};function cN(_){_=uN(dN,_);var T=_.released,A=j9(_.results?nN:pN),E=j9(lN),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 pN(){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 lN(){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 nN(){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(){}x9.exports=cN});var y9=W((Ck,S9)=>{var iN={results:!0};function aN(_){_=Object.assign({},iN,_);var T,A;if(_.results)T=sN,A=tN;else T=oN,A=rN;return E;function E(L,J,X,H){if(H=(H||eN).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 oN(_,T,A){var E=0,L=T.length;J();function J(){if(E<L)b8(_,T[E++],J);else A()}}function rN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=w9;else J=b8;X();function X(){if(E<L)J(_[E++],T,X);else A()}}function sN(_,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)b8(_,T[E++],X);else A(null,J)}}function tN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=w9;else J=b8;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 w9(_,T,A){_(A)}function b8(_,T,A){_(T,A)}function eN(){}S9.exports=aN});var k9=W((v9)=>{Object.defineProperty(v9,"__esModule",{value:!0});v9.default=void 0;var Ok=v9.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var g9=W((f9)=>{Object.defineProperty(f9,"__esModule",{value:!0});f9.default=void 0;var Dk=f9.default="00000000-0000-0000-0000-000000000000"});var d9=W((m9)=>{Object.defineProperty(m9,"__esModule",{value:!0});m9.default=void 0;var qk=m9.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((c9)=>{Object.defineProperty(c9,"__esModule",{value:!0});c9.default=void 0;var _Q=TQ(d9());function TQ(_){return _&&_.__esModule?_:{default:_}}function AQ(_){return typeof _==="string"&&_Q.default.test(_)}var Pk=c9.default=AQ});var j4=W((l9)=>{Object.defineProperty(l9,"__esModule",{value:!0});l9.default=void 0;var EQ=LQ(P4());function LQ(_){return _&&_.__esModule?_:{default:_}}function JQ(_){if(!(0,EQ.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 xk=l9.default=JQ});var B0=W((a9)=>{Object.defineProperty(a9,"__esModule",{value:!0});a9.default=void 0;a9.unsafeStringify=i9;var XQ=HQ(P4());function HQ(_){return _&&_.__esModule?_:{default:_}}var b_=[];for(let _=0;_<256;++_)b_.push((_+256).toString(16).slice(1));function i9(_,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 ZQ(_,T=0){let A=i9(_,T);if(!(0,XQ.default)(A))throw TypeError("Stringified UUID is invalid");return A}var Sk=a9.default=ZQ});var u8=W((r9)=>{Object.defineProperty(r9,"__esModule",{value:!0});r9.default=GQ;var KQ=$Q(I("crypto"));function $Q(_){return _&&_.__esModule?_:{default:_}}var m8=new Uint8Array(256),g8=m8.length;function GQ(){if(g8>m8.length-16)KQ.default.randomFillSync(m8),g8=0;return m8.slice(g8,g8+=16)}});var c5=W((s9)=>{Object.defineProperty(s9,"__esModule",{value:!0});s9.default=void 0;var WQ=QQ(u8()),NQ=B0();function QQ(_){return _&&_.__esModule?_:{default:_}}var m5,d8,u5=0,d5=0;function MQ(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let{node:J,clockseq:X}=_;if(!_._v6){if(!J)J=m5;if(X==null)X=d8}if(J==null||X==null){let G=_.random||(_.rng||WQ.default)();if(J==null){if(J=[G[0],G[1],G[2],G[3],G[4],G[5]],!m5&&!_._v6)J[0]|=1,m5=J}if(X==null){if(X=(G[6]<<8|G[7])&16383,d8===void 0&&!_._v6)d8=X}}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:d5+1,Y=H-u5+(Z-d5)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>u5)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");u5=H,d5=Z,d8=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,NQ.unsafeStringify)(L)}var hk=s9.default=MQ});var p5=W((e9)=>{Object.defineProperty(e9,"__esModule",{value:!0});e9.default=CQ;var VQ=FQ(j4()),zQ=B0();function FQ(_){return _&&_.__esModule?_:{default:_}}function CQ(_){let T=typeof _==="string"?(0,VQ.default)(_):_,A=OQ(T);return typeof _==="string"?(0,zQ.unsafeStringify)(A):A}function OQ(_,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 l5=W((_7)=>{Object.defineProperty(_7,"__esModule",{value:!0});_7.URL=_7.DNS=void 0;_7.default=xQ;var DQ=B0(),BQ=qQ(j4());function qQ(_){return _&&_.__esModule?_:{default:_}}function IQ(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var PQ=_7.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",jQ=_7.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function xQ(_,T,A){function E(L,J,X,H){var Z;if(typeof L==="string")L=IQ(L);if(typeof J==="string")J=(0,BQ.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,DQ.unsafeStringify)(Y)}try{E.name=_}catch(L){}return E.DNS=PQ,E.URL=jQ,E}});var L7=W((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});A7.default=void 0;var yQ=vQ(I("crypto"));function vQ(_){return _&&_.__esModule?_:{default:_}}function hQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return yQ.default.createHash("md5").update(_).digest()}var gk=A7.default=hQ});var Z7=W((X7)=>{Object.defineProperty(X7,"__esModule",{value:!0});X7.default=void 0;var kQ=J7(l5()),fQ=J7(L7());function J7(_){return _&&_.__esModule?_:{default:_}}var bQ=(0,kQ.default)("v3",48,fQ.default),uk=X7.default=bQ});var $7=W((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});Y7.default=void 0;var gQ=mQ(I("crypto"));function mQ(_){return _&&_.__esModule?_:{default:_}}var ck=Y7.default={randomUUID:gQ.default.randomUUID}});var Q7=W((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});W7.default=void 0;var G7=U7($7()),uQ=U7(u8()),dQ=B0();function U7(_){return _&&_.__esModule?_:{default:_}}function cQ(_,T,A){if(G7.default.randomUUID&&!T&&!_)return G7.default.randomUUID();_=_||{};let E=_.random||(_.rng||uQ.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,dQ.unsafeStringify)(E)}var lk=W7.default=cQ});var z7=W((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});M7.default=void 0;var pQ=lQ(I("crypto"));function lQ(_){return _&&_.__esModule?_:{default:_}}function nQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return pQ.default.createHash("sha1").update(_).digest()}var ik=M7.default=nQ});var R7=W((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});C7.default=void 0;var iQ=F7(l5()),aQ=F7(z7());function F7(_){return _&&_.__esModule?_:{default:_}}var oQ=(0,iQ.default)("v5",80,aQ.default),ok=C7.default=oQ});var q7=W((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});B7.default=eQ;var rQ=B0(),sQ=D7(c5()),tQ=D7(p5());function D7(_){return _&&_.__esModule?_:{default:_}}function eQ(_={},T,A=0){let E=(0,sQ.default)({..._,_v6:!0},new Uint8Array(16));if(E=(0,tQ.default)(E),T){for(let L=0;L<16;L++)T[A+L]=E[L];return T}return(0,rQ.unsafeStringify)(E)}});var P7=W((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});I7.default=LM;var TM=EM(j4()),AM=B0();function EM(_){return _&&_.__esModule?_:{default:_}}function LM(_){let T=typeof _==="string"?(0,TM.default)(_):_,A=JM(T);return typeof _==="string"?(0,AM.unsafeStringify)(A):A}function JM(_){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 y7=W((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});w7.default=void 0;var HM=YM(u8()),ZM=B0();function YM(_){return _&&_.__esModule?_:{default:_}}var j7=null,x7=null,k1=0;function KM(_,T,A){_=_||{};let E=T&&A||0,L=T||new Uint8Array(16),J=_.random||(_.rng||HM.default)(),X=_.msecs!==void 0?_.msecs:Date.now(),H=_.seq!==void 0?_.seq:null,Z=x7,Y=j7;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 x7=Z,j7=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,ZM.unsafeStringify)(L)}var ek=w7.default=KM});var k7=W((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});v7.default=void 0;var $M=GM(P4());function GM(_){return _&&_.__esModule?_:{default:_}}function UM(_){if(!(0,$M.default)(_))throw TypeError("Invalid UUID");return parseInt(_.slice(14,15),16)}var Tf=v7.default=UM});var f7=W((p_)=>{Object.defineProperty(p_,"__esModule",{value:!0});Object.defineProperty(p_,"MAX",{enumerable:!0,get:function(){return WM.default}});Object.defineProperty(p_,"NIL",{enumerable:!0,get:function(){return NM.default}});Object.defineProperty(p_,"parse",{enumerable:!0,get:function(){return QM.default}});Object.defineProperty(p_,"stringify",{enumerable:!0,get:function(){return MM.default}});Object.defineProperty(p_,"v1",{enumerable:!0,get:function(){return VM.default}});Object.defineProperty(p_,"v1ToV6",{enumerable:!0,get:function(){return zM.default}});Object.defineProperty(p_,"v3",{enumerable:!0,get:function(){return FM.default}});Object.defineProperty(p_,"v4",{enumerable:!0,get:function(){return CM.default}});Object.defineProperty(p_,"v5",{enumerable:!0,get:function(){return OM.default}});Object.defineProperty(p_,"v6",{enumerable:!0,get:function(){return RM.default}});Object.defineProperty(p_,"v6ToV1",{enumerable:!0,get:function(){return DM.default}});Object.defineProperty(p_,"v7",{enumerable:!0,get:function(){return BM.default}});Object.defineProperty(p_,"validate",{enumerable:!0,get:function(){return qM.default}});Object.defineProperty(p_,"version",{enumerable:!0,get:function(){return IM.default}});var WM=J1(k9()),NM=J1(g9()),QM=J1(j4()),MM=J1(B0()),VM=J1(c5()),zM=J1(p5()),FM=J1(Z7()),CM=J1(Q7()),OM=J1(R7()),RM=J1(q7()),DM=J1(P7()),BM=J1(y7()),qM=J1(P4()),IM=J1(k7());function J1(_){return _&&_.__esModule?_:{default:_}}});var uT=W((Lf,b7)=>{function PM(_,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}b7.exports=PM});var n5=W((Jf,g7)=>{var f1=I("util");g7.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 o5=W((u7)=>{var c8=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,_)}c8.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,_)}c8.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 p8=I("stream");function i5(_){p8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}c8.inherits(i5,p8.Readable);i5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function a5(_){p8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}c8.inherits(a5,p8.Writable);a5.prototype._write=function(_,T,A){this._restorer(_),A()};var m7=null;function jM(_){if(_!==m7){let T=n5();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),m7=_}return u7}u7.Qlobber=L_;u7.QlobberDedup=V1;u7.QlobberTrue=s1;u7.VisitorStream=i5;u7.RestorerStream=a5;u7.set_native=jM});var d7=W((Hf,s5)=>{var kM=I("util"),fM=o5(),r5=fM.Qlobber;function z1(_){r5.call(this,_),this.subscriptionsCount=0}kM.inherits(z1,r5);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,r5.prototype.clear.call(this)};z1.set_native=function(_){let T=n5();return z1.native=T(_.QlobberSub,z1),s5.exports};s5.exports=z1});var n7=W((Zf,e5)=>{var{Readable:x4}=I("stream"),bM=d7(),{QlobberTrue:gM}=o5(),t5=uT(),p7={wildcard_one:"+",wildcard_some:"#",separator:"/"};function*mM(_){for(let T of _)yield*T}function*c7(_,T){let A=new gM(p7);A.add(T);for(let[E,L]of _)if(A.test(E))yield L}function*uM(_,T){for(let A of _.values())if(!T[A.brokerId])yield A}function*dM(_,T){for(let[A,E]of _)if(E.has(T))yield A}class l7{#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 bM(p7)}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 c7(this.#J,A)});return x4.from(mM(T))}createRetainedStream(_){return x4.from(c7(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 t5(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 t5(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(uM(this.#N,_))}getClientList(_){return x4.from(dM(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}e5.exports=()=>{return new l7};e5.exports.Packet=t5});var a7=W((Yf,i7)=>{var b1=I("util");i7.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 s7=W((r7)=>{var l8=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,_)}l8.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,_)}l8.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 n8=I("stream");function _6(_){n8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}l8.inherits(_6,n8.Readable);_6.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function T6(_){n8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}l8.inherits(T6,n8.Writable);T6.prototype._write=function(_,T,A){this._restorer(_),A()};var o7=null;function cM(_){if(_!==o7){let T=a7();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),o7=_}return r7}r7.Qlobber=J_;r7.QlobberDedup=F1;r7.QlobberTrue=t1;r7.VisitorStream=_6;r7.RestorerStream=T6;r7.set_native=cM});var e7=W(($f,t7)=>{var{Qlobber:rM}=s7(),dT=I("assert"),sM=g5();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=sM({results:!1,released:A}),this.concurrency=_.concurrency||0,this.current=0,this._doing=!1,this._matcher=new rM({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||tM,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 tM(){}t7.exports=e1});var z_=W((Gf,TJ)=>{class _J 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=_}}TJ.exports={AggregateError:_J,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 A6=W((Uf,AJ)=>{AJ.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((Wf,XJ)=>{var{format:eM,inspect:i8}=A6(),{AggregateError:_V}=z_(),TV=globalThis.AggregateError||_V,AV=Symbol("kIsNodeError"),EV=["string","function","number","object","Function","Object","boolean","bigint","symbol"],LV=/^([A-Z][a-z0-9]*)+$/,a8={};function YT(_,T){if(!_)throw new a8.ERR_INTERNAL_ASSERTION(T)}function EJ(_){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 JV(_,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 eM(T,...A)}function g_(_,T,A){if(!A)A=Error;class E extends A{constructor(...L){super(JV(_,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[AV]=!0,a8[_]=E}function LJ(_){let T="__node_internal_"+_.name;return Object.defineProperty(_,"name",{value:T}),_}function XV(_,T){if(_&&T&&_!==T){if(Array.isArray(T.errors))return T.errors.push(_),T;let A=new TV([T,_],T.message);return A.code=T.code,A}return _||T}class JJ extends Error{constructor(_="The operation was aborted",T=void 0){if(T!==void 0&&typeof T!=="object")throw new a8.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"),EV.includes(Z))L.push(Z.toLowerCase());else if(LV.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=i8(A,{depth:-1});E+=`. Received ${Z}`}}else{let Z=i8(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=i8(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=EJ(String(A));else if(typeof A==="bigint"){E=String(A);let L=BigInt(2)**BigInt(32);if(A>L||A<-L)E=EJ(E);E+="n"}else E=i8(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);XJ.exports={AbortError:JJ,aggregateTwoErrors:LJ(XV),hideStackFrames:LJ,codes:a8}});var s_=W((Nf,L6)=>{var HV=I("buffer"),{format:ZV,inspect:YV}=A6(),{codes:{ERR_INVALID_ARG_TYPE:E6}}=l_(),{kResistStopPropagation:KV,AggregateError:$V,SymbolDispose:GV}=z_(),UV=globalThis.AbortSignal||I("abort-controller").AbortSignal,WV=globalThis.AbortController||I("abort-controller").AbortController,NV=Object.getPrototypeOf(async function(){}).constructor,HJ=globalThis.Blob||HV.Blob,QV=typeof HJ<"u"?function(T){return T instanceof HJ}:function(T){return!1},ZJ=(_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new E6(T,"AbortSignal",_)},MV=(_,T)=>{if(typeof _!=="function")throw new E6(T,"Function",_)};L6.exports={AggregateError:$V,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:ZV,inspect:YV,types:{isAsyncFunction(_){return _ instanceof NV},isArrayBufferView(_){return ArrayBuffer.isView(_)}},isBlob:QV,deprecate(_,T){return _},addAbortListener:I("events").addAbortListener||function(T,A){if(T===void 0)throw new E6("signal","AbortSignal",T);ZJ(T,"signal"),MV(A,"listener");let E;if(T.aborted)queueMicrotask(()=>A());else T.addEventListener("abort",A,{__proto__:null,once:!0,[KV]:!0}),E=()=>{T.removeEventListener("abort",A)};return{__proto__:null,[GV](){var L;(L=E)===null||L===void 0||L()}}},AbortSignalAny:UV.any||function(T){if(T.length===1)return T[0];let A=new WV,E=()=>A.abort();return T.forEach((L)=>{ZJ(L,"signals"),L.addEventListener("abort",E,{once:!0})}),A.signal.addEventListener("abort",()=>{T.forEach((L)=>L.removeEventListener("abort",E))},{once:!0}),A.signal}};L6.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var pT=W((Qf,VJ)=>{var{ArrayIsArray:X6,ArrayPrototypeIncludes:GJ,ArrayPrototypeJoin:UJ,ArrayPrototypeMap:VV,NumberIsInteger:H6,NumberIsNaN:zV,NumberMAX_SAFE_INTEGER:FV,NumberMIN_SAFE_INTEGER:CV,NumberParseInt:OV,ObjectPrototypeHasOwnProperty:RV,RegExpPrototypeExec:WJ,String:DV,StringPrototypeToUpperCase:BV,StringPrototypeTrim:qV}=z_(),{hideStackFrames:C1,codes:{ERR_SOCKET_BAD_PORT:IV,ERR_INVALID_ARG_TYPE:n_,ERR_INVALID_ARG_VALUE:cT,ERR_OUT_OF_RANGE:KT,ERR_UNKNOWN_SIGNAL:YJ}}=l_(),{normalizeEncoding:PV}=s_(),{isAsyncFunction:jV,isArrayBufferView:xV}=s_().types,KJ={};function wV(_){return _===(_|0)}function SV(_){return _===_>>>0}var yV=/^[0-7]+$/,vV="must be a 32-bit unsigned integer or an octal string";function hV(_,T,A){if(typeof _>"u")_=A;if(typeof _==="string"){if(WJ(yV,_)===null)throw new cT(T,_,vV);_=OV(_,8)}return NJ(_,T),_}var kV=C1((_,T,A=CV,E=FV)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!H6(_))throw new KT(T,"an integer",_);if(_<A||_>E)throw new KT(T,`>= ${A} && <= ${E}`,_)}),fV=C1((_,T,A=-2147483648,E=2147483647)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!H6(_))throw new KT(T,"an integer",_);if(_<A||_>E)throw new KT(T,`>= ${A} && <= ${E}`,_)}),NJ=C1((_,T,A=!1)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!H6(_))throw new KT(T,"an integer",_);let E=A?1:0,L=4294967295;if(_<E||_>L)throw new KT(T,`>= ${E} && <= ${L}`,_)});function Z6(_,T){if(typeof _!=="string")throw new n_(T,"string",_)}function bV(_,T,A=void 0,E){if(typeof _!=="number")throw new n_(T,"number",_);if(A!=null&&_<A||E!=null&&_>E||(A!=null||E!=null)&&zV(_))throw new KT(T,`${A!=null?`>= ${A}`:""}${A!=null&&E!=null?" && ":""}${E!=null?`<= ${E}`:""}`,_)}var gV=C1((_,T,A)=>{if(!GJ(A,_)){let L="must be one of: "+UJ(VV(A,(J)=>typeof J==="string"?`'${J}'`:DV(J)),", ");throw new cT(T,_,L)}});function QJ(_,T){if(typeof _!=="boolean")throw new n_(T,"boolean",_)}function J6(_,T,A){return _==null||!RV(_,T)?A:_[T]}var mV=C1((_,T,A=null)=>{let E=J6(A,"allowArray",!1),L=J6(A,"allowFunction",!1);if(!J6(A,"nullable",!1)&&_===null||!E&&X6(_)||typeof _!=="object"&&(!L||typeof _!=="function"))throw new n_(T,"Object",_)}),uV=C1((_,T)=>{if(_!=null&&typeof _!=="object"&&typeof _!=="function")throw new n_(T,"a dictionary",_)}),o8=C1((_,T,A=0)=>{if(!X6(_))throw new n_(T,"Array",_);if(_.length<A){let E=`must be longer than ${A}`;throw new cT(T,_,E)}});function dV(_,T){o8(_,T);for(let A=0;A<_.length;A++)Z6(_[A],`${T}[${A}]`)}function cV(_,T){o8(_,T);for(let A=0;A<_.length;A++)QJ(_[A],`${T}[${A}]`)}function pV(_,T){o8(_,T);for(let A=0;A<_.length;A++){let E=_[A],L=`${T}[${A}]`;if(E==null)throw new n_(L,"AbortSignal",E);MJ(E,L)}}function lV(_,T="signal"){if(Z6(_,T),KJ[_]===void 0){if(KJ[BV(_)]!==void 0)throw new YJ(_+" (signals must use all capital letters)");throw new YJ(_)}}var nV=C1((_,T="buffer")=>{if(!xV(_))throw new n_(T,["Buffer","TypedArray","DataView"],_)});function iV(_,T){let A=PV(T),E=_.length;if(A==="hex"&&E%2!==0)throw new cT("encoding",T,`is invalid for data of length ${E}`)}function aV(_,T="Port",A=!0){if(typeof _!=="number"&&typeof _!=="string"||typeof _==="string"&&qV(_).length===0||+_!==+_>>>0||_>65535||_===0&&!A)throw new IV(T,_,A);return _|0}var MJ=C1((_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new n_(T,"AbortSignal",_)}),oV=C1((_,T)=>{if(typeof _!=="function")throw new n_(T,"Function",_)}),rV=C1((_,T)=>{if(typeof _!=="function"||jV(_))throw new n_(T,"Function",_)}),sV=C1((_,T)=>{if(_!==void 0)throw new n_(T,"undefined",_)});function tV(_,T,A){if(!GJ(A,_))throw new n_(T,`('${UJ(A,"|")}')`,_)}var eV=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function $J(_,T){if(typeof _>"u"||!WJ(eV,_))throw new cT(T,_,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function _z(_){if(typeof _==="string")return $J(_,"hints"),_;else if(X6(_)){let T=_.length,A="";if(T===0)return A;for(let E=0;E<T;E++){let L=_[E];if($J(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"')}VJ.exports={isInt32:wV,isUint32:SV,parseFileMode:hV,validateArray:o8,validateStringArray:dV,validateBooleanArray:cV,validateAbortSignalArray:pV,validateBoolean:QJ,validateBuffer:nV,validateDictionary:uV,validateEncoding:iV,validateFunction:oV,validateInt32:fV,validateInteger:kV,validateNumber:bV,validateObject:mV,validateOneOf:gV,validatePlainFunction:rV,validatePort:aV,validateSignalName:lV,validateString:Z6,validateUint32:NJ,validateUndefined:sV,validateUnion:tV,validateAbortSignal:MJ,validateLinkHeaderValue:_z}});var c0=W((Mf,zJ)=>{zJ.exports=global.process});var T0=W((Vf,vJ)=>{var{SymbolAsyncIterator:FJ,SymbolIterator:CJ,SymbolFor:$T}=z_(),OJ=$T("nodejs.stream.destroyed"),RJ=$T("nodejs.stream.errored"),Y6=$T("nodejs.stream.readable"),K6=$T("nodejs.stream.writable"),DJ=$T("nodejs.stream.disturbed"),Tz=$T("nodejs.webstream.isClosedPromise"),Az=$T("nodejs.webstream.controllerErrorFunction");function r8(_,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 s8(_){var T;return!!(_&&typeof _.write==="function"&&typeof _.on==="function"&&(!_._readableState||((T=_._writableState)===null||T===void 0?void 0:T.writable)!==!1))}function Ez(_){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 BJ(_){return!!(_&&!_0(_)&&typeof _.pipeThrough==="function"&&typeof _.getReader==="function"&&typeof _.cancel==="function")}function qJ(_){return!!(_&&!_0(_)&&typeof _.getWriter==="function"&&typeof _.abort==="function")}function IJ(_){return!!(_&&!_0(_)&&typeof _.readable==="object"&&typeof _.writable==="object")}function Lz(_){return BJ(_)||qJ(_)||IJ(_)}function Jz(_,T){if(_==null)return!1;if(T===!0)return typeof _[FJ]==="function";if(T===!1)return typeof _[CJ]==="function";return typeof _[FJ]==="function"||typeof _[CJ]==="function"}function t8(_){if(!_0(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!!(_.destroyed||_[OJ]||E!==null&&E!==void 0&&E.destroyed)}function PJ(_){if(!s8(_))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 Xz(_,T){if(!s8(_))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 Hz(_){if(!r8(_))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 jJ(_,T){if(!r8(_))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 xJ(_){if(_&&_[Y6]!=null)return _[Y6];if(typeof(_===null||_===void 0?void 0:_.readable)!=="boolean")return null;if(t8(_))return!1;return r8(_)&&_.readable&&!jJ(_)}function wJ(_){if(_&&_[K6]!=null)return _[K6];if(typeof(_===null||_===void 0?void 0:_.writable)!=="boolean")return null;if(t8(_))return!1;return s8(_)&&_.writable&&!PJ(_)}function Zz(_,T){if(!_0(_))return null;if(t8(_))return!0;if((T===null||T===void 0?void 0:T.readable)!==!1&&xJ(_))return!1;if((T===null||T===void 0?void 0:T.writable)!==!1&&wJ(_))return!1;return!0}function Yz(_){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 Kz(_){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 $z(_){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"&&SJ(_))return _._closed;return null}function SJ(_){return typeof _._closed==="boolean"&&typeof _._defaultKeepAlive==="boolean"&&typeof _._removedConnection==="boolean"&&typeof _._removedContLen==="boolean"}function yJ(_){return typeof _._sent100==="boolean"&&SJ(_)}function Gz(_){var T;return typeof _._consuming==="boolean"&&typeof _._dumped==="boolean"&&((T=_.req)===null||T===void 0?void 0:T.upgradeOrConnect)===void 0}function Uz(_){if(!_0(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!E&&yJ(_)||!!(E&&E.autoDestroy&&E.emitClose&&E.closed===!1)}function Wz(_){var T;return!!(_&&((T=_[DJ])!==null&&T!==void 0?T:_.readableDidRead||_.readableAborted))}function Nz(_){var T,A,E,L,J,X,H,Z,Y,K;return!!(_&&((T=(A=(E=(L=(J=(X=_[RJ])!==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))}vJ.exports={isDestroyed:t8,kIsDestroyed:OJ,isDisturbed:Wz,kIsDisturbed:DJ,isErrored:Nz,kIsErrored:RJ,isReadable:xJ,kIsReadable:Y6,kIsClosedPromise:Tz,kControllerErrorFunction:Az,kIsWritable:K6,isClosed:$z,isDuplexNodeStream:Ez,isFinished:Zz,isIterable:Jz,isReadableNodeStream:r8,isReadableStream:BJ,isReadableEnded:Hz,isReadableFinished:jJ,isReadableErrored:Kz,isNodeStream:_0,isWebStream:Lz,isWritable:wJ,isWritableNodeStream:s8,isWritableStream:qJ,isWritableEnded:PJ,isWritableFinished:Xz,isWritableErrored:Yz,isServerRequest:Gz,isServerResponse:yJ,willEmitClose:Uz,isTransformStream:IJ}});var q0=W((zf,N6)=>{var p0=c0(),{AbortError:cJ,codes:Qz}=l_(),{ERR_INVALID_ARG_TYPE:Mz,ERR_STREAM_PREMATURE_CLOSE:hJ}=Qz,{kEmptyObject:G6,once:U6}=s_(),{validateAbortSignal:Vz,validateFunction:zz,validateObject:Fz,validateBoolean:Cz}=pT(),{Promise:Oz,PromisePrototypeThen:Rz,SymbolDispose:pJ}=z_(),{isClosed:Dz,isReadable:kJ,isReadableNodeStream:$6,isReadableStream:Bz,isReadableFinished:fJ,isReadableErrored:bJ,isWritable:gJ,isWritableNodeStream:mJ,isWritableStream:qz,isWritableFinished:uJ,isWritableErrored:dJ,isNodeStream:Iz,willEmitClose:Pz,kIsClosedPromise:jz}=T0(),lT;function xz(_){return _.setHeader&&typeof _.abort==="function"}var W6=()=>{};function lJ(_,T,A){var E,L;if(arguments.length===2)A=T,T=G6;else if(T==null)T=G6;else Fz(T,"options");if(zz(A,"callback"),Vz(T.signal,"options.signal"),A=U6(A),Bz(_)||qz(_))return wz(_,T,A);if(!Iz(_))throw new Mz("stream",["ReadableStream","WritableStream","Stream"],_);let J=(E=T.readable)!==null&&E!==void 0?E:$6(_),X=(L=T.writable)!==null&&L!==void 0?L:mJ(_),H=_._writableState,Z=_._readableState,Y=()=>{if(!_.writable)G()},K=Pz(_)&&$6(_)===J&&mJ(_)===X,$=uJ(_,!1),G=()=>{if($=!0,_.destroyed)K=!1;if(K&&(!_.readable||J))return;if(!J||U)A.call(_)},U=fJ(_,!1),V=()=>{if(U=!0,_.destroyed)K=!1;if(K&&(!_.writable||X))return;if(!X||$)A.call(_)},N=(b)=>{A.call(_,b)},z=Dz(_),Q=()=>{z=!0;let b=dJ(_)||bJ(_);if(b&&typeof b!=="boolean")return A.call(_,b);if(J&&!U&&$6(_,!0)){if(!fJ(_,!1))return A.call(_,new hJ)}if(X&&!$){if(!uJ(_,!1))return A.call(_,new hJ)}A.call(_)},F=()=>{z=!0;let b=dJ(_)||bJ(_);if(b&&typeof b!=="boolean")return A.call(_,b);A.call(_)},R=()=>{_.req.on("finish",G)};if(xz(_)){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||kJ(_))&&($||gJ(_)===!1))p0.nextTick(F);else if(!X&&(!K||gJ(_))&&(U||kJ(_)===!1))p0.nextTick(F);else if(Z&&_.req&&_.aborted)p0.nextTick(F);let q=()=>{if(A=W6,_.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 b=()=>{let k=A;q(),k.call(_,new cJ(void 0,{cause:T.signal.reason}))};if(T.signal.aborted)p0.nextTick(b);else{lT=lT||s_().addAbortListener;let k=lT(T.signal,b),g=A;A=U6((...l)=>{k[pJ](),g.apply(_,l)})}}return q}function wz(_,T,A){let E=!1,L=W6;if(T.signal)if(L=()=>{E=!0,A.call(_,new cJ(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=U6((...Z)=>{X[pJ](),H.apply(_,Z)})}let J=(...X)=>{if(!E)p0.nextTick(()=>A.apply(_,X))};return Rz(_[jz].promise,J,J),W6}function Sz(_,T){var A;let E=!1;if(T===null)T=G6;if((A=T)!==null&&A!==void 0&&A.cleanup)Cz(T.cleanup,"cleanup"),E=T.cleanup;return new Oz((L,J)=>{let X=lJ(_,T,(H)=>{if(E)X();if(H)J(H);else L()})})}N6.exports=lJ;N6.exports.finished=Sz});var GT=W((Ff,eJ)=>{var A0=c0(),{aggregateTwoErrors:yz,codes:{ERR_MULTIPLE_CALLBACK:vz},AbortError:hz}=l_(),{Symbol:aJ}=z_(),{kIsDestroyed:kz,isDestroyed:fz,isFinished:bz,isServerRequest:gz}=T0(),oJ=aJ("kDestroy"),Q6=aJ("kConstruct");function rJ(_,T,A){if(_){if(_.stack,T&&!T.errored)T.errored=_;if(A&&!A.errored)A.errored=_}}function mz(_,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(rJ(_,E,A),E)E.destroyed=!0;if(A)A.destroyed=!0;if(!L.constructed)this.once(oJ,function(J){nJ(this,yz(J,_),T)});else nJ(this,_,T);return this}function nJ(_,T,A){let E=!1;function L(J){if(E)return;E=!0;let{_readableState:X,_writableState:H}=_;if(rJ(J,H,X),H)H.closed=!0;if(X)X.closed=!0;if(typeof A==="function")A(J);if(J)A0.nextTick(uz,_,J);else A0.nextTick(sJ,_)}try{_._destroy(T||null,L)}catch(J){L(J)}}function uz(_,T){M6(_,T),sJ(_)}function sJ(_){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 M6(_,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 dz(){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 V6(_,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(M6,_,T);else M6(_,T)}}function cz(_,T){if(typeof _._construct!=="function")return;let{_readableState:A,_writableState:E}=_;if(A)A.constructed=!1;if(E)E.constructed=!1;if(_.once(Q6,T),_.listenerCount(Q6)>1)return;A0.nextTick(pz,_)}function pz(_){let T=!1;function A(E){if(T){V6(_,E!==null&&E!==void 0?E:new vz);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(oJ,E);else if(E)V6(_,E,!0);else A0.nextTick(lz,_)}try{_._construct((E)=>{A0.nextTick(A,E)})}catch(E){A0.nextTick(A,E)}}function lz(_){_.emit(Q6)}function iJ(_){return(_===null||_===void 0?void 0:_.setHeader)&&typeof _.abort==="function"}function tJ(_){_.emit("close")}function nz(_,T){_.emit("error",T),A0.nextTick(tJ,_)}function iz(_,T){if(!_||fz(_))return;if(!T&&!bz(_))T=new hz;if(gz(_))_.socket=null,_.destroy(T);else if(iJ(_))_.abort();else if(iJ(_.req))_.req.abort();else if(typeof _.destroy==="function")_.destroy(T);else if(typeof _.close==="function")_.close();else if(T)A0.nextTick(nz,_,T);else A0.nextTick(tJ,_);if(!_.destroyed)_[kz]=!0}eJ.exports={construct:cz,destroyer:iz,destroy:mz,undestroy:dz,errorOrDestroy:V6}});var TA=W((Cf,TX)=>{var{ArrayIsArray:az,ObjectSetPrototypeOf:_X}=z_(),{EventEmitter:e8}=I("events");function _A(_){e8.call(this,_)}_X(_A.prototype,e8.prototype);_X(_A,e8);_A.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(),e8.listenerCount(this,"error")===0)this.emit("error",K)}z6(A,"error",Z),z6(_,"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 z6(_,T,A){if(typeof _.prependListener==="function")return _.prependListener(T,A);if(!_._events||!_._events[T])_.on(T,A);else if(az(_._events[T]))_._events[T].unshift(A);else _._events[T]=[A,_._events[T]]}TX.exports={Stream:_A,prependListener:z6}});var w4=W((TF,AA)=>{var{SymbolDispose:oz}=z_(),{AbortError:AX,codes:rz}=l_(),{isNodeStream:EX,isWebStream:sz,kControllerErrorFunction:tz}=T0(),ez=q0(),{ERR_INVALID_ARG_TYPE:LX}=rz,F6,_F=(_,T)=>{if(typeof _!=="object"||!("aborted"in _))throw new LX(T,"AbortSignal",_)};TF.addAbortSignal=function(T,A){if(_F(T,"signal"),!EX(A)&&!sz(A))throw new LX("stream",["ReadableStream","WritableStream","Stream"],A);return TF.addAbortSignalNoValidate(T,A)};TF.addAbortSignalNoValidate=function(_,T){if(typeof _!=="object"||!("aborted"in _))return T;let A=EX(T)?()=>{T.destroy(new AX(void 0,{cause:_.reason}))}:()=>{T[tz](new AX(void 0,{cause:_.reason}))};if(_.aborted)A();else{F6=F6||s_().addAbortListener;let E=F6(_,A);ez(T,E[oz])}return T}});var HX=W((Of,XX)=>{var{StringPrototypeSlice:JX,SymbolIterator:LF,TypedArrayPrototypeSet:EA,Uint8Array:JF}=z_(),{Buffer:C6}=I("buffer"),{inspect:XF}=s_();XX.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 C6.alloc(0);let A=C6.allocUnsafe(T>>>0),E=this.head,L=0;while(E)EA(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}*[LF](){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+=JX(J,0,T),this.head=E,E.data=JX(J,T);break}++L}while((E=E.next)!==null);return this.length-=L,A}_getBuffer(T){let A=C6.allocUnsafe(T),E=T,L=this.head,J=0;do{let X=L.data;if(T>X.length)EA(A,X,E-T),T-=X.length;else{if(T===X.length)if(EA(A,X,E-T),++J,L.next)this.head=L.next;else this.head=this.tail=null;else EA(A,new JF(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 XF(this,{...A,depth:0,customInspect:!1})}}});var S4=W((Rf,$X)=>{var{MathFloor:HF,NumberIsInteger:ZF}=z_(),{validateInteger:YF}=pT(),{ERR_INVALID_ARG_VALUE:KF}=l_().codes,ZX=16384,YX=16;function $F(_,T,A){return _.highWaterMark!=null?_.highWaterMark:T?_[A]:null}function KX(_){return _?YX:ZX}function GF(_,T){if(YF(T,"value",0),_)YX=T;else ZX=T}function UF(_,T,A,E){let L=$F(T,E,A);if(L!=null){if(!ZF(L)||L<0){let J=E?`options.${A}`:"options.highWaterMark";throw new KF(J,L)}return HF(L)}return KX(_.objectMode)}$X.exports={getHighWaterMark:UF,getDefaultHighWaterMark:KX,setDefaultHighWaterMark:GF}});var WX=W((O6,UX)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var LA=I("buffer"),E0=LA.Buffer;function GX(_,T){for(var A in _)T[A]=_[A]}if(E0.from&&E0.alloc&&E0.allocUnsafe&&E0.allocUnsafeSlow)UX.exports=LA;else GX(LA,O6),O6.Buffer=UT;function UT(_,T,A){return E0(_,T,A)}UT.prototype=Object.create(E0.prototype);GX(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 LA.SlowBuffer(_)}});var QX=W((IF)=>{var D6=WX().Buffer,NX=D6.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 WF(_){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 NF(_){var T=WF(_);if(typeof T!=="string"&&(D6.isEncoding===NX||!NX(_)))throw Error("Unknown encoding: "+_);return T||_}IF.StringDecoder=y4;function y4(_){this.encoding=NF(_);var T;switch(this.encoding){case"utf16le":this.text=CF,this.end=OF,T=4;break;case"utf8":this.fillLast=VF,T=4;break;case"base64":this.text=RF,this.end=DF,T=3;break;default:this.write=BF,this.end=qF;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=D6.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=FF;y4.prototype.text=zF;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 R6(_){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 QF(_,T,A){var E=T.length-1;if(E<A)return 0;var L=R6(T[E]);if(L>=0){if(L>0)_.lastNeed=L-1;return L}if(--E<A||L===-2)return 0;if(L=R6(T[E]),L>=0){if(L>0)_.lastNeed=L-2;return L}if(--E<A||L===-2)return 0;if(L=R6(T[E]),L>=0){if(L>0)if(L===2)L=0;else _.lastNeed=L-3;return L}return 0}function MF(_,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 VF(_){var T=this.lastTotal-this.lastNeed,A=MF(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 zF(_,T){var A=QF(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 FF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+"\uFFFD";return T}function CF(_,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 OF(_){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 RF(_,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 DF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+this.lastChar.toString("base64",0,3-this.lastNeed);return T}function BF(_){return _.toString(this.encoding)}function qF(_){return _&&_.length?this.write(_):""}});var B6=W((Bf,FX)=>{var MX=c0(),{PromisePrototypeThen:jF,SymbolAsyncIterator:VX,SymbolIterator:zX}=z_(),{Buffer:xF}=I("buffer"),{ERR_INVALID_ARG_TYPE:wF,ERR_STREAM_NULL_VALUES:SF}=l_().codes;function yF(_,T,A){let E;if(typeof T==="string"||T instanceof xF)return new _({objectMode:!0,...A,read(){this.push(T),this.push(null)}});let L;if(T&&T[VX])L=!0,E=T[VX]();else if(T&&T[zX])L=!1,E=T[zX]();else throw new wF("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){jF(H(Y),()=>MX.nextTick(K,Y),($)=>MX.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 SF;else if(J.push($))continue;else X=!1}}catch(Y){J.destroy(Y)}break}}return J}FX.exports=yF});var h4=W((qf,bX)=>{var g1=c0(),{ArrayPrototypeIndexOf:vF,NumberIsInteger:hF,NumberIsNaN:kF,NumberParseInt:fF,ObjectDefineProperties:y6,ObjectKeys:bF,ObjectSetPrototypeOf:RX,Promise:DX,SafeSet:gF,SymbolAsyncDispose:mF,SymbolAsyncIterator:uF,Symbol:dF}=z_();bX.exports=s;s.ReadableState=ZA;var{EventEmitter:cF}=I("events"),{Stream:l0,prependListener:pF}=TA(),{Buffer:q6}=I("buffer"),{addAbortSignal:lF}=w4(),BX=q0(),A_=s_().debuglog("stream",(_)=>{A_=_}),nF=HX(),aT=GT(),{getHighWaterMark:iF,getDefaultHighWaterMark:aF}=S4(),{aggregateTwoErrors:CX,codes:{ERR_INVALID_ARG_TYPE:oF,ERR_METHOD_NOT_IMPLEMENTED:rF,ERR_OUT_OF_RANGE:sF,ERR_STREAM_PUSH_AFTER_EOF:tF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:eF},AbortError:_C}=l_(),{validateObject:TC}=pT(),WT=dF("kPaused"),{StringDecoder:qX}=QX(),AC=B6();RX(s.prototype,l0.prototype);RX(s,l0);var I6=()=>{},{errorOrDestroy:nT}=aT,iT=1,EC=2,IX=4,v4=8,PX=16,JA=32,XA=64,jX=128,LC=256,JC=512,XC=1024,w6=2048,S6=4096,HC=8192,ZC=16384,YC=32768,xX=65536,KC=131072,$C=262144;function w_(_){return{enumerable:!1,get(){return(this.state&_)!==0},set(T){if(T)this.state|=_;else this.state&=~_}}}y6(ZA.prototype,{objectMode:w_(iT),ended:w_(EC),endEmitted:w_(IX),reading:w_(v4),constructed:w_(PX),sync:w_(JA),needReadable:w_(XA),emittedReadable:w_(jX),readableListening:w_(LC),resumeScheduled:w_(JC),errorEmitted:w_(XC),emitClose:w_(w6),autoDestroy:w_(S6),destroyed:w_(HC),closed:w_(ZC),closeEmitted:w_(YC),multiAwaitDrain:w_(xX),readingMore:w_(KC),dataEmitted:w_($C)});function ZA(_,T,A){if(typeof A!=="boolean")A=T instanceof L0();if(this.state=w6|S6|PX|JA,_&&_.objectMode)this.state|=iT;if(A&&_&&_.readableObjectMode)this.state|=iT;if(this.highWaterMark=_?iF(this,_,"readableHighWaterMark",A):aF(!1),this.buffer=new nF,this.length=0,this.pipes=[],this.flowing=null,this[WT]=null,_&&_.emitClose===!1)this.state&=~w6;if(_&&_.autoDestroy===!1)this.state&=~S6;if(this.errored=null,this.defaultEncoding=_&&_.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,_&&_.encoding)this.decoder=new qX(_.encoding),this.encoding=_.encoding}function s(_){if(!(this instanceof s))return new s(_);let T=this instanceof L0();if(this._readableState=new ZA(_,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)lF(_.signal,this)}l0.call(this,_),aT.construct(this,()=>{if(this._readableState.needReadable)HA(this,this._readableState)})}s.prototype.destroy=aT.destroy;s.prototype._undestroy=aT.undestroy;s.prototype._destroy=function(_,T){T(_)};s.prototype[cF.captureRejectionSymbol]=function(_){this.destroy(_)};s.prototype[mF]=function(){let _;if(!this.destroyed)_=this.readableEnded?null:new _C,this.destroy(_);return new DX((T,A)=>BX(this,(E)=>E&&E!==_?A(E):T(null)))};s.prototype.push=function(_,T){return wX(this,_,T,!1)};s.prototype.unshift=function(_,T){return wX(this,_,T,!0)};function wX(_,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=q6.from(T,A).toString(L.encoding);else T=q6.from(T,A),A=""}else if(T instanceof q6)A="";else if(l0._isUint8Array(T))T=l0._uint8ArrayToBuffer(T),A="";else if(T!=null)J=new oF("chunk",["string","Buffer","Uint8Array"],T)}if(J)nT(_,J);else if(T===null)L.state&=~v4,WC(_,L);else if((L.state&iT)!==0||T&&T.length>0)if(E)if((L.state&IX)!==0)nT(_,new eF);else if(L.destroyed||L.errored)return!1;else P6(_,L,T,!0);else if(L.ended)nT(_,new tF);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)P6(_,L,T,!1);else HA(_,L);else P6(_,L,T,!1);else if(!E)L.state&=~v4,HA(_,L);return!L.ended&&(L.length<L.highWaterMark||L.length===0)}function P6(_,T,A,E){if(T.flowing&&T.length===0&&!T.sync&&_.listenerCount("data")>0){if((T.state&xX)!==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&XA)!==0)YA(_)}HA(_,T)}s.prototype.isPaused=function(){let _=this._readableState;return _[WT]===!0||_.flowing===!1};s.prototype.setEncoding=function(_){let T=new qX(_);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 GC=1073741824;function UC(_){if(_>GC)throw new sF("size","<= 1GiB",_);else _--,_|=_>>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++;return _}function OX(_,T){if(_<=0||T.length===0&&T.ended)return 0;if((T.state&iT)!==0)return 1;if(kF(_)){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(!hF(_))_=fF(_,10);let T=this._readableState,A=_;if(_>T.highWaterMark)T.highWaterMark=UC(_);if(_!==0)T.state&=~jX;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)j6(this);else YA(this);return null}if(_=OX(_,T),_===0&&T.ended){if(T.length===0)j6(this);return null}let E=(T.state&XA)!==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|JA,T.length===0)T.state|=XA;try{this._read(T.highWaterMark)}catch(J){nT(this,J)}if(T.state&=~JA,!T.reading)_=OX(A,T)}let L;if(_>0)L=kX(_,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)j6(this)}if(L!==null&&!T.errorEmitted&&!T.closeEmitted)T.dataEmitted=!0,this.emit("data",L);return L};function WC(_,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)YA(_);else T.needReadable=!1,T.emittedReadable=!0,SX(_)}function YA(_){let T=_._readableState;if(A_("emitReadable",T.needReadable,T.emittedReadable),T.needReadable=!1,!T.emittedReadable)A_("emitReadable",T.flowing),T.emittedReadable=!0,g1.nextTick(SX,_)}function SX(_){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,vX(_)}function HA(_,T){if(!T.readingMore&&T.constructed)T.readingMore=!0,g1.nextTick(NC,_,T)}function NC(_,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 rF("_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 gF(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=QC(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)}}pF(_,"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 QC(_,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=vF(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)YA(this);else if(!E.reading)g1.nextTick(MC,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(yX,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(yX,this);return T};function yX(_){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 MC(_){A_("readable nexttick read 0"),_.read(0)}s.prototype.resume=function(){let _=this._readableState;if(!_.flowing)A_("resume"),_.flowing=!_.readableListening,VC(this,_);return _[WT]=!1,this};function VC(_,T){if(!T.resumeScheduled)T.resumeScheduled=!0,g1.nextTick(zC,_,T)}function zC(_,T){if(A_("resume",T.reading),!T.reading)_.read(0);if(T.resumeScheduled=!1,_.emit("resume"),vX(_),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 vX(_){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=bF(_);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[uF]=function(){return hX(this)};s.prototype.iterator=function(_){if(_!==void 0)TC(_,"options");return hX(this,_)};function hX(_,T){if(typeof _.read!=="function")_=s.wrap(_,{objectMode:!0});let A=FC(_,T);return A.stream=_,A}async function*FC(_,T){let A=I6;function E(X){if(this===_)A(),A=I6;else A=X}_.on("readable",E);let L,J=BX(_,{writable:!1},(X)=>{L=X?CX(L,X):null,A(),A=I6});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 DX(E)}}catch(X){throw L=CX(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()}}y6(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}}});y6(ZA.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[WT]!==!1},set(_){this[WT]=!!_}}});s._fromList=kX;function kX(_,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 j6(_){let T=_._readableState;if(A_("endReadable",T.endEmitted),!T.endEmitted)T.ended=!0,g1.nextTick(CC,T,_)}function CC(_,T){if(A_("endReadableNT",_.endEmitted,_.length),!_.errored&&!_.closeEmitted&&!_.endEmitted&&_.length===0){if(_.endEmitted=!0,T.emit("end"),T.writable&&T.allowHalfOpen===!1)g1.nextTick(OC,T);else if(_.autoDestroy){let A=T._writableState;if(!A||A.autoDestroy&&(A.finished||A.writable===!1))T.destroy()}}}function OC(_){if(_.writable&&!_.writableEnded&&!_.destroyed)_.end()}s.from=function(_,T){return AC(s,_,T)};var x6;function fX(){if(x6===void 0)x6={};return x6}s.fromWeb=function(_,T){return fX().newStreamReadableFromReadableStream(_,T)};s.toWeb=function(_,T){return fX().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 WA=W((If,rX)=>{var NT=c0(),{ArrayPrototypeSlice:uX,Error:RC,FunctionPrototypeSymbolHasInstance:dX,ObjectDefineProperty:cX,ObjectDefineProperties:DC,ObjectSetPrototypeOf:pX,StringPrototypeToLowerCase:BC,Symbol:qC,SymbolHasInstance:IC}=z_();rX.exports=O_;O_.WritableState=b4;var{EventEmitter:PC}=I("events"),k4=TA().Stream,{Buffer:KA}=I("buffer"),UA=GT(),{addAbortSignal:jC}=w4(),{getHighWaterMark:xC,getDefaultHighWaterMark:wC}=S4(),{ERR_INVALID_ARG_TYPE:SC,ERR_METHOD_NOT_IMPLEMENTED:yC,ERR_MULTIPLE_CALLBACK:lX,ERR_STREAM_CANNOT_PIPE:vC,ERR_STREAM_DESTROYED:f4,ERR_STREAM_ALREADY_FINISHED:hC,ERR_STREAM_NULL_VALUES:kC,ERR_STREAM_WRITE_AFTER_END:fC,ERR_UNKNOWN_ENCODING:nX}=l_().codes,{errorOrDestroy:oT}=UA;pX(O_.prototype,k4.prototype);pX(O_,k4);function k6(){}var rT=qC("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=_?xC(this,_,"writableHighWaterMark",A):wC(!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=gC.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 uX(this.buffered,this.bufferedIndex)};cX(b4.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function O_(_){let T=this instanceof L0();if(!T&&!dX(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)jC(_.signal,this)}k4.call(this,_),UA.construct(this,()=>{let A=this._writableState;if(!A.writing)b6(this,A);g6(this,A)})}cX(O_,IC,{__proto__:null,value:function(_){if(dX(this,_))return!0;if(this!==O_)return!1;return _&&_._writableState instanceof b4}});O_.prototype.pipe=function(){oT(this,new vC)};function iX(_,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"&&!KA.isEncoding(A))throw new nX(A);if(typeof E!=="function")E=k6}if(T===null)throw new kC;else if(!L.objectMode)if(typeof T==="string"){if(L.decodeStrings!==!1)T=KA.from(T,A),A="buffer"}else if(T instanceof KA)A="buffer";else if(k4._isUint8Array(T))T=k4._uint8ArrayToBuffer(T),A="buffer";else throw new SC("chunk",["string","Buffer","Uint8Array"],T);let J;if(L.ending)J=new fC;else if(L.destroyed)J=new f4("write");if(J)return NT.nextTick(E,J),oT(_,J,!0),J;return L.pendingcb++,bC(_,L,T,A,E)}O_.prototype.write=function(_,T,A){return iX(this,_,T,A)===!0};O_.prototype.cork=function(){this._writableState.corked++};O_.prototype.uncork=function(){let _=this._writableState;if(_.corked){if(_.corked--,!_.writing)b6(this,_)}};O_.prototype.setDefaultEncoding=function(T){if(typeof T==="string")T=BC(T);if(!KA.isEncoding(T))throw new nX(T);return this._writableState.defaultEncoding=T,this};function bC(_,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!==k6)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 gX(_,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 mX(_,T,A,E){--T.pendingcb,E(A),f6(T),oT(_,A)}function gC(_,T){let A=_._writableState,E=A.sync,L=A.writecb;if(typeof L!=="function"){oT(_,new lX);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(mX,_,A,T,L);else mX(_,A,T,L)}else{if(A.buffered.length>A.bufferedIndex)b6(_,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(mC,A.afterWriteTickInfo);else aX(_,A,1,L)}}function mC({stream:_,state:T,count:A,cb:E}){return T.afterWriteTickInfo=null,aX(_,T,A,E)}function aX(_,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)f6(T);g6(_,T)}function f6(_){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 b6(_,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?k6:(Y)=>{for(let K=X;K<A.length;++K)A[K].callback(Y)},Z=T.allNoop&&X===0?A:uX(A,X);Z.allBuffers=T.allBuffers,gX(_,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;gX(_,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 yC("_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=iX(this,_,T);if(J instanceof RC)L=J}if(E.corked)E.corked=1,this.uncork();if(L);else if(!E.errored&&!E.ending)E.ending=!0,g6(this,E,!0),E.ended=!0;else if(E.finished)L=new hC("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 $A(_){return _.ending&&!_.destroyed&&_.constructed&&_.length===0&&!_.errored&&_.buffered.length===0&&!_.finished&&!_.writing&&!_.errorEmitted&&!_.closeEmitted}function uC(_,T){let A=!1;function E(L){if(A){oT(_,L!==null&&L!==void 0?L:lX());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($A(T))T.prefinished=!0,_.emit("prefinish"),T.pendingcb++,NT.nextTick(h6,_,T)}T.sync=!0,T.pendingcb++;try{_._final(E)}catch(L){E(L)}T.sync=!1}function dC(_,T){if(!T.prefinished&&!T.finalCalled)if(typeof _._final==="function"&&!T.destroyed)T.finalCalled=!0,uC(_,T);else T.prefinished=!0,_.emit("prefinish")}function g6(_,T,A){if($A(T)){if(dC(_,T),T.pendingcb===0){if(A)T.pendingcb++,NT.nextTick((E,L)=>{if($A(L))h6(E,L);else L.pendingcb--},_,T);else if($A(T))T.pendingcb++,h6(_,T)}}}function h6(_,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()}}DC(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 cC=UA.destroy;O_.prototype.destroy=function(_,T){let A=this._writableState;if(!A.destroyed&&(A.bufferedIndex<A.buffered.length||A[rT].length))NT.nextTick(f6,A);return cC.call(this,_,T),this};O_.prototype._undestroy=UA.undestroy;O_.prototype._destroy=function(_,T){T(_)};O_.prototype[PC.captureRejectionSymbol]=function(_){this.destroy(_)};var v6;function oX(){if(v6===void 0)v6={};return v6}O_.fromWeb=function(_,T){return oX().newStreamWritableFromWritableStream(_,T)};O_.toWeb=function(_){return oX().newWritableStreamFromStreamWritable(_)}});var $H=W((Pf,KH)=>{var m6=c0(),pC=I("buffer"),{isReadable:lC,isWritable:nC,isIterable:sX,isNodeStream:iC,isReadableNodeStream:tX,isWritableNodeStream:eX,isDuplexNodeStream:aC,isReadableStream:_H,isWritableStream:TH}=T0(),AH=q0(),{AbortError:ZH,codes:{ERR_INVALID_ARG_TYPE:oC,ERR_INVALID_RETURN_VALUE:EH}}=l_(),{destroyer:tT}=GT(),rC=L0(),YH=h4(),sC=WA(),{createDeferredPromise:LH}=s_(),JH=B6(),XH=globalThis.Blob||pC.Blob,tC=typeof XH<"u"?function(T){return T instanceof XH}:function(T){return!1},eC=globalThis.AbortController||I("abort-controller").AbortController,{FunctionPrototypeCall:HH}=z_();class QT extends rC{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}}KH.exports=function _(T,A){if(aC(T))return T;if(tX(T))return sT({readable:T});if(eX(T))return sT({writable:T});if(iC(T))return sT({writable:!1,readable:!1});if(_H(T))return sT({readable:YH.fromWeb(T)});if(TH(T))return sT({writable:sC.fromWeb(T)});if(typeof T==="function"){let{value:L,write:J,final:X,destroy:H}=_O(T);if(sX(L))return JH(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=HH(Z,L,($)=>{if($!=null)throw new EH("nully","body",$)},($)=>{tT(Y,$)});return Y=new QT({objectMode:!0,readable:!1,write:J,final($){X(async()=>{try{await K,m6.nextTick($,null)}catch(G){m6.nextTick($,G)}})},destroy:H})}throw new EH("Iterable, AsyncIterable or AsyncFunction",A,L)}if(tC(T))return _(T.arrayBuffer());if(sX(T))return JH(QT,T,{objectMode:!0,writable:!1});if(_H(T===null||T===void 0?void 0:T.readable)&&TH(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?tX(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?eX(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 HH(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 oC(A,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],T)};function _O(_){let{promise:T,resolve:A}=LH(),E=new eC,L=E.signal;return{value:_(async function*(){while(!0){let X=T;T=null;let{chunk:H,done:Z,cb:Y}=await X;if(m6.nextTick(Y),Z)return;if(L.aborted)throw new ZH(void 0,{cause:L.reason});({promise:T,resolve:A}=LH()),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"?YH.wrap(_.readable):_.readable,A=_.writable,E=!!lC(T),L=!!nC(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)AH(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)AH(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 ZH;if(H=null,J=null,X=null,Z===null)G($);else Z=G,tT(A,$),tT(T,$)},Y}});var L0=W((jf,WH)=>{var{ObjectDefineProperties:TO,ObjectGetOwnPropertyDescriptor:I0,ObjectKeys:AO,ObjectSetPrototypeOf:GH}=z_();WH.exports=m1;var c6=h4(),O1=WA();GH(m1.prototype,c6.prototype);GH(m1,c6);{let _=AO(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(c6.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}TO(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 u6;function UH(){if(u6===void 0)u6={};return u6}m1.fromWeb=function(_,T){return UH().newStreamDuplexFromReadableWritablePair(_,T)};m1.toWeb=function(_){return UH().newReadableWritablePairFromDuplex(_)};var d6;m1.from=function(_){if(!d6)d6=$H();return d6(_,"body")}});var n6=W((xf,QH)=>{var{ObjectSetPrototypeOf:NH,Symbol:EO}=z_();QH.exports=P0;var{ERR_METHOD_NOT_IMPLEMENTED:LO}=l_().codes,l6=L0(),{getHighWaterMark:JO}=S4();NH(P0.prototype,l6.prototype);NH(P0,l6);var g4=EO("kCallback");function P0(_){if(!(this instanceof P0))return new P0(_);let T=_?JO(this,_,"readableHighWaterMark",!0):null;if(T===0)_={..._,highWaterMark:null,readableHighWaterMark:T,writableHighWaterMark:_.writableHighWaterMark||0};if(l6.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",XO)}function p6(_){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 XO(){if(this._final!==p6)p6.call(this)}P0.prototype._final=p6;P0.prototype._transform=function(_,T,A){throw new LO("_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 a6=W((wf,VH)=>{var{ObjectSetPrototypeOf:MH}=z_();VH.exports=eT;var i6=n6();MH(eT.prototype,i6.prototype);MH(eT,i6);function eT(_){if(!(this instanceof eT))return new eT(_);i6.call(this,_)}eT.prototype._transform=function(_,T,A){A(null,_)}});var VA=W((Sf,RH)=>{var m4=c0(),{ArrayIsArray:HO,Promise:ZO,SymbolAsyncIterator:YO,SymbolDispose:KO}=z_(),MA=q0(),{once:$O}=s_(),GO=GT(),zH=L0(),{aggregateTwoErrors:UO,codes:{ERR_INVALID_ARG_TYPE:EE,ERR_INVALID_RETURN_VALUE:o6,ERR_MISSING_ARGS:WO,ERR_STREAM_DESTROYED:NO,ERR_STREAM_PREMATURE_CLOSE:QO},AbortError:MO}=l_(),{validateFunction:VO,validateAbortSignal:zO}=pT(),{isIterable:MT,isReadable:r6,isReadableNodeStream:QA,isNodeStream:FH,isTransformStream:_4,isWebStream:FO,isReadableStream:s6,isReadableFinished:CO}=T0(),OO=globalThis.AbortController||I("abort-controller").AbortController,t6,e6,_E;function CH(_,T,A){let E=!1;_.on("close",()=>{E=!0});let L=MA(_,{readable:T,writable:A},(J)=>{E=!J});return{destroy:(J)=>{if(E)return;E=!0,GO.destroyer(_,J||new NO("pipe"))},cleanup:L}}function RO(_){return VO(_[_.length-1],"streams[stream.length - 1]"),_.pop()}function TE(_){if(MT(_))return _;else if(QA(_))return DO(_);throw new EE("val",["Readable","Iterable","AsyncIterable"],_)}async function*DO(_){if(!e6)e6=h4();yield*e6.prototype[YO].call(_)}async function NA(_,T,A,{end:E}){let L,J=null,X=(Y)=>{if(Y)L=Y;if(J){let K=J;J=null,K()}},H=()=>new ZO((Y,K)=>{if(L)K(L);else J=()=>{if(L)K(L);else Y()}});T.on("drain",X);let Z=MA(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?UO(L,Y):Y)}finally{Z(),T.off("drain",X)}}async function AE(_,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 BO(..._){return OH(_,$O(RO(_)))}function OH(_,T,A){if(_.length===1&&HO(_[0]))_=_[0];if(_.length<2)throw new WO("streams");let E=new OO,L=E.signal,J=A===null||A===void 0?void 0:A.signal,X=[];zO(J,"options.signal");function H(){V(new MO)}_E=_E||s_().addAbortListener;let Z;if(J)Z=_E(J,H);let Y,K,$=[],G=0;function U(R){V(R,--G===0)}function V(R,q){var b;if(R&&(!Y||Y.code==="ERR_STREAM_PREMATURE_CLOSE"))Y=R;if(!Y&&!q)return;while($.length)$.shift()(Y);if((b=Z)===null||b===void 0||b[KO](),E.abort(),q){if(!Y)X.forEach((k)=>k());m4.nextTick(T,Y,K)}}let N;for(let R=0;R<_.length;R++){let q=_[R],b=R<_.length-1,k=R>0,g=b||(A===null||A===void 0?void 0:A.end)!==!1,l=R===_.length-1;if(FH(q)){let c=function(W_){if(W_&&W_.name!=="AbortError"&&W_.code!=="ERR_STREAM_PREMATURE_CLOSE")U(W_)};var F=c;if(g){let{destroy:W_,cleanup:c_}=CH(q,b,k);if($.push(W_),r6(q)&&l)X.push(c_)}if(q.on("error",c),r6(q)&&l)X.push(()=>{q.removeListener("error",c)})}if(R===0)if(typeof q==="function"){if(N=q({signal:L}),!MT(N))throw new o6("Iterable, AsyncIterable or Stream","source",N)}else if(MT(q)||QA(q)||_4(q))N=q;else N=zH.from(q);else if(typeof q==="function"){if(_4(N)){var z;N=TE((z=N)===null||z===void 0?void 0:z.readable)}else N=TE(N);if(N=q(N,{signal:L}),b){if(!MT(N,!0))throw new o6("AsyncIterable",`transform[${R-1}]`,N)}else{var Q;if(!t6)t6=a6();let c=new t6({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(g)c.end();m4.nextTick(U)},(C_)=>{c.destroy(C_),m4.nextTick(U,C_)});else if(MT(N,!0))G++,NA(N,c,U,{end:g});else if(s6(N)||_4(N)){let C_=N.readable||N;G++,NA(C_,c,U,{end:g})}else throw new o6("AsyncIterable or Promise","destination",N);N=c;let{destroy:c_,cleanup:q_}=CH(N,!1,!0);if($.push(c_),l)X.push(q_)}}else if(FH(q)){if(QA(N)){G+=2;let c=qO(N,q,U,{end:g});if(r6(q)&&l)X.push(c)}else if(_4(N)||s6(N)){let c=N.readable||N;G++,NA(c,q,U,{end:g})}else if(MT(N))G++,NA(N,q,U,{end:g});else throw new EE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else if(FO(q)){if(QA(N))G++,AE(TE(N),q,U,{end:g});else if(s6(N)||MT(N))G++,AE(N,q,U,{end:g});else if(_4(N))G++,AE(N.readable,q,U,{end:g});else throw new EE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else N=zH.from(q)}if(L!==null&&L!==void 0&&L.aborted||J!==null&&J!==void 0&&J.aborted)m4.nextTick(H);return N}function qO(_,T,A,{end:E}){let L=!1;if(T.on("close",()=>{if(!L)A(new QO)}),_.pipe(T,{end:!1}),E){let X=function(){L=!0,T.end()};var J=X;if(CO(_))m4.nextTick(X);else _.once("end",X)}else A();return MA(_,{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)}),MA(T,{readable:!1,writable:!0},A)}RH.exports={pipelineImpl:OH,pipeline:BO}});var JE=W((yf,jH)=>{var{pipeline:IO}=VA(),zA=L0(),{destroyer:PO}=GT(),{isNodeStream:FA,isReadable:DH,isWritable:BH,isWebStream:LE,isTransformStream:VT,isWritableStream:qH,isReadableStream:IH}=T0(),{AbortError:jO,codes:{ERR_INVALID_ARG_VALUE:PH,ERR_MISSING_ARGS:xO}}=l_(),wO=q0();jH.exports=function(...T){if(T.length===0)throw new xO("streams");if(T.length===1)return zA.from(T[0]);let A=[...T];if(typeof T[0]==="function")T[0]=zA.from(T[0]);if(typeof T[T.length-1]==="function"){let U=T.length-1;T[U]=zA.from(T[U])}for(let U=0;U<T.length;++U){if(!FA(T[U])&&!LE(T[U]))continue;if(U<T.length-1&&!(DH(T[U])||IH(T[U])||VT(T[U])))throw new PH(`streams[${U}]`,A[U],"must be readable");if(U>0&&!(BH(T[U])||qH(T[U])||VT(T[U])))throw new PH(`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=IO(T,Z),$=!!(BH(Y)||qH(Y)||VT(Y)),G=!!(DH(K)||IH(K)||VT(K));if(H=new zA({writableObjectMode:!!(Y!==null&&Y!==void 0&&Y.writableObjectMode),readableObjectMode:!!(K!==null&&K!==void 0&&K.readableObjectMode),writable:$,readable:G}),$){if(FA(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(LE(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;wO(U,()=>{if(L){let V=L;L=null,V()}})}if(G){if(FA(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(LE(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 jO;if(J=null,E=null,L=null,X===null)V(U);else if(X=V,FA(K))PO(K,U)},H}});var mH=W((JR,HE)=>{var SO=globalThis.AbortController||I("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:yO,ERR_INVALID_ARG_TYPE:u4,ERR_MISSING_ARGS:vO,ERR_OUT_OF_RANGE:hO},AbortError:J0}=l_(),{validateAbortSignal:zT,validateInteger:xH,validateObject:FT}=pT(),kO=z_().Symbol("kWeak"),fO=z_().Symbol("kResistStopPropagation"),{finished:bO}=q0(),gO=JE(),{addAbortSignalNoValidate:mO}=w4(),{isWritable:uO,isNodeStream:dO}=T0(),{deprecate:cO}=s_(),{ArrayPrototypePush:pO,Boolean:lO,MathFloor:wH,Number:nO,NumberIsNaN:iO,Promise:SH,PromiseReject:yH,PromiseResolve:aO,PromisePrototypeThen:vH,Symbol:kH}=z_(),CA=kH("kEmpty"),hH=kH("kEof");function oO(_,T){if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");if(dO(_)&&!uO(_))throw new yO("stream",_,"must be writable");let A=gO(this,_);if(T!==null&&T!==void 0&&T.signal)mO(T.signal,A);return A}function OA(_,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=wH(T.concurrency);let E=A-1;if((T===null||T===void 0?void 0:T.highWaterMark)!=null)E=wH(T.highWaterMark);return xH(A,"options.concurrency",1),xH(E,"options.highWaterMark",0),E+=A,async function*(){let J=s_().AbortSignalAny([T===null||T===void 0?void 0:T.signal].filter(lO)),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===CA)continue;Q=aO(Q)}catch(F){Q=yH(F)}if(G+=1,vH(Q,V,U),H.push(Q),Y)Y(),Y=null;if(!$&&(H.length>=E||G>=A))await new SH((F)=>{K=F})}H.push(hH)}catch(Q){let F=yH(Q);vH(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===hH)return;if(J.aborted)throw new J0;if(Q!==CA)yield Q;H.shift(),N()}await new SH((Q)=>{Y=Q})}}finally{if($=!0,K)K(),K=null}}.call(this)}function rO(_=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 fH(_,T=void 0){for await(let A of XE.call(this,_,T))return!0;return!1}async function sO(_,T=void 0){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);return!await fH.call(this,async(...A)=>{return!await _(...A)},T)}async function tO(_,T){for await(let A of XE.call(this,_,T))return A;return}async function eO(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){return await _(E,L),CA}for await(let E of OA.call(this,A,T));}function XE(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){if(await _(E,L))return E;return CA}return OA.call(this,A,T)}class bH extends vO{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function _R(_,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 bO(this.destroy(Y)),Y}let J=new SO,X=J.signal;if(A!==null&&A!==void 0&&A.signal){let Y={once:!0,[kO]:this,[fO]:!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 bH}finally{J.abort()}return T}async function TR(_){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});pO(T,E)}return T}function AR(_,T){let A=OA.call(this,_,T);return async function*(){for await(let L of A)yield*L}.call(this)}function gH(_){if(_=nO(_),iO(_))return 0;if(_<0)throw new hO("number",">= 0",_);return _}function ER(_,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 _=gH(_),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 LR(_,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 _=gH(_),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)}JR.streamReturningOperators={asIndexedPairs:cO(rO,"readable.asIndexedPairs will be removed in a future version."),drop:ER,filter:XE,flatMap:AR,map:OA,take:LR,compose:oO};JR.promiseReturningOperators={every:sO,forEach:eO,reduce:_R,toArray:TR,some:fH,find:tO}});var ZE=W((vf,uH)=>{var{ArrayPrototypePop:ZR,Promise:YR}=z_(),{isIterable:KR,isNodeStream:$R,isWebStream:GR}=T0(),{pipelineImpl:UR}=VA(),{finished:WR}=q0();YE();function NR(..._){return new YR((T,A)=>{let E,L,J=_[_.length-1];if(J&&typeof J==="object"&&!$R(J)&&!KR(J)&&!GR(J)){let X=ZR(_);E=X.signal,L=X.end}UR(_,(X,H)=>{if(X)A(X);else T(H)},{signal:E,end:L})})}uH.exports={finished:WR,pipeline:NR}});var YE=W((hf,rH)=>{var{Buffer:QR}=I("buffer"),{ObjectDefineProperty:j0,ObjectKeys:pH,ReflectApply:lH}=z_(),{promisify:{custom:nH}}=s_(),{streamReturningOperators:dH,promiseReturningOperators:cH}=mH(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:iH}}=l_(),MR=JE(),{setDefaultHighWaterMark:VR,getDefaultHighWaterMark:zR}=S4(),{pipeline:aH}=VA(),{destroyer:FR}=GT(),oH=q0(),KE=ZE(),d4=T0(),V_=rH.exports=TA().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 pH(dH)){let A=function(...E){if(new.target)throw iH();return V_.Readable.from(lH(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})}for(let _ of pH(cH)){let A=function(...E){if(new.target)throw iH();return lH(T,this,E)},T=cH[_];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=WA();V_.Duplex=L0();V_.Transform=n6();V_.PassThrough=a6();V_.pipeline=aH;var{addAbortSignal:CR}=w4();V_.addAbortSignal=CR;V_.finished=oH;V_.destroy=FR;V_.compose=MR;V_.setDefaultHighWaterMark=VR;V_.getDefaultHighWaterMark=zR;j0(V_,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return KE}});j0(aH,nH,{__proto__:null,enumerable:!0,get(){return KE.pipeline}});j0(oH,nH,{__proto__:null,enumerable:!0,get(){return KE.finished}});V_.Stream=V_;V_._isUint8Array=function(T){return T instanceof Uint8Array};V_._uint8ArrayToBuffer=function(T){return QR.from(T.buffer,T.byteOffset,T.byteLength)}});var n0=W((kf,__)=>{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 _=YE(),T=ZE(),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 sH=W((_b,$E)=>{if(typeof Object.create==="function")$E.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 $E.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 tH=W((Tb,GE)=>{try{if(RA=I("util"),typeof RA.inherits!=="function")throw"";GE.exports=RA.inherits}catch(_){GE.exports=sH()}var RA});var TZ=W((Ab,_Z)=>{var{Buffer:u1}=I("buffer"),eH=Symbol.for("BufferList");function H_(_){if(!(this instanceof H_))return new H_(_);H_._init.call(this,_)}H_._init=function(T){if(Object.defineProperty(this,eH,{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[eH]};_Z.exports=H_});var AZ=W((Eb,DA)=>{var UE=n0().Duplex,OR=tH(),c4=TZ();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,_),UE.call(this)}OR(i_,UE);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(UE.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;DA.exports=i_;DA.exports.BufferListStream=i_;DA.exports.BufferList=c4});var JZ=W((Lb,LZ)=>{class EZ{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}LZ.exports=EZ});var WE=W((Jb,XZ)=>{var x=Jb,{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 ZZ=W((Xb,HZ)=>{var T4=1000,A4=T4*60,E4=A4*60,CT=E4*24,RR=CT*7,DR=CT*365.25;HZ.exports=function(_,T){T=T||{};var A=typeof _;if(A==="string"&&_.length>0)return BR(_);else if(A==="number"&&isFinite(_))return T.long?IR(_):qR(_);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(_))};function BR(_){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*DR;case"weeks":case"week":case"w":return A*RR;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 qR(_){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 IR(_){var T=Math.abs(_);if(T>=CT)return BA(_,T,CT,"day");if(T>=E4)return BA(_,T,E4,"hour");if(T>=A4)return BA(_,T,A4,"minute");if(T>=T4)return BA(_,T,T4,"second");return _+" ms"}function BA(_,T,A,E){var L=T>=A*1.5;return Math.round(_/A)+" "+E+(L?"s":"")}});var NE=W((Hb,YZ)=>{function PR(_){A.debug=A,A.default=A,A.coerce=Z,A.disable=X,A.enable=L,A.enabled=H,A.humanize=ZZ(),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,(k,g)=>{if(k==="%%")return"%";q++;let l=A.formatters[g];if(typeof l==="function"){let c=z[q];k=l.call(Q,c),z.splice(q,1),q--}return k}),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}YZ.exports=PR});var $Z=W((KZ,qA)=>{KZ.formatArgs=xR;KZ.save=wR;KZ.load=SR;KZ.useColors=jR;KZ.storage=yR();KZ.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`.")}})();KZ.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 jR(){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 xR(_){if(_[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+_[0]+(this.useColors?"%c ":" ")+"+"+qA.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)}KZ.log=console.debug||console.log||(()=>{});function wR(_){try{if(_)KZ.storage.setItem("debug",_);else KZ.storage.removeItem("debug")}catch(T){}}function SR(){let _;try{_=KZ.storage.getItem("debug")||KZ.storage.getItem("DEBUG")}catch(T){}if(!_&&typeof process<"u"&&"env"in process)_=process.env.DEBUG;return _}function yR(){try{return localStorage}catch(_){}}qA.exports=NE()(KZ);var{formatters:vR}=qA.exports;vR.j=function(_){try{return JSON.stringify(_)}catch(T){return"[UnexpectedJSONParseError]: "+T.message}}});var NZ=W((UZ,PA)=>{var dR=I("tty"),IA=I("util");UZ.init=oR;UZ.log=nR;UZ.formatArgs=pR;UZ.save=iR;UZ.load=aR;UZ.useColors=cR;UZ.destroy=IA.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");UZ.colors=[6,2,3,4,5,1];try{let _=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(_&&(_.stderr||_).level>=2)UZ.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(_){}UZ.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 cR(){return"colors"in UZ.inspectOpts?Boolean(UZ.inspectOpts.colors):dR.isatty(process.stderr.fd)}function pR(_){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 DN=Object.create;var{getPrototypeOf:BN,defineProperty:Q9,getOwnPropertyNames:qN}=Object;var IN=Object.prototype.hasOwnProperty;var B_=(_,T,A)=>{A=_!=null?DN(BN(_)):{};let E=T||!_||!_.__esModule?Q9(A,"default",{value:_,enumerable:!0}):A;for(let L of qN(_))if(!IN.call(E,L))Q9(E,L,{get:()=>_[L],enumerable:!0});return E};var W=(_,T)=>()=>(T||_((T={exports:{}}).exports,T),T.exports);var I=import.meta.require;var I9=W((Ck,q9)=>{q9.exports=mN;var gN=Object.prototype.hasOwnProperty;function mN(){var _={};for(var T=0;T<arguments.length;T++){var A=arguments[T];for(var E in A)if(gN.call(A,E))_[E]=A[E]}return _}});var f8=W((Ok,P9)=>{function uN(_){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}}P9.exports=uN});var u5=W((Rk,x9)=>{var dN=I9(),j9=f8(),cN={released:D0,results:!0};function pN(_){_=dN(cN,_);var T=_.released,A=j9(_.results?iN:lN),E=j9(nN),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 lN(){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 nN(){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 iN(){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(){}x9.exports=pN});var y9=W((Dk,S9)=>{var aN={results:!0};function oN(_){_=Object.assign({},aN,_);var T,A;if(_.results)T=tN,A=eN;else T=rN,A=sN;return E;function E(L,J,X,H){if(H=(H||_Q).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 rN(_,T,A){var E=0,L=T.length;J();function J(){if(E<L)b8(_,T[E++],J);else A()}}function sN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=w9;else J=b8;X();function X(){if(E<L)J(_[E++],T,X);else A()}}function tN(_,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)b8(_,T[E++],X);else A(null,J)}}function eN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=w9;else J=b8;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 w9(_,T,A){_(A)}function b8(_,T,A){_(T,A)}function _Q(){}S9.exports=oN});var k9=W((v9)=>{Object.defineProperty(v9,"__esModule",{value:!0});v9.default=void 0;var Bk=v9.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var g9=W((f9)=>{Object.defineProperty(f9,"__esModule",{value:!0});f9.default=void 0;var Ik=f9.default="00000000-0000-0000-0000-000000000000"});var d9=W((m9)=>{Object.defineProperty(m9,"__esModule",{value:!0});m9.default=void 0;var jk=m9.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((c9)=>{Object.defineProperty(c9,"__esModule",{value:!0});c9.default=void 0;var TQ=AQ(d9());function AQ(_){return _&&_.__esModule?_:{default:_}}function EQ(_){return typeof _==="string"&&TQ.default.test(_)}var wk=c9.default=EQ});var j4=W((l9)=>{Object.defineProperty(l9,"__esModule",{value:!0});l9.default=void 0;var LQ=JQ(P4());function JQ(_){return _&&_.__esModule?_:{default:_}}function XQ(_){if(!(0,LQ.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 yk=l9.default=XQ});var B0=W((a9)=>{Object.defineProperty(a9,"__esModule",{value:!0});a9.default=void 0;a9.unsafeStringify=i9;var HQ=ZQ(P4());function ZQ(_){return _&&_.__esModule?_:{default:_}}var b_=[];for(let _=0;_<256;++_)b_.push((_+256).toString(16).slice(1));function i9(_,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 YQ(_,T=0){let A=i9(_,T);if(!(0,HQ.default)(A))throw TypeError("Stringified UUID is invalid");return A}var hk=a9.default=YQ});var u8=W((r9)=>{Object.defineProperty(r9,"__esModule",{value:!0});r9.default=UQ;var $Q=GQ(I("crypto"));function GQ(_){return _&&_.__esModule?_:{default:_}}var m8=new Uint8Array(256),g8=m8.length;function UQ(){if(g8>m8.length-16)$Q.default.randomFillSync(m8),g8=0;return m8.slice(g8,g8+=16)}});var l5=W((s9)=>{Object.defineProperty(s9,"__esModule",{value:!0});s9.default=void 0;var NQ=MQ(u8()),QQ=B0();function MQ(_){return _&&_.__esModule?_:{default:_}}var d5,d8,c5=0,p5=0;function VQ(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let{node:J,clockseq:X}=_;if(!_._v6){if(!J)J=d5;if(X==null)X=d8}if(J==null||X==null){let G=_.random||(_.rng||NQ.default)();if(J==null){if(J=[G[0],G[1],G[2],G[3],G[4],G[5]],!d5&&!_._v6)J[0]|=1,d5=J}if(X==null){if(X=(G[6]<<8|G[7])&16383,d8===void 0&&!_._v6)d8=X}}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:p5+1,Y=H-c5+(Z-p5)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>c5)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");c5=H,p5=Z,d8=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,QQ.unsafeStringify)(L)}var bk=s9.default=VQ});var n5=W((e9)=>{Object.defineProperty(e9,"__esModule",{value:!0});e9.default=OQ;var zQ=CQ(j4()),FQ=B0();function CQ(_){return _&&_.__esModule?_:{default:_}}function OQ(_){let T=typeof _==="string"?(0,zQ.default)(_):_,A=RQ(T);return typeof _==="string"?(0,FQ.unsafeStringify)(A):A}function RQ(_,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 i5=W((_7)=>{Object.defineProperty(_7,"__esModule",{value:!0});_7.URL=_7.DNS=void 0;_7.default=wQ;var BQ=B0(),qQ=IQ(j4());function IQ(_){return _&&_.__esModule?_:{default:_}}function PQ(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var jQ=_7.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xQ=_7.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function wQ(_,T,A){function E(L,J,X,H){var Z;if(typeof L==="string")L=PQ(L);if(typeof J==="string")J=(0,qQ.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,BQ.unsafeStringify)(Y)}try{E.name=_}catch(L){}return E.DNS=jQ,E.URL=xQ,E}});var L7=W((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});A7.default=void 0;var vQ=hQ(I("crypto"));function hQ(_){return _&&_.__esModule?_:{default:_}}function kQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return vQ.default.createHash("md5").update(_).digest()}var dk=A7.default=kQ});var Z7=W((X7)=>{Object.defineProperty(X7,"__esModule",{value:!0});X7.default=void 0;var fQ=J7(i5()),bQ=J7(L7());function J7(_){return _&&_.__esModule?_:{default:_}}var gQ=(0,fQ.default)("v3",48,bQ.default),pk=X7.default=gQ});var $7=W((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});Y7.default=void 0;var mQ=uQ(I("crypto"));function uQ(_){return _&&_.__esModule?_:{default:_}}var nk=Y7.default={randomUUID:mQ.default.randomUUID}});var Q7=W((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});W7.default=void 0;var G7=U7($7()),dQ=U7(u8()),cQ=B0();function U7(_){return _&&_.__esModule?_:{default:_}}function pQ(_,T,A){if(G7.default.randomUUID&&!T&&!_)return G7.default.randomUUID();_=_||{};let E=_.random||(_.rng||dQ.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,cQ.unsafeStringify)(E)}var ak=W7.default=pQ});var z7=W((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});M7.default=void 0;var lQ=nQ(I("crypto"));function nQ(_){return _&&_.__esModule?_:{default:_}}function iQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return lQ.default.createHash("sha1").update(_).digest()}var rk=M7.default=iQ});var R7=W((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});C7.default=void 0;var aQ=F7(i5()),oQ=F7(z7());function F7(_){return _&&_.__esModule?_:{default:_}}var rQ=(0,aQ.default)("v5",80,oQ.default),tk=C7.default=rQ});var q7=W((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});B7.default=_M;var sQ=B0(),tQ=D7(l5()),eQ=D7(n5());function D7(_){return _&&_.__esModule?_:{default:_}}function _M(_={},T,A=0){let E=(0,tQ.default)({..._,_v6:!0},new Uint8Array(16));if(E=(0,eQ.default)(E),T){for(let L=0;L<16;L++)T[A+L]=E[L];return T}return(0,sQ.unsafeStringify)(E)}});var P7=W((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});I7.default=JM;var AM=LM(j4()),EM=B0();function LM(_){return _&&_.__esModule?_:{default:_}}function JM(_){let T=typeof _==="string"?(0,AM.default)(_):_,A=XM(T);return typeof _==="string"?(0,EM.unsafeStringify)(A):A}function XM(_){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 y7=W((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});w7.default=void 0;var ZM=KM(u8()),YM=B0();function KM(_){return _&&_.__esModule?_:{default:_}}var j7=null,x7=null,k1=0;function $M(_,T,A){_=_||{};let E=T&&A||0,L=T||new Uint8Array(16),J=_.random||(_.rng||ZM.default)(),X=_.msecs!==void 0?_.msecs:Date.now(),H=_.seq!==void 0?_.seq:null,Z=x7,Y=j7;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 x7=Z,j7=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,YM.unsafeStringify)(L)}var Af=w7.default=$M});var k7=W((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});v7.default=void 0;var GM=UM(P4());function UM(_){return _&&_.__esModule?_:{default:_}}function WM(_){if(!(0,GM.default)(_))throw TypeError("Invalid UUID");return parseInt(_.slice(14,15),16)}var Lf=v7.default=WM});var f7=W((l_)=>{Object.defineProperty(l_,"__esModule",{value:!0});Object.defineProperty(l_,"MAX",{enumerable:!0,get:function(){return NM.default}});Object.defineProperty(l_,"NIL",{enumerable:!0,get:function(){return QM.default}});Object.defineProperty(l_,"parse",{enumerable:!0,get:function(){return MM.default}});Object.defineProperty(l_,"stringify",{enumerable:!0,get:function(){return VM.default}});Object.defineProperty(l_,"v1",{enumerable:!0,get:function(){return zM.default}});Object.defineProperty(l_,"v1ToV6",{enumerable:!0,get:function(){return FM.default}});Object.defineProperty(l_,"v3",{enumerable:!0,get:function(){return CM.default}});Object.defineProperty(l_,"v4",{enumerable:!0,get:function(){return OM.default}});Object.defineProperty(l_,"v5",{enumerable:!0,get:function(){return RM.default}});Object.defineProperty(l_,"v6",{enumerable:!0,get:function(){return DM.default}});Object.defineProperty(l_,"v6ToV1",{enumerable:!0,get:function(){return BM.default}});Object.defineProperty(l_,"v7",{enumerable:!0,get:function(){return qM.default}});Object.defineProperty(l_,"validate",{enumerable:!0,get:function(){return IM.default}});Object.defineProperty(l_,"version",{enumerable:!0,get:function(){return PM.default}});var NM=J1(k9()),QM=J1(g9()),MM=J1(j4()),VM=J1(B0()),zM=J1(l5()),FM=J1(n5()),CM=J1(Z7()),OM=J1(Q7()),RM=J1(R7()),DM=J1(q7()),BM=J1(P7()),qM=J1(y7()),IM=J1(P4()),PM=J1(k7());function J1(_){return _&&_.__esModule?_:{default:_}}});var uT=W((Hf,b7)=>{function jM(_,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}b7.exports=jM});var a5=W((Zf,g7)=>{var f1=I("util");g7.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 s5=W((u7)=>{var c8=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 M1(_){L_.call(this,_)}c8.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 s1(_){L_.call(this,_)}c8.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 p8=I("stream");function o5(_){p8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}c8.inherits(o5,p8.Readable);o5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function r5(_){p8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}c8.inherits(r5,p8.Writable);r5.prototype._write=function(_,T,A){this._restorer(_),A()};var m7=null;function xM(_){if(_!==m7){let T=a5();L_.nativeString=T(_.QlobberString,L_),L_.nativeNumber=T(_.QlobberNumber,L_),M1.nativeString=T(_.QlobberDedupString,M1),M1.nativeNumber=T(_.QlobberDedupNumber,M1),s1.native=T(_.QlobberTrue,s1),m7=_}return u7}u7.Qlobber=L_;u7.QlobberDedup=M1;u7.QlobberTrue=s1;u7.VisitorStream=o5;u7.RestorerStream=r5;u7.set_native=xM});var d7=W((Kf,e5)=>{var fM=I("util"),bM=s5(),t5=bM.Qlobber;function V1(_){t5.call(this,_),this.subscriptionsCount=0}fM.inherits(V1,t5);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,t5.prototype.clear.call(this)};V1.set_native=function(_){let T=a5();return V1.native=T(_.QlobberSub,V1),e5.exports};e5.exports=V1});var n7=W(($f,T6)=>{var{Readable:x4}=I("stream"),gM=d7(),{QlobberTrue:mM}=s5(),_6=uT(),p7={wildcard_one:"+",wildcard_some:"#",separator:"/"};function*uM(_){for(let T of _)yield*T}function*c7(_,T){let A=new mM(p7);A.add(T);for(let[E,L]of _)if(A.test(E))yield L}function*dM(_,T){for(let A of _.values())if(!T[A.brokerId])yield A}function*cM(_,T){for(let[A,E]of _)if(E.has(T))yield A}class l7{#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 gM(p7)}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 c7(this.#J,A)});return x4.from(uM(T))}createRetainedStream(_){return x4.from(c7(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 _6(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 _6(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(dM(this.#N,_))}getClientList(_){return x4.from(cM(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}T6.exports=()=>{return new l7};T6.exports.Packet=_6});var a7=W((Gf,i7)=>{var b1=I("util");i7.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 s7=W((r7)=>{var l8=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 z1(_){J_.call(this,_)}l8.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 t1(_){J_.call(this,_)}l8.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 n8=I("stream");function A6(_){n8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}l8.inherits(A6,n8.Readable);A6.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function E6(_){n8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}l8.inherits(E6,n8.Writable);E6.prototype._write=function(_,T,A){this._restorer(_),A()};var o7=null;function pM(_){if(_!==o7){let T=a7();J_.nativeString=T(_.QlobberString,J_),J_.nativeNumber=T(_.QlobberNumber,J_),z1.nativeString=T(_.QlobberDedupString,z1),z1.nativeNumber=T(_.QlobberDedupNumber,z1),t1.native=T(_.QlobberTrue,t1),o7=_}return r7}r7.Qlobber=J_;r7.QlobberDedup=z1;r7.QlobberTrue=t1;r7.VisitorStream=A6;r7.RestorerStream=E6;r7.set_native=pM});var e7=W((Wf,t7)=>{var{Qlobber:sM}=s7(),dT=I("assert"),tM=u5();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=tM({results:!1,released:A}),this.concurrency=_.concurrency||0,this.current=0,this._doing=!1,this._matcher=new sM({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||eM,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 eM(){}t7.exports=e1});var F_=W((Nf,TJ)=>{class _J 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=_}}TJ.exports={AggregateError:_J,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 L6=W((Qf,AJ)=>{AJ.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 n_=W((Mf,XJ)=>{var{format:_V,inspect:i8}=L6(),{AggregateError:TV}=F_(),AV=globalThis.AggregateError||TV,EV=Symbol("kIsNodeError"),LV=["string","function","number","object","Function","Object","boolean","bigint","symbol"],JV=/^([A-Z][a-z0-9]*)+$/,a8={};function YT(_,T){if(!_)throw new a8.ERR_INTERNAL_ASSERTION(T)}function EJ(_){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 XV(_,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 _V(T,...A)}function g_(_,T,A){if(!A)A=Error;class E extends A{constructor(...L){super(XV(_,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[EV]=!0,a8[_]=E}function LJ(_){let T="__node_internal_"+_.name;return Object.defineProperty(_,"name",{value:T}),_}function HV(_,T){if(_&&T&&_!==T){if(Array.isArray(T.errors))return T.errors.push(_),T;let A=new AV([T,_],T.message);return A.code=T.code,A}return _||T}class JJ extends Error{constructor(_="The operation was aborted",T=void 0){if(T!==void 0&&typeof T!=="object")throw new a8.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"),LV.includes(Z))L.push(Z.toLowerCase());else if(JV.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=i8(A,{depth:-1});E+=`. Received ${Z}`}}else{let Z=i8(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=i8(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=EJ(String(A));else if(typeof A==="bigint"){E=String(A);let L=BigInt(2)**BigInt(32);if(A>L||A<-L)E=EJ(E);E+="n"}else E=i8(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);XJ.exports={AbortError:JJ,aggregateTwoErrors:LJ(HV),hideStackFrames:LJ,codes:a8}});var s_=W((Vf,X6)=>{var ZV=I("buffer"),{format:YV,inspect:KV}=L6(),{codes:{ERR_INVALID_ARG_TYPE:J6}}=n_(),{kResistStopPropagation:$V,AggregateError:GV,SymbolDispose:UV}=F_(),WV=globalThis.AbortSignal||I("abort-controller").AbortSignal,NV=globalThis.AbortController||I("abort-controller").AbortController,QV=Object.getPrototypeOf(async function(){}).constructor,HJ=globalThis.Blob||ZV.Blob,MV=typeof HJ<"u"?function(T){return T instanceof HJ}:function(T){return!1},ZJ=(_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new J6(T,"AbortSignal",_)},VV=(_,T)=>{if(typeof _!=="function")throw new J6(T,"Function",_)};X6.exports={AggregateError:GV,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:YV,inspect:KV,types:{isAsyncFunction(_){return _ instanceof QV},isArrayBufferView(_){return ArrayBuffer.isView(_)}},isBlob:MV,deprecate(_,T){return _},addAbortListener:I("events").addAbortListener||function(T,A){if(T===void 0)throw new J6("signal","AbortSignal",T);ZJ(T,"signal"),VV(A,"listener");let E;if(T.aborted)queueMicrotask(()=>A());else T.addEventListener("abort",A,{__proto__:null,once:!0,[$V]:!0}),E=()=>{T.removeEventListener("abort",A)};return{__proto__:null,[UV](){var L;(L=E)===null||L===void 0||L()}}},AbortSignalAny:WV.any||function(T){if(T.length===1)return T[0];let A=new NV,E=()=>A.abort();return T.forEach((L)=>{ZJ(L,"signals"),L.addEventListener("abort",E,{once:!0})}),A.signal.addEventListener("abort",()=>{T.forEach((L)=>L.removeEventListener("abort",E))},{once:!0}),A.signal}};X6.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var pT=W((zf,VJ)=>{var{ArrayIsArray:Z6,ArrayPrototypeIncludes:GJ,ArrayPrototypeJoin:UJ,ArrayPrototypeMap:zV,NumberIsInteger:Y6,NumberIsNaN:FV,NumberMAX_SAFE_INTEGER:CV,NumberMIN_SAFE_INTEGER:OV,NumberParseInt:RV,ObjectPrototypeHasOwnProperty:DV,RegExpPrototypeExec:WJ,String:BV,StringPrototypeToUpperCase:qV,StringPrototypeTrim:IV}=F_(),{hideStackFrames:F1,codes:{ERR_SOCKET_BAD_PORT:PV,ERR_INVALID_ARG_TYPE:i_,ERR_INVALID_ARG_VALUE:cT,ERR_OUT_OF_RANGE:KT,ERR_UNKNOWN_SIGNAL:YJ}}=n_(),{normalizeEncoding:jV}=s_(),{isAsyncFunction:xV,isArrayBufferView:wV}=s_().types,KJ={};function SV(_){return _===(_|0)}function yV(_){return _===_>>>0}var vV=/^[0-7]+$/,hV="must be a 32-bit unsigned integer or an octal string";function kV(_,T,A){if(typeof _>"u")_=A;if(typeof _==="string"){if(WJ(vV,_)===null)throw new cT(T,_,hV);_=RV(_,8)}return NJ(_,T),_}var fV=F1((_,T,A=OV,E=CV)=>{if(typeof _!=="number")throw new i_(T,"number",_);if(!Y6(_))throw new KT(T,"an integer",_);if(_<A||_>E)throw new KT(T,`>= ${A} && <= ${E}`,_)}),bV=F1((_,T,A=-2147483648,E=2147483647)=>{if(typeof _!=="number")throw new i_(T,"number",_);if(!Y6(_))throw new KT(T,"an integer",_);if(_<A||_>E)throw new KT(T,`>= ${A} && <= ${E}`,_)}),NJ=F1((_,T,A=!1)=>{if(typeof _!=="number")throw new i_(T,"number",_);if(!Y6(_))throw new KT(T,"an integer",_);let E=A?1:0,L=4294967295;if(_<E||_>L)throw new KT(T,`>= ${E} && <= ${L}`,_)});function K6(_,T){if(typeof _!=="string")throw new i_(T,"string",_)}function gV(_,T,A=void 0,E){if(typeof _!=="number")throw new i_(T,"number",_);if(A!=null&&_<A||E!=null&&_>E||(A!=null||E!=null)&&FV(_))throw new KT(T,`${A!=null?`>= ${A}`:""}${A!=null&&E!=null?" && ":""}${E!=null?`<= ${E}`:""}`,_)}var mV=F1((_,T,A)=>{if(!GJ(A,_)){let L="must be one of: "+UJ(zV(A,(J)=>typeof J==="string"?`'${J}'`:BV(J)),", ");throw new cT(T,_,L)}});function QJ(_,T){if(typeof _!=="boolean")throw new i_(T,"boolean",_)}function H6(_,T,A){return _==null||!DV(_,T)?A:_[T]}var uV=F1((_,T,A=null)=>{let E=H6(A,"allowArray",!1),L=H6(A,"allowFunction",!1);if(!H6(A,"nullable",!1)&&_===null||!E&&Z6(_)||typeof _!=="object"&&(!L||typeof _!=="function"))throw new i_(T,"Object",_)}),dV=F1((_,T)=>{if(_!=null&&typeof _!=="object"&&typeof _!=="function")throw new i_(T,"a dictionary",_)}),o8=F1((_,T,A=0)=>{if(!Z6(_))throw new i_(T,"Array",_);if(_.length<A){let E=`must be longer than ${A}`;throw new cT(T,_,E)}});function cV(_,T){o8(_,T);for(let A=0;A<_.length;A++)K6(_[A],`${T}[${A}]`)}function pV(_,T){o8(_,T);for(let A=0;A<_.length;A++)QJ(_[A],`${T}[${A}]`)}function lV(_,T){o8(_,T);for(let A=0;A<_.length;A++){let E=_[A],L=`${T}[${A}]`;if(E==null)throw new i_(L,"AbortSignal",E);MJ(E,L)}}function nV(_,T="signal"){if(K6(_,T),KJ[_]===void 0){if(KJ[qV(_)]!==void 0)throw new YJ(_+" (signals must use all capital letters)");throw new YJ(_)}}var iV=F1((_,T="buffer")=>{if(!wV(_))throw new i_(T,["Buffer","TypedArray","DataView"],_)});function aV(_,T){let A=jV(T),E=_.length;if(A==="hex"&&E%2!==0)throw new cT("encoding",T,`is invalid for data of length ${E}`)}function oV(_,T="Port",A=!0){if(typeof _!=="number"&&typeof _!=="string"||typeof _==="string"&&IV(_).length===0||+_!==+_>>>0||_>65535||_===0&&!A)throw new PV(T,_,A);return _|0}var MJ=F1((_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new i_(T,"AbortSignal",_)}),rV=F1((_,T)=>{if(typeof _!=="function")throw new i_(T,"Function",_)}),sV=F1((_,T)=>{if(typeof _!=="function"||xV(_))throw new i_(T,"Function",_)}),tV=F1((_,T)=>{if(_!==void 0)throw new i_(T,"undefined",_)});function eV(_,T,A){if(!GJ(A,_))throw new i_(T,`('${UJ(A,"|")}')`,_)}var _z=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function $J(_,T){if(typeof _>"u"||!WJ(_z,_))throw new cT(T,_,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function Tz(_){if(typeof _==="string")return $J(_,"hints"),_;else if(Z6(_)){let T=_.length,A="";if(T===0)return A;for(let E=0;E<T;E++){let L=_[E];if($J(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"')}VJ.exports={isInt32:SV,isUint32:yV,parseFileMode:kV,validateArray:o8,validateStringArray:cV,validateBooleanArray:pV,validateAbortSignalArray:lV,validateBoolean:QJ,validateBuffer:iV,validateDictionary:dV,validateEncoding:aV,validateFunction:rV,validateInt32:bV,validateInteger:fV,validateNumber:gV,validateObject:uV,validateOneOf:mV,validatePlainFunction:sV,validatePort:oV,validateSignalName:nV,validateString:K6,validateUint32:NJ,validateUndefined:tV,validateUnion:eV,validateAbortSignal:MJ,validateLinkHeaderValue:Tz}});var c0=W((Ff,zJ)=>{zJ.exports=global.process});var T0=W((Cf,vJ)=>{var{SymbolAsyncIterator:FJ,SymbolIterator:CJ,SymbolFor:$T}=F_(),OJ=$T("nodejs.stream.destroyed"),RJ=$T("nodejs.stream.errored"),$6=$T("nodejs.stream.readable"),G6=$T("nodejs.stream.writable"),DJ=$T("nodejs.stream.disturbed"),Az=$T("nodejs.webstream.isClosedPromise"),Ez=$T("nodejs.webstream.controllerErrorFunction");function r8(_,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 s8(_){var T;return!!(_&&typeof _.write==="function"&&typeof _.on==="function"&&(!_._readableState||((T=_._writableState)===null||T===void 0?void 0:T.writable)!==!1))}function Lz(_){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 BJ(_){return!!(_&&!_0(_)&&typeof _.pipeThrough==="function"&&typeof _.getReader==="function"&&typeof _.cancel==="function")}function qJ(_){return!!(_&&!_0(_)&&typeof _.getWriter==="function"&&typeof _.abort==="function")}function IJ(_){return!!(_&&!_0(_)&&typeof _.readable==="object"&&typeof _.writable==="object")}function Jz(_){return BJ(_)||qJ(_)||IJ(_)}function Xz(_,T){if(_==null)return!1;if(T===!0)return typeof _[FJ]==="function";if(T===!1)return typeof _[CJ]==="function";return typeof _[FJ]==="function"||typeof _[CJ]==="function"}function t8(_){if(!_0(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!!(_.destroyed||_[OJ]||E!==null&&E!==void 0&&E.destroyed)}function PJ(_){if(!s8(_))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 Hz(_,T){if(!s8(_))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 Zz(_){if(!r8(_))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 jJ(_,T){if(!r8(_))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 xJ(_){if(_&&_[$6]!=null)return _[$6];if(typeof(_===null||_===void 0?void 0:_.readable)!=="boolean")return null;if(t8(_))return!1;return r8(_)&&_.readable&&!jJ(_)}function wJ(_){if(_&&_[G6]!=null)return _[G6];if(typeof(_===null||_===void 0?void 0:_.writable)!=="boolean")return null;if(t8(_))return!1;return s8(_)&&_.writable&&!PJ(_)}function Yz(_,T){if(!_0(_))return null;if(t8(_))return!0;if((T===null||T===void 0?void 0:T.readable)!==!1&&xJ(_))return!1;if((T===null||T===void 0?void 0:T.writable)!==!1&&wJ(_))return!1;return!0}function Kz(_){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 $z(_){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 Gz(_){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"&&SJ(_))return _._closed;return null}function SJ(_){return typeof _._closed==="boolean"&&typeof _._defaultKeepAlive==="boolean"&&typeof _._removedConnection==="boolean"&&typeof _._removedContLen==="boolean"}function yJ(_){return typeof _._sent100==="boolean"&&SJ(_)}function Uz(_){var T;return typeof _._consuming==="boolean"&&typeof _._dumped==="boolean"&&((T=_.req)===null||T===void 0?void 0:T.upgradeOrConnect)===void 0}function Wz(_){if(!_0(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!E&&yJ(_)||!!(E&&E.autoDestroy&&E.emitClose&&E.closed===!1)}function Nz(_){var T;return!!(_&&((T=_[DJ])!==null&&T!==void 0?T:_.readableDidRead||_.readableAborted))}function Qz(_){var T,A,E,L,J,X,H,Z,Y,K;return!!(_&&((T=(A=(E=(L=(J=(X=_[RJ])!==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))}vJ.exports={isDestroyed:t8,kIsDestroyed:OJ,isDisturbed:Nz,kIsDisturbed:DJ,isErrored:Qz,kIsErrored:RJ,isReadable:xJ,kIsReadable:$6,kIsClosedPromise:Az,kControllerErrorFunction:Ez,kIsWritable:G6,isClosed:Gz,isDuplexNodeStream:Lz,isFinished:Yz,isIterable:Xz,isReadableNodeStream:r8,isReadableStream:BJ,isReadableEnded:Zz,isReadableFinished:jJ,isReadableErrored:$z,isNodeStream:_0,isWebStream:Jz,isWritable:wJ,isWritableNodeStream:s8,isWritableStream:qJ,isWritableEnded:PJ,isWritableFinished:Hz,isWritableErrored:Kz,isServerRequest:Uz,isServerResponse:yJ,willEmitClose:Wz,isTransformStream:IJ}});var q0=W((Of,M6)=>{var p0=c0(),{AbortError:cJ,codes:Mz}=n_(),{ERR_INVALID_ARG_TYPE:Vz,ERR_STREAM_PREMATURE_CLOSE:hJ}=Mz,{kEmptyObject:W6,once:N6}=s_(),{validateAbortSignal:zz,validateFunction:Fz,validateObject:Cz,validateBoolean:Oz}=pT(),{Promise:Rz,PromisePrototypeThen:Dz,SymbolDispose:pJ}=F_(),{isClosed:Bz,isReadable:kJ,isReadableNodeStream:U6,isReadableStream:qz,isReadableFinished:fJ,isReadableErrored:bJ,isWritable:gJ,isWritableNodeStream:mJ,isWritableStream:Iz,isWritableFinished:uJ,isWritableErrored:dJ,isNodeStream:Pz,willEmitClose:jz,kIsClosedPromise:xz}=T0(),lT;function wz(_){return _.setHeader&&typeof _.abort==="function"}var Q6=()=>{};function lJ(_,T,A){var E,L;if(arguments.length===2)A=T,T=W6;else if(T==null)T=W6;else Cz(T,"options");if(Fz(A,"callback"),zz(T.signal,"options.signal"),A=N6(A),qz(_)||Iz(_))return Sz(_,T,A);if(!Pz(_))throw new Vz("stream",["ReadableStream","WritableStream","Stream"],_);let J=(E=T.readable)!==null&&E!==void 0?E:U6(_),X=(L=T.writable)!==null&&L!==void 0?L:mJ(_),H=_._writableState,Z=_._readableState,Y=()=>{if(!_.writable)G()},K=jz(_)&&U6(_)===J&&mJ(_)===X,$=uJ(_,!1),G=()=>{if($=!0,_.destroyed)K=!1;if(K&&(!_.readable||J))return;if(!J||U)A.call(_)},U=fJ(_,!1),V=()=>{if(U=!0,_.destroyed)K=!1;if(K&&(!_.writable||X))return;if(!X||$)A.call(_)},N=(f)=>{A.call(_,f)},z=Bz(_),Q=()=>{z=!0;let f=dJ(_)||bJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);if(J&&!U&&U6(_,!0)){if(!fJ(_,!1))return A.call(_,new hJ)}if(X&&!$){if(!uJ(_,!1))return A.call(_,new hJ)}A.call(_)},F=()=>{z=!0;let f=dJ(_)||bJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);A.call(_)},R=()=>{_.req.on("finish",G)};if(wz(_)){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||kJ(_))&&($||gJ(_)===!1))p0.nextTick(F);else if(!X&&(!K||gJ(_))&&(U||kJ(_)===!1))p0.nextTick(F);else if(Z&&_.req&&_.aborted)p0.nextTick(F);let q=()=>{if(A=Q6,_.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 S=A;q(),S.call(_,new cJ(void 0,{cause:T.signal.reason}))};if(T.signal.aborted)p0.nextTick(f);else{lT=lT||s_().addAbortListener;let S=lT(T.signal,f),g=A;A=N6((...l)=>{S[pJ](),g.apply(_,l)})}}return q}function Sz(_,T,A){let E=!1,L=Q6;if(T.signal)if(L=()=>{E=!0,A.call(_,new cJ(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=N6((...Z)=>{X[pJ](),H.apply(_,Z)})}let J=(...X)=>{if(!E)p0.nextTick(()=>A.apply(_,X))};return Dz(_[xz].promise,J,J),Q6}function yz(_,T){var A;let E=!1;if(T===null)T=W6;if((A=T)!==null&&A!==void 0&&A.cleanup)Oz(T.cleanup,"cleanup"),E=T.cleanup;return new Rz((L,J)=>{let X=lJ(_,T,(H)=>{if(E)X();if(H)J(H);else L()})})}M6.exports=lJ;M6.exports.finished=yz});var GT=W((Rf,eJ)=>{var A0=c0(),{aggregateTwoErrors:vz,codes:{ERR_MULTIPLE_CALLBACK:hz},AbortError:kz}=n_(),{Symbol:aJ}=F_(),{kIsDestroyed:fz,isDestroyed:bz,isFinished:gz,isServerRequest:mz}=T0(),oJ=aJ("kDestroy"),V6=aJ("kConstruct");function rJ(_,T,A){if(_){if(_.stack,T&&!T.errored)T.errored=_;if(A&&!A.errored)A.errored=_}}function uz(_,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(rJ(_,E,A),E)E.destroyed=!0;if(A)A.destroyed=!0;if(!L.constructed)this.once(oJ,function(J){nJ(this,vz(J,_),T)});else nJ(this,_,T);return this}function nJ(_,T,A){let E=!1;function L(J){if(E)return;E=!0;let{_readableState:X,_writableState:H}=_;if(rJ(J,H,X),H)H.closed=!0;if(X)X.closed=!0;if(typeof A==="function")A(J);if(J)A0.nextTick(dz,_,J);else A0.nextTick(sJ,_)}try{_._destroy(T||null,L)}catch(J){L(J)}}function dz(_,T){z6(_,T),sJ(_)}function sJ(_){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 z6(_,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 cz(){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 F6(_,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(z6,_,T);else z6(_,T)}}function pz(_,T){if(typeof _._construct!=="function")return;let{_readableState:A,_writableState:E}=_;if(A)A.constructed=!1;if(E)E.constructed=!1;if(_.once(V6,T),_.listenerCount(V6)>1)return;A0.nextTick(lz,_)}function lz(_){let T=!1;function A(E){if(T){F6(_,E!==null&&E!==void 0?E:new hz);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(oJ,E);else if(E)F6(_,E,!0);else A0.nextTick(nz,_)}try{_._construct((E)=>{A0.nextTick(A,E)})}catch(E){A0.nextTick(A,E)}}function nz(_){_.emit(V6)}function iJ(_){return(_===null||_===void 0?void 0:_.setHeader)&&typeof _.abort==="function"}function tJ(_){_.emit("close")}function iz(_,T){_.emit("error",T),A0.nextTick(tJ,_)}function az(_,T){if(!_||bz(_))return;if(!T&&!gz(_))T=new kz;if(mz(_))_.socket=null,_.destroy(T);else if(iJ(_))_.abort();else if(iJ(_.req))_.req.abort();else if(typeof _.destroy==="function")_.destroy(T);else if(typeof _.close==="function")_.close();else if(T)A0.nextTick(iz,_,T);else A0.nextTick(tJ,_);if(!_.destroyed)_[fz]=!0}eJ.exports={construct:pz,destroyer:az,destroy:uz,undestroy:cz,errorOrDestroy:F6}});var TA=W((Df,TX)=>{var{ArrayIsArray:oz,ObjectSetPrototypeOf:_X}=F_(),{EventEmitter:e8}=I("events");function _A(_){e8.call(this,_)}_X(_A.prototype,e8.prototype);_X(_A,e8);_A.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(),e8.listenerCount(this,"error")===0)this.emit("error",K)}C6(A,"error",Z),C6(_,"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 C6(_,T,A){if(typeof _.prependListener==="function")return _.prependListener(T,A);if(!_._events||!_._events[T])_.on(T,A);else if(oz(_._events[T]))_._events[T].unshift(A);else _._events[T]=[A,_._events[T]]}TX.exports={Stream:_A,prependListener:C6}});var w4=W((AF,AA)=>{var{SymbolDispose:rz}=F_(),{AbortError:AX,codes:sz}=n_(),{isNodeStream:EX,isWebStream:tz,kControllerErrorFunction:ez}=T0(),_F=q0(),{ERR_INVALID_ARG_TYPE:LX}=sz,O6,TF=(_,T)=>{if(typeof _!=="object"||!("aborted"in _))throw new LX(T,"AbortSignal",_)};AF.addAbortSignal=function(T,A){if(TF(T,"signal"),!EX(A)&&!tz(A))throw new LX("stream",["ReadableStream","WritableStream","Stream"],A);return AF.addAbortSignalNoValidate(T,A)};AF.addAbortSignalNoValidate=function(_,T){if(typeof _!=="object"||!("aborted"in _))return T;let A=EX(T)?()=>{T.destroy(new AX(void 0,{cause:_.reason}))}:()=>{T[ez](new AX(void 0,{cause:_.reason}))};if(_.aborted)A();else{O6=O6||s_().addAbortListener;let E=O6(_,A);_F(T,E[rz])}return T}});var HX=W((Bf,XX)=>{var{StringPrototypeSlice:JX,SymbolIterator:JF,TypedArrayPrototypeSet:EA,Uint8Array:XF}=F_(),{Buffer:R6}=I("buffer"),{inspect:HF}=s_();XX.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 R6.alloc(0);let A=R6.allocUnsafe(T>>>0),E=this.head,L=0;while(E)EA(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}*[JF](){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+=JX(J,0,T),this.head=E,E.data=JX(J,T);break}++L}while((E=E.next)!==null);return this.length-=L,A}_getBuffer(T){let A=R6.allocUnsafe(T),E=T,L=this.head,J=0;do{let X=L.data;if(T>X.length)EA(A,X,E-T),T-=X.length;else{if(T===X.length)if(EA(A,X,E-T),++J,L.next)this.head=L.next;else this.head=this.tail=null;else EA(A,new XF(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 HF(this,{...A,depth:0,customInspect:!1})}}});var S4=W((qf,$X)=>{var{MathFloor:ZF,NumberIsInteger:YF}=F_(),{validateInteger:KF}=pT(),{ERR_INVALID_ARG_VALUE:$F}=n_().codes,ZX=16384,YX=16;function GF(_,T,A){return _.highWaterMark!=null?_.highWaterMark:T?_[A]:null}function KX(_){return _?YX:ZX}function UF(_,T){if(KF(T,"value",0),_)YX=T;else ZX=T}function WF(_,T,A,E){let L=GF(T,E,A);if(L!=null){if(!YF(L)||L<0){let J=E?`options.${A}`:"options.highWaterMark";throw new $F(J,L)}return ZF(L)}return KX(_.objectMode)}$X.exports={getHighWaterMark:WF,getDefaultHighWaterMark:KX,setDefaultHighWaterMark:UF}});var WX=W((D6,UX)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var LA=I("buffer"),E0=LA.Buffer;function GX(_,T){for(var A in _)T[A]=_[A]}if(E0.from&&E0.alloc&&E0.allocUnsafe&&E0.allocUnsafeSlow)UX.exports=LA;else GX(LA,D6),D6.Buffer=UT;function UT(_,T,A){return E0(_,T,A)}UT.prototype=Object.create(E0.prototype);GX(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 LA.SlowBuffer(_)}});var QX=W((PF)=>{var q6=WX().Buffer,NX=q6.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 NF(_){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 QF(_){var T=NF(_);if(typeof T!=="string"&&(q6.isEncoding===NX||!NX(_)))throw Error("Unknown encoding: "+_);return T||_}PF.StringDecoder=y4;function y4(_){this.encoding=QF(_);var T;switch(this.encoding){case"utf16le":this.text=OF,this.end=RF,T=4;break;case"utf8":this.fillLast=zF,T=4;break;case"base64":this.text=DF,this.end=BF,T=3;break;default:this.write=qF,this.end=IF;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=q6.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=CF;y4.prototype.text=FF;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 B6(_){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 MF(_,T,A){var E=T.length-1;if(E<A)return 0;var L=B6(T[E]);if(L>=0){if(L>0)_.lastNeed=L-1;return L}if(--E<A||L===-2)return 0;if(L=B6(T[E]),L>=0){if(L>0)_.lastNeed=L-2;return L}if(--E<A||L===-2)return 0;if(L=B6(T[E]),L>=0){if(L>0)if(L===2)L=0;else _.lastNeed=L-3;return L}return 0}function VF(_,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 zF(_){var T=this.lastTotal-this.lastNeed,A=VF(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 FF(_,T){var A=MF(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 CF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+"\uFFFD";return T}function OF(_,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 RF(_){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 DF(_,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 BF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+this.lastChar.toString("base64",0,3-this.lastNeed);return T}function qF(_){return _.toString(this.encoding)}function IF(_){return _&&_.length?this.write(_):""}});var I6=W((Pf,FX)=>{var MX=c0(),{PromisePrototypeThen:xF,SymbolAsyncIterator:VX,SymbolIterator:zX}=F_(),{Buffer:wF}=I("buffer"),{ERR_INVALID_ARG_TYPE:SF,ERR_STREAM_NULL_VALUES:yF}=n_().codes;function vF(_,T,A){let E;if(typeof T==="string"||T instanceof wF)return new _({objectMode:!0,...A,read(){this.push(T),this.push(null)}});let L;if(T&&T[VX])L=!0,E=T[VX]();else if(T&&T[zX])L=!1,E=T[zX]();else throw new SF("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){xF(H(Y),()=>MX.nextTick(K,Y),($)=>MX.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 yF;else if(J.push($))continue;else X=!1}}catch(Y){J.destroy(Y)}break}}return J}FX.exports=vF});var h4=W((jf,bX)=>{var g1=c0(),{ArrayPrototypeIndexOf:hF,NumberIsInteger:kF,NumberIsNaN:fF,NumberParseInt:bF,ObjectDefineProperties:h6,ObjectKeys:gF,ObjectSetPrototypeOf:RX,Promise:DX,SafeSet:mF,SymbolAsyncDispose:uF,SymbolAsyncIterator:dF,Symbol:cF}=F_();bX.exports=t;t.ReadableState=ZA;var{EventEmitter:pF}=I("events"),{Stream:l0,prependListener:lF}=TA(),{Buffer:P6}=I("buffer"),{addAbortSignal:nF}=w4(),BX=q0(),A_=s_().debuglog("stream",(_)=>{A_=_}),iF=HX(),aT=GT(),{getHighWaterMark:aF,getDefaultHighWaterMark:oF}=S4(),{aggregateTwoErrors:CX,codes:{ERR_INVALID_ARG_TYPE:rF,ERR_METHOD_NOT_IMPLEMENTED:sF,ERR_OUT_OF_RANGE:tF,ERR_STREAM_PUSH_AFTER_EOF:eF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:_C},AbortError:TC}=n_(),{validateObject:AC}=pT(),WT=cF("kPaused"),{StringDecoder:qX}=QX(),EC=I6();RX(t.prototype,l0.prototype);RX(t,l0);var j6=()=>{},{errorOrDestroy:nT}=aT,iT=1,LC=2,IX=4,v4=8,PX=16,JA=32,XA=64,jX=128,JC=256,XC=512,HC=1024,y6=2048,v6=4096,ZC=8192,YC=16384,KC=32768,xX=65536,$C=131072,GC=262144;function w_(_){return{enumerable:!1,get(){return(this.state&_)!==0},set(T){if(T)this.state|=_;else this.state&=~_}}}h6(ZA.prototype,{objectMode:w_(iT),ended:w_(LC),endEmitted:w_(IX),reading:w_(v4),constructed:w_(PX),sync:w_(JA),needReadable:w_(XA),emittedReadable:w_(jX),readableListening:w_(JC),resumeScheduled:w_(XC),errorEmitted:w_(HC),emitClose:w_(y6),autoDestroy:w_(v6),destroyed:w_(ZC),closed:w_(YC),closeEmitted:w_(KC),multiAwaitDrain:w_(xX),readingMore:w_($C),dataEmitted:w_(GC)});function ZA(_,T,A){if(typeof A!=="boolean")A=T instanceof L0();if(this.state=y6|v6|PX|JA,_&&_.objectMode)this.state|=iT;if(A&&_&&_.readableObjectMode)this.state|=iT;if(this.highWaterMark=_?aF(this,_,"readableHighWaterMark",A):oF(!1),this.buffer=new iF,this.length=0,this.pipes=[],this.flowing=null,this[WT]=null,_&&_.emitClose===!1)this.state&=~y6;if(_&&_.autoDestroy===!1)this.state&=~v6;if(this.errored=null,this.defaultEncoding=_&&_.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,_&&_.encoding)this.decoder=new qX(_.encoding),this.encoding=_.encoding}function t(_){if(!(this instanceof t))return new t(_);let T=this instanceof L0();if(this._readableState=new ZA(_,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)nF(_.signal,this)}l0.call(this,_),aT.construct(this,()=>{if(this._readableState.needReadable)HA(this,this._readableState)})}t.prototype.destroy=aT.destroy;t.prototype._undestroy=aT.undestroy;t.prototype._destroy=function(_,T){T(_)};t.prototype[pF.captureRejectionSymbol]=function(_){this.destroy(_)};t.prototype[uF]=function(){let _;if(!this.destroyed)_=this.readableEnded?null:new TC,this.destroy(_);return new DX((T,A)=>BX(this,(E)=>E&&E!==_?A(E):T(null)))};t.prototype.push=function(_,T){return wX(this,_,T,!1)};t.prototype.unshift=function(_,T){return wX(this,_,T,!0)};function wX(_,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=P6.from(T,A).toString(L.encoding);else T=P6.from(T,A),A=""}else if(T instanceof P6)A="";else if(l0._isUint8Array(T))T=l0._uint8ArrayToBuffer(T),A="";else if(T!=null)J=new rF("chunk",["string","Buffer","Uint8Array"],T)}if(J)nT(_,J);else if(T===null)L.state&=~v4,NC(_,L);else if((L.state&iT)!==0||T&&T.length>0)if(E)if((L.state&IX)!==0)nT(_,new _C);else if(L.destroyed||L.errored)return!1;else x6(_,L,T,!0);else if(L.ended)nT(_,new eF);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)x6(_,L,T,!1);else HA(_,L);else x6(_,L,T,!1);else if(!E)L.state&=~v4,HA(_,L);return!L.ended&&(L.length<L.highWaterMark||L.length===0)}function x6(_,T,A,E){if(T.flowing&&T.length===0&&!T.sync&&_.listenerCount("data")>0){if((T.state&xX)!==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&XA)!==0)YA(_)}HA(_,T)}t.prototype.isPaused=function(){let _=this._readableState;return _[WT]===!0||_.flowing===!1};t.prototype.setEncoding=function(_){let T=new qX(_);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 UC=1073741824;function WC(_){if(_>UC)throw new tF("size","<= 1GiB",_);else _--,_|=_>>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++;return _}function OX(_,T){if(_<=0||T.length===0&&T.ended)return 0;if((T.state&iT)!==0)return 1;if(fF(_)){if(T.flowing&&T.length)return T.buffer.first().length;return T.length}if(_<=T.length)return _;return T.ended?T.length:0}t.prototype.read=function(_){if(A_("read",_),_===void 0)_=NaN;else if(!kF(_))_=bF(_,10);let T=this._readableState,A=_;if(_>T.highWaterMark)T.highWaterMark=WC(_);if(_!==0)T.state&=~jX;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)w6(this);else YA(this);return null}if(_=OX(_,T),_===0&&T.ended){if(T.length===0)w6(this);return null}let E=(T.state&XA)!==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|JA,T.length===0)T.state|=XA;try{this._read(T.highWaterMark)}catch(J){nT(this,J)}if(T.state&=~JA,!T.reading)_=OX(A,T)}let L;if(_>0)L=kX(_,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)w6(this)}if(L!==null&&!T.errorEmitted&&!T.closeEmitted)T.dataEmitted=!0,this.emit("data",L);return L};function NC(_,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)YA(_);else T.needReadable=!1,T.emittedReadable=!0,SX(_)}function YA(_){let T=_._readableState;if(A_("emitReadable",T.needReadable,T.emittedReadable),T.needReadable=!1,!T.emittedReadable)A_("emitReadable",T.flowing),T.emittedReadable=!0,g1.nextTick(SX,_)}function SX(_){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,vX(_)}function HA(_,T){if(!T.readingMore&&T.constructed)T.readingMore=!0,g1.nextTick(QC,_,T)}function QC(_,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}t.prototype._read=function(_){throw new sF("_read()")};t.prototype.pipe=function(_,T){let A=this,E=this._readableState;if(E.pipes.length===1){if(!E.multiAwaitDrain)E.multiAwaitDrain=!0,E.awaitDrainWriters=new mF(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=MC(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)}}lF(_,"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 MC(_,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()}}t.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=hF(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};t.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)YA(this);else if(!E.reading)g1.nextTick(VC,this)}}return A};t.prototype.addListener=t.prototype.on;t.prototype.removeListener=function(_,T){let A=l0.prototype.removeListener.call(this,_,T);if(_==="readable")g1.nextTick(yX,this);return A};t.prototype.off=t.prototype.removeListener;t.prototype.removeAllListeners=function(_){let T=l0.prototype.removeAllListeners.apply(this,arguments);if(_==="readable"||_===void 0)g1.nextTick(yX,this);return T};function yX(_){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 VC(_){A_("readable nexttick read 0"),_.read(0)}t.prototype.resume=function(){let _=this._readableState;if(!_.flowing)A_("resume"),_.flowing=!_.readableListening,zC(this,_);return _[WT]=!1,this};function zC(_,T){if(!T.resumeScheduled)T.resumeScheduled=!0,g1.nextTick(FC,_,T)}function FC(_,T){if(A_("resume",T.reading),!T.reading)_.read(0);if(T.resumeScheduled=!1,_.emit("resume"),vX(_),T.flowing&&!T.reading)_.read(0)}t.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 vX(_){let T=_._readableState;A_("flow",T.flowing);while(T.flowing&&_.read()!==null);}t.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=gF(_);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};t.prototype[dF]=function(){return hX(this)};t.prototype.iterator=function(_){if(_!==void 0)AC(_,"options");return hX(this,_)};function hX(_,T){if(typeof _.read!=="function")_=t.wrap(_,{objectMode:!0});let A=CC(_,T);return A.stream=_,A}async function*CC(_,T){let A=j6;function E(X){if(this===_)A(),A=j6;else A=X}_.on("readable",E);let L,J=BX(_,{writable:!1},(X)=>{L=X?CX(L,X):null,A(),A=j6});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 DX(E)}}catch(X){throw L=CX(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()}}h6(t.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}}});h6(ZA.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[WT]!==!1},set(_){this[WT]=!!_}}});t._fromList=kX;function kX(_,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 w6(_){let T=_._readableState;if(A_("endReadable",T.endEmitted),!T.endEmitted)T.ended=!0,g1.nextTick(OC,T,_)}function OC(_,T){if(A_("endReadableNT",_.endEmitted,_.length),!_.errored&&!_.closeEmitted&&!_.endEmitted&&_.length===0){if(_.endEmitted=!0,T.emit("end"),T.writable&&T.allowHalfOpen===!1)g1.nextTick(RC,T);else if(_.autoDestroy){let A=T._writableState;if(!A||A.autoDestroy&&(A.finished||A.writable===!1))T.destroy()}}}function RC(_){if(_.writable&&!_.writableEnded&&!_.destroyed)_.end()}t.from=function(_,T){return EC(t,_,T)};var S6;function fX(){if(S6===void 0)S6={};return S6}t.fromWeb=function(_,T){return fX().newStreamReadableFromReadableStream(_,T)};t.toWeb=function(_,T){return fX().newReadableStreamFromStreamReadable(_,T)};t.wrap=function(_,T){var A,E;return new t({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 WA=W((xf,rX)=>{var NT=c0(),{ArrayPrototypeSlice:uX,Error:DC,FunctionPrototypeSymbolHasInstance:dX,ObjectDefineProperty:cX,ObjectDefineProperties:BC,ObjectSetPrototypeOf:pX,StringPrototypeToLowerCase:qC,Symbol:IC,SymbolHasInstance:PC}=F_();rX.exports=O_;O_.WritableState=b4;var{EventEmitter:jC}=I("events"),k4=TA().Stream,{Buffer:KA}=I("buffer"),UA=GT(),{addAbortSignal:xC}=w4(),{getHighWaterMark:wC,getDefaultHighWaterMark:SC}=S4(),{ERR_INVALID_ARG_TYPE:yC,ERR_METHOD_NOT_IMPLEMENTED:vC,ERR_MULTIPLE_CALLBACK:lX,ERR_STREAM_CANNOT_PIPE:hC,ERR_STREAM_DESTROYED:f4,ERR_STREAM_ALREADY_FINISHED:kC,ERR_STREAM_NULL_VALUES:fC,ERR_STREAM_WRITE_AFTER_END:bC,ERR_UNKNOWN_ENCODING:nX}=n_().codes,{errorOrDestroy:oT}=UA;pX(O_.prototype,k4.prototype);pX(O_,k4);function b6(){}var rT=IC("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=_?wC(this,_,"writableHighWaterMark",A):SC(!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=mC.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 uX(this.buffered,this.bufferedIndex)};cX(b4.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function O_(_){let T=this instanceof L0();if(!T&&!dX(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)xC(_.signal,this)}k4.call(this,_),UA.construct(this,()=>{let A=this._writableState;if(!A.writing)m6(this,A);u6(this,A)})}cX(O_,PC,{__proto__:null,value:function(_){if(dX(this,_))return!0;if(this!==O_)return!1;return _&&_._writableState instanceof b4}});O_.prototype.pipe=function(){oT(this,new hC)};function iX(_,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"&&!KA.isEncoding(A))throw new nX(A);if(typeof E!=="function")E=b6}if(T===null)throw new fC;else if(!L.objectMode)if(typeof T==="string"){if(L.decodeStrings!==!1)T=KA.from(T,A),A="buffer"}else if(T instanceof KA)A="buffer";else if(k4._isUint8Array(T))T=k4._uint8ArrayToBuffer(T),A="buffer";else throw new yC("chunk",["string","Buffer","Uint8Array"],T);let J;if(L.ending)J=new bC;else if(L.destroyed)J=new f4("write");if(J)return NT.nextTick(E,J),oT(_,J,!0),J;return L.pendingcb++,gC(_,L,T,A,E)}O_.prototype.write=function(_,T,A){return iX(this,_,T,A)===!0};O_.prototype.cork=function(){this._writableState.corked++};O_.prototype.uncork=function(){let _=this._writableState;if(_.corked){if(_.corked--,!_.writing)m6(this,_)}};O_.prototype.setDefaultEncoding=function(T){if(typeof T==="string")T=qC(T);if(!KA.isEncoding(T))throw new nX(T);return this._writableState.defaultEncoding=T,this};function gC(_,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!==b6)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 gX(_,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 mX(_,T,A,E){--T.pendingcb,E(A),g6(T),oT(_,A)}function mC(_,T){let A=_._writableState,E=A.sync,L=A.writecb;if(typeof L!=="function"){oT(_,new lX);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(mX,_,A,T,L);else mX(_,A,T,L)}else{if(A.buffered.length>A.bufferedIndex)m6(_,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(uC,A.afterWriteTickInfo);else aX(_,A,1,L)}}function uC({stream:_,state:T,count:A,cb:E}){return T.afterWriteTickInfo=null,aX(_,T,A,E)}function aX(_,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)g6(T);u6(_,T)}function g6(_){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 m6(_,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?b6:(Y)=>{for(let K=X;K<A.length;++K)A[K].callback(Y)},Z=T.allNoop&&X===0?A:uX(A,X);Z.allBuffers=T.allBuffers,gX(_,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;gX(_,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 vC("_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=iX(this,_,T);if(J instanceof DC)L=J}if(E.corked)E.corked=1,this.uncork();if(L);else if(!E.errored&&!E.ending)E.ending=!0,u6(this,E,!0),E.ended=!0;else if(E.finished)L=new kC("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 $A(_){return _.ending&&!_.destroyed&&_.constructed&&_.length===0&&!_.errored&&_.buffered.length===0&&!_.finished&&!_.writing&&!_.errorEmitted&&!_.closeEmitted}function dC(_,T){let A=!1;function E(L){if(A){oT(_,L!==null&&L!==void 0?L:lX());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($A(T))T.prefinished=!0,_.emit("prefinish"),T.pendingcb++,NT.nextTick(f6,_,T)}T.sync=!0,T.pendingcb++;try{_._final(E)}catch(L){E(L)}T.sync=!1}function cC(_,T){if(!T.prefinished&&!T.finalCalled)if(typeof _._final==="function"&&!T.destroyed)T.finalCalled=!0,dC(_,T);else T.prefinished=!0,_.emit("prefinish")}function u6(_,T,A){if($A(T)){if(cC(_,T),T.pendingcb===0){if(A)T.pendingcb++,NT.nextTick((E,L)=>{if($A(L))f6(E,L);else L.pendingcb--},_,T);else if($A(T))T.pendingcb++,f6(_,T)}}}function f6(_,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()}}BC(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 pC=UA.destroy;O_.prototype.destroy=function(_,T){let A=this._writableState;if(!A.destroyed&&(A.bufferedIndex<A.buffered.length||A[rT].length))NT.nextTick(g6,A);return pC.call(this,_,T),this};O_.prototype._undestroy=UA.undestroy;O_.prototype._destroy=function(_,T){T(_)};O_.prototype[jC.captureRejectionSymbol]=function(_){this.destroy(_)};var k6;function oX(){if(k6===void 0)k6={};return k6}O_.fromWeb=function(_,T){return oX().newStreamWritableFromWritableStream(_,T)};O_.toWeb=function(_){return oX().newWritableStreamFromStreamWritable(_)}});var $H=W((wf,KH)=>{var d6=c0(),lC=I("buffer"),{isReadable:nC,isWritable:iC,isIterable:sX,isNodeStream:aC,isReadableNodeStream:tX,isWritableNodeStream:eX,isDuplexNodeStream:oC,isReadableStream:_H,isWritableStream:TH}=T0(),AH=q0(),{AbortError:ZH,codes:{ERR_INVALID_ARG_TYPE:rC,ERR_INVALID_RETURN_VALUE:EH}}=n_(),{destroyer:tT}=GT(),sC=L0(),YH=h4(),tC=WA(),{createDeferredPromise:LH}=s_(),JH=I6(),XH=globalThis.Blob||lC.Blob,eC=typeof XH<"u"?function(T){return T instanceof XH}:function(T){return!1},_O=globalThis.AbortController||I("abort-controller").AbortController,{FunctionPrototypeCall:HH}=F_();class QT extends sC{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}}KH.exports=function _(T,A){if(oC(T))return T;if(tX(T))return sT({readable:T});if(eX(T))return sT({writable:T});if(aC(T))return sT({writable:!1,readable:!1});if(_H(T))return sT({readable:YH.fromWeb(T)});if(TH(T))return sT({writable:tC.fromWeb(T)});if(typeof T==="function"){let{value:L,write:J,final:X,destroy:H}=TO(T);if(sX(L))return JH(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=HH(Z,L,($)=>{if($!=null)throw new EH("nully","body",$)},($)=>{tT(Y,$)});return Y=new QT({objectMode:!0,readable:!1,write:J,final($){X(async()=>{try{await K,d6.nextTick($,null)}catch(G){d6.nextTick($,G)}})},destroy:H})}throw new EH("Iterable, AsyncIterable or AsyncFunction",A,L)}if(eC(T))return _(T.arrayBuffer());if(sX(T))return JH(QT,T,{objectMode:!0,writable:!1});if(_H(T===null||T===void 0?void 0:T.readable)&&TH(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?tX(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?eX(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 HH(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 rC(A,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],T)};function TO(_){let{promise:T,resolve:A}=LH(),E=new _O,L=E.signal;return{value:_(async function*(){while(!0){let X=T;T=null;let{chunk:H,done:Z,cb:Y}=await X;if(d6.nextTick(Y),Z)return;if(L.aborted)throw new ZH(void 0,{cause:L.reason});({promise:T,resolve:A}=LH()),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"?YH.wrap(_.readable):_.readable,A=_.writable,E=!!nC(T),L=!!iC(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)AH(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)AH(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 ZH;if(H=null,J=null,X=null,Z===null)G($);else Z=G,tT(A,$),tT(T,$)},Y}});var L0=W((Sf,WH)=>{var{ObjectDefineProperties:AO,ObjectGetOwnPropertyDescriptor:I0,ObjectKeys:EO,ObjectSetPrototypeOf:GH}=F_();WH.exports=m1;var l6=h4(),C1=WA();GH(m1.prototype,l6.prototype);GH(m1,l6);{let _=EO(C1.prototype);for(let T=0;T<_.length;T++){let A=_[T];if(!m1.prototype[A])m1.prototype[A]=C1.prototype[A]}}function m1(_){if(!(this instanceof m1))return new m1(_);if(l6.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}AO(m1.prototype,{writable:{__proto__:null,...I0(C1.prototype,"writable")},writableHighWaterMark:{__proto__:null,...I0(C1.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...I0(C1.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...I0(C1.prototype,"writableBuffer")},writableLength:{__proto__:null,...I0(C1.prototype,"writableLength")},writableFinished:{__proto__:null,...I0(C1.prototype,"writableFinished")},writableCorked:{__proto__:null,...I0(C1.prototype,"writableCorked")},writableEnded:{__proto__:null,...I0(C1.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...I0(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 c6;function UH(){if(c6===void 0)c6={};return c6}m1.fromWeb=function(_,T){return UH().newStreamDuplexFromReadableWritablePair(_,T)};m1.toWeb=function(_){return UH().newReadableWritablePairFromDuplex(_)};var p6;m1.from=function(_){if(!p6)p6=$H();return p6(_,"body")}});var a6=W((yf,QH)=>{var{ObjectSetPrototypeOf:NH,Symbol:LO}=F_();QH.exports=P0;var{ERR_METHOD_NOT_IMPLEMENTED:JO}=n_().codes,i6=L0(),{getHighWaterMark:XO}=S4();NH(P0.prototype,i6.prototype);NH(P0,i6);var g4=LO("kCallback");function P0(_){if(!(this instanceof P0))return new P0(_);let T=_?XO(this,_,"readableHighWaterMark",!0):null;if(T===0)_={..._,highWaterMark:null,readableHighWaterMark:T,writableHighWaterMark:_.writableHighWaterMark||0};if(i6.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",HO)}function n6(_){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 HO(){if(this._final!==n6)n6.call(this)}P0.prototype._final=n6;P0.prototype._transform=function(_,T,A){throw new JO("_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 r6=W((vf,VH)=>{var{ObjectSetPrototypeOf:MH}=F_();VH.exports=eT;var o6=a6();MH(eT.prototype,o6.prototype);MH(eT,o6);function eT(_){if(!(this instanceof eT))return new eT(_);o6.call(this,_)}eT.prototype._transform=function(_,T,A){A(null,_)}});var VA=W((hf,RH)=>{var m4=c0(),{ArrayIsArray:ZO,Promise:YO,SymbolAsyncIterator:KO,SymbolDispose:$O}=F_(),MA=q0(),{once:GO}=s_(),UO=GT(),zH=L0(),{aggregateTwoErrors:WO,codes:{ERR_INVALID_ARG_TYPE:JE,ERR_INVALID_RETURN_VALUE:s6,ERR_MISSING_ARGS:NO,ERR_STREAM_DESTROYED:QO,ERR_STREAM_PREMATURE_CLOSE:MO},AbortError:VO}=n_(),{validateFunction:zO,validateAbortSignal:FO}=pT(),{isIterable:MT,isReadable:t6,isReadableNodeStream:QA,isNodeStream:FH,isTransformStream:_4,isWebStream:CO,isReadableStream:e6,isReadableFinished:OO}=T0(),RO=globalThis.AbortController||I("abort-controller").AbortController,_E,TE,AE;function CH(_,T,A){let E=!1;_.on("close",()=>{E=!0});let L=MA(_,{readable:T,writable:A},(J)=>{E=!J});return{destroy:(J)=>{if(E)return;E=!0,UO.destroyer(_,J||new QO("pipe"))},cleanup:L}}function DO(_){return zO(_[_.length-1],"streams[stream.length - 1]"),_.pop()}function EE(_){if(MT(_))return _;else if(QA(_))return BO(_);throw new JE("val",["Readable","Iterable","AsyncIterable"],_)}async function*BO(_){if(!TE)TE=h4();yield*TE.prototype[KO].call(_)}async function NA(_,T,A,{end:E}){let L,J=null,X=(Y)=>{if(Y)L=Y;if(J){let K=J;J=null,K()}},H=()=>new YO((Y,K)=>{if(L)K(L);else J=()=>{if(L)K(L);else Y()}});T.on("drain",X);let Z=MA(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?WO(L,Y):Y)}finally{Z(),T.off("drain",X)}}async function LE(_,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 qO(..._){return OH(_,GO(DO(_)))}function OH(_,T,A){if(_.length===1&&ZO(_[0]))_=_[0];if(_.length<2)throw new NO("streams");let E=new RO,L=E.signal,J=A===null||A===void 0?void 0:A.signal,X=[];FO(J,"options.signal");function H(){V(new VO)}AE=AE||s_().addAbortListener;let Z;if(J)Z=AE(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[$O](),E.abort(),q){if(!Y)X.forEach((S)=>S());m4.nextTick(T,Y,K)}}let N;for(let R=0;R<_.length;R++){let q=_[R],f=R<_.length-1,S=R>0,g=f||(A===null||A===void 0?void 0:A.end)!==!1,l=R===_.length-1;if(FH(q)){let c=function(W_){if(W_&&W_.name!=="AbortError"&&W_.code!=="ERR_STREAM_PREMATURE_CLOSE")U(W_)};var F=c;if(g){let{destroy:W_,cleanup:p_}=CH(q,f,S);if($.push(W_),t6(q)&&l)X.push(p_)}if(q.on("error",c),t6(q)&&l)X.push(()=>{q.removeListener("error",c)})}if(R===0)if(typeof q==="function"){if(N=q({signal:L}),!MT(N))throw new s6("Iterable, AsyncIterable or Stream","source",N)}else if(MT(q)||QA(q)||_4(q))N=q;else N=zH.from(q);else if(typeof q==="function"){if(_4(N)){var z;N=EE((z=N)===null||z===void 0?void 0:z.readable)}else N=EE(N);if(N=q(N,{signal:L}),f){if(!MT(N,!0))throw new s6("AsyncIterable",`transform[${R-1}]`,N)}else{var Q;if(!_E)_E=r6();let c=new _E({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(g)c.end();m4.nextTick(U)},(C_)=>{c.destroy(C_),m4.nextTick(U,C_)});else if(MT(N,!0))G++,NA(N,c,U,{end:g});else if(e6(N)||_4(N)){let C_=N.readable||N;G++,NA(C_,c,U,{end:g})}else throw new s6("AsyncIterable or Promise","destination",N);N=c;let{destroy:p_,cleanup:q_}=CH(N,!1,!0);if($.push(p_),l)X.push(q_)}}else if(FH(q)){if(QA(N)){G+=2;let c=IO(N,q,U,{end:g});if(t6(q)&&l)X.push(c)}else if(_4(N)||e6(N)){let c=N.readable||N;G++,NA(c,q,U,{end:g})}else if(MT(N))G++,NA(N,q,U,{end:g});else throw new JE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else if(CO(q)){if(QA(N))G++,LE(EE(N),q,U,{end:g});else if(e6(N)||MT(N))G++,LE(N,q,U,{end:g});else if(_4(N))G++,LE(N.readable,q,U,{end:g});else throw new JE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else N=zH.from(q)}if(L!==null&&L!==void 0&&L.aborted||J!==null&&J!==void 0&&J.aborted)m4.nextTick(H);return N}function IO(_,T,A,{end:E}){let L=!1;if(T.on("close",()=>{if(!L)A(new MO)}),_.pipe(T,{end:!1}),E){let X=function(){L=!0,T.end()};var J=X;if(OO(_))m4.nextTick(X);else _.once("end",X)}else A();return MA(_,{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)}),MA(T,{readable:!1,writable:!0},A)}RH.exports={pipelineImpl:OH,pipeline:qO}});var HE=W((kf,jH)=>{var{pipeline:PO}=VA(),zA=L0(),{destroyer:jO}=GT(),{isNodeStream:FA,isReadable:DH,isWritable:BH,isWebStream:XE,isTransformStream:VT,isWritableStream:qH,isReadableStream:IH}=T0(),{AbortError:xO,codes:{ERR_INVALID_ARG_VALUE:PH,ERR_MISSING_ARGS:wO}}=n_(),SO=q0();jH.exports=function(...T){if(T.length===0)throw new wO("streams");if(T.length===1)return zA.from(T[0]);let A=[...T];if(typeof T[0]==="function")T[0]=zA.from(T[0]);if(typeof T[T.length-1]==="function"){let U=T.length-1;T[U]=zA.from(T[U])}for(let U=0;U<T.length;++U){if(!FA(T[U])&&!XE(T[U]))continue;if(U<T.length-1&&!(DH(T[U])||IH(T[U])||VT(T[U])))throw new PH(`streams[${U}]`,A[U],"must be readable");if(U>0&&!(BH(T[U])||qH(T[U])||VT(T[U])))throw new PH(`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=PO(T,Z),$=!!(BH(Y)||qH(Y)||VT(Y)),G=!!(DH(K)||IH(K)||VT(K));if(H=new zA({writableObjectMode:!!(Y!==null&&Y!==void 0&&Y.writableObjectMode),readableObjectMode:!!(K!==null&&K!==void 0&&K.readableObjectMode),writable:$,readable:G}),$){if(FA(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(XE(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;SO(U,()=>{if(L){let V=L;L=null,V()}})}if(G){if(FA(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(XE(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 xO;if(J=null,E=null,L=null,X===null)V(U);else if(X=V,FA(K))jO(K,U)},H}});var mH=W((XR,YE)=>{var yO=globalThis.AbortController||I("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:vO,ERR_INVALID_ARG_TYPE:u4,ERR_MISSING_ARGS:hO,ERR_OUT_OF_RANGE:kO},AbortError:J0}=n_(),{validateAbortSignal:zT,validateInteger:xH,validateObject:FT}=pT(),fO=F_().Symbol("kWeak"),bO=F_().Symbol("kResistStopPropagation"),{finished:gO}=q0(),mO=HE(),{addAbortSignalNoValidate:uO}=w4(),{isWritable:dO,isNodeStream:cO}=T0(),{deprecate:pO}=s_(),{ArrayPrototypePush:lO,Boolean:nO,MathFloor:wH,Number:iO,NumberIsNaN:aO,Promise:SH,PromiseReject:yH,PromiseResolve:oO,PromisePrototypeThen:vH,Symbol:kH}=F_(),CA=kH("kEmpty"),hH=kH("kEof");function rO(_,T){if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");if(cO(_)&&!dO(_))throw new vO("stream",_,"must be writable");let A=mO(this,_);if(T!==null&&T!==void 0&&T.signal)uO(T.signal,A);return A}function OA(_,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=wH(T.concurrency);let E=A-1;if((T===null||T===void 0?void 0:T.highWaterMark)!=null)E=wH(T.highWaterMark);return xH(A,"options.concurrency",1),xH(E,"options.highWaterMark",0),E+=A,async function*(){let J=s_().AbortSignalAny([T===null||T===void 0?void 0:T.signal].filter(nO)),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===CA)continue;Q=oO(Q)}catch(F){Q=yH(F)}if(G+=1,vH(Q,V,U),H.push(Q),Y)Y(),Y=null;if(!$&&(H.length>=E||G>=A))await new SH((F)=>{K=F})}H.push(hH)}catch(Q){let F=yH(Q);vH(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===hH)return;if(J.aborted)throw new J0;if(Q!==CA)yield Q;H.shift(),N()}await new SH((Q)=>{Y=Q})}}finally{if($=!0,K)K(),K=null}}.call(this)}function sO(_=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 fH(_,T=void 0){for await(let A of ZE.call(this,_,T))return!0;return!1}async function tO(_,T=void 0){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);return!await fH.call(this,async(...A)=>{return!await _(...A)},T)}async function eO(_,T){for await(let A of ZE.call(this,_,T))return A;return}async function _R(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){return await _(E,L),CA}for await(let E of OA.call(this,A,T));}function ZE(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){if(await _(E,L))return E;return CA}return OA.call(this,A,T)}class bH extends hO{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function TR(_,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 gO(this.destroy(Y)),Y}let J=new yO,X=J.signal;if(A!==null&&A!==void 0&&A.signal){let Y={once:!0,[fO]:this,[bO]:!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 bH}finally{J.abort()}return T}async function AR(_){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});lO(T,E)}return T}function ER(_,T){let A=OA.call(this,_,T);return async function*(){for await(let L of A)yield*L}.call(this)}function gH(_){if(_=iO(_),aO(_))return 0;if(_<0)throw new kO("number",">= 0",_);return _}function LR(_,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 _=gH(_),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 JR(_,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 _=gH(_),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)}XR.streamReturningOperators={asIndexedPairs:pO(sO,"readable.asIndexedPairs will be removed in a future version."),drop:LR,filter:ZE,flatMap:ER,map:OA,take:JR,compose:rO};XR.promiseReturningOperators={every:tO,forEach:_R,reduce:TR,toArray:AR,some:fH,find:eO}});var KE=W((ff,uH)=>{var{ArrayPrototypePop:YR,Promise:KR}=F_(),{isIterable:$R,isNodeStream:GR,isWebStream:UR}=T0(),{pipelineImpl:WR}=VA(),{finished:NR}=q0();$E();function QR(..._){return new KR((T,A)=>{let E,L,J=_[_.length-1];if(J&&typeof J==="object"&&!GR(J)&&!$R(J)&&!UR(J)){let X=YR(_);E=X.signal,L=X.end}WR(_,(X,H)=>{if(X)A(X);else T(H)},{signal:E,end:L})})}uH.exports={finished:NR,pipeline:QR}});var $E=W((bf,rH)=>{var{Buffer:MR}=I("buffer"),{ObjectDefineProperty:j0,ObjectKeys:pH,ReflectApply:lH}=F_(),{promisify:{custom:nH}}=s_(),{streamReturningOperators:dH,promiseReturningOperators:cH}=mH(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:iH}}=n_(),VR=HE(),{setDefaultHighWaterMark:zR,getDefaultHighWaterMark:FR}=S4(),{pipeline:aH}=VA(),{destroyer:CR}=GT(),oH=q0(),GE=KE(),d4=T0(),V_=rH.exports=TA().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 pH(dH)){let A=function(...E){if(new.target)throw iH();return V_.Readable.from(lH(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})}for(let _ of pH(cH)){let A=function(...E){if(new.target)throw iH();return lH(T,this,E)},T=cH[_];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=WA();V_.Duplex=L0();V_.Transform=a6();V_.PassThrough=r6();V_.pipeline=aH;var{addAbortSignal:OR}=w4();V_.addAbortSignal=OR;V_.finished=oH;V_.destroy=CR;V_.compose=VR;V_.setDefaultHighWaterMark=zR;V_.getDefaultHighWaterMark=FR;j0(V_,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return GE}});j0(aH,nH,{__proto__:null,enumerable:!0,get(){return GE.pipeline}});j0(oH,nH,{__proto__:null,enumerable:!0,get(){return GE.finished}});V_.Stream=V_;V_._isUint8Array=function(T){return T instanceof Uint8Array};V_._uint8ArrayToBuffer=function(T){return MR.from(T.buffer,T.byteOffset,T.byteLength)}});var n0=W((gf,__)=>{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 _=$E(),T=KE(),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 sH=W((Eb,UE)=>{if(typeof Object.create==="function")UE.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 UE.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 tH=W((Lb,WE)=>{try{if(RA=I("util"),typeof RA.inherits!=="function")throw"";WE.exports=RA.inherits}catch(_){WE.exports=sH()}var RA});var TZ=W((Jb,_Z)=>{var{Buffer:u1}=I("buffer"),eH=Symbol.for("BufferList");function H_(_){if(!(this instanceof H_))return new H_(_);H_._init.call(this,_)}H_._init=function(T){if(Object.defineProperty(this,eH,{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[eH]};_Z.exports=H_});var AZ=W((Xb,DA)=>{var NE=n0().Duplex,RR=tH(),c4=TZ();function a_(_){if(!(this instanceof a_))return new a_(_);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,_),NE.call(this)}RR(a_,NE);Object.assign(a_.prototype,c4.prototype);a_.prototype._new=function(T){return new a_(T)};a_.prototype._write=function(T,A,E){if(this._appendBuffer(T),typeof E==="function")E()};a_.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)};a_.prototype.end=function(T){if(NE.prototype.end.call(this,T),this._callback)this._callback(null,this.slice()),this._callback=null};a_.prototype._destroy=function(T,A){this._bufs.length=0,this.length=0,A(T)};a_.prototype._isBufferList=function(T){return T instanceof a_||T instanceof c4||a_.isBufferList(T)};a_.isBufferList=c4.isBufferList;DA.exports=a_;DA.exports.BufferListStream=a_;DA.exports.BufferList=c4});var JZ=W((Hb,LZ)=>{class EZ{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}LZ.exports=EZ});var QE=W((Zb,XZ)=>{var x=Zb,{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 ZZ=W((Yb,HZ)=>{var T4=1000,A4=T4*60,E4=A4*60,CT=E4*24,DR=CT*7,BR=CT*365.25;HZ.exports=function(_,T){T=T||{};var A=typeof _;if(A==="string"&&_.length>0)return qR(_);else if(A==="number"&&isFinite(_))return T.long?PR(_):IR(_);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(_))};function qR(_){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*BR;case"weeks":case"week":case"w":return A*DR;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 IR(_){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 PR(_){var T=Math.abs(_);if(T>=CT)return BA(_,T,CT,"day");if(T>=E4)return BA(_,T,E4,"hour");if(T>=A4)return BA(_,T,A4,"minute");if(T>=T4)return BA(_,T,T4,"second");return _+" ms"}function BA(_,T,A,E){var L=T>=A*1.5;return Math.round(_/A)+" "+E+(L?"s":"")}});var ME=W((Kb,YZ)=>{function jR(_){A.debug=A,A.default=A,A.coerce=Z,A.disable=X,A.enable=L,A.enabled=H,A.humanize=ZZ(),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,(S,g)=>{if(S==="%%")return"%";q++;let l=A.formatters[g];if(typeof l==="function"){let c=z[q];S=l.call(Q,c),z.splice(q,1),q--}return S}),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}YZ.exports=jR});var $Z=W((KZ,qA)=>{KZ.formatArgs=wR;KZ.save=SR;KZ.load=yR;KZ.useColors=xR;KZ.storage=vR();KZ.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`.")}})();KZ.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 xR(){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 wR(_){if(_[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+_[0]+(this.useColors?"%c ":" ")+"+"+qA.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)}KZ.log=console.debug||console.log||(()=>{});function SR(_){try{if(_)KZ.storage.setItem("debug",_);else KZ.storage.removeItem("debug")}catch(T){}}function yR(){let _;try{_=KZ.storage.getItem("debug")||KZ.storage.getItem("DEBUG")}catch(T){}if(!_&&typeof process<"u"&&"env"in process)_=process.env.DEBUG;return _}function vR(){try{return localStorage}catch(_){}}qA.exports=ME()(KZ);var{formatters:hR}=qA.exports;hR.j=function(_){try{return JSON.stringify(_)}catch(T){return"[UnexpectedJSONParseError]: "+T.message}}});var NZ=W((UZ,PA)=>{var cR=I("tty"),IA=I("util");UZ.init=rR;UZ.log=iR;UZ.formatArgs=lR;UZ.save=aR;UZ.load=oR;UZ.useColors=pR;UZ.destroy=IA.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");UZ.colors=[6,2,3,4,5,1];try{let _=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(_&&(_.stderr||_).level>=2)UZ.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(_){}UZ.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 pR(){return"colors"in UZ.inspectOpts?Boolean(UZ.inspectOpts.colors):cR.isatty(process.stderr.fd)}function lR(_){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+"+PA.exports.humanize(this.diff)+"\x1B[0m")}else _[0]=lR()+T+" "+_[0]}function lR(){if(UZ.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function nR(..._){return process.stderr.write(IA.formatWithOptions(UZ.inspectOpts,..._)+`
6
- `)}function iR(_){if(_)process.env.DEBUG=_;else delete process.env.DEBUG}function aR(){return process.env.DEBUG}function oR(_){_.inspectOpts={};let T=Object.keys(UZ.inspectOpts);for(let A=0;A<T.length;A++)_.inspectOpts[T[A]]=UZ.inspectOpts[T[A]]}PA.exports=NE()(UZ);var{formatters:GZ}=PA.exports;GZ.o=function(_){return this.inspectOpts.colors=this.useColors,IA.inspect(_,this.inspectOpts).split(`
7
- `).map((T)=>T.trim()).join(" ")};GZ.O=function(_){return this.inspectOpts.colors=this.useColors,IA.inspect(_,this.inspectOpts)}});var d1=W((Kb,QE)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)QE.exports=$Z();else QE.exports=NZ()});var VZ=W(($b,MZ)=>{var ED=AZ(),{EventEmitter:LD}=I("events"),QZ=JZ(),E_=WE(),n=d1()("mqtt-packet:parser");class jA extends LD{constructor(){super();this.parser=this.constructor.parser}static parser(_){if(!(this instanceof jA))return new jA().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 QZ,this.error=null,this._list=ED(),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 QZ,this._pos=0,!0}_emitError(_){n("_emitError",_),this.error=_,this.emit("error",_)}}MZ.exports=jA});var OZ=W((Gb,CZ)=>{var{Buffer:l4}=I("buffer"),zZ={},JD=l4.isBuffer(l4.from([1,2]).subarray(0,1));function FZ(_){let T=l4.allocUnsafe(2);return T.writeUInt8(_>>8,0),T.writeUInt8(_&255,1),T}function XD(){for(let _=0;_<65536;_++)zZ[_]=FZ(_)}function HD(_){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 JD?L.subarray(0,E):L.slice(0,E)}function ZD(_){let T=l4.allocUnsafe(4);return T.writeUInt32BE(_,0),T}CZ.exports={cache:zZ,generateCache:XD,generateNumber:FZ,genBufVariableByteInt:HD,generate4ByteBuffer:ZD}});var RZ=W((Ub,ME)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)ME.exports={nextTick:YD};else ME.exports=process;function YD(_,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 FE=W((Wb,wZ)=>{var i=WE(),{Buffer:p}=I("buffer"),KD=p.allocUnsafe(0),$D=p.from([0]),n4=OZ(),GD=RZ().nextTick,R1=d1()("mqtt-packet:writeToStream"),xA=n4.cache,UD=n4.generateNumber,WD=n4.generateCache,VE=n4.genBufVariableByteInt,ND=n4.generate4ByteBuffer,t_=zE,wA=!0;function jZ(_,T,A){if(R1("generate called"),T.cork)T.cork(),GD(QD,T);if(wA)wA=!1,WD();switch(R1("generate: packet.cmd: %s",_.cmd),_.cmd){case"connect":return MD(_,T,A);case"connack":return VD(_,T,A);case"publish":return zD(_,T,A);case"puback":case"pubrec":case"pubrel":case"pubcomp":return FD(_,T,A);case"subscribe":return CD(_,T,A);case"suback":return OD(_,T,A);case"unsubscribe":return RD(_,T,A);case"unsuback":return DD(_,T,A);case"pingreq":case"pingresp":return BD(_,T,A);case"disconnect":return qD(_,T,A);case"auth":return ID(_,T,A);default:return T.destroy(Error("Unknown command")),!1}}Object.defineProperty(jZ,"cacheNumbers",{get(){return t_===zE},set(_){if(_){if(!xA||Object.keys(xA).length===0)wA=!0;t_=zE}else wA=!1,t_=PD}});function QD(_){_.uncork()}function MD(_,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(PZ(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(PZ($))U+=xZ($)+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 VD(_,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:$D),T.write(p.from([J])),Z!=null)Z.write();return!0}function zD(_,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||KD,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,xZ(H)),T.write(H),J>0)t_(T,Y);if(G!=null)G.write();return R1("publish: payload: %o",Z),T.write(Z)}function FD(_,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 CD(_,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 OD(_,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 RD(_,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 DD(_,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 BD(_,T,A){return T.write(i.EMPTY[_.cmd])}function qD(_,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 ID(_,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 DZ={};function D1(_,T){if(T>i.VARBYTEINT_MAX)return _.destroy(Error(`Invalid variable byte integer: ${T}`)),!1;let A=DZ[T];if(!A){if(A=VE(T),T<16384)DZ[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 BZ(_,T,A){RT(_,T),RT(_,A)}function zE(_,T){return R1("writeNumberCached: number: %d",T),R1("writeNumberCached: %o",xA[T]),_.write(xA[T])}function PD(_,T){let A=UD(T);return R1("writeNumberGenerated: %o",A),_.write(A)}function jD(_,T){let A=ND(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(){IZ(_,{},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(VE(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(VE(A))+A,write(){IZ(_,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 qZ(_,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]])),jD(_,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]])),BZ(_,L.toString(),X.toString())});else _.write(p.from([i.properties[T]])),BZ(_,L.toString(),J.toString())});break}default:return _.destroy(Error(`Invalid property ${T} value: ${A}`)),!1}}function IZ(_,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++)qZ(_,E,L[J]);else qZ(_,E,L)}}function xZ(_){if(!_)return 0;else if(_ instanceof p)return _.length;else return p.byteLength(_)}function PZ(_){return typeof _==="string"||_ instanceof p}wZ.exports=jZ});var hZ=W((Nb,vZ)=>{var xD=FE(),{EventEmitter:wD}=I("events"),{Buffer:SZ}=I("buffer");function SD(_,T){let A=new yZ;return xD(_,A,T),A.concat()}class yZ extends wD{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]=SZ.byteLength(A[L]);_+=T[L]}let J=SZ.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",_)}}vZ.exports=SD});var SA=W((yD)=>{yD.parser=VZ().parser;yD.generate=hZ();yD.writeToStream=FE()});var bZ=W((Mb,fZ)=>{fZ.exports=kZ;function kZ(_,T){if(_&&T)return kZ(_)(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 uZ=W((Vb,CE)=>{var gZ=bZ();CE.exports=gZ(yA);CE.exports.strict=gZ(mZ);yA.proto=yA(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return yA(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return mZ(this)},configurable:!0})});function yA(_){var T=function(){if(T.called)return T.value;return T.called=!0,T.value=_.apply(this,arguments)};return T.called=!1,T}function mZ(_){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 pZ=W((zb,cZ)=>{var fD=uZ(),bD=function(){},gD=global.Bare?queueMicrotask:process.nextTick.bind(process),mD=function(_){return _.setHeader&&typeof _.abort==="function"},uD=function(_){return _.stdio&&Array.isArray(_.stdio)&&_.stdio.length===3},dZ=function(_,T,A){if(typeof T==="function")return dZ(_,null,T);if(!T)T={};A=fD(A||bD);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(){gD(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(mD(_))if(_.on("complete",Y),_.on("abort",U),_.req)N();else _.on("request",N);else if(X&&!E)_.on("end",Z),_.on("close",Z);if(uD(_))_.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)}};cZ.exports=dZ});var x0=W((Fb,lZ)=>{var dD=SA();function cD(_,T,A){let E=null;if(_.connecting||_.connected)try{if(!dD.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,_)}lZ.exports=cD});var OE=W((Cb,aZ)=>{var nZ=uT(),pD=I("util");function iZ(_,T){if(nZ.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}pD.inherits(iZ,nZ);aZ.exports=iZ});var sZ=W((Ob,rZ)=>{var lD=f8(),oZ=[];function nD(_,T){if(Array.isArray(_))T=_,_=null;var A=lD(iD);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 iD(){this.list=oZ,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=oZ,_.count=0,_.release(_)}}}rZ.exports=nD});var DT=W((Rb,tZ)=>{var{Transform:aD,Writable:oD}=I("stream");function rD(_,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 sD(_){return new aD({objectMode:!0,transform:_})}function tD(_){return new oD({objectMode:!0,writev:function(T,A){_(T.map((E)=>E.chunk),A)}})}tZ.exports={validateTopic:rD,through:sD,bulk:tD,$SYS_PREFIX:"$SYS/"}});var vA=W((Db,L2)=>{var _2=sZ(),T2=uT(),{through:eD}=DT(),{validateTopic:_B,$SYS_PREFIX:TB}=DT(),AB=x0(),EB=_2([A2,GB,E2]),LB=_2([A2,E2]);function JB(_,T){this.cmd="suback",this.messageId=_.messageId,this.granted=T}function eZ(_,T,A,E,L){this.qos=_,this.func=T,this.rh=A,this.rap=E,this.nl=L}function XB(_,T,A,E){this.client=_,this.packet=T,this.actions=A?LB:EB,this.finish=E,this.subState=[]}function HB(_,T,A,E,L,J){this.client=_,this.packet=T,this.granted=A,this.rh=E,this.rap=L,this.nl=J}function ZB(_){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 YB(_,T,A,E){T.subscriptions=T.subscriptions.length===1?T.subscriptions:ZB(T.subscriptions),_.broker._parallel(new XB(_,T,A,E),KB,T.subscriptions,A?E:WB)}function KB(_,T){let A=new HB(this.client,this.packet,_.qos,_.rh,_.rap,_.nl);this.subState.push(A),this.actions.call(A,_,T)}function A2(_,T){let A=_B(_.topic,"SUBSCRIBE");if(A)return T(A);let E=this.client;E.broker.authorizeSubscribe(E,_,T)}function $B(_){return function(A,E){if(A.topic.charCodeAt(0)===36)E();else _(A,E)}}function GB(_,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 E2(_,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 T2(G,E),G.nl=Z,!H)G.retain=!1;K(G,U)},UB(L))Y=$B(Y);if(A.closed||A.broker.closed)return;if(!A.subscriptions[L])A.subscriptions[L]=new eZ(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 eZ(J,Y,X,H,Z),E.subscribe(L,Y,T);else T()}function UB(_){let T=_.charCodeAt(0);return T===43||T===35}function WB(_){let T=this.finish;if(_)return T(_);let A=this.packet,E=this.client;if(A.messageId!==void 0)AB(E,new JB(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:TB+L.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:E.id,subs:J}),"utf8")},NB),X.length>0)L.persistence.createRetainedStreamCombi(X).pipe(eD(function(K,$,G){K=new T2({cmd:K.cmd,qos:K.qos,topic:K.topic,payload:K.payload,retain:!0},L),K.brokerId=null,E.deliverQoS(K,G)}))}function NB(){}L2.exports=YB});var DE=W((Bb,J2)=>{var QB=x0(),{validateTopic:MB,$SYS_PREFIX:VB}=DT();function zB(_){this.cmd="unsuback",this.messageId=_.messageId}function FB(_,T,A){this.client=_,this.packet=T,this.finish=A}function CB(_,T,A){let E=_.broker,L=T.unsubscriptions,J;for(let X=0;X<L.length;X++)if(J=MB(L[X],"UNSUBSCRIBE"),J)return A(J);if(T.messageId!==void 0){if(_.clean)return RE(_,T,A);E.persistence.removeSubscriptions(_,L,function(X){if(X)return A(X);RE(_,T,A)})}else RE(_,T,A)}function RE(_,T,A){_.broker._parallel(new FB(_,T,A),OB,T.unsubscriptions,RB)}function OB(_,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 RB(_){let T=this.client;if(_){T.emit("error",_);return}let A=this.packet,E=this.finish;if(A.messageId!==void 0)QB(T,new zB(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:VB+T.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:T.id,subs:A.unsubscriptions}),"utf8")},DB)}function DB(){}J2.exports=CB});var H2=W((qb,X2)=>{X2.exports=function(){let T=process.hrtime();return Math.floor(T[0]*1000+T[1]/1e6)}});var Y2=W((Ib,Z2)=>{Z2.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var G2=W((Pb,qE)=>{var hA=H2(),{clearTimeout:K2,setTimeout:$2}=Y2();class BE{constructor(_,T,A){let E=this;this._started=hA(),this._rescheduled=0,this._scheduled=T,this._args=A,this._triggered=!1,this._timerWrapper=()=>{if(E._rescheduled>0)E._scheduled=E._rescheduled-(hA()-E._started),E._schedule(E._scheduled);else E._triggered=!0,_.apply(null,E._args)},this._timer=$2(this._timerWrapper,T)}reschedule(_){if(!_)_=this._scheduled;let T=hA();if(T+_-(this._started+this._scheduled)<0)K2(this._timer),this._schedule(_);else if(!this._triggered)this._started=T,this._rescheduled=_;else this._schedule(_)}_schedule(_){this._triggered=!1,this._started=hA(),this._rescheduled=0,this._scheduled=_,this._timer=$2(this._timerWrapper,_)}clear(){K2(this._timer)}}function BB(){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 BE(arguments[0],arguments[1],_)}qE.exports=BB;qE.exports.Retimer=BE});var IE=W((U2)=>{Object.defineProperty(U2,"__esModule",{value:!0});U2.default=PB;var qB=IB(I("crypto"));function IB(_){return _&&_.__esModule?_:{default:_}}var fA=new Uint8Array(256),kA=fA.length;function PB(){if(kA>fA.length-16)qB.default.randomFillSync(fA),kA=0;return fA.slice(kA,kA+=16)}});var Q2=W((W2)=>{Object.defineProperty(W2,"__esModule",{value:!0});W2.default=void 0;var xB=/^(?:[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;W2.default=xB});var o4=W((M2)=>{Object.defineProperty(M2,"__esModule",{value:!0});M2.default=void 0;var wB=SB(Q2());function SB(_){return _&&_.__esModule?_:{default:_}}function yB(_){return typeof _==="string"&&wB.default.test(_)}var vB=yB;M2.default=vB});var r4=W((z2)=>{Object.defineProperty(z2,"__esModule",{value:!0});z2.default=void 0;var hB=kB(o4());function kB(_){return _&&_.__esModule?_:{default:_}}var m_=[];for(let _=0;_<256;++_)m_.push((_+256).toString(16).substr(1));function fB(_,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,hB.default)(A))throw TypeError("Stringified UUID is invalid");return A}var bB=fB;z2.default=bB});var B2=W((R2)=>{Object.defineProperty(R2,"__esModule",{value:!0});R2.default=void 0;var gB=O2(IE()),mB=O2(r4());function O2(_){return _&&_.__esModule?_:{default:_}}var C2,PE,jE=0,xE=0;function uB(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let J=_.node||C2,X=_.clockseq!==void 0?_.clockseq:PE;if(J==null||X==null){let G=_.random||(_.rng||gB.default)();if(J==null)J=C2=[G[0]|1,G[1],G[2],G[3],G[4],G[5]];if(X==null)X=PE=(G[6]<<8|G[7])&16383}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:xE+1,Y=H-jE+(Z-xE)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>jE)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");jE=H,xE=Z,PE=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,mB.default)(L)}var dB=uB;R2.default=dB});var wE=W((q2)=>{Object.defineProperty(q2,"__esModule",{value:!0});q2.default=void 0;var cB=pB(o4());function pB(_){return _&&_.__esModule?_:{default:_}}function lB(_){if(!(0,cB.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 nB=lB;q2.default=nB});var SE=W((w2)=>{Object.defineProperty(w2,"__esModule",{value:!0});w2.default=rB;w2.URL=w2.DNS=void 0;var iB=P2(r4()),aB=P2(wE());function P2(_){return _&&_.__esModule?_:{default:_}}function oB(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var j2="6ba7b810-9dad-11d1-80b4-00c04fd430c8";w2.DNS=j2;var x2="6ba7b811-9dad-11d1-80b4-00c04fd430c8";w2.URL=x2;function rB(_,T,A){function E(L,J,X,H){if(typeof L==="string")L=oB(L);if(typeof J==="string")J=(0,aB.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,iB.default)(Z)}try{E.name=_}catch(L){}return E.DNS=j2,E.URL=x2,E}});var h2=W((y2)=>{Object.defineProperty(y2,"__esModule",{value:!0});y2.default=void 0;var eB=_q(I("crypto"));function _q(_){return _&&_.__esModule?_:{default:_}}function Tq(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return eB.default.createHash("md5").update(_).digest()}var Aq=Tq;y2.default=Aq});var g2=W((f2)=>{Object.defineProperty(f2,"__esModule",{value:!0});f2.default=void 0;var Eq=k2(SE()),Lq=k2(h2());function k2(_){return _&&_.__esModule?_:{default:_}}var Jq=(0,Eq.default)("v3",48,Lq.default),Xq=Jq;f2.default=Xq});var c2=W((u2)=>{Object.defineProperty(u2,"__esModule",{value:!0});u2.default=void 0;var Hq=m2(IE()),Zq=m2(r4());function m2(_){return _&&_.__esModule?_:{default:_}}function Yq(_,T,A){_=_||{};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,Zq.default)(E)}var Kq=Yq;u2.default=Kq});var n2=W((p2)=>{Object.defineProperty(p2,"__esModule",{value:!0});p2.default=void 0;var $q=Gq(I("crypto"));function Gq(_){return _&&_.__esModule?_:{default:_}}function Uq(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return $q.default.createHash("sha1").update(_).digest()}var Wq=Uq;p2.default=Wq});var r2=W((a2)=>{Object.defineProperty(a2,"__esModule",{value:!0});a2.default=void 0;var Nq=i2(SE()),Qq=i2(n2());function i2(_){return _&&_.__esModule?_:{default:_}}var Mq=(0,Nq.default)("v5",80,Qq.default),Vq=Mq;a2.default=Vq});var e2=W((s2)=>{Object.defineProperty(s2,"__esModule",{value:!0});s2.default=void 0;var zq="00000000-0000-0000-0000-000000000000";s2.default=zq});var AY=W((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});_Y.default=void 0;var Fq=Cq(o4());function Cq(_){return _&&_.__esModule?_:{default:_}}function Oq(_){if(!(0,Fq.default)(_))throw TypeError("Invalid UUID");return parseInt(_.substr(14,1),16)}var Rq=Oq;_Y.default=Rq});var EY=W((c1)=>{Object.defineProperty(c1,"__esModule",{value:!0});Object.defineProperty(c1,"v1",{enumerable:!0,get:function(){return Dq.default}});Object.defineProperty(c1,"v3",{enumerable:!0,get:function(){return Bq.default}});Object.defineProperty(c1,"v4",{enumerable:!0,get:function(){return qq.default}});Object.defineProperty(c1,"v5",{enumerable:!0,get:function(){return Iq.default}});Object.defineProperty(c1,"NIL",{enumerable:!0,get:function(){return Pq.default}});Object.defineProperty(c1,"version",{enumerable:!0,get:function(){return jq.default}});Object.defineProperty(c1,"validate",{enumerable:!0,get:function(){return xq.default}});Object.defineProperty(c1,"stringify",{enumerable:!0,get:function(){return wq.default}});Object.defineProperty(c1,"parse",{enumerable:!0,get:function(){return Sq.default}});var Dq=w0(B2()),Bq=w0(g2()),qq=w0(c2()),Iq=w0(r2()),Pq=w0(e2()),jq=w0(AY()),xq=w0(o4()),wq=w0(r4()),Sq=w0(wE());function w0(_){return _&&_.__esModule?_:{default:_}}});var XY=W((pb,JY)=>{var yq=EY(),LY=I("crypto");JY.exports=typeof LY.randomUUID==="function"?LY.randomUUID:yq.v4});var YY=W((lb,ZY)=>{var yE=[],HY={};for(o0=0;o0<256;o0++)yE[o0]=(o0+256).toString(16).substr(1),HY[yE[o0]]=o0;var o0;function vq(_,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++]=HY[J]});while(L<16)T[E+L++]=0;return T}function hq(_,T){var A=T||0,E=yE;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++]]}ZY.exports={parse:vq,unparse:hq}});var $Y=W((cq)=>{cq.byteLength=fq;cq.toByteArray=gq;cq.fromByteArray=dq;var X0=[],B1=[],kq=typeof Uint8Array<"u"?Uint8Array:Array,vE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(r0=0,hE=vE.length;r0<hE;++r0)X0[r0]=vE[r0],B1[vE.charCodeAt(r0)]=r0;var r0,hE;B1[45]=62;B1[95]=63;function KY(_){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 fq(_){var T=KY(_),A=T[0],E=T[1];return(A+E)*3/4-E}function bq(_,T,A){return(T+A)*3/4-A}function gq(_){var T,A=KY(_),E=A[0],L=A[1],J=new kq(bq(_,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 mq(_){return X0[_>>18&63]+X0[_>>12&63]+X0[_>>6&63]+X0[_&63]}function uq(_,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(mq(E));return L.join("")}function dq(_){var T,A=_.length,E=A%3,L=[],J=16383;for(var X=0,H=A-E;X<H;X+=J)L.push(uq(_,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 GY=W((iq)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */iq.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)};iq.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 qY=W((zI)=>{/*!
5
+ `+J),_.push(L+"m+"+PA.exports.humanize(this.diff)+"\x1B[0m")}else _[0]=nR()+T+" "+_[0]}function nR(){if(UZ.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function iR(..._){return process.stderr.write(IA.formatWithOptions(UZ.inspectOpts,..._)+`
6
+ `)}function aR(_){if(_)process.env.DEBUG=_;else delete process.env.DEBUG}function oR(){return process.env.DEBUG}function rR(_){_.inspectOpts={};let T=Object.keys(UZ.inspectOpts);for(let A=0;A<T.length;A++)_.inspectOpts[T[A]]=UZ.inspectOpts[T[A]]}PA.exports=ME()(UZ);var{formatters:GZ}=PA.exports;GZ.o=function(_){return this.inspectOpts.colors=this.useColors,IA.inspect(_,this.inspectOpts).split(`
7
+ `).map((T)=>T.trim()).join(" ")};GZ.O=function(_){return this.inspectOpts.colors=this.useColors,IA.inspect(_,this.inspectOpts)}});var d1=W((Ub,VE)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)VE.exports=$Z();else VE.exports=NZ()});var VZ=W((Wb,MZ)=>{var LD=AZ(),{EventEmitter:JD}=I("events"),QZ=JZ(),E_=QE(),n=d1()("mqtt-packet:parser");class jA extends JD{constructor(){super();this.parser=this.constructor.parser}static parser(_){if(!(this instanceof jA))return new jA().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 QZ,this.error=null,this._list=LD(),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 QZ,this._pos=0,!0}_emitError(_){n("_emitError",_),this.error=_,this.emit("error",_)}}MZ.exports=jA});var OZ=W((Nb,CZ)=>{var{Buffer:l4}=I("buffer"),zZ={},XD=l4.isBuffer(l4.from([1,2]).subarray(0,1));function FZ(_){let T=l4.allocUnsafe(2);return T.writeUInt8(_>>8,0),T.writeUInt8(_&255,1),T}function HD(){for(let _=0;_<65536;_++)zZ[_]=FZ(_)}function ZD(_){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 XD?L.subarray(0,E):L.slice(0,E)}function YD(_){let T=l4.allocUnsafe(4);return T.writeUInt32BE(_,0),T}CZ.exports={cache:zZ,generateCache:HD,generateNumber:FZ,genBufVariableByteInt:ZD,generate4ByteBuffer:YD}});var RZ=W((Qb,zE)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)zE.exports={nextTick:KD};else zE.exports=process;function KD(_,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 OE=W((Mb,wZ)=>{var i=QE(),{Buffer:p}=I("buffer"),$D=p.allocUnsafe(0),GD=p.from([0]),n4=OZ(),UD=RZ().nextTick,O1=d1()("mqtt-packet:writeToStream"),xA=n4.cache,WD=n4.generateNumber,ND=n4.generateCache,FE=n4.genBufVariableByteInt,QD=n4.generate4ByteBuffer,t_=CE,wA=!0;function jZ(_,T,A){if(O1("generate called"),T.cork)T.cork(),UD(MD,T);if(wA)wA=!1,ND();switch(O1("generate: packet.cmd: %s",_.cmd),_.cmd){case"connect":return VD(_,T,A);case"connack":return zD(_,T,A);case"publish":return FD(_,T,A);case"puback":case"pubrec":case"pubrel":case"pubcomp":return CD(_,T,A);case"subscribe":return OD(_,T,A);case"suback":return RD(_,T,A);case"unsubscribe":return DD(_,T,A);case"unsuback":return BD(_,T,A);case"pingreq":case"pingresp":return qD(_,T,A);case"disconnect":return ID(_,T,A);case"auth":return PD(_,T,A);default:return T.destroy(Error("Unknown command")),!1}}Object.defineProperty(jZ,"cacheNumbers",{get(){return t_===CE},set(_){if(_){if(!xA||Object.keys(xA).length===0)wA=!0;t_=CE}else wA=!1,t_=jD}});function MD(_){_.uncork()}function VD(_,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(PZ(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(PZ($))U+=xZ($)+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|=$!=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 zD(_,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:GD),T.write(p.from([J])),Z!=null)Z.write();return!0}function FD(_,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||$D,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]),R1(T,$),t_(T,xZ(H)),T.write(H),J>0)t_(T,Y);if(G!=null)G.write();return O1("publish: payload: %o",Z),T.write(Z)}function CD(_,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(R1(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 OD(_,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 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(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 $=!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 RD(_,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 DD(_,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]),R1(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 BD(_,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]),R1(T,$),t_(T,J),G!==null)G.write();if(E===5)T.write(p.from(H));return!0}function qD(_,T,A){return T.write(i.EMPTY[_.cmd])}function ID(_,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 PD(_,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 DZ={};function R1(_,T){if(T>i.VARBYTEINT_MAX)return _.destroy(Error(`Invalid variable byte integer: ${T}`)),!1;let A=DZ[T];if(!A){if(A=FE(T),T<16384)DZ[T]=A}return O1("writeVarByteInt: writing to stream: %o",A),_.write(A)}function RT(_,T){let A=p.byteLength(T);return t_(_,A),O1("writeString: %s",T),_.write(T,"utf8")}function BZ(_,T,A){RT(_,T),RT(_,A)}function CE(_,T){return O1("writeNumberCached: number: %d",T),O1("writeNumberCached: %o",xA[T]),_.write(xA[T])}function jD(_,T){let A=WD(T);return O1("writeNumberGenerated: %o",A),_.write(A)}function xD(_,T){let A=QD(T);return O1("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(){IZ(_,{},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(FE(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(FE(A))+A,write(){IZ(_,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 qZ(_,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]])),xD(_,A);break}case"var":{_.write(p.from([i.properties[T]])),R1(_,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]])),BZ(_,L.toString(),X.toString())});else _.write(p.from([i.properties[T]])),BZ(_,L.toString(),J.toString())});break}default:return _.destroy(Error(`Invalid property ${T} value: ${A}`)),!1}}function IZ(_,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++)qZ(_,E,L[J]);else qZ(_,E,L)}}function xZ(_){if(!_)return 0;else if(_ instanceof p)return _.length;else return p.byteLength(_)}function PZ(_){return typeof _==="string"||_ instanceof p}wZ.exports=jZ});var hZ=W((Vb,vZ)=>{var wD=OE(),{EventEmitter:SD}=I("events"),{Buffer:SZ}=I("buffer");function yD(_,T){let A=new yZ;return wD(_,A,T),A.concat()}class yZ extends SD{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]=SZ.byteLength(A[L]);_+=T[L]}let J=SZ.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",_)}}vZ.exports=yD});var SA=W((vD)=>{vD.parser=VZ().parser;vD.generate=hZ();vD.writeToStream=OE()});var bZ=W((Fb,fZ)=>{fZ.exports=kZ;function kZ(_,T){if(_&&T)return kZ(_)(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 uZ=W((Cb,RE)=>{var gZ=bZ();RE.exports=gZ(yA);RE.exports.strict=gZ(mZ);yA.proto=yA(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return yA(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return mZ(this)},configurable:!0})});function yA(_){var T=function(){if(T.called)return T.value;return T.called=!0,T.value=_.apply(this,arguments)};return T.called=!1,T}function mZ(_){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 pZ=W((Ob,cZ)=>{var bD=uZ(),gD=function(){},mD=global.Bare?queueMicrotask:process.nextTick.bind(process),uD=function(_){return _.setHeader&&typeof _.abort==="function"},dD=function(_){return _.stdio&&Array.isArray(_.stdio)&&_.stdio.length===3},dZ=function(_,T,A){if(typeof T==="function")return dZ(_,null,T);if(!T)T={};A=bD(A||gD);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(){mD(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(uD(_))if(_.on("complete",Y),_.on("abort",U),_.req)N();else _.on("request",N);else if(X&&!E)_.on("end",Z),_.on("close",Z);if(dD(_))_.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)}};cZ.exports=dZ});var x0=W((Rb,lZ)=>{var cD=SA();function pD(_,T,A){let E=null;if(_.connecting||_.connected)try{if(!cD.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,_)}lZ.exports=pD});var DE=W((Db,aZ)=>{var nZ=uT(),lD=I("util");function iZ(_,T){if(nZ.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}lD.inherits(iZ,nZ);aZ.exports=iZ});var sZ=W((Bb,rZ)=>{var nD=f8(),oZ=[];function iD(_,T){if(Array.isArray(_))T=_,_=null;var A=nD(aD);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 aD(){this.list=oZ,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=oZ,_.count=0,_.release(_)}}}rZ.exports=iD});var DT=W((qb,tZ)=>{var{Transform:oD,Writable:rD}=I("stream");function sD(_,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 tD(_){return new oD({objectMode:!0,transform:_})}function eD(_){return new rD({objectMode:!0,writev:function(T,A){_(T.map((E)=>E.chunk),A)}})}tZ.exports={validateTopic:sD,through:tD,bulk:eD,$SYS_PREFIX:"$SYS/"}});var vA=W((Ib,L2)=>{var _2=sZ(),T2=uT(),{through:_B}=DT(),{validateTopic:TB,$SYS_PREFIX:AB}=DT(),EB=x0(),LB=_2([A2,UB,E2]),JB=_2([A2,E2]);function XB(_,T){this.cmd="suback",this.messageId=_.messageId,this.granted=T}function eZ(_,T,A,E,L){this.qos=_,this.func=T,this.rh=A,this.rap=E,this.nl=L}function HB(_,T,A,E){this.client=_,this.packet=T,this.actions=A?JB:LB,this.finish=E,this.subState=[]}function ZB(_,T,A,E,L,J){this.client=_,this.packet=T,this.granted=A,this.rh=E,this.rap=L,this.nl=J}function YB(_){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 KB(_,T,A,E){T.subscriptions=T.subscriptions.length===1?T.subscriptions:YB(T.subscriptions),_.broker._parallel(new HB(_,T,A,E),$B,T.subscriptions,A?E:NB)}function $B(_,T){let A=new ZB(this.client,this.packet,_.qos,_.rh,_.rap,_.nl);this.subState.push(A),this.actions.call(A,_,T)}function A2(_,T){let A=TB(_.topic,"SUBSCRIBE");if(A)return T(A);let E=this.client;E.broker.authorizeSubscribe(E,_,T)}function GB(_){return function(A,E){if(A.topic.charCodeAt(0)===36)E();else _(A,E)}}function UB(_,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 E2(_,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 T2(G,E),G.nl=Z,!H)G.retain=!1;K(G,U)},WB(L))Y=GB(Y);if(A.closed||A.broker.closed)return;if(!A.subscriptions[L])A.subscriptions[L]=new eZ(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 eZ(J,Y,X,H,Z),E.subscribe(L,Y,T);else T()}function WB(_){let T=_.charCodeAt(0);return T===43||T===35}function NB(_){let T=this.finish;if(_)return T(_);let A=this.packet,E=this.client;if(A.messageId!==void 0)EB(E,new XB(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:AB+L.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:E.id,subs:J}),"utf8")},QB),X.length>0)L.persistence.createRetainedStreamCombi(X).pipe(_B(function(K,$,G){K=new T2({cmd:K.cmd,qos:K.qos,topic:K.topic,payload:K.payload,retain:!0},L),K.brokerId=null,E.deliverQoS(K,G)}))}function QB(){}L2.exports=KB});var qE=W((Pb,J2)=>{var MB=x0(),{validateTopic:VB,$SYS_PREFIX:zB}=DT();function FB(_){this.cmd="unsuback",this.messageId=_.messageId}function CB(_,T,A){this.client=_,this.packet=T,this.finish=A}function OB(_,T,A){let E=_.broker,L=T.unsubscriptions,J;for(let X=0;X<L.length;X++)if(J=VB(L[X],"UNSUBSCRIBE"),J)return A(J);if(T.messageId!==void 0){if(_.clean)return BE(_,T,A);E.persistence.removeSubscriptions(_,L,function(X){if(X)return A(X);BE(_,T,A)})}else BE(_,T,A)}function BE(_,T,A){_.broker._parallel(new CB(_,T,A),RB,T.unsubscriptions,DB)}function RB(_,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 DB(_){let T=this.client;if(_){T.emit("error",_);return}let A=this.packet,E=this.finish;if(A.messageId!==void 0)MB(T,new FB(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:zB+T.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:T.id,subs:A.unsubscriptions}),"utf8")},BB)}function BB(){}J2.exports=OB});var H2=W((jb,X2)=>{X2.exports=function(){let T=process.hrtime();return Math.floor(T[0]*1000+T[1]/1e6)}});var Y2=W((xb,Z2)=>{Z2.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var G2=W((wb,PE)=>{var hA=H2(),{clearTimeout:K2,setTimeout:$2}=Y2();class IE{constructor(_,T,A){let E=this;this._started=hA(),this._rescheduled=0,this._scheduled=T,this._args=A,this._triggered=!1,this._timerWrapper=()=>{if(E._rescheduled>0)E._scheduled=E._rescheduled-(hA()-E._started),E._schedule(E._scheduled);else E._triggered=!0,_.apply(null,E._args)},this._timer=$2(this._timerWrapper,T)}reschedule(_){if(!_)_=this._scheduled;let T=hA();if(T+_-(this._started+this._scheduled)<0)K2(this._timer),this._schedule(_);else if(!this._triggered)this._started=T,this._rescheduled=_;else this._schedule(_)}_schedule(_){this._triggered=!1,this._started=hA(),this._rescheduled=0,this._scheduled=_,this._timer=$2(this._timerWrapper,_)}clear(){K2(this._timer)}}function qB(){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 IE(arguments[0],arguments[1],_)}PE.exports=qB;PE.exports.Retimer=IE});var jE=W((U2)=>{Object.defineProperty(U2,"__esModule",{value:!0});U2.default=jB;var IB=PB(I("crypto"));function PB(_){return _&&_.__esModule?_:{default:_}}var fA=new Uint8Array(256),kA=fA.length;function jB(){if(kA>fA.length-16)IB.default.randomFillSync(fA),kA=0;return fA.slice(kA,kA+=16)}});var Q2=W((W2)=>{Object.defineProperty(W2,"__esModule",{value:!0});W2.default=void 0;var wB=/^(?:[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;W2.default=wB});var o4=W((M2)=>{Object.defineProperty(M2,"__esModule",{value:!0});M2.default=void 0;var SB=yB(Q2());function yB(_){return _&&_.__esModule?_:{default:_}}function vB(_){return typeof _==="string"&&SB.default.test(_)}var hB=vB;M2.default=hB});var r4=W((z2)=>{Object.defineProperty(z2,"__esModule",{value:!0});z2.default=void 0;var kB=fB(o4());function fB(_){return _&&_.__esModule?_:{default:_}}var m_=[];for(let _=0;_<256;++_)m_.push((_+256).toString(16).substr(1));function bB(_,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,kB.default)(A))throw TypeError("Stringified UUID is invalid");return A}var gB=bB;z2.default=gB});var B2=W((R2)=>{Object.defineProperty(R2,"__esModule",{value:!0});R2.default=void 0;var mB=O2(jE()),uB=O2(r4());function O2(_){return _&&_.__esModule?_:{default:_}}var C2,xE,wE=0,SE=0;function dB(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let J=_.node||C2,X=_.clockseq!==void 0?_.clockseq:xE;if(J==null||X==null){let G=_.random||(_.rng||mB.default)();if(J==null)J=C2=[G[0]|1,G[1],G[2],G[3],G[4],G[5]];if(X==null)X=xE=(G[6]<<8|G[7])&16383}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:SE+1,Y=H-wE+(Z-SE)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>wE)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");wE=H,SE=Z,xE=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,uB.default)(L)}var cB=dB;R2.default=cB});var yE=W((q2)=>{Object.defineProperty(q2,"__esModule",{value:!0});q2.default=void 0;var pB=lB(o4());function lB(_){return _&&_.__esModule?_:{default:_}}function nB(_){if(!(0,pB.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 iB=nB;q2.default=iB});var vE=W((w2)=>{Object.defineProperty(w2,"__esModule",{value:!0});w2.default=sB;w2.URL=w2.DNS=void 0;var aB=P2(r4()),oB=P2(yE());function P2(_){return _&&_.__esModule?_:{default:_}}function rB(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var j2="6ba7b810-9dad-11d1-80b4-00c04fd430c8";w2.DNS=j2;var x2="6ba7b811-9dad-11d1-80b4-00c04fd430c8";w2.URL=x2;function sB(_,T,A){function E(L,J,X,H){if(typeof L==="string")L=rB(L);if(typeof J==="string")J=(0,oB.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,aB.default)(Z)}try{E.name=_}catch(L){}return E.DNS=j2,E.URL=x2,E}});var h2=W((y2)=>{Object.defineProperty(y2,"__esModule",{value:!0});y2.default=void 0;var _q=Tq(I("crypto"));function Tq(_){return _&&_.__esModule?_:{default:_}}function Aq(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return _q.default.createHash("md5").update(_).digest()}var Eq=Aq;y2.default=Eq});var g2=W((f2)=>{Object.defineProperty(f2,"__esModule",{value:!0});f2.default=void 0;var Lq=k2(vE()),Jq=k2(h2());function k2(_){return _&&_.__esModule?_:{default:_}}var Xq=(0,Lq.default)("v3",48,Jq.default),Hq=Xq;f2.default=Hq});var c2=W((u2)=>{Object.defineProperty(u2,"__esModule",{value:!0});u2.default=void 0;var Zq=m2(jE()),Yq=m2(r4());function m2(_){return _&&_.__esModule?_:{default:_}}function Kq(_,T,A){_=_||{};let E=_.random||(_.rng||Zq.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,Yq.default)(E)}var $q=Kq;u2.default=$q});var n2=W((p2)=>{Object.defineProperty(p2,"__esModule",{value:!0});p2.default=void 0;var Gq=Uq(I("crypto"));function Uq(_){return _&&_.__esModule?_:{default:_}}function Wq(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return Gq.default.createHash("sha1").update(_).digest()}var Nq=Wq;p2.default=Nq});var r2=W((a2)=>{Object.defineProperty(a2,"__esModule",{value:!0});a2.default=void 0;var Qq=i2(vE()),Mq=i2(n2());function i2(_){return _&&_.__esModule?_:{default:_}}var Vq=(0,Qq.default)("v5",80,Mq.default),zq=Vq;a2.default=zq});var e2=W((s2)=>{Object.defineProperty(s2,"__esModule",{value:!0});s2.default=void 0;var Fq="00000000-0000-0000-0000-000000000000";s2.default=Fq});var AY=W((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});_Y.default=void 0;var Cq=Oq(o4());function Oq(_){return _&&_.__esModule?_:{default:_}}function Rq(_){if(!(0,Cq.default)(_))throw TypeError("Invalid UUID");return parseInt(_.substr(14,1),16)}var Dq=Rq;_Y.default=Dq});var EY=W((c1)=>{Object.defineProperty(c1,"__esModule",{value:!0});Object.defineProperty(c1,"v1",{enumerable:!0,get:function(){return Bq.default}});Object.defineProperty(c1,"v3",{enumerable:!0,get:function(){return qq.default}});Object.defineProperty(c1,"v4",{enumerable:!0,get:function(){return Iq.default}});Object.defineProperty(c1,"v5",{enumerable:!0,get:function(){return Pq.default}});Object.defineProperty(c1,"NIL",{enumerable:!0,get:function(){return jq.default}});Object.defineProperty(c1,"version",{enumerable:!0,get:function(){return xq.default}});Object.defineProperty(c1,"validate",{enumerable:!0,get:function(){return wq.default}});Object.defineProperty(c1,"stringify",{enumerable:!0,get:function(){return Sq.default}});Object.defineProperty(c1,"parse",{enumerable:!0,get:function(){return yq.default}});var Bq=w0(B2()),qq=w0(g2()),Iq=w0(c2()),Pq=w0(r2()),jq=w0(e2()),xq=w0(AY()),wq=w0(o4()),Sq=w0(r4()),yq=w0(yE());function w0(_){return _&&_.__esModule?_:{default:_}}});var XY=W((ib,JY)=>{var vq=EY(),LY=I("crypto");JY.exports=typeof LY.randomUUID==="function"?LY.randomUUID:vq.v4});var YY=W((ab,ZY)=>{var hE=[],HY={};for(o0=0;o0<256;o0++)hE[o0]=(o0+256).toString(16).substr(1),HY[hE[o0]]=o0;var o0;function hq(_,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++]=HY[J]});while(L<16)T[E+L++]=0;return T}function kq(_,T){var A=T||0,E=hE;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++]]}ZY.exports={parse:hq,unparse:kq}});var $Y=W((pq)=>{pq.byteLength=bq;pq.toByteArray=mq;pq.fromByteArray=cq;var X0=[],D1=[],fq=typeof Uint8Array<"u"?Uint8Array:Array,kE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(r0=0,fE=kE.length;r0<fE;++r0)X0[r0]=kE[r0],D1[kE.charCodeAt(r0)]=r0;var r0,fE;D1[45]=62;D1[95]=63;function KY(_){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 bq(_){var T=KY(_),A=T[0],E=T[1];return(A+E)*3/4-E}function gq(_,T,A){return(T+A)*3/4-A}function mq(_){var T,A=KY(_),E=A[0],L=A[1],J=new fq(gq(_,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 uq(_){return X0[_>>18&63]+X0[_>>12&63]+X0[_>>6&63]+X0[_&63]}function dq(_,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(uq(E));return L.join("")}function cq(_){var T,A=_.length,E=A%3,L=[],J=16383;for(var X=0,H=A-E;X<H;X+=J)L.push(dq(_,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 GY=W((aq)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */aq.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)};aq.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 qY=W((FI)=>{/*!
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 kE=$Y(),J4=GY(),UY=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;zI.Buffer=B;zI.SlowBuffer=TI;zI.INSPECT_MAX_BYTES=50;var bA=2147483647;zI.kMaxLength=bA;B.TYPED_ARRAY_SUPPORT=rq();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 rq(){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(_>bA)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 mE(_)}return QY(_,T,A)}B.poolSize=8192;function QY(_,T,A){if(typeof _==="string")return tq(_,T);if(ArrayBuffer.isView(_))return eq(_);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 bE(_,T,A);if(typeof SharedArrayBuffer<"u"&&(H0(_,SharedArrayBuffer)||_&&H0(_.buffer,SharedArrayBuffer)))return bE(_,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=_I(_);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 QY(_,T,A)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function MY(_){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 sq(_,T,A){if(MY(_),_<=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 sq(_,T,A)};function mE(_){return MY(_),S0(_<0?0:uE(_)|0)}B.allocUnsafe=function(_){return mE(_)};B.allocUnsafeSlow=function(_){return mE(_)};function tq(_,T){if(typeof T!=="string"||T==="")T="utf8";if(!B.isEncoding(T))throw TypeError("Unknown encoding: "+T);var A=VY(_,T)|0,E=S0(A),L=E.write(_,T);if(L!==A)E=E.slice(0,L);return E}function fE(_){var T=_.length<0?0:uE(_.length)|0,A=S0(T);for(var E=0;E<T;E+=1)A[E]=_[E]&255;return A}function eq(_){if(H0(_,Uint8Array)){var T=new Uint8Array(_);return bE(T.buffer,T.byteOffset,T.byteLength)}return fE(_)}function bE(_,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 _I(_){if(B.isBuffer(_)){var T=uE(_.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"||dE(_.length))return S0(0);return fE(_)}if(_.type==="Buffer"&&Array.isArray(_.data))return fE(_.data)}function uE(_){if(_>=bA)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+bA.toString(16)+" bytes");return _|0}function TI(_){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 VY(_,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 gE(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return DY(_).length;default:if(L)return E?-1:gE(_).length;T=(""+T).toLowerCase(),L=!0}}B.byteLength=VY;function AI(_,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 GI(this,T,A);case"utf8":case"utf-8":return FY(this,T,A);case"ascii":return KI(this,T,A);case"latin1":case"binary":return $I(this,T,A);case"base64":return ZI(this,T,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return UI(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 FY(this,0,T);return AI.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=zI.INSPECT_MAX_BYTES;if(T=this.toString("hex",0,A).replace(/(.{2})/g,"$1 ").trim(),this.length>A)T+=" ... ";return"<Buffer "+T+">"};if(UY)B.prototype[UY]=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 zY(_,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,dE(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 WY(_,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 WY(_,[T],A,E,L)}throw TypeError("val must be string, number or Buffer")}function WY(_,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 zY(this,T,A,E,!0)};B.prototype.lastIndexOf=function(T,A,E){return zY(this,T,A,E,!1)};function EI(_,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(dE(H))return X;_[A+X]=H}return X}function LI(_,T,A,E){return gA(gE(T,_.length-A),_,A,E)}function JI(_,T,A,E){return gA(QI(T),_,A,E)}function XI(_,T,A,E){return gA(DY(T),_,A,E)}function HI(_,T,A,E){return gA(MI(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 EI(this,T,A,E);case"utf8":case"utf-8":return LI(this,T,A,E);case"ascii":case"latin1":case"binary":return JI(this,T,A,E);case"base64":return XI(this,T,A,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return HI(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 ZI(_,T,A){if(T===0&&A===_.length)return kE.fromByteArray(_);else return kE.fromByteArray(_.slice(T,A))}function FY(_,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 YI(E)}var NY=4096;function YI(_){var T=_.length;if(T<=NY)return String.fromCharCode.apply(String,_);var A="",E=0;while(E<T)A+=String.fromCharCode.apply(String,_.slice(E,E+=NY));return A}function KI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]&127);return E}function $I(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]);return E}function GI(_,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+=VI[_[J]];return L}function UI(_,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 CY(_,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 OY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)CY(_,T,A,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return J4.write(_,T,A,E,23,4),A+4}B.prototype.writeFloatLE=function(T,A,E){return OY(this,T,A,!0,E)};B.prototype.writeFloatBE=function(T,A,E){return OY(this,T,A,!1,E)};function RY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)CY(_,T,A,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return J4.write(_,T,A,E,52,8),A+8}B.prototype.writeDoubleLE=function(T,A,E){return RY(this,T,A,!0,E)};B.prototype.writeDoubleBE=function(T,A,E){return RY(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 WI=/[^+/0-9A-Za-z-_]/g;function NI(_){if(_=_.split("=")[0],_=_.trim().replace(WI,""),_.length<2)return"";while(_.length%4!==0)_=_+"=";return _}function gE(_,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 QI(_){var T=[];for(var A=0;A<_.length;++A)T.push(_.charCodeAt(A)&255);return T}function MI(_,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 DY(_){return kE.toByteArray(NI(_))}function gA(_,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 dE(_){return _!==_}var VI=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 wY=W((ob,cE)=>{var IY=XY(),jY=YY(),mA=RI();function RI(){let _=I("buffer");return _&&_.Buffer?_.Buffer:qY().Buffer}var DI=mA.from("==","base64");function BI(_){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=IY(),X.decode=xY;let L=PY(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=IY(),L=PY(X.uuid,A),J=0;if(T)H=L+`0000000000${J}`.slice(-10);else H=L+J;return J=J+1|0,H}}function PY(_,T){let A=mA.concat([mA.from(jY.parse(_)),DI]).toString("base64");if(T)return A.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"-");return A.replace(/=+$/,"/")}function xY(_,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:jY.unparse(mA.from(L+"==","base64")),count:J}}cE.exports=BI;cE.exports.decode=xY});var vY=W((rb,yY)=>{var qI=G2(),{pipeline:II}=I("stream"),SY=x0(),PI=OE(),{through:jI}=DT(),xI=vA(),wI=wY()();function SI(_){this.cmd="connack",this.returnCode=_.returnCode,this.sessionPresent=_.sessionPresent}function yI(_,T){this.client=_,this.packet=T}var vI=[fI,bI,gI,uI,dI,cI,lE,pI],pE=["","unacceptable protocol version","identifier rejected","Server unavailable","bad user name or password","not authorized","keep alive limit exceeded"];function hI(_,T,A){clearTimeout(_._connectTimer),_._connectTimer=null,_.connecting=!0,_.broker.preConnect(_,T,E);function E(L,J){if(!L&&J===!0)setImmediate(kI,_,T,A);else _.connecting=!1,A(L)}}function kI(_,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(pE[L]);J.errorCode=L,lE({client:_,returnCode:L,sessionPresent:!1},A.bind(this,J));return}_.id=E||"aedes_"+wI(),_.clean=T.clean,_.version=T.protocolVersion,_._will=T.will,_.broker._series(new yI(_,T),vI,{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 fI(_,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=pE[_.returnCode]}else _.returnCode=5,L=Error(pE[_.returnCode]);L.errorCode=_.returnCode,_.client=A,lE(_,A.close.bind(A,T.bind(this,L)))}}function bI(_,T){if(this.packet.keepalive>0){let A=this.client;A._keepaliveInterval=this.packet.keepalive*1500+1,A._keepaliveTimer=qI(function(){A.broker.emit("keepaliveTimeout",A),A.emit("error",Error("keep alive timeout"))},A._keepaliveInterval)}T()}function gI(_,T){let A=this.client;if(!this.packet.clean){A.broker.persistence.subscriptionsByClient({id:A.id,done:T,arg:_},mI);return}_.sessionPresent=!1,A.broker.persistence.cleanSubscriptions(A,T)}function mI(_,T,A){if(_)return A.done(_);A.arg.subs=T,A.done()}function uI(_,T){if(_.subs){xI(this.client,{subscriptions:_.subs},!0,T),_.sessionPresent=!!_.subs;return}_.sessionPresent=!1,T()}function dI(_,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 cI(_,T){let A=this.client;A.broker.registerClient(A),T()}function lE(_,T){let A=_.client||this.client,E=new SI(_);SY(A,E,function(L){if(!L)A.broker.emit("connackSent",E,A),A.connackSent=!0;T(L)})}function pI(_,T){let A=this.client,E=A.broker.persistence,L=E.outgoingStream(A);A.resume(),II(L,jI(function(X,H,Z){let Y=new PI(X,A);Y.writeCallback=(K,$)=>Z(K),E.outgoingUpdate(A,Y,lI)}),T)}function lI(_,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 SY(T,A,E)}yY.exports=hI});var fY=W((sb,kY)=>{var hY=x0();function nI(_){this.cmd="puback",this.messageId=_.messageId}function iI(_){this.cmd="pubrec",this.messageId=_.messageId}var aI=[sI,rI];function oI(_,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(_,aI,T,A)}function rI(_,T){let A=this;switch(_.qos){case 2:A.broker.persistence.incomingStorePacket(A,_,function(E){if(E)return T(E);hY(A,new iI(_),T)});break;case 1:hY(A,new nI(_),function(E){if(E)return T(E);A.broker.publish(_,A,T)});break;case 0:A.broker.publish(_,A,T);break;default:}}function sI(_,T){this.broker.authorizePublish(this,_,T)}kY.exports=oI});var gY=W((tb,bY)=>{function tI(_,T,A){_.broker.persistence.outgoingClearMessageId(_,T,function(L,J){_.broker.emit("ack",J,_),A(L)})}bY.exports=tI});var uY=W((eb,mY)=>{var eI=x0();function _P(_,T){this.client=_,this.packet=T}function TP(_){this.cmd="pubcomp",this.messageId=_.messageId}var AP=[LP,JP,XP,HP];function EP(_,T,A){_.broker._series(new _P(_,T),AP,{},A)}function LP(_,T){this.client.broker.persistence.incomingGetPacket(this.client,this.packet,E);function E(L,J){_.packet=J,T(L)}}function JP(_,T){this.client.broker.publish(_.packet,this.client,T)}function XP(_,T){eI(this.client,new TP(_.packet),T)}function HP(_,T){this.client.broker.persistence.incomingDelPacket(this.client,_.packet,T)}mY.exports=EP});var pY=W((_g,cY)=>{var dY=x0();function ZP(_){this.cmd="pubrel",this.messageId=_.messageId}function YP(_,T,A){let E=new ZP(T);if(_.clean){dY(_,E,A);return}_.broker.persistence.outgoingUpdate(_,E,L);function L(J){if(J)A(J);else dY(_,E,A)}}cY.exports=YP});var nY=W((Tg,lY)=>{var KP=x0(),$P={cmd:"pingresp"};function GP(_,T,A){_.broker.emit("ping",T,_),KP(_,$P,A)}lY.exports=GP});var oY=W((Ag,aY)=>{var UP=vY(),WP=vA(),NP=DE(),QP=fY(),MP=gY(),VP=uY(),zP=pY(),FP=nY();function CP(_,T,A){if(T.cmd==="connect"){if(_.connecting||_.connected){iY(_.conn,T,A);return}UP(_,T,A);return}if(!_.connecting&&!_.connected){iY(_.conn,T,A);return}switch(T.cmd){case"publish":QP(_,T,A);break;case"subscribe":WP(_,T,!1,A);break;case"unsubscribe":NP(_,T,A);break;case"pubcomp":case"puback":MP(_,T,A);break;case"pubrel":VP(_,T,A);break;case"pubrec":zP(_,T,A);break;case"pingreq":FP(_,T,A);break;case"disconnect":_._disconnected=!0,_.conn.destroy(),A();return;default:_.conn.destroy(),A();return}if(_._keepaliveInterval>0)_._keepaliveTimer.reschedule(_._keepaliveInterval)}function iY(_,T,A){_.destroy();let E=Error("Invalid protocol");E.info=T,A(E)}aY.exports=CP});var EK=W((Eg,AK)=>{var OP=SA(),RP=I("events"),DP=I("util"),BP=pZ(),sY=uT(),tY=x0(),qP=OE(),IP=vA(),eY=DE(),_K=oY(),{pipeline:PP}=I("stream"),{through:jP}=DT();AK.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=OP.parser(),this._parser.client=this,this._parser._queue=[],this._parser.on("packet",SP),this.once("connected",yP);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",TK),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=BP(this.conn,this.close.bind(this));let J=(X)=>{if(X.clientId===E.id&&X.nl)return;return xP(E,X)&&E.broker.authorizeForward(E,X)};this.deliver0=function(H,Z){let Y=J(H);if(Y)setImmediate(()=>{let K=new sY(Y,_);K.qos=0,tY(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 qP(Y,E),$=E.subscriptions[K.topic];if($&&($.qos||0)<K.qos)K.qos=$.qos;if(K.writeCallback=Z,E.clean||K.retain)rY(null,E,K);else _.persistence.outgoingUpdate(E,K,rY)});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 xP(_,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 rY(_,T,A){if(_)T.emit("error",_),A.writeCallback();else tY(T,A,function(E){if(E)T.emit("error",E);A.writeCallback()})}function wP(_){_.callback()}function TK(_){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(wP),this.broker.emit(this.id?"clientError":"connectionError",this,_),this.close()}DP.inherits(Z0,RP);Z0.prototype._onError=TK;Z0.prototype.publish=function(_,T){let A=new sY(_,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:_}}IP(this,_,!1,T)};Z0.prototype.unsubscribe=function(_,T){if(!_.unsubscriptions){if(!Array.isArray(_))_=[_];_={unsubscriptions:_}}eY(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,eY(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 SP(_){let T=this.client;if(T._parsingBatch++,T.connackSent||T._parsingBatch===1)_K(T,_,T._nextBatch);else if(this._queue.length<T.broker.queueLimit)this._queue.push(_);else this.emit("error",Error("Client queue limit reached"))}function yP(){let _=this._parser._queue;if(_){for(let T=0,A=_.length;T<A;T++)_K(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)}PP(A.outgoingStream(T),jP(E),_)};function X4(){}});var LK=W((Lg,vP)=>{vP.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 YK=W((Jg,ZK)=>{var hP=I("events"),kP=I("util"),fP=g5(),bP=y9(),{v4:gP}=f7(),mP=f8(),{pipeline:uP}=I("stream"),dP=uT(),cP=n7(),pP=e7(),lP=EK(),{$SYS_PREFIX:Y0,bulk:nP}=DT();ZK.exports=Z1.createBroker=Z1;var iP={concurrency:100,heartbeatInterval:60000,connectTimeout:30000,decodeProtocol:null,preConnect:_j,authenticate:Tj,authorizePublish:Aj,authorizeSubscribe:Ej,authorizeForward:Lj,published:Jj,trustProxy:!1,trustedProxies:[],queueLimit:42,maxClientsIdLength:23,keepaliveLimit:0};function Z1(_){let T=this;if(!(this instanceof Z1))return new Z1(_);_=Object.assign({},iP,_),this.id=_.id||gP(),this.counter=0,this.queueLimit=_.queueLimit,this.connectTimeout=_.connectTimeout,this.keepaliveLimit=_.keepaliveLimit,this.maxClientsIdLength=_.maxClientsIdLength,this.mq=_.mq||pP({concurrency:_.concurrency,matchEmptyLevels:!0}),this.handle=function(K,$){return K.setMaxListeners(_.concurrency*2),new lP(T,K,$)},this.persistence=_.persistence||cP(),this.persistence.broker=this,this._parallel=fP(),this._series=bP(),this._enqueuers=mP(oP),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),uP(T.persistence.streamWill(T.brokers),nP(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}kP.inherits(Z1,hP);function JK(_,T){if(_.retain)this.broker.persistence.storeRetained(_,T);else T()}function XK(_,T){if(this.client)_.clientId=this.client.id;this.broker.mq.emit(_,T)}function aP(_,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 oP(){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(rP);let{packet:J,complete:X}=_;_.packet=null,_.complete=null,_.topic=null,L.persistence.outgoingEnqueueCombi(E,J,X),L._enqueuers.release(_)}}function rP(_){let T=_.topic.charCodeAt(0);return T!==43&&T!==35}function HK(_,T){this.broker.published(this.packet,this.client,T),this.broker.emit("publish",this.packet,this.client)}var sP=[JK,XK,HK],tP=[JK,aP,XK,HK];Z1.prototype.publish=function(_,T,A){if(typeof T==="function")A=T,T=null;let E=new dP(_,this),L=E.qos>0?tP:sP;this._series(new Xj(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 eP(_,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,eP,Object.keys(this.clients),A);function A(){T.emit("closed"),T.mq.close(_)}};Z1.prototype.version=LK().version;function _j(_,T,A){A(null,!0)}function Tj(_,T,A,E){E(null,!0)}function Aj(_,T,A){if(T.topic.startsWith(Y0))return A(Error(Y0+" topic is reserved"));A(null)}function Ej(_,T,A){A(null,T)}function Lj(_,T){return T}function Jj(_,T,A){A(null)}function Xj(_,T,A){this.broker=_,this.client=T,this.packet=A}function s4(){}});var UK=W((Wg,GK)=>{GK.exports=Zj;function H4(_){if(_ instanceof Buffer)return Buffer.from(_);return new _.constructor(_.buffer.slice(),_.byteOffset,_.length)}function Zj(_){if(_=_||{},_.circles)return Yj(_);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 Yj(_){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 NK=W((Ng,WK)=>{WK.exports=UK()()});var VK=W((MK)=>{Object.defineProperty(MK,"__esModule",{value:!0});MK.validateTopic=QK;MK.validateTopics=Kj;function QK(_){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 Kj(_){if(_.length===0)return"empty_topic_list";for(let T=0;T<_.length;T++)if(!QK(_[T]))return _[T];return null}});var nE=W((FK)=>{Object.defineProperty(FK,"__esModule",{value:!0});var Uj=n0(),Wj={objectMode:!0},Nj={clean:!0};class zK{options;_inflights;constructor(_){this.options=_||{},this.options={...Nj,..._},this._inflights=new Map}put(_,T){if(this._inflights.set(_.messageId,_),T)T();return this}createStream(){let _=new Uj.Readable(Wj),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(_)_()}}FK.default=zK});var RK=W((OK)=>{Object.defineProperty(OK,"__esModule",{value:!0});var CK=[0,16,128,131,135,144,145,151,153],Mj=(_,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(CK.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(CK.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}};OK.default=Mj});var DK=W((zg,zj)=>{zj.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((BK)=>{Object.defineProperty(BK,"__esModule",{value:!0});BK.MQTTJS_VERSION=BK.nextTick=BK.ErrorWithSubackPacket=BK.ErrorWithReasonCode=void 0;BK.applyMixin=Fj;class iE extends Error{code;constructor(_,T){super(_);this.code=T,Object.setPrototypeOf(this,iE.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}BK.ErrorWithReasonCode=iE;class aE extends Error{packet;constructor(_,T){super(_);this.packet=T,Object.setPrototypeOf(this,aE.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}BK.ErrorWithSubackPacket=aE;function Fj(_,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))}BK.nextTick=typeof process?.nextTick==="function"?process.nextTick:(_)=>{setTimeout(_,0)};BK.MQTTJS_VERSION=DK().version});var e4=W((PK)=>{Object.defineProperty(PK,"__esModule",{value:!0});PK.ReasonCodes=void 0;var IK=qT();PK.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 Bj=(_,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 IK.ErrorWithReasonCode(`Publish error: ${PK.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 IK.ErrorWithReasonCode(`Publish error: ${PK.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: ${PK.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")};PK.default=Bj});var wK=W((xK)=>{Object.defineProperty(xK,"__esModule",{value:!0});var jK=qT(),Ij=e4(),Pj=(_,T)=>{let{options:A}=_,E=A.protocolVersion,L=E===5?T.reasonCode:T.returnCode;if(E!==5){let J=new jK.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 jK.ErrorWithReasonCode(`Connection refused: ${Ij.ReasonCodes[L]}`,L);_.emit("error",H)}})};xK.default=Pj});var bK=W((kK)=>{Object.defineProperty(kK,"__esModule",{value:!0});kK.LRUCache=void 0;var Z4=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,yK=new Set,oE=typeof process==="object"&&!!process?process:{},vK=(_,T,A,E)=>{typeof oE.emitWarning==="function"?oE.emitWarning(_,T,A,E):console.error(`[${A}] ${T}: ${_}`)},dA=globalThis.AbortController,SK=globalThis.AbortSignal;if(typeof dA>"u"){SK=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(E,L){this._onabort.push(L)}},dA=class{constructor(){T()}signal=new SK;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 _=oE.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",T=()=>{if(!_)return;_=!1,vK("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 xj=(_)=>!yK.has(_),Rg=Symbol("type"),s0=(_)=>_&&_===Math.floor(_)&&_>0&&isFinite(_),hK=(_)=>!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=hK(_);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 rE{#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:b}=_;if(T!==0&&!s0(T))throw TypeError("max option must be a nonnegative integer");let k=T?hK(T):Array;if(!k)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 k(T),this.#Q=new k(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=!!b,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(xj("LRU_CACHE_UNBOUNDED"))yK.add("LRU_CACHE_UNBOUNDED"),vK("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",rE)}}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 dA,{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 dA}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 b=this.#V(R);if(!N&&!b){if(z)z.fetch="hit";if(this.#w(R),E)this.#j(R);if(z)this.#I(z,R);return q}let k=this.#v(_,R,F,V),l=k.__staleWhileFetching!==void 0&&A;if(z){if(z.fetch=b?"stale":"refresh",l&&b)z.returnedStale=!0}return l?k.__staleWhileFetching:k.__returned=k}}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)}}}kK.LRUCache=rE});var K0=W((uK)=>{Object.defineProperty(uK,"t",{value:!0});uK.ContainerIterator=uK.Container=uK.Base=void 0;class gK{constructor(_=0){this.iteratorType=_}equals(_){return this.o===_.o}}uK.ContainerIterator=gK;class sE{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}}uK.Base=sE;class mK extends sE{}uK.Container=mK});var nK=W((pK)=>{Object.defineProperty(pK,"t",{value:!0});pK.default=void 0;var yj=K0();class cK extends yj.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 vj=cK;pK.default=vj});var rK=W((aK)=>{Object.defineProperty(aK,"t",{value:!0});aK.default=void 0;var hj=K0();class iK extends hj.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 kj=iK;aK.default=kj});var _3=W((tK)=>{Object.defineProperty(tK,"t",{value:!0});tK.default=void 0;var fj=K0();class sK extends fj.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 bj=sK;tK.default=bj});var cA=W((A3)=>{Object.defineProperty(A3,"t",{value:!0});A3.default=void 0;var gj=K0();class T3 extends gj.Container{}var mj=T3;A3.default=mj});var $0=W((L3)=>{Object.defineProperty(L3,"t",{value:!0});L3.throwIteratorAccessError=uj;function uj(){throw RangeError("Iterator access denied!")}});var tE=W((X3)=>{Object.defineProperty(X3,"t",{value:!0});X3.RandomIterator=void 0;var cj=K0(),pA=$0();class J3 extends cj.ContainerIterator{constructor(_,T){super(T);if(this.o=_,this.iteratorType===0)this.pre=function(){if(this.o===0)(0,pA.throwIteratorAccessError)();return this.o-=1,this},this.next=function(){if(this.o===this.container.size())(0,pA.throwIteratorAccessError)();return this.o+=1,this};else this.pre=function(){if(this.o===this.container.size()-1)(0,pA.throwIteratorAccessError)();return this.o+=1,this},this.next=function(){if(this.o===-1)(0,pA.throwIteratorAccessError)();return this.o-=1,this}}get pointer(){return this.container.getElementByPos(this.o)}set pointer(_){this.container.setElementByPos(this.o,_)}}X3.RandomIterator=J3});var $3=W((Y3)=>{Object.defineProperty(Y3,"t",{value:!0});Y3.default=void 0;var pj=nj(cA()),lj=tE();function nj(_){return _&&_.t?_:{default:_}}class IT extends lj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new IT(this.o,this.container,this.iteratorType)}}class Z3 extends pj.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 ij=Z3;Y3.default=ij});var N3=W((U3)=>{Object.defineProperty(U3,"t",{value:!0});U3.default=void 0;var aj=rj(cA()),oj=K0(),PT=$0();function rj(_){return _&&_.t?_:{default:_}}class jT extends oj.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 G3 extends aj.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 sj=G3;U3.default=sj});var z3=W((M3)=>{Object.defineProperty(M3,"t",{value:!0});M3.default=void 0;var tj=_x(cA()),ej=tE();function _x(_){return _&&_.t?_:{default:_}}class xT extends ej.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new xT(this.o,this.container,this.iteratorType)}}class Q3 extends tj.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 Tx=Q3;M3.default=Tx});var R3=W((C3)=>{Object.defineProperty(C3,"t",{value:!0});C3.TreeNodeEnableIndex=C3.TreeNode=void 0;class eE{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}}C3.TreeNode=eE;class F3 extends eE{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}}C3.TreeNodeEnableIndex=F3});var _L=W((I3)=>{Object.defineProperty(I3,"t",{value:!0});I3.default=void 0;var D3=R3(),Ex=K0(),B3=$0();class q3 extends Ex.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=D3.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=D3.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,B3.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,B3.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 Lx=q3;I3.default=Lx});var TL=W((x3)=>{Object.defineProperty(x3,"t",{value:!0});x3.default=void 0;var Jx=K0(),lA=$0();class j3 extends Jx.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,lA.throwIteratorAccessError)();return this.o=this.o.L(),this},this.next=function(){if(this.o===this.h)(0,lA.throwIteratorAccessError)();return this.o=this.o.B(),this};else this.pre=function(){if(this.o===this.h.W)(0,lA.throwIteratorAccessError)();return this.o=this.o.B(),this},this.next=function(){if(this.o===this.h)(0,lA.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 Xx=j3;x3.default=Xx});var k3=W((v3)=>{Object.defineProperty(v3,"t",{value:!0});v3.default=void 0;var Hx=S3(_L()),Zx=S3(TL()),Yx=$0();function S3(_){return _&&_.t?_:{default:_}}class p1 extends Zx.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Yx.throwIteratorAccessError)();return this.o.u}copy(){return new p1(this.o,this.h,this.container,this.iteratorType)}}class y3 extends Hx.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 Kx=y3;v3.default=Kx});var u3=W((g3)=>{Object.defineProperty(g3,"t",{value:!0});g3.default=void 0;var $x=f3(_L()),Gx=f3(TL()),Ux=$0();function f3(_){return _&&_.t?_:{default:_}}class l1 extends Gx.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Ux.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 b3 extends $x.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 Wx=b3;g3.default=Wx});var AL=W((d3)=>{Object.defineProperty(d3,"t",{value:!0});d3.default=Nx;function Nx(_){let T=typeof _;return T==="object"&&_!==null||T==="function"}});var LL=W((n3)=>{Object.defineProperty(n3,"t",{value:!0});n3.HashContainerIterator=n3.HashContainer=void 0;var c3=K0(),EL=Mx(AL()),T8=$0();function Mx(_){return _&&_.t?_:{default:_}}class p3 extends c3.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}}}n3.HashContainerIterator=p3;class l3 extends c3.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,EL.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,EL.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,EL.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}}n3.HashContainer=l3});var t3=W((r3)=>{Object.defineProperty(r3,"t",{value:!0});r3.default=void 0;var a3=LL(),zx=$0();class wT extends a3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,zx.throwIteratorAccessError)();return this.o.u}copy(){return new wT(this.o,this.h,this.container,this.iteratorType)}}class o3 extends a3.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 Fx=o3;r3.default=Fx});var E$=W((T$)=>{Object.defineProperty(T$,"t",{value:!0});T$.default=void 0;var e3=LL(),Cx=Rx(AL()),Ox=$0();function Rx(_){return _&&_.t?_:{default:_}}class ST extends e3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Ox.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 _$ extends e3.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,Cx.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 Dx=_$;T$.default=Dx});var L$=W((q1)=>{Object.defineProperty(q1,"t",{value:!0});Object.defineProperty(q1,"Deque",{enumerable:!0,get:function(){return xx.default}});Object.defineProperty(q1,"HashMap",{enumerable:!0,get:function(){return hx.default}});Object.defineProperty(q1,"HashSet",{enumerable:!0,get:function(){return vx.default}});Object.defineProperty(q1,"LinkList",{enumerable:!0,get:function(){return jx.default}});Object.defineProperty(q1,"OrderedMap",{enumerable:!0,get:function(){return yx.default}});Object.defineProperty(q1,"OrderedSet",{enumerable:!0,get:function(){return Sx.default}});Object.defineProperty(q1,"PriorityQueue",{enumerable:!0,get:function(){return Ix.default}});Object.defineProperty(q1,"Queue",{enumerable:!0,get:function(){return qx.default}});Object.defineProperty(q1,"Stack",{enumerable:!0,get:function(){return Bx.default}});Object.defineProperty(q1,"Vector",{enumerable:!0,get:function(){return Px.default}});var Bx=G0(nK()),qx=G0(rK()),Ix=G0(_3()),Px=G0($3()),jx=G0(N3()),xx=G0(z3()),Sx=G0(k3()),yx=G0(u3()),vx=G0(t3()),hx=G0(E$());function G0(_){return _&&_.t?_:{default:_}}});var X$=W((lg,J$)=>{var kx=L$().OrderedSet,U0=d1()("number-allocator:trace"),fx=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 kx([],(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){fx("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(_)};J$.exports=W0});var JL=W((gx,H$)=>{var bx=X$();gx.NumberAllocator=bx});var K$=W((Y$)=>{Object.defineProperty(Y$,"__esModule",{value:!0});var ux=bK(),dx=JL();class Z${aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(_){if(_>0)this.aliasToTopic=new ux.LRUCache({max:_}),this.topicToAlias={},this.numberAllocator=new dx.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]}}Y$.default=Z$});var $$=W((A8)=>{var px=A8&&A8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(A8,"__esModule",{value:!0});var lx=e4(),nx=px(K$()),ix=qT(),ax=(_,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 nx.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 ix.ErrorWithReasonCode(`Connection refused: ${lx.ReasonCodes[L]}`,L);if(_.emit("error",J),_.options.reconnectOnConnackError)_._cleanUp(!0)}};A8.default=ax});var U$=W((G$)=>{Object.defineProperty(G$,"__esModule",{value:!0});var ox=(_,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)})};G$.default=ox});var W$=W((E8)=>{var L8=E8&&E8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(E8,"__esModule",{value:!0});var sx=L8(RK()),tx=L8(wK()),ex=L8($$()),_w=L8(e4()),Tw=L8(U$()),Aw=(_,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,sx.default)(_,T,A);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":_.reschedulePing(),(0,_w.default)(_,T),A();break;case"pubrel":_.reschedulePing(),(0,Tw.default)(_,T,A);break;case"connack":(0,ex.default)(_,T),A();break;case"auth":_.reschedulePing(),(0,tx.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=Aw});var XL=W((Q$)=>{Object.defineProperty(Q$,"__esModule",{value:!0});class N${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(){}}Q$.default=N$});var z$=W((V$)=>{Object.defineProperty(V$,"__esModule",{value:!0});class M${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={}}}V$.default=M$});var F$=W((K4)=>{var Jw=K4&&K4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(K4,"__esModule",{value:!0});K4.TypedEventEmitter=void 0;var Xw=Jw(I("events")),Hw=qT();class HL{}K4.TypedEventEmitter=HL;(0,Hw.applyMixin)(HL,Xw.default)});var J8=W((eg,y0)=>{function ZL(_){return y0.exports=ZL=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,ZL(_)}y0.exports=ZL,y0.exports.__esModule=!0,y0.exports.default=y0.exports});var O$=W((_m,X8)=>{var C$=J8().default;function Zw(_,T){if(C$(_)!="object"||!_)return _;var A=_[Symbol.toPrimitive];if(A!==void 0){var E=A.call(_,T||"default");if(C$(E)!="object")return E;throw TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(_)}X8.exports=Zw,X8.exports.__esModule=!0,X8.exports.default=X8.exports});var R$=W((Tm,H8)=>{var Yw=J8().default,Kw=O$();function $w(_){var T=Kw(_,"string");return Yw(T)=="symbol"?T:T+""}H8.exports=$w,H8.exports.__esModule=!0,H8.exports.default=H8.exports});var D$=W((Am,Z8)=>{var Gw=R$();function Uw(_,T,A){return(T=Gw(T))in _?Object.defineProperty(_,T,{value:A,enumerable:!0,configurable:!0,writable:!0}):_[T]=A,_}Z8.exports=Uw,Z8.exports.__esModule=!0,Z8.exports.default=Z8.exports});var B$=W((Em,Y8)=>{function Ww(_){if(Array.isArray(_))return _}Y8.exports=Ww,Y8.exports.__esModule=!0,Y8.exports.default=Y8.exports});var q$=W((Lm,K8)=>{function Nw(_,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=Nw,K8.exports.__esModule=!0,K8.exports.default=K8.exports});var I$=W((Jm,$8)=>{function Qw(_,T){(T==null||T>_.length)&&(T=_.length);for(var A=0,E=Array(T);A<T;A++)E[A]=_[A];return E}$8.exports=Qw,$8.exports.__esModule=!0,$8.exports.default=$8.exports});var j$=W((Xm,G8)=>{var P$=I$();function Mw(_,T){if(_){if(typeof _=="string")return P$(_,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)?P$(_,T):void 0}}G8.exports=Mw,G8.exports.__esModule=!0,G8.exports.default=G8.exports});var x$=W((Hm,U8)=>{function Vw(){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=Vw,U8.exports.__esModule=!0,U8.exports.default=U8.exports});var w$=W((Zm,W8)=>{var zw=B$(),Fw=q$(),Cw=j$(),Ow=x$();function Rw(_,T){return zw(_)||Fw(_,T)||Cw(_,T)||Ow()}W8.exports=Rw,W8.exports.__esModule=!0,W8.exports.default=W8.exports});var v$=W((S$)=>{Object.defineProperty(S$,"__esModule",{value:!0});S$.createAddUniqueNumber=void 0;var Dw=(_)=>{return(T)=>{let A=_(T);return T.add(A),A}};S$.createAddUniqueNumber=Dw});var f$=W((h$)=>{Object.defineProperty(h$,"__esModule",{value:!0});h$.createCache=void 0;var Bw=(_)=>{return(T,A)=>{return _.set(T,A),A}};h$.createCache=Bw});var c$=W((u$)=>{Object.defineProperty(u$,"__esModule",{value:!0});u$.createGenerateUniqueNumber=void 0;var b$=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,m$=536870912,g$=m$*2,qw=(_,T)=>{return(A)=>{let E=T.get(A),L=E===void 0?A.size:E<g$?E+1:0;if(!A.has(L))return _(A,L);if(A.size<m$){while(A.has(L))L=Math.floor(Math.random()*g$);return _(A,L)}if(A.size>b$)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(A.has(L))L=Math.floor(Math.random()*b$);return _(A,L)}};u$.createGenerateUniqueNumber=qw});var YL=W((l$)=>{Object.defineProperty(l$,"__esModule",{value:!0});l$.generateUniqueNumber=l$.addUniqueNumber=void 0;var Iw=v$(),Pw=f$(),jw=c$(),p$=new WeakMap,xw=(0,Pw.createCache)(p$),ww=l$.generateUniqueNumber=(0,jw.createGenerateUniqueNumber)(xw,p$),Gm=l$.addUniqueNumber=(0,Iw.createAddUniqueNumber)(ww)});var a$=W((Wm,N8)=>{function i$(_,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 yw(_){return function(){var T=this,A=arguments;return new Promise(function(E,L){var J=_.apply(T,A);function X(Z){i$(J,E,L,X,H,"next",Z)}function H(Z){i$(J,E,L,X,H,"throw",Z)}X(void 0)})}}N8.exports=yw,N8.exports.__esModule=!0,N8.exports.default=N8.exports});var KL=W((Nm,Q8)=>{function vw(_,T){this.v=_,this.k=T}Q8.exports=vw,Q8.exports.__esModule=!0,Q8.exports.default=Q8.exports});var $L=W((Qm,v0)=>{function nA(_,T,A,E){var L=Object.defineProperty;try{L({},"",{})}catch(J){L=0}v0.exports=nA=function(X,H,Z,Y){function K($,G){nA(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,nA(_,T,A,E)}v0.exports=nA,v0.exports.__esModule=!0,v0.exports.default=v0.exports});var GL=W((Mm,h0)=>{var N0=$L();function o$(){/*! 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,b){var k,g,l,c=0,W_=b||[],c_=!1,q_={p:0,n:0,v:_,a:C_,f:C_.bind(_,4),d:function(M_,I_){return k=M_,g=0,l=_,q_.n=I_,X}};function C_(K_,M_){for(g=K_,l=M_,T=0;!c_&&c&&!I_&&T<W_.length;T++){var I_,j_=W_[T],R0=q_.p,y1=j_[2];K_>3?(I_=y1===M_)&&(l=j_[(g=j_[4])?5:(g=3,3)],j_[4]=j_[5]=_):j_[0]<=R0&&((I_=K_<2&&R0<j_[1])?(g=0,q_.v=M_,q_.n=j_[1]):R0<y1&&(I_=K_<3||j_[0]>M_||M_>y1)&&(j_[4]=K_,j_[5]=M_,q_.n=y1,g=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_),g=M_,l=I_;(T=g<2?_:l)||!c_;){k||(g?g<3?(g>1&&(q_.n=-1),C_(g,l)):q_.n=l:q_.v=l);try{if(c=2,k){if(g||(K_="next"),T=k[K_]){if(!(T=T.call(k,l)))throw TypeError("iterator result is not an object");if(!T.done)return T;l=T.value,g<2&&(g=0)}else g===1&&(T=k.return)&&T.call(k),g<2&&(l=TypeError("The iterator does not provide a '"+K_+"' method"),g=1);k=_}else if((T=(c_=q_.n<0)?l:R.call(q,q_))!==X)break}catch(j_){k=_,g=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=o$=function(){return{w:J,m:G}},h0.exports.__esModule=!0,h0.exports.default=h0.exports)()}h0.exports=o$,h0.exports.__esModule=!0,h0.exports.default=h0.exports});var NL=W((Vm,M8)=>{var hw=KL(),UL=$L();function WL(_,T){function A(L,J,X,H){try{var Z=_[L](J),Y=Z.value;return Y instanceof hw?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||(UL(WL.prototype),UL(WL.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),UL(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=WL,M8.exports.__esModule=!0,M8.exports.default=M8.exports});var QL=W((zm,V8)=>{var kw=GL(),fw=NL();function bw(_,T,A,E,L){return new fw(kw().w(_,T,A,E),L||Promise)}V8.exports=bw,V8.exports.__esModule=!0,V8.exports.default=V8.exports});var r$=W((Fm,z8)=>{var gw=QL();function mw(_,T,A,E,L){var J=gw(_,T,A,E,L);return J.next().then(function(X){return X.done?X.value:J.next()})}z8.exports=mw,z8.exports.__esModule=!0,z8.exports.default=z8.exports});var s$=W((Cm,F8)=>{function uw(_){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=uw,F8.exports.__esModule=!0,F8.exports.default=F8.exports});var t$=W((Om,C8)=>{var dw=J8().default;function cw(_){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(dw(_)+" is not iterable")}C8.exports=cw,C8.exports.__esModule=!0,C8.exports.default=C8.exports});var _G=W((Rm,k0)=>{var pw=KL(),lw=GL(),nw=r$(),iw=QL(),aw=NL(),ow=s$(),e$=t$();function ML(){var _=lw(),T=_.m(ML),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,e$($),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=ML=function(){return{wrap:function(Z,Y,K,$){return _.w(J(Z),Y,K,$&&$.reverse())},isGeneratorFunction:E,mark:_.m,awrap:function(Z,Y){return new pw(Z,Y)},AsyncIterator:aw,async:function(Z,Y,K,$,G){return(E(Y)?iw:nw)(J(Z),Y,K,$,G)},keys:ow,values:e$}},k0.exports.__esModule=!0,k0.exports.default=k0.exports)()}k0.exports=ML,k0.exports.__esModule=!0,k0.exports.default=k0.exports});var AG=W((Dm,TG)=>{var iA=_G()();TG.exports=iA;try{regeneratorRuntime=iA}catch(_){if(typeof globalThis==="object")globalThis.regeneratorRuntime=iA;else Function("r","regeneratorRuntime = r")(iA)}});var LG=W((aA,EG)=>{(function(_,T){typeof aA==="object"&&typeof EG<"u"?T(aA,D$(),w$(),YL(),a$(),AG()):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))})(aA,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 b(){var k,g,l,c;return J.wrap(function(W_){while(!0)switch(W_.prev=W_.next){case 0:return k=new MessageChannel,g=k.port1,l=k.port2,W_.next=1,q("connect",{port:g},[g]);case 1:return c=W_.sent,H.set(l,c),W_.abrupt("return",l);case 2:case"end":return W_.stop()}},b)}))},disconnect:function(R){var q=R.call;return function(){var b=L(J.mark(function k(g){var l;return J.wrap(function(c){while(!0)switch(c.prev=c.next){case 0:if(l=H.get(g),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()}},k)}));return function(k){return b.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 b=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_)})},k=function(K_,M_){var I_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];R.postMessage({id:null,method:K_,params:M_},I_)},g={};for(var l=0,c=Object.entries(F);l<c.length;l++){var W_=A(c[l],2),c_=W_[0],q_=W_[1];g=G(G({},g),{},T({},c_,q_({call:b,notify:k})))}return G({},g)}};_.createBroker=N})});var XG=W((oA,JG)=>{(function(_,T){typeof oA==="object"&&typeof JG<"u"?T(oA,J8(),LG(),YL()):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))})(oA,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 ZG=W((rA,HG)=>{(function(_,T){typeof rA==="object"&&typeof HG<"u"?T(rA,XG()):typeof define==="function"&&define.amd?define(["exports","worker-timers-broker"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.workerTimers={},_.workerTimersBroker))})(rA,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(($G)=>{Object.defineProperty($G,"__esModule",{value:!0});$G.isReactNativeBrowser=$G.isWebWorker=void 0;var rw=()=>{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},YG=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),KG=()=>typeof navigator<"u"&&navigator.product==="ReactNative",sw=rw()||YG()||KG();$G.isWebWorker=YG();$G.isReactNativeBrowser=KG();$G.default=sw});var QG=W((f0)=>{var _S=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]}),TS=f0&&f0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),AS=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")_S(A,T,E[L])}return TS(A,T),A}}();Object.defineProperty(f0,"__esModule",{value:!0});var UG=ZG(),VL=AS(O8()),WG={set:UG.setInterval,clear:UG.clearInterval},NG={set:(_,T)=>setInterval(_,T),clear:(_)=>clearInterval(_)},ES=(_)=>{switch(_){case"native":return NG;case"worker":return WG;case"auto":default:return VL.default&&!VL.isWebWorker&&!VL.isReactNativeBrowser?WG:NG}};f0.default=ES});var zL=W((R8)=>{var LS=R8&&R8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(R8,"__esModule",{value:!0});var JS=LS(QG());class MG{_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,JS.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=MG});var tA=W((n1)=>{var XS=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]}),HS=n1&&n1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),OG=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")XS(A,T,E[L])}return HS(A,T),A}}(),t0=n1&&n1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(n1,"__esModule",{value:!0});var FL=t0(SA()),ZS=n0(),VG=t0(NK()),YS=t0(d1()),zG=OG(VK()),$4=t0(nE()),KS=t0(W$()),$S=t0(XL()),GS=t0(z$()),D8=qT(),US=F$(),WS=t0(zL()),FG=OG(O8()),CL=globalThis.setImmediate||((..._)=>{let T=_.shift();(0,D8.nextTick)(()=>{T(..._)})}),CG={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1000,connectTimeout:30000,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class sA extends US.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 CG)if(typeof this.options[A]>"u")this.options[A]=CG[A];else this.options[A]=T[A];if(this.log=this.options.log||(0,YS.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",sA.VERSION),FG.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",FG.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:sA.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)FL.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=_,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new $S.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 GS.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 ZS.Writable,T=FL.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,KS.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=zG.validateTopics(J);if(X!==null)return CL(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:b}=q;for(let k=0;k<b.length;k+=1)U[k].qos=b[k]}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=zG.validateTopics(_);if(E!==null)return CL(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),CL(()=>{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,VG.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=FL.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,VG.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 WS.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=sA});var BG=W((DG)=>{Object.defineProperty(DG,"__esModule",{value:!0});var NS=JL();class RG{numberAllocator;lastId;constructor(){this.numberAllocator=new NS.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()}}DG.default=RG});var eA=W((jG)=>{Object.defineProperty(jG,"__esModule",{value:!0});jG.BufferedDuplex=void 0;jG.writev=IG;var MS=n0(),qG=I("buffer");function IG(_,T){let A=Array(_.length);for(let E=0;E<_.length;E++)if(typeof _[E].chunk==="string")A[E]=qG.Buffer.from(_[E].chunk,"utf8");else A[E]=_[E].chunk;this._write(qG.Buffer.concat(A),"binary",T)}class PG extends MS.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(_,T,A){super({objectMode:!0});if(this.proxy=T,this.socket=A,this.writeQueue=[],!_.objectMode)this._writev=IG.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)}}}jG.BufferedDuplex=PG});var B8=W((_T)=>{var RL=_T&&_T.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(_T,"__esModule",{value:!0});_T.streamBuilder=_T.browserStreamBuilder=void 0;var _5=I("buffer"),wG=RL(I("ws")),zS=RL(d1()),FS=n0(),CS=RL(O8()),OL=eA(),e0=(0,zS.default)("mqttjs:ws"),OS=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function SG(_,T){let A=`${_.protocol}://${_.hostname}:${_.port}${_.path}`;if(typeof _.transformWsUrl==="function")A=_.transformWsUrl(A,_,T);return A}function yG(_){let T=_;if(!_.port)if(_.protocol==="wss")T.port=443;else T.port=80;if(!_.path)T.path="/";if(!_.wsOptions)T.wsOptions={};if(!CS.default&&!_.forceNativeWebSocket&&_.protocol==="wss")OS.forEach((A)=>{if(Object.prototype.hasOwnProperty.call(_,A)&&!Object.prototype.hasOwnProperty.call(_.wsOptions,A))T.wsOptions[A]=_[A]});return T}function RS(_){let T=yG(_);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 DS(_,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 wG.default(T,[E],A.wsOptions);return L}function BS(_,T){let A=T.protocolId==="MQIsdp"&&T.protocolVersion===3?"mqttv3.1":"mqtt",E=SG(T,_),L;if(T.createWebsocket)L=T.createWebsocket(E,[A],T);else L=new WebSocket(E,[A]);return L.binaryType="arraybuffer",L}var qS=(_,T)=>{e0("streamBuilder");let A=yG(T);A.hostname=A.hostname||A.host||"localhost";let E=SG(A,_),L=DS(_,E,A),J=wG.default.createWebSocketStream(L,A.wsOptions);return J.url=E,L.on("close",()=>{J.destroy()}),J};_T.streamBuilder=qS;var IS=(_,T)=>{e0("browserStreamBuilder");let A,L=RS(T).browserBufferSize||524288,J=T.browserBufferTimeout||1000,X=!T.objectMode,H=BS(_,T),Z=K(T,N,z);if(!T.objectMode)Z._writev=OL.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 OL.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 FS.Transform({objectMode:Q.objectMode});return q._write=F,q._flush=R,q}function $(){if(e0("WebSocket onOpen"),A instanceof OL.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=_5.Buffer.from(F);else if(F instanceof Blob)F=_5.Buffer.from(await new Response(F).arrayBuffer());else F=_5.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=_5.Buffer.from(Q,"utf8");try{H.send(Q)}catch(q){return R(q)}R()}function z(Q){H.close(),Q()}return A};_T.browserStreamBuilder=IS});var bG=W((fG)=>{Object.defineProperty(fG,"__esModule",{value:!0});var vG=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."};fG.ERRORS=yT;function PS(_){if(!vG.Buffer.isEncoding(_))throw Error(yT.INVALID_ENCODING)}fG.checkEncoding=PS;function hG(_){return typeof _==="number"&&isFinite(_)&&SS(_)}fG.isFiniteInteger=hG;function kG(_,T){if(typeof _==="number"){if(!hG(_)||_<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 jS(_){kG(_,!1)}fG.checkLengthValue=jS;function xS(_){kG(_,!0)}fG.checkOffsetValue=xS;function wS(_,T){if(_<0||_>T.length)throw Error(yT.INVALID_TARGET_OFFSET)}fG.checkTargetOffset=wS;function SS(_){return typeof _==="number"&&isFinite(_)&&Math.floor(_)===_}function yS(_){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof vG.Buffer.prototype[_]>"u")throw Error(`Platform does not support Buffer.prototype.${_}.`)}fG.bigIntAndBufferInt64Check=yS});var uG=W((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});var t=bG(),gG=4096,uS="utf8";class DL{constructor(_){if(this.length=0,this._encoding=uS,this._writeOffset=0,this._readOffset=0,DL.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(gG)}else{if(typeof _<"u")throw Error(t.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(gG)}}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}}mG.SmartBuffer=DL});var BL=W((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.SOCKS5_NO_ACCEPTABLE_AUTH=aG.SOCKS5_CUSTOM_AUTH_END=aG.SOCKS5_CUSTOM_AUTH_START=aG.SOCKS_INCOMING_PACKET_SIZES=aG.SocksClientState=aG.Socks5Response=aG.Socks5HostType=aG.Socks5Auth=aG.Socks4Response=aG.SocksCommand=aG.ERRORS=aG.DEFAULT_TIMEOUT=void 0;var cS=30000;aG.DEFAULT_TIMEOUT=cS;var pS={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"};aG.ERRORS=pS;var lS={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(_)=>_+7,Socks4Response:8};aG.SOCKS_INCOMING_PACKET_SIZES=lS;var dG;(function(_){_[_.connect=1]="connect",_[_.bind=2]="bind",_[_.associate=3]="associate"})(dG||(aG.SocksCommand=dG={}));var cG;(function(_){_[_.Granted=90]="Granted",_[_.Failed=91]="Failed",_[_.Rejected=92]="Rejected",_[_.RejectedIdent=93]="RejectedIdent"})(cG||(aG.Socks4Response=cG={}));var pG;(function(_){_[_.NoAuth=0]="NoAuth",_[_.GSSApi=1]="GSSApi",_[_.UserPass=2]="UserPass"})(pG||(aG.Socks5Auth=pG={}));var nS=128;aG.SOCKS5_CUSTOM_AUTH_START=nS;var iS=254;aG.SOCKS5_CUSTOM_AUTH_END=iS;var aS=255;aG.SOCKS5_NO_ACCEPTABLE_AUTH=aS;var lG;(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"})(lG||(aG.Socks5Response=lG={}));var nG;(function(_){_[_.IPv4=1]="IPv4",_[_.Hostname=3]="Hostname",_[_.IPv6=4]="IPv6"})(nG||(aG.Socks5HostType=nG={}));var iG;(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"})(iG||(aG.SocksClientState=iG={}))});var qL=W((sG)=>{Object.defineProperty(sG,"__esModule",{value:!0});sG.shuffleArray=sG.SocksClientError=void 0;class rG extends Error{constructor(_,T){super(_);this.options=T}}sG.SocksClientError=rG;function Xy(_){for(let T=_.length-1;T>0;T--){let A=Math.floor(Math.random()*(T+1));[_[T],_[A]]=[_[A],_[T]]}}sG.shuffleArray=Xy});var T5=W((_U)=>{Object.defineProperty(_U,"__esModule",{value:!0});_U.isInSubnet=Zy;_U.isCorrect=Yy;_U.numberToPaddedHex=eG;_U.stringToPaddedHex=Ky;_U.testBit=$y;function Zy(_){if(this.subnetMask<_.subnetMask)return!1;if(this.mask(_.subnetMask)===_.mask())return!0;return!1}function Yy(_){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===_&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function eG(_){return _.toString(16).padStart(2,"0")}function Ky(_){return eG(parseInt(_,10))}function $y(_,T){let{length:A}=_;if(T>A)return!1;let E=A-T;return _.substring(E,E+1)==="1"}});var IL=W((TU)=>{Object.defineProperty(TU,"__esModule",{value:!0});TU.RE_SUBNET_STRING=TU.RE_ADDRESS=TU.GROUPS=TU.BITS=void 0;TU.BITS=32;TU.GROUPS=4;TU.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;TU.RE_SUBNET_STRING=/\/\d{1,2}$/});var A5=W((LU)=>{Object.defineProperty(LU,"__esModule",{value:!0});LU.AddressError=void 0;class EU extends Error{constructor(_,T){super(_);this.name="AddressError",this.parseMessage=T}}LU.AddressError=EU});var PL=W((Q0)=>{var Fy=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]}),Cy=Q0&&Q0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),XU=Q0&&Q0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))Fy(T,_,A)}return Cy(T,_),T};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.Address4=void 0;var G4=XU(T5()),i1=XU(IL()),q8=A5();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 jL=W((HU)=>{Object.defineProperty(HU,"__esModule",{value:!0});HU.RE_URL_WITH_PORT=HU.RE_URL=HU.RE_ZONE_STRING=HU.RE_SUBNET_STRING=HU.RE_BAD_ADDRESS=HU.RE_BAD_CHARACTERS=HU.TYPES=HU.SCOPES=HU.GROUPS=HU.BITS=void 0;HU.BITS=128;HU.GROUPS=8;HU.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};HU.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"};HU.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;HU.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;HU.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;HU.RE_ZONE_STRING=/%.*$/;HU.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;HU.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var xL=W(($U)=>{Object.defineProperty($U,"__esModule",{value:!0});$U.spanAllZeroes=YU;$U.spanAll=wy;$U.spanLeadingZeroes=Sy;$U.simpleGroup=yy;function YU(_){return _.replace(/(0+)/g,'<span class="zero">$1</span>')}function wy(_,T=0){return _.split("").map((E,L)=>`<span class="digit value-${E} position-${L+T}">${YU(E)}</span>`).join("")}function KU(_){return _.replace(/^(0+)/,'<span class="zero">$1</span>')}function Sy(_){return _.split(":").map((A)=>KU(A)).join(":")}function yy(_,T=0){return _.split(":").map((E,L)=>{if(/group-v4/.test(E))return E;return`<span class="hover-group group-${L+T}">${KU(E)}</span>`})}});var GU=W((Y1)=>{var by=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]}),gy=Y1&&Y1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),my=Y1&&Y1.__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(Y1,"__esModule",{value:!0});Y1.ADDRESS_BOUNDARY=void 0;Y1.groupPossibilities=L5;Y1.padGroup=E5;Y1.simpleRegularExpression=dy;Y1.possibleElisions=cy;var uy=my(jL());function L5(_){return`(${_.join("|")})`}function E5(_){if(_.length<4)return`0{0,${4-_.length}}${_}`;return _}Y1.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function dy(_){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===uy.GROUPS-1?":":"";return L5([E5(L),X])}return E5(L)}).join(":"));return A.push(_.map(E5).join(":")),L5(A)}function cy(_,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 L5(J)}});var QU=W((M0)=>{var py=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]}),ly=M0&&M0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),H5=M0&&M0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))py(T,_,A)}return ly(T,_),T};Object.defineProperty(M0,"__esModule",{value:!0});M0.Address6=void 0;var UU=H5(T5()),wL=H5(IL()),N_=H5(jL()),SL=H5(xL()),vT=PL(),hT=GU(),b0=A5(),J5=T5();function X5(_){if(!_)throw Error("Assertion failed.")}function ny(_){let T=/(\d+)(\d{3})/;while(T.test(_))_=_.replace(T,"$1,$2");return _}function iy(_){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 ay(_,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 WU(_){return parseInt(_,16).toString(16).padStart(4,"0")}function NU(_){return _&255}class k_{constructor(_,T){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=UU.isInSubnet,this.isCorrect=UU.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-(wL.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 ny((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=ay(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(wL.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(wL.RE_ADDRESS,this.address4.parsedAddress.map(iy).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(WU).join(":")}decimal(){return this.parsedAddress.map((_)=>parseInt(_,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(WU).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,J5.testBit)(X,15),Z=(0,J5.testBit)(X,14),Y=(0,J5.testBit)(X,8),K=(0,J5.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(NU)}static fromByteArray(_){return this.fromUnsignedByteArray(_.map(NU))}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 SL.simpleGroup(this.address).join(":");X5(typeof this.elidedGroups==="number"),X5(typeof this.elisionBegin==="number");let _=[],[T,A]=this.address.split("::");if(T.length)_.push(...SL.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(...SL.simpleGroup(A,this.elisionEnd));else _.push("");if(this.is4())X5(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(X5(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 yL=W((a_)=>{var oy=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]}),ry=a_&&a_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),sy=a_&&a_.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))oy(T,_,A)}return ry(T,_),T};Object.defineProperty(a_,"__esModule",{value:!0});a_.v6=a_.AddressError=a_.Address6=a_.Address4=void 0;var ty=PL();Object.defineProperty(a_,"Address4",{enumerable:!0,get:function(){return ty.Address4}});var ey=QU();Object.defineProperty(a_,"Address6",{enumerable:!0,get:function(){return ey.Address6}});var _v=A5();Object.defineProperty(a_,"AddressError",{enumerable:!0,get:function(){return _v.AddressError}});var Tv=sy(xL());a_.v6={helpers:Tv}});var DU=W((OU)=>{Object.defineProperty(OU,"__esModule",{value:!0});OU.ipToBuffer=OU.int32ToIpv4=OU.ipv4ToInt32=OU.validateSocksClientChainOptions=OU.validateSocksClientOptions=void 0;var _1=qL(),f_=BL(),Av=I("stream"),vL=yL(),MU=I("net");function Ev(_,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(!zU(_.destination))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsDestination,_);if(!FU(_.proxy))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);if(VU(_.proxy,_),_.timeout&&!CU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_);if(_.existing_socket&&!(_.existing_socket instanceof Av.Duplex))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsExistingSocket,_)}OU.validateSocksClientOptions=Ev;function Lv(_){if(_.command!=="connect")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommandChain,_);if(!zU(_.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(!FU(T))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);VU(T,_)}),_.timeout&&!CU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_)}OU.validateSocksClientChainOptions=Lv;function VU(_,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 zU(_){return _&&typeof _.host==="string"&&Buffer.byteLength(_.host)<256&&typeof _.port==="number"&&_.port>=0&&_.port<=65535}function FU(_){return _&&(typeof _.host==="string"||typeof _.ipaddress==="string")&&typeof _.port==="number"&&_.port>=0&&_.port<=65535&&(_.type===4||_.type===5)}function CU(_){return typeof _==="number"&&_>0}function Jv(_){return new vL.Address4(_).toArray().reduce((A,E)=>(A<<8)+E,0)>>>0}OU.ipv4ToInt32=Jv;function Xv(_){let T=_>>>24&255,A=_>>>16&255,E=_>>>8&255,L=_&255;return[T,A,E,L].join(".")}OU.int32ToIpv4=Xv;function Hv(_){if(MU.isIPv4(_)){let T=new vL.Address4(_);return Buffer.from(T.toArray())}else if(MU.isIPv6(_)){let T=new vL.Address6(_);return Buffer.from(T.canonicalForm().split(":").map((A)=>A.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}OU.ipToBuffer=Hv});var PU=W((qU)=>{Object.defineProperty(qU,"__esModule",{value:!0});qU.ReceiveBuffer=void 0;class BU{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}}qU.ReceiveBuffer=BU});var jU=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 Gv=I("events"),W4=I("net"),K1=uG(),P=BL(),W1=DU(),Uv=PU(),kL=qL();Object.defineProperty(TT,"SocksClientError",{enumerable:!0,get:function(){return kL.SocksClientError}});var hL=yL();class Z5 extends Gv.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 Z5(_);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,kL.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 Z5.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=hL.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 Uv.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 kL.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:hL.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:hL.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=Z5});var xU=W((kT)=>{var Wv=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]}),Nv=kT&&kT.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))Wv(T,_,A)};Object.defineProperty(kT,"__esModule",{value:!0});Nv(jU(),kT)});var bL=W((a1)=>{var Qv=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]}),Mv=a1&&a1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Vv=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")Qv(A,T,E[L])}return Mv(A,T),A}}(),wU=a1&&a1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(a1,"__esModule",{value:!0});a1.default=Iv;var zv=wU(d1()),Fv=I("stream"),Cv=xU(),Ov=Vv(I("dns")),Rv=I("util"),fL=wU(I("assert")),g0=(0,zv.default)("mqttjs:socks");class SU extends Fv.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(_){if(g0("proxy stream started"),(0,fL.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,fL.default)(this._socket),this._socket.write(_,A)}_read(_){this._flowing=!0,this._socket?.resume?.()}_destroy(_,T){this._socket?.destroy?.(_),T(_)}_onData=(_)=>{if((0,fL.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 Y5(_){try{if(_.code===void 0)_.code="SOCKS";return _}catch{return _}}function Dv(_){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 Bv(_){let T=new URL(_);if(T.pathname||T.hash||T.search)throw Y5(Error("bad SOCKS URL"));let[A,E]=Dv(T.protocol);if(!A)throw Y5(Error("bad SOCKS URL: invalid protocol"));let L=parseInt(T.port,10);if(Number.isNaN(L))throw Y5(Error("bad SOCKS URL: invalid port"));return[{host:T.hostname,port:L,type:A},E]}async function qv(_,T,A,E,L={}){let J=L.lookup??(0,Rv.promisify)(Ov.lookup),[X,H]=Bv(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 Cv.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(Y5(Y))})}function Iv(_,T,A,E){g0("SOCKS connection to %s:%d via %s",_,T,A);let L=new SU;return qv(_,T,A,L,E).catch((J)=>{g0("SOCKS failed: %s",J),L.destroy(J)}),L}});var mL=W((I8)=>{var gL=I8&&I8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(I8,"__esModule",{value:!0});var Pv=gL(I("net")),jv=gL(d1()),xv=gL(bL()),wv=(0,jv.default)("mqttjs:tcp"),Sv=(_,T)=>{if(T.port=T.port||1883,T.hostname=T.hostname||T.host||"localhost",T.socksProxy)return(0,xv.default)(T.hostname,T.port,T.socksProxy,{timeout:T.socksTimeout});let{port:A,path:E}=T,L=T.hostname;return wv("port %d and host %s",A,L),Pv.default.createConnection({port:A,host:L,path:E})};I8.default=Sv});var dL=W((P8)=>{var uL=P8&&P8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(P8,"__esModule",{value:!0});var yU=I("tls"),yv=uL(I("net")),vv=uL(d1()),hv=uL(bL()),kv=(0,vv.default)("mqttjs:tls");function fv(_){let{host:T,port:A,socksProxy:E,...L}=_;if(E!==void 0){let J=(0,hv.default)(T,A,E,{timeout:_.socksTimeout});return(0,yU.connect)({...L,socket:J})}return(0,yU.connect)(_)}var bv=(_,T)=>{if(T.port=T.port||8883,T.host=T.hostname||T.host||"localhost",yv.default.isIP(T.host)===0)T.servername=T.host;T.rejectUnauthorized=T.rejectUnauthorized!==!1,delete T.path,kv("port %d host %s rejectUnauthorized %b",T.port,T.host,T.rejectUnauthorized);let A=fv(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=bv});var pL=W((hU)=>{Object.defineProperty(hU,"__esModule",{value:!0});var vU=I("buffer"),gv=n0(),mv=eA(),V0,cL,N1;function uv(){let _=new gv.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 dv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function cv(_,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 pv(){V0.onOpen(()=>{N1.socketReady()}),V0.onMessage((_)=>{let{data:T}=_;if(T instanceof ArrayBuffer)T=vU.Buffer.from(T);else T=vU.Buffer.from(T,"utf8");cL.push(T)}),V0.onClose(()=>{N1.emit("close"),N1.end(),N1.destroy()}),V0.onError((_)=>{let T=Error(_.errMsg);N1.destroy(T)})}var lv=(_,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";dv(T);let E=cv(T,_);V0=wx.connectSocket({url:E,protocols:[A]}),cL=uv(),N1=new mv.BufferedDuplex(T,cL,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},pv(),N1};hU.default=lv});var nL=W((fU)=>{Object.defineProperty(fU,"__esModule",{value:!0});var lL=I("buffer"),iv=n0(),av=eA(),m0,j8,N4,kU=!1;function ov(){let _=new iv.Transform;return _._write=(T,A,E)=>{m0.sendSocketMessage({data:T.buffer,success(){E()},fail(){E(Error())}})},_._flush=(T)=>{m0.closeSocket({success(){T()}})},_}function rv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function sv(_,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 tv(){if(kU)return;kU=!0,m0.onSocketOpen(()=>{N4.socketReady()}),m0.onSocketMessage((_)=>{if(typeof _.data==="string"){let T=lL.Buffer.from(_.data,"base64");j8.push(T)}else{let T=new FileReader;T.addEventListener("load",()=>{if(T.result instanceof ArrayBuffer){j8.push(lL.Buffer.from(T.result));return}j8.push(lL.Buffer.from(T.result,"utf-8"))}),T.readAsArrayBuffer(_.data)}}),m0.onSocketClose(()=>{N4.end(),N4.destroy()}),m0.onSocketError((_)=>{N4.destroy(_)})}var ev=(_,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";rv(T);let E=sv(T,_);return m0=T.my,m0.connectSocket({url:E,protocols:A}),j8=ov(),N4=new av.BufferedDuplex(T,j8,m0),tv(),N4};fU.default=ev});var uU=W((Q4)=>{var K5=Q4&&Q4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(Q4,"__esModule",{value:!0});Q4.connectAsync=Jh;var Th=K5(d1()),Ah=K5(I("url")),Eh=K5(tA()),bU=K5(O8());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var gU=(0,Th.default)("mqttjs"),y_=null;function Lh(_){let T;if(_.auth)if(T=_.auth.match(/^(.+):(.+)$/),T){let[,A,E]=T;_.username=A,_.password=E}else _.username=_.auth}function mU(_,T){if(gU("connecting to an MQTT broker..."),typeof _==="object"&&!T)T=_,_="";if(T=T||{},_&&typeof _==="string"){let L=Ah.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(Lh(T),T.query&&typeof T.query.clientId==="string")T.clientId=T.query.clientId;if(bU.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_={},!bU.default&&!T.forceNativeWebSocket)y_.ws=B8().streamBuilder,y_.wss=B8().streamBuilder,y_.mqtt=mL().default,y_.tcp=mL().default,y_.ssl=dL().default,y_.tls=y_.ssl,y_.mqtts=dL().default;else y_.ws=B8().browserStreamBuilder,y_.wss=B8().browserStreamBuilder,y_.wx=pL().default,y_.wxs=pL().default,y_.ali=nL().default,y_.alis=nL().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 gU("calling streambuilder for",T.protocol),y_[T.protocol](L,T)}let E=new Eh.default(A,T);return E.on("error",()=>{}),E}function Jh(_,T,A=!0){return new Promise((E,L)=>{let J=mU(_,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=mU});var iL=W((Z_)=>{var dU=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]}),Xh=Z_&&Z_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Hh=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")dU(A,T,E[L])}return Xh(A,T),A}}(),cU=Z_&&Z_.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))dU(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 pU=x8(tA());Z_.MqttClient=pU.default;var Zh=x8(XL());Z_.DefaultMessageIdProvider=Zh.default;var Yh=x8(BG());Z_.UniqueMessageIdProvider=Yh.default;var Kh=x8(nE());Z_.Store=Kh.default;var lU=Hh(uU());Z_.connect=lU.default;Object.defineProperty(Z_,"connectAsync",{enumerable:!0,get:function(){return lU.connectAsync}});var $h=x8(zL());Z_.KeepaliveManager=$h.default;Z_.Client=pU.default;cU(tA(),Z_);cU(qT(),Z_);var Gh=e4();Object.defineProperty(Z_,"ReasonCodes",{enumerable:!0,get:function(){return Gh.ReasonCodes}})});var iU=W((I1)=>{var nU=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]}),Uh=I1&&I1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Wh=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")nU(A,T,E[L])}return Uh(A,T),A}}(),Nh=I1&&I1.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))nU(T,_,A)};Object.defineProperty(I1,"__esModule",{value:!0});var Qh=Wh(iL());I1.default=Qh;Nh(iL(),I1)});var sL=W((Su,_W)=>{_W.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var EW=W((yu,AW)=>{var Rh=sL();function TW(_){this.mode=Rh.MODE_8BIT_BYTE,this.data=_}TW.prototype={getLength:function(){return this.data.length},write:function(_){for(var T=0;T<this.data.length;T++)_.put(this.data.charCodeAt(T),8)}};AW.exports=TW});var tL=W((vu,LW)=>{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_;LW.exports=o1});var eL=W((hu,JW)=>{var fT=tL();function M5(_,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]}M5.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 M5(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 M5(A,0).mod(_)}};JW.exports=M5});var HW=W((ku,XW)=>{XW.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var KW=W((fu,YW)=>{var j1=sL(),ZW=eL(),Dh=tL(),AT=HW(),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 ZW([1],0);for(var A=0;A<_;A++)T=T.multiply(new ZW([1,Dh.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}};YW.exports=u_});var _9=W((bu,$W)=>{$W.exports={L:1,M:0,Q:3,H:2}});var UW=W((gu,GW)=>{var V5=_9();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 V5.L:return z0.RS_BLOCK_TABLE[(_-1)*4+0];case V5.M:return z0.RS_BLOCK_TABLE[(_-1)*4+1];case V5.Q:return z0.RS_BLOCK_TABLE[(_-1)*4+2];case V5.H:return z0.RS_BLOCK_TABLE[(_-1)*4+3];default:return}};GW.exports=z0});var QW=W((mu,NW)=>{function WW(){this.buffer=[],this.length=0}WW.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++}};NW.exports=WW});var FW=W((uu,zW)=>{var Bh=EW(),ET=KW(),qh=eL(),MW=UW(),VW=QW();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 Bh(_);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=MW.getRSBlocks(_,this.errorCorrectLevel),A=new VW,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=MW.getRSBlocks(_,T),L=new VW;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 qh(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 b=0;b<T.length;b++)if(q<J[b].length)F[R++]=J[b][q];for(var k=0;k<L;k++)for(var g=0;g<T.length;g++)if(k<X[g].length)F[R++]=X[g][k];return F};zW.exports=F0});var RW=W((du,OW)=>{var Ih=FW(),CW=_9(),Ph="\x1B[40m \x1B[0m",z5="\x1B[47m \x1B[0m",jh=function(_){return _?Ph:z5},T9=function(_){return{times:function(T){return Array(T).join(_)}}},xh=function(_,T){var A=Array(_);for(var E=0;E<_;E++)A[E]=T;return A};OW.exports={error:CW.L,generate:function(_,T,A){if(typeof T==="function")A=T,T={};var E=new Ih(-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(xh(H,X));var K={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},$=T9(K.BLACK_WHITE).times(H+3),G=T9(K.WHITE_BLACK).times(H+3);L+=$+`
12
+ */var bE=$Y(),J4=GY(),UY=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;FI.Buffer=B;FI.SlowBuffer=AI;FI.INSPECT_MAX_BYTES=50;var bA=2147483647;FI.kMaxLength=bA;B.TYPED_ARRAY_SUPPORT=sq();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 sq(){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(_>bA)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 dE(_)}return QY(_,T,A)}B.poolSize=8192;function QY(_,T,A){if(typeof _==="string")return eq(_,T);if(ArrayBuffer.isView(_))return _I(_);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 mE(_,T,A);if(typeof SharedArrayBuffer<"u"&&(H0(_,SharedArrayBuffer)||_&&H0(_.buffer,SharedArrayBuffer)))return mE(_,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=TI(_);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 QY(_,T,A)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function MY(_){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 tq(_,T,A){if(MY(_),_<=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 tq(_,T,A)};function dE(_){return MY(_),S0(_<0?0:cE(_)|0)}B.allocUnsafe=function(_){return dE(_)};B.allocUnsafeSlow=function(_){return dE(_)};function eq(_,T){if(typeof T!=="string"||T==="")T="utf8";if(!B.isEncoding(T))throw TypeError("Unknown encoding: "+T);var A=VY(_,T)|0,E=S0(A),L=E.write(_,T);if(L!==A)E=E.slice(0,L);return E}function gE(_){var T=_.length<0?0:cE(_.length)|0,A=S0(T);for(var E=0;E<T;E+=1)A[E]=_[E]&255;return A}function _I(_){if(H0(_,Uint8Array)){var T=new Uint8Array(_);return mE(T.buffer,T.byteOffset,T.byteLength)}return gE(_)}function mE(_,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 TI(_){if(B.isBuffer(_)){var T=cE(_.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"||pE(_.length))return S0(0);return gE(_)}if(_.type==="Buffer"&&Array.isArray(_.data))return gE(_.data)}function cE(_){if(_>=bA)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+bA.toString(16)+" bytes");return _|0}function AI(_){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 VY(_,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 uE(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return DY(_).length;default:if(L)return E?-1:uE(_).length;T=(""+T).toLowerCase(),L=!0}}B.byteLength=VY;function EI(_,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 UI(this,T,A);case"utf8":case"utf-8":return FY(this,T,A);case"ascii":return $I(this,T,A);case"latin1":case"binary":return GI(this,T,A);case"base64":return YI(this,T,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return WI(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 FY(this,0,T);return EI.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=FI.INSPECT_MAX_BYTES;if(T=this.toString("hex",0,A).replace(/(.{2})/g,"$1 ").trim(),this.length>A)T+=" ... ";return"<Buffer "+T+">"};if(UY)B.prototype[UY]=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 zY(_,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,pE(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 WY(_,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 WY(_,[T],A,E,L)}throw TypeError("val must be string, number or Buffer")}function WY(_,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 zY(this,T,A,E,!0)};B.prototype.lastIndexOf=function(T,A,E){return zY(this,T,A,E,!1)};function LI(_,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(pE(H))return X;_[A+X]=H}return X}function JI(_,T,A,E){return gA(uE(T,_.length-A),_,A,E)}function XI(_,T,A,E){return gA(MI(T),_,A,E)}function HI(_,T,A,E){return gA(DY(T),_,A,E)}function ZI(_,T,A,E){return gA(VI(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 LI(this,T,A,E);case"utf8":case"utf-8":return JI(this,T,A,E);case"ascii":case"latin1":case"binary":return XI(this,T,A,E);case"base64":return HI(this,T,A,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ZI(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 YI(_,T,A){if(T===0&&A===_.length)return bE.fromByteArray(_);else return bE.fromByteArray(_.slice(T,A))}function FY(_,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 KI(E)}var NY=4096;function KI(_){var T=_.length;if(T<=NY)return String.fromCharCode.apply(String,_);var A="",E=0;while(E<T)A+=String.fromCharCode.apply(String,_.slice(E,E+=NY));return A}function $I(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]&127);return E}function GI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]);return E}function UI(_,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+=zI[_[J]];return L}function WI(_,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 CY(_,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 OY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)CY(_,T,A,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return J4.write(_,T,A,E,23,4),A+4}B.prototype.writeFloatLE=function(T,A,E){return OY(this,T,A,!0,E)};B.prototype.writeFloatBE=function(T,A,E){return OY(this,T,A,!1,E)};function RY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)CY(_,T,A,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return J4.write(_,T,A,E,52,8),A+8}B.prototype.writeDoubleLE=function(T,A,E){return RY(this,T,A,!0,E)};B.prototype.writeDoubleBE=function(T,A,E){return RY(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 NI=/[^+/0-9A-Za-z-_]/g;function QI(_){if(_=_.split("=")[0],_=_.trim().replace(NI,""),_.length<2)return"";while(_.length%4!==0)_=_+"=";return _}function uE(_,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 MI(_){var T=[];for(var A=0;A<_.length;++A)T.push(_.charCodeAt(A)&255);return T}function VI(_,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 DY(_){return bE.toByteArray(QI(_))}function gA(_,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 pE(_){return _!==_}var zI=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 wY=W((tb,lE)=>{var IY=XY(),jY=YY(),mA=DI();function DI(){let _=I("buffer");return _&&_.Buffer?_.Buffer:qY().Buffer}var BI=mA.from("==","base64");function qI(_){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=IY(),X.decode=xY;let L=PY(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=IY(),L=PY(X.uuid,A),J=0;if(T)H=L+`0000000000${J}`.slice(-10);else H=L+J;return J=J+1|0,H}}function PY(_,T){let A=mA.concat([mA.from(jY.parse(_)),BI]).toString("base64");if(T)return A.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"-");return A.replace(/=+$/,"/")}function xY(_,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:jY.unparse(mA.from(L+"==","base64")),count:J}}lE.exports=qI;lE.exports.decode=xY});var vY=W((eb,yY)=>{var II=G2(),{pipeline:PI}=I("stream"),SY=x0(),jI=DE(),{through:xI}=DT(),wI=vA(),SI=wY()();function yI(_){this.cmd="connack",this.returnCode=_.returnCode,this.sessionPresent=_.sessionPresent}function vI(_,T){this.client=_,this.packet=T}var hI=[bI,gI,mI,dI,cI,pI,iE,lI],nE=["","unacceptable protocol version","identifier rejected","Server unavailable","bad user name or password","not authorized","keep alive limit exceeded"];function kI(_,T,A){clearTimeout(_._connectTimer),_._connectTimer=null,_.connecting=!0,_.broker.preConnect(_,T,E);function E(L,J){if(!L&&J===!0)setImmediate(fI,_,T,A);else _.connecting=!1,A(L)}}function fI(_,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(nE[L]);J.errorCode=L,iE({client:_,returnCode:L,sessionPresent:!1},A.bind(this,J));return}_.id=E||"aedes_"+SI(),_.clean=T.clean,_.version=T.protocolVersion,_._will=T.will,_.broker._series(new vI(_,T),hI,{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 bI(_,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=nE[_.returnCode]}else _.returnCode=5,L=Error(nE[_.returnCode]);L.errorCode=_.returnCode,_.client=A,iE(_,A.close.bind(A,T.bind(this,L)))}}function gI(_,T){if(this.packet.keepalive>0){let A=this.client;A._keepaliveInterval=this.packet.keepalive*1500+1,A._keepaliveTimer=II(function(){A.broker.emit("keepaliveTimeout",A),A.emit("error",Error("keep alive timeout"))},A._keepaliveInterval)}T()}function mI(_,T){let A=this.client;if(!this.packet.clean){A.broker.persistence.subscriptionsByClient({id:A.id,done:T,arg:_},uI);return}_.sessionPresent=!1,A.broker.persistence.cleanSubscriptions(A,T)}function uI(_,T,A){if(_)return A.done(_);A.arg.subs=T,A.done()}function dI(_,T){if(_.subs){wI(this.client,{subscriptions:_.subs},!0,T),_.sessionPresent=!!_.subs;return}_.sessionPresent=!1,T()}function cI(_,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 pI(_,T){let A=this.client;A.broker.registerClient(A),T()}function iE(_,T){let A=_.client||this.client,E=new yI(_);SY(A,E,function(L){if(!L)A.broker.emit("connackSent",E,A),A.connackSent=!0;T(L)})}function lI(_,T){let A=this.client,E=A.broker.persistence,L=E.outgoingStream(A);A.resume(),PI(L,xI(function(X,H,Z){let Y=new jI(X,A);Y.writeCallback=(K,$)=>Z(K),E.outgoingUpdate(A,Y,nI)}),T)}function nI(_,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 SY(T,A,E)}yY.exports=kI});var fY=W((_g,kY)=>{var hY=x0();function iI(_){this.cmd="puback",this.messageId=_.messageId}function aI(_){this.cmd="pubrec",this.messageId=_.messageId}var oI=[tI,sI];function rI(_,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(_,oI,T,A)}function sI(_,T){let A=this;switch(_.qos){case 2:A.broker.persistence.incomingStorePacket(A,_,function(E){if(E)return T(E);hY(A,new aI(_),T)});break;case 1:hY(A,new iI(_),function(E){if(E)return T(E);A.broker.publish(_,A,T)});break;case 0:A.broker.publish(_,A,T);break;default:}}function tI(_,T){this.broker.authorizePublish(this,_,T)}kY.exports=rI});var gY=W((Tg,bY)=>{function eI(_,T,A){_.broker.persistence.outgoingClearMessageId(_,T,function(L,J){_.broker.emit("ack",J,_),A(L)})}bY.exports=eI});var uY=W((Ag,mY)=>{var _P=x0();function TP(_,T){this.client=_,this.packet=T}function AP(_){this.cmd="pubcomp",this.messageId=_.messageId}var EP=[JP,XP,HP,ZP];function LP(_,T,A){_.broker._series(new TP(_,T),EP,{},A)}function JP(_,T){this.client.broker.persistence.incomingGetPacket(this.client,this.packet,E);function E(L,J){_.packet=J,T(L)}}function XP(_,T){this.client.broker.publish(_.packet,this.client,T)}function HP(_,T){_P(this.client,new AP(_.packet),T)}function ZP(_,T){this.client.broker.persistence.incomingDelPacket(this.client,_.packet,T)}mY.exports=LP});var pY=W((Eg,cY)=>{var dY=x0();function YP(_){this.cmd="pubrel",this.messageId=_.messageId}function KP(_,T,A){let E=new YP(T);if(_.clean){dY(_,E,A);return}_.broker.persistence.outgoingUpdate(_,E,L);function L(J){if(J)A(J);else dY(_,E,A)}}cY.exports=KP});var nY=W((Lg,lY)=>{var $P=x0(),GP={cmd:"pingresp"};function UP(_,T,A){_.broker.emit("ping",T,_),$P(_,GP,A)}lY.exports=UP});var oY=W((Jg,aY)=>{var WP=vY(),NP=vA(),QP=qE(),MP=fY(),VP=gY(),zP=uY(),FP=pY(),CP=nY();function OP(_,T,A){if(T.cmd==="connect"){if(_.connecting||_.connected){iY(_.conn,T,A);return}WP(_,T,A);return}if(!_.connecting&&!_.connected){iY(_.conn,T,A);return}switch(T.cmd){case"publish":MP(_,T,A);break;case"subscribe":NP(_,T,!1,A);break;case"unsubscribe":QP(_,T,A);break;case"pubcomp":case"puback":VP(_,T,A);break;case"pubrel":zP(_,T,A);break;case"pubrec":FP(_,T,A);break;case"pingreq":CP(_,T,A);break;case"disconnect":_._disconnected=!0,_.conn.destroy(),A();return;default:_.conn.destroy(),A();return}if(_._keepaliveInterval>0)_._keepaliveTimer.reschedule(_._keepaliveInterval)}function iY(_,T,A){_.destroy();let E=Error("Invalid protocol");E.info=T,A(E)}aY.exports=OP});var EK=W((Xg,AK)=>{var RP=SA(),DP=I("events"),BP=I("util"),qP=pZ(),sY=uT(),tY=x0(),IP=DE(),PP=vA(),eY=qE(),_K=oY(),{pipeline:jP}=I("stream"),{through:xP}=DT();AK.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=RP.parser(),this._parser.client=this,this._parser._queue=[],this._parser.on("packet",yP),this.once("connected",vP);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",TK),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=qP(this.conn,this.close.bind(this));let J=(X)=>{if(X.clientId===E.id&&X.nl)return;return wP(E,X)&&E.broker.authorizeForward(E,X)};this.deliver0=function(H,Z){let Y=J(H);if(Y)setImmediate(()=>{let K=new sY(Y,_);K.qos=0,tY(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 IP(Y,E),$=E.subscriptions[K.topic];if($&&($.qos||0)<K.qos)K.qos=$.qos;if(K.writeCallback=Z,E.clean||K.retain)rY(null,E,K);else _.persistence.outgoingUpdate(E,K,rY)});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 wP(_,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 rY(_,T,A){if(_)T.emit("error",_),A.writeCallback();else tY(T,A,function(E){if(E)T.emit("error",E);A.writeCallback()})}function SP(_){_.callback()}function TK(_){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(SP),this.broker.emit(this.id?"clientError":"connectionError",this,_),this.close()}BP.inherits(Z0,DP);Z0.prototype._onError=TK;Z0.prototype.publish=function(_,T){let A=new sY(_,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:_}}PP(this,_,!1,T)};Z0.prototype.unsubscribe=function(_,T){if(!_.unsubscriptions){if(!Array.isArray(_))_=[_];_={unsubscriptions:_}}eY(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,eY(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 yP(_){let T=this.client;if(T._parsingBatch++,T.connackSent||T._parsingBatch===1)_K(T,_,T._nextBatch);else if(this._queue.length<T.broker.queueLimit)this._queue.push(_);else this.emit("error",Error("Client queue limit reached"))}function vP(){let _=this._parser._queue;if(_){for(let T=0,A=_.length;T<A;T++)_K(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)}jP(A.outgoingStream(T),xP(E),_)};function X4(){}});var LK=W((Hg,hP)=>{hP.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 YK=W((Zg,ZK)=>{var kP=I("events"),fP=I("util"),bP=u5(),gP=y9(),{v4:mP}=f7(),uP=f8(),{pipeline:dP}=I("stream"),cP=uT(),pP=n7(),lP=e7(),nP=EK(),{$SYS_PREFIX:Y0,bulk:iP}=DT();ZK.exports=Z1.createBroker=Z1;var aP={concurrency:100,heartbeatInterval:60000,connectTimeout:30000,decodeProtocol:null,preConnect:Tj,authenticate:Aj,authorizePublish:Ej,authorizeSubscribe:Lj,authorizeForward:Jj,published:Xj,trustProxy:!1,trustedProxies:[],queueLimit:42,maxClientsIdLength:23,keepaliveLimit:0};function Z1(_){let T=this;if(!(this instanceof Z1))return new Z1(_);_=Object.assign({},aP,_),this.id=_.id||mP(),this.counter=0,this.queueLimit=_.queueLimit,this.connectTimeout=_.connectTimeout,this.keepaliveLimit=_.keepaliveLimit,this.maxClientsIdLength=_.maxClientsIdLength,this.mq=_.mq||lP({concurrency:_.concurrency,matchEmptyLevels:!0}),this.handle=function(K,$){return K.setMaxListeners(_.concurrency*2),new nP(T,K,$)},this.persistence=_.persistence||pP(),this.persistence.broker=this,this._parallel=bP(),this._series=gP(),this._enqueuers=uP(rP),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),dP(T.persistence.streamWill(T.brokers),iP(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}fP.inherits(Z1,kP);function JK(_,T){if(_.retain)this.broker.persistence.storeRetained(_,T);else T()}function XK(_,T){if(this.client)_.clientId=this.client.id;this.broker.mq.emit(_,T)}function oP(_,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 rP(){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(sP);let{packet:J,complete:X}=_;_.packet=null,_.complete=null,_.topic=null,L.persistence.outgoingEnqueueCombi(E,J,X),L._enqueuers.release(_)}}function sP(_){let T=_.topic.charCodeAt(0);return T!==43&&T!==35}function HK(_,T){this.broker.published(this.packet,this.client,T),this.broker.emit("publish",this.packet,this.client)}var tP=[JK,XK,HK],eP=[JK,oP,XK,HK];Z1.prototype.publish=function(_,T,A){if(typeof T==="function")A=T,T=null;let E=new cP(_,this),L=E.qos>0?eP:tP;this._series(new Hj(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 _j(_,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,_j,Object.keys(this.clients),A);function A(){T.emit("closed"),T.mq.close(_)}};Z1.prototype.version=LK().version;function Tj(_,T,A){A(null,!0)}function Aj(_,T,A,E){E(null,!0)}function Ej(_,T,A){if(T.topic.startsWith(Y0))return A(Error(Y0+" topic is reserved"));A(null)}function Lj(_,T,A){A(null,T)}function Jj(_,T){return T}function Xj(_,T,A){A(null)}function Hj(_,T,A){this.broker=_,this.client=T,this.packet=A}function s4(){}});var UK=W((Mg,GK)=>{GK.exports=Yj;function H4(_){if(_ instanceof Buffer)return Buffer.from(_);return new _.constructor(_.buffer.slice(),_.byteOffset,_.length)}function Yj(_){if(_=_||{},_.circles)return Kj(_);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 Kj(_){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 NK=W((Vg,WK)=>{WK.exports=UK()()});var VK=W((MK)=>{Object.defineProperty(MK,"__esModule",{value:!0});MK.validateTopic=QK;MK.validateTopics=$j;function QK(_){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 $j(_){if(_.length===0)return"empty_topic_list";for(let T=0;T<_.length;T++)if(!QK(_[T]))return _[T];return null}});var aE=W((FK)=>{Object.defineProperty(FK,"__esModule",{value:!0});var Wj=n0(),Nj={objectMode:!0},Qj={clean:!0};class zK{options;_inflights;constructor(_){this.options=_||{},this.options={...Qj,..._},this._inflights=new Map}put(_,T){if(this._inflights.set(_.messageId,_),T)T();return this}createStream(){let _=new Wj.Readable(Nj),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(_)_()}}FK.default=zK});var RK=W((OK)=>{Object.defineProperty(OK,"__esModule",{value:!0});var CK=[0,16,128,131,135,144,145,151,153],Vj=(_,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(CK.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(CK.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}};OK.default=Vj});var DK=W((Og,Fj)=>{Fj.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((BK)=>{Object.defineProperty(BK,"__esModule",{value:!0});BK.MQTTJS_VERSION=BK.nextTick=BK.ErrorWithSubackPacket=BK.ErrorWithReasonCode=void 0;BK.applyMixin=Cj;class oE extends Error{code;constructor(_,T){super(_);this.code=T,Object.setPrototypeOf(this,oE.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}BK.ErrorWithReasonCode=oE;class rE extends Error{packet;constructor(_,T){super(_);this.packet=T,Object.setPrototypeOf(this,rE.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}BK.ErrorWithSubackPacket=rE;function Cj(_,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))}BK.nextTick=typeof process?.nextTick==="function"?process.nextTick:(_)=>{setTimeout(_,0)};BK.MQTTJS_VERSION=DK().version});var e4=W((PK)=>{Object.defineProperty(PK,"__esModule",{value:!0});PK.ReasonCodes=void 0;var IK=qT();PK.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 qj=(_,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 IK.ErrorWithReasonCode(`Publish error: ${PK.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 IK.ErrorWithReasonCode(`Publish error: ${PK.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: ${PK.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")};PK.default=qj});var wK=W((xK)=>{Object.defineProperty(xK,"__esModule",{value:!0});var jK=qT(),Pj=e4(),jj=(_,T)=>{let{options:A}=_,E=A.protocolVersion,L=E===5?T.reasonCode:T.returnCode;if(E!==5){let J=new jK.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 jK.ErrorWithReasonCode(`Connection refused: ${Pj.ReasonCodes[L]}`,L);_.emit("error",H)}})};xK.default=jj});var bK=W((kK)=>{Object.defineProperty(kK,"__esModule",{value:!0});kK.LRUCache=void 0;var Z4=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,yK=new Set,sE=typeof process==="object"&&!!process?process:{},vK=(_,T,A,E)=>{typeof sE.emitWarning==="function"?sE.emitWarning(_,T,A,E):console.error(`[${A}] ${T}: ${_}`)},dA=globalThis.AbortController,SK=globalThis.AbortSignal;if(typeof dA>"u"){SK=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(E,L){this._onabort.push(L)}},dA=class{constructor(){T()}signal=new SK;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 _=sE.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",T=()=>{if(!_)return;_=!1,vK("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 wj=(_)=>!yK.has(_),qg=Symbol("type"),s0=(_)=>_&&_===Math.floor(_)&&_>0&&isFinite(_),hK=(_)=>!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=hK(_);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 tE{#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 S=T?hK(T):Array;if(!S)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 S(T),this.#Q=new S(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(wj("LRU_CACHE_UNBOUNDED"))yK.add("LRU_CACHE_UNBOUNDED"),vK("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",tE)}}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 dA,{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 dA}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 S=this.#v(_,R,F,V),l=S.__staleWhileFetching!==void 0&&A;if(z){if(z.fetch=f?"stale":"refresh",l&&f)z.returnedStale=!0}return l?S.__staleWhileFetching:S.__returned=S}}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)}}}kK.LRUCache=tE});var K0=W((uK)=>{Object.defineProperty(uK,"t",{value:!0});uK.ContainerIterator=uK.Container=uK.Base=void 0;class gK{constructor(_=0){this.iteratorType=_}equals(_){return this.o===_.o}}uK.ContainerIterator=gK;class eE{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}}uK.Base=eE;class mK extends eE{}uK.Container=mK});var nK=W((pK)=>{Object.defineProperty(pK,"t",{value:!0});pK.default=void 0;var vj=K0();class cK extends vj.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 hj=cK;pK.default=hj});var rK=W((aK)=>{Object.defineProperty(aK,"t",{value:!0});aK.default=void 0;var kj=K0();class iK extends kj.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 fj=iK;aK.default=fj});var _3=W((tK)=>{Object.defineProperty(tK,"t",{value:!0});tK.default=void 0;var bj=K0();class sK extends bj.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 gj=sK;tK.default=gj});var cA=W((A3)=>{Object.defineProperty(A3,"t",{value:!0});A3.default=void 0;var mj=K0();class T3 extends mj.Container{}var uj=T3;A3.default=uj});var $0=W((L3)=>{Object.defineProperty(L3,"t",{value:!0});L3.throwIteratorAccessError=dj;function dj(){throw RangeError("Iterator access denied!")}});var _L=W((X3)=>{Object.defineProperty(X3,"t",{value:!0});X3.RandomIterator=void 0;var pj=K0(),pA=$0();class J3 extends pj.ContainerIterator{constructor(_,T){super(T);if(this.o=_,this.iteratorType===0)this.pre=function(){if(this.o===0)(0,pA.throwIteratorAccessError)();return this.o-=1,this},this.next=function(){if(this.o===this.container.size())(0,pA.throwIteratorAccessError)();return this.o+=1,this};else this.pre=function(){if(this.o===this.container.size()-1)(0,pA.throwIteratorAccessError)();return this.o+=1,this},this.next=function(){if(this.o===-1)(0,pA.throwIteratorAccessError)();return this.o-=1,this}}get pointer(){return this.container.getElementByPos(this.o)}set pointer(_){this.container.setElementByPos(this.o,_)}}X3.RandomIterator=J3});var $3=W((Y3)=>{Object.defineProperty(Y3,"t",{value:!0});Y3.default=void 0;var lj=ij(cA()),nj=_L();function ij(_){return _&&_.t?_:{default:_}}class IT extends nj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new IT(this.o,this.container,this.iteratorType)}}class Z3 extends lj.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 aj=Z3;Y3.default=aj});var N3=W((U3)=>{Object.defineProperty(U3,"t",{value:!0});U3.default=void 0;var oj=sj(cA()),rj=K0(),PT=$0();function sj(_){return _&&_.t?_:{default:_}}class jT extends rj.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 G3 extends oj.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 tj=G3;U3.default=tj});var z3=W((M3)=>{Object.defineProperty(M3,"t",{value:!0});M3.default=void 0;var ej=Tx(cA()),_x=_L();function Tx(_){return _&&_.t?_:{default:_}}class xT extends _x.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new xT(this.o,this.container,this.iteratorType)}}class Q3 extends ej.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 Ax=Q3;M3.default=Ax});var R3=W((C3)=>{Object.defineProperty(C3,"t",{value:!0});C3.TreeNodeEnableIndex=C3.TreeNode=void 0;class TL{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}}C3.TreeNode=TL;class F3 extends TL{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}}C3.TreeNodeEnableIndex=F3});var AL=W((I3)=>{Object.defineProperty(I3,"t",{value:!0});I3.default=void 0;var D3=R3(),Lx=K0(),B3=$0();class q3 extends Lx.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=D3.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=D3.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,B3.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,B3.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 Jx=q3;I3.default=Jx});var EL=W((x3)=>{Object.defineProperty(x3,"t",{value:!0});x3.default=void 0;var Xx=K0(),lA=$0();class j3 extends Xx.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,lA.throwIteratorAccessError)();return this.o=this.o.L(),this},this.next=function(){if(this.o===this.h)(0,lA.throwIteratorAccessError)();return this.o=this.o.B(),this};else this.pre=function(){if(this.o===this.h.W)(0,lA.throwIteratorAccessError)();return this.o=this.o.B(),this},this.next=function(){if(this.o===this.h)(0,lA.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 Hx=j3;x3.default=Hx});var k3=W((v3)=>{Object.defineProperty(v3,"t",{value:!0});v3.default=void 0;var Zx=S3(AL()),Yx=S3(EL()),Kx=$0();function S3(_){return _&&_.t?_:{default:_}}class p1 extends Yx.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Kx.throwIteratorAccessError)();return this.o.u}copy(){return new p1(this.o,this.h,this.container,this.iteratorType)}}class y3 extends Zx.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 $x=y3;v3.default=$x});var u3=W((g3)=>{Object.defineProperty(g3,"t",{value:!0});g3.default=void 0;var Gx=f3(AL()),Ux=f3(EL()),Wx=$0();function f3(_){return _&&_.t?_:{default:_}}class l1 extends Ux.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Wx.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 b3 extends Gx.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 Nx=b3;g3.default=Nx});var LL=W((d3)=>{Object.defineProperty(d3,"t",{value:!0});d3.default=Qx;function Qx(_){let T=typeof _;return T==="object"&&_!==null||T==="function"}});var XL=W((n3)=>{Object.defineProperty(n3,"t",{value:!0});n3.HashContainerIterator=n3.HashContainer=void 0;var c3=K0(),JL=Vx(LL()),T8=$0();function Vx(_){return _&&_.t?_:{default:_}}class p3 extends c3.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}}}n3.HashContainerIterator=p3;class l3 extends c3.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,JL.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,JL.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,JL.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}}n3.HashContainer=l3});var t3=W((r3)=>{Object.defineProperty(r3,"t",{value:!0});r3.default=void 0;var a3=XL(),Fx=$0();class wT extends a3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Fx.throwIteratorAccessError)();return this.o.u}copy(){return new wT(this.o,this.h,this.container,this.iteratorType)}}class o3 extends a3.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 Cx=o3;r3.default=Cx});var E$=W((T$)=>{Object.defineProperty(T$,"t",{value:!0});T$.default=void 0;var e3=XL(),Ox=Dx(LL()),Rx=$0();function Dx(_){return _&&_.t?_:{default:_}}class ST extends e3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Rx.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 _$ extends e3.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,Ox.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 Bx=_$;T$.default=Bx});var L$=W((B1)=>{Object.defineProperty(B1,"t",{value:!0});Object.defineProperty(B1,"Deque",{enumerable:!0,get:function(){return Sx.default}});Object.defineProperty(B1,"HashMap",{enumerable:!0,get:function(){return kx.default}});Object.defineProperty(B1,"HashSet",{enumerable:!0,get:function(){return hx.default}});Object.defineProperty(B1,"LinkList",{enumerable:!0,get:function(){return xx.default}});Object.defineProperty(B1,"OrderedMap",{enumerable:!0,get:function(){return vx.default}});Object.defineProperty(B1,"OrderedSet",{enumerable:!0,get:function(){return yx.default}});Object.defineProperty(B1,"PriorityQueue",{enumerable:!0,get:function(){return Px.default}});Object.defineProperty(B1,"Queue",{enumerable:!0,get:function(){return Ix.default}});Object.defineProperty(B1,"Stack",{enumerable:!0,get:function(){return qx.default}});Object.defineProperty(B1,"Vector",{enumerable:!0,get:function(){return jx.default}});var qx=G0(nK()),Ix=G0(rK()),Px=G0(_3()),jx=G0($3()),xx=G0(N3()),Sx=G0(z3()),yx=G0(k3()),vx=G0(u3()),hx=G0(t3()),kx=G0(E$());function G0(_){return _&&_.t?_:{default:_}}});var X$=W((ag,J$)=>{var fx=L$().OrderedSet,U0=d1()("number-allocator:trace"),bx=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 fx([],(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){bx("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(_)};J$.exports=W0});var HL=W((mx,H$)=>{var gx=X$();mx.NumberAllocator=gx});var K$=W((Y$)=>{Object.defineProperty(Y$,"__esModule",{value:!0});var dx=bK(),cx=HL();class Z${aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(_){if(_>0)this.aliasToTopic=new dx.LRUCache({max:_}),this.topicToAlias={},this.numberAllocator=new cx.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]}}Y$.default=Z$});var $$=W((A8)=>{var lx=A8&&A8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(A8,"__esModule",{value:!0});var nx=e4(),ix=lx(K$()),ax=qT(),ox=(_,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 ix.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 ax.ErrorWithReasonCode(`Connection refused: ${nx.ReasonCodes[L]}`,L);if(_.emit("error",J),_.options.reconnectOnConnackError)_._cleanUp(!0)}};A8.default=ox});var U$=W((G$)=>{Object.defineProperty(G$,"__esModule",{value:!0});var rx=(_,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)})};G$.default=rx});var W$=W((E8)=>{var L8=E8&&E8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(E8,"__esModule",{value:!0});var tx=L8(RK()),ex=L8(wK()),_w=L8($$()),Tw=L8(e4()),Aw=L8(U$()),Ew=(_,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,tx.default)(_,T,A);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":_.reschedulePing(),(0,Tw.default)(_,T),A();break;case"pubrel":_.reschedulePing(),(0,Aw.default)(_,T,A);break;case"connack":(0,_w.default)(_,T),A();break;case"auth":_.reschedulePing(),(0,ex.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=Ew});var ZL=W((Q$)=>{Object.defineProperty(Q$,"__esModule",{value:!0});class N${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(){}}Q$.default=N$});var z$=W((V$)=>{Object.defineProperty(V$,"__esModule",{value:!0});class M${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={}}}V$.default=M$});var F$=W((K4)=>{var Xw=K4&&K4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(K4,"__esModule",{value:!0});K4.TypedEventEmitter=void 0;var Hw=Xw(I("events")),Zw=qT();class YL{}K4.TypedEventEmitter=YL;(0,Zw.applyMixin)(YL,Hw.default)});var J8=W((Am,y0)=>{function KL(_){return y0.exports=KL=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,KL(_)}y0.exports=KL,y0.exports.__esModule=!0,y0.exports.default=y0.exports});var O$=W((Em,X8)=>{var C$=J8().default;function Yw(_,T){if(C$(_)!="object"||!_)return _;var A=_[Symbol.toPrimitive];if(A!==void 0){var E=A.call(_,T||"default");if(C$(E)!="object")return E;throw TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(_)}X8.exports=Yw,X8.exports.__esModule=!0,X8.exports.default=X8.exports});var R$=W((Lm,H8)=>{var Kw=J8().default,$w=O$();function Gw(_){var T=$w(_,"string");return Kw(T)=="symbol"?T:T+""}H8.exports=Gw,H8.exports.__esModule=!0,H8.exports.default=H8.exports});var D$=W((Jm,Z8)=>{var Uw=R$();function Ww(_,T,A){return(T=Uw(T))in _?Object.defineProperty(_,T,{value:A,enumerable:!0,configurable:!0,writable:!0}):_[T]=A,_}Z8.exports=Ww,Z8.exports.__esModule=!0,Z8.exports.default=Z8.exports});var B$=W((Xm,Y8)=>{function Nw(_){if(Array.isArray(_))return _}Y8.exports=Nw,Y8.exports.__esModule=!0,Y8.exports.default=Y8.exports});var q$=W((Hm,K8)=>{function Qw(_,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=Qw,K8.exports.__esModule=!0,K8.exports.default=K8.exports});var I$=W((Zm,$8)=>{function Mw(_,T){(T==null||T>_.length)&&(T=_.length);for(var A=0,E=Array(T);A<T;A++)E[A]=_[A];return E}$8.exports=Mw,$8.exports.__esModule=!0,$8.exports.default=$8.exports});var j$=W((Ym,G8)=>{var P$=I$();function Vw(_,T){if(_){if(typeof _=="string")return P$(_,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)?P$(_,T):void 0}}G8.exports=Vw,G8.exports.__esModule=!0,G8.exports.default=G8.exports});var x$=W((Km,U8)=>{function zw(){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=zw,U8.exports.__esModule=!0,U8.exports.default=U8.exports});var w$=W(($m,W8)=>{var Fw=B$(),Cw=q$(),Ow=j$(),Rw=x$();function Dw(_,T){return Fw(_)||Cw(_,T)||Ow(_,T)||Rw()}W8.exports=Dw,W8.exports.__esModule=!0,W8.exports.default=W8.exports});var v$=W((S$)=>{Object.defineProperty(S$,"__esModule",{value:!0});S$.createAddUniqueNumber=void 0;var Bw=(_)=>{return(T)=>{let A=_(T);return T.add(A),A}};S$.createAddUniqueNumber=Bw});var f$=W((h$)=>{Object.defineProperty(h$,"__esModule",{value:!0});h$.createCache=void 0;var qw=(_)=>{return(T,A)=>{return _.set(T,A),A}};h$.createCache=qw});var c$=W((u$)=>{Object.defineProperty(u$,"__esModule",{value:!0});u$.createGenerateUniqueNumber=void 0;var b$=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,m$=536870912,g$=m$*2,Iw=(_,T)=>{return(A)=>{let E=T.get(A),L=E===void 0?A.size:E<g$?E+1:0;if(!A.has(L))return _(A,L);if(A.size<m$){while(A.has(L))L=Math.floor(Math.random()*g$);return _(A,L)}if(A.size>b$)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(A.has(L))L=Math.floor(Math.random()*b$);return _(A,L)}};u$.createGenerateUniqueNumber=Iw});var $L=W((l$)=>{Object.defineProperty(l$,"__esModule",{value:!0});l$.generateUniqueNumber=l$.addUniqueNumber=void 0;var Pw=v$(),jw=f$(),xw=c$(),p$=new WeakMap,ww=(0,jw.createCache)(p$),Sw=l$.generateUniqueNumber=(0,xw.createGenerateUniqueNumber)(ww,p$),Nm=l$.addUniqueNumber=(0,Pw.createAddUniqueNumber)(Sw)});var a$=W((Mm,N8)=>{function i$(_,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 vw(_){return function(){var T=this,A=arguments;return new Promise(function(E,L){var J=_.apply(T,A);function X(Z){i$(J,E,L,X,H,"next",Z)}function H(Z){i$(J,E,L,X,H,"throw",Z)}X(void 0)})}}N8.exports=vw,N8.exports.__esModule=!0,N8.exports.default=N8.exports});var GL=W((Vm,Q8)=>{function hw(_,T){this.v=_,this.k=T}Q8.exports=hw,Q8.exports.__esModule=!0,Q8.exports.default=Q8.exports});var UL=W((zm,v0)=>{function nA(_,T,A,E){var L=Object.defineProperty;try{L({},"",{})}catch(J){L=0}v0.exports=nA=function(X,H,Z,Y){function K($,G){nA(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,nA(_,T,A,E)}v0.exports=nA,v0.exports.__esModule=!0,v0.exports.default=v0.exports});var WL=W((Fm,h0)=>{var N0=UL();function o$(){/*! 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 S,g,l,c=0,W_=f||[],p_=!1,q_={p:0,n:0,v:_,a:C_,f:C_.bind(_,4),d:function(M_,I_){return S=M_,g=0,l=_,q_.n=I_,X}};function C_(K_,M_){for(g=K_,l=M_,T=0;!p_&&c&&!I_&&T<W_.length;T++){var I_,j_=W_[T],R0=q_.p,y1=j_[2];K_>3?(I_=y1===M_)&&(l=j_[(g=j_[4])?5:(g=3,3)],j_[4]=j_[5]=_):j_[0]<=R0&&((I_=K_<2&&R0<j_[1])?(g=0,q_.v=M_,q_.n=j_[1]):R0<y1&&(I_=K_<3||j_[0]>M_||M_>y1)&&(j_[4]=K_,j_[5]=M_,q_.n=y1,g=0))}if(I_||K_>1)return X;throw p_=!0,M_}return function(K_,M_,I_){if(c>1)throw TypeError("Generator is already running");for(p_&&M_===1&&C_(M_,I_),g=M_,l=I_;(T=g<2?_:l)||!p_;){S||(g?g<3?(g>1&&(q_.n=-1),C_(g,l)):q_.n=l:q_.v=l);try{if(c=2,S){if(g||(K_="next"),T=S[K_]){if(!(T=T.call(S,l)))throw TypeError("iterator result is not an object");if(!T.done)return T;l=T.value,g<2&&(g=0)}else g===1&&(T=S.return)&&T.call(S),g<2&&(l=TypeError("The iterator does not provide a '"+K_+"' method"),g=1);S=_}else if((T=(p_=q_.n<0)?l:R.call(q,q_))!==X)break}catch(j_){S=_,g=1,l=j_}finally{c=1}}return{value:T,done:p_}}}(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=o$=function(){return{w:J,m:G}},h0.exports.__esModule=!0,h0.exports.default=h0.exports)()}h0.exports=o$,h0.exports.__esModule=!0,h0.exports.default=h0.exports});var ML=W((Cm,M8)=>{var kw=GL(),NL=UL();function QL(_,T){function A(L,J,X,H){try{var Z=_[L](J),Y=Z.value;return Y instanceof kw?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||(NL(QL.prototype),NL(QL.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),NL(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=QL,M8.exports.__esModule=!0,M8.exports.default=M8.exports});var VL=W((Om,V8)=>{var fw=WL(),bw=ML();function gw(_,T,A,E,L){return new bw(fw().w(_,T,A,E),L||Promise)}V8.exports=gw,V8.exports.__esModule=!0,V8.exports.default=V8.exports});var r$=W((Rm,z8)=>{var mw=VL();function uw(_,T,A,E,L){var J=mw(_,T,A,E,L);return J.next().then(function(X){return X.done?X.value:J.next()})}z8.exports=uw,z8.exports.__esModule=!0,z8.exports.default=z8.exports});var s$=W((Dm,F8)=>{function dw(_){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=dw,F8.exports.__esModule=!0,F8.exports.default=F8.exports});var t$=W((Bm,C8)=>{var cw=J8().default;function pw(_){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(cw(_)+" is not iterable")}C8.exports=pw,C8.exports.__esModule=!0,C8.exports.default=C8.exports});var _G=W((qm,k0)=>{var lw=GL(),nw=WL(),iw=r$(),aw=VL(),ow=ML(),rw=s$(),e$=t$();function zL(){var _=nw(),T=_.m(zL),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,e$($),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=zL=function(){return{wrap:function(Z,Y,K,$){return _.w(J(Z),Y,K,$&&$.reverse())},isGeneratorFunction:E,mark:_.m,awrap:function(Z,Y){return new lw(Z,Y)},AsyncIterator:ow,async:function(Z,Y,K,$,G){return(E(Y)?aw:iw)(J(Z),Y,K,$,G)},keys:rw,values:e$}},k0.exports.__esModule=!0,k0.exports.default=k0.exports)()}k0.exports=zL,k0.exports.__esModule=!0,k0.exports.default=k0.exports});var AG=W((Im,TG)=>{var iA=_G()();TG.exports=iA;try{regeneratorRuntime=iA}catch(_){if(typeof globalThis==="object")globalThis.regeneratorRuntime=iA;else Function("r","regeneratorRuntime = r")(iA)}});var LG=W((aA,EG)=>{(function(_,T){typeof aA==="object"&&typeof EG<"u"?T(aA,D$(),w$(),$L(),a$(),AG()):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))})(aA,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 S,g,l,c;return J.wrap(function(W_){while(!0)switch(W_.prev=W_.next){case 0:return S=new MessageChannel,g=S.port1,l=S.port2,W_.next=1,q("connect",{port:g},[g]);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 S(g){var l;return J.wrap(function(c){while(!0)switch(c.prev=c.next){case 0:if(l=H.get(g),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()}},S)}));return function(S){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_)})},S=function(K_,M_){var I_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];R.postMessage({id:null,method:K_,params:M_},I_)},g={};for(var l=0,c=Object.entries(F);l<c.length;l++){var W_=A(c[l],2),p_=W_[0],q_=W_[1];g=G(G({},g),{},T({},p_,q_({call:f,notify:S})))}return G({},g)}};_.createBroker=N})});var XG=W((oA,JG)=>{(function(_,T){typeof oA==="object"&&typeof JG<"u"?T(oA,J8(),LG(),$L()):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))})(oA,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 ZG=W((rA,HG)=>{(function(_,T){typeof rA==="object"&&typeof HG<"u"?T(rA,XG()):typeof define==="function"&&define.amd?define(["exports","worker-timers-broker"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.workerTimers={},_.workerTimersBroker))})(rA,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(($G)=>{Object.defineProperty($G,"__esModule",{value:!0});$G.isReactNativeBrowser=$G.isWebWorker=void 0;var sw=()=>{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},YG=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),KG=()=>typeof navigator<"u"&&navigator.product==="ReactNative",tw=sw()||YG()||KG();$G.isWebWorker=YG();$G.isReactNativeBrowser=KG();$G.default=tw});var QG=W((f0)=>{var TS=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]}),AS=f0&&f0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),ES=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")TS(A,T,E[L])}return AS(A,T),A}}();Object.defineProperty(f0,"__esModule",{value:!0});var UG=ZG(),FL=ES(O8()),WG={set:UG.setInterval,clear:UG.clearInterval},NG={set:(_,T)=>setInterval(_,T),clear:(_)=>clearInterval(_)},LS=(_)=>{switch(_){case"native":return NG;case"worker":return WG;case"auto":default:return FL.default&&!FL.isWebWorker&&!FL.isReactNativeBrowser?WG:NG}};f0.default=LS});var CL=W((R8)=>{var JS=R8&&R8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(R8,"__esModule",{value:!0});var XS=JS(QG());class MG{_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,XS.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=MG});var tA=W((n1)=>{var HS=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]}),ZS=n1&&n1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),OG=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")HS(A,T,E[L])}return ZS(A,T),A}}(),t0=n1&&n1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(n1,"__esModule",{value:!0});var OL=t0(SA()),YS=n0(),VG=t0(NK()),KS=t0(d1()),zG=OG(VK()),$4=t0(aE()),$S=t0(W$()),GS=t0(ZL()),US=t0(z$()),D8=qT(),WS=F$(),NS=t0(CL()),FG=OG(O8()),RL=globalThis.setImmediate||((..._)=>{let T=_.shift();(0,D8.nextTick)(()=>{T(..._)})}),CG={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1000,connectTimeout:30000,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class sA extends WS.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 CG)if(typeof this.options[A]>"u")this.options[A]=CG[A];else this.options[A]=T[A];if(this.log=this.options.log||(0,KS.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",sA.VERSION),FG.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",FG.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:sA.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)OL.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=_,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new GS.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 US.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 YS.Writable,T=OL.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,$S.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=zG.validateTopics(J);if(X!==null)return RL(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 S=0;S<f.length;S+=1)U[S].qos=f[S]}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=zG.validateTopics(_);if(E!==null)return RL(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),RL(()=>{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,VG.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=OL.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,VG.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 NS.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=sA});var BG=W((DG)=>{Object.defineProperty(DG,"__esModule",{value:!0});var QS=HL();class RG{numberAllocator;lastId;constructor(){this.numberAllocator=new QS.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()}}DG.default=RG});var eA=W((jG)=>{Object.defineProperty(jG,"__esModule",{value:!0});jG.BufferedDuplex=void 0;jG.writev=IG;var VS=n0(),qG=I("buffer");function IG(_,T){let A=Array(_.length);for(let E=0;E<_.length;E++)if(typeof _[E].chunk==="string")A[E]=qG.Buffer.from(_[E].chunk,"utf8");else A[E]=_[E].chunk;this._write(qG.Buffer.concat(A),"binary",T)}class PG extends VS.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(_,T,A){super({objectMode:!0});if(this.proxy=T,this.socket=A,this.writeQueue=[],!_.objectMode)this._writev=IG.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)}}}jG.BufferedDuplex=PG});var B8=W((_T)=>{var BL=_T&&_T.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(_T,"__esModule",{value:!0});_T.streamBuilder=_T.browserStreamBuilder=void 0;var _5=I("buffer"),wG=BL(I("ws")),FS=BL(d1()),CS=n0(),OS=BL(O8()),DL=eA(),e0=(0,FS.default)("mqttjs:ws"),RS=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function SG(_,T){let A=`${_.protocol}://${_.hostname}:${_.port}${_.path}`;if(typeof _.transformWsUrl==="function")A=_.transformWsUrl(A,_,T);return A}function yG(_){let T=_;if(!_.port)if(_.protocol==="wss")T.port=443;else T.port=80;if(!_.path)T.path="/";if(!_.wsOptions)T.wsOptions={};if(!OS.default&&!_.forceNativeWebSocket&&_.protocol==="wss")RS.forEach((A)=>{if(Object.prototype.hasOwnProperty.call(_,A)&&!Object.prototype.hasOwnProperty.call(_.wsOptions,A))T.wsOptions[A]=_[A]});return T}function DS(_){let T=yG(_);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 BS(_,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 wG.default(T,[E],A.wsOptions);return L}function qS(_,T){let A=T.protocolId==="MQIsdp"&&T.protocolVersion===3?"mqttv3.1":"mqtt",E=SG(T,_),L;if(T.createWebsocket)L=T.createWebsocket(E,[A],T);else L=new WebSocket(E,[A]);return L.binaryType="arraybuffer",L}var IS=(_,T)=>{e0("streamBuilder");let A=yG(T);A.hostname=A.hostname||A.host||"localhost";let E=SG(A,_),L=BS(_,E,A),J=wG.default.createWebSocketStream(L,A.wsOptions);return J.url=E,L.on("close",()=>{J.destroy()}),J};_T.streamBuilder=IS;var PS=(_,T)=>{e0("browserStreamBuilder");let A,L=DS(T).browserBufferSize||524288,J=T.browserBufferTimeout||1000,X=!T.objectMode,H=qS(_,T),Z=K(T,N,z);if(!T.objectMode)Z._writev=DL.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 DL.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 CS.Transform({objectMode:Q.objectMode});return q._write=F,q._flush=R,q}function $(){if(e0("WebSocket onOpen"),A instanceof DL.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=_5.Buffer.from(F);else if(F instanceof Blob)F=_5.Buffer.from(await new Response(F).arrayBuffer());else F=_5.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=_5.Buffer.from(Q,"utf8");try{H.send(Q)}catch(q){return R(q)}R()}function z(Q){H.close(),Q()}return A};_T.browserStreamBuilder=PS});var bG=W((fG)=>{Object.defineProperty(fG,"__esModule",{value:!0});var vG=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."};fG.ERRORS=yT;function jS(_){if(!vG.Buffer.isEncoding(_))throw Error(yT.INVALID_ENCODING)}fG.checkEncoding=jS;function hG(_){return typeof _==="number"&&isFinite(_)&&yS(_)}fG.isFiniteInteger=hG;function kG(_,T){if(typeof _==="number"){if(!hG(_)||_<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 xS(_){kG(_,!1)}fG.checkLengthValue=xS;function wS(_){kG(_,!0)}fG.checkOffsetValue=wS;function SS(_,T){if(_<0||_>T.length)throw Error(yT.INVALID_TARGET_OFFSET)}fG.checkTargetOffset=SS;function yS(_){return typeof _==="number"&&isFinite(_)&&Math.floor(_)===_}function vS(_){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof vG.Buffer.prototype[_]>"u")throw Error(`Platform does not support Buffer.prototype.${_}.`)}fG.bigIntAndBufferInt64Check=vS});var uG=W((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});var e=bG(),gG=4096,dS="utf8";class qL{constructor(_){if(this.length=0,this._encoding=dS,this._writeOffset=0,this._readOffset=0,qL.isSmartBufferOptions(_)){if(_.encoding)e.checkEncoding(_.encoding),this._encoding=_.encoding;if(_.size)if(e.isFiniteInteger(_.size)&&_.size>0)this._buff=Buffer.allocUnsafe(_.size);else throw Error(e.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(_.buff)if(Buffer.isBuffer(_.buff))this._buff=_.buff,this.length=_.buff.length;else throw Error(e.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(gG)}else{if(typeof _<"u")throw Error(e.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(gG)}}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 e.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,_)}readBigInt64LE(_){return e.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 e.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,_,T)}insertBigInt64BE(_,T){return e.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,_,T)}writeBigInt64LE(_,T){return e.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,_,T)}insertBigInt64LE(_,T){return e.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 e.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,_)}readBigUInt64LE(_){return e.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 e.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,_,T)}insertBigUInt64BE(_,T){return e.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,_,T)}writeBigUInt64LE(_,T){return e.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,_,T)}insertBigUInt64LE(_,T){return e.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")e.checkLengthValue(_),A=Math.min(_,this.length-this._readOffset);else T=_,A=this.length-this._readOffset;if(typeof T<"u")e.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 e.checkOffsetValue(T),this._handleString(_,!0,T,A)}writeString(_,T,A){return this._handleString(_,!1,T,A)}readStringNT(_){if(typeof _<"u")e.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 e.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")e.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 e.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 e.checkOffsetValue(T),this.insertBuffer(_,T),this.insertUInt8(0,T+_.length),this}writeBufferNT(_,T){if(typeof T<"u")e.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(_){e.checkOffsetValue(_),e.checkTargetOffset(_,this),this._readOffset=_}get writeOffset(){return this._writeOffset}set writeOffset(_){e.checkOffsetValue(_),e.checkTargetOffset(_,this),this._writeOffset=_}get encoding(){return this._encoding}set encoding(_){e.checkEncoding(_),this._encoding=_}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(_){let T=typeof _==="string"?_:this._encoding;return e.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")e.checkEncoding(A),J=A;if(typeof E==="string")e.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")e.checkOffsetValue(T),A=T;if(A<0||A+_>this.length)throw Error(e.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(_,T){if(e.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 e.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(e.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);e.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}}mG.SmartBuffer=qL});var IL=W((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.SOCKS5_NO_ACCEPTABLE_AUTH=aG.SOCKS5_CUSTOM_AUTH_END=aG.SOCKS5_CUSTOM_AUTH_START=aG.SOCKS_INCOMING_PACKET_SIZES=aG.SocksClientState=aG.Socks5Response=aG.Socks5HostType=aG.Socks5Auth=aG.Socks4Response=aG.SocksCommand=aG.ERRORS=aG.DEFAULT_TIMEOUT=void 0;var pS=30000;aG.DEFAULT_TIMEOUT=pS;var lS={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"};aG.ERRORS=lS;var nS={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(_)=>_+7,Socks4Response:8};aG.SOCKS_INCOMING_PACKET_SIZES=nS;var dG;(function(_){_[_.connect=1]="connect",_[_.bind=2]="bind",_[_.associate=3]="associate"})(dG||(aG.SocksCommand=dG={}));var cG;(function(_){_[_.Granted=90]="Granted",_[_.Failed=91]="Failed",_[_.Rejected=92]="Rejected",_[_.RejectedIdent=93]="RejectedIdent"})(cG||(aG.Socks4Response=cG={}));var pG;(function(_){_[_.NoAuth=0]="NoAuth",_[_.GSSApi=1]="GSSApi",_[_.UserPass=2]="UserPass"})(pG||(aG.Socks5Auth=pG={}));var iS=128;aG.SOCKS5_CUSTOM_AUTH_START=iS;var aS=254;aG.SOCKS5_CUSTOM_AUTH_END=aS;var oS=255;aG.SOCKS5_NO_ACCEPTABLE_AUTH=oS;var lG;(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"})(lG||(aG.Socks5Response=lG={}));var nG;(function(_){_[_.IPv4=1]="IPv4",_[_.Hostname=3]="Hostname",_[_.IPv6=4]="IPv6"})(nG||(aG.Socks5HostType=nG={}));var iG;(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"})(iG||(aG.SocksClientState=iG={}))});var PL=W((sG)=>{Object.defineProperty(sG,"__esModule",{value:!0});sG.shuffleArray=sG.SocksClientError=void 0;class rG extends Error{constructor(_,T){super(_);this.options=T}}sG.SocksClientError=rG;function Hy(_){for(let T=_.length-1;T>0;T--){let A=Math.floor(Math.random()*(T+1));[_[T],_[A]]=[_[A],_[T]]}}sG.shuffleArray=Hy});var T5=W((_U)=>{Object.defineProperty(_U,"__esModule",{value:!0});_U.isInSubnet=Yy;_U.isCorrect=Ky;_U.numberToPaddedHex=eG;_U.stringToPaddedHex=$y;_U.testBit=Gy;function Yy(_){if(this.subnetMask<_.subnetMask)return!1;if(this.mask(_.subnetMask)===_.mask())return!0;return!1}function Ky(_){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===_&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function eG(_){return _.toString(16).padStart(2,"0")}function $y(_){return eG(parseInt(_,10))}function Gy(_,T){let{length:A}=_;if(T>A)return!1;let E=A-T;return _.substring(E,E+1)==="1"}});var jL=W((TU)=>{Object.defineProperty(TU,"__esModule",{value:!0});TU.RE_SUBNET_STRING=TU.RE_ADDRESS=TU.GROUPS=TU.BITS=void 0;TU.BITS=32;TU.GROUPS=4;TU.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;TU.RE_SUBNET_STRING=/\/\d{1,2}$/});var A5=W((LU)=>{Object.defineProperty(LU,"__esModule",{value:!0});LU.AddressError=void 0;class EU extends Error{constructor(_,T){super(_);this.name="AddressError",this.parseMessage=T}}LU.AddressError=EU});var xL=W((Q0)=>{var Cy=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]}),Oy=Q0&&Q0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),XU=Q0&&Q0.__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 Oy(T,_),T};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.Address4=void 0;var G4=XU(T5()),i1=XU(jL()),q8=A5();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 wL=W((HU)=>{Object.defineProperty(HU,"__esModule",{value:!0});HU.RE_URL_WITH_PORT=HU.RE_URL=HU.RE_ZONE_STRING=HU.RE_SUBNET_STRING=HU.RE_BAD_ADDRESS=HU.RE_BAD_CHARACTERS=HU.TYPES=HU.SCOPES=HU.GROUPS=HU.BITS=void 0;HU.BITS=128;HU.GROUPS=8;HU.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};HU.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"};HU.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;HU.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;HU.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;HU.RE_ZONE_STRING=/%.*$/;HU.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;HU.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var SL=W(($U)=>{Object.defineProperty($U,"__esModule",{value:!0});$U.spanAllZeroes=YU;$U.spanAll=Sy;$U.spanLeadingZeroes=yy;$U.simpleGroup=vy;function YU(_){return _.replace(/(0+)/g,'<span class="zero">$1</span>')}function Sy(_,T=0){return _.split("").map((E,L)=>`<span class="digit value-${E} position-${L+T}">${YU(E)}</span>`).join("")}function KU(_){return _.replace(/^(0+)/,'<span class="zero">$1</span>')}function yy(_){return _.split(":").map((A)=>KU(A)).join(":")}function vy(_,T=0){return _.split(":").map((E,L)=>{if(/group-v4/.test(E))return E;return`<span class="hover-group group-${L+T}">${KU(E)}</span>`})}});var GU=W((Y1)=>{var gy=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]}),my=Y1&&Y1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),uy=Y1&&Y1.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))gy(T,_,A)}return my(T,_),T};Object.defineProperty(Y1,"__esModule",{value:!0});Y1.ADDRESS_BOUNDARY=void 0;Y1.groupPossibilities=L5;Y1.padGroup=E5;Y1.simpleRegularExpression=cy;Y1.possibleElisions=py;var dy=uy(wL());function L5(_){return`(${_.join("|")})`}function E5(_){if(_.length<4)return`0{0,${4-_.length}}${_}`;return _}Y1.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function cy(_){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===dy.GROUPS-1?":":"";return L5([E5(L),X])}return E5(L)}).join(":"));return A.push(_.map(E5).join(":")),L5(A)}function py(_,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 L5(J)}});var QU=W((M0)=>{var ly=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]}),ny=M0&&M0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),H5=M0&&M0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))ly(T,_,A)}return ny(T,_),T};Object.defineProperty(M0,"__esModule",{value:!0});M0.Address6=void 0;var UU=H5(T5()),yL=H5(jL()),N_=H5(wL()),vL=H5(SL()),vT=xL(),hT=GU(),b0=A5(),J5=T5();function X5(_){if(!_)throw Error("Assertion failed.")}function iy(_){let T=/(\d+)(\d{3})/;while(T.test(_))_=_.replace(T,"$1,$2");return _}function ay(_){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 oy(_,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 WU(_){return parseInt(_,16).toString(16).padStart(4,"0")}function NU(_){return _&255}class k_{constructor(_,T){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=UU.isInSubnet,this.isCorrect=UU.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-(yL.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 iy((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=oy(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(yL.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(yL.RE_ADDRESS,this.address4.parsedAddress.map(ay).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(WU).join(":")}decimal(){return this.parsedAddress.map((_)=>parseInt(_,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(WU).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,J5.testBit)(X,15),Z=(0,J5.testBit)(X,14),Y=(0,J5.testBit)(X,8),K=(0,J5.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(NU)}static fromByteArray(_){return this.fromUnsignedByteArray(_.map(NU))}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 vL.simpleGroup(this.address).join(":");X5(typeof this.elidedGroups==="number"),X5(typeof this.elisionBegin==="number");let _=[],[T,A]=this.address.split("::");if(T.length)_.push(...vL.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(...vL.simpleGroup(A,this.elisionEnd));else _.push("");if(this.is4())X5(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(X5(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 hL=W((o_)=>{var ry=o_&&o_.__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]}),sy=o_&&o_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),ty=o_&&o_.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))ry(T,_,A)}return sy(T,_),T};Object.defineProperty(o_,"__esModule",{value:!0});o_.v6=o_.AddressError=o_.Address6=o_.Address4=void 0;var ey=xL();Object.defineProperty(o_,"Address4",{enumerable:!0,get:function(){return ey.Address4}});var _v=QU();Object.defineProperty(o_,"Address6",{enumerable:!0,get:function(){return _v.Address6}});var Tv=A5();Object.defineProperty(o_,"AddressError",{enumerable:!0,get:function(){return Tv.AddressError}});var Av=ty(SL());o_.v6={helpers:Av}});var DU=W((OU)=>{Object.defineProperty(OU,"__esModule",{value:!0});OU.ipToBuffer=OU.int32ToIpv4=OU.ipv4ToInt32=OU.validateSocksClientChainOptions=OU.validateSocksClientOptions=void 0;var _1=PL(),f_=IL(),Ev=I("stream"),kL=hL(),MU=I("net");function Lv(_,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(!zU(_.destination))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsDestination,_);if(!FU(_.proxy))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);if(VU(_.proxy,_),_.timeout&&!CU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_);if(_.existing_socket&&!(_.existing_socket instanceof Ev.Duplex))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsExistingSocket,_)}OU.validateSocksClientOptions=Lv;function Jv(_){if(_.command!=="connect")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommandChain,_);if(!zU(_.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(!FU(T))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);VU(T,_)}),_.timeout&&!CU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_)}OU.validateSocksClientChainOptions=Jv;function VU(_,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 zU(_){return _&&typeof _.host==="string"&&Buffer.byteLength(_.host)<256&&typeof _.port==="number"&&_.port>=0&&_.port<=65535}function FU(_){return _&&(typeof _.host==="string"||typeof _.ipaddress==="string")&&typeof _.port==="number"&&_.port>=0&&_.port<=65535&&(_.type===4||_.type===5)}function CU(_){return typeof _==="number"&&_>0}function Xv(_){return new kL.Address4(_).toArray().reduce((A,E)=>(A<<8)+E,0)>>>0}OU.ipv4ToInt32=Xv;function Hv(_){let T=_>>>24&255,A=_>>>16&255,E=_>>>8&255,L=_&255;return[T,A,E,L].join(".")}OU.int32ToIpv4=Hv;function Zv(_){if(MU.isIPv4(_)){let T=new kL.Address4(_);return Buffer.from(T.toArray())}else if(MU.isIPv6(_)){let T=new kL.Address6(_);return Buffer.from(T.canonicalForm().split(":").map((A)=>A.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}OU.ipToBuffer=Zv});var PU=W((qU)=>{Object.defineProperty(qU,"__esModule",{value:!0});qU.ReceiveBuffer=void 0;class BU{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}}qU.ReceiveBuffer=BU});var jU=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 Uv=I("events"),W4=I("net"),K1=uG(),P=IL(),W1=DU(),Wv=PU(),bL=PL();Object.defineProperty(TT,"SocksClientError",{enumerable:!0,get:function(){return bL.SocksClientError}});var fL=hL();class Z5 extends Uv.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 Z5(_);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,bL.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 Z5.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=fL.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 Wv.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 bL.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:fL.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:fL.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=Z5});var xU=W((kT)=>{var Nv=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]}),Qv=kT&&kT.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))Nv(T,_,A)};Object.defineProperty(kT,"__esModule",{value:!0});Qv(jU(),kT)});var mL=W((a1)=>{var Mv=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]}),Vv=a1&&a1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),zv=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")Mv(A,T,E[L])}return Vv(A,T),A}}(),wU=a1&&a1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(a1,"__esModule",{value:!0});a1.default=Pv;var Fv=wU(d1()),Cv=I("stream"),Ov=xU(),Rv=zv(I("dns")),Dv=I("util"),gL=wU(I("assert")),g0=(0,Fv.default)("mqttjs:socks");class SU extends Cv.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(_){if(g0("proxy stream started"),(0,gL.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,gL.default)(this._socket),this._socket.write(_,A)}_read(_){this._flowing=!0,this._socket?.resume?.()}_destroy(_,T){this._socket?.destroy?.(_),T(_)}_onData=(_)=>{if((0,gL.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 Y5(_){try{if(_.code===void 0)_.code="SOCKS";return _}catch{return _}}function Bv(_){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 qv(_){let T=new URL(_);if(T.pathname||T.hash||T.search)throw Y5(Error("bad SOCKS URL"));let[A,E]=Bv(T.protocol);if(!A)throw Y5(Error("bad SOCKS URL: invalid protocol"));let L=parseInt(T.port,10);if(Number.isNaN(L))throw Y5(Error("bad SOCKS URL: invalid port"));return[{host:T.hostname,port:L,type:A},E]}async function Iv(_,T,A,E,L={}){let J=L.lookup??(0,Dv.promisify)(Rv.lookup),[X,H]=qv(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 Ov.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(Y5(Y))})}function Pv(_,T,A,E){g0("SOCKS connection to %s:%d via %s",_,T,A);let L=new SU;return Iv(_,T,A,L,E).catch((J)=>{g0("SOCKS failed: %s",J),L.destroy(J)}),L}});var dL=W((I8)=>{var uL=I8&&I8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(I8,"__esModule",{value:!0});var jv=uL(I("net")),xv=uL(d1()),wv=uL(mL()),Sv=(0,xv.default)("mqttjs:tcp"),yv=(_,T)=>{if(T.port=T.port||1883,T.hostname=T.hostname||T.host||"localhost",T.socksProxy)return(0,wv.default)(T.hostname,T.port,T.socksProxy,{timeout:T.socksTimeout});let{port:A,path:E}=T,L=T.hostname;return Sv("port %d and host %s",A,L),jv.default.createConnection({port:A,host:L,path:E})};I8.default=yv});var pL=W((P8)=>{var cL=P8&&P8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(P8,"__esModule",{value:!0});var yU=I("tls"),vv=cL(I("net")),hv=cL(d1()),kv=cL(mL()),fv=(0,hv.default)("mqttjs:tls");function bv(_){let{host:T,port:A,socksProxy:E,...L}=_;if(E!==void 0){let J=(0,kv.default)(T,A,E,{timeout:_.socksTimeout});return(0,yU.connect)({...L,socket:J})}return(0,yU.connect)(_)}var gv=(_,T)=>{if(T.port=T.port||8883,T.host=T.hostname||T.host||"localhost",vv.default.isIP(T.host)===0)T.servername=T.host;T.rejectUnauthorized=T.rejectUnauthorized!==!1,delete T.path,fv("port %d host %s rejectUnauthorized %b",T.port,T.host,T.rejectUnauthorized);let A=bv(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=gv});var nL=W((hU)=>{Object.defineProperty(hU,"__esModule",{value:!0});var vU=I("buffer"),mv=n0(),uv=eA(),V0,lL,N1;function dv(){let _=new mv.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 cv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function pv(_,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 lv(){V0.onOpen(()=>{N1.socketReady()}),V0.onMessage((_)=>{let{data:T}=_;if(T instanceof ArrayBuffer)T=vU.Buffer.from(T);else T=vU.Buffer.from(T,"utf8");lL.push(T)}),V0.onClose(()=>{N1.emit("close"),N1.end(),N1.destroy()}),V0.onError((_)=>{let T=Error(_.errMsg);N1.destroy(T)})}var nv=(_,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";cv(T);let E=pv(T,_);V0=wx.connectSocket({url:E,protocols:[A]}),lL=dv(),N1=new uv.BufferedDuplex(T,lL,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},lv(),N1};hU.default=nv});var aL=W((fU)=>{Object.defineProperty(fU,"__esModule",{value:!0});var iL=I("buffer"),av=n0(),ov=eA(),m0,j8,N4,kU=!1;function rv(){let _=new av.Transform;return _._write=(T,A,E)=>{m0.sendSocketMessage({data:T.buffer,success(){E()},fail(){E(Error())}})},_._flush=(T)=>{m0.closeSocket({success(){T()}})},_}function sv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function tv(_,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 ev(){if(kU)return;kU=!0,m0.onSocketOpen(()=>{N4.socketReady()}),m0.onSocketMessage((_)=>{if(typeof _.data==="string"){let T=iL.Buffer.from(_.data,"base64");j8.push(T)}else{let T=new FileReader;T.addEventListener("load",()=>{if(T.result instanceof ArrayBuffer){j8.push(iL.Buffer.from(T.result));return}j8.push(iL.Buffer.from(T.result,"utf-8"))}),T.readAsArrayBuffer(_.data)}}),m0.onSocketClose(()=>{N4.end(),N4.destroy()}),m0.onSocketError((_)=>{N4.destroy(_)})}var _h=(_,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";sv(T);let E=tv(T,_);return m0=T.my,m0.connectSocket({url:E,protocols:A}),j8=rv(),N4=new ov.BufferedDuplex(T,j8,m0),ev(),N4};fU.default=_h});var uU=W((Q4)=>{var K5=Q4&&Q4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(Q4,"__esModule",{value:!0});Q4.connectAsync=Xh;var Ah=K5(d1()),Eh=K5(I("url")),Lh=K5(tA()),bU=K5(O8());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var gU=(0,Ah.default)("mqttjs"),y_=null;function Jh(_){let T;if(_.auth)if(T=_.auth.match(/^(.+):(.+)$/),T){let[,A,E]=T;_.username=A,_.password=E}else _.username=_.auth}function mU(_,T){if(gU("connecting to an MQTT broker..."),typeof _==="object"&&!T)T=_,_="";if(T=T||{},_&&typeof _==="string"){let L=Eh.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(Jh(T),T.query&&typeof T.query.clientId==="string")T.clientId=T.query.clientId;if(bU.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_={},!bU.default&&!T.forceNativeWebSocket)y_.ws=B8().streamBuilder,y_.wss=B8().streamBuilder,y_.mqtt=dL().default,y_.tcp=dL().default,y_.ssl=pL().default,y_.tls=y_.ssl,y_.mqtts=pL().default;else y_.ws=B8().browserStreamBuilder,y_.wss=B8().browserStreamBuilder,y_.wx=nL().default,y_.wxs=nL().default,y_.ali=aL().default,y_.alis=aL().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 gU("calling streambuilder for",T.protocol),y_[T.protocol](L,T)}let E=new Lh.default(A,T);return E.on("error",()=>{}),E}function Xh(_,T,A=!0){return new Promise((E,L)=>{let J=mU(_,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=mU});var oL=W((Z_)=>{var dU=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]}),Hh=Z_&&Z_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Zh=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")dU(A,T,E[L])}return Hh(A,T),A}}(),cU=Z_&&Z_.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))dU(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 pU=x8(tA());Z_.MqttClient=pU.default;var Yh=x8(ZL());Z_.DefaultMessageIdProvider=Yh.default;var Kh=x8(BG());Z_.UniqueMessageIdProvider=Kh.default;var $h=x8(aE());Z_.Store=$h.default;var lU=Zh(uU());Z_.connect=lU.default;Object.defineProperty(Z_,"connectAsync",{enumerable:!0,get:function(){return lU.connectAsync}});var Gh=x8(CL());Z_.KeepaliveManager=Gh.default;Z_.Client=pU.default;cU(tA(),Z_);cU(qT(),Z_);var Uh=e4();Object.defineProperty(Z_,"ReasonCodes",{enumerable:!0,get:function(){return Uh.ReasonCodes}})});var iU=W((q1)=>{var nU=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]}),Wh=q1&&q1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Nh=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")nU(A,T,E[L])}return Wh(A,T),A}}(),Qh=q1&&q1.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))nU(T,_,A)};Object.defineProperty(q1,"__esModule",{value:!0});var Mh=Nh(oL());q1.default=Mh;Qh(oL(),q1)});var eL=W((hu,_W)=>{_W.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var EW=W((ku,AW)=>{var Dh=eL();function TW(_){this.mode=Dh.MODE_8BIT_BYTE,this.data=_}TW.prototype={getLength:function(){return this.data.length},write:function(_){for(var T=0;T<this.data.length;T++)_.put(this.data.charCodeAt(T),8)}};AW.exports=TW});var _9=W((fu,LW)=>{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_;LW.exports=o1});var T9=W((bu,JW)=>{var fT=_9();function M5(_,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]}M5.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 M5(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 M5(A,0).mod(_)}};JW.exports=M5});var HW=W((gu,XW)=>{XW.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var KW=W((mu,YW)=>{var P1=eL(),ZW=T9(),Bh=_9(),AT=HW(),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 ZW([1],0);for(var A=0;A<_;A++)T=T.multiply(new ZW([1,Bh.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 $=Math.abs(100*K/T/T-50)/5;return A+=$*10,A}};YW.exports=u_});var A9=W((uu,$W)=>{$W.exports={L:1,M:0,Q:3,H:2}});var UW=W((du,GW)=>{var V5=A9();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 V5.L:return z0.RS_BLOCK_TABLE[(_-1)*4+0];case V5.M:return z0.RS_BLOCK_TABLE[(_-1)*4+1];case V5.Q:return z0.RS_BLOCK_TABLE[(_-1)*4+2];case V5.H:return z0.RS_BLOCK_TABLE[(_-1)*4+3];default:return}};GW.exports=z0});var QW=W((cu,NW)=>{function WW(){this.buffer=[],this.length=0}WW.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++}};NW.exports=WW});var FW=W((pu,zW)=>{var qh=EW(),ET=KW(),Ih=T9(),MW=UW(),VW=QW();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 qh(_);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=MW.getRSBlocks(_,this.errorCorrectLevel),A=new VW,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=MW.getRSBlocks(_,T),L=new VW;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 Ih(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 S=0;S<L;S++)for(var g=0;g<T.length;g++)if(S<X[g].length)F[R++]=X[g][S];return F};zW.exports=F0});var RW=W((lu,OW)=>{var Ph=FW(),CW=A9(),jh="\x1B[40m \x1B[0m",z5="\x1B[47m \x1B[0m",xh=function(_){return _?jh:z5},E9=function(_){return{times:function(T){return Array(T).join(_)}}},wh=function(_,T){var A=Array(_);for(var E=0;E<_;E++)A[E]=T;return A};OW.exports={error:CW.L,generate:function(_,T,A){if(typeof T==="function")A=T,T={};var E=new Ph(-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(wh(H,X));var K={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},$=E9(K.BLACK_WHITE).times(H+3),G=E9(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+=G}else{var N=T9(z5).times(E.getModuleCount()+3);L+=N+`
17
- `,E.modules.forEach(function(z){L+=z5,L+=z.map(jh).join(""),L+=z5+`
18
- `}),L+=N}if(A)A(L);else console.log(L)},setErrorLevel:function(_){this.error=CW[_]||this.error}}});import{readFileSync as M9}from"fs";import{join as V9}from"path";function G1(){return"2.0.0-alpha.6"}function v5(_){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(_){let T=v5(_);if(!T.preRelease)return"stable";if(T.preRelease.startsWith("alpha"))return"alpha";return"beta"}function h5(_,T){try{let A=v5(_),E=v5(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 IN}from"util";var PN={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 z9(){let _=IN({options:PN,allowPositionals:!1,strict:!0});if(_.values.version)console.log(`ccc v${G1()}`),process.exit(0);if(_.values.help)jN(),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 jN(){console.log(`
16
+ `}if(!Y)L+=G}else{var N=E9(z5).times(E.getModuleCount()+3);L+=N+`
17
+ `,E.modules.forEach(function(z){L+=z5,L+=z.map(xh).join(""),L+=z5+`
18
+ `}),L+=N}if(A)A(L);else console.log(L)},setErrorLevel:function(_){this.error=CW[_]||this.error}}});import{readFileSync as M9}from"fs";import{join as V9}from"path";function G1(){return"2.0.0-alpha.8"}function k5(_){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(_){let T=k5(_);if(!T.preRelease)return"stable";if(T.preRelease.startsWith("alpha"))return"alpha";return"beta"}function f5(_,T){try{let A=k5(_),E=k5(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 PN}from"util";var jN={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 z9(){let _=PN({options:jN,allowPositionals:!1,strict:!0});if(_.values.version)console.log(`ccc v${G1()}`),process.exit(0);if(_.values.help)xN(),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 xN(){console.log(`
19
19
  Backend v2 - Clean modular architecture
20
20
 
21
21
  Usage:
@@ -34,15 +34,15 @@ Options:
34
34
  --auto-update-check-interval <min> Check interval in minutes (default: 60)
35
35
  -v, --version Show version
36
36
  -h, --help Show this help message
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 h8 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 k5 extends B4{constructor(_){super(_,"ROUTER_ERROR",500);this.name="RouterError"}}class k8 extends B4{constructor(_="Authentication failed"){super(_,"AUTH_ERROR",401);this.name="AuthenticationError"}}function F9(_){return xN(_),wN(_),{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 xN(_){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 wN(_){if(_.ngrokToken&&(!_.username||!_.password))throw new q4("Error: MQTT authentication (--username and --password) is required when using ngrok tunnels for security.")}class f5{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 C9(_=!1){return I4=new f5(_),I4}function h(){if(!I4)I4=new f5(!1);return I4}import*as d0 from"fs";import*as mT from"path";var SN={FULL_WIDTH:0,FITTING:1,SMUSHING:2,CONTROLLED_SMUSHING:3};class O9{constructor(){this.comment="",this.numChars=0,this.options={}}}var b5=["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 yN(_){return/[.*+?^${}()|[\]\\]/.test(_)?"\\"+_:_}var R9=(()=>{let{FULL_WIDTH:_=0,FITTING:T,SMUSHING:A,CONTROLLED_SMUSHING:E}=SN,L={},J={font:"Standard",fontPath:"./fonts",fetchFontIfMissing:!0};function X(O,D,M){let C=yN(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,f;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(f=!1,f=M.fittingRules&&M.fittingRules.vRule1?V(w,y):f,f=!f&&M.fittingRules&&M.fittingRules.vRule2?N(w,y):f,f=!f&&M.fittingRules&&M.fittingRules.vRule3?z(w,y):f,f=!f&&M.fittingRules&&M.fittingRules.vRule4?Q(w,y):f,S=!0,!f)return"invalid"}if(S)return"end";else return"valid"}function b(O,D,M){let{length:C,length:j}=O,w,y,S,f=1,d,o,a;while(f<=C){w=O.slice(Math.max(0,j-f),j),y=D.slice(0,Math.min(C,f)),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"){f--;break}if(a==="end")break;if(a==="valid")f++}return Math.min(C,f)}function k(O,D,M){let C,j=Math.min(O.length,D.length),w,y,S="",f,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 f=!1,f=d.vRule5?F(w,y):f,f=!f&&d.vRule1?V(w,y):f,f=!f&&d.vRule2?N(w,y):f,f=!f&&d.vRule3?z(w,y):f,f=!f&&d.vRule4?Q(w,y):f,S+=f;else S+=R(w,y);return S}function g(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),f=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=k(S[d],f[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=b(O,D,M),g(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,f=1,d=!1,o,a,r,T_;if(w===0)return 0;_:while(f<=S){let v1=w-f;o=O.substring(v1,v1+f),a=D.substring(0,Math.min(f,y));for(j=0;j<Math.min(f,y);j++)if(r=o.substring(j,j+1),T_=a.substring(j,j+1),r!==" "&&T_!==" "){if(C.hLayout===T){f=f-1;break _}else if(C.hLayout===A){if(r===M.hardBlank||T_===M.hardBlank)f=f-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))){f=f-1;break _}}if(d)break;f++}return Math.min(S,f)}function c_(O,D,M,C){let j,w,y=[],S,f,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,f=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 ON=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+=ON}else d+=R(M1,L1,C.hardBlank)}if(M>=r)o="";else o=v1.substring(M,M+Math.max(0,r-M));y[j]=f+d+o}return y}function q_(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)},q_(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:q_(D),chars:O}}function I_(O,D,M){let C,j,w=0,y,S,f,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=q_(d);let M1=M.fittingRules||{};if(M.printDirection===1)O=O.split("").reverse().join("");f=O.length;for(C=0;C<f;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=q_(d);T_=[]}else o.push(S),S=q_(d)}if(M.width>0&&M.whitespaceBreak){if(!E1||C===f-1)r.chars.push({fig:j,overlap:w});if(E1||C===f-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=q_(d);if(C===f-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){f=L1.length;for(y=0;y<f;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
+ `)}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 h8 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 b5 extends B4{constructor(_){super(_,"ROUTER_ERROR",500);this.name="RouterError"}}class k8 extends B4{constructor(_="Authentication failed"){super(_,"AUTH_ERROR",401);this.name="AuthenticationError"}}function F9(_){return wN(_),SN(_),{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,mqttPort:_.mqttPort,terminalPort:_.terminalPort,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 wN(_){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 SN(_){if(_.ngrokToken&&(!_.username||!_.password))throw new q4("Error: MQTT authentication (--username and --password) is required when using ngrok tunnels for security.")}class g5{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 C9(_=!1){return I4=new g5(_),I4}function k(){if(!I4)I4=new g5(!1);return I4}import*as d0 from"fs";import*as mT from"path";var yN={FULL_WIDTH:0,FITTING:1,SMUSHING:2,CONTROLLED_SMUSHING:3};class O9{constructor(){this.comment="",this.numChars=0,this.options={}}}var m5=["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 vN(_){return/[.*+?^${}()|[\]\\]/.test(_)?"\\"+_:_}var R9=(()=>{let{FULL_WIDTH:_=0,FITTING:T,SMUSHING:A,CONTROLLED_SMUSHING:E}=yN,L={},J={font:"Standard",fontPath:"./fonts",fetchFontIfMissing:!0};function X(O,D,M){let C=vN(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,v,y]of j)if(C>=w){if(C-=w,M[v]===void 0)M[v]=y}else if(v!=="vLayout"&&v!=="hLayout")M[v]=!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),v=w+1;return M.substring(w,v)}}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,v,y=!1,b;if(j===0)return"invalid";for(C=0;C<j;C++)if(w=O.substring(C,C+1),v=D.substring(C,C+1),w!==" "&&v!==" ")if(M.fittingRules&&M.fittingRules.vLayout===T)return"invalid";else if(M.fittingRules&&M.fittingRules.vLayout===A)return"end";else{if(F(w,v)){y=y||!1;continue}if(b=!1,b=M.fittingRules&&M.fittingRules.vRule1?V(w,v):b,b=!b&&M.fittingRules&&M.fittingRules.vRule2?N(w,v):b,b=!b&&M.fittingRules&&M.fittingRules.vRule3?z(w,v):b,b=!b&&M.fittingRules&&M.fittingRules.vRule4?Q(w,v):b,y=!0,!b)return"invalid"}if(y)return"end";else return"valid"}function f(O,D,M){let{length:C,length:j}=O,w,v,y,b=1,d,o,a;while(b<=C){w=O.slice(Math.max(0,j-b),j),v=D.slice(0,Math.min(C,b)),y=v.length,a="";for(d=0;d<y;d++)if(o=q(w[d],v[d],M),o==="end")a=o;else if(o==="invalid"){a=o;break}else if(a==="")a="valid";if(a==="invalid"){b--;break}if(a==="end")break;if(a==="valid")b++}return Math.min(C,b)}function S(O,D,M){let C,j=Math.min(O.length,D.length),w,v,y="",b,d=M.fittingRules||{};for(C=0;C<j;C++)if(w=O.substring(C,C+1),v=D.substring(C,C+1),w!==" "&&v!==" ")if(d.vLayout===T)y+=R(w,v);else if(d.vLayout===A)y+=R(w,v);else b=!1,b=d.vRule5?F(w,v):b,b=!b&&d.vRule1?V(w,v):b,b=!b&&d.vRule2?N(w,v):b,b=!b&&d.vRule3?z(w,v):b,b=!b&&d.vRule4?Q(w,v):b,y+=b;else y+=R(w,v);return y}function g(O,D,M,C){let j=O.length,w=D.length,v=O.slice(0,Math.max(0,j-M)),y=O.slice(Math.max(0,j-M),j),b=D.slice(0,Math.min(M,w)),d,o,a,s=[],T_;o=y.length;for(d=0;d<o;d++){if(d>=w)a=y[d];else a=S(y[d],b[d],C);s.push(a)}return T_=D.slice(Math.min(M,w),w),[...v,...s,...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),g(O,D,w,M)}function W_(O,D,M){let C=M.fittingRules||{};if(C.hLayout===_)return 0;let j,w=O.length,v=D.length,y=w,b=1,d=!1,o,a,s,T_;if(w===0)return 0;_:while(b<=y){let v1=w-b;o=O.substring(v1,v1+b),a=D.substring(0,Math.min(b,v));for(j=0;j<Math.min(b,v);j++)if(s=o.substring(j,j+1),T_=a.substring(j,j+1),s!==" "&&T_!==" "){if(C.hLayout===T){b=b-1;break _}else if(C.hLayout===A){if(s===M.hardBlank||T_===M.hardBlank)b=b-1;break _}else if(d=!0,!(C.hRule1&&Z(s,T_,M.hardBlank)||C.hRule2&&Y(s,T_)||C.hRule3&&K(s,T_)||C.hRule4&&$(s,T_)||C.hRule5&&G(s,T_)||C.hRule6&&U(s,T_,M.hardBlank))){b=b-1;break _}}if(d)break;b++}return Math.min(y,b)}function p_(O,D,M,C){let j,w,v=[],y,b,d,o,a,s,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,s=v1.length,y=a-M,b=T_.slice(0,Math.max(0,y)),d="";let D4=Math.max(0,a-M),h1=T_.substring(D4,D4+M),JT=v1.substring(0,Math.min(M,s));for(w=0;w<M;w++){let Q1=w<a?h1.substring(w,w+1):" ",L1=w<s?JT.substring(w,w+1):" ";if(Q1!==" "&&L1!==" ")if(E1.hLayout===T||E1.hLayout===A)d+=R(Q1,L1,C.hardBlank);else{let RN=E1.hRule1&&Z(Q1,L1,C.hardBlank)||E1.hRule2&&Y(Q1,L1)||E1.hRule3&&K(Q1,L1)||E1.hRule4&&$(Q1,L1)||E1.hRule5&&G(Q1,L1)||E1.hRule6&&U(Q1,L1,C.hardBlank)||R(Q1,L1,C.hardBlank);d+=RN}else d+=R(Q1,L1,C.hardBlank)}if(M>=s)o="";else o=v1.substring(M,M+Math.max(0,s-M));v[j]=b+d+o}return v}function q_(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 p_(C,j.fig,j.overlap||0,M)},q_(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:q_(D),chars:O}}function I_(O,D,M){let C,j,w=0,v,y,b,d=M.height,o=[],a,s={chars:[],overlap:w},T_=[],v1,E1,D4,h1,JT;if(typeof d!=="number")throw Error("height is not defined.");y=q_(d);let Q1=M.fittingRules||{};if(M.printDirection===1)O=O.split("").reverse().join("");b=O.length;for(C=0;C<b;C++)if(v1=O.substring(C,C+1),E1=v1.match(/\s/),j=D[v1.charCodeAt(0)],h1=null,j){if(Q1.hLayout!==_){w=1e4;for(v=0;v<d;v++)w=Math.min(w,W_(y[v],j[v],M));w=w===1e4?0:w}if(M.width>0){if(M.whitespaceBreak)D4=K_(s.chars.concat([{fig:j,overlap:w}]),d,M),h1=K_(T_.concat([{fig:D4,overlap:s.overlap}]),d,M),a=C_(h1);else h1=p_(y,j,w,M),a=C_(h1);if(a>=M.width&&C>0)if(M.whitespaceBreak){if(y=K_(T_.slice(0,-1),d,M),T_.length>1)o.push(y),y=q_(d);T_=[]}else o.push(y),y=q_(d)}if(M.width>0&&M.whitespaceBreak){if(!E1||C===b-1)s.chars.push({fig:j,overlap:w});if(E1||C===b-1){JT=null;while(!0)if(h1=K_(s.chars,d,M),a=C_(h1),a>=M.width)JT=M_(s.chars,d,M),s={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:s.overlap});if(E1)T_.push({fig:j,overlap:w}),y=q_(d);if(C===b-1)y=K_(T_,d,M);s={chars:[],overlap:w};continue}}y=p_(y,j,w,M)}if(C_(y)>0)o.push(y);if(!M.showHardBlanks)o.forEach(function(L1){b=L1.length;for(v=0;v<b;v++)L1[v]=L1[v].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,`
38
38
  `).replace(/\r/g,`
39
39
  `);let C=M.split(`
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 N9(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,N9(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=N9(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,`
40
+ `),j=[],w,v,y;v=C.length;for(w=0;w<v;w++)j=j.concat(I_(C[w],L[O],D));v=j.length,y=j[0];for(w=1;w<v;w++)y=c(y,j[w],D);return y?y.join(`
41
+ `):""};function N9(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 v=await P_.loadFont(w),y=v?y1(w,N9(v,C),O):"";if(j)j(null,y);return y}catch(v){let y=v instanceof Error?v:Error(String(v));if(j)return j(y),"";throw y}},P_.textSync=function(O,D){if(O=O+"",typeof D==="string")D={font:D};else D=D||{};let M=D.font||J.font,C=N9(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,`
42
42
  `).replace(/\r/g,`
43
43
  `);let C=new O9,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(b5),O)O(null,b5)})},P_.fontsSync=function(){return b5},P_.figFonts=L,P_})();import{fileURLToPath as vN}from"url";var hN=vN(import.meta.url),kN=mT.dirname(hN),fN=mT.join(kN,"/../fonts/"),x_=R9;x_.defaults({fontPath:fN});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 D9=`flf2a$ 6 5 16 15 13 0 24463 229
44
+ `),w=j.shift();if(!w)throw Error("Invalid font file: missing header");let v=w.split(" "),y={hardBlank:v[0].substring(5,6),height:parseInt(v[1],10),baseline:parseInt(v[2],10),maxLength:parseInt(v[3],10),oldLayout:parseInt(v[4],10),numCommentLines:parseInt(v[5],10),printDirection:v[6]?parseInt(v[6],10):0,fullLayout:v[7]?parseInt(v[7],10):null,codeTagCount:v[8]?parseInt(v[8],10):null};if((y.hardBlank||"").length!==1||[y.height,y.baseline,y.maxLength,y.oldLayout,y.numCommentLines].some((o)=>o===null||o===void 0||isNaN(o)))throw Error("FIGlet header contains invalid values.");if(y.height==null||y.numCommentLines==null)throw Error("FIGlet header contains invalid values.");y.fittingRules=H(y.oldLayout,y.fullLayout),C.options=y;let d=[];for(let o=32;o<=126;o++)d.push(o);if(d.push(196,214,220,228,246,252,223),j.length<y.numCommentLines+y.height*d.length)throw Error(`FIGlet file is missing data. Line length: ${j.length}. Comment lines: ${y.numCommentLines}. Height: ${y.height}. Num chars: ${d.length}.`);C.comment=j.splice(0,y.numCommentLines).join(`
45
+ `),C.numChars=0;while(j.length>0&&C.numChars<d.length){let o=d[C.numChars];C[o]=j.splice(0,y.height);for(let a=0;a<y.height;a++)if(typeof C[o][a]>"u")C[o][a]="";else C[o][a]=X(C[o][a],a,y.height);C.numChars++}while(j.length>0){let o=j.shift();if(!o||o.trim()==="")break;let a=o.split(" ")[0],s;if(/^-?0[xX][0-9a-fA-F]+$/.test(a))s=parseInt(a,16);else if(/^-?0[0-7]+$/.test(a))s=parseInt(a,8);else if(/^-?[0-9]+$/.test(a))s=parseInt(a,10);else throw Error(`Error parsing data. Invalid data: ${a}`);if(s===-1||s<-2147483648||s>2147483647){let T_=s===-1?"The char code -1 is not permitted.":`The char code cannot be ${s<-2147483648?"less than -2147483648":"greater than 2147483647"}.`;throw Error(`Error parsing data. ${T_}`)}C[s]=j.splice(0,y.height);for(let T_=0;T_<y.height;T_++)if(typeof C[s][T_]>"u")C[s][T_]="";else C[s][T_]=X(C[s][T_],T_,y.height);C.numChars++}return L[O]=C,y},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(m5),O)O(null,m5)})},P_.fontsSync=function(){return m5},P_.figFonts=L,P_})();import{fileURLToPath as hN}from"url";var kN=hN(import.meta.url),fN=mT.dirname(kN),bN=mT.join(fN,"/../fonts/"),x_=R9;x_.defaults({fontPath:bN});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 D9=`flf2a$ 6 5 16 15 13 0 24463 229
46
46
  Standard by Glenn Chappell & Ian Chai 3/93 -- based on Frank's .sig
47
47
  Includes ISO Latin-1
48
48
  figlet release 2.1 -- 12 Aug 1994
@@ -2280,7 +2280,7 @@ Font modified May 20, 2012 by patorjk to add the 0xCA0 character
2280
2280
  @@
2281
2281
  `;x_.parseFont("Standard",D9);function B9(){let _=x_.textSync("ccc",{font:"Standard",horizontalLayout:"default",verticalLayout:"default"});console.log(`
2282
2282
  `),console.log(_),console.log("Code Chat Connect - v2.0.0"),console.log("Mobile IDE to code on the go!"),console.log(`
2283
- `)}var $K=B_(YK(),1);import{Duplex as Hj}from"stream";async function KK(_,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 Hj({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 uA{servers=null;broker=null;running=!1;startedAt;config;name="CCC MQTT Broker";constructor(_){this.config=_,this.createBrokerInstance()}createBrokerInstance(){this.broker=$K.default({id:"ccc-mqtt-broker",heartbeatInterval:this.config.heartbeatInterval||30000,connectTimeout:this.config.connectTimeout||30000,authenticate:this.authenticate.bind(this)}),this.setupBrokerEvents()}setupBrokerEvents(){let _=h();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 _=h();this.servers=await KK(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 h8(`Failed to start MQTT broker: ${_ instanceof Error?_.message:String(_)}`)}}async stop(){try{let _=h();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 h8(`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=h();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 aU=B_(iU(),1);var P1=h();class $5{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=aU.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 oU=5,Mh=900000;class aL{credentials;failedAttempts=new Map;blockedIPs=new Map;logger=h();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 k8("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>=oU)this.blockedIPs.set(A,Date.now()+Mh),this.failedAttempts.delete(A),this.logger.warn(`IP blocked after ${oU} failed attempts`,{ip:A});throw new k8("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 G5=null;async function Vh(){if(!G5)try{G5=await import("../../lib/bun-pty-loader.generated")}catch{G5=await import("bun-pty")}return G5}var rU=5,zh=300000,Fh=102400;class oL{sessions=new Map;projectPath=process.cwd();logger=h();async createSession(_,T=80,A=24){if(Array.from(this.sessions.values()).filter((L)=>!L.disconnectedAt).length>=rU)throw new HT(`Maximum concurrent sessions (${rU}) reached`);try{let{spawn:L}=await Vh(),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)<Fh)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(_)},zh),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 sU(_){return`<!DOCTYPE html>
2283
+ `)}var $K=B_(YK(),1);import{Duplex as Zj}from"stream";async function KK(_,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 Zj({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 uA{servers=null;broker=null;running=!1;startedAt;config;name="CCC MQTT Broker";constructor(_){this.config=_,this.createBrokerInstance()}createBrokerInstance(){this.broker=$K.default({id:"ccc-mqtt-broker",heartbeatInterval:this.config.heartbeatInterval||30000,connectTimeout:this.config.connectTimeout||30000,authenticate:this.authenticate.bind(this)}),this.setupBrokerEvents()}setupBrokerEvents(){let _=k();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 _=k();this.servers=await KK(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 h8(`Failed to start MQTT broker: ${_ instanceof Error?_.message:String(_)}`)}}async stop(){try{let _=k();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 h8(`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=k();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 aU=B_(iU(),1);var I1=k();class $5{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=aU.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 oU=5,Vh=900000;class rL{credentials;failedAttempts=new Map;blockedIPs=new Map;logger=k();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 k8("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>=oU)this.blockedIPs.set(A,Date.now()+Vh),this.failedAttempts.delete(A),this.logger.warn(`IP blocked after ${oU} failed attempts`,{ip:A});throw new k8("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 G5=null;async function zh(){if(!G5)try{G5=await import("../../lib/bun-pty-loader.generated")}catch{G5=await import("bun-pty")}return G5}var rU=5,Fh=300000,Ch=102400;class sL{sessions=new Map;projectPath=process.cwd();logger=k();async createSession(_,T=80,A=24){if(Array.from(this.sessions.values()).filter((L)=>!L.disconnectedAt).length>=rU)throw new HT(`Maximum concurrent sessions (${rU}) reached`);try{let{spawn:L}=await zh(),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)<Ch)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(_)},Fh),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 sU(_){return`<!DOCTYPE html>
2284
2284
  <html lang="en">
2285
2285
  <head>
2286
2286
  <meta charset="UTF-8">
@@ -2606,36 +2606,36 @@ Font modified May 20, 2012 by patorjk to add the 0xCA0 character
2606
2606
  })();
2607
2607
  </script>
2608
2608
  </body>
2609
- </html>`}class U5{server=null;authenticator;ptyManager;running=!1;startedAt;config;logger=h();sessionMap=new Map;name="CCC Terminal Service";constructor(_){this.config=_,this.authenticator=new aL,this.ptyManager=new oL}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=sU(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
2609
+ </html>`}class U5{server=null;authenticator;ptyManager;running=!1;startedAt;config;logger=k();sessionMap=new Map;name="CCC Terminal Service";constructor(_){this.config=_,this.authenticator=new rL,this.ptyManager=new sL}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=sU(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
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
2611
2611
  \r
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 W5 from"http";import*as eU from"net";import{WebSocketServer as Ch,WebSocket as tU}from"ws";class N5{server=null;wss=null;running=!1;startedAt;config;logger=h();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=W5.createServer((A,E)=>{this.handleHttpRequest(A,E)}),this.wss=new Ch({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 k5(`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=W5.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=eU.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 tU(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===tU.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 rL=null;async function Oh(){if(!rL)rL=await import("@ngrok/ngrok");return rL.default}class Q5{listener;tunnelUrl=null;running=!1;startedAt;config;name="CCC Ngrok Service";constructor(_){this.config=_}async start(){try{let _=h();_.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 Oh();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=h(),A=_ instanceof Error?_.message:String(_);throw T.error("Failed to start ngrok tunnel",_),Error(`ngrok tunnel failed: ${A}`)}}async stop(){try{let _=h();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(_){h().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 DW=B_(RW(),1);class F5{running=!1;startedAt;config;codesGenerated=0;name="CCC QR Code Service";constructor(_){this.config=_}async start(){try{let _=h();_.debug("QR Code Service starting"),this.running=!0,this.startedAt=new Date,this.display(),_.debug("QR Code Service started")}catch(_){throw h().error("Failed to start QR Code service",_),this.running=!1,_}}async stop(){try{let _=h();if(!this.running)return;this.running=!1,_.debug("QR Code Service stopped")}catch(_){h().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 _=h();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 W5 from"http";import*as eU from"net";import{WebSocketServer as Oh,WebSocket as tU}from"ws";class N5{server=null;wss=null;running=!1;startedAt;config;logger=k();routes;activeBrokerSockets=new Set;name="CCC Router Service";constructor(_){this.config=_,this.routes=[{path:"/mqtt",target:`localhost:${_.mqttPort}`},{path:"/terminal",target:`localhost:${_.terminalPort}`}]}async start(){return new Promise((_,T)=>{try{this.server=W5.createServer((A,E)=>{this.handleHttpRequest(A,E)}),this.wss=new Oh({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 b5(`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=W5.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=eU.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 tU(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===tU.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 tL=null;async function Rh(){if(!tL)tL=await import("@ngrok/ngrok");return tL.default}class Q5{listener;tunnelUrl=null;running=!1;startedAt;config;name="CCC Ngrok Service";constructor(_){this.config=_}async start(){try{let _=k();_.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 Rh();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=k(),A=_ instanceof Error?_.message:String(_);throw T.error("Failed to start ngrok tunnel",_),Error(`ngrok tunnel failed: ${A}`)}}async stop(){try{let _=k();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(_){k().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 DW=B_(RW(),1);class F5{running=!1;startedAt;config;codesGenerated=0;name="CCC QR Code Service";constructor(_){this.config=_}async start(){try{let _=k();_.debug("QR Code Service starting"),this.running=!0,this.startedAt=new Date,this.display(),_.debug("QR Code Service started")}catch(_){throw k().error("Failed to start QR Code service",_),this.running=!1,_}}async stop(){try{let _=k();if(!this.running)return;this.running=!1,_.debug("QR Code Service stopped")}catch(_){k().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 _=k();try{if(this.codesGenerated=0,console.log(`
2614
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
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);DW.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=h();function BW(_){switch(_){case"alpha":return"alpha";case"beta":return"beta";default:return"latest"}}async function qW(_){let T=G1(),A=XT(T);x1.debug("Checking for updates",{currentVersion:T,releaseChannel:A,packageName:_});try{let E=BW(A),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=h5(X,T);return x1.debug("Version comparison result",{currentVersion:T,latestVersion:X,updateAvailable:H,isNewer:h5(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 IW(_){let T=G1(),A=XT(T),E=BW(A);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 C5{name="CCC Auto-Update Service";config;running=!1;enabled=!1;logger=h();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 qW(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 IW(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 yh,readdirSync as vh,existsSync as hh}from"fs";import{stat as wW}from"fs/promises";import{join as gT,basename as kh}from"path";import{homedir as SW}from"os";import*as o_ from"path";import*as A9 from"os";var M4=h();class PW{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 jW=new PW;var Q1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6},wh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Sh="worktrees",F_=h();class xW{claudeProjectsDir;cccDir;constructor(){this.claudeProjectsDir=o_.join(A9.homedir(),".claude","projects"),this.cccDir=o_.join(A9.homedir(),".ccc")}async getWorktreePathsForProject(_){let T=await import("fs"),A=o_.basename(_),E=o_.join(this.cccDir,`${A}-${Sh}`);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(`
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(`
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 wh.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 jW.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 b=null;if(q.type==="assistant"){if(q.message?.usage)b=q.message.usage;else if(q.usage)b=q.usage}if(q.type==="result"&&q.usage)b=q.usage;if(b&&(b.input_tokens!==void 0||b.output_tokens!==void 0))L=b,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 xW;var X_=h(),fh="worktrees";class E9{watches=new Map;registeredProjects=[];mqttClient;claudeProjectsDir;cccDir;constructor(_){this.mqttClient=_,this.claudeProjectsDir=gT(SW(),".claude","projects"),this.cccDir=gT(SW(),".ccc")}getWorktreePathsForProject(_){let T=kh(_),A=gT(this.cccDir,`${T}-${fh}`);if(!hh(A))return[];try{let E=vh(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 wW(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 wW(T)}catch{return X_.debug(`[SessionWatcher] Sessions directory not found: ${T}`),null}return yh(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 $_=h();class O5{name="Sessions Service";running=!1;startedAt;mqttClient=null;watcher;claudeAgentService=null;constructor(){}setMQTTClient(_){this.mqttClient=_,this.watcher=new E9(_)}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 yW from"os";var T1=h(),bh="1.0.0";class R5{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=yW.platform(),L=yW.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:bh,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=h();class D5{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 S8 from"path";import ZN from"os";var r1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};var e=h();class L9{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(`
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(`
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(`
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}})+`
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)+`
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_=h(),gh=300000,kW=new Map,J9=null;function fW(_){if(!_)return!1;return Date.now()-_.timestamp<gh}function mh(_){let T=kW.get(_);if(fW(T))return T.data;return null}function vW(_,T){kW.set(_,{data:T,timestamp:Date.now()})}function uh(){if(fW(J9))return J9.data;return null}function hW(_){J9={data:_,timestamp:Date.now()}}function dh(){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 ch(){let _=dh();for(let T of _)try{if(await Bun.file(T).exists())return T}catch{}return null}async function bW(){try{if((await u`gh --version`.quiet()).exitCode===0)return await ph("gh")}catch{}let _=await ch();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 ph(_){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 X9(){let _=uh();if(_)return _;try{let T=await u`gh api /user/orgs --jq '.[] | {login, id, description, avatar_url}'`.text();if(!T.trim())return hW([]),[];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 hW(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 B5(_,T=20){let A=`${_||"personal"}_${T}`,E=mh(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 vW(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 vW(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 gW(_,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([B5(void 0,100),X9()]),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 B5(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 mW(_,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 uW(_,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 dW(_,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 q5(_,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 H9(_){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=lh(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 lh(_){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=nh(E,L,_.startsWith("2 "));return{path:H,status:Y,staged:E!=="."&&E!=="?",oldPath:Z||void 0}}return null}function nh(_,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 cW(_,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(`
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);DW.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 j1=k();function BW(_){switch(_){case"alpha":return"alpha";case"beta":return"beta";default:return"latest"}}async function qW(_){let T=G1(),A=XT(T);j1.debug("Checking for updates",{currentVersion:T,releaseChannel:A,packageName:_});try{let E=BW(A),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=f5(X,T);return j1.debug("Version comparison result",{currentVersion:T,latestVersion:X,updateAvailable:H,isNewer:f5(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 IW(_){let T=G1(),A=XT(T),E=BW(A);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 C5{name="CCC Auto-Update Service";config;running=!1;enabled=!1;logger=k();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 qW(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 IW(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 vh,readdirSync as hh,existsSync as kh}from"fs";import{stat as SW}from"fs/promises";import{join as gT,basename as fh}from"path";import{homedir as yW}from"os";import*as d_ from"path";import*as O5 from"os";var M4=k();class PW{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 jW=new PW;var x1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};async function xW(){try{let _=d_.join(O5.homedir(),".claude.json"),T=Bun.file(_);if(await T.exists()){if((await T.json()).autoCompactEnabled===!1)return!1}}catch(_){z_.debug("[SessionManager] Failed to read ~/.claude.json:",_)}return!0}var Sh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,yh="worktrees",z_=k();class wW{claudeProjectsDir;cccDir;constructor(){this.claudeProjectsDir=d_.join(O5.homedir(),".claude","projects"),this.cccDir=d_.join(O5.homedir(),".ccc")}async getWorktreePathsForProject(_){let T=await import("fs"),A=d_.basename(_),E=d_.join(this.cccDir,`${A}-${yh}`);if(z_.debug("[SessionManager] Looking for worktrees:",{projectPath:_,repoName:A,cccDir:this.cccDir,worktreesDir:E}),!T.existsSync(E))return z_.debug("[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=d_.join(E,X.name);J.push(H)}return z_.debug("[SessionManager] Found worktree paths:",J),J}catch(L){return z_.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 d_.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(`
2617
+ `).filter((E)=>E.trim()).length}catch(T){return z_.warn("[SessionManager] Error counting lines:",T),0}}async extractTitle(_){try{let E=(await Bun.file(_).text()).trim().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 z_.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 z_.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=d_.basename(H,".jsonl");return Sh.test(Z)}).map(async(H)=>{let Z=d_.basename(H,".jsonl"),Y=d_.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 z_.warn(`[SessionManager] Error listing sessions from ${_}`,E),[]}}async listSessions(_){if(!(await import("fs")).existsSync(_))return z_.warn("[SessionManager] Project path does not exist:",_),{sessions:[],projectPath:_,pathExists:!1};try{let E=this.getProjectSessionsDir(_);z_.debug("[SessionManager] Main sessions dir:",E);let L=await this.listSessionsFromDir(E);z_.debug("[SessionManager] Main sessions count:",L.length);let J=await this.getWorktreePathsForProject(_);z_.debug("[SessionManager] Worktree paths to check:",J.length);let X=J.map(async($)=>{let G=this.getProjectSessionsDir($);z_.debug("[SessionManager] Checking worktree sessions dir:",G);let U=d_.basename($),V={path:$,branch:`session/${U}`},N=await this.listSessionsFromDir(G,V);return z_.debug("[SessionManager] Found sessions in worktree:",{worktreePath:$,count:N.length,worktreeInfo:V}),N}),Z=(await Promise.all(X)).flat();z_.debug("[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 z_.debug(`[SessionManager] Found ${K.length} sessions for ${_} (${L.length} main, ${Z.length} worktree)`),{sessions:K,projectPath:_,pathExists:!0}}catch(E){return z_.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 z_.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=d_.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=d_.join(H,`${T}.jsonl`);if(A.existsSync(Z)){let Y=d_.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 z_.warn("[SessionManager] Session file not found for:",{projectPath:_,sessionId:T}),{messages:[],hasMore:!1,sessionId:T,projectPath:_,timestamp:Date.now()};let H=await jW.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 z_.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 q of E){if(!q.trim())continue;try{let f=JSON.parse(q);X++;let S=null;if(f.type==="assistant"){if(f.message?.usage)S=f.message.usage;else if(f.usage)S=f.usage}if(f.type==="result"&&f.usage)S=f.usage;if(S&&(S.input_tokens!==void 0||S.output_tokens!==void 0))L=S,J++}catch{continue}}if(z_.debug("[SessionManager] Context calculation stats:",{sessionFile:d_.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 z_.warn("[SessionManager] No usage data found in session file:",_),await 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=x1.SYSTEM_PROMPT,U=x1.TOOLS_TOTAL,V=0,z=await xW()?x1.AUTOCOMPACT_BUFFER:0,Q=Math.max(0,$-G-U-V),F=$+z,R=x1.CONTEXT_LIMIT_STANDARD;return z_.debug("[SessionManager] Context breakdown calculated:",{total:F,apiTokens:$,inputTokens:H,cacheCreation:Y,cacheRead:K,percentage:Math.round(F/R*100),breakdown:{systemPrompt:G,tools:U,mcpServers:V,messages:Q,autocompactBuffer:z,remaining:Math.max(0,R-F)}}),{total:F,inputTokens:H,outputTokens:Z,cacheCreation:Y,cacheRead:K,systemPrompt:G,tools:U,mcpServers:V,messages:Q,autocompactBuffer:z,contextLimit:R,remaining:Math.max(0,R-F),percentage:Math.round(F/R*100),lastUpdated:Date.now()}}catch(T){return z_.error("[SessionManager] Error calculating context breakdown:",T),await this.getEmptyContextBreakdown()}}async getEmptyContextBreakdown(){let T=await xW()?x1.AUTOCOMPACT_BUFFER:0,A=x1.SYSTEM_PROMPT+x1.TOOLS_TOTAL+T;return{total:A,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:x1.SYSTEM_PROMPT,tools:x1.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:T,contextLimit:x1.CONTEXT_LIMIT_STANDARD,remaining:x1.CONTEXT_LIMIT_STANDARD-A,percentage:Math.round(A/x1.CONTEXT_LIMIT_STANDARD*100),lastUpdated:Date.now()}}}var bT=new wW;var X_=k(),bh="worktrees";class L9{watches=new Map;registeredProjects=[];mqttClient;claudeProjectsDir;cccDir;constructor(_){this.mqttClient=_,this.claudeProjectsDir=gT(yW(),".claude","projects"),this.cccDir=gT(yW(),".ccc")}getWorktreePathsForProject(_){let T=fh(_),A=gT(this.cccDir,`${T}-${bh}`);if(!kh(A))return[];try{let E=hh(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 SW(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 SW(T)}catch{return X_.debug(`[SessionWatcher] Sessions directory not found: ${T}`),null}return vh(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 $_=k();class R5{name="Sessions Service";running=!1;startedAt;mqttClient=null;watcher;claudeAgentService=null;constructor(){}setMQTTClient(_){this.mqttClient=_,this.watcher=new L9(_)}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 vW from"os";var T1=k(),gh="1.0.0";class D5{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=vW.platform(),L=vW.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:gh,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=k();class B5{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 S8 from"path";import YN from"os";import mh from"os";var r1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};var r=k();async function uh(){try{let _=`${mh.homedir()}/.claude.json`,T=Bun.file(_);if(await T.exists()){if((await T.json()).autoCompactEnabled===!1)return!1}}catch(_){r.debug("[ClaudeProcessManager] Failed to read ~/.claude.json:",_)}return!0}class q5{sessions=new Map;tempSessions=new Map;config;callbacks;resolvedClaudePath=null;autoCompactEnabled=!0;autoCompactLastChecked=0;static AUTO_COMPACT_CHECK_INTERVAL=30000;constructor(_,T={}){this.config=_,this.callbacks=T,this.refreshAutoCompactSetting()}async refreshAutoCompactSetting(){this.autoCompactEnabled=await uh(),this.autoCompactLastChecked=Date.now(),r.debug("[ClaudeProcessManager] autoCompactEnabled:",this.autoCompactEnabled)}getAutoCompactEnabled(){if(Date.now()-this.autoCompactLastChecked>q5.AUTO_COMPACT_CHECK_INTERVAL)this.refreshAutoCompactSetting();return this.autoCompactEnabled}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=_,r.debug(`[ClaudeProcessManager] Using claude at ${_}`),_}catch(T){r.debug(`[ClaudeProcessManager] claude.cmd not found at ${_}`)}}try{if(await Bun.spawn(["claude","--version"],{stdout:"pipe",stderr:"pipe"}).exited===0)return this.resolvedClaudePath="claude",r.debug("[ClaudeProcessManager] Found claude in PATH"),"claude"}catch(_){r.debug("[ClaudeProcessManager] claude not found in PATH")}return r.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(r.debug(`[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),r.debug(`[ClaudeProcessManager] Resuming session: ${J}`);r.debug(`[ClaudeProcessManager] Spawning: ${Y} ${G.join(" ")}`,{cwd:E,claudePath:Y});try{if((await Bun.$`test -d ${E}`.quiet().nothrow()).exitCode!==0){if(r.debug(`[ClaudeProcessManager] Directory does not exist, creating: ${E}`),(await Bun.$`mkdir -p ${E}`.quiet().nothrow()).exitCode!==0)throw Error(`Failed to create directory: ${E}`);r.debug(`[ClaudeProcessManager] Directory created successfully: ${E}`)}}catch(N){throw r.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)=>{r.debug("[ClaudeProcessManager] Claude process exited",{tempId:A,sessionId:_.sessionId,exitCode:E});let L=`exited with code ${E}`;this.handleSessionStopped(_,L)}).catch((E)=>{r.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(`
2620
+ `);E=X.pop()||"";for(let H of X)if(H.trim())try{let Z=JSON.parse(H);this.handleClaudeMessage(T,Z)}catch(Z){r.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){r.error("[ClaudeProcessManager] Failed to parse final JSON from Claude:",{tempId:T.tempId,sessionId:T.sessionId,buffer:E})}}catch(A){r.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(`
2621
+ `);E=X.pop()||"";for(let H of X)if(H.trim())r.warn("[ClaudeProcessManager] Claude stderr:",{tempId:T.tempId,sessionId:T.sessionId,line:H})}if(E.trim())r.warn("[ClaudeProcessManager] Claude stderr (final):",{tempId:T.tempId,sessionId:T.sessionId,line:E})}catch(A){r.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){r.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",r.debug("[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"))r.debug("[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(`
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=this.getAutoCompactEnabled()?r1.AUTOCOMPACT_BUFFER:0,$=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(){let _=this.getAutoCompactEnabled()?r1.AUTOCOMPACT_BUFFER:0;return{total:0,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:r1.SYSTEM_PROMPT,tools:r1.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:_,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,r.debug("[ClaudeProcessManager] Title from summary:",{sessionId:_.sessionId,title:E}),this.callbacks.onTitleGenerated?.(_,E)}}handleResultMessage(_,T){if(r.debug("[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,r.debug("[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",r.debug("[ClaudeProcessManager] Permission request:",{sessionId:_.sessionId,fullRequest:JSON.stringify(T),requestId:T.request_id,action:T.action}),this.callbacks.onPermissionRequest?.(_,T)}handleSessionError(_,T){_.status="error",r.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){r.debug("[ClaudeProcessManager] Skipping session_stopped - session is respawning:",{tempId:_.tempId,sessionId:_.sessionId});return}if(_.status="stopped",r.debug("[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 r.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}})+`
2623
+ `;_.process.stdin.write(J),_.lastActivity=new Date,_.messageCount++,_.status="processing",this.callbacks.onProcessingStarted?.(_)}sendPermissionResponse(_,T){let A=this.sessions.get(_);if(!A){r.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)+`
2624
+ `;A.process.stdin.write(J),r.debug("[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 r.warn(`[ClaudeProcessManager] Cannot respawn - session not found: ${_}`),null;let{tempId:L,userId:J,projectId:X,directoryPath:H,model:Z}=E;r.debug("[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 r.debug("[ClaudeProcessManager] Session respawned successfully:",{sessionId:_,newPermissionMode:T,newTempId:K.tempId}),K}catch(K){return r.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){r.warn(`[ClaudeProcessManager] Session not found: ${_}`);return}r.debug("[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(){r.debug(`[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)r.debug("[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_=k(),dh=300000,fW=new Map,J9=null;function bW(_){if(!_)return!1;return Date.now()-_.timestamp<dh}function ch(_){let T=fW.get(_);if(bW(T))return T.data;return null}function hW(_,T){fW.set(_,{data:T,timestamp:Date.now()})}function ph(){if(bW(J9))return J9.data;return null}function kW(_){J9={data:_,timestamp:Date.now()}}function lh(){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 nh(){let _=lh();for(let T of _)try{if(await Bun.file(T).exists())return T}catch{}return null}async function gW(){try{if((await u`gh --version`.quiet()).exitCode===0)return await ih("gh")}catch{}let _=await nh();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 ih(_){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 X9(){let _=ph();if(_)return _;try{let T=await u`gh api /user/orgs --jq '.[] | {login, id, description, avatar_url}'`.text();if(!T.trim())return kW([]),[];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 kW(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 I5(_,T=20){let A=`${_||"personal"}_${T}`,E=ch(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 hW(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 hW(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 mW(_,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([I5(void 0,100),X9()]),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 I5(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 uW(_,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 dW(_,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 cW(_,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 P5(_,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 H9(_){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=ah(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 ah(_){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=oh(E,L,_.startsWith("2 "));return{path:H,status:Y,staged:E!=="."&&E!=="?",oldPath:Z||void 0}}return null}function oh(_,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 pW(_,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
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 pW(_,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 lW(_,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 nW(_,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 iW(_,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 aW(_,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 oW(_,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 rW(_,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 sW(_,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/),b=R.match(/(\d+) insertions?\(\+\)/),k=R.match(/(\d+) deletions?\(-\)/);if(q?.[1])N=parseInt(q[1],10);if(b?.[1])z=parseInt(b[1],10);if(k?.[1])Q=parseInt(k[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 tW(_,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(`
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 lW(_,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 nW(_,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 iW(_,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 aW(_,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 oW(_,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 rW(_,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 sW(_,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 tW(_,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?\(\+\)/),S=R.match(/(\d+) deletions?\(-\)/);if(q?.[1])N=parseInt(q[1],10);if(f?.[1])z=parseInt(f[1],10);if(S?.[1])Q=parseInt(S[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 eW(_,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(`
2634
2634
  `),J=L[0]||"",X=L[1]||"",H=L[2]||"",Z=L.length-3,Y=L.slice(3,Z).join(`
2635
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(`
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),b=R[1]==="-"?0:parseInt(R[1]||"0",10),k=R.slice(2).join("\t");if(N+=q,z+=b,k.includes(" => ")){let[g,l]=k.split(" => ").map((c)=>c.trim().replace(/[{}]/g,""));V.push({path:l||"",oldPath:g||"",status:"renamed",insertions:q,deletions:b})}else V.push({path:k,status:"modified",insertions:q,deletions:b})}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(`
2637
- `)){if(!F.trim())continue;let R=F.split("\t");if(R.length<2)continue;let q=R[0]?.[0]||"M",b=R.length>2?R[2]:R[1],k=V.find((g)=>g.path===b||g.oldPath===R[1]);if(k)switch(q){case"A":k.status="added";break;case"D":k.status="deleted";break;case"R":k.status="renamed";break;case"C":k.status="copied";break;default:k.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 eW(_){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 _N(_,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 TN(_,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 AN(_){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 Z9(_){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 EN(_){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 Z9(_);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 K9 from"os";var G_=h();function C4(_){return r_.normalize(_).toLowerCase()}var ih="worktrees",ah="sessions";function Y9(){return r_.join(K9.homedir(),".ccc",ah)}function oh(){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=Y9();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(Y9(),_);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(Y9(),_);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(K9.homedir(),".ccc");return r_.join(A,`${T}-${ih}`)}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 q5(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=oh(),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 dW(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 q5(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 q5(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 aW(E,J,X),G_.debug("[WorktreeManager] Moved worktree",{from:J,to:X}),await iW(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 $9 from"path";import*as XN from"os";var w1=h(),I5=$9.join(XN.homedir(),".ccc"),JN=$9.join(I5,"pending-permissions.json");class HN{cache=null;async ensureDirectory(){try{let _=await import("fs");if(!_.existsSync(I5))_.mkdirSync(I5,{recursive:!0}),w1.debug("[PendingPermissions] Created .ccc directory:",I5)}catch(_){throw w1.error("[PendingPermissions] Error ensuring directory:",_),_}}async load(){if(this.cache)return this.cache;try{let _=Bun.file(JN);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(JN,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 HN;var v=h();class P5{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 L9(_,{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,E=!1){try{if(!E)return v.debug("[ClaudeAgent] Git worktrees disabled, using project path",{projectId:_,directoryPath:T}),{path:T,isWorktree:!1};if(!await z4(T))return v.debug("[ClaudeAgent] Not a git repo, using project path",{projectId:_,directoryPath:T}),{path:T,isWorktree:!1};let J=await O0(T);if(!J)return v.warn("[ClaudeAgent] Could not determine repo root, using project path",{directoryPath:T}),{path:T,isWorktree:!1};v.info("[ClaudeAgent] Git repo detected, creating worktree",{projectId:_,sessionId:A,repoRoot:J});let{worktree:X,isNew:H}=await this.worktreeManager.getOrCreateForSession(A,J);return v.info("[ClaudeAgent] Worktree ready",{sessionId:A,worktreePath:X.path,branch:X.branch,isNew:H}),{path:X.path,isWorktree:!0,branch:X.branch}}catch(L){return v.error("[ClaudeAgent] Worktree creation failed, falling back to project path",{projectId:_,sessionId:A,error:L instanceof Error?L.message:"Unknown error"}),{path:T,isWorktree:!1}}}setMQTTClient(_){this.mqttClient=_}setSessionsService(_){this.sessionsService=_}async start(){try{if(this.running=!0,this.startedAt=new Date,v.info("[ClaudeAgent] Service started"),this.mqttClient)this.registerMQTTHandlers();else v.warn("[ClaudeAgent] MQTT client not set - handlers will not be registered");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions()},300000),v.info("[ClaudeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions,sessionTimeoutMs:this.config.sessionTimeoutMs})}catch(_){throw v.error("[ClaudeAgent] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval);this.processManager.stopAll(),v.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)}),this.mqttClient.subscribe("settings/claude/request",(_,T)=>{this.handleClaudeSettingsRequest(_,T)}),this.mqttClient.subscribe("settings/claude/update",(_,T)=>{this.handleClaudeSettingsUpdate(_,T)}),v.info("[ClaudeAgent] MQTT handlers registered")}async handleSessionStart(_,T,A){try{let E=JSON.parse(A.toString());v.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,gitWorktreesEnabled:E.gitWorktreesEnabled});let{path:L,isWorktree:J,branch:X}=await this.determineWorkingDirectory(E.projectId,E.directoryPath,E.tempId,E.gitWorktreesEnabled??!1),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++,v.info("[ClaudeAgent] Session spawned successfully:",{userId:_,tempId:E.tempId,projectId:E.projectId,workingPath:L,isWorktree:J})}catch(E){v.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)){v.warn("[ClaudeAgent] Received request without message or attachments:",{userId:_,sessionId:L.sessionId,hasAttachments:!!L.attachments});return}v.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){v.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,L.gitWorktreesEnabled??!1);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++,v.info(`[ClaudeAgent] Session ${Z?"resumed":"created"} successfully:`,{userId:_,sessionId:L.sessionId,isResume:Z,workingPath:Y,isWorktree:K}),this.totalMessagesProcessed++;return}catch(Y){v.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(v.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 v.error("[ClaudeAgent] Failed to respawn session with new permission mode");this.processManager.sendUserMessage(J,L.message||"",L.attachments),this.totalMessagesProcessed++}catch(L){v.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());v.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)v.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),v.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(v.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)=>{v.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};v.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(v.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)v.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)=>{v.error("[ClaudeAgent] Failed to remove pending permission from storage:",H)})}catch(L){v.error("[ClaudeAgent] Error handling permission response:",{userId:_,sessionId:T,error:L instanceof Error?L.message:"Unknown error"})}}handleSessionStop(_,T){v.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){v.warn("[ClaudeAgent] Pending permissions request missing clientId");return}v.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($)),v.info("[ClaudeAgent] Sent pending permissions response:",{clientId:E,count:Y.length,totalStored:X.length})}catch(A){v.error("[ClaudeAgent] Error handling pending permissions request:",A)}}async handleClaudeSettingsRequest(_,T){try{let A=JSON.parse(T.toString()),{clientId:E}=A;if(!E){v.warn("[ClaudeAgent] Claude settings request missing clientId");return}v.info("[ClaudeAgent] Claude settings request:",{clientId:E});let L=S8.join(ZN.homedir(),".claude","settings.json"),J={};try{let Z=Bun.file(L);if(await Z.exists())J=JSON.parse(await Z.text())}catch(Z){v.warn("[ClaudeAgent] Could not read Claude settings file:",Z)}let X=`settings/claude/${E}/response`,H={success:!0,settings:J,timestamp:Date.now()};await this.mqttClient?.publish(X,JSON.stringify(H)),v.info("[ClaudeAgent] Sent Claude settings response:",{clientId:E})}catch(A){v.error("[ClaudeAgent] Error handling Claude settings request:",A)}}async handleClaudeSettingsUpdate(_,T){try{let A=JSON.parse(T.toString()),{clientId:E,key:L,value:J}=A;if(!E||!L){v.warn("[ClaudeAgent] Claude settings update missing clientId or key");return}v.info("[ClaudeAgent] Claude settings update:",{clientId:E,key:L,value:J});let X=S8.join(ZN.homedir(),".claude"),H=S8.join(X,"settings.json");try{await Bun.$`mkdir -p ${X}`.quiet()}catch($){}let Z={};try{let $=Bun.file(H);if(await $.exists())Z=JSON.parse(await $.text())}catch($){v.warn("[ClaudeAgent] Could not read existing Claude settings, starting fresh")}Z[L]=J,await Bun.write(H,JSON.stringify(Z,null,2));let Y=`settings/claude/${E}/response`,K={success:!0,timestamp:Date.now()};await this.mqttClient?.publish(Y,JSON.stringify(K)),v.info("[ClaudeAgent] Updated Claude setting:",{clientId:E,key:L,value:J})}catch(A){v.error("[ClaudeAgent] Error handling Claude settings update:",A);try{let L=`settings/claude/${JSON.parse(T.toString()).clientId}/response`,J={success:!1,error:A instanceof Error?A.message:"Unknown error",timestamp:Date.now()};await this.mqttClient?.publish(L,JSON.stringify(J))}catch{}}}handleSessionInitialized(_,T){if(v.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)=>{v.warn("[ClaudeAgent] Failed to notify sessions service about new session",{error:E})})}}handleTitleGenerated(_,T){v.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(v.info("[ClaudeAgent] Permission request callback:",{sessionId:_.sessionId,requestId:T.request_id,action:T.action}),_.sessionId)this.publishPermissionRequest(_,T)}handleSessionError(_,T){v.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(v.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(v.info("[ClaudeAgent] Processing started:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_processing",sessionId:_.sessionId,timestamp:Date.now()})}handleProcessingComplete(_){if(v.info("[ClaudeAgent] Processing complete:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_idle",sessionId:_.sessionId,timestamp:Date.now()})}handleContextUpdate(_,T){if(v.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 v.warn("[ClaudeAgent] Cannot publish context update - no sessionId yet")}publishStatus(_,T,A){if(!this.mqttClient){v.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)=>{v.error(`[ClaudeAgent] Failed to publish status to ${E}`,{error:J.message})})}publishOutput(_,T,A){if(!this.mqttClient){v.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)=>{v.error(`[ClaudeAgent] Failed to publish output to ${E}`,{error:J.message})})}publishContextUpdate(_,T,A){if(!this.mqttClient){v.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)=>{v.error(`[ClaudeAgent] Failed to publish context to ${E}`,{error:J.message})})}publishPermissionRequest(_,T){if(!this.mqttClient){v.warn("[ClaudeAgent] Cannot publish permission request - MQTT client not available");return}let{userId:A,sessionId:E}=_;v.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)=>{v.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($);v.info("[ClaudeAgent] Publishing transformed permission request:",{topic:G,request_id:$.request_id,action:$.action}),this.mqttClient.publish(G,U).catch((V)=>{v.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=S8.join(_,".claude"),E=S8.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)),v.info("[ClaudeAgent] Updated settings.local.json with allowed tool:",{settingsPath:E,toolPattern:T,totalAllowed:J.permissions.allow.length})}catch(A){v.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=h();class j5{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 G9 from"path";var A1=h(),R4=51200,YN=50;class x5{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 j5}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(YN)}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:G9.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=G9.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(YN)}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 m=h();class w5{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 bW(),!this.ghAuthResult.authenticated)m.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else m.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username});if(this.mqttClient)this.registerMQTTHandlers();m.info("[GitService] Service started")}catch(_){throw m.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),m.debug(`[GitService] Unsubscribed from ${_}`);this.messageHandlers.clear()}this.worktreeManager.clearCache(),m.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)}),m.info("[GitService] MQTT handlers registered")}registerHandler(_,T){if(!this.mqttClient)return;this.messageHandlers.set(_,T),this.mqttClient.subscribe(_,T),m.debug(`[GitService] Subscribed to ${_}`)}async publishResponse(_,T){if(!this.mqttClient){m.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(m.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 X9(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${T.clientId}/response`,E),this.requestsHandled++}catch(T){m.error("[GitService] Error handling orgs request",{error:T})}}async handleReposRequest(_){try{let T=JSON.parse(_.toString()),A=T.requestId||T.clientId;if(m.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 B5(T.org,T.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,L),this.requestsHandled++}catch(T){m.error("[GitService] Error handling repos request",{error:T})}}async handleSearchReposRequest(_){try{let T=JSON.parse(_.toString());if(m.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 gW(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),m.debug("[GitService] Sent search results",{source:E,count:A.length,isComplete:L})},T.limit||50),this.requestsHandled++}catch(T){m.error("[GitService] Error handling search repos request",{error:T})}}async handleBranchesRequest(_){try{let T=JSON.parse(_.toString());if(m.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 mW(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){m.error("[GitService] Error handling branches request",{error:T})}}async handleCloneRequest(_){try{let T=JSON.parse(_.toString());if(m.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 uW(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){m.error("[GitService] Error handling clone request",{error:T})}}async handleIsRepoRequest(_){try{let T=JSON.parse(_.toString());m.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),oW(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){m.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());m.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){m.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());m.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){m.error("[GitService] Error handling worktree get request",{error:T})}}async handleWorktreeListRequest(_){try{let T=JSON.parse(_.toString());m.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){m.error("[GitService] Error handling worktree list request",{error:T})}}async handleStatusRequest(_){try{let T=JSON.parse(_.toString());m.debug("[GitService] Status request",{clientId:T.clientId,path:T.path});let E={success:!0,status:await H9(T.path),timestamp:Date.now()};await this.publishResponse(`git/status/${T.clientId}/response`,E),this.requestsHandled++}catch(T){m.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());m.debug("[GitService] Diff request",{clientId:T.clientId,path:T.path,file:T.file,staged:T.staged});let A=await cW(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){m.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());m.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 H9(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){m.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){m.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());m.debug("[GitService] Stage request",{clientId:T.clientId,path:T.path,files:T.files}),await pW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){m.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());m.debug("[GitService] Unstage request",{clientId:T.clientId,path:T.path,files:T.files}),await lW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){m.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());m.info("[GitService] Commit request",{clientId:T.clientId,path:T.path,signoff:T.signoff});let E={success:!0,commit:await nW(T.path,T.message,T.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${T.clientId}/response`,E),this.requestsHandled++}catch(T){m.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());m.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){m.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());m.info("[GitService] Push request",{clientId:T.clientId,path:T.path,force:T.force});let A=await rW(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){m.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());m.info("[GitService] History request",{clientId:T.clientId,path:T.path,limit:T.limit});let A=await sW(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){m.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());m.debug("[GitService] Commit details request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash});let E={success:!0,commit:await tW(T.path,T.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${T.clientId}/response`,E),this.requestsHandled++}catch(T){m.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());m.debug("[GitService] Commit file diff request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash,filePath:T.filePath});let A=await _N(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){m.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());m.info("[GitService] Sync request",{clientId:T.clientId,path:T.path});let A=await eW(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){m.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());m.info("[GitService] Create PR request",{clientId:T.clientId,path:T.path,title:T.title,baseBranch:T.baseBranch,draft:T.draft});let A=await TN(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){m.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());m.debug("[GitService] Default branch request",{clientId:T.clientId,path:T.path});let A=await Z9(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){m.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());m.debug("[GitService] Existing PR request",{clientId:T.clientId,path:T.path});let A=await AN(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){m.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());m.debug("[GitService] Remote branches request",{clientId:T.clientId,path:T.path});let A=await EN(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){m.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 MN from"path";import*as S5 from"path";import*as GN from"os";var d_=h(),y8=S5.join(GN.homedir(),".ccc"),KN=S5.join(y8,"device-tokens.json"),$N=S5.join(y8,"notification-preferences.json");class UN{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if((await Bun.$`test -d ${y8}`.quiet().nothrow()).exitCode!==0)await Bun.$`mkdir -p ${y8}`.quiet(),d_.debug("[NotificationStorage] Created .ccc directory:",y8)}catch(_){throw d_.error("[NotificationStorage] Error ensuring directory:",_),_}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let _=Bun.file(KN);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(KN,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($N);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($N,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 UN;var U9=null;async function WN(){if(!U9)U9=await import("expo-server-sdk");return U9}var $1=h();class NN{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;async getExpo(){if(!this.expo){let _=await WN();this.expo=new _.default}return this.expo}async isValidToken(_){return(await WN()).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 v8=new NN;var Q_=h(),QN=200,rh=900000;class y5{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(()=>{v8.checkReceipts().catch((_)=>{Q_.error("[Notification] Error checking receipts:",_)})},rh),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=MN.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(`
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),S=R.slice(2).join("\t");if(N+=q,z+=f,S.includes(" => ")){let[g,l]=S.split(" => ").map((c)=>c.trim().replace(/[{}]/g,""));V.push({path:l||"",oldPath:g||"",status:"renamed",insertions:q,deletions:f})}else V.push({path:S,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(`
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],S=V.find((g)=>g.path===f||g.oldPath===R[1]);if(S)switch(q){case"A":S.status="added";break;case"D":S.status="deleted";break;case"R":S.status="renamed";break;case"C":S.status="copied";break;default:S.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 _N(_){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 TN(_,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 AN(_,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 EN(_){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 Z9(_){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 LN(_){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 Z9(_);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 K9 from"os";var G_=k();function C4(_){return r_.normalize(_).toLowerCase()}var rh="worktrees",sh="sessions";function Y9(){return r_.join(K9.homedir(),".ccc",sh)}function th(){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=Y9();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(Y9(),_);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(Y9(),_);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(K9.homedir(),".ccc");return r_.join(A,`${T}-${rh}`)}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 P5(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=th(),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 cW(J,K,$);return U.sessionId=_,this.saveSessionMapping(_,K),this.worktreeCache.set(_,U),G_.debug("[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 P5(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_.debug("[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_.debug("[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 P5(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 oW(E,J,X),G_.debug("[WorktreeManager] Moved worktree",{from:J,to:X}),await aW(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_.debug("[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 $9 from"path";import*as HN from"os";var w1=k(),j5=$9.join(HN.homedir(),".ccc"),XN=$9.join(j5,"pending-permissions.json");class ZN{cache=null;async ensureDirectory(){try{let _=await import("fs");if(!_.existsSync(j5))_.mkdirSync(j5,{recursive:!0}),w1.debug("[PendingPermissions] Created .ccc directory:",j5)}catch(_){throw w1.error("[PendingPermissions] Error ensuring directory:",_),_}}async load(){if(this.cache)return this.cache;try{let _=Bun.file(XN);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(XN,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.debug("[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.debug("[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.debug("[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.debug("[PendingPermissions] Cleared all pending permissions")}clearCache(){this.cache=null,w1.debug("[PendingPermissions] Cleared cache")}}var LT=new ZN;var h=k();class x5{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 q5(_,{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,E=!1){try{if(!E)return h.debug("[ClaudeAgent] Git worktrees disabled, using project path",{projectId:_,directoryPath:T}),{path:T,isWorktree:!1};if(!await z4(T))return h.debug("[ClaudeAgent] Not a git repo, using project path",{projectId:_,directoryPath:T}),{path:T,isWorktree:!1};let J=await O0(T);if(!J)return h.warn("[ClaudeAgent] Could not determine repo root, using project path",{directoryPath:T}),{path:T,isWorktree:!1};h.debug("[ClaudeAgent] Git repo detected, creating worktree",{projectId:_,sessionId:A,repoRoot:J});let{worktree:X,isNew:H}=await this.worktreeManager.getOrCreateForSession(A,J);return h.debug("[ClaudeAgent] Worktree ready",{sessionId:A,worktreePath:X.path,branch:X.branch,isNew:H}),{path:X.path,isWorktree:!0,branch:X.branch}}catch(L){return h.error("[ClaudeAgent] Worktree creation failed, falling back to project path",{projectId:_,sessionId:A,error:L instanceof Error?L.message:"Unknown error"}),{path:T,isWorktree:!1}}}setMQTTClient(_){this.mqttClient=_}setSessionsService(_){this.sessionsService=_}async start(){try{if(this.running=!0,this.startedAt=new Date,h.info("[ClaudeAgent] Service started"),this.mqttClient)this.registerMQTTHandlers();else h.warn("[ClaudeAgent] MQTT client not set - handlers will not be registered");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions()},300000),h.info("[ClaudeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions,sessionTimeoutMs:this.config.sessionTimeoutMs})}catch(_){throw h.error("[ClaudeAgent] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval);this.processManager.stopAll(),h.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)}),this.mqttClient.subscribe("settings/claude/request",(_,T)=>{this.handleClaudeSettingsRequest(_,T)}),this.mqttClient.subscribe("settings/claude/update",(_,T)=>{this.handleClaudeSettingsUpdate(_,T)}),h.info("[ClaudeAgent] MQTT handlers registered")}async handleSessionStart(_,T,A){try{let E=JSON.parse(A.toString());h.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,gitWorktreesEnabled:E.gitWorktreesEnabled});let{path:L,isWorktree:J,branch:X}=await this.determineWorkingDirectory(E.projectId,E.directoryPath,E.tempId,E.gitWorktreesEnabled??!1),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++,h.info("[ClaudeAgent] Session spawned successfully:",{userId:_,tempId:E.tempId,projectId:E.projectId,workingPath:L,isWorktree:J})}catch(E){h.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)){h.warn("[ClaudeAgent] Received request without message or attachments:",{userId:_,sessionId:L.sessionId,hasAttachments:!!L.attachments});return}h.debug("[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){h.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,L.gitWorktreesEnabled??!1);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++,h.info(`[ClaudeAgent] Session ${Z?"resumed":"created"} successfully:`,{userId:_,sessionId:L.sessionId,isResume:Z,workingPath:Y,isWorktree:K}),this.totalMessagesProcessed++;return}catch(Y){h.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(h.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 h.error("[ClaudeAgent] Failed to respawn session with new permission mode");this.processManager.sendUserMessage(J,L.message||"",L.attachments),this.totalMessagesProcessed++}catch(L){h.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());h.debug("[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)h.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),h.debug("[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(h.debug("[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)=>{h.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};h.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(h.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)h.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)=>{h.error("[ClaudeAgent] Failed to remove pending permission from storage:",H)})}catch(L){h.error("[ClaudeAgent] Error handling permission response:",{userId:_,sessionId:T,error:L instanceof Error?L.message:"Unknown error"})}}handleSessionStop(_,T){h.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){h.warn("[ClaudeAgent] Pending permissions request missing clientId");return}h.debug("[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($)),h.debug("[ClaudeAgent] Sent pending permissions response:",{clientId:E,count:Y.length,totalStored:X.length})}catch(A){h.error("[ClaudeAgent] Error handling pending permissions request:",A)}}async handleClaudeSettingsRequest(_,T){try{let A=JSON.parse(T.toString()),{clientId:E}=A;if(!E){h.warn("[ClaudeAgent] Claude settings request missing clientId");return}h.debug("[ClaudeAgent] Claude settings request:",{clientId:E});let L=S8.join(YN.homedir(),".claude","settings.json"),J={};try{let Z=Bun.file(L);if(await Z.exists())J=JSON.parse(await Z.text())}catch(Z){h.warn("[ClaudeAgent] Could not read Claude settings file:",Z)}let X=`settings/claude/${E}/response`,H={success:!0,settings:J,timestamp:Date.now()};await this.mqttClient?.publish(X,JSON.stringify(H)),h.debug("[ClaudeAgent] Sent Claude settings response:",{clientId:E})}catch(A){h.error("[ClaudeAgent] Error handling Claude settings request:",A)}}async handleClaudeSettingsUpdate(_,T){try{let A=JSON.parse(T.toString()),{clientId:E,key:L,value:J}=A;if(!E||!L){h.warn("[ClaudeAgent] Claude settings update missing clientId or key");return}h.debug("[ClaudeAgent] Claude settings update:",{clientId:E,key:L,value:J});let X=S8.join(YN.homedir(),".claude"),H=S8.join(X,"settings.json");try{await Bun.$`mkdir -p ${X}`.quiet()}catch($){}let Z={};try{let $=Bun.file(H);if(await $.exists())Z=JSON.parse(await $.text())}catch($){h.warn("[ClaudeAgent] Could not read existing Claude settings, starting fresh")}Z[L]=J,await Bun.write(H,JSON.stringify(Z,null,2));let Y=`settings/claude/${E}/response`,K={success:!0,timestamp:Date.now()};await this.mqttClient?.publish(Y,JSON.stringify(K)),h.debug("[ClaudeAgent] Updated Claude setting:",{clientId:E,key:L,value:J})}catch(A){h.error("[ClaudeAgent] Error handling Claude settings update:",A);try{let L=`settings/claude/${JSON.parse(T.toString()).clientId}/response`,J={success:!1,error:A instanceof Error?A.message:"Unknown error",timestamp:Date.now()};await this.mqttClient?.publish(L,JSON.stringify(J))}catch{}}}handleSessionInitialized(_,T){if(h.debug("[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)=>{h.warn("[ClaudeAgent] Failed to notify sessions service about new session",{error:E})})}}handleTitleGenerated(_,T){h.debug("[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(h.debug("[ClaudeAgent] Permission request callback:",{sessionId:_.sessionId,requestId:T.request_id,action:T.action}),_.sessionId)this.publishPermissionRequest(_,T)}handleSessionError(_,T){h.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(h.debug("[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(h.debug("[ClaudeAgent] Processing started:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_processing",sessionId:_.sessionId,timestamp:Date.now()})}handleProcessingComplete(_){if(h.debug("[ClaudeAgent] Processing complete:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_idle",sessionId:_.sessionId,timestamp:Date.now()})}handleContextUpdate(_,T){if(h.debug(`[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 h.warn("[ClaudeAgent] Cannot publish context update - no sessionId yet")}publishStatus(_,T,A){if(!this.mqttClient){h.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)=>{h.error(`[ClaudeAgent] Failed to publish status to ${E}`,{error:J.message})})}publishOutput(_,T,A){if(!this.mqttClient){h.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)=>{h.error(`[ClaudeAgent] Failed to publish output to ${E}`,{error:J.message})})}publishContextUpdate(_,T,A){if(!this.mqttClient){h.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)=>{h.error(`[ClaudeAgent] Failed to publish context to ${E}`,{error:J.message})})}publishPermissionRequest(_,T){if(!this.mqttClient){h.warn("[ClaudeAgent] Cannot publish permission request - MQTT client not available");return}let{userId:A,sessionId:E}=_;h.debug("[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)=>{h.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($);h.debug("[ClaudeAgent] Publishing transformed permission request:",{topic:G,request_id:$.request_id,action:$.action}),this.mqttClient.publish(G,U).catch((V)=>{h.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=S8.join(_,".claude"),E=S8.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)),h.debug("[ClaudeAgent] Updated settings.local.json with allowed tool:",{settingsPath:E,toolPattern:T,totalAllowed:J.permissions.allow.length})}catch(A){h.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=k();class w5{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 G9 from"path";var A1=k(),R4=51200,KN=50;class S5{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 w5}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(KN)}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:G9.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=G9.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(KN)}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 m=k();class y5{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 gW(),!this.ghAuthResult.authenticated)m.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else m.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username});if(this.mqttClient)this.registerMQTTHandlers();m.info("[GitService] Service started")}catch(_){throw m.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),m.debug(`[GitService] Unsubscribed from ${_}`);this.messageHandlers.clear()}this.worktreeManager.clearCache(),m.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)}),m.info("[GitService] MQTT handlers registered")}registerHandler(_,T){if(!this.mqttClient)return;this.messageHandlers.set(_,T),this.mqttClient.subscribe(_,T),m.debug(`[GitService] Subscribed to ${_}`)}async publishResponse(_,T){if(!this.mqttClient){m.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(m.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 X9(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${T.clientId}/response`,E),this.requestsHandled++}catch(T){m.error("[GitService] Error handling orgs request",{error:T})}}async handleReposRequest(_){try{let T=JSON.parse(_.toString()),A=T.requestId||T.clientId;if(m.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 I5(T.org,T.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,L),this.requestsHandled++}catch(T){m.error("[GitService] Error handling repos request",{error:T})}}async handleSearchReposRequest(_){try{let T=JSON.parse(_.toString());if(m.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 mW(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),m.debug("[GitService] Sent search results",{source:E,count:A.length,isComplete:L})},T.limit||50),this.requestsHandled++}catch(T){m.error("[GitService] Error handling search repos request",{error:T})}}async handleBranchesRequest(_){try{let T=JSON.parse(_.toString());if(m.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 uW(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){m.error("[GitService] Error handling branches request",{error:T})}}async handleCloneRequest(_){try{let T=JSON.parse(_.toString());if(m.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 dW(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){m.error("[GitService] Error handling clone request",{error:T})}}async handleIsRepoRequest(_){try{let T=JSON.parse(_.toString());m.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),rW(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){m.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());m.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){m.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());m.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){m.error("[GitService] Error handling worktree get request",{error:T})}}async handleWorktreeListRequest(_){try{let T=JSON.parse(_.toString());m.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){m.error("[GitService] Error handling worktree list request",{error:T})}}async handleStatusRequest(_){try{let T=JSON.parse(_.toString());m.debug("[GitService] Status request",{clientId:T.clientId,path:T.path});let E={success:!0,status:await H9(T.path),timestamp:Date.now()};await this.publishResponse(`git/status/${T.clientId}/response`,E),this.requestsHandled++}catch(T){m.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());m.debug("[GitService] Diff request",{clientId:T.clientId,path:T.path,file:T.file,staged:T.staged});let A=await pW(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){m.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());m.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 H9(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){m.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){m.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());m.debug("[GitService] Stage request",{clientId:T.clientId,path:T.path,files:T.files}),await lW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){m.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());m.debug("[GitService] Unstage request",{clientId:T.clientId,path:T.path,files:T.files}),await nW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){m.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());m.info("[GitService] Commit request",{clientId:T.clientId,path:T.path,signoff:T.signoff});let E={success:!0,commit:await iW(T.path,T.message,T.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${T.clientId}/response`,E),this.requestsHandled++}catch(T){m.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());m.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){m.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());m.info("[GitService] Push request",{clientId:T.clientId,path:T.path,force:T.force});let A=await sW(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){m.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());m.info("[GitService] History request",{clientId:T.clientId,path:T.path,limit:T.limit});let A=await tW(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){m.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());m.debug("[GitService] Commit details request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash});let E={success:!0,commit:await eW(T.path,T.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${T.clientId}/response`,E),this.requestsHandled++}catch(T){m.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());m.debug("[GitService] Commit file diff request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash,filePath:T.filePath});let A=await TN(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){m.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());m.info("[GitService] Sync request",{clientId:T.clientId,path:T.path});let A=await _N(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){m.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());m.info("[GitService] Create PR request",{clientId:T.clientId,path:T.path,title:T.title,baseBranch:T.baseBranch,draft:T.draft});let A=await AN(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){m.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());m.debug("[GitService] Default branch request",{clientId:T.clientId,path:T.path});let A=await Z9(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){m.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());m.debug("[GitService] Existing PR request",{clientId:T.clientId,path:T.path});let A=await EN(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){m.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());m.debug("[GitService] Remote branches request",{clientId:T.clientId,path:T.path});let A=await LN(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){m.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 VN from"path";import*as v5 from"path";import*as UN from"os";var c_=k(),y8=v5.join(UN.homedir(),".ccc"),$N=v5.join(y8,"device-tokens.json"),GN=v5.join(y8,"notification-preferences.json");class WN{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if((await Bun.$`test -d ${y8}`.quiet().nothrow()).exitCode!==0)await Bun.$`mkdir -p ${y8}`.quiet(),c_.debug("[NotificationStorage] Created .ccc directory:",y8)}catch(_){throw c_.error("[NotificationStorage] Error ensuring directory:",_),_}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let _=Bun.file($N);if(await _.exists()){let T=await _.text();return this.tokensCache=JSON.parse(T),c_.debug("[NotificationStorage] Loaded tokens:",{count:this.tokensCache?.tokens?.length||0}),this.tokensCache}}catch(_){c_.warn("[NotificationStorage] Error loading tokens, starting fresh:",_)}return this.tokensCache={tokens:[]},this.tokensCache}async saveTokens(_){try{await this.ensureDirectory(),await Bun.write($N,JSON.stringify(_,null,2)),this.tokensCache=_,c_.debug("[NotificationStorage] Saved tokens:",{count:_.tokens.length})}catch(T){throw c_.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,c_.info("[NotificationStorage] Updated device token:",{deviceId:_,platform:E,hasExpoPushToken:!!A});else J.tokens.push(Z),c_.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),c_.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),c_.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(GN);if(await _.exists()){let T=await _.text();return this.preferencesCache=JSON.parse(T),c_.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys(this.preferencesCache?.preferences||{}).length}),this.preferencesCache}}catch(_){c_.warn("[NotificationStorage] Error loading preferences, starting fresh:",_)}return this.preferencesCache={preferences:{}},this.preferencesCache}async savePreferences(_){try{await this.ensureDirectory(),await Bun.write(GN,JSON.stringify(_,null,2)),this.preferencesCache=_,c_.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(_.preferences).length})}catch(T){throw c_.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),c_.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),c_.info("[NotificationStorage] Updated preferences:",{deviceId:_,updates:T}),A.preferences[_]}async isNotificationEnabled(_,T){return(await this.getPreferences(_))[T]}clearCache(){this.tokensCache=null,this.preferencesCache=null,c_.debug("[NotificationStorage] Cleared cache")}}var S1=new WN;var U9=null;async function NN(){if(!U9)U9=await import("expo-server-sdk");return U9}var $1=k();class QN{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;async getExpo(){if(!this.expo){let _=await NN();this.expo=new _.default}return this.expo}async isValidToken(_){return(await NN()).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 v8=new QN;var Q_=k(),MN=200,eh=900000;class h5{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(()=>{v8.checkReceipts().catch((_)=>{Q_.error("[Notification] Error checking receipts:",_)})},eh),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=VN.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(`
2640
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(`
2641
- `)}if(!T.trim())return null;if(T.length>QN)T=T.substring(0,QN)+"...";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 v8.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 _=v8.getStats();return{name:this.name,running:this.running,startedAt:this.startedAt,registeredDevices:0,notificationsSent:_.notificationsSent,lastNotificationAt:_.lastNotificationAt}}}class W9{services=[];startedServices=[];logger=h();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 VN from"os";function zN(){let _=VN.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 FN(){let _=VN.hostname().toLowerCase();if(_.endsWith(".local"))_=_.slice(0,-6);return _=_.replace(/\./g,"-"),_||"ccc-server"}var CN=process.argv.slice(2);if(CN.includes("--version")||CN.includes("-v"))console.log(`ccc v${G1()}`),process.exit(0);function sh(_){let T=h();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 th(){try{B9();let _=z9();C9(_.debug);let T=h();T.info("Backend v2 starting...");let A=F9(_);if(_.debug)T.debug("Configuration",A);let E=new uA(A.mqtt),L=new $5({host:"localhost",port:A.mqtt.port,username:A.mqtt.auth?.username,password:A.mqtt.auth?.password}),J=new U5(A.terminal),X=new N5(A.router),H=new C5(A.autoUpdate),Z=new O5,Y=new R5,K=new D5(J),$=new P5(A.claudeAgent),G=new x5,U=new w5,V=new y5,N=new W9;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 Q5(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=zN(),R=F?`${F}:${A.router.port}`:void 0;if(z&&z.getStatus().active)Q=z.getUrl()||void 0;let q=FN(),b={...A.qrcode,profileName:q,ipBasedUrl:R,ngrokUrl:Q},k=new F5(b);N.addService(k),await k.start(),N.printStatus(),T.info("Backend v2 is ready"),sh(k);let g=!1,l=async(c)=>{if(g){T.warn("Shutdown already in progress, ignoring signal");return}g=!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(_){h().error("Fatal error",_),process.exit(1)}}th();
2641
+ `)}if(!T.trim())return null;if(T.length>MN)T=T.substring(0,MN)+"...";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 v8.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 _=v8.getStats();return{name:this.name,running:this.running,startedAt:this.startedAt,registeredDevices:0,notificationsSent:_.notificationsSent,lastNotificationAt:_.lastNotificationAt}}}class W9{services=[];startedServices=[];logger=k();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 zN from"os";function FN(){let _=zN.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 CN(){let _=zN.hostname().toLowerCase();if(_.endsWith(".local"))_=_.slice(0,-6);return _=_.replace(/\./g,"-"),_||"ccc-server"}var ON=process.argv.slice(2);if(ON.includes("--version")||ON.includes("-v"))console.log(`ccc v${G1()}`),process.exit(0);function _k(_){let T=k();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 Tk(){try{B9();let _=z9();C9(_.debug);let T=k();T.info("Backend v2 starting...");let A=F9(_);if(_.debug)T.debug("Configuration",A);let E=new uA(A.mqtt),L=new $5({host:"localhost",port:A.mqtt.port,username:A.mqtt.auth?.username,password:A.mqtt.auth?.password}),J=new U5(A.terminal),X=new N5(A.router),H=new C5(A.autoUpdate),Z=new R5,Y=new D5,K=new B5(J),$=new x5(A.claudeAgent),G=new S5,U=new y5,V=new h5,N=new W9;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 Q5(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=FN(),R=F?`${F}:${A.router.port}`:void 0;if(z&&z.getStatus().active)Q=z.getUrl()||void 0;let q=CN(),f={...A.qrcode,profileName:q,ipBasedUrl:R,ngrokUrl:Q},S=new F5(f);N.addService(S),await S.start(),N.printStatus(),T.info("Backend v2 is ready"),_k(S);let g=!1,l=async(c)=>{if(g){T.warn("Shutdown already in progress, ignoring signal");return}g=!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(_){k().error("Fatal error",_),process.exit(1)}}Tk();