@naarang/ccc 2.0.0-alpha.3 → 2.0.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +43 -43
- package/dist/scripts/build-binaries.ts +58 -0
- package/dist/scripts/build-dist.ts +36 -0
- package/dist/scripts/install.ps1 +159 -0
- package/dist/scripts/install.sh +197 -0
- package/package.json +11 -7
- package/scripts/build-binaries.ts +58 -0
- package/scripts/build-dist.ts +36 -0
- package/scripts/install.ps1 +159 -0
- package/scripts/install.sh +197 -0
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var VN=Object.create;var{getPrototypeOf:zN,defineProperty:$9,getOwnPropertyNames:FN}=Object;var CN=Object.prototype.hasOwnProperty;var v_=(_,T,A)=>{A=_!=null?VN(zN(_)):{};let E=T||!_||!_.__esModule?$9(A,"default",{value:_,enumerable:!0}):A;for(let L of FN(_))if(!CN.call(E,L))$9(E,L,{get:()=>_[L],enumerable:!0});return E};var W=(_,T)=>()=>(T||_((T={exports:{}}).exports,T),T.exports);var j=import.meta.require;var U9=W((rh,ON)=>{ON.exports={name:"@naarang/ccc",version:"2.0.0-alpha.3",description:"Code Chat Connect - Control Claude Code from your mobile device",type:"module",main:"dist/index.js",bin:{ccc:"./bin/ccc.cjs"},scripts:{dev:"bun src/index.ts",build:"bun run clean && bun run build:dist && bun run copy-scripts","build:dist":"bun build src/index.ts --outdir dist --target bun --minify --external bun-pty --external expo-server-sdk --external @ngrok/ngrok","build:compile":"bun build --compile --minify --sourcemap src/index.ts --outfile ccc","copy-scripts":`node -e "require('fs').cpSync('scripts', 'dist/scripts', {recursive: true})"`,clean:"rm -rf dist","type-check":"tsc --noEmit",setup:"bun install","test:tools":"bun run scripts/test-claude-tools.ts",prepublishOnly:"bun run build",postinstall:"node scripts/postinstall.cjs || true"},keywords:["ccc","ccc-ui","claude","claude-code","mqtt","chat","mobile","ai","assistant","cli","bun"],author:"Vishal",license:"UNLICENSED",private:!1,publishConfig:{access:"public"},files:["dist","bin","scripts","README.md","LICENSE"],preferGlobal:!0,engines:{bun:">=1.0.0"},dependencies:{"@ngrok/ngrok":"^1.5.2","@seriousme/opifex":"^1.11.2","@types/bun":"^1.3.2","@types/qrcode-terminal":"^0.12.2","@types/ws":"^8.18.1","@xterm/addon-fit":"^0.10.0","@xterm/xterm":"^5.5.0",aedes:"^0.51.3","aedes-server-factory":"^0.2.1","bonjour-service":"^1.3.0","bun-pty":"^0.4.2","expo-server-sdk":"^4.0.0",figlet:"^1.9.3",mqtt:"^5.14.1","node-gyp":"11.4.2","qrcode-terminal":"^0.12.0",ws:"^8.18.3"},devDependencies:{typescript:"^5"}}});var O9=W((Gk,C9)=>{C9.exports=hN;var vN=Object.prototype.hasOwnProperty;function hN(){var _={};for(var T=0;T<arguments.length;T++){var A=arguments[T];for(var E in A)if(vN.call(A,E))_[E]=A[E]}return _}});var k8=W(($k,R9)=>{function kN(_){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}}R9.exports=kN});var h5=W((Uk,B9)=>{var fN=O9(),D9=k8(),bN={released:R0,results:!0};function gN(_){_=fN(bN,_);var T=_.released,A=D9(_.results?dN:mN),E=D9(uN),L=_.results?K:$,J=_.results?Y:G;return X;function X(U,V,N,z){var Q=A.get();if(z=z||R0,V.length===0)z.call(U),T(Q);else{if(Q._callback=z,Q._callThat=U,Q._release=H,typeof V==="function")J(U,V,N,Q);else L(U,V,N,Q);if(Q._count===0)Q.release()}}function H(U){A.release(U),T(U)}function Z(U){E.release(U)}function Y(U,V,N,z){var Q=null;z._count=N.length,z._results=Array(z._count);for(var F=0;F<N.length;F++)if(Q=E.get(),Q._release=Z,Q.parent=z,Q.pos=F,U)V.call(U,N[F],Q.release);else V(N[F],Q.release)}function K(U,V,N,z){var Q=null,F=R0;z._count=V.length,z._results=Array(z._count);for(var R=0;R<V.length;R++)if(Q=E.get(),Q._release=Z,Q.parent=z,Q.pos=R,F=V[R],U)if(F.length===1)F.call(U,Q.release);else F.call(U,N,Q.release);else if(F.length===1)F(Q.release);else F(N,Q.release)}function G(U,V,N,z){z._count=N.length;for(var Q=0;Q<N.length;Q++)if(U)V.call(U,N[Q],z.release);else V(N[Q],z.release)}function $(U,V,N,z){var Q=null;z._count=V.length;for(var F=0;F<V.length;F++)if(Q=V[F],U)if(Q.length===1)Q.call(U,z.release);else Q.call(U,N,z.release);else if(Q.length===1)Q(z.release);else Q(N,z.release)}}function mN(){this._count=-1,this._callback=R0,this._callThat=null,this._release=null,this.next=null;var _=this,T=0;this.release=function(){var A=_._callback;if(++T===_._count||_._count===0){if(_._callThat)A.call(_._callThat);else A();_._callback=R0,_._callThat=null,T=0,_._release(_)}}}function uN(){this.pos=-1,this._release=R0,this.parent=null,this.next=null;var _=this;this.release=function(T,A){_.parent.release(T,_.pos,A),_.pos=-1,_.parent=null,_._release(_)}}function dN(){this._count=-1,this._callback=R0,this._results=null,this._err=null,this._callThat=null,this._release=R0,this.next=null;var _=this,T=0;this.release=function(A,E,L){if(_._err=_._err||A,E>=0)_._results[E]=L;var J=_._callback;if(++T===_._count||_._count===0){if(_._callThat)J.call(_._callThat,_._err,_._results);else J(_._err,_._results);_._callback=R0,_._results=null,_._err=null,_._callThat=null,T=0,_._release(_)}}}function R0(){}B9.exports=gN});var P9=W((Wk,I9)=>{var cN={results:!0};function pN(_){_=Object.assign({},cN,_);var T,A;if(_.results)T=iN,A=aN;else T=lN,A=nN;return E;function E(L,J,X,H){if(H=(H||oN).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 lN(_,T,A){var E=0,L=T.length;J();function J(){if(E<L)f8(_,T[E++],J);else A()}}function nN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=q9;else J=f8;X();function X(){if(E<L)J(_[E++],T,X);else A()}}function iN(_,T,A){var E=0,L=T.length,J=Array(L);X(null,null);function X(H,Z){if(H){A(H);return}if(E>0)J[E-1]=Z;if(E<L)f8(_,T[E++],X);else A(null,J)}}function aN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=q9;else J=f8;var X=Array(L);H(null,null);function H(Z,Y){if(Z){A(Z);return}if(E>0)X[E-1]=Y;if(E<L)J(_[E++],T,H);else A(null,X)}}function q9(_,T,A){_(A)}function f8(_,T,A){_(T,A)}function oN(){}I9.exports=pN});var w9=W((j9)=>{Object.defineProperty(j9,"__esModule",{value:!0});j9.default=void 0;var Nk=j9.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var v9=W((S9)=>{Object.defineProperty(S9,"__esModule",{value:!0});S9.default=void 0;var Mk=S9.default="00000000-0000-0000-0000-000000000000"});var f9=W((h9)=>{Object.defineProperty(h9,"__esModule",{value:!0});h9.default=void 0;var zk=h9.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((b9)=>{Object.defineProperty(b9,"__esModule",{value:!0});b9.default=void 0;var rN=sN(f9());function sN(_){return _&&_.__esModule?_:{default:_}}function tN(_){return typeof _==="string"&&rN.default.test(_)}var Ck=b9.default=tN});var j4=W((m9)=>{Object.defineProperty(m9,"__esModule",{value:!0});m9.default=void 0;var eN=_Q(P4());function _Q(_){return _&&_.__esModule?_:{default:_}}function TQ(_){if(!(0,eN.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 Rk=m9.default=TQ});var D0=W((c9)=>{Object.defineProperty(c9,"__esModule",{value:!0});c9.default=void 0;c9.unsafeStringify=d9;var AQ=EQ(P4());function EQ(_){return _&&_.__esModule?_:{default:_}}var b_=[];for(let _=0;_<256;++_)b_.push((_+256).toString(16).slice(1));function d9(_,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 LQ(_,T=0){let A=d9(_,T);if(!(0,AQ.default)(A))throw TypeError("Stringified UUID is invalid");return A}var Bk=c9.default=LQ});var m8=W((l9)=>{Object.defineProperty(l9,"__esModule",{value:!0});l9.default=ZQ;var XQ=HQ(j("crypto"));function HQ(_){return _&&_.__esModule?_:{default:_}}var g8=new Uint8Array(256),b8=g8.length;function ZQ(){if(b8>g8.length-16)XQ.default.randomFillSync(g8),b8=0;return g8.slice(b8,b8+=16)}});var g5=W((n9)=>{Object.defineProperty(n9,"__esModule",{value:!0});n9.default=void 0;var KQ=$Q(m8()),GQ=D0();function $Q(_){return _&&_.__esModule?_:{default:_}}var k5,u8,f5=0,b5=0;function UQ(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let{node:J,clockseq:X}=_;if(!_._v6){if(!J)J=k5;if(X==null)X=u8}if(J==null||X==null){let $=_.random||(_.rng||KQ.default)();if(J==null){if(J=[$[0],$[1],$[2],$[3],$[4],$[5]],!k5&&!_._v6)J[0]|=1,k5=J}if(X==null){if(X=($[6]<<8|$[7])&16383,u8===void 0&&!_._v6)u8=X}}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:b5+1,Y=H-f5+(Z-b5)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>f5)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");f5=H,b5=Z,u8=X,H+=12219292800000;let K=((H&268435455)*1e4+Z)%4294967296;L[E++]=K>>>24&255,L[E++]=K>>>16&255,L[E++]=K>>>8&255,L[E++]=K&255;let G=H/4294967296*1e4&268435455;L[E++]=G>>>8&255,L[E++]=G&255,L[E++]=G>>>24&15|16,L[E++]=G>>>16&255,L[E++]=X>>>8|128,L[E++]=X&255;for(let $=0;$<6;++$)L[E+$]=J[$];return T||(0,GQ.unsafeStringify)(L)}var Pk=n9.default=UQ});var m5=W((a9)=>{Object.defineProperty(a9,"__esModule",{value:!0});a9.default=MQ;var WQ=QQ(j4()),NQ=D0();function QQ(_){return _&&_.__esModule?_:{default:_}}function MQ(_){let T=typeof _==="string"?(0,WQ.default)(_):_,A=VQ(T);return typeof _==="string"?(0,NQ.unsafeStringify)(A):A}function VQ(_,T=!1){return Uint8Array.of((_[6]&15)<<4|_[7]>>4&15,(_[7]&15)<<4|(_[4]&240)>>4,(_[4]&15)<<4|(_[5]&240)>>4,(_[5]&15)<<4|(_[0]&240)>>4,(_[0]&15)<<4|(_[1]&240)>>4,(_[1]&15)<<4|(_[2]&240)>>4,96|_[2]&15,_[3],_[8],_[9],_[10],_[11],_[12],_[13],_[14],_[15])}});var u5=W((o9)=>{Object.defineProperty(o9,"__esModule",{value:!0});o9.URL=o9.DNS=void 0;o9.default=qQ;var FQ=D0(),CQ=OQ(j4());function OQ(_){return _&&_.__esModule?_:{default:_}}function RQ(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var DQ=o9.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",BQ=o9.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function qQ(_,T,A){function E(L,J,X,H){var Z;if(typeof L==="string")L=RQ(L);if(typeof J==="string")J=(0,CQ.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,FQ.unsafeStringify)(Y)}try{E.name=_}catch(L){}return E.DNS=DQ,E.URL=BQ,E}});var e9=W((s9)=>{Object.defineProperty(s9,"__esModule",{value:!0});s9.default=void 0;var jQ=xQ(j("crypto"));function xQ(_){return _&&_.__esModule?_:{default:_}}function wQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return jQ.default.createHash("md5").update(_).digest()}var Sk=s9.default=wQ});var E7=W((T7)=>{Object.defineProperty(T7,"__esModule",{value:!0});T7.default=void 0;var SQ=_7(u5()),yQ=_7(e9());function _7(_){return _&&_.__esModule?_:{default:_}}var vQ=(0,SQ.default)("v3",48,yQ.default),vk=T7.default=vQ});var X7=W((L7)=>{Object.defineProperty(L7,"__esModule",{value:!0});L7.default=void 0;var hQ=kQ(j("crypto"));function kQ(_){return _&&_.__esModule?_:{default:_}}var kk=L7.default={randomUUID:hQ.default.randomUUID}});var G7=W((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});Y7.default=void 0;var H7=Z7(X7()),fQ=Z7(m8()),bQ=D0();function Z7(_){return _&&_.__esModule?_:{default:_}}function gQ(_,T,A){if(H7.default.randomUUID&&!T&&!_)return H7.default.randomUUID();_=_||{};let E=_.random||(_.rng||fQ.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,bQ.unsafeStringify)(E)}var bk=Y7.default=gQ});var W7=W(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});$7.default=void 0;var mQ=uQ(j("crypto"));function uQ(_){return _&&_.__esModule?_:{default:_}}function dQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return mQ.default.createHash("sha1").update(_).digest()}var mk=$7.default=dQ});var V7=W((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});Q7.default=void 0;var cQ=N7(u5()),pQ=N7(W7());function N7(_){return _&&_.__esModule?_:{default:_}}var lQ=(0,cQ.default)("v5",80,pQ.default),dk=Q7.default=lQ});var C7=W((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});F7.default=oQ;var nQ=D0(),iQ=z7(g5()),aQ=z7(m5());function z7(_){return _&&_.__esModule?_:{default:_}}function oQ(_={},T,A=0){let E=(0,iQ.default)({..._,_v6:!0},new Uint8Array(16));if(E=(0,aQ.default)(E),T){for(let L=0;L<16;L++)T[A+L]=E[L];return T}return(0,nQ.unsafeStringify)(E)}});var R7=W((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});O7.default=_M;var sQ=eQ(j4()),tQ=D0();function eQ(_){return _&&_.__esModule?_:{default:_}}function _M(_){let T=typeof _==="string"?(0,sQ.default)(_):_,A=TM(T);return typeof _==="string"?(0,tQ.unsafeStringify)(A):A}function TM(_){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 P7=W((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});q7.default=void 0;var EM=JM(m8()),LM=D0();function JM(_){return _&&_.__esModule?_:{default:_}}var D7=null,B7=null,h1=0;function XM(_,T,A){_=_||{};let E=T&&A||0,L=T||new Uint8Array(16),J=_.random||(_.rng||EM.default)(),X=_.msecs!==void 0?_.msecs:Date.now(),H=_.seq!==void 0?_.seq:null,Z=B7,Y=D7;if(X>h1&&_.msecs===void 0){if(h1=X,H!==null)Z=null,Y=null}if(H!==null){if(H>2147483647)H=2147483647;Z=H>>>19&4095,Y=H&524287}if(Z===null||Y===null)Z=J[6]&127,Z=Z<<8|J[7],Y=J[8]&63,Y=Y<<8|J[9],Y=Y<<5|J[10]>>>3;if(X+1e4>h1&&H===null){if(++Y>524287){if(Y=0,++Z>4095)Z=0,h1++}}else h1=X;return B7=Z,D7=Y,L[E++]=h1/1099511627776&255,L[E++]=h1/4294967296&255,L[E++]=h1/16777216&255,L[E++]=h1/65536&255,L[E++]=h1/256&255,L[E++]=h1&255,L[E++]=Z>>>4&15|112,L[E++]=Z&255,L[E++]=Y>>>13&63|128,L[E++]=Y>>>5&255,L[E++]=Y<<3&255|J[10]&7,L[E++]=J[11],L[E++]=J[12],L[E++]=J[13],L[E++]=J[14],L[E++]=J[15],T||(0,LM.unsafeStringify)(L)}var nk=q7.default=XM});var w7=W((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});j7.default=void 0;var HM=ZM(P4());function ZM(_){return _&&_.__esModule?_:{default:_}}function YM(_){if(!(0,HM.default)(_))throw TypeError("Invalid UUID");return parseInt(_.slice(14,15),16)}var ak=j7.default=YM});var S7=W((p_)=>{Object.defineProperty(p_,"__esModule",{value:!0});Object.defineProperty(p_,"MAX",{enumerable:!0,get:function(){return KM.default}});Object.defineProperty(p_,"NIL",{enumerable:!0,get:function(){return GM.default}});Object.defineProperty(p_,"parse",{enumerable:!0,get:function(){return $M.default}});Object.defineProperty(p_,"stringify",{enumerable:!0,get:function(){return UM.default}});Object.defineProperty(p_,"v1",{enumerable:!0,get:function(){return WM.default}});Object.defineProperty(p_,"v1ToV6",{enumerable:!0,get:function(){return NM.default}});Object.defineProperty(p_,"v3",{enumerable:!0,get:function(){return QM.default}});Object.defineProperty(p_,"v4",{enumerable:!0,get:function(){return MM.default}});Object.defineProperty(p_,"v5",{enumerable:!0,get:function(){return VM.default}});Object.defineProperty(p_,"v6",{enumerable:!0,get:function(){return zM.default}});Object.defineProperty(p_,"v6ToV1",{enumerable:!0,get:function(){return FM.default}});Object.defineProperty(p_,"v7",{enumerable:!0,get:function(){return CM.default}});Object.defineProperty(p_,"validate",{enumerable:!0,get:function(){return OM.default}});Object.defineProperty(p_,"version",{enumerable:!0,get:function(){return RM.default}});var KM=J1(w9()),GM=J1(v9()),$M=J1(j4()),UM=J1(D0()),WM=J1(g5()),NM=J1(m5()),QM=J1(E7()),MM=J1(G7()),VM=J1(V7()),zM=J1(C7()),FM=J1(R7()),CM=J1(P7()),OM=J1(P4()),RM=J1(w7());function J1(_){return _&&_.__esModule?_:{default:_}}});var uT=W((sk,y7)=>{function DM(_,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}y7.exports=DM});var d5=W((tk,v7)=>{var k1=j("util");v7.exports=function(_,T){class A extends _{constructor(E){super(E);this.addP=k1.promisify(this.add_async),this.removeP=k1.promisify(this.remove_async),this.matchP=k1.promisify(this.match_async),this.testP=k1.promisify(this.test_async),this.clearP=k1.promisify(this.clear_async),this._get_visitorP=k1.promisify(this.get_visitor_async),this._visit_nextP=k1.promisify(this.visit_next_async),this._get_restorerP=k1.promisify(this.get_restorer_async),this._restore_nextP=k1.promisify(this.restore_next_async),this._match_iterP=k1.promisify(this.match_iter_async),this._match_nextP=k1.promisify(this.match_next_async)}*visit(){let E=this.get_visitor();while(!0){let L=this.visit_next(E);if(L===void 0)break;yield L}}async*visitP(){let E=await this._get_visitorP();while(!0){let L=await this._visit_nextP(E);if(L===void 0)break;yield L}}*match_iter(E,L){let J=super.match_iter(E,L);while(!0){let X=this.match_next(J);if(X===void 0)break;yield X.value}}async*match_iterP(E,L){let J=await this._match_iterP(E,L);while(!0){let X=await this._match_nextP(J);if(X===void 0)break;yield X.value}}get_trie(){let E=new T(this.options),L=E.get_restorer();for(let J of this.visit())L(J);return E.get_trie()}get_restorer(E){let L=super.get_restorer(E);return(J)=>{super.restore_next(L,J)}}async get_restorerP(E){let L=await this._get_restorerP(E);return async(J)=>{await this._restore_nextP(L,J)}}}return A.is_native=!0,A.nonNative=T,A}});var l5=W((k7)=>{var d8=j("util");function L_(_){if(_=_||{},this._separator=_.separator||".",this._wildcard_one=_.wildcard_one||"*",this._wildcard_some=_.wildcard_some||"#",this._max_words=_.max_words||100,this._max_wildcard_somes=_.max_wildcard_somes||3,this._match_empty_levels=_.match_empty_levels,this._trie=new Map,_.cache_adds instanceof Map)this._shortcuts=_.cache_adds;else if(_.cache_adds)this._shortcuts=new Map;if(_.cache_splits>0)this._cache_splits=_.cache_splits,this._split_cache=new Map}L_.prototype._initial_value=function(_){return[_]};L_.prototype._add_value=function(_,T){_[_.length]=T};L_.prototype._add_values=function(_,T){var A,E=_.length,L=T.length;for(A=0;A<L;A+=1)_[E+A]=T[A]};L_.prototype._iter_values=function(_,T){return _[Symbol.iterator](T)};L_.prototype._remove_value=function(_,T){if(T===void 0)return!0;var A=_.lastIndexOf(T);if(A>=0)_.splice(A,1);return _.length===0};L_.prototype._add=function(_,T,A,E){var L,J;if(T===A.length){if(L=E.get(this._separator),L)this._add_value(L,_);else L=this._initial_value(_),E.set(this._separator,L);return L}if(J=A[T],L=E.get(J),!L)L=new Map,E.set(J,L);return this._add(_,T+1,A,L)};L_.prototype._remove=function(_,T,A,E){var L,J,X;if(T===A.length){if(L=E.get(this._separator),L&&this._remove_value(L,_))return E.delete(this._separator),!0;return!1}if(J=A[T],L=E.get(J),!L)return!1;if(X=this._remove(_,T+1,A,L),L.size===0)E.delete(J);return X};L_.prototype._match_some=function(_,T,A,E,L){var J,X;for(X of E.keys())if(X!==this._separator){for(J=T;J<A.length;J+=1)_=this._match(_,J,A,E,L);break}return _};L_.prototype._match=function(_,T,A,E,L){var J,X;if(X=E.get(this._wildcard_some),X)_=this._match_some(_,T,A,X,L),_=this._match(_,A.length,A,X,L);if(T===A.length){if(X=E.get(this._separator),X)if(_.dest)this._add_values(_.dest,_.source,L),this._add_values(_.dest,X,L),_=_.dest;else if(_.source)_.dest=_.source,_.source=X;else this._add_values(_,X,L)}else{if(J=A[T],J!==this._wildcard_one&&J!==this._wildcard_some){if(X=E.get(J),X)_=this._match(_,T+1,A,X,L)}if(J||this._match_empty_levels){if(X=E.get(this._wildcard_one),X)_=this._match(_,T+1,A,X,L)}}return _};L_.prototype._match2=function(_,T,A){var E=this._match({source:_},0,this._split(T,!1),this._trie,A);return E.source||E};L_.prototype._test_some=function(_,T,A,E){var L,J;for(J of E.keys())if(J!==this._separator){for(L=T;L<A.length;L+=1)if(this._test(_,L,A,E))return!0;break}return!1};L_.prototype._test=function(_,T,A,E){var L,J;if(J=E.get(this._wildcard_some),J){if(this._test_some(_,T,A,J)||this._test(_,A.length,A,J))return!0}if(T===A.length){if(J=E.get(this._separator),J&&this.test_values(J,_))return!0}else{if(L=A[T],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=E.get(L),J&&this._test(_,T+1,A,J))return!0}if(L||this._match_empty_levels){if(J=E.get(this._wildcard_one),J&&this._test(_,T+1,A,J))return!0}}return!1};L_.prototype._match_some_iter=function*(_,T,A,E){var L,J;for(J of A.keys())if(J!==this._separator){for(L=_;L<T.length;L+=1)yield*this._match_iter(L,T,A,E);break}};L_.prototype._match_iter=function*(_,T,A,E){var L,J;if(J=A.get(this._wildcard_some),J)yield*this._match_some_iter(_,T,J,E),yield*this._match_iter(T.length,T,J,E);if(_===T.length){if(J=A.get(this._separator),J)yield*this._iter_values(J,E)}else{if(L=T[_],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=A.get(L),J)yield*this._match_iter(_+1,T,J,E)}if(L||this._match_empty_levels){if(J=A.get(this._wildcard_one),J)yield*this._match_iter(_+1,T,J,E)}}};L_.prototype._split_words=function(_){let T=_.split(this._separator);if(T.length>this._max_words)throw Error("too many words");return T};L_.prototype._split=function(_,T){let A;if(this._split_cache){if(A=this._split_cache.get(_),A===void 0){if(A=this._split_words(_),this._split_cache.set(_,A),this._split_cache.size>this._cache_splits)for(let E of this._split_cache.keys()){this._split_cache.delete(E);break}}}else A=this._split_words(_);if(T&&A.reduce((E,L)=>E+(L===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return A};L_.prototype.add=function(_,T){var A=this._shortcuts&&this._shortcuts.get(_);if(A)this._add_value(A,T);else if(A=this._add(T,0,this._split(_,!0),this._trie),this._shortcuts)this._shortcuts.set(_,A);return this};L_.prototype.remove=function(_,T){if(this._remove(T,0,this._split(_,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(_);return this};L_.prototype.match=function(_,T){return this._match2([],_,T)};L_.prototype.match_iter=function(_,T){return this._match_iter(0,this._split(_,!1),this._trie,T)};L_.prototype.test=function(_,T){return this._test(T,0,this._split(_,!1),this._trie)};L_.prototype.test_values=function(_,T){return _.indexOf(T)>=0};L_.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};L_.prototype.get_trie=function(){return this._trie};L_.prototype.visit=function*(){let _=[],T=this._trie.entries(),A=0;while(!0){if(A===0)yield{type:"start_entries"};let E=T.next();if(E.done){yield{type:"end_entries"};let X=_.pop();if(X===void 0)return;[T,A]=X;continue}let[L,J]=E.value;if(yield{type:"entry",key:L},++A,L===this._separator){if(yield{type:"start_values"},J[Symbol.iterator])for(let X of J)yield{type:"value",value:X};else yield{type:"value",value:J};yield{type:"end_values"};continue}_.push([T,A]),T=J.entries(),A=0}};L_.prototype.get_restorer=function(_){_=_||{};let T=[],A=this._trie,E="";return(L)=>{switch(L.type){case"entry":if(A=A||new Map,T.push([A,L.key,E]),A=A.get(L.key),_.cache_adds){if(E)E+=this._separator;E+=L.key}break;case"value":if(A)this._add_value(A,L.value);else A=this._initial_value(L.value);break;case"end_entries":if(A&&A.size===0)A=void 0;case"end_values":let J=T.pop();if(J===void 0)A=void 0,E="";else{let[X,H,Z]=J;if(A){if(_.cache_adds&&this._shortcuts&&L.type==="end_values")this._shortcuts.set(Z,A);X.set(H,A)}A=X,E=Z}break}}};function M1(_){L_.call(this,_)}d8.inherits(M1,L_);M1.prototype._initial_value=function(_){return new Set().add(_)};M1.prototype._add_value=function(_,T){_.add(T)};M1.prototype._add_values=function(_,T){T.forEach(function(A){_.add(A)})};M1.prototype._remove_value=function(_,T){if(T===void 0)return!0;return _.delete(T),_.size===0};M1.prototype.test_values=function(_,T){return _.has(T)};M1.prototype.match=function(_,T){return this._match2(new Set,_,T)};function r1(_){L_.call(this,_)}d8.inherits(r1,L_);r1.prototype._initial_value=function(){return!0};r1.prototype._add_value=function(){};r1.prototype._remove_value=function(){return!0};r1.prototype._iter_values=function*(){yield!0};r1.prototype.test_values=function(){return!0};r1.prototype.match=function(_,T){return this.test(_,T)};var c8=j("stream");function c5(_){c8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}d8.inherits(c5,c8.Readable);c5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function p5(_){c8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}d8.inherits(p5,c8.Writable);p5.prototype._write=function(_,T,A){this._restorer(_),A()};var h7=null;function BM(_){if(_!==h7){let T=d5();L_.nativeString=T(_.QlobberString,L_),L_.nativeNumber=T(_.QlobberNumber,L_),M1.nativeString=T(_.QlobberDedupString,M1),M1.nativeNumber=T(_.QlobberDedupNumber,M1),r1.native=T(_.QlobberTrue,r1),h7=_}return k7}k7.Qlobber=L_;k7.QlobberDedup=M1;k7.QlobberTrue=r1;k7.VisitorStream=c5;k7.RestorerStream=p5;k7.set_native=BM});var f7=W((_f,i5)=>{var SM=j("util"),yM=l5(),n5=yM.Qlobber;function V1(_){n5.call(this,_),this.subscriptionsCount=0}SM.inherits(V1,n5);V1.prototype._initial_value=function(_){this.subscriptionsCount+=1;let T={topic:_.topic,clientMap:new Map().set(_.clientId,{qos:_.qos,rh:_.rh,rap:_.rap,nl:_.nl})};return T[Symbol.iterator]=function*(A){if(A===void 0)for(let[E,L]of T.clientMap)yield{topic:T.topic,clientId:E,...L};else if(T.topic===A)for(let[E,L]of T.clientMap)yield{clientId:E,...L}},T};V1.prototype._add_value=function(_,T){var A=_.clientMap,E=A.size;if(A.set(T.clientId,{qos:T.qos,rh:T.rh,rap:T.rap,nl:T.nl}),A.size>E)this.subscriptionsCount+=1};V1.prototype._add_values=function(_,T,A){if(A===void 0)for(let[E,L]of T.clientMap)_.push({clientId:E,topic:T.topic,...L});else if(T.topic===A)for(let[E,L]of T.clientMap)_.push({clientId:E,...L})};V1.prototype._remove_value=function(_,T){var A=_.clientMap,E=A.size;A.delete(T.clientId);var L=A.size;if(L<E)this.subscriptionsCount-=1;return L===0};V1.prototype.test_values=function(_,T){var A=_.clientMap;return _.topic===T.topic&&A.size===1&&A.has(T.clientId)};V1.prototype.match=function(_,T){return this._match([],0,_.split(this._separator),this._trie,T)};V1.prototype.clear=function(){return this.subscriptionsCount=0,n5.prototype.clear.call(this)};V1.set_native=function(_){let T=d5();return V1.native=T(_.QlobberSub,V1),i5.exports};i5.exports=V1});var u7=W((Tf,o5)=>{var{Readable:x4}=j("stream"),vM=f7(),{QlobberTrue:hM}=l5(),a5=uT(),g7={wildcard_one:"+",wildcard_some:"#",separator:"/"};function*kM(_){for(let T of _)yield*T}function*b7(_,T){let A=new hM(g7);A.add(T);for(let[E,L]of _)if(A.test(E))yield L}function*fM(_,T){for(let A of _.values())if(!T[A.brokerId])yield A}function*bM(_,T){for(let[A,E]of _)if(E.has(T))yield A}class m7{#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 vM(g7)}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 b7(this.#J,A)});return x4.from(kM(T))}createRetainedStream(_){return x4.from(b7(this.#J,_))}addSubscriptions(_,T,A){let E=this.#L.get(_.id),L=this.#A;if(!E)E=new Map,this.#L.set(_.id,E),this.#z++;for(let J of T){let X=E.get(J.topic);if(J.qos>0)L.add(J.topic,{clientId:_.id,topic:J.topic,qos:J.qos,rh:J.rh,rap:J.rap,nl:J.nl});else if(X?.qos>0)L.remove(J.topic,{clientId:_.id,topic:J.topic});E.set(J.topic,{qos:J.qos,rh:J.rh,rap:J.rap,nl:J.nl})}A(null,_)}removeSubscriptions(_,T,A){let E=this.#L.get(_.id),L=this.#A;if(E){for(let J of T){let X=E.get(J);if(X!==void 0){if(X.qos>0)L.remove(J,{clientId:_.id,topic:J});E.delete(J)}}if(E.size===0)this.#z--,this.#L.delete(_.id)}A(null,_)}subscriptionsByClient(_,T){let A=null,E=this.#L.get(_.id);if(E){A=[];for(let[L,J]of E)A.push({topic:L,...J})}T(null,A,_)}countOffline(_){return _(null,this.#A.subscriptionsCount,this.#z)}subscriptionsByTopic(_,T){T(null,this.#A.match(_))}cleanSubscriptions(_,T){let A=this.#A,E=this.#L.get(_.id);if(E){for(let[L,J]of E)if(J.qos>0)A.remove(L,{clientId:_.id,topic:L});this.#z--,this.#L.delete(_.id)}T(null,_)}#W(_,T){let A=_.clientId,E=HT(this.#Y,A,[],!0);E[E.length]=new a5(T)}outgoingEnqueue(_,T,A){this.#W(_,T),process.nextTick(A)}outgoingEnqueueCombi(_,T,A){for(let E=0;E<_.length;E++)this.#W(_[E],T);process.nextTick(A)}outgoingUpdate(_,T,A){let E=HT(this.#Y,_.id,[],!0),L;for(let J=0;J<E.length;J++)if(L=E[J],L.brokerId===T.brokerId){if(L.brokerCounter===T.brokerCounter)return L.messageId=T.messageId,A(null,_,T)}else if(L.messageId===T.messageId)return E[J]=T,A(null,_,T);A(Error("no such packet"),_,T)}outgoingClearMessageId(_,T,A){let E=HT(this.#Y,_.id,[],!0),L;for(let J=0;J<E.length;J++)if(L=E[J],L.messageId===T.messageId)return E.splice(J,1),A(null,L);A()}outgoingStream(_){let T=[].concat(HT(this.#Y,_.id,[]));return x4.from(T)}incomingStorePacket(_,T,A){let E=_.id,L=HT(this.#K,E,{},!0);L[T.messageId]=new a5(T),L[T.messageId].messageId=T.messageId,A(null)}incomingGetPacket(_,T,A){let E=_.id,L=HT(this.#K,E,{}),J=null;if(this.#K.set(E,L),!L[T.messageId])J=Error("no such packet");A(J,L[T.messageId])}incomingDelPacket(_,T,A){let E=_.id,L=HT(this.#K,E,{}),J=L[T.messageId],X=null;if(!J)X=Error("no such packet");else delete L[T.messageId];A(X)}putWill(_,T,A){T.brokerId=this.broker.id,T.clientId=_.id,this.#N.set(_.id,T),A(null,_)}getWill(_,T){T(null,this.#N.get(_.id),_)}delWill(_,T){let A=this.#N.get(_.id);this.#N.delete(_.id),T(null,A,_)}streamWill(_={}){return x4.from(fM(this.#N,_))}getClientList(_){return x4.from(bM(this.#L,_))}destroy(_){if(this.#J=null,_)_(null)}}function HT(_,T,A,E=!1){let L=_.get(T);if(L===void 0&&E)_.set(T,A);return L||A}o5.exports=()=>{return new m7};o5.exports.Packet=a5});var c7=W((Af,d7)=>{var f1=j("util");d7.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 n7=W((l7)=>{var p8=j("util");function J_(_){if(_=_||{},this._separator=_.separator||".",this._wildcard_one=_.wildcard_one||"*",this._wildcard_some=_.wildcard_some||"#",this._max_words=_.max_words||100,this._max_wildcard_somes=_.max_wildcard_somes||3,this._match_empty_levels=_.match_empty_levels,this._trie=new Map,_.cache_adds instanceof Map)this._shortcuts=_.cache_adds;else if(_.cache_adds)this._shortcuts=new Map;if(_.cache_splits>0)this._cache_splits=_.cache_splits,this._split_cache=new Map}J_.prototype._initial_value=function(_){return[_]};J_.prototype._add_value=function(_,T){_[_.length]=T};J_.prototype._add_values=function(_,T){var A,E=_.length,L=T.length;for(A=0;A<L;A+=1)_[E+A]=T[A]};J_.prototype._iter_values=function(_,T){return _[Symbol.iterator](T)};J_.prototype._remove_value=function(_,T){if(T===void 0)return!0;var A=_.lastIndexOf(T);if(A>=0)_.splice(A,1);return _.length===0};J_.prototype._add=function(_,T,A,E){var L,J;if(T===A.length){if(L=E.get(this._separator),L)this._add_value(L,_);else L=this._initial_value(_),E.set(this._separator,L);return L}if(J=A[T],L=E.get(J),!L)L=new Map,E.set(J,L);return this._add(_,T+1,A,L)};J_.prototype._remove=function(_,T,A,E){var L,J,X;if(T===A.length){if(L=E.get(this._separator),L&&this._remove_value(L,_))return E.delete(this._separator),!0;return!1}if(J=A[T],L=E.get(J),!L)return!1;if(X=this._remove(_,T+1,A,L),L.size===0)E.delete(J);return X};J_.prototype._match_some=function(_,T,A,E,L){var J,X;for(X of E.keys())if(X!==this._separator){for(J=T;J<A.length;J+=1)_=this._match(_,J,A,E,L);break}return _};J_.prototype._match=function(_,T,A,E,L){var J,X;if(X=E.get(this._wildcard_some),X)_=this._match_some(_,T,A,X,L),_=this._match(_,A.length,A,X,L);if(T===A.length){if(X=E.get(this._separator),X)if(_.dest)this._add_values(_.dest,_.source,L),this._add_values(_.dest,X,L),_=_.dest;else if(_.source)_.dest=_.source,_.source=X;else this._add_values(_,X,L)}else{if(J=A[T],J!==this._wildcard_one&&J!==this._wildcard_some){if(X=E.get(J),X)_=this._match(_,T+1,A,X,L)}if(J||this._match_empty_levels){if(X=E.get(this._wildcard_one),X)_=this._match(_,T+1,A,X,L)}}return _};J_.prototype._match2=function(_,T,A){var E=this._match({source:_},0,this._split(T,!1),this._trie,A);return E.source||E};J_.prototype._test_some=function(_,T,A,E){var L,J;for(J of E.keys())if(J!==this._separator){for(L=T;L<A.length;L+=1)if(this._test(_,L,A,E))return!0;break}return!1};J_.prototype._test=function(_,T,A,E){var L,J;if(J=E.get(this._wildcard_some),J){if(this._test_some(_,T,A,J)||this._test(_,A.length,A,J))return!0}if(T===A.length){if(J=E.get(this._separator),J&&this.test_values(J,_))return!0}else{if(L=A[T],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=E.get(L),J&&this._test(_,T+1,A,J))return!0}if(L||this._match_empty_levels){if(J=E.get(this._wildcard_one),J&&this._test(_,T+1,A,J))return!0}}return!1};J_.prototype._match_some_iter=function*(_,T,A,E){var L,J;for(J of A.keys())if(J!==this._separator){for(L=_;L<T.length;L+=1)yield*this._match_iter(L,T,A,E);break}};J_.prototype._match_iter=function*(_,T,A,E){var L,J;if(J=A.get(this._wildcard_some),J)yield*this._match_some_iter(_,T,J,E),yield*this._match_iter(T.length,T,J,E);if(_===T.length){if(J=A.get(this._separator),J)yield*this._iter_values(J,E)}else{if(L=T[_],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=A.get(L),J)yield*this._match_iter(_+1,T,J,E)}if(L||this._match_empty_levels){if(J=A.get(this._wildcard_one),J)yield*this._match_iter(_+1,T,J,E)}}};J_.prototype._split_words=function(_){let T=_.split(this._separator);if(T.length>this._max_words)throw Error("too many words");return T};J_.prototype._split=function(_,T){let A;if(this._split_cache){if(A=this._split_cache.get(_),A===void 0){if(A=this._split_words(_),this._split_cache.set(_,A),this._split_cache.size>this._cache_splits)for(let E of this._split_cache.keys()){this._split_cache.delete(E);break}}}else A=this._split_words(_);if(T&&A.reduce((E,L)=>E+(L===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return A};J_.prototype.add=function(_,T){var A=this._shortcuts&&this._shortcuts.get(_);if(A)this._add_value(A,T);else if(A=this._add(T,0,this._split(_,!0),this._trie),this._shortcuts)this._shortcuts.set(_,A);return this};J_.prototype.remove=function(_,T){if(this._remove(T,0,this._split(_,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(_);return this};J_.prototype.match=function(_,T){return this._match2([],_,T)};J_.prototype.match_iter=function(_,T){return this._match_iter(0,this._split(_,!1),this._trie,T)};J_.prototype.test=function(_,T){return this._test(T,0,this._split(_,!1),this._trie)};J_.prototype.test_values=function(_,T){return _.indexOf(T)>=0};J_.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};J_.prototype.get_trie=function(){return this._trie};J_.prototype.visit=function*(){let _=[],T=this._trie.entries(),A=0;while(!0){if(A===0)yield{type:"start_entries"};let E=T.next();if(E.done){yield{type:"end_entries"};let X=_.pop();if(X===void 0)return;[T,A]=X;continue}let[L,J]=E.value;if(yield{type:"entry",key:L},++A,L===this._separator){if(yield{type:"start_values"},J[Symbol.iterator])for(let X of J)yield{type:"value",value:X};else yield{type:"value",value:J};yield{type:"end_values"};continue}_.push([T,A]),T=J.entries(),A=0}};J_.prototype.get_restorer=function(_){_=_||{};let T=[],A=this._trie,E="";return(L)=>{switch(L.type){case"entry":if(A=A||new Map,T.push([A,L.key,E]),A=A.get(L.key),_.cache_adds){if(E)E+=this._separator;E+=L.key}break;case"value":if(A)this._add_value(A,L.value);else A=this._initial_value(L.value);break;case"end_entries":if(A&&A.size===0)A=void 0;case"end_values":let J=T.pop();if(J===void 0)A=void 0,E="";else{let[X,H,Z]=J;if(A){if(_.cache_adds&&this._shortcuts&&L.type==="end_values")this._shortcuts.set(Z,A);X.set(H,A)}A=X,E=Z}break}}};function z1(_){J_.call(this,_)}p8.inherits(z1,J_);z1.prototype._initial_value=function(_){return new Set().add(_)};z1.prototype._add_value=function(_,T){_.add(T)};z1.prototype._add_values=function(_,T){T.forEach(function(A){_.add(A)})};z1.prototype._remove_value=function(_,T){if(T===void 0)return!0;return _.delete(T),_.size===0};z1.prototype.test_values=function(_,T){return _.has(T)};z1.prototype.match=function(_,T){return this._match2(new Set,_,T)};function s1(_){J_.call(this,_)}p8.inherits(s1,J_);s1.prototype._initial_value=function(){return!0};s1.prototype._add_value=function(){};s1.prototype._remove_value=function(){return!0};s1.prototype._iter_values=function*(){yield!0};s1.prototype.test_values=function(){return!0};s1.prototype.match=function(_,T){return this.test(_,T)};var l8=j("stream");function r5(_){l8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}p8.inherits(r5,l8.Readable);r5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function s5(_){l8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}p8.inherits(s5,l8.Writable);s5.prototype._write=function(_,T,A){this._restorer(_),A()};var p7=null;function gM(_){if(_!==p7){let T=c7();J_.nativeString=T(_.QlobberString,J_),J_.nativeNumber=T(_.QlobberNumber,J_),z1.nativeString=T(_.QlobberDedupString,z1),z1.nativeNumber=T(_.QlobberDedupNumber,z1),s1.native=T(_.QlobberTrue,s1),p7=_}return l7}l7.Qlobber=J_;l7.QlobberDedup=z1;l7.QlobberTrue=s1;l7.VisitorStream=r5;l7.RestorerStream=s5;l7.set_native=gM});var a7=W((Lf,i7)=>{var{Qlobber:nM}=n7(),dT=j("assert"),iM=h5();function t1(_){if(!(this instanceof t1))return new t1(_);let T=this;_=_||{},_.matchEmptyLevels=_.matchEmptyLevels===void 0?!0:!!_.matchEmptyLevels,_.separator=_.separator||"/",_.wildcardOne=_.wildcardOne||"+",_.wildcardSome=_.wildcardSome||"#",this._messageQueue=[],this._messageCallbacks=[],this._parallel=iM({results:!1,released:A}),this.concurrency=_.concurrency||0,this.current=0,this._doing=!1,this._matcher=new nM({match_empty_levels:_.matchEmptyLevels,separator:_.separator,wildcard_one:_.wildcardOne,wildcard_some:_.wildcardSome}),this.closed=!1,this._released=A;function A(){T.current--;let E=T._messageQueue.shift(),L=T._messageCallbacks.shift();if(E)T._do(E,L);else T._doing=!1}}Object.defineProperty(t1.prototype,"length",{get:function(){return this._messageQueue.length},enumerable:!0});t1.prototype.on=function(T,A,E){if(dT(T),dT(A),this._matcher.add(T,A),E)setImmediate(E);return this};t1.prototype.removeListener=function(T,A,E){dT(T),dT(A);let L=this;return setImmediate(function(){if(L._matcher.remove(T,A),E)E()}),this};t1.prototype.removeAllListeners=function(T,A){if(dT(T),this._matcher.remove(T),A)setImmediate(A);return this};t1.prototype.emit=function(T,A){if(dT(T),A=A||aM,this.closed)return A(Error("mqemitter is closed"));if(this.concurrency>0&&this.current>=this.concurrency){if(this._messageQueue.push(T),this._messageCallbacks.push(A),!this._doing)process.emitWarning("MqEmitter leak detected",{detail:"For more info check: https://github.com/mcollina/mqemitter/pull/94"}),this._released()}else this._do(T,A);return this};t1.prototype.close=function(T){return this.closed=!0,setImmediate(T),this};t1.prototype._do=function(_,T){this._doing=!0;let A=this._matcher.match(_.topic);return this.current++,this._parallel(this,A,_,T),this};function aM(){}i7.exports=t1});var z_=W((Jf,r7)=>{class o7 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=_}}r7.exports={AggregateError:o7,ArrayIsArray(_){return Array.isArray(_)},ArrayPrototypeIncludes(_,T){return _.includes(T)},ArrayPrototypeIndexOf(_,T){return _.indexOf(T)},ArrayPrototypeJoin(_,T){return _.join(T)},ArrayPrototypeMap(_,T){return _.map(T)},ArrayPrototypePop(_,T){return _.pop(T)},ArrayPrototypePush(_,T){return _.push(T)},ArrayPrototypeSlice(_,T,A){return _.slice(T,A)},Error,FunctionPrototypeCall(_,T,...A){return _.call(T,...A)},FunctionPrototypeSymbolHasInstance(_,T){return Function.prototype[Symbol.hasInstance].call(_,T)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(_,T){return Object.defineProperties(_,T)},ObjectDefineProperty(_,T,A){return Object.defineProperty(_,T,A)},ObjectGetOwnPropertyDescriptor(_,T){return Object.getOwnPropertyDescriptor(_,T)},ObjectKeys(_){return Object.keys(_)},ObjectSetPrototypeOf(_,T){return Object.setPrototypeOf(_,T)},Promise,PromisePrototypeCatch(_,T){return _.catch(T)},PromisePrototypeThen(_,T,A){return _.then(T,A)},PromiseReject(_){return Promise.reject(_)},PromiseResolve(_){return Promise.resolve(_)},ReflectApply:Reflect.apply,RegExpPrototypeTest(_,T){return _.test(T)},SafeSet:Set,String,StringPrototypeSlice(_,T,A){return _.slice(T,A)},StringPrototypeToLowerCase(_){return _.toLowerCase()},StringPrototypeToUpperCase(_){return _.toUpperCase()},StringPrototypeTrim(_){return _.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(_,T,A){return _.set(T,A)},Boolean,Uint8Array}});var t5=W((Xf,s7)=>{s7.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((Hf,TJ)=>{var{format:oM,inspect:n8}=t5(),{AggregateError:rM}=z_(),sM=globalThis.AggregateError||rM,tM=Symbol("kIsNodeError"),eM=["string","function","number","object","Function","Object","boolean","bigint","symbol"],_V=/^([A-Z][a-z0-9]*)+$/,i8={};function ZT(_,T){if(!_)throw new i8.ERR_INTERNAL_ASSERTION(T)}function t7(_){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 TV(_,T,A){if(typeof T==="function")return ZT(T.length<=A.length,`Code: ${_}; The provided arguments length (${A.length}) does not match the required ones (${T.length}).`),T(...A);let E=(T.match(/%[dfijoOs]/g)||[]).length;if(ZT(E===A.length,`Code: ${_}; The provided arguments length (${A.length}) does not match the required ones (${E}).`),A.length===0)return T;return oM(T,...A)}function g_(_,T,A){if(!A)A=Error;class E extends A{constructor(...L){super(TV(_,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[tM]=!0,i8[_]=E}function e7(_){let T="__node_internal_"+_.name;return Object.defineProperty(_,"name",{value:T}),_}function AV(_,T){if(_&&T&&_!==T){if(Array.isArray(T.errors))return T.errors.push(_),T;let A=new sM([T,_],T.message);return A.code=T.code,A}return _||T}class _J extends Error{constructor(_="The operation was aborted",T=void 0){if(T!==void 0&&typeof T!=="object")throw new i8.ERR_INVALID_ARG_TYPE("options","Object",T);super(_,T);this.code="ABORT_ERR",this.name="AbortError"}}g_("ERR_ASSERTION","%s",Error);g_("ERR_INVALID_ARG_TYPE",(_,T,A)=>{if(ZT(typeof _==="string","'name' must be a string"),!Array.isArray(T))T=[T];let E="The ";if(_.endsWith(" argument"))E+=`${_} `;else E+=`"${_}" ${_.includes(".")?"property":"argument"} `;E+="must be ";let L=[],J=[],X=[];for(let Z of T)if(ZT(typeof Z==="string","All expected entries have to be of type string"),eM.includes(Z))L.push(Z.toLowerCase());else if(_V.test(Z))J.push(Z);else ZT(Z!=="object",'The value "object" should be written as "Object"'),X.push(Z);if(J.length>0){let Z=L.indexOf("object");if(Z!==-1)L.splice(L,Z,1),J.push("Object")}if(L.length>0){switch(L.length){case 1:E+=`of type ${L[0]}`;break;case 2:E+=`one of type ${L[0]} or ${L[1]}`;break;default:{let Z=L.pop();E+=`one of type ${L.join(", ")}, or ${Z}`}}if(J.length>0||X.length>0)E+=" or "}if(J.length>0){switch(J.length){case 1:E+=`an instance of ${J[0]}`;break;case 2:E+=`an instance of ${J[0]} or ${J[1]}`;break;default:{let Z=J.pop();E+=`an instance of ${J.join(", ")}, or ${Z}`}}if(X.length>0)E+=" or "}switch(X.length){case 0:break;case 1:if(X[0].toLowerCase()!==X[0])E+="an ";E+=`${X[0]}`;break;case 2:E+=`one of ${X[0]} or ${X[1]}`;break;default:{let Z=X.pop();E+=`one of ${X.join(", ")}, or ${Z}`}}if(A==null)E+=`. Received ${A}`;else if(typeof A==="function"&&A.name)E+=`. Received function ${A.name}`;else if(typeof A==="object"){var H;if((H=A.constructor)!==null&&H!==void 0&&H.name)E+=`. Received an instance of ${A.constructor.name}`;else{let Z=n8(A,{depth:-1});E+=`. Received ${Z}`}}else{let Z=n8(A,{colors:!1});if(Z.length>25)Z=`${Z.slice(0,25)}...`;E+=`. Received type ${typeof A} (${Z})`}return E},TypeError);g_("ERR_INVALID_ARG_VALUE",(_,T,A="is invalid")=>{let E=n8(T);if(E.length>128)E=E.slice(0,128)+"...";return`The ${_.includes(".")?"property":"argument"} '${_}' ${A}. Received ${E}`},TypeError);g_("ERR_INVALID_RETURN_VALUE",(_,T,A)=>{var E;let L=A!==null&&A!==void 0&&(E=A.constructor)!==null&&E!==void 0&&E.name?`instance of ${A.constructor.name}`:`type ${typeof A}`;return`Expected ${_} to be returned from the "${T}" function but got ${L}.`},TypeError);g_("ERR_MISSING_ARGS",(..._)=>{ZT(_.length>0,"At least one arg needs to be specified");let T,A=_.length;switch(_=(Array.isArray(_)?_:[_]).map((E)=>`"${E}"`).join(" or "),A){case 1:T+=`The ${_[0]} argument`;break;case 2:T+=`The ${_[0]} and ${_[1]} arguments`;break;default:{let E=_.pop();T+=`The ${_.join(", ")}, and ${E} arguments`}break}return`${T} must be specified`},TypeError);g_("ERR_OUT_OF_RANGE",(_,T,A)=>{ZT(T,'Missing "range" argument');let E;if(Number.isInteger(A)&&Math.abs(A)>4294967296)E=t7(String(A));else if(typeof A==="bigint"){E=String(A);let L=BigInt(2)**BigInt(32);if(A>L||A<-L)E=t7(E);E+="n"}else E=n8(A);return`The value of "${_}" is out of range. It must be ${T}. Received ${E}`},RangeError);g_("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);g_("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);g_("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);g_("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);g_("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);g_("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);g_("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);g_("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);g_("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);g_("ERR_STREAM_WRITE_AFTER_END","write after end",Error);g_("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);TJ.exports={AbortError:_J,aggregateTwoErrors:e7(AV),hideStackFrames:e7,codes:i8}});var s_=W((Zf,_6)=>{var EV=j("buffer"),{format:LV,inspect:JV}=t5(),{codes:{ERR_INVALID_ARG_TYPE:e5}}=l_(),{kResistStopPropagation:XV,AggregateError:HV,SymbolDispose:ZV}=z_(),YV=globalThis.AbortSignal||j("abort-controller").AbortSignal,KV=globalThis.AbortController||j("abort-controller").AbortController,GV=Object.getPrototypeOf(async function(){}).constructor,AJ=globalThis.Blob||EV.Blob,$V=typeof AJ<"u"?function(T){return T instanceof AJ}:function(T){return!1},EJ=(_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new e5(T,"AbortSignal",_)},UV=(_,T)=>{if(typeof _!=="function")throw new e5(T,"Function",_)};_6.exports={AggregateError:HV,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:LV,inspect:JV,types:{isAsyncFunction(_){return _ instanceof GV},isArrayBufferView(_){return ArrayBuffer.isView(_)}},isBlob:$V,deprecate(_,T){return _},addAbortListener:j("events").addAbortListener||function(T,A){if(T===void 0)throw new e5("signal","AbortSignal",T);EJ(T,"signal"),UV(A,"listener");let E;if(T.aborted)queueMicrotask(()=>A());else T.addEventListener("abort",A,{__proto__:null,once:!0,[XV]:!0}),E=()=>{T.removeEventListener("abort",A)};return{__proto__:null,[ZV](){var L;(L=E)===null||L===void 0||L()}}},AbortSignalAny:YV.any||function(T){if(T.length===1)return T[0];let A=new KV,E=()=>A.abort();return T.forEach((L)=>{EJ(L,"signals"),L.addEventListener("abort",E,{once:!0})}),A.signal.addEventListener("abort",()=>{T.forEach((L)=>L.removeEventListener("abort",E))},{once:!0}),A.signal}};_6.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var pT=W((Yf,UJ)=>{var{ArrayIsArray:A6,ArrayPrototypeIncludes:HJ,ArrayPrototypeJoin:ZJ,ArrayPrototypeMap:WV,NumberIsInteger:E6,NumberIsNaN:NV,NumberMAX_SAFE_INTEGER:QV,NumberMIN_SAFE_INTEGER:MV,NumberParseInt:VV,ObjectPrototypeHasOwnProperty:zV,RegExpPrototypeExec:YJ,String:FV,StringPrototypeToUpperCase:CV,StringPrototypeTrim:OV}=z_(),{hideStackFrames:F1,codes:{ERR_SOCKET_BAD_PORT:RV,ERR_INVALID_ARG_TYPE:n_,ERR_INVALID_ARG_VALUE:cT,ERR_OUT_OF_RANGE:YT,ERR_UNKNOWN_SIGNAL:LJ}}=l_(),{normalizeEncoding:DV}=s_(),{isAsyncFunction:BV,isArrayBufferView:qV}=s_().types,JJ={};function IV(_){return _===(_|0)}function PV(_){return _===_>>>0}var jV=/^[0-7]+$/,xV="must be a 32-bit unsigned integer or an octal string";function wV(_,T,A){if(typeof _>"u")_=A;if(typeof _==="string"){if(YJ(jV,_)===null)throw new cT(T,_,xV);_=VV(_,8)}return KJ(_,T),_}var SV=F1((_,T,A=MV,E=QV)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!E6(_))throw new YT(T,"an integer",_);if(_<A||_>E)throw new YT(T,`>= ${A} && <= ${E}`,_)}),yV=F1((_,T,A=-2147483648,E=2147483647)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!E6(_))throw new YT(T,"an integer",_);if(_<A||_>E)throw new YT(T,`>= ${A} && <= ${E}`,_)}),KJ=F1((_,T,A=!1)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!E6(_))throw new YT(T,"an integer",_);let E=A?1:0,L=4294967295;if(_<E||_>L)throw new YT(T,`>= ${E} && <= ${L}`,_)});function L6(_,T){if(typeof _!=="string")throw new n_(T,"string",_)}function vV(_,T,A=void 0,E){if(typeof _!=="number")throw new n_(T,"number",_);if(A!=null&&_<A||E!=null&&_>E||(A!=null||E!=null)&&NV(_))throw new YT(T,`${A!=null?`>= ${A}`:""}${A!=null&&E!=null?" && ":""}${E!=null?`<= ${E}`:""}`,_)}var hV=F1((_,T,A)=>{if(!HJ(A,_)){let L="must be one of: "+ZJ(WV(A,(J)=>typeof J==="string"?`'${J}'`:FV(J)),", ");throw new cT(T,_,L)}});function GJ(_,T){if(typeof _!=="boolean")throw new n_(T,"boolean",_)}function T6(_,T,A){return _==null||!zV(_,T)?A:_[T]}var kV=F1((_,T,A=null)=>{let E=T6(A,"allowArray",!1),L=T6(A,"allowFunction",!1);if(!T6(A,"nullable",!1)&&_===null||!E&&A6(_)||typeof _!=="object"&&(!L||typeof _!=="function"))throw new n_(T,"Object",_)}),fV=F1((_,T)=>{if(_!=null&&typeof _!=="object"&&typeof _!=="function")throw new n_(T,"a dictionary",_)}),a8=F1((_,T,A=0)=>{if(!A6(_))throw new n_(T,"Array",_);if(_.length<A){let E=`must be longer than ${A}`;throw new cT(T,_,E)}});function bV(_,T){a8(_,T);for(let A=0;A<_.length;A++)L6(_[A],`${T}[${A}]`)}function gV(_,T){a8(_,T);for(let A=0;A<_.length;A++)GJ(_[A],`${T}[${A}]`)}function mV(_,T){a8(_,T);for(let A=0;A<_.length;A++){let E=_[A],L=`${T}[${A}]`;if(E==null)throw new n_(L,"AbortSignal",E);$J(E,L)}}function uV(_,T="signal"){if(L6(_,T),JJ[_]===void 0){if(JJ[CV(_)]!==void 0)throw new LJ(_+" (signals must use all capital letters)");throw new LJ(_)}}var dV=F1((_,T="buffer")=>{if(!qV(_))throw new n_(T,["Buffer","TypedArray","DataView"],_)});function cV(_,T){let A=DV(T),E=_.length;if(A==="hex"&&E%2!==0)throw new cT("encoding",T,`is invalid for data of length ${E}`)}function pV(_,T="Port",A=!0){if(typeof _!=="number"&&typeof _!=="string"||typeof _==="string"&&OV(_).length===0||+_!==+_>>>0||_>65535||_===0&&!A)throw new RV(T,_,A);return _|0}var $J=F1((_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new n_(T,"AbortSignal",_)}),lV=F1((_,T)=>{if(typeof _!=="function")throw new n_(T,"Function",_)}),nV=F1((_,T)=>{if(typeof _!=="function"||BV(_))throw new n_(T,"Function",_)}),iV=F1((_,T)=>{if(_!==void 0)throw new n_(T,"undefined",_)});function aV(_,T,A){if(!HJ(A,_))throw new n_(T,`('${ZJ(A,"|")}')`,_)}var oV=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function XJ(_,T){if(typeof _>"u"||!YJ(oV,_))throw new cT(T,_,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function rV(_){if(typeof _==="string")return XJ(_,"hints"),_;else if(A6(_)){let T=_.length,A="";if(T===0)return A;for(let E=0;E<T;E++){let L=_[E];if(XJ(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"')}UJ.exports={isInt32:IV,isUint32:PV,parseFileMode:wV,validateArray:a8,validateStringArray:bV,validateBooleanArray:gV,validateAbortSignalArray:mV,validateBoolean:GJ,validateBuffer:dV,validateDictionary:fV,validateEncoding:cV,validateFunction:lV,validateInt32:yV,validateInteger:SV,validateNumber:vV,validateObject:kV,validateOneOf:hV,validatePlainFunction:nV,validatePort:pV,validateSignalName:uV,validateString:L6,validateUint32:KJ,validateUndefined:iV,validateUnion:aV,validateAbortSignal:$J,validateLinkHeaderValue:rV}});var c0=W((Kf,WJ)=>{WJ.exports=global.process});var _0=W((Gf,jJ)=>{var{SymbolAsyncIterator:NJ,SymbolIterator:QJ,SymbolFor:KT}=z_(),MJ=KT("nodejs.stream.destroyed"),VJ=KT("nodejs.stream.errored"),J6=KT("nodejs.stream.readable"),X6=KT("nodejs.stream.writable"),zJ=KT("nodejs.stream.disturbed"),sV=KT("nodejs.webstream.isClosedPromise"),tV=KT("nodejs.webstream.controllerErrorFunction");function o8(_,T=!1){var A;return!!(_&&typeof _.pipe==="function"&&typeof _.on==="function"&&(!T||typeof _.pause==="function"&&typeof _.resume==="function")&&(!_._writableState||((A=_._readableState)===null||A===void 0?void 0:A.readable)!==!1)&&(!_._writableState||_._readableState))}function r8(_){var T;return!!(_&&typeof _.write==="function"&&typeof _.on==="function"&&(!_._readableState||((T=_._writableState)===null||T===void 0?void 0:T.writable)!==!1))}function eV(_){return!!(_&&typeof _.pipe==="function"&&_._readableState&&typeof _.on==="function"&&typeof _.write==="function")}function e1(_){return _&&(_._readableState||_._writableState||typeof _.write==="function"&&typeof _.on==="function"||typeof _.pipe==="function"&&typeof _.on==="function")}function FJ(_){return!!(_&&!e1(_)&&typeof _.pipeThrough==="function"&&typeof _.getReader==="function"&&typeof _.cancel==="function")}function CJ(_){return!!(_&&!e1(_)&&typeof _.getWriter==="function"&&typeof _.abort==="function")}function OJ(_){return!!(_&&!e1(_)&&typeof _.readable==="object"&&typeof _.writable==="object")}function _z(_){return FJ(_)||CJ(_)||OJ(_)}function Tz(_,T){if(_==null)return!1;if(T===!0)return typeof _[NJ]==="function";if(T===!1)return typeof _[QJ]==="function";return typeof _[NJ]==="function"||typeof _[QJ]==="function"}function s8(_){if(!e1(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!!(_.destroyed||_[MJ]||E!==null&&E!==void 0&&E.destroyed)}function RJ(_){if(!r8(_))return null;if(_.writableEnded===!0)return!0;let T=_._writableState;if(T!==null&&T!==void 0&&T.errored)return!1;if(typeof(T===null||T===void 0?void 0:T.ended)!=="boolean")return null;return T.ended}function Az(_,T){if(!r8(_))return null;if(_.writableFinished===!0)return!0;let A=_._writableState;if(A!==null&&A!==void 0&&A.errored)return!1;if(typeof(A===null||A===void 0?void 0:A.finished)!=="boolean")return null;return!!(A.finished||T===!1&&A.ended===!0&&A.length===0)}function Ez(_){if(!o8(_))return null;if(_.readableEnded===!0)return!0;let T=_._readableState;if(!T||T.errored)return!1;if(typeof(T===null||T===void 0?void 0:T.ended)!=="boolean")return null;return T.ended}function DJ(_,T){if(!o8(_))return null;let A=_._readableState;if(A!==null&&A!==void 0&&A.errored)return!1;if(typeof(A===null||A===void 0?void 0:A.endEmitted)!=="boolean")return null;return!!(A.endEmitted||T===!1&&A.ended===!0&&A.length===0)}function BJ(_){if(_&&_[J6]!=null)return _[J6];if(typeof(_===null||_===void 0?void 0:_.readable)!=="boolean")return null;if(s8(_))return!1;return o8(_)&&_.readable&&!DJ(_)}function qJ(_){if(_&&_[X6]!=null)return _[X6];if(typeof(_===null||_===void 0?void 0:_.writable)!=="boolean")return null;if(s8(_))return!1;return r8(_)&&_.writable&&!RJ(_)}function Lz(_,T){if(!e1(_))return null;if(s8(_))return!0;if((T===null||T===void 0?void 0:T.readable)!==!1&&BJ(_))return!1;if((T===null||T===void 0?void 0:T.writable)!==!1&&qJ(_))return!1;return!0}function Jz(_){var T,A;if(!e1(_))return null;if(_.writableErrored)return _.writableErrored;return(T=(A=_._writableState)===null||A===void 0?void 0:A.errored)!==null&&T!==void 0?T:null}function Xz(_){var T,A;if(!e1(_))return null;if(_.readableErrored)return _.readableErrored;return(T=(A=_._readableState)===null||A===void 0?void 0:A.errored)!==null&&T!==void 0?T:null}function Hz(_){if(!e1(_))return null;if(typeof _.closed==="boolean")return _.closed;let{_writableState:T,_readableState:A}=_;if(typeof(T===null||T===void 0?void 0:T.closed)==="boolean"||typeof(A===null||A===void 0?void 0:A.closed)==="boolean")return(T===null||T===void 0?void 0:T.closed)||(A===null||A===void 0?void 0:A.closed);if(typeof _._closed==="boolean"&&IJ(_))return _._closed;return null}function IJ(_){return typeof _._closed==="boolean"&&typeof _._defaultKeepAlive==="boolean"&&typeof _._removedConnection==="boolean"&&typeof _._removedContLen==="boolean"}function PJ(_){return typeof _._sent100==="boolean"&&IJ(_)}function Zz(_){var T;return typeof _._consuming==="boolean"&&typeof _._dumped==="boolean"&&((T=_.req)===null||T===void 0?void 0:T.upgradeOrConnect)===void 0}function Yz(_){if(!e1(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!E&&PJ(_)||!!(E&&E.autoDestroy&&E.emitClose&&E.closed===!1)}function Kz(_){var T;return!!(_&&((T=_[zJ])!==null&&T!==void 0?T:_.readableDidRead||_.readableAborted))}function Gz(_){var T,A,E,L,J,X,H,Z,Y,K;return!!(_&&((T=(A=(E=(L=(J=(X=_[VJ])!==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))}jJ.exports={isDestroyed:s8,kIsDestroyed:MJ,isDisturbed:Kz,kIsDisturbed:zJ,isErrored:Gz,kIsErrored:VJ,isReadable:BJ,kIsReadable:J6,kIsClosedPromise:sV,kControllerErrorFunction:tV,kIsWritable:X6,isClosed:Hz,isDuplexNodeStream:eV,isFinished:Lz,isIterable:Tz,isReadableNodeStream:o8,isReadableStream:FJ,isReadableEnded:Ez,isReadableFinished:DJ,isReadableErrored:Xz,isNodeStream:e1,isWebStream:_z,isWritable:qJ,isWritableNodeStream:r8,isWritableStream:CJ,isWritableEnded:RJ,isWritableFinished:Az,isWritableErrored:Jz,isServerRequest:Zz,isServerResponse:PJ,willEmitClose:Yz,isTransformStream:OJ}});var B0=W(($f,G6)=>{var p0=c0(),{AbortError:bJ,codes:$z}=l_(),{ERR_INVALID_ARG_TYPE:Uz,ERR_STREAM_PREMATURE_CLOSE:xJ}=$z,{kEmptyObject:Z6,once:Y6}=s_(),{validateAbortSignal:Wz,validateFunction:Nz,validateObject:Qz,validateBoolean:Mz}=pT(),{Promise:Vz,PromisePrototypeThen:zz,SymbolDispose:gJ}=z_(),{isClosed:Fz,isReadable:wJ,isReadableNodeStream:H6,isReadableStream:Cz,isReadableFinished:SJ,isReadableErrored:yJ,isWritable:vJ,isWritableNodeStream:hJ,isWritableStream:Oz,isWritableFinished:kJ,isWritableErrored:fJ,isNodeStream:Rz,willEmitClose:Dz,kIsClosedPromise:Bz}=_0(),lT;function qz(_){return _.setHeader&&typeof _.abort==="function"}var K6=()=>{};function mJ(_,T,A){var E,L;if(arguments.length===2)A=T,T=Z6;else if(T==null)T=Z6;else Qz(T,"options");if(Nz(A,"callback"),Wz(T.signal,"options.signal"),A=Y6(A),Cz(_)||Oz(_))return Iz(_,T,A);if(!Rz(_))throw new Uz("stream",["ReadableStream","WritableStream","Stream"],_);let J=(E=T.readable)!==null&&E!==void 0?E:H6(_),X=(L=T.writable)!==null&&L!==void 0?L:hJ(_),H=_._writableState,Z=_._readableState,Y=()=>{if(!_.writable)$()},K=Dz(_)&&H6(_)===J&&hJ(_)===X,G=kJ(_,!1),$=()=>{if(G=!0,_.destroyed)K=!1;if(K&&(!_.readable||J))return;if(!J||U)A.call(_)},U=SJ(_,!1),V=()=>{if(U=!0,_.destroyed)K=!1;if(K&&(!_.writable||X))return;if(!X||G)A.call(_)},N=(f)=>{A.call(_,f)},z=Fz(_),Q=()=>{z=!0;let f=fJ(_)||yJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);if(J&&!U&&H6(_,!0)){if(!SJ(_,!1))return A.call(_,new xJ)}if(X&&!G){if(!kJ(_,!1))return A.call(_,new xJ)}A.call(_)},F=()=>{z=!0;let f=fJ(_)||yJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);A.call(_)},R=()=>{_.req.on("finish",$)};if(qz(_)){if(_.on("complete",$),!K)_.on("abort",Q);if(_.req)R();else _.on("request",R)}else if(X&&!H)_.on("end",Y),_.on("close",Y);if(!K&&typeof _.aborted==="boolean")_.on("aborted",Q);if(_.on("end",V),_.on("finish",$),T.error!==!1)_.on("error",N);if(_.on("close",Q),z)p0.nextTick(Q);else if(H!==null&&H!==void 0&&H.errorEmitted||Z!==null&&Z!==void 0&&Z.errorEmitted){if(!K)p0.nextTick(F)}else if(!J&&(!K||wJ(_))&&(G||vJ(_)===!1))p0.nextTick(F);else if(!X&&(!K||vJ(_))&&(U||wJ(_)===!1))p0.nextTick(F);else if(Z&&_.req&&_.aborted)p0.nextTick(F);let q=()=>{if(A=K6,_.removeListener("aborted",Q),_.removeListener("complete",$),_.removeListener("abort",Q),_.removeListener("request",R),_.req)_.req.removeListener("finish",$);_.removeListener("end",Y),_.removeListener("close",Y),_.removeListener("finish",$),_.removeListener("end",V),_.removeListener("error",N),_.removeListener("close",Q)};if(T.signal&&!z){let f=()=>{let h=A;q(),h.call(_,new bJ(void 0,{cause:T.signal.reason}))};if(T.signal.aborted)p0.nextTick(f);else{lT=lT||s_().addAbortListener;let h=lT(T.signal,f),b=A;A=Y6((...l)=>{h[gJ](),b.apply(_,l)})}}return q}function Iz(_,T,A){let E=!1,L=K6;if(T.signal)if(L=()=>{E=!0,A.call(_,new bJ(void 0,{cause:T.signal.reason}))},T.signal.aborted)p0.nextTick(L);else{lT=lT||s_().addAbortListener;let X=lT(T.signal,L),H=A;A=Y6((...Z)=>{X[gJ](),H.apply(_,Z)})}let J=(...X)=>{if(!E)p0.nextTick(()=>A.apply(_,X))};return zz(_[Bz].promise,J,J),K6}function Pz(_,T){var A;let E=!1;if(T===null)T=Z6;if((A=T)!==null&&A!==void 0&&A.cleanup)Mz(T.cleanup,"cleanup"),E=T.cleanup;return new Vz((L,J)=>{let X=mJ(_,T,(H)=>{if(E)X();if(H)J(H);else L()})})}G6.exports=mJ;G6.exports.finished=Pz});var GT=W((Uf,aJ)=>{var T0=c0(),{aggregateTwoErrors:jz,codes:{ERR_MULTIPLE_CALLBACK:xz},AbortError:wz}=l_(),{Symbol:cJ}=z_(),{kIsDestroyed:Sz,isDestroyed:yz,isFinished:vz,isServerRequest:hz}=_0(),pJ=cJ("kDestroy"),$6=cJ("kConstruct");function lJ(_,T,A){if(_){if(_.stack,T&&!T.errored)T.errored=_;if(A&&!A.errored)A.errored=_}}function kz(_,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(lJ(_,E,A),E)E.destroyed=!0;if(A)A.destroyed=!0;if(!L.constructed)this.once(pJ,function(J){uJ(this,jz(J,_),T)});else uJ(this,_,T);return this}function uJ(_,T,A){let E=!1;function L(J){if(E)return;E=!0;let{_readableState:X,_writableState:H}=_;if(lJ(J,H,X),H)H.closed=!0;if(X)X.closed=!0;if(typeof A==="function")A(J);if(J)T0.nextTick(fz,_,J);else T0.nextTick(nJ,_)}try{_._destroy(T||null,L)}catch(J){L(J)}}function fz(_,T){U6(_,T),nJ(_)}function nJ(_){let{_readableState:T,_writableState:A}=_;if(A)A.closeEmitted=!0;if(T)T.closeEmitted=!0;if(A!==null&&A!==void 0&&A.emitClose||T!==null&&T!==void 0&&T.emitClose)_.emit("close")}function U6(_,T){let{_readableState:A,_writableState:E}=_;if(E!==null&&E!==void 0&&E.errorEmitted||A!==null&&A!==void 0&&A.errorEmitted)return;if(E)E.errorEmitted=!0;if(A)A.errorEmitted=!0;_.emit("error",T)}function bz(){let _=this._readableState,T=this._writableState;if(_)_.constructed=!0,_.closed=!1,_.closeEmitted=!1,_.destroyed=!1,_.errored=null,_.errorEmitted=!1,_.reading=!1,_.ended=_.readable===!1,_.endEmitted=_.readable===!1;if(T)T.constructed=!0,T.destroyed=!1,T.closed=!1,T.closeEmitted=!1,T.errored=null,T.errorEmitted=!1,T.finalCalled=!1,T.prefinished=!1,T.ended=T.writable===!1,T.ending=T.writable===!1,T.finished=T.writable===!1}function W6(_,T,A){let{_readableState:E,_writableState:L}=_;if(L!==null&&L!==void 0&&L.destroyed||E!==null&&E!==void 0&&E.destroyed)return this;if(E!==null&&E!==void 0&&E.autoDestroy||L!==null&&L!==void 0&&L.autoDestroy)_.destroy(T);else if(T){if(T.stack,L&&!L.errored)L.errored=T;if(E&&!E.errored)E.errored=T;if(A)T0.nextTick(U6,_,T);else U6(_,T)}}function gz(_,T){if(typeof _._construct!=="function")return;let{_readableState:A,_writableState:E}=_;if(A)A.constructed=!1;if(E)E.constructed=!1;if(_.once($6,T),_.listenerCount($6)>1)return;T0.nextTick(mz,_)}function mz(_){let T=!1;function A(E){if(T){W6(_,E!==null&&E!==void 0?E:new xz);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(pJ,E);else if(E)W6(_,E,!0);else T0.nextTick(uz,_)}try{_._construct((E)=>{T0.nextTick(A,E)})}catch(E){T0.nextTick(A,E)}}function uz(_){_.emit($6)}function dJ(_){return(_===null||_===void 0?void 0:_.setHeader)&&typeof _.abort==="function"}function iJ(_){_.emit("close")}function dz(_,T){_.emit("error",T),T0.nextTick(iJ,_)}function cz(_,T){if(!_||yz(_))return;if(!T&&!vz(_))T=new wz;if(hz(_))_.socket=null,_.destroy(T);else if(dJ(_))_.abort();else if(dJ(_.req))_.req.abort();else if(typeof _.destroy==="function")_.destroy(T);else if(typeof _.close==="function")_.close();else if(T)T0.nextTick(dz,_,T);else T0.nextTick(iJ,_);if(!_.destroyed)_[Sz]=!0}aJ.exports={construct:gz,destroyer:cz,destroy:kz,undestroy:bz,errorOrDestroy:W6}});var _A=W((Wf,rJ)=>{var{ArrayIsArray:pz,ObjectSetPrototypeOf:oJ}=z_(),{EventEmitter:t8}=j("events");function e8(_){t8.call(this,_)}oJ(e8.prototype,t8.prototype);oJ(e8,t8);e8.prototype.pipe=function(_,T){let A=this;function E(K){if(_.writable&&_.write(K)===!1&&A.pause)A.pause()}A.on("data",E);function L(){if(A.readable&&A.resume)A.resume()}if(_.on("drain",L),!_._isStdio&&(!T||T.end!==!1))A.on("end",X),A.on("close",H);let J=!1;function X(){if(J)return;J=!0,_.end()}function H(){if(J)return;if(J=!0,typeof _.destroy==="function")_.destroy()}function Z(K){if(Y(),t8.listenerCount(this,"error")===0)this.emit("error",K)}N6(A,"error",Z),N6(_,"error",Z);function Y(){A.removeListener("data",E),_.removeListener("drain",L),A.removeListener("end",X),A.removeListener("close",H),A.removeListener("error",Z),_.removeListener("error",Z),A.removeListener("end",Y),A.removeListener("close",Y),_.removeListener("close",Y)}return A.on("end",Y),A.on("close",Y),_.on("close",Y),_.emit("pipe",A),_};function N6(_,T,A){if(typeof _.prependListener==="function")return _.prependListener(T,A);if(!_._events||!_._events[T])_.on(T,A);else if(pz(_._events[T]))_._events[T].unshift(A);else _._events[T]=[A,_._events[T]]}rJ.exports={Stream:e8,prependListener:N6}});var w4=W((sz,TA)=>{var{SymbolDispose:lz}=z_(),{AbortError:sJ,codes:nz}=l_(),{isNodeStream:tJ,isWebStream:iz,kControllerErrorFunction:az}=_0(),oz=B0(),{ERR_INVALID_ARG_TYPE:eJ}=nz,Q6,rz=(_,T)=>{if(typeof _!=="object"||!("aborted"in _))throw new eJ(T,"AbortSignal",_)};sz.addAbortSignal=function(T,A){if(rz(T,"signal"),!tJ(A)&&!iz(A))throw new eJ("stream",["ReadableStream","WritableStream","Stream"],A);return sz.addAbortSignalNoValidate(T,A)};sz.addAbortSignalNoValidate=function(_,T){if(typeof _!=="object"||!("aborted"in _))return T;let A=tJ(T)?()=>{T.destroy(new sJ(void 0,{cause:_.reason}))}:()=>{T[az](new sJ(void 0,{cause:_.reason}))};if(_.aborted)A();else{Q6=Q6||s_().addAbortListener;let E=Q6(_,A);oz(T,E[lz])}return T}});var AX=W((Nf,TX)=>{var{StringPrototypeSlice:_X,SymbolIterator:_F,TypedArrayPrototypeSet:AA,Uint8Array:TF}=z_(),{Buffer:M6}=j("buffer"),{inspect:AF}=s_();TX.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(T){let A={data:T,next:null};if(this.length>0)this.tail.next=A;else this.head=A;this.tail=A,++this.length}unshift(T){let A={data:T,next:this.head};if(this.length===0)this.tail=A;this.head=A,++this.length}shift(){if(this.length===0)return;let T=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,T}clear(){this.head=this.tail=null,this.length=0}join(T){if(this.length===0)return"";let A=this.head,E=""+A.data;while((A=A.next)!==null)E+=T+A.data;return E}concat(T){if(this.length===0)return M6.alloc(0);let A=M6.allocUnsafe(T>>>0),E=this.head,L=0;while(E)AA(A,E.data,L),L+=E.data.length,E=E.next;return A}consume(T,A){let E=this.head.data;if(T<E.length){let L=E.slice(0,T);return this.head.data=E.slice(T),L}if(T===E.length)return this.shift();return A?this._getString(T):this._getBuffer(T)}first(){return this.head.data}*[_F](){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+=_X(J,0,T),this.head=E,E.data=_X(J,T);break}++L}while((E=E.next)!==null);return this.length-=L,A}_getBuffer(T){let A=M6.allocUnsafe(T),E=T,L=this.head,J=0;do{let X=L.data;if(T>X.length)AA(A,X,E-T),T-=X.length;else{if(T===X.length)if(AA(A,X,E-T),++J,L.next)this.head=L.next;else this.head=this.tail=null;else AA(A,new TF(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 AF(this,{...A,depth:0,customInspect:!1})}}});var S4=W((Qf,XX)=>{var{MathFloor:EF,NumberIsInteger:LF}=z_(),{validateInteger:JF}=pT(),{ERR_INVALID_ARG_VALUE:XF}=l_().codes,EX=16384,LX=16;function HF(_,T,A){return _.highWaterMark!=null?_.highWaterMark:T?_[A]:null}function JX(_){return _?LX:EX}function ZF(_,T){if(JF(T,"value",0),_)LX=T;else EX=T}function YF(_,T,A,E){let L=HF(T,E,A);if(L!=null){if(!LF(L)||L<0){let J=E?`options.${A}`:"options.highWaterMark";throw new XF(J,L)}return EF(L)}return JX(_.objectMode)}XX.exports={getHighWaterMark:YF,getDefaultHighWaterMark:JX,setDefaultHighWaterMark:ZF}});var YX=W((V6,ZX)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var EA=j("buffer"),A0=EA.Buffer;function HX(_,T){for(var A in _)T[A]=_[A]}if(A0.from&&A0.alloc&&A0.allocUnsafe&&A0.allocUnsafeSlow)ZX.exports=EA;else HX(EA,V6),V6.Buffer=$T;function $T(_,T,A){return A0(_,T,A)}$T.prototype=Object.create(A0.prototype);HX(A0,$T);$T.from=function(_,T,A){if(typeof _==="number")throw TypeError("Argument must not be a number");return A0(_,T,A)};$T.alloc=function(_,T,A){if(typeof _!=="number")throw TypeError("Argument must be a number");var E=A0(_);if(T!==void 0)if(typeof A==="string")E.fill(T,A);else E.fill(T);else E.fill(0);return E};$T.allocUnsafe=function(_){if(typeof _!=="number")throw TypeError("Argument must be a number");return A0(_)};$T.allocUnsafeSlow=function(_){if(typeof _!=="number")throw TypeError("Argument must be a number");return EA.SlowBuffer(_)}});var GX=W((RF)=>{var F6=YX().Buffer,KX=F6.isEncoding||function(_){switch(_=""+_,_&&_.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function KF(_){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 GF(_){var T=KF(_);if(typeof T!=="string"&&(F6.isEncoding===KX||!KX(_)))throw Error("Unknown encoding: "+_);return T||_}RF.StringDecoder=y4;function y4(_){this.encoding=GF(_);var T;switch(this.encoding){case"utf16le":this.text=MF,this.end=VF,T=4;break;case"utf8":this.fillLast=WF,T=4;break;case"base64":this.text=zF,this.end=FF,T=3;break;default:this.write=CF,this.end=OF;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=F6.allocUnsafe(T)}y4.prototype.write=function(_){if(_.length===0)return"";var T,A;if(this.lastNeed){if(T=this.fillLast(_),T===void 0)return"";A=this.lastNeed,this.lastNeed=0}else A=0;if(A<_.length)return T?T+this.text(_,A):this.text(_,A);return T||""};y4.prototype.end=QF;y4.prototype.text=NF;y4.prototype.fillLast=function(_){if(this.lastNeed<=_.length)return _.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);_.copy(this.lastChar,this.lastTotal-this.lastNeed,0,_.length),this.lastNeed-=_.length};function z6(_){if(_<=127)return 0;else if(_>>5===6)return 2;else if(_>>4===14)return 3;else if(_>>3===30)return 4;return _>>6===2?-1:-2}function $F(_,T,A){var E=T.length-1;if(E<A)return 0;var L=z6(T[E]);if(L>=0){if(L>0)_.lastNeed=L-1;return L}if(--E<A||L===-2)return 0;if(L=z6(T[E]),L>=0){if(L>0)_.lastNeed=L-2;return L}if(--E<A||L===-2)return 0;if(L=z6(T[E]),L>=0){if(L>0)if(L===2)L=0;else _.lastNeed=L-3;return L}return 0}function UF(_,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 WF(_){var T=this.lastTotal-this.lastNeed,A=UF(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 NF(_,T){var A=$F(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 QF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+"\uFFFD";return T}function MF(_,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 VF(_){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 zF(_,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 FF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+this.lastChar.toString("base64",0,3-this.lastNeed);return T}function CF(_){return _.toString(this.encoding)}function OF(_){return _&&_.length?this.write(_):""}});var C6=W((Vf,NX)=>{var $X=c0(),{PromisePrototypeThen:BF,SymbolAsyncIterator:UX,SymbolIterator:WX}=z_(),{Buffer:qF}=j("buffer"),{ERR_INVALID_ARG_TYPE:IF,ERR_STREAM_NULL_VALUES:PF}=l_().codes;function jF(_,T,A){let E;if(typeof T==="string"||T instanceof qF)return new _({objectMode:!0,...A,read(){this.push(T),this.push(null)}});let L;if(T&&T[UX])L=!0,E=T[UX]();else if(T&&T[WX])L=!1,E=T[WX]();else throw new IF("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){BF(H(Y),()=>$X.nextTick(K,Y),(G)=>$X.nextTick(K,G||Y))};async function H(Y){let K=Y!==void 0&&Y!==null,G=typeof E.throw==="function";if(K&&G){let{value:$,done:U}=await E.throw(Y);if(await $,U)return}if(typeof E.return==="function"){let{value:$}=await E.return();await $}}async function Z(){for(;;){try{let{value:Y,done:K}=L?await E.next():E.next();if(K)J.push(null);else{let G=Y&&typeof Y.then==="function"?await Y:Y;if(G===null)throw X=!1,new PF;else if(J.push(G))continue;else X=!1}}catch(Y){J.destroy(Y)}break}}return J}NX.exports=jF});var h4=W((zf,yX)=>{var b1=c0(),{ArrayPrototypeIndexOf:xF,NumberIsInteger:wF,NumberIsNaN:SF,NumberParseInt:yF,ObjectDefineProperties:j6,ObjectKeys:vF,ObjectSetPrototypeOf:VX,Promise:zX,SafeSet:hF,SymbolAsyncDispose:kF,SymbolAsyncIterator:fF,Symbol:bF}=z_();yX.exports=s;s.ReadableState=HA;var{EventEmitter:gF}=j("events"),{Stream:l0,prependListener:mF}=_A(),{Buffer:O6}=j("buffer"),{addAbortSignal:uF}=w4(),FX=B0(),A_=s_().debuglog("stream",(_)=>{A_=_}),dF=AX(),aT=GT(),{getHighWaterMark:cF,getDefaultHighWaterMark:pF}=S4(),{aggregateTwoErrors:QX,codes:{ERR_INVALID_ARG_TYPE:lF,ERR_METHOD_NOT_IMPLEMENTED:nF,ERR_OUT_OF_RANGE:iF,ERR_STREAM_PUSH_AFTER_EOF:aF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:oF},AbortError:rF}=l_(),{validateObject:sF}=pT(),UT=bF("kPaused"),{StringDecoder:CX}=GX(),tF=C6();VX(s.prototype,l0.prototype);VX(s,l0);var R6=()=>{},{errorOrDestroy:nT}=aT,iT=1,eF=2,OX=4,v4=8,RX=16,LA=32,JA=64,DX=128,_C=256,TC=512,AC=1024,I6=2048,P6=4096,EC=8192,LC=16384,JC=32768,BX=65536,XC=131072,HC=262144;function x_(_){return{enumerable:!1,get(){return(this.state&_)!==0},set(T){if(T)this.state|=_;else this.state&=~_}}}j6(HA.prototype,{objectMode:x_(iT),ended:x_(eF),endEmitted:x_(OX),reading:x_(v4),constructed:x_(RX),sync:x_(LA),needReadable:x_(JA),emittedReadable:x_(DX),readableListening:x_(_C),resumeScheduled:x_(TC),errorEmitted:x_(AC),emitClose:x_(I6),autoDestroy:x_(P6),destroyed:x_(EC),closed:x_(LC),closeEmitted:x_(JC),multiAwaitDrain:x_(BX),readingMore:x_(XC),dataEmitted:x_(HC)});function HA(_,T,A){if(typeof A!=="boolean")A=T instanceof E0();if(this.state=I6|P6|RX|LA,_&&_.objectMode)this.state|=iT;if(A&&_&&_.readableObjectMode)this.state|=iT;if(this.highWaterMark=_?cF(this,_,"readableHighWaterMark",A):pF(!1),this.buffer=new dF,this.length=0,this.pipes=[],this.flowing=null,this[UT]=null,_&&_.emitClose===!1)this.state&=~I6;if(_&&_.autoDestroy===!1)this.state&=~P6;if(this.errored=null,this.defaultEncoding=_&&_.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,_&&_.encoding)this.decoder=new CX(_.encoding),this.encoding=_.encoding}function s(_){if(!(this instanceof s))return new s(_);let T=this instanceof E0();if(this._readableState=new HA(_,this,T),_){if(typeof _.read==="function")this._read=_.read;if(typeof _.destroy==="function")this._destroy=_.destroy;if(typeof _.construct==="function")this._construct=_.construct;if(_.signal&&!T)uF(_.signal,this)}l0.call(this,_),aT.construct(this,()=>{if(this._readableState.needReadable)XA(this,this._readableState)})}s.prototype.destroy=aT.destroy;s.prototype._undestroy=aT.undestroy;s.prototype._destroy=function(_,T){T(_)};s.prototype[gF.captureRejectionSymbol]=function(_){this.destroy(_)};s.prototype[kF]=function(){let _;if(!this.destroyed)_=this.readableEnded?null:new rF,this.destroy(_);return new zX((T,A)=>FX(this,(E)=>E&&E!==_?A(E):T(null)))};s.prototype.push=function(_,T){return qX(this,_,T,!1)};s.prototype.unshift=function(_,T){return qX(this,_,T,!0)};function qX(_,T,A,E){A_("readableAddChunk",T);let L=_._readableState,J;if((L.state&iT)===0){if(typeof T==="string"){if(A=A||L.defaultEncoding,L.encoding!==A)if(E&&L.encoding)T=O6.from(T,A).toString(L.encoding);else T=O6.from(T,A),A=""}else if(T instanceof O6)A="";else if(l0._isUint8Array(T))T=l0._uint8ArrayToBuffer(T),A="";else if(T!=null)J=new lF("chunk",["string","Buffer","Uint8Array"],T)}if(J)nT(_,J);else if(T===null)L.state&=~v4,KC(_,L);else if((L.state&iT)!==0||T&&T.length>0)if(E)if((L.state&OX)!==0)nT(_,new oF);else if(L.destroyed||L.errored)return!1;else D6(_,L,T,!0);else if(L.ended)nT(_,new aF);else if(L.destroyed||L.errored)return!1;else if(L.state&=~v4,L.decoder&&!A)if(T=L.decoder.write(T),L.objectMode||T.length!==0)D6(_,L,T,!1);else XA(_,L);else D6(_,L,T,!1);else if(!E)L.state&=~v4,XA(_,L);return!L.ended&&(L.length<L.highWaterMark||L.length===0)}function D6(_,T,A,E){if(T.flowing&&T.length===0&&!T.sync&&_.listenerCount("data")>0){if((T.state&BX)!==0)T.awaitDrainWriters.clear();else T.awaitDrainWriters=null;T.dataEmitted=!0,_.emit("data",A)}else{if(T.length+=T.objectMode?1:A.length,E)T.buffer.unshift(A);else T.buffer.push(A);if((T.state&JA)!==0)ZA(_)}XA(_,T)}s.prototype.isPaused=function(){let _=this._readableState;return _[UT]===!0||_.flowing===!1};s.prototype.setEncoding=function(_){let T=new CX(_);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 ZC=1073741824;function YC(_){if(_>ZC)throw new iF("size","<= 1GiB",_);else _--,_|=_>>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++;return _}function MX(_,T){if(_<=0||T.length===0&&T.ended)return 0;if((T.state&iT)!==0)return 1;if(SF(_)){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(!wF(_))_=yF(_,10);let T=this._readableState,A=_;if(_>T.highWaterMark)T.highWaterMark=YC(_);if(_!==0)T.state&=~DX;if(_===0&&T.needReadable&&((T.highWaterMark!==0?T.length>=T.highWaterMark:T.length>0)||T.ended)){if(A_("read: emitReadable",T.length,T.ended),T.length===0&&T.ended)B6(this);else ZA(this);return null}if(_=MX(_,T),_===0&&T.ended){if(T.length===0)B6(this);return null}let E=(T.state&JA)!==0;if(A_("need readable",E),T.length===0||T.length-_<T.highWaterMark)E=!0,A_("length less than watermark",E);if(T.ended||T.reading||T.destroyed||T.errored||!T.constructed)E=!1,A_("reading, ended or constructing",E);else if(E){if(A_("do read"),T.state|=v4|LA,T.length===0)T.state|=JA;try{this._read(T.highWaterMark)}catch(J){nT(this,J)}if(T.state&=~LA,!T.reading)_=MX(A,T)}let L;if(_>0)L=wX(_,T);else L=null;if(L===null)T.needReadable=T.length<=T.highWaterMark,_=0;else if(T.length-=_,T.multiAwaitDrain)T.awaitDrainWriters.clear();else T.awaitDrainWriters=null;if(T.length===0){if(!T.ended)T.needReadable=!0;if(A!==_&&T.ended)B6(this)}if(L!==null&&!T.errorEmitted&&!T.closeEmitted)T.dataEmitted=!0,this.emit("data",L);return L};function KC(_,T){if(A_("onEofChunk"),T.ended)return;if(T.decoder){let A=T.decoder.end();if(A&&A.length)T.buffer.push(A),T.length+=T.objectMode?1:A.length}if(T.ended=!0,T.sync)ZA(_);else T.needReadable=!1,T.emittedReadable=!0,IX(_)}function ZA(_){let T=_._readableState;if(A_("emitReadable",T.needReadable,T.emittedReadable),T.needReadable=!1,!T.emittedReadable)A_("emitReadable",T.flowing),T.emittedReadable=!0,b1.nextTick(IX,_)}function IX(_){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,jX(_)}function XA(_,T){if(!T.readingMore&&T.constructed)T.readingMore=!0,b1.nextTick(GC,_,T)}function GC(_,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 nF("_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 hF(E.awaitDrainWriters?[E.awaitDrainWriters]:[])}E.pipes.push(_),A_("pipe count=%d opts=%j",E.pipes.length,T);let J=(!T||T.end!==!1)&&_!==b1.stdout&&_!==b1.stderr?H:z;if(E.endEmitted)b1.nextTick(J);else A.once("end",J);_.on("unpipe",X);function X(Q,F){if(A_("onunpipe"),Q===A){if(F&&F.hasUnpiped===!1)F.hasUnpiped=!0,K()}}function H(){A_("onend"),_.end()}let Z,Y=!1;function K(){if(A_("cleanup"),_.removeListener("close",V),_.removeListener("finish",N),Z)_.removeListener("drain",Z);if(_.removeListener("error",U),_.removeListener("unpipe",X),A.removeListener("end",H),A.removeListener("end",z),A.removeListener("data",$),Y=!0,Z&&E.awaitDrainWriters&&(!_._writableState||_._writableState.needDrain))Z()}function G(){if(!Y){if(E.pipes.length===1&&E.pipes[0]===_)A_("false write response, pause",0),E.awaitDrainWriters=_,E.multiAwaitDrain=!1;else if(E.pipes.length>1&&E.pipes.includes(_))A_("false write response, pause",E.awaitDrainWriters.size),E.awaitDrainWriters.add(_);A.pause()}if(!Z)Z=$C(A,_),_.on("drain",Z)}A.on("data",$);function $(Q){A_("ondata");let F=_.write(Q);if(A_("dest.write",F),F===!1)G()}function U(Q){if(A_("onerror",Q),z(),_.removeListener("error",U),_.listenerCount("error")===0){let F=_._writableState||_._readableState;if(F&&!F.errorEmitted)nT(_,Q);else _.emit("error",Q)}}mF(_,"error",U);function V(){_.removeListener("finish",N),z()}_.once("close",V);function N(){A_("onfinish"),_.removeListener("close",V),z()}_.once("finish",N);function z(){A_("unpipe"),A.unpipe(_)}if(_.emit("pipe",A),_.writableNeedDrain===!0)G();else if(!E.flowing)A_("pipe resume"),A.resume();return _};function $C(_,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=xF(T.pipes,_);if(E===-1)return this;if(T.pipes.splice(E,1),T.pipes.length===0)this.pause();return _.emit("unpipe",this,A),this};s.prototype.on=function(_,T){let A=l0.prototype.on.call(this,_,T),E=this._readableState;if(_==="data"){if(E.readableListening=this.listenerCount("readable")>0,E.flowing!==!1)this.resume()}else if(_==="readable"){if(!E.endEmitted&&!E.readableListening){if(E.readableListening=E.needReadable=!0,E.flowing=!1,E.emittedReadable=!1,A_("on readable",E.length,E.reading),E.length)ZA(this);else if(!E.reading)b1.nextTick(UC,this)}}return A};s.prototype.addListener=s.prototype.on;s.prototype.removeListener=function(_,T){let A=l0.prototype.removeListener.call(this,_,T);if(_==="readable")b1.nextTick(PX,this);return A};s.prototype.off=s.prototype.removeListener;s.prototype.removeAllListeners=function(_){let T=l0.prototype.removeAllListeners.apply(this,arguments);if(_==="readable"||_===void 0)b1.nextTick(PX,this);return T};function PX(_){let T=_._readableState;if(T.readableListening=_.listenerCount("readable")>0,T.resumeScheduled&&T[UT]===!1)T.flowing=!0;else if(_.listenerCount("data")>0)_.resume();else if(!T.readableListening)T.flowing=null}function UC(_){A_("readable nexttick read 0"),_.read(0)}s.prototype.resume=function(){let _=this._readableState;if(!_.flowing)A_("resume"),_.flowing=!_.readableListening,WC(this,_);return _[UT]=!1,this};function WC(_,T){if(!T.resumeScheduled)T.resumeScheduled=!0,b1.nextTick(NC,_,T)}function NC(_,T){if(A_("resume",T.reading),!T.reading)_.read(0);if(T.resumeScheduled=!1,_.emit("resume"),jX(_),T.flowing&&!T.reading)_.read(0)}s.prototype.pause=function(){if(A_("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)A_("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState[UT]=!0,this};function jX(_){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=vF(_);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[fF]=function(){return xX(this)};s.prototype.iterator=function(_){if(_!==void 0)sF(_,"options");return xX(this,_)};function xX(_,T){if(typeof _.read!=="function")_=s.wrap(_,{objectMode:!0});let A=QC(_,T);return A.stream=_,A}async function*QC(_,T){let A=R6;function E(X){if(this===_)A(),A=R6;else A=X}_.on("readable",E);let L,J=FX(_,{writable:!1},(X)=>{L=X?QX(L,X):null,A(),A=R6});try{while(!0){let X=_.destroyed?null:_.read();if(X!==null)yield X;else if(L)throw L;else if(L===null)return;else await new zX(E)}}catch(X){throw L=QX(L,X),L}finally{if((L||(T===null||T===void 0?void 0:T.destroyOnReturn)!==!1)&&(L===void 0||_._readableState.autoDestroy))aT.destroyer(_,null);else _.off("readable",E),J()}}j6(s.prototype,{readable:{__proto__:null,get(){let _=this._readableState;return!!_&&_.readable!==!1&&!_.destroyed&&!_.errorEmitted&&!_.endEmitted},set(_){if(this._readableState)this._readableState.readable=!!_}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(_){if(this._readableState)this._readableState.flowing=_}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(_){if(!this._readableState)return;this._readableState.destroyed=_}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});j6(HA.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[UT]!==!1},set(_){this[UT]=!!_}}});s._fromList=wX;function wX(_,T){if(T.length===0)return null;let A;if(T.objectMode)A=T.buffer.shift();else if(!_||_>=T.length){if(T.decoder)A=T.buffer.join("");else if(T.buffer.length===1)A=T.buffer.first();else A=T.buffer.concat(T.length);T.buffer.clear()}else A=T.buffer.consume(_,T.decoder);return A}function B6(_){let T=_._readableState;if(A_("endReadable",T.endEmitted),!T.endEmitted)T.ended=!0,b1.nextTick(MC,T,_)}function MC(_,T){if(A_("endReadableNT",_.endEmitted,_.length),!_.errored&&!_.closeEmitted&&!_.endEmitted&&_.length===0){if(_.endEmitted=!0,T.emit("end"),T.writable&&T.allowHalfOpen===!1)b1.nextTick(VC,T);else if(_.autoDestroy){let A=T._writableState;if(!A||A.autoDestroy&&(A.finished||A.writable===!1))T.destroy()}}}function VC(_){if(_.writable&&!_.writableEnded&&!_.destroyed)_.end()}s.from=function(_,T){return tF(s,_,T)};var q6;function SX(){if(q6===void 0)q6={};return q6}s.fromWeb=function(_,T){return SX().newStreamReadableFromReadableStream(_,T)};s.toWeb=function(_,T){return SX().newReadableStreamFromStreamReadable(_,T)};s.wrap=function(_,T){var A,E;return new s({objectMode:(A=(E=_.readableObjectMode)!==null&&E!==void 0?E:_.objectMode)!==null&&A!==void 0?A:!0,...T,destroy(L,J){aT.destroyer(_,L),J(L)}}).wrap(_)}});var UA=W((Ff,lX)=>{var WT=c0(),{ArrayPrototypeSlice:kX,Error:zC,FunctionPrototypeSymbolHasInstance:fX,ObjectDefineProperty:bX,ObjectDefineProperties:FC,ObjectSetPrototypeOf:gX,StringPrototypeToLowerCase:CC,Symbol:OC,SymbolHasInstance:RC}=z_();lX.exports=O_;O_.WritableState=b4;var{EventEmitter:DC}=j("events"),k4=_A().Stream,{Buffer:YA}=j("buffer"),$A=GT(),{addAbortSignal:BC}=w4(),{getHighWaterMark:qC,getDefaultHighWaterMark:IC}=S4(),{ERR_INVALID_ARG_TYPE:PC,ERR_METHOD_NOT_IMPLEMENTED:jC,ERR_MULTIPLE_CALLBACK:mX,ERR_STREAM_CANNOT_PIPE:xC,ERR_STREAM_DESTROYED:f4,ERR_STREAM_ALREADY_FINISHED:wC,ERR_STREAM_NULL_VALUES:SC,ERR_STREAM_WRITE_AFTER_END:yC,ERR_UNKNOWN_ENCODING:uX}=l_().codes,{errorOrDestroy:oT}=$A;gX(O_.prototype,k4.prototype);gX(O_,k4);function S6(){}var rT=OC("kOnFinished");function b4(_,T,A){if(typeof A!=="boolean")A=T instanceof E0();if(this.objectMode=!!(_&&_.objectMode),A)this.objectMode=this.objectMode||!!(_&&_.writableObjectMode);this.highWaterMark=_?qC(this,_,"writableHighWaterMark",A):IC(!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=hC.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 kX(this.buffered,this.bufferedIndex)};bX(b4.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function O_(_){let T=this instanceof E0();if(!T&&!fX(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)BC(_.signal,this)}k4.call(this,_),$A.construct(this,()=>{let A=this._writableState;if(!A.writing)v6(this,A);h6(this,A)})}bX(O_,RC,{__proto__:null,value:function(_){if(fX(this,_))return!0;if(this!==O_)return!1;return _&&_._writableState instanceof b4}});O_.prototype.pipe=function(){oT(this,new xC)};function dX(_,T,A,E){let L=_._writableState;if(typeof A==="function")E=A,A=L.defaultEncoding;else{if(!A)A=L.defaultEncoding;else if(A!=="buffer"&&!YA.isEncoding(A))throw new uX(A);if(typeof E!=="function")E=S6}if(T===null)throw new SC;else if(!L.objectMode)if(typeof T==="string"){if(L.decodeStrings!==!1)T=YA.from(T,A),A="buffer"}else if(T instanceof YA)A="buffer";else if(k4._isUint8Array(T))T=k4._uint8ArrayToBuffer(T),A="buffer";else throw new PC("chunk",["string","Buffer","Uint8Array"],T);let J;if(L.ending)J=new yC;else if(L.destroyed)J=new f4("write");if(J)return WT.nextTick(E,J),oT(_,J,!0),J;return L.pendingcb++,vC(_,L,T,A,E)}O_.prototype.write=function(_,T,A){return dX(this,_,T,A)===!0};O_.prototype.cork=function(){this._writableState.corked++};O_.prototype.uncork=function(){let _=this._writableState;if(_.corked){if(_.corked--,!_.writing)v6(this,_)}};O_.prototype.setDefaultEncoding=function(T){if(typeof T==="string")T=CC(T);if(!YA.isEncoding(T))throw new uX(T);return this._writableState.defaultEncoding=T,this};function vC(_,T,A,E,L){let J=T.objectMode?1:A.length;T.length+=J;let X=T.length<T.highWaterMark;if(!X)T.needDrain=!0;if(T.writing||T.corked||T.errored||!T.constructed){if(T.buffered.push({chunk:A,encoding:E,callback:L}),T.allBuffers&&E!=="buffer")T.allBuffers=!1;if(T.allNoop&&L!==S6)T.allNoop=!1}else T.writelen=J,T.writecb=L,T.writing=!0,T.sync=!0,_._write(A,E,T.onwrite),T.sync=!1;return X&&!T.errored&&!T.destroyed}function vX(_,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 hX(_,T,A,E){--T.pendingcb,E(A),y6(T),oT(_,A)}function hC(_,T){let A=_._writableState,E=A.sync,L=A.writecb;if(typeof L!=="function"){oT(_,new mX);return}if(A.writing=!1,A.writecb=null,A.length-=A.writelen,A.writelen=0,T){if(T.stack,!A.errored)A.errored=T;if(_._readableState&&!_._readableState.errored)_._readableState.errored=T;if(E)WT.nextTick(hX,_,A,T,L);else hX(_,A,T,L)}else{if(A.buffered.length>A.bufferedIndex)v6(_,A);if(E)if(A.afterWriteTickInfo!==null&&A.afterWriteTickInfo.cb===L)A.afterWriteTickInfo.count++;else A.afterWriteTickInfo={count:1,cb:L,stream:_,state:A},WT.nextTick(kC,A.afterWriteTickInfo);else cX(_,A,1,L)}}function kC({stream:_,state:T,count:A,cb:E}){return T.afterWriteTickInfo=null,cX(_,T,A,E)}function cX(_,T,A,E){if(!T.ending&&!_.destroyed&&T.length===0&&T.needDrain)T.needDrain=!1,_.emit("drain");while(A-- >0)T.pendingcb--,E();if(T.destroyed)y6(T);h6(_,T)}function y6(_){if(_.writing)return;for(let L=_.bufferedIndex;L<_.buffered.length;++L){var T;let{chunk:J,callback:X}=_.buffered[L],H=_.objectMode?1:J.length;_.length-=H,X((T=_.errored)!==null&&T!==void 0?T:new f4("write"))}let A=_[rT].splice(0);for(let L=0;L<A.length;L++){var E;A[L]((E=_.errored)!==null&&E!==void 0?E:new f4("end"))}GA(_)}function v6(_,T){if(T.corked||T.bufferProcessing||T.destroyed||!T.constructed)return;let{buffered:A,bufferedIndex:E,objectMode:L}=T,J=A.length-E;if(!J)return;let X=E;if(T.bufferProcessing=!0,J>1&&_._writev){T.pendingcb-=J-1;let H=T.allNoop?S6:(Y)=>{for(let K=X;K<A.length;++K)A[K].callback(Y)},Z=T.allNoop&&X===0?A:kX(A,X);Z.allBuffers=T.allBuffers,vX(_,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;vX(_,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 jC("_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=dX(this,_,T);if(J instanceof zC)L=J}if(E.corked)E.corked=1,this.uncork();if(L);else if(!E.errored&&!E.ending)E.ending=!0,h6(this,E,!0),E.ended=!0;else if(E.finished)L=new wC("end");else if(E.destroyed)L=new f4("end");if(typeof A==="function")if(L||E.finished)WT.nextTick(A,L);else E[rT].push(A);return this};function KA(_){return _.ending&&!_.destroyed&&_.constructed&&_.length===0&&!_.errored&&_.buffered.length===0&&!_.finished&&!_.writing&&!_.errorEmitted&&!_.closeEmitted}function fC(_,T){let A=!1;function E(L){if(A){oT(_,L!==null&&L!==void 0?L:mX());return}if(A=!0,T.pendingcb--,L){let J=T[rT].splice(0);for(let X=0;X<J.length;X++)J[X](L);oT(_,L,T.sync)}else if(KA(T))T.prefinished=!0,_.emit("prefinish"),T.pendingcb++,WT.nextTick(w6,_,T)}T.sync=!0,T.pendingcb++;try{_._final(E)}catch(L){E(L)}T.sync=!1}function bC(_,T){if(!T.prefinished&&!T.finalCalled)if(typeof _._final==="function"&&!T.destroyed)T.finalCalled=!0,fC(_,T);else T.prefinished=!0,_.emit("prefinish")}function h6(_,T,A){if(KA(T)){if(bC(_,T),T.pendingcb===0){if(A)T.pendingcb++,WT.nextTick((E,L)=>{if(KA(L))w6(E,L);else L.pendingcb--},_,T);else if(KA(T))T.pendingcb++,w6(_,T)}}}function w6(_,T){T.pendingcb--,T.finished=!0;let A=T[rT].splice(0);for(let E=0;E<A.length;E++)A[E]();if(_.emit("finish"),T.autoDestroy){let E=_._readableState;if(!E||E.autoDestroy&&(E.endEmitted||E.readable===!1))_.destroy()}}FC(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 gC=$A.destroy;O_.prototype.destroy=function(_,T){let A=this._writableState;if(!A.destroyed&&(A.bufferedIndex<A.buffered.length||A[rT].length))WT.nextTick(y6,A);return gC.call(this,_,T),this};O_.prototype._undestroy=$A.undestroy;O_.prototype._destroy=function(_,T){T(_)};O_.prototype[DC.captureRejectionSymbol]=function(_){this.destroy(_)};var x6;function pX(){if(x6===void 0)x6={};return x6}O_.fromWeb=function(_,T){return pX().newStreamWritableFromWritableStream(_,T)};O_.toWeb=function(_){return pX().newWritableStreamFromStreamWritable(_)}});var XH=W((Cf,JH)=>{var k6=c0(),mC=j("buffer"),{isReadable:uC,isWritable:dC,isIterable:nX,isNodeStream:cC,isReadableNodeStream:iX,isWritableNodeStream:aX,isDuplexNodeStream:pC,isReadableStream:oX,isWritableStream:rX}=_0(),sX=B0(),{AbortError:EH,codes:{ERR_INVALID_ARG_TYPE:lC,ERR_INVALID_RETURN_VALUE:tX}}=l_(),{destroyer:tT}=GT(),nC=E0(),LH=h4(),iC=UA(),{createDeferredPromise:eX}=s_(),_H=C6(),TH=globalThis.Blob||mC.Blob,aC=typeof TH<"u"?function(T){return T instanceof TH}:function(T){return!1},oC=globalThis.AbortController||j("abort-controller").AbortController,{FunctionPrototypeCall:AH}=z_();class NT extends nC{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}}JH.exports=function _(T,A){if(pC(T))return T;if(iX(T))return sT({readable:T});if(aX(T))return sT({writable:T});if(cC(T))return sT({writable:!1,readable:!1});if(oX(T))return sT({readable:LH.fromWeb(T)});if(rX(T))return sT({writable:iC.fromWeb(T)});if(typeof T==="function"){let{value:L,write:J,final:X,destroy:H}=rC(T);if(nX(L))return _H(NT,L,{objectMode:!0,write:J,final:X,destroy:H});let Z=L===null||L===void 0?void 0:L.then;if(typeof Z==="function"){let Y,K=AH(Z,L,(G)=>{if(G!=null)throw new tX("nully","body",G)},(G)=>{tT(Y,G)});return Y=new NT({objectMode:!0,readable:!1,write:J,final(G){X(async()=>{try{await K,k6.nextTick(G,null)}catch($){k6.nextTick(G,$)}})},destroy:H})}throw new tX("Iterable, AsyncIterable or AsyncFunction",A,L)}if(aC(T))return _(T.arrayBuffer());if(nX(T))return _H(NT,T,{objectMode:!0,writable:!1});if(oX(T===null||T===void 0?void 0:T.readable)&&rX(T===null||T===void 0?void 0:T.writable))return NT.fromWeb(T);if(typeof(T===null||T===void 0?void 0:T.writable)==="object"||typeof(T===null||T===void 0?void 0:T.readable)==="object"){let L=T!==null&&T!==void 0&&T.readable?iX(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?aX(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 AH(E,T,(J)=>{if(J!=null)L.push(J);L.push(null)},(J)=>{tT(L,J)}),L=new NT({objectMode:!0,writable:!1,read(){}})}throw new lC(A,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],T)};function rC(_){let{promise:T,resolve:A}=eX(),E=new oC,L=E.signal;return{value:_(async function*(){while(!0){let X=T;T=null;let{chunk:H,done:Z,cb:Y}=await X;if(k6.nextTick(Y),Z)return;if(L.aborted)throw new EH(void 0,{cause:L.reason});({promise:T,resolve:A}=eX()),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"?LH.wrap(_.readable):_.readable,A=_.writable,E=!!uC(T),L=!!dC(A),J,X,H,Z,Y;function K(G){let $=Z;if(Z=null,$)$(G);else if(G)Y.destroy(G)}if(Y=new NT({readableObjectMode:!!(T!==null&&T!==void 0&&T.readableObjectMode),writableObjectMode:!!(A!==null&&A!==void 0&&A.writableObjectMode),readable:E,writable:L}),L)sX(A,(G)=>{if(L=!1,G)tT(T,G);K(G)}),Y._write=function(G,$,U){if(A.write(G,$))U();else J=U},Y._final=function(G){A.end(),X=G},A.on("drain",function(){if(J){let G=J;J=null,G()}}),A.on("finish",function(){if(X){let G=X;X=null,G()}});if(E)sX(T,(G)=>{if(E=!1,G)tT(T,G);K(G)}),T.on("readable",function(){if(H){let G=H;H=null,G()}}),T.on("end",function(){Y.push(null)}),Y._read=function(){while(!0){let G=T.read();if(G===null){H=Y._read;return}if(!Y.push(G))return}};return Y._destroy=function(G,$){if(!G&&Z!==null)G=new EH;if(H=null,J=null,X=null,Z===null)$(G);else Z=$,tT(A,G),tT(T,G)},Y}});var E0=W((Of,YH)=>{var{ObjectDefineProperties:sC,ObjectGetOwnPropertyDescriptor:q0,ObjectKeys:tC,ObjectSetPrototypeOf:HH}=z_();YH.exports=g1;var g6=h4(),C1=UA();HH(g1.prototype,g6.prototype);HH(g1,g6);{let _=tC(C1.prototype);for(let T=0;T<_.length;T++){let A=_[T];if(!g1.prototype[A])g1.prototype[A]=C1.prototype[A]}}function g1(_){if(!(this instanceof g1))return new g1(_);if(g6.call(this,_),C1.call(this,_),_){if(this.allowHalfOpen=_.allowHalfOpen!==!1,_.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(_.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}sC(g1.prototype,{writable:{__proto__:null,...q0(C1.prototype,"writable")},writableHighWaterMark:{__proto__:null,...q0(C1.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...q0(C1.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...q0(C1.prototype,"writableBuffer")},writableLength:{__proto__:null,...q0(C1.prototype,"writableLength")},writableFinished:{__proto__:null,...q0(C1.prototype,"writableFinished")},writableCorked:{__proto__:null,...q0(C1.prototype,"writableCorked")},writableEnded:{__proto__:null,...q0(C1.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...q0(C1.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(_){if(this._readableState&&this._writableState)this._readableState.destroyed=_,this._writableState.destroyed=_}}});var f6;function ZH(){if(f6===void 0)f6={};return f6}g1.fromWeb=function(_,T){return ZH().newStreamDuplexFromReadableWritablePair(_,T)};g1.toWeb=function(_){return ZH().newReadableWritablePairFromDuplex(_)};var b6;g1.from=function(_){if(!b6)b6=XH();return b6(_,"body")}});var d6=W((Rf,GH)=>{var{ObjectSetPrototypeOf:KH,Symbol:eC}=z_();GH.exports=I0;var{ERR_METHOD_NOT_IMPLEMENTED:_O}=l_().codes,u6=E0(),{getHighWaterMark:TO}=S4();KH(I0.prototype,u6.prototype);KH(I0,u6);var g4=eC("kCallback");function I0(_){if(!(this instanceof I0))return new I0(_);let T=_?TO(this,_,"readableHighWaterMark",!0):null;if(T===0)_={..._,highWaterMark:null,readableHighWaterMark:T,writableHighWaterMark:_.writableHighWaterMark||0};if(u6.call(this,_),this._readableState.sync=!1,this[g4]=null,_){if(typeof _.transform==="function")this._transform=_.transform;if(typeof _.flush==="function")this._flush=_.flush}this.on("prefinish",AO)}function m6(_){if(typeof this._flush==="function"&&!this.destroyed)this._flush((T,A)=>{if(T){if(_)_(T);else this.destroy(T);return}if(A!=null)this.push(A);if(this.push(null),_)_()});else if(this.push(null),_)_()}function AO(){if(this._final!==m6)m6.call(this)}I0.prototype._final=m6;I0.prototype._transform=function(_,T,A){throw new _O("_transform()")};I0.prototype._write=function(_,T,A){let E=this._readableState,L=this._writableState,J=E.length;this._transform(_,T,(X,H)=>{if(X){A(X);return}if(H!=null)this.push(H);if(L.ended||J===E.length||E.length<E.highWaterMark)A();else this[g4]=A})};I0.prototype._read=function(){if(this[g4]){let _=this[g4];this[g4]=null,_()}}});var p6=W((Df,UH)=>{var{ObjectSetPrototypeOf:$H}=z_();UH.exports=eT;var c6=d6();$H(eT.prototype,c6.prototype);$H(eT,c6);function eT(_){if(!(this instanceof eT))return new eT(_);c6.call(this,_)}eT.prototype._transform=function(_,T,A){A(null,_)}});var MA=W((Bf,VH)=>{var m4=c0(),{ArrayIsArray:EO,Promise:LO,SymbolAsyncIterator:JO,SymbolDispose:XO}=z_(),QA=B0(),{once:HO}=s_(),ZO=GT(),WH=E0(),{aggregateTwoErrors:YO,codes:{ERR_INVALID_ARG_TYPE:e6,ERR_INVALID_RETURN_VALUE:l6,ERR_MISSING_ARGS:KO,ERR_STREAM_DESTROYED:GO,ERR_STREAM_PREMATURE_CLOSE:$O},AbortError:UO}=l_(),{validateFunction:WO,validateAbortSignal:NO}=pT(),{isIterable:QT,isReadable:n6,isReadableNodeStream:NA,isNodeStream:NH,isTransformStream:_4,isWebStream:QO,isReadableStream:i6,isReadableFinished:MO}=_0(),VO=globalThis.AbortController||j("abort-controller").AbortController,a6,o6,r6;function QH(_,T,A){let E=!1;_.on("close",()=>{E=!0});let L=QA(_,{readable:T,writable:A},(J)=>{E=!J});return{destroy:(J)=>{if(E)return;E=!0,ZO.destroyer(_,J||new GO("pipe"))},cleanup:L}}function zO(_){return WO(_[_.length-1],"streams[stream.length - 1]"),_.pop()}function s6(_){if(QT(_))return _;else if(NA(_))return FO(_);throw new e6("val",["Readable","Iterable","AsyncIterable"],_)}async function*FO(_){if(!o6)o6=h4();yield*o6.prototype[JO].call(_)}async function WA(_,T,A,{end:E}){let L,J=null,X=(Y)=>{if(Y)L=Y;if(J){let K=J;J=null,K()}},H=()=>new LO((Y,K)=>{if(L)K(L);else J=()=>{if(L)K(L);else Y()}});T.on("drain",X);let Z=QA(T,{readable:!1},X);try{if(T.writableNeedDrain)await H();for await(let Y of _)if(!T.write(Y))await H();if(E)T.end(),await H();A()}catch(Y){A(L!==Y?YO(L,Y):Y)}finally{Z(),T.off("drain",X)}}async function t6(_,T,A,{end:E}){if(_4(T))T=T.writable;let L=T.getWriter();try{for await(let J of _)await L.ready,L.write(J).catch(()=>{});if(await L.ready,E)await L.close();A()}catch(J){try{await L.abort(J),A(J)}catch(X){A(X)}}}function CO(..._){return MH(_,HO(zO(_)))}function MH(_,T,A){if(_.length===1&&EO(_[0]))_=_[0];if(_.length<2)throw new KO("streams");let E=new VO,L=E.signal,J=A===null||A===void 0?void 0:A.signal,X=[];NO(J,"options.signal");function H(){V(new UO)}r6=r6||s_().addAbortListener;let Z;if(J)Z=r6(J,H);let Y,K,G=[],$=0;function U(R){V(R,--$===0)}function V(R,q){var f;if(R&&(!Y||Y.code==="ERR_STREAM_PREMATURE_CLOSE"))Y=R;if(!Y&&!q)return;while(G.length)G.shift()(Y);if((f=Z)===null||f===void 0||f[XO](),E.abort(),q){if(!Y)X.forEach((h)=>h());m4.nextTick(T,Y,K)}}let N;for(let R=0;R<_.length;R++){let q=_[R],f=R<_.length-1,h=R>0,b=f||(A===null||A===void 0?void 0:A.end)!==!1,l=R===_.length-1;if(NH(q)){let c=function(W_){if(W_&&W_.name!=="AbortError"&&W_.code!=="ERR_STREAM_PREMATURE_CLOSE")U(W_)};var F=c;if(b){let{destroy:W_,cleanup:c_}=QH(q,f,h);if(G.push(W_),n6(q)&&l)X.push(c_)}if(q.on("error",c),n6(q)&&l)X.push(()=>{q.removeListener("error",c)})}if(R===0)if(typeof q==="function"){if(N=q({signal:L}),!QT(N))throw new l6("Iterable, AsyncIterable or Stream","source",N)}else if(QT(q)||NA(q)||_4(q))N=q;else N=WH.from(q);else if(typeof q==="function"){if(_4(N)){var z;N=s6((z=N)===null||z===void 0?void 0:z.readable)}else N=s6(N);if(N=q(N,{signal:L}),f){if(!QT(N,!0))throw new l6("AsyncIterable",`transform[${R-1}]`,N)}else{var Q;if(!a6)a6=p6();let c=new a6({objectMode:!0}),W_=(Q=N)===null||Q===void 0?void 0:Q.then;if(typeof W_==="function")$++,W_.call(N,(C_)=>{if(K=C_,C_!=null)c.write(C_);if(b)c.end();m4.nextTick(U)},(C_)=>{c.destroy(C_),m4.nextTick(U,C_)});else if(QT(N,!0))$++,WA(N,c,U,{end:b});else if(i6(N)||_4(N)){let C_=N.readable||N;$++,WA(C_,c,U,{end:b})}else throw new l6("AsyncIterable or Promise","destination",N);N=c;let{destroy:c_,cleanup:B_}=QH(N,!1,!0);if(G.push(c_),l)X.push(B_)}}else if(NH(q)){if(NA(N)){$+=2;let c=OO(N,q,U,{end:b});if(n6(q)&&l)X.push(c)}else if(_4(N)||i6(N)){let c=N.readable||N;$++,WA(c,q,U,{end:b})}else if(QT(N))$++,WA(N,q,U,{end:b});else throw new e6("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else if(QO(q)){if(NA(N))$++,t6(s6(N),q,U,{end:b});else if(i6(N)||QT(N))$++,t6(N,q,U,{end:b});else if(_4(N))$++,t6(N.readable,q,U,{end:b});else throw new e6("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else N=WH.from(q)}if(L!==null&&L!==void 0&&L.aborted||J!==null&&J!==void 0&&J.aborted)m4.nextTick(H);return N}function OO(_,T,A,{end:E}){let L=!1;if(T.on("close",()=>{if(!L)A(new $O)}),_.pipe(T,{end:!1}),E){let X=function(){L=!0,T.end()};var J=X;if(MO(_))m4.nextTick(X);else _.once("end",X)}else A();return QA(_,{readable:!0,writable:!1},(X)=>{let H=_._readableState;if(X&&X.code==="ERR_STREAM_PREMATURE_CLOSE"&&H&&H.ended&&!H.errored&&!H.errorEmitted)_.once("end",A).once("error",A);else A(X)}),QA(T,{readable:!1,writable:!0},A)}VH.exports={pipelineImpl:MH,pipeline:CO}});var TE=W((qf,DH)=>{var{pipeline:RO}=MA(),VA=E0(),{destroyer:DO}=GT(),{isNodeStream:zA,isReadable:zH,isWritable:FH,isWebStream:_E,isTransformStream:MT,isWritableStream:CH,isReadableStream:OH}=_0(),{AbortError:BO,codes:{ERR_INVALID_ARG_VALUE:RH,ERR_MISSING_ARGS:qO}}=l_(),IO=B0();DH.exports=function(...T){if(T.length===0)throw new qO("streams");if(T.length===1)return VA.from(T[0]);let A=[...T];if(typeof T[0]==="function")T[0]=VA.from(T[0]);if(typeof T[T.length-1]==="function"){let U=T.length-1;T[U]=VA.from(T[U])}for(let U=0;U<T.length;++U){if(!zA(T[U])&&!_E(T[U]))continue;if(U<T.length-1&&!(zH(T[U])||OH(T[U])||MT(T[U])))throw new RH(`streams[${U}]`,A[U],"must be readable");if(U>0&&!(FH(T[U])||CH(T[U])||MT(T[U])))throw new RH(`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=RO(T,Z),G=!!(FH(Y)||CH(Y)||MT(Y)),$=!!(zH(K)||OH(K)||MT(K));if(H=new VA({writableObjectMode:!!(Y!==null&&Y!==void 0&&Y.writableObjectMode),readableObjectMode:!!(K!==null&&K!==void 0&&K.readableObjectMode),writable:G,readable:$}),G){if(zA(Y))H._write=function(V,N,z){if(Y.write(V,N))z();else E=z},H._final=function(V){Y.end(),L=V},Y.on("drain",function(){if(E){let V=E;E=null,V()}});else if(_E(Y)){let N=(MT(Y)?Y.writable:Y).getWriter();H._write=async function(z,Q,F){try{await N.ready,N.write(z).catch(()=>{}),F()}catch(R){F(R)}},H._final=async function(z){try{await N.ready,N.close().catch(()=>{}),L=z}catch(Q){z(Q)}}}let U=MT(K)?K.readable:K;IO(U,()=>{if(L){let V=L;L=null,V()}})}if($){if(zA(K))K.on("readable",function(){if(J){let U=J;J=null,U()}}),K.on("end",function(){H.push(null)}),H._read=function(){while(!0){let U=K.read();if(U===null){J=H._read;return}if(!H.push(U))return}};else if(_E(K)){let V=(MT(K)?K.readable:K).getReader();H._read=async function(){while(!0)try{let{value:N,done:z}=await V.read();if(!H.push(N))return;if(z){H.push(null);return}}catch{return}}}}return H._destroy=function(U,V){if(!U&&X!==null)U=new BO;if(J=null,E=null,L=null,X===null)V(U);else if(X=V,zA(K))DO(K,U)},H}});var hH=W((TR,EE)=>{var PO=globalThis.AbortController||j("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:jO,ERR_INVALID_ARG_TYPE:u4,ERR_MISSING_ARGS:xO,ERR_OUT_OF_RANGE:wO},AbortError:L0}=l_(),{validateAbortSignal:VT,validateInteger:BH,validateObject:zT}=pT(),SO=z_().Symbol("kWeak"),yO=z_().Symbol("kResistStopPropagation"),{finished:vO}=B0(),hO=TE(),{addAbortSignalNoValidate:kO}=w4(),{isWritable:fO,isNodeStream:bO}=_0(),{deprecate:gO}=s_(),{ArrayPrototypePush:mO,Boolean:uO,MathFloor:qH,Number:dO,NumberIsNaN:cO,Promise:IH,PromiseReject:PH,PromiseResolve:pO,PromisePrototypeThen:jH,Symbol:wH}=z_(),FA=wH("kEmpty"),xH=wH("kEof");function lO(_,T){if(T!=null)zT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)VT(T.signal,"options.signal");if(bO(_)&&!fO(_))throw new jO("stream",_,"must be writable");let A=hO(this,_);if(T!==null&&T!==void 0&&T.signal)kO(T.signal,A);return A}function CA(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);if(T!=null)zT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)VT(T.signal,"options.signal");let A=1;if((T===null||T===void 0?void 0:T.concurrency)!=null)A=qH(T.concurrency);let E=A-1;if((T===null||T===void 0?void 0:T.highWaterMark)!=null)E=qH(T.highWaterMark);return BH(A,"options.concurrency",1),BH(E,"options.highWaterMark",0),E+=A,async function*(){let J=s_().AbortSignalAny([T===null||T===void 0?void 0:T.signal].filter(uO)),X=this,H=[],Z={signal:J},Y,K,G=!1,$=0;function U(){G=!0,V()}function V(){$-=1,N()}function N(){if(K&&!G&&$<A&&H.length<E)K(),K=null}async function z(){try{for await(let Q of X){if(G)return;if(J.aborted)throw new L0;try{if(Q=_(Q,Z),Q===FA)continue;Q=pO(Q)}catch(F){Q=PH(F)}if($+=1,jH(Q,V,U),H.push(Q),Y)Y(),Y=null;if(!G&&(H.length>=E||$>=A))await new IH((F)=>{K=F})}H.push(xH)}catch(Q){let F=PH(Q);jH(F,V,U),H.push(F)}finally{if(G=!0,Y)Y(),Y=null}}z();try{while(!0){while(H.length>0){let Q=await H[0];if(Q===xH)return;if(J.aborted)throw new L0;if(Q!==FA)yield Q;H.shift(),N()}await new IH((Q)=>{Y=Q})}}finally{if(G=!0,K)K(),K=null}}.call(this)}function nO(_=void 0){if(_!=null)zT(_,"options");if((_===null||_===void 0?void 0:_.signal)!=null)VT(_.signal,"options.signal");return async function*(){let A=0;for await(let L of this){var E;if(_!==null&&_!==void 0&&(E=_.signal)!==null&&E!==void 0&&E.aborted)throw new L0({cause:_.signal.reason});yield[A++,L]}}.call(this)}async function SH(_,T=void 0){for await(let A of AE.call(this,_,T))return!0;return!1}async function iO(_,T=void 0){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);return!await SH.call(this,async(...A)=>{return!await _(...A)},T)}async function aO(_,T){for await(let A of AE.call(this,_,T))return A;return}async function oO(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){return await _(E,L),FA}for await(let E of CA.call(this,A,T));}function AE(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){if(await _(E,L))return E;return FA}return CA.call(this,A,T)}class yH extends xO{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function rO(_,T,A){var E;if(typeof _!=="function")throw new u4("reducer",["Function","AsyncFunction"],_);if(A!=null)zT(A,"options");if((A===null||A===void 0?void 0:A.signal)!=null)VT(A.signal,"options.signal");let L=arguments.length>1;if(A!==null&&A!==void 0&&(E=A.signal)!==null&&E!==void 0&&E.aborted){let Y=new L0(void 0,{cause:A.signal.reason});throw this.once("error",()=>{}),await vO(this.destroy(Y)),Y}let J=new PO,X=J.signal;if(A!==null&&A!==void 0&&A.signal){let Y={once:!0,[SO]:this,[yO]:!0};A.signal.addEventListener("abort",()=>J.abort(),Y)}let H=!1;try{for await(let Y of this){var Z;if(H=!0,A!==null&&A!==void 0&&(Z=A.signal)!==null&&Z!==void 0&&Z.aborted)throw new L0;if(!L)T=Y,L=!0;else T=await _(T,Y,{signal:X})}if(!H&&!L)throw new yH}finally{J.abort()}return T}async function sO(_){if(_!=null)zT(_,"options");if((_===null||_===void 0?void 0:_.signal)!=null)VT(_.signal,"options.signal");let T=[];for await(let E of this){var A;if(_!==null&&_!==void 0&&(A=_.signal)!==null&&A!==void 0&&A.aborted)throw new L0(void 0,{cause:_.signal.reason});mO(T,E)}return T}function tO(_,T){let A=CA.call(this,_,T);return async function*(){for await(let L of A)yield*L}.call(this)}function vH(_){if(_=dO(_),cO(_))return 0;if(_<0)throw new wO("number",">= 0",_);return _}function eO(_,T=void 0){if(T!=null)zT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)VT(T.signal,"options.signal");return _=vH(_),async function*(){var E;if(T!==null&&T!==void 0&&(E=T.signal)!==null&&E!==void 0&&E.aborted)throw new L0;for await(let J of this){var L;if(T!==null&&T!==void 0&&(L=T.signal)!==null&&L!==void 0&&L.aborted)throw new L0;if(_--<=0)yield J}}.call(this)}function _R(_,T=void 0){if(T!=null)zT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)VT(T.signal,"options.signal");return _=vH(_),async function*(){var E;if(T!==null&&T!==void 0&&(E=T.signal)!==null&&E!==void 0&&E.aborted)throw new L0;for await(let J of this){var L;if(T!==null&&T!==void 0&&(L=T.signal)!==null&&L!==void 0&&L.aborted)throw new L0;if(_-- >0)yield J;if(_<=0)return}}.call(this)}TR.streamReturningOperators={asIndexedPairs:gO(nO,"readable.asIndexedPairs will be removed in a future version."),drop:eO,filter:AE,flatMap:tO,map:CA,take:_R,compose:lO};TR.promiseReturningOperators={every:iO,forEach:oO,reduce:rO,toArray:sO,some:SH,find:aO}});var LE=W((If,kH)=>{var{ArrayPrototypePop:LR,Promise:JR}=z_(),{isIterable:XR,isNodeStream:HR,isWebStream:ZR}=_0(),{pipelineImpl:YR}=MA(),{finished:KR}=B0();JE();function GR(..._){return new JR((T,A)=>{let E,L,J=_[_.length-1];if(J&&typeof J==="object"&&!HR(J)&&!XR(J)&&!ZR(J)){let X=LR(_);E=X.signal,L=X.end}YR(_,(X,H)=>{if(X)A(X);else T(H)},{signal:E,end:L})})}kH.exports={finished:KR,pipeline:GR}});var JE=W((Pf,lH)=>{var{Buffer:$R}=j("buffer"),{ObjectDefineProperty:P0,ObjectKeys:gH,ReflectApply:mH}=z_(),{promisify:{custom:uH}}=s_(),{streamReturningOperators:fH,promiseReturningOperators:bH}=hH(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:dH}}=l_(),UR=TE(),{setDefaultHighWaterMark:WR,getDefaultHighWaterMark:NR}=S4(),{pipeline:cH}=MA(),{destroyer:QR}=GT(),pH=B0(),XE=LE(),d4=_0(),V_=lH.exports=_A().Stream;V_.isDestroyed=d4.isDestroyed;V_.isDisturbed=d4.isDisturbed;V_.isErrored=d4.isErrored;V_.isReadable=d4.isReadable;V_.isWritable=d4.isWritable;V_.Readable=h4();for(let _ of gH(fH)){let A=function(...E){if(new.target)throw dH();return V_.Readable.from(mH(T,this,E))},T=fH[_];P0(A,"name",{__proto__:null,value:T.name}),P0(A,"length",{__proto__:null,value:T.length}),P0(V_.Readable.prototype,_,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}for(let _ of gH(bH)){let A=function(...E){if(new.target)throw dH();return mH(T,this,E)},T=bH[_];P0(A,"name",{__proto__:null,value:T.name}),P0(A,"length",{__proto__:null,value:T.length}),P0(V_.Readable.prototype,_,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}V_.Writable=UA();V_.Duplex=E0();V_.Transform=d6();V_.PassThrough=p6();V_.pipeline=cH;var{addAbortSignal:MR}=w4();V_.addAbortSignal=MR;V_.finished=pH;V_.destroy=QR;V_.compose=UR;V_.setDefaultHighWaterMark=WR;V_.getDefaultHighWaterMark=NR;P0(V_,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return XE}});P0(cH,uH,{__proto__:null,enumerable:!0,get(){return XE.pipeline}});P0(pH,uH,{__proto__:null,enumerable:!0,get(){return XE.finished}});V_.Stream=V_;V_._isUint8Array=function(T){return T instanceof Uint8Array};V_._uint8ArrayToBuffer=function(T){return $R.from(T.buffer,T.byteOffset,T.byteLength)}});var n0=W((jf,__)=>{var w_=j("stream");if(w_&&process.env.READABLE_STREAM==="disable"){let _=w_.promises;__.exports._uint8ArrayToBuffer=w_._uint8ArrayToBuffer,__.exports._isUint8Array=w_._isUint8Array,__.exports.isDisturbed=w_.isDisturbed,__.exports.isErrored=w_.isErrored,__.exports.isReadable=w_.isReadable,__.exports.Readable=w_.Readable,__.exports.Writable=w_.Writable,__.exports.Duplex=w_.Duplex,__.exports.Transform=w_.Transform,__.exports.PassThrough=w_.PassThrough,__.exports.addAbortSignal=w_.addAbortSignal,__.exports.finished=w_.finished,__.exports.destroy=w_.destroy,__.exports.pipeline=w_.pipeline,__.exports.compose=w_.compose,Object.defineProperty(w_,"promises",{configurable:!0,enumerable:!0,get(){return _}}),__.exports.Stream=w_.Stream}else{let _=JE(),T=LE(),A=_.Readable.destroy;__.exports=_.Readable,__.exports._uint8ArrayToBuffer=_._uint8ArrayToBuffer,__.exports._isUint8Array=_._isUint8Array,__.exports.isDisturbed=_.isDisturbed,__.exports.isErrored=_.isErrored,__.exports.isReadable=_.isReadable,__.exports.Readable=_.Readable,__.exports.Writable=_.Writable,__.exports.Duplex=_.Duplex,__.exports.Transform=_.Transform,__.exports.PassThrough=_.PassThrough,__.exports.addAbortSignal=_.addAbortSignal,__.exports.finished=_.finished,__.exports.destroy=_.destroy,__.exports.destroy=A,__.exports.pipeline=_.pipeline,__.exports.compose=_.compose,Object.defineProperty(_,"promises",{configurable:!0,enumerable:!0,get(){return T}}),__.exports.Stream=_.Stream}__.exports.default=__.exports});var nH=W((nf,HE)=>{if(typeof Object.create==="function")HE.exports=function(T,A){if(A)T.super_=A,T.prototype=Object.create(A.prototype,{constructor:{value:T,enumerable:!1,writable:!0,configurable:!0}})};else HE.exports=function(T,A){if(A){T.super_=A;var E=function(){};E.prototype=A.prototype,T.prototype=new E,T.prototype.constructor=T}}});var iH=W((af,ZE)=>{try{if(OA=j("util"),typeof OA.inherits!=="function")throw"";ZE.exports=OA.inherits}catch(_){ZE.exports=nH()}var OA});var rH=W((of,oH)=>{var{Buffer:m1}=j("buffer"),aH=Symbol.for("BufferList");function H_(_){if(!(this instanceof H_))return new H_(_);H_._init.call(this,_)}H_._init=function(T){if(Object.defineProperty(this,aH,{value:!0}),this._bufs=[],this.length=0,T)this.append(T)};H_.prototype._new=function(T){return new H_(T)};H_.prototype._offset=function(T){if(T===0)return[0,0];let A=0;for(let E=0;E<this._bufs.length;E++){let L=A+this._bufs[E].length;if(T<L||E===this._bufs.length-1)return[E,T-A];A=L}};H_.prototype._reverseOffset=function(_){let T=_[0],A=_[1];for(let E=0;E<T;E++)A+=this._bufs[E].length;return A};H_.prototype.getBuffers=function(){return this._bufs};H_.prototype.get=function(T){if(T>this.length||T<0)return;let A=this._offset(T);return this._bufs[A[0]][A[1]]};H_.prototype.slice=function(T,A){if(typeof T==="number"&&T<0)T+=this.length;if(typeof A==="number"&&A<0)A+=this.length;return this.copy(null,0,T,A)};H_.prototype.copy=function(T,A,E,L){if(typeof E!=="number"||E<0)E=0;if(typeof L!=="number"||L>this.length)L=this.length;if(E>=this.length)return T||m1.alloc(0);if(L<=0)return T||m1.alloc(0);let J=!!T,X=this._offset(E),H=L-E,Z=H,Y=J&&A||0,K=X[1];if(E===0&&L===this.length){if(!J)return this._bufs.length===1?this._bufs[0]:m1.concat(this._bufs,this.length);for(let G=0;G<this._bufs.length;G++)this._bufs[G].copy(T,Y),Y+=this._bufs[G].length;return T}if(Z<=this._bufs[X[0]].length-K)return J?this._bufs[X[0]].copy(T,A,K,K+Z):this._bufs[X[0]].slice(K,K+Z);if(!J)T=m1.allocUnsafe(H);for(let G=X[0];G<this._bufs.length;G++){let $=this._bufs[G].length-K;if(Z>$)this._bufs[G].copy(T,Y,K),Y+=$;else{this._bufs[G].copy(T,Y,K,K+Z),Y+=$;break}if(Z-=$,K)K=0}if(T.length>Y)return T.slice(0,Y);return T};H_.prototype.shallowSlice=function(T,A){if(T=T||0,A=typeof A!=="number"?this.length:A,T<0)T+=this.length;if(A<0)A+=this.length;if(T===A)return this._new();let E=this._offset(T),L=this._offset(A),J=this._bufs.slice(E[0],L[0]+1);if(L[1]===0)J.pop();else J[J.length-1]=J[J.length-1].slice(0,L[1]);if(E[1]!==0)J[0]=J[0].slice(E[1]);return this._new(J)};H_.prototype.toString=function(T,A,E){return this.slice(A,E).toString(T)};H_.prototype.consume=function(T){if(T=Math.trunc(T),Number.isNaN(T)||T<=0)return this;while(this._bufs.length)if(T>=this._bufs[0].length)T-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(T),this.length-=T;break}return this};H_.prototype.duplicate=function(){let T=this._new();for(let A=0;A<this._bufs.length;A++)T.append(this._bufs[A]);return T};H_.prototype.append=function(T){return this._attach(T,H_.prototype._appendBuffer)};H_.prototype.prepend=function(T){return this._attach(T,H_.prototype._prependBuffer,!0)};H_.prototype._attach=function(T,A,E){if(T==null)return this;if(T.buffer)A.call(this,m1.from(T.buffer,T.byteOffset,T.byteLength));else if(Array.isArray(T)){let[L,J]=E?[T.length-1,-1]:[0,1];for(let X=L;X>=0&&X<T.length;X+=J)this._attach(T[X],A,E)}else if(this._isBufferList(T)){let[L,J]=E?[T._bufs.length-1,-1]:[0,1];for(let X=L;X>=0&&X<T._bufs.length;X+=J)this._attach(T._bufs[X],A,E)}else{if(typeof T==="number")T=T.toString();A.call(this,m1.from(T))}return this};H_.prototype._appendBuffer=function(T){this._bufs.push(T),this.length+=T.length};H_.prototype._prependBuffer=function(T){this._bufs.unshift(T),this.length+=T.length};H_.prototype.indexOf=function(_,T,A){if(A===void 0&&typeof T==="string")A=T,T=void 0;if(typeof _==="function"||Array.isArray(_))throw TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');else if(typeof _==="number")_=m1.from([_]);else if(typeof _==="string")_=m1.from(_,A);else if(this._isBufferList(_))_=_.slice();else if(Array.isArray(_.buffer))_=m1.from(_.buffer,_.byteOffset,_.byteLength);else if(!m1.isBuffer(_))_=m1.from(_);if(T=Number(T||0),isNaN(T))T=0;if(T<0)T=this.length+T;if(T<0)T=0;if(_.length===0)return T>this.length?this.length:T;let E=this._offset(T),L=E[0],J=E[1];for(;L<this._bufs.length;L++){let X=this._bufs[L];while(J<X.length)if(X.length-J>=_.length){let Z=X.indexOf(_,J);if(Z!==-1)return this._reverseOffset([L,Z]);J=X.length-_.length+1}else{let Z=this._reverseOffset([L,J]);if(this._match(Z,_))return Z;J++}J=0}return-1};H_.prototype._match=function(_,T){if(this.length-_<T.length)return!1;for(let A=0;A<T.length;A++)if(this.get(_+A)!==T[A])return!1;return!0};(function(){let _={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let T in _)(function(A){if(_[A]===null)H_.prototype[A]=function(E,L){return this.slice(E,E+L)[A](0,L)};else H_.prototype[A]=function(E=0){return this.slice(E,E+_[A])[A](0)}})(T)})();H_.prototype._isBufferList=function(T){return T instanceof H_||H_.isBufferList(T)};H_.isBufferList=function(T){return T!=null&&T[aH]};oH.exports=H_});var sH=W((rf,RA)=>{var YE=n0().Duplex,VR=iH(),c4=rH();function i_(_){if(!(this instanceof i_))return new i_(_);if(typeof _==="function"){this._callback=_;let T=function(E){if(this._callback)this._callback(E),this._callback=null}.bind(this);this.on("pipe",function(E){E.on("error",T)}),this.on("unpipe",function(E){E.removeListener("error",T)}),_=null}c4._init.call(this,_),YE.call(this)}VR(i_,YE);Object.assign(i_.prototype,c4.prototype);i_.prototype._new=function(T){return new i_(T)};i_.prototype._write=function(T,A,E){if(this._appendBuffer(T),typeof E==="function")E()};i_.prototype._read=function(T){if(!this.length)return this.push(null);T=Math.min(T,this.length),this.push(this.slice(0,T)),this.consume(T)};i_.prototype.end=function(T){if(YE.prototype.end.call(this,T),this._callback)this._callback(null,this.slice()),this._callback=null};i_.prototype._destroy=function(T,A){this._bufs.length=0,this.length=0,A(T)};i_.prototype._isBufferList=function(T){return T instanceof i_||T instanceof c4||i_.isBufferList(T)};i_.isBufferList=c4.isBufferList;RA.exports=i_;RA.exports.BufferListStream=i_;RA.exports.BufferList=c4});var _2=W((sf,eH)=>{class tH{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}eH.exports=tH});var KE=W((tf,T2)=>{var x=tf,{Buffer:X1}=j("buffer");x.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};x.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0};x.requiredHeaderFlagsErrors={};for(let _ in x.requiredHeaderFlags){let T=x.requiredHeaderFlags[_];x.requiredHeaderFlagsErrors[_]="Invalid header flag bits, must be 0x"+T.toString(16)+" for "+x.types[_]+" packet"}x.codes={};for(let _ in x.types){let T=x.types[_];x.codes[T]=_}x.CMD_SHIFT=4;x.CMD_MASK=240;x.DUP_MASK=8;x.QOS_MASK=3;x.QOS_SHIFT=1;x.RETAIN_MASK=1;x.VARBYTEINT_MASK=127;x.VARBYTEINT_FIN_MASK=128;x.VARBYTEINT_MAX=268435455;x.SESSIONPRESENT_MASK=1;x.SESSIONPRESENT_HEADER=X1.from([x.SESSIONPRESENT_MASK]);x.CONNACK_HEADER=X1.from([x.codes.connack<<x.CMD_SHIFT]);x.USERNAME_MASK=128;x.PASSWORD_MASK=64;x.WILL_RETAIN_MASK=32;x.WILL_QOS_MASK=24;x.WILL_QOS_SHIFT=3;x.WILL_FLAG_MASK=4;x.CLEAN_SESSION_MASK=2;x.CONNECT_HEADER=X1.from([x.codes.connect<<x.CMD_SHIFT]);x.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11};x.propertiesCodes={};for(let _ in x.properties){let T=x.properties[_];x.propertiesCodes[T]=_}x.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function i0(_){return[0,1,2].map((T)=>{return[0,1].map((A)=>{return[0,1].map((E)=>{let L=X1.alloc(1);return L.writeUInt8(x.codes[_]<<x.CMD_SHIFT|(A?x.DUP_MASK:0)|T<<x.QOS_SHIFT|E,0,!0),L})})})}x.PUBLISH_HEADER=i0("publish");x.SUBSCRIBE_HEADER=i0("subscribe");x.SUBSCRIBE_OPTIONS_QOS_MASK=3;x.SUBSCRIBE_OPTIONS_NL_MASK=1;x.SUBSCRIBE_OPTIONS_NL_SHIFT=2;x.SUBSCRIBE_OPTIONS_RAP_MASK=1;x.SUBSCRIBE_OPTIONS_RAP_SHIFT=3;x.SUBSCRIBE_OPTIONS_RH_MASK=3;x.SUBSCRIBE_OPTIONS_RH_SHIFT=4;x.SUBSCRIBE_OPTIONS_RH=[0,16,32];x.SUBSCRIBE_OPTIONS_NL=4;x.SUBSCRIBE_OPTIONS_RAP=8;x.SUBSCRIBE_OPTIONS_QOS=[0,1,2];x.UNSUBSCRIBE_HEADER=i0("unsubscribe");x.ACKS={unsuback:i0("unsuback"),puback:i0("puback"),pubcomp:i0("pubcomp"),pubrel:i0("pubrel"),pubrec:i0("pubrec")};x.SUBACK_HEADER=X1.from([x.codes.suback<<x.CMD_SHIFT]);x.VERSION3=X1.from([3]);x.VERSION4=X1.from([4]);x.VERSION5=X1.from([5]);x.VERSION131=X1.from([131]);x.VERSION132=X1.from([132]);x.QOS=[0,1,2].map((_)=>{return X1.from([_])});x.EMPTY={pingreq:X1.from([x.codes.pingreq<<4,0]),pingresp:X1.from([x.codes.pingresp<<4,0]),disconnect:X1.from([x.codes.disconnect<<4,0])};x.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"};x.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"};x.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};x.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"};x.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};x.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}});var E2=W((ef,A2)=>{var T4=1000,A4=T4*60,E4=A4*60,FT=E4*24,zR=FT*7,FR=FT*365.25;A2.exports=function(_,T){T=T||{};var A=typeof _;if(A==="string"&&_.length>0)return CR(_);else if(A==="number"&&isFinite(_))return T.long?RR(_):OR(_);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(_))};function CR(_){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*FR;case"weeks":case"week":case"w":return A*zR;case"days":case"day":case"d":return A*FT;case"hours":case"hour":case"hrs":case"hr":case"h":return A*E4;case"minutes":case"minute":case"mins":case"min":case"m":return A*A4;case"seconds":case"second":case"secs":case"sec":case"s":return A*T4;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return}}function OR(_){var T=Math.abs(_);if(T>=FT)return Math.round(_/FT)+"d";if(T>=E4)return Math.round(_/E4)+"h";if(T>=A4)return Math.round(_/A4)+"m";if(T>=T4)return Math.round(_/T4)+"s";return _+"ms"}function RR(_){var T=Math.abs(_);if(T>=FT)return DA(_,T,FT,"day");if(T>=E4)return DA(_,T,E4,"hour");if(T>=A4)return DA(_,T,A4,"minute");if(T>=T4)return DA(_,T,T4,"second");return _+" ms"}function DA(_,T,A,E){var L=T>=A*1.5;return Math.round(_/A)+" "+E+(L?"s":"")}});var GE=W((_b,L2)=>{function DR(_){A.debug=A,A.default=A,A.coerce=Z,A.disable=X,A.enable=L,A.enabled=H,A.humanize=E2(),A.destroy=Y,Object.keys(_).forEach((K)=>{A[K]=_[K]}),A.names=[],A.skips=[],A.formatters={};function T(K){let G=0;for(let $=0;$<K.length;$++)G=(G<<5)-G+K.charCodeAt($),G|=0;return A.colors[Math.abs(G)%A.colors.length]}A.selectColor=T;function A(K){let G,$=null,U,V;function N(...z){if(!N.enabled)return;let Q=N,F=Number(new Date),R=F-(G||F);if(Q.diff=R,Q.prev=G,Q.curr=F,G=F,z[0]=A.coerce(z[0]),typeof z[0]!=="string")z.unshift("%O");let q=0;z[0]=z[0].replace(/%([a-zA-Z%])/g,(h,b)=>{if(h==="%%")return"%";q++;let l=A.formatters[b];if(typeof l==="function"){let c=z[q];h=l.call(Q,c),z.splice(q,1),q--}return h}),A.formatArgs.call(Q,z),(Q.log||A.log).apply(Q,z)}if(N.namespace=K,N.useColors=A.useColors(),N.color=A.selectColor(K),N.extend=E,N.destroy=A.destroy,Object.defineProperty(N,"enabled",{enumerable:!0,configurable:!1,get:()=>{if($!==null)return $;if(U!==A.namespaces)U=A.namespaces,V=A.enabled(K);return V},set:(z)=>{$=z}}),typeof A.init==="function")A.init(N);return N}function E(K,G){let $=A(this.namespace+(typeof G>"u"?":":G)+K);return $.log=this.log,$}function L(K){A.save(K),A.namespaces=K,A.names=[],A.skips=[];let G=(typeof K==="string"?K:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let $ of G)if($[0]==="-")A.skips.push($.slice(1));else A.names.push($)}function J(K,G){let $=0,U=0,V=-1,N=0;while($<K.length)if(U<G.length&&(G[U]===K[$]||G[U]==="*"))if(G[U]==="*")V=U,N=$,U++;else $++,U++;else if(V!==-1)U=V+1,N++,$=N;else return!1;while(U<G.length&&G[U]==="*")U++;return U===G.length}function X(){let K=[...A.names,...A.skips.map((G)=>"-"+G)].join(",");return A.enable(""),K}function H(K){for(let G of A.skips)if(J(K,G))return!1;for(let G of A.names)if(J(K,G))return!0;return!1}function Z(K){if(K instanceof Error)return K.stack||K.message;return K}function Y(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return A.enable(A.load()),A}L2.exports=DR});var X2=W((J2,BA)=>{J2.formatArgs=qR;J2.save=IR;J2.load=PR;J2.useColors=BR;J2.storage=jR();J2.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`.")}})();J2.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 BR(){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 qR(_){if(_[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+_[0]+(this.useColors?"%c ":" ")+"+"+BA.exports.humanize(this.diff),!this.useColors)return;let T="color: "+this.color;_.splice(1,0,T,"color: inherit");let A=0,E=0;_[0].replace(/%[a-zA-Z%]/g,(L)=>{if(L==="%%")return;if(A++,L==="%c")E=A}),_.splice(E,0,T)}J2.log=console.debug||console.log||(()=>{});function IR(_){try{if(_)J2.storage.setItem("debug",_);else J2.storage.removeItem("debug")}catch(T){}}function PR(){let _;try{_=J2.storage.getItem("debug")||J2.storage.getItem("DEBUG")}catch(T){}if(!_&&typeof process<"u"&&"env"in process)_=process.env.DEBUG;return _}function jR(){try{return localStorage}catch(_){}}BA.exports=GE()(J2);var{formatters:xR}=BA.exports;xR.j=function(_){try{return JSON.stringify(_)}catch(T){return"[UnexpectedJSONParseError]: "+T.message}}});var K2=W((Z2,IA)=>{var bR=j("tty"),qA=j("util");Z2.init=lR;Z2.log=dR;Z2.formatArgs=mR;Z2.save=cR;Z2.load=pR;Z2.useColors=gR;Z2.destroy=qA.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Z2.colors=[6,2,3,4,5,1];try{let _=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(_&&(_.stderr||_).level>=2)Z2.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(_){}Z2.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 gR(){return"colors"in Z2.inspectOpts?Boolean(Z2.inspectOpts.colors):bR.isatty(process.stderr.fd)}function mR(_){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 ON=Object.create;var{getPrototypeOf:RN,defineProperty:N9,getOwnPropertyNames:DN}=Object;var BN=Object.prototype.hasOwnProperty;var q_=(_,T,A)=>{A=_!=null?ON(RN(_)):{};let E=T||!_||!_.__esModule?N9(A,"default",{value:_,enumerable:!0}):A;for(let L of DN(_))if(!BN.call(E,L))N9(E,L,{get:()=>_[L],enumerable:!0});return E};var W=(_,T)=>()=>(T||_((T={exports:{}}).exports,T),T.exports);var I=import.meta.require;var q9=W((Mk,B9)=>{B9.exports=bN;var fN=Object.prototype.hasOwnProperty;function bN(){var _={};for(var T=0;T<arguments.length;T++){var A=arguments[T];for(var E in A)if(fN.call(A,E))_[E]=A[E]}return _}});var k8=W((Vk,I9)=>{function gN(_){var T=new _,A=T;function E(){var J=T;if(J.next)T=J.next;else T=new _,A=T;return J.next=null,J}function L(J){A.next=J,A=J}return{get:E,release:L}}I9.exports=gN});var f5=W((zk,j9)=>{var mN=q9(),P9=k8(),uN={released:D0,results:!0};function dN(_){_=mN(uN,_);var T=_.released,A=P9(_.results?lN:cN),E=P9(pN),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 cN(){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 pN(){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 lN(){this._count=-1,this._callback=D0,this._results=null,this._err=null,this._callThat=null,this._release=D0,this.next=null;var _=this,T=0;this.release=function(A,E,L){if(_._err=_._err||A,E>=0)_._results[E]=L;var J=_._callback;if(++T===_._count||_._count===0){if(_._callThat)J.call(_._callThat,_._err,_._results);else J(_._err,_._results);_._callback=D0,_._results=null,_._err=null,_._callThat=null,T=0,_._release(_)}}}function D0(){}j9.exports=dN});var S9=W((Fk,w9)=>{var nN={results:!0};function iN(_){_=Object.assign({},nN,_);var T,A;if(_.results)T=rN,A=sN;else T=aN,A=oN;return E;function E(L,J,X,H){if(H=(H||tN).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 aN(_,T,A){var E=0,L=T.length;J();function J(){if(E<L)f8(_,T[E++],J);else A()}}function oN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=x9;else J=f8;X();function X(){if(E<L)J(_[E++],T,X);else A()}}function rN(_,T,A){var E=0,L=T.length,J=Array(L);X(null,null);function X(H,Z){if(H){A(H);return}if(E>0)J[E-1]=Z;if(E<L)f8(_,T[E++],X);else A(null,J)}}function sN(_,T,A){var E=0,L=_.length,J;if(_[0].length===1)J=x9;else J=f8;var X=Array(L);H(null,null);function H(Z,Y){if(Z){A(Z);return}if(E>0)X[E-1]=Y;if(E<L)J(_[E++],T,H);else A(null,X)}}function x9(_,T,A){_(A)}function f8(_,T,A){_(T,A)}function tN(){}w9.exports=iN});var h9=W((y9)=>{Object.defineProperty(y9,"__esModule",{value:!0});y9.default=void 0;var Ck=y9.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var b9=W((k9)=>{Object.defineProperty(k9,"__esModule",{value:!0});k9.default=void 0;var Rk=k9.default="00000000-0000-0000-0000-000000000000"});var u9=W((g9)=>{Object.defineProperty(g9,"__esModule",{value:!0});g9.default=void 0;var Bk=g9.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var P4=W((d9)=>{Object.defineProperty(d9,"__esModule",{value:!0});d9.default=void 0;var eN=_Q(u9());function _Q(_){return _&&_.__esModule?_:{default:_}}function TQ(_){return typeof _==="string"&&eN.default.test(_)}var Ik=d9.default=TQ});var j4=W((p9)=>{Object.defineProperty(p9,"__esModule",{value:!0});p9.default=void 0;var AQ=EQ(P4());function EQ(_){return _&&_.__esModule?_:{default:_}}function LQ(_){if(!(0,AQ.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 jk=p9.default=LQ});var B0=W((i9)=>{Object.defineProperty(i9,"__esModule",{value:!0});i9.default=void 0;i9.unsafeStringify=n9;var JQ=XQ(P4());function XQ(_){return _&&_.__esModule?_:{default:_}}var b_=[];for(let _=0;_<256;++_)b_.push((_+256).toString(16).slice(1));function n9(_,T=0){return(b_[_[T+0]]+b_[_[T+1]]+b_[_[T+2]]+b_[_[T+3]]+"-"+b_[_[T+4]]+b_[_[T+5]]+"-"+b_[_[T+6]]+b_[_[T+7]]+"-"+b_[_[T+8]]+b_[_[T+9]]+"-"+b_[_[T+10]]+b_[_[T+11]]+b_[_[T+12]]+b_[_[T+13]]+b_[_[T+14]]+b_[_[T+15]]).toLowerCase()}function HQ(_,T=0){let A=n9(_,T);if(!(0,JQ.default)(A))throw TypeError("Stringified UUID is invalid");return A}var wk=i9.default=HQ});var m8=W((o9)=>{Object.defineProperty(o9,"__esModule",{value:!0});o9.default=$Q;var YQ=KQ(I("crypto"));function KQ(_){return _&&_.__esModule?_:{default:_}}var g8=new Uint8Array(256),b8=g8.length;function $Q(){if(b8>g8.length-16)YQ.default.randomFillSync(g8),b8=0;return g8.slice(b8,b8+=16)}});var u5=W((r9)=>{Object.defineProperty(r9,"__esModule",{value:!0});r9.default=void 0;var UQ=NQ(m8()),WQ=B0();function NQ(_){return _&&_.__esModule?_:{default:_}}var b5,u8,g5=0,m5=0;function QQ(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let{node:J,clockseq:X}=_;if(!_._v6){if(!J)J=b5;if(X==null)X=u8}if(J==null||X==null){let G=_.random||(_.rng||UQ.default)();if(J==null){if(J=[G[0],G[1],G[2],G[3],G[4],G[5]],!b5&&!_._v6)J[0]|=1,b5=J}if(X==null){if(X=(G[6]<<8|G[7])&16383,u8===void 0&&!_._v6)u8=X}}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:m5+1,Y=H-g5+(Z-m5)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>g5)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");g5=H,m5=Z,u8=X,H+=12219292800000;let K=((H&268435455)*1e4+Z)%4294967296;L[E++]=K>>>24&255,L[E++]=K>>>16&255,L[E++]=K>>>8&255,L[E++]=K&255;let $=H/4294967296*1e4&268435455;L[E++]=$>>>8&255,L[E++]=$&255,L[E++]=$>>>24&15|16,L[E++]=$>>>16&255,L[E++]=X>>>8|128,L[E++]=X&255;for(let G=0;G<6;++G)L[E+G]=J[G];return T||(0,WQ.unsafeStringify)(L)}var vk=r9.default=QQ});var d5=W((t9)=>{Object.defineProperty(t9,"__esModule",{value:!0});t9.default=FQ;var MQ=zQ(j4()),VQ=B0();function zQ(_){return _&&_.__esModule?_:{default:_}}function FQ(_){let T=typeof _==="string"?(0,MQ.default)(_):_,A=CQ(T);return typeof _==="string"?(0,VQ.unsafeStringify)(A):A}function CQ(_,T=!1){return Uint8Array.of((_[6]&15)<<4|_[7]>>4&15,(_[7]&15)<<4|(_[4]&240)>>4,(_[4]&15)<<4|(_[5]&240)>>4,(_[5]&15)<<4|(_[0]&240)>>4,(_[0]&15)<<4|(_[1]&240)>>4,(_[1]&15)<<4|(_[2]&240)>>4,96|_[2]&15,_[3],_[8],_[9],_[10],_[11],_[12],_[13],_[14],_[15])}});var c5=W((e9)=>{Object.defineProperty(e9,"__esModule",{value:!0});e9.URL=e9.DNS=void 0;e9.default=jQ;var RQ=B0(),DQ=BQ(j4());function BQ(_){return _&&_.__esModule?_:{default:_}}function qQ(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var IQ=e9.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",PQ=e9.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function jQ(_,T,A){function E(L,J,X,H){var Z;if(typeof L==="string")L=qQ(L);if(typeof J==="string")J=(0,DQ.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,RQ.unsafeStringify)(Y)}try{E.name=_}catch(L){}return E.DNS=IQ,E.URL=PQ,E}});var E7=W((T7)=>{Object.defineProperty(T7,"__esModule",{value:!0});T7.default=void 0;var SQ=yQ(I("crypto"));function yQ(_){return _&&_.__esModule?_:{default:_}}function vQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return SQ.default.createHash("md5").update(_).digest()}var bk=T7.default=vQ});var H7=W((J7)=>{Object.defineProperty(J7,"__esModule",{value:!0});J7.default=void 0;var hQ=L7(c5()),kQ=L7(E7());function L7(_){return _&&_.__esModule?_:{default:_}}var fQ=(0,hQ.default)("v3",48,kQ.default),mk=J7.default=fQ});var K7=W((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});Z7.default=void 0;var bQ=gQ(I("crypto"));function gQ(_){return _&&_.__esModule?_:{default:_}}var dk=Z7.default={randomUUID:bQ.default.randomUUID}});var N7=W((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});U7.default=void 0;var $7=G7(K7()),mQ=G7(m8()),uQ=B0();function G7(_){return _&&_.__esModule?_:{default:_}}function dQ(_,T,A){if($7.default.randomUUID&&!T&&!_)return $7.default.randomUUID();_=_||{};let E=_.random||(_.rng||mQ.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,uQ.unsafeStringify)(E)}var pk=U7.default=dQ});var V7=W((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});Q7.default=void 0;var cQ=pQ(I("crypto"));function pQ(_){return _&&_.__esModule?_:{default:_}}function lQ(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return cQ.default.createHash("sha1").update(_).digest()}var nk=Q7.default=lQ});var O7=W((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});F7.default=void 0;var nQ=z7(c5()),iQ=z7(V7());function z7(_){return _&&_.__esModule?_:{default:_}}var aQ=(0,nQ.default)("v5",80,iQ.default),ak=F7.default=aQ});var B7=W((D7)=>{Object.defineProperty(D7,"__esModule",{value:!0});D7.default=tQ;var oQ=B0(),rQ=R7(u5()),sQ=R7(d5());function R7(_){return _&&_.__esModule?_:{default:_}}function tQ(_={},T,A=0){let E=(0,rQ.default)({..._,_v6:!0},new Uint8Array(16));if(E=(0,sQ.default)(E),T){for(let L=0;L<16;L++)T[A+L]=E[L];return T}return(0,oQ.unsafeStringify)(E)}});var I7=W((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});q7.default=EM;var _M=AM(j4()),TM=B0();function AM(_){return _&&_.__esModule?_:{default:_}}function EM(_){let T=typeof _==="string"?(0,_M.default)(_):_,A=LM(T);return typeof _==="string"?(0,TM.unsafeStringify)(A):A}function LM(_){return Uint8Array.of((_[3]&15)<<4|_[4]>>4&15,(_[4]&15)<<4|(_[5]&240)>>4,(_[5]&15)<<4|_[6]&15,_[7],(_[1]&15)<<4|(_[2]&240)>>4,(_[2]&15)<<4|(_[3]&240)>>4,16|(_[0]&240)>>4,(_[0]&15)<<4|(_[1]&240)>>4,_[8],_[9],_[10],_[11],_[12],_[13],_[14],_[15])}});var S7=W((x7)=>{Object.defineProperty(x7,"__esModule",{value:!0});x7.default=void 0;var XM=ZM(m8()),HM=B0();function ZM(_){return _&&_.__esModule?_:{default:_}}var P7=null,j7=null,k1=0;function YM(_,T,A){_=_||{};let E=T&&A||0,L=T||new Uint8Array(16),J=_.random||(_.rng||XM.default)(),X=_.msecs!==void 0?_.msecs:Date.now(),H=_.seq!==void 0?_.seq:null,Z=j7,Y=P7;if(X>k1&&_.msecs===void 0){if(k1=X,H!==null)Z=null,Y=null}if(H!==null){if(H>2147483647)H=2147483647;Z=H>>>19&4095,Y=H&524287}if(Z===null||Y===null)Z=J[6]&127,Z=Z<<8|J[7],Y=J[8]&63,Y=Y<<8|J[9],Y=Y<<5|J[10]>>>3;if(X+1e4>k1&&H===null){if(++Y>524287){if(Y=0,++Z>4095)Z=0,k1++}}else k1=X;return j7=Z,P7=Y,L[E++]=k1/1099511627776&255,L[E++]=k1/4294967296&255,L[E++]=k1/16777216&255,L[E++]=k1/65536&255,L[E++]=k1/256&255,L[E++]=k1&255,L[E++]=Z>>>4&15|112,L[E++]=Z&255,L[E++]=Y>>>13&63|128,L[E++]=Y>>>5&255,L[E++]=Y<<3&255|J[10]&7,L[E++]=J[11],L[E++]=J[12],L[E++]=J[13],L[E++]=J[14],L[E++]=J[15],T||(0,HM.unsafeStringify)(L)}var tk=x7.default=YM});var h7=W((y7)=>{Object.defineProperty(y7,"__esModule",{value:!0});y7.default=void 0;var KM=$M(P4());function $M(_){return _&&_.__esModule?_:{default:_}}function GM(_){if(!(0,KM.default)(_))throw TypeError("Invalid UUID");return parseInt(_.slice(14,15),16)}var _f=y7.default=GM});var k7=W((p_)=>{Object.defineProperty(p_,"__esModule",{value:!0});Object.defineProperty(p_,"MAX",{enumerable:!0,get:function(){return UM.default}});Object.defineProperty(p_,"NIL",{enumerable:!0,get:function(){return WM.default}});Object.defineProperty(p_,"parse",{enumerable:!0,get:function(){return NM.default}});Object.defineProperty(p_,"stringify",{enumerable:!0,get:function(){return QM.default}});Object.defineProperty(p_,"v1",{enumerable:!0,get:function(){return MM.default}});Object.defineProperty(p_,"v1ToV6",{enumerable:!0,get:function(){return VM.default}});Object.defineProperty(p_,"v3",{enumerable:!0,get:function(){return zM.default}});Object.defineProperty(p_,"v4",{enumerable:!0,get:function(){return FM.default}});Object.defineProperty(p_,"v5",{enumerable:!0,get:function(){return CM.default}});Object.defineProperty(p_,"v6",{enumerable:!0,get:function(){return OM.default}});Object.defineProperty(p_,"v6ToV1",{enumerable:!0,get:function(){return RM.default}});Object.defineProperty(p_,"v7",{enumerable:!0,get:function(){return DM.default}});Object.defineProperty(p_,"validate",{enumerable:!0,get:function(){return BM.default}});Object.defineProperty(p_,"version",{enumerable:!0,get:function(){return qM.default}});var UM=J1(h9()),WM=J1(b9()),NM=J1(j4()),QM=J1(B0()),MM=J1(u5()),VM=J1(d5()),zM=J1(H7()),FM=J1(N7()),CM=J1(O7()),OM=J1(B7()),RM=J1(I7()),DM=J1(S7()),BM=J1(P4()),qM=J1(h7());function J1(_){return _&&_.__esModule?_:{default:_}}});var uT=W((Ef,f7)=>{function IM(_,T){if(Object.prototype.hasOwnProperty.call(_,"clientId"))this.clientId=_.clientId;if(Object.prototype.hasOwnProperty.call(_,"nl"))this.nl=_.nl;if(this.cmd=_.cmd||"publish",this.brokerId=_.brokerId||T&&T.id,this.brokerCounter=_.brokerCounter||(T?++T.counter:0),this.topic=_.topic,this.payload=_.payload||Buffer.alloc(0),this.qos=_.qos||0,this.retain=_.retain||!1,this.dup=_.dup||!1,this.qos>0||this.cmd!=="publish")this.messageId=void 0}f7.exports=IM});var p5=W((Lf,b7)=>{var f1=I("util");b7.exports=function(_,T){class A extends _{constructor(E){super(E);this.addP=f1.promisify(this.add_async),this.removeP=f1.promisify(this.remove_async),this.matchP=f1.promisify(this.match_async),this.testP=f1.promisify(this.test_async),this.clearP=f1.promisify(this.clear_async),this._get_visitorP=f1.promisify(this.get_visitor_async),this._visit_nextP=f1.promisify(this.visit_next_async),this._get_restorerP=f1.promisify(this.get_restorer_async),this._restore_nextP=f1.promisify(this.restore_next_async),this._match_iterP=f1.promisify(this.match_iter_async),this._match_nextP=f1.promisify(this.match_next_async)}*visit(){let E=this.get_visitor();while(!0){let L=this.visit_next(E);if(L===void 0)break;yield L}}async*visitP(){let E=await this._get_visitorP();while(!0){let L=await this._visit_nextP(E);if(L===void 0)break;yield L}}*match_iter(E,L){let J=super.match_iter(E,L);while(!0){let X=this.match_next(J);if(X===void 0)break;yield X.value}}async*match_iterP(E,L){let J=await this._match_iterP(E,L);while(!0){let X=await this._match_nextP(J);if(X===void 0)break;yield X.value}}get_trie(){let E=new T(this.options),L=E.get_restorer();for(let J of this.visit())L(J);return E.get_trie()}get_restorer(E){let L=super.get_restorer(E);return(J)=>{super.restore_next(L,J)}}async get_restorerP(E){let L=await this._get_restorerP(E);return async(J)=>{await this._restore_nextP(L,J)}}}return A.is_native=!0,A.nonNative=T,A}});var i5=W((m7)=>{var d8=I("util");function L_(_){if(_=_||{},this._separator=_.separator||".",this._wildcard_one=_.wildcard_one||"*",this._wildcard_some=_.wildcard_some||"#",this._max_words=_.max_words||100,this._max_wildcard_somes=_.max_wildcard_somes||3,this._match_empty_levels=_.match_empty_levels,this._trie=new Map,_.cache_adds instanceof Map)this._shortcuts=_.cache_adds;else if(_.cache_adds)this._shortcuts=new Map;if(_.cache_splits>0)this._cache_splits=_.cache_splits,this._split_cache=new Map}L_.prototype._initial_value=function(_){return[_]};L_.prototype._add_value=function(_,T){_[_.length]=T};L_.prototype._add_values=function(_,T){var A,E=_.length,L=T.length;for(A=0;A<L;A+=1)_[E+A]=T[A]};L_.prototype._iter_values=function(_,T){return _[Symbol.iterator](T)};L_.prototype._remove_value=function(_,T){if(T===void 0)return!0;var A=_.lastIndexOf(T);if(A>=0)_.splice(A,1);return _.length===0};L_.prototype._add=function(_,T,A,E){var L,J;if(T===A.length){if(L=E.get(this._separator),L)this._add_value(L,_);else L=this._initial_value(_),E.set(this._separator,L);return L}if(J=A[T],L=E.get(J),!L)L=new Map,E.set(J,L);return this._add(_,T+1,A,L)};L_.prototype._remove=function(_,T,A,E){var L,J,X;if(T===A.length){if(L=E.get(this._separator),L&&this._remove_value(L,_))return E.delete(this._separator),!0;return!1}if(J=A[T],L=E.get(J),!L)return!1;if(X=this._remove(_,T+1,A,L),L.size===0)E.delete(J);return X};L_.prototype._match_some=function(_,T,A,E,L){var J,X;for(X of E.keys())if(X!==this._separator){for(J=T;J<A.length;J+=1)_=this._match(_,J,A,E,L);break}return _};L_.prototype._match=function(_,T,A,E,L){var J,X;if(X=E.get(this._wildcard_some),X)_=this._match_some(_,T,A,X,L),_=this._match(_,A.length,A,X,L);if(T===A.length){if(X=E.get(this._separator),X)if(_.dest)this._add_values(_.dest,_.source,L),this._add_values(_.dest,X,L),_=_.dest;else if(_.source)_.dest=_.source,_.source=X;else this._add_values(_,X,L)}else{if(J=A[T],J!==this._wildcard_one&&J!==this._wildcard_some){if(X=E.get(J),X)_=this._match(_,T+1,A,X,L)}if(J||this._match_empty_levels){if(X=E.get(this._wildcard_one),X)_=this._match(_,T+1,A,X,L)}}return _};L_.prototype._match2=function(_,T,A){var E=this._match({source:_},0,this._split(T,!1),this._trie,A);return E.source||E};L_.prototype._test_some=function(_,T,A,E){var L,J;for(J of E.keys())if(J!==this._separator){for(L=T;L<A.length;L+=1)if(this._test(_,L,A,E))return!0;break}return!1};L_.prototype._test=function(_,T,A,E){var L,J;if(J=E.get(this._wildcard_some),J){if(this._test_some(_,T,A,J)||this._test(_,A.length,A,J))return!0}if(T===A.length){if(J=E.get(this._separator),J&&this.test_values(J,_))return!0}else{if(L=A[T],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=E.get(L),J&&this._test(_,T+1,A,J))return!0}if(L||this._match_empty_levels){if(J=E.get(this._wildcard_one),J&&this._test(_,T+1,A,J))return!0}}return!1};L_.prototype._match_some_iter=function*(_,T,A,E){var L,J;for(J of A.keys())if(J!==this._separator){for(L=_;L<T.length;L+=1)yield*this._match_iter(L,T,A,E);break}};L_.prototype._match_iter=function*(_,T,A,E){var L,J;if(J=A.get(this._wildcard_some),J)yield*this._match_some_iter(_,T,J,E),yield*this._match_iter(T.length,T,J,E);if(_===T.length){if(J=A.get(this._separator),J)yield*this._iter_values(J,E)}else{if(L=T[_],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=A.get(L),J)yield*this._match_iter(_+1,T,J,E)}if(L||this._match_empty_levels){if(J=A.get(this._wildcard_one),J)yield*this._match_iter(_+1,T,J,E)}}};L_.prototype._split_words=function(_){let T=_.split(this._separator);if(T.length>this._max_words)throw Error("too many words");return T};L_.prototype._split=function(_,T){let A;if(this._split_cache){if(A=this._split_cache.get(_),A===void 0){if(A=this._split_words(_),this._split_cache.set(_,A),this._split_cache.size>this._cache_splits)for(let E of this._split_cache.keys()){this._split_cache.delete(E);break}}}else A=this._split_words(_);if(T&&A.reduce((E,L)=>E+(L===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return A};L_.prototype.add=function(_,T){var A=this._shortcuts&&this._shortcuts.get(_);if(A)this._add_value(A,T);else if(A=this._add(T,0,this._split(_,!0),this._trie),this._shortcuts)this._shortcuts.set(_,A);return this};L_.prototype.remove=function(_,T){if(this._remove(T,0,this._split(_,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(_);return this};L_.prototype.match=function(_,T){return this._match2([],_,T)};L_.prototype.match_iter=function(_,T){return this._match_iter(0,this._split(_,!1),this._trie,T)};L_.prototype.test=function(_,T){return this._test(T,0,this._split(_,!1),this._trie)};L_.prototype.test_values=function(_,T){return _.indexOf(T)>=0};L_.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};L_.prototype.get_trie=function(){return this._trie};L_.prototype.visit=function*(){let _=[],T=this._trie.entries(),A=0;while(!0){if(A===0)yield{type:"start_entries"};let E=T.next();if(E.done){yield{type:"end_entries"};let X=_.pop();if(X===void 0)return;[T,A]=X;continue}let[L,J]=E.value;if(yield{type:"entry",key:L},++A,L===this._separator){if(yield{type:"start_values"},J[Symbol.iterator])for(let X of J)yield{type:"value",value:X};else yield{type:"value",value:J};yield{type:"end_values"};continue}_.push([T,A]),T=J.entries(),A=0}};L_.prototype.get_restorer=function(_){_=_||{};let T=[],A=this._trie,E="";return(L)=>{switch(L.type){case"entry":if(A=A||new Map,T.push([A,L.key,E]),A=A.get(L.key),_.cache_adds){if(E)E+=this._separator;E+=L.key}break;case"value":if(A)this._add_value(A,L.value);else A=this._initial_value(L.value);break;case"end_entries":if(A&&A.size===0)A=void 0;case"end_values":let J=T.pop();if(J===void 0)A=void 0,E="";else{let[X,H,Z]=J;if(A){if(_.cache_adds&&this._shortcuts&&L.type==="end_values")this._shortcuts.set(Z,A);X.set(H,A)}A=X,E=Z}break}}};function V1(_){L_.call(this,_)}d8.inherits(V1,L_);V1.prototype._initial_value=function(_){return new Set().add(_)};V1.prototype._add_value=function(_,T){_.add(T)};V1.prototype._add_values=function(_,T){T.forEach(function(A){_.add(A)})};V1.prototype._remove_value=function(_,T){if(T===void 0)return!0;return _.delete(T),_.size===0};V1.prototype.test_values=function(_,T){return _.has(T)};V1.prototype.match=function(_,T){return this._match2(new Set,_,T)};function s1(_){L_.call(this,_)}d8.inherits(s1,L_);s1.prototype._initial_value=function(){return!0};s1.prototype._add_value=function(){};s1.prototype._remove_value=function(){return!0};s1.prototype._iter_values=function*(){yield!0};s1.prototype.test_values=function(){return!0};s1.prototype.match=function(_,T){return this.test(_,T)};var c8=I("stream");function l5(_){c8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}d8.inherits(l5,c8.Readable);l5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function n5(_){c8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}d8.inherits(n5,c8.Writable);n5.prototype._write=function(_,T,A){this._restorer(_),A()};var g7=null;function PM(_){if(_!==g7){let T=p5();L_.nativeString=T(_.QlobberString,L_),L_.nativeNumber=T(_.QlobberNumber,L_),V1.nativeString=T(_.QlobberDedupString,V1),V1.nativeNumber=T(_.QlobberDedupNumber,V1),s1.native=T(_.QlobberTrue,s1),g7=_}return m7}m7.Qlobber=L_;m7.QlobberDedup=V1;m7.QlobberTrue=s1;m7.VisitorStream=l5;m7.RestorerStream=n5;m7.set_native=PM});var u7=W((Xf,o5)=>{var hM=I("util"),kM=i5(),a5=kM.Qlobber;function z1(_){a5.call(this,_),this.subscriptionsCount=0}hM.inherits(z1,a5);z1.prototype._initial_value=function(_){this.subscriptionsCount+=1;let T={topic:_.topic,clientMap:new Map().set(_.clientId,{qos:_.qos,rh:_.rh,rap:_.rap,nl:_.nl})};return T[Symbol.iterator]=function*(A){if(A===void 0)for(let[E,L]of T.clientMap)yield{topic:T.topic,clientId:E,...L};else if(T.topic===A)for(let[E,L]of T.clientMap)yield{clientId:E,...L}},T};z1.prototype._add_value=function(_,T){var A=_.clientMap,E=A.size;if(A.set(T.clientId,{qos:T.qos,rh:T.rh,rap:T.rap,nl:T.nl}),A.size>E)this.subscriptionsCount+=1};z1.prototype._add_values=function(_,T,A){if(A===void 0)for(let[E,L]of T.clientMap)_.push({clientId:E,topic:T.topic,...L});else if(T.topic===A)for(let[E,L]of T.clientMap)_.push({clientId:E,...L})};z1.prototype._remove_value=function(_,T){var A=_.clientMap,E=A.size;A.delete(T.clientId);var L=A.size;if(L<E)this.subscriptionsCount-=1;return L===0};z1.prototype.test_values=function(_,T){var A=_.clientMap;return _.topic===T.topic&&A.size===1&&A.has(T.clientId)};z1.prototype.match=function(_,T){return this._match([],0,_.split(this._separator),this._trie,T)};z1.prototype.clear=function(){return this.subscriptionsCount=0,a5.prototype.clear.call(this)};z1.set_native=function(_){let T=p5();return z1.native=T(_.QlobberSub,z1),o5.exports};o5.exports=z1});var l7=W((Hf,s5)=>{var{Readable:x4}=I("stream"),fM=u7(),{QlobberTrue:bM}=i5(),r5=uT(),c7={wildcard_one:"+",wildcard_some:"#",separator:"/"};function*gM(_){for(let T of _)yield*T}function*d7(_,T){let A=new bM(c7);A.add(T);for(let[E,L]of _)if(A.test(E))yield L}function*mM(_,T){for(let A of _.values())if(!T[A.brokerId])yield A}function*uM(_,T){for(let[A,E]of _)if(E.has(T))yield A}class p7{#J;#L;#Y;#K;#N;#z;#A;constructor(){this.#J=new Map,this.#L=new Map,this.#Y=new Map,this.#K=new Map,this.#N=new Map,this.#z=0,this.#A=new fM(c7)}storeRetained(_,T){let A=Object.assign({},_);if(A.payload.length===0)this.#J.delete(A.topic);else this.#J.set(A.topic,A);T(null)}createRetainedStreamCombi(_){let T=_.map((A)=>{return d7(this.#J,A)});return x4.from(gM(T))}createRetainedStream(_){return x4.from(d7(this.#J,_))}addSubscriptions(_,T,A){let E=this.#L.get(_.id),L=this.#A;if(!E)E=new Map,this.#L.set(_.id,E),this.#z++;for(let J of T){let X=E.get(J.topic);if(J.qos>0)L.add(J.topic,{clientId:_.id,topic:J.topic,qos:J.qos,rh:J.rh,rap:J.rap,nl:J.nl});else if(X?.qos>0)L.remove(J.topic,{clientId:_.id,topic:J.topic});E.set(J.topic,{qos:J.qos,rh:J.rh,rap:J.rap,nl:J.nl})}A(null,_)}removeSubscriptions(_,T,A){let E=this.#L.get(_.id),L=this.#A;if(E){for(let J of T){let X=E.get(J);if(X!==void 0){if(X.qos>0)L.remove(J,{clientId:_.id,topic:J});E.delete(J)}}if(E.size===0)this.#z--,this.#L.delete(_.id)}A(null,_)}subscriptionsByClient(_,T){let A=null,E=this.#L.get(_.id);if(E){A=[];for(let[L,J]of E)A.push({topic:L,...J})}T(null,A,_)}countOffline(_){return _(null,this.#A.subscriptionsCount,this.#z)}subscriptionsByTopic(_,T){T(null,this.#A.match(_))}cleanSubscriptions(_,T){let A=this.#A,E=this.#L.get(_.id);if(E){for(let[L,J]of E)if(J.qos>0)A.remove(L,{clientId:_.id,topic:L});this.#z--,this.#L.delete(_.id)}T(null,_)}#W(_,T){let A=_.clientId,E=ZT(this.#Y,A,[],!0);E[E.length]=new r5(T)}outgoingEnqueue(_,T,A){this.#W(_,T),process.nextTick(A)}outgoingEnqueueCombi(_,T,A){for(let E=0;E<_.length;E++)this.#W(_[E],T);process.nextTick(A)}outgoingUpdate(_,T,A){let E=ZT(this.#Y,_.id,[],!0),L;for(let J=0;J<E.length;J++)if(L=E[J],L.brokerId===T.brokerId){if(L.brokerCounter===T.brokerCounter)return L.messageId=T.messageId,A(null,_,T)}else if(L.messageId===T.messageId)return E[J]=T,A(null,_,T);A(Error("no such packet"),_,T)}outgoingClearMessageId(_,T,A){let E=ZT(this.#Y,_.id,[],!0),L;for(let J=0;J<E.length;J++)if(L=E[J],L.messageId===T.messageId)return E.splice(J,1),A(null,L);A()}outgoingStream(_){let T=[].concat(ZT(this.#Y,_.id,[]));return x4.from(T)}incomingStorePacket(_,T,A){let E=_.id,L=ZT(this.#K,E,{},!0);L[T.messageId]=new r5(T),L[T.messageId].messageId=T.messageId,A(null)}incomingGetPacket(_,T,A){let E=_.id,L=ZT(this.#K,E,{}),J=null;if(this.#K.set(E,L),!L[T.messageId])J=Error("no such packet");A(J,L[T.messageId])}incomingDelPacket(_,T,A){let E=_.id,L=ZT(this.#K,E,{}),J=L[T.messageId],X=null;if(!J)X=Error("no such packet");else delete L[T.messageId];A(X)}putWill(_,T,A){T.brokerId=this.broker.id,T.clientId=_.id,this.#N.set(_.id,T),A(null,_)}getWill(_,T){T(null,this.#N.get(_.id),_)}delWill(_,T){let A=this.#N.get(_.id);this.#N.delete(_.id),T(null,A,_)}streamWill(_={}){return x4.from(mM(this.#N,_))}getClientList(_){return x4.from(uM(this.#L,_))}destroy(_){if(this.#J=null,_)_(null)}}function ZT(_,T,A,E=!1){let L=_.get(T);if(L===void 0&&E)_.set(T,A);return L||A}s5.exports=()=>{return new p7};s5.exports.Packet=r5});var i7=W((Zf,n7)=>{var b1=I("util");n7.exports=function(_,T){class A extends _{constructor(E){super(E);this.addP=b1.promisify(this.add_async),this.removeP=b1.promisify(this.remove_async),this.matchP=b1.promisify(this.match_async),this.testP=b1.promisify(this.test_async),this.clearP=b1.promisify(this.clear_async),this._get_visitorP=b1.promisify(this.get_visitor_async),this._visit_nextP=b1.promisify(this.visit_next_async),this._get_restorerP=b1.promisify(this.get_restorer_async),this._restore_nextP=b1.promisify(this.restore_next_async),this._match_iterP=b1.promisify(this.match_iter_async),this._match_nextP=b1.promisify(this.match_next_async)}*visit(){let E=this.get_visitor();while(!0){let L=this.visit_next(E);if(L===void 0)break;yield L}}async*visitP(){let E=await this._get_visitorP();while(!0){let L=await this._visit_nextP(E);if(L===void 0)break;yield L}}*match_iter(E,L){let J=super.match_iter(E,L);while(!0){let X=this.match_next(J);if(X===void 0)break;yield X.value}}async*match_iterP(E,L){let J=await this._match_iterP(E,L);while(!0){let X=await this._match_nextP(J);if(X===void 0)break;yield X.value}}get_trie(){let E=new T(this.options),L=E.get_restorer();for(let J of this.visit())L(J);return E.get_trie()}get_restorer(E){let L=super.get_restorer(E);return(J)=>{super.restore_next(L,J)}}async get_restorerP(E){let L=await this._get_restorerP(E);return async(J)=>{await this._restore_nextP(L,J)}}}return A.is_native=!0,A.nonNative=T,A}});var r7=W((o7)=>{var p8=I("util");function J_(_){if(_=_||{},this._separator=_.separator||".",this._wildcard_one=_.wildcard_one||"*",this._wildcard_some=_.wildcard_some||"#",this._max_words=_.max_words||100,this._max_wildcard_somes=_.max_wildcard_somes||3,this._match_empty_levels=_.match_empty_levels,this._trie=new Map,_.cache_adds instanceof Map)this._shortcuts=_.cache_adds;else if(_.cache_adds)this._shortcuts=new Map;if(_.cache_splits>0)this._cache_splits=_.cache_splits,this._split_cache=new Map}J_.prototype._initial_value=function(_){return[_]};J_.prototype._add_value=function(_,T){_[_.length]=T};J_.prototype._add_values=function(_,T){var A,E=_.length,L=T.length;for(A=0;A<L;A+=1)_[E+A]=T[A]};J_.prototype._iter_values=function(_,T){return _[Symbol.iterator](T)};J_.prototype._remove_value=function(_,T){if(T===void 0)return!0;var A=_.lastIndexOf(T);if(A>=0)_.splice(A,1);return _.length===0};J_.prototype._add=function(_,T,A,E){var L,J;if(T===A.length){if(L=E.get(this._separator),L)this._add_value(L,_);else L=this._initial_value(_),E.set(this._separator,L);return L}if(J=A[T],L=E.get(J),!L)L=new Map,E.set(J,L);return this._add(_,T+1,A,L)};J_.prototype._remove=function(_,T,A,E){var L,J,X;if(T===A.length){if(L=E.get(this._separator),L&&this._remove_value(L,_))return E.delete(this._separator),!0;return!1}if(J=A[T],L=E.get(J),!L)return!1;if(X=this._remove(_,T+1,A,L),L.size===0)E.delete(J);return X};J_.prototype._match_some=function(_,T,A,E,L){var J,X;for(X of E.keys())if(X!==this._separator){for(J=T;J<A.length;J+=1)_=this._match(_,J,A,E,L);break}return _};J_.prototype._match=function(_,T,A,E,L){var J,X;if(X=E.get(this._wildcard_some),X)_=this._match_some(_,T,A,X,L),_=this._match(_,A.length,A,X,L);if(T===A.length){if(X=E.get(this._separator),X)if(_.dest)this._add_values(_.dest,_.source,L),this._add_values(_.dest,X,L),_=_.dest;else if(_.source)_.dest=_.source,_.source=X;else this._add_values(_,X,L)}else{if(J=A[T],J!==this._wildcard_one&&J!==this._wildcard_some){if(X=E.get(J),X)_=this._match(_,T+1,A,X,L)}if(J||this._match_empty_levels){if(X=E.get(this._wildcard_one),X)_=this._match(_,T+1,A,X,L)}}return _};J_.prototype._match2=function(_,T,A){var E=this._match({source:_},0,this._split(T,!1),this._trie,A);return E.source||E};J_.prototype._test_some=function(_,T,A,E){var L,J;for(J of E.keys())if(J!==this._separator){for(L=T;L<A.length;L+=1)if(this._test(_,L,A,E))return!0;break}return!1};J_.prototype._test=function(_,T,A,E){var L,J;if(J=E.get(this._wildcard_some),J){if(this._test_some(_,T,A,J)||this._test(_,A.length,A,J))return!0}if(T===A.length){if(J=E.get(this._separator),J&&this.test_values(J,_))return!0}else{if(L=A[T],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=E.get(L),J&&this._test(_,T+1,A,J))return!0}if(L||this._match_empty_levels){if(J=E.get(this._wildcard_one),J&&this._test(_,T+1,A,J))return!0}}return!1};J_.prototype._match_some_iter=function*(_,T,A,E){var L,J;for(J of A.keys())if(J!==this._separator){for(L=_;L<T.length;L+=1)yield*this._match_iter(L,T,A,E);break}};J_.prototype._match_iter=function*(_,T,A,E){var L,J;if(J=A.get(this._wildcard_some),J)yield*this._match_some_iter(_,T,J,E),yield*this._match_iter(T.length,T,J,E);if(_===T.length){if(J=A.get(this._separator),J)yield*this._iter_values(J,E)}else{if(L=T[_],L!==this._wildcard_one&&L!==this._wildcard_some){if(J=A.get(L),J)yield*this._match_iter(_+1,T,J,E)}if(L||this._match_empty_levels){if(J=A.get(this._wildcard_one),J)yield*this._match_iter(_+1,T,J,E)}}};J_.prototype._split_words=function(_){let T=_.split(this._separator);if(T.length>this._max_words)throw Error("too many words");return T};J_.prototype._split=function(_,T){let A;if(this._split_cache){if(A=this._split_cache.get(_),A===void 0){if(A=this._split_words(_),this._split_cache.set(_,A),this._split_cache.size>this._cache_splits)for(let E of this._split_cache.keys()){this._split_cache.delete(E);break}}}else A=this._split_words(_);if(T&&A.reduce((E,L)=>E+(L===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return A};J_.prototype.add=function(_,T){var A=this._shortcuts&&this._shortcuts.get(_);if(A)this._add_value(A,T);else if(A=this._add(T,0,this._split(_,!0),this._trie),this._shortcuts)this._shortcuts.set(_,A);return this};J_.prototype.remove=function(_,T){if(this._remove(T,0,this._split(_,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(_);return this};J_.prototype.match=function(_,T){return this._match2([],_,T)};J_.prototype.match_iter=function(_,T){return this._match_iter(0,this._split(_,!1),this._trie,T)};J_.prototype.test=function(_,T){return this._test(T,0,this._split(_,!1),this._trie)};J_.prototype.test_values=function(_,T){return _.indexOf(T)>=0};J_.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};J_.prototype.get_trie=function(){return this._trie};J_.prototype.visit=function*(){let _=[],T=this._trie.entries(),A=0;while(!0){if(A===0)yield{type:"start_entries"};let E=T.next();if(E.done){yield{type:"end_entries"};let X=_.pop();if(X===void 0)return;[T,A]=X;continue}let[L,J]=E.value;if(yield{type:"entry",key:L},++A,L===this._separator){if(yield{type:"start_values"},J[Symbol.iterator])for(let X of J)yield{type:"value",value:X};else yield{type:"value",value:J};yield{type:"end_values"};continue}_.push([T,A]),T=J.entries(),A=0}};J_.prototype.get_restorer=function(_){_=_||{};let T=[],A=this._trie,E="";return(L)=>{switch(L.type){case"entry":if(A=A||new Map,T.push([A,L.key,E]),A=A.get(L.key),_.cache_adds){if(E)E+=this._separator;E+=L.key}break;case"value":if(A)this._add_value(A,L.value);else A=this._initial_value(L.value);break;case"end_entries":if(A&&A.size===0)A=void 0;case"end_values":let J=T.pop();if(J===void 0)A=void 0,E="";else{let[X,H,Z]=J;if(A){if(_.cache_adds&&this._shortcuts&&L.type==="end_values")this._shortcuts.set(Z,A);X.set(H,A)}A=X,E=Z}break}}};function F1(_){J_.call(this,_)}p8.inherits(F1,J_);F1.prototype._initial_value=function(_){return new Set().add(_)};F1.prototype._add_value=function(_,T){_.add(T)};F1.prototype._add_values=function(_,T){T.forEach(function(A){_.add(A)})};F1.prototype._remove_value=function(_,T){if(T===void 0)return!0;return _.delete(T),_.size===0};F1.prototype.test_values=function(_,T){return _.has(T)};F1.prototype.match=function(_,T){return this._match2(new Set,_,T)};function t1(_){J_.call(this,_)}p8.inherits(t1,J_);t1.prototype._initial_value=function(){return!0};t1.prototype._add_value=function(){};t1.prototype._remove_value=function(){return!0};t1.prototype._iter_values=function*(){yield!0};t1.prototype.test_values=function(){return!0};t1.prototype.match=function(_,T){return this.test(_,T)};var l8=I("stream");function t5(_){l8.Readable.call(this,{objectMode:!0}),this._iterator=_.visit()}p8.inherits(t5,l8.Readable);t5.prototype._read=function(){while(!0){let{done:_,value:T}=this._iterator.next();if(_){this.push(null);break}if(!this.push(T))break}};function e5(_){l8.Writable.call(this,{objectMode:!0}),this._restorer=_.get_restorer()}p8.inherits(e5,l8.Writable);e5.prototype._write=function(_,T,A){this._restorer(_),A()};var a7=null;function dM(_){if(_!==a7){let T=i7();J_.nativeString=T(_.QlobberString,J_),J_.nativeNumber=T(_.QlobberNumber,J_),F1.nativeString=T(_.QlobberDedupString,F1),F1.nativeNumber=T(_.QlobberDedupNumber,F1),t1.native=T(_.QlobberTrue,t1),a7=_}return o7}o7.Qlobber=J_;o7.QlobberDedup=F1;o7.QlobberTrue=t1;o7.VisitorStream=t5;o7.RestorerStream=e5;o7.set_native=dM});var t7=W((Kf,s7)=>{var{Qlobber:oM}=r7(),dT=I("assert"),rM=f5();function e1(_){if(!(this instanceof e1))return new e1(_);let T=this;_=_||{},_.matchEmptyLevels=_.matchEmptyLevels===void 0?!0:!!_.matchEmptyLevels,_.separator=_.separator||"/",_.wildcardOne=_.wildcardOne||"+",_.wildcardSome=_.wildcardSome||"#",this._messageQueue=[],this._messageCallbacks=[],this._parallel=rM({results:!1,released:A}),this.concurrency=_.concurrency||0,this.current=0,this._doing=!1,this._matcher=new oM({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||sM,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 sM(){}s7.exports=e1});var z_=W(($f,_J)=>{class e7 extends Error{constructor(_){if(!Array.isArray(_))throw TypeError(`Expected input to be an Array, got ${typeof _}`);let T="";for(let A=0;A<_.length;A++)T+=` ${_[A].stack}
|
|
3
|
+
`;super(T);this.name="AggregateError",this.errors=_}}_J.exports={AggregateError:e7,ArrayIsArray(_){return Array.isArray(_)},ArrayPrototypeIncludes(_,T){return _.includes(T)},ArrayPrototypeIndexOf(_,T){return _.indexOf(T)},ArrayPrototypeJoin(_,T){return _.join(T)},ArrayPrototypeMap(_,T){return _.map(T)},ArrayPrototypePop(_,T){return _.pop(T)},ArrayPrototypePush(_,T){return _.push(T)},ArrayPrototypeSlice(_,T,A){return _.slice(T,A)},Error,FunctionPrototypeCall(_,T,...A){return _.call(T,...A)},FunctionPrototypeSymbolHasInstance(_,T){return Function.prototype[Symbol.hasInstance].call(_,T)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(_,T){return Object.defineProperties(_,T)},ObjectDefineProperty(_,T,A){return Object.defineProperty(_,T,A)},ObjectGetOwnPropertyDescriptor(_,T){return Object.getOwnPropertyDescriptor(_,T)},ObjectKeys(_){return Object.keys(_)},ObjectSetPrototypeOf(_,T){return Object.setPrototypeOf(_,T)},Promise,PromisePrototypeCatch(_,T){return _.catch(T)},PromisePrototypeThen(_,T,A){return _.then(T,A)},PromiseReject(_){return Promise.reject(_)},PromiseResolve(_){return Promise.resolve(_)},ReflectApply:Reflect.apply,RegExpPrototypeTest(_,T){return _.test(T)},SafeSet:Set,String,StringPrototypeSlice(_,T,A){return _.slice(T,A)},StringPrototypeToLowerCase(_){return _.toLowerCase()},StringPrototypeToUpperCase(_){return _.toUpperCase()},StringPrototypeTrim(_){return _.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(_,T,A){return _.set(T,A)},Boolean,Uint8Array}});var _6=W((Gf,TJ)=>{TJ.exports={format(_,...T){return _.replace(/%([sdifj])/g,function(...[A,E]){let L=T.shift();if(E==="f")return L.toFixed(6);else if(E==="j")return JSON.stringify(L);else if(E==="s"&&typeof L==="object")return`${L.constructor!==Object?L.constructor.name:""} {}`.trim();else return L.toString()})},inspect(_){switch(typeof _){case"string":if(_.includes("'")){if(!_.includes('"'))return`"${_}"`;else if(!_.includes("`")&&!_.includes("${"))return`\`${_}\``}return`'${_}'`;case"number":if(isNaN(_))return"NaN";else if(Object.is(_,-0))return String(_);return _;case"bigint":return`${String(_)}n`;case"boolean":case"undefined":return String(_);case"object":return"{}"}}}});var l_=W((Uf,JJ)=>{var{format:tM,inspect:n8}=_6(),{AggregateError:eM}=z_(),_V=globalThis.AggregateError||eM,TV=Symbol("kIsNodeError"),AV=["string","function","number","object","Function","Object","boolean","bigint","symbol"],EV=/^([A-Z][a-z0-9]*)+$/,i8={};function YT(_,T){if(!_)throw new i8.ERR_INTERNAL_ASSERTION(T)}function AJ(_){let T="",A=_.length,E=_[0]==="-"?1:0;for(;A>=E+4;A-=3)T=`_${_.slice(A-3,A)}${T}`;return`${_.slice(0,A)}${T}`}function LV(_,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 tM(T,...A)}function g_(_,T,A){if(!A)A=Error;class E extends A{constructor(...L){super(LV(_,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[TV]=!0,i8[_]=E}function EJ(_){let T="__node_internal_"+_.name;return Object.defineProperty(_,"name",{value:T}),_}function JV(_,T){if(_&&T&&_!==T){if(Array.isArray(T.errors))return T.errors.push(_),T;let A=new _V([T,_],T.message);return A.code=T.code,A}return _||T}class LJ extends Error{constructor(_="The operation was aborted",T=void 0){if(T!==void 0&&typeof T!=="object")throw new i8.ERR_INVALID_ARG_TYPE("options","Object",T);super(_,T);this.code="ABORT_ERR",this.name="AbortError"}}g_("ERR_ASSERTION","%s",Error);g_("ERR_INVALID_ARG_TYPE",(_,T,A)=>{if(YT(typeof _==="string","'name' must be a string"),!Array.isArray(T))T=[T];let E="The ";if(_.endsWith(" argument"))E+=`${_} `;else E+=`"${_}" ${_.includes(".")?"property":"argument"} `;E+="must be ";let L=[],J=[],X=[];for(let Z of T)if(YT(typeof Z==="string","All expected entries have to be of type string"),AV.includes(Z))L.push(Z.toLowerCase());else if(EV.test(Z))J.push(Z);else YT(Z!=="object",'The value "object" should be written as "Object"'),X.push(Z);if(J.length>0){let Z=L.indexOf("object");if(Z!==-1)L.splice(L,Z,1),J.push("Object")}if(L.length>0){switch(L.length){case 1:E+=`of type ${L[0]}`;break;case 2:E+=`one of type ${L[0]} or ${L[1]}`;break;default:{let Z=L.pop();E+=`one of type ${L.join(", ")}, or ${Z}`}}if(J.length>0||X.length>0)E+=" or "}if(J.length>0){switch(J.length){case 1:E+=`an instance of ${J[0]}`;break;case 2:E+=`an instance of ${J[0]} or ${J[1]}`;break;default:{let Z=J.pop();E+=`an instance of ${J.join(", ")}, or ${Z}`}}if(X.length>0)E+=" or "}switch(X.length){case 0:break;case 1:if(X[0].toLowerCase()!==X[0])E+="an ";E+=`${X[0]}`;break;case 2:E+=`one of ${X[0]} or ${X[1]}`;break;default:{let Z=X.pop();E+=`one of ${X.join(", ")}, or ${Z}`}}if(A==null)E+=`. Received ${A}`;else if(typeof A==="function"&&A.name)E+=`. Received function ${A.name}`;else if(typeof A==="object"){var H;if((H=A.constructor)!==null&&H!==void 0&&H.name)E+=`. Received an instance of ${A.constructor.name}`;else{let Z=n8(A,{depth:-1});E+=`. Received ${Z}`}}else{let Z=n8(A,{colors:!1});if(Z.length>25)Z=`${Z.slice(0,25)}...`;E+=`. Received type ${typeof A} (${Z})`}return E},TypeError);g_("ERR_INVALID_ARG_VALUE",(_,T,A="is invalid")=>{let E=n8(T);if(E.length>128)E=E.slice(0,128)+"...";return`The ${_.includes(".")?"property":"argument"} '${_}' ${A}. Received ${E}`},TypeError);g_("ERR_INVALID_RETURN_VALUE",(_,T,A)=>{var E;let L=A!==null&&A!==void 0&&(E=A.constructor)!==null&&E!==void 0&&E.name?`instance of ${A.constructor.name}`:`type ${typeof A}`;return`Expected ${_} to be returned from the "${T}" function but got ${L}.`},TypeError);g_("ERR_MISSING_ARGS",(..._)=>{YT(_.length>0,"At least one arg needs to be specified");let T,A=_.length;switch(_=(Array.isArray(_)?_:[_]).map((E)=>`"${E}"`).join(" or "),A){case 1:T+=`The ${_[0]} argument`;break;case 2:T+=`The ${_[0]} and ${_[1]} arguments`;break;default:{let E=_.pop();T+=`The ${_.join(", ")}, and ${E} arguments`}break}return`${T} must be specified`},TypeError);g_("ERR_OUT_OF_RANGE",(_,T,A)=>{YT(T,'Missing "range" argument');let E;if(Number.isInteger(A)&&Math.abs(A)>4294967296)E=AJ(String(A));else if(typeof A==="bigint"){E=String(A);let L=BigInt(2)**BigInt(32);if(A>L||A<-L)E=AJ(E);E+="n"}else E=n8(A);return`The value of "${_}" is out of range. It must be ${T}. Received ${E}`},RangeError);g_("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);g_("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);g_("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);g_("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);g_("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);g_("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);g_("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);g_("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);g_("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);g_("ERR_STREAM_WRITE_AFTER_END","write after end",Error);g_("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);JJ.exports={AbortError:LJ,aggregateTwoErrors:EJ(JV),hideStackFrames:EJ,codes:i8}});var s_=W((Wf,A6)=>{var XV=I("buffer"),{format:HV,inspect:ZV}=_6(),{codes:{ERR_INVALID_ARG_TYPE:T6}}=l_(),{kResistStopPropagation:YV,AggregateError:KV,SymbolDispose:$V}=z_(),GV=globalThis.AbortSignal||I("abort-controller").AbortSignal,UV=globalThis.AbortController||I("abort-controller").AbortController,WV=Object.getPrototypeOf(async function(){}).constructor,XJ=globalThis.Blob||XV.Blob,NV=typeof XJ<"u"?function(T){return T instanceof XJ}:function(T){return!1},HJ=(_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new T6(T,"AbortSignal",_)},QV=(_,T)=>{if(typeof _!=="function")throw new T6(T,"Function",_)};A6.exports={AggregateError:KV,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:HV,inspect:ZV,types:{isAsyncFunction(_){return _ instanceof WV},isArrayBufferView(_){return ArrayBuffer.isView(_)}},isBlob:NV,deprecate(_,T){return _},addAbortListener:I("events").addAbortListener||function(T,A){if(T===void 0)throw new T6("signal","AbortSignal",T);HJ(T,"signal"),QV(A,"listener");let E;if(T.aborted)queueMicrotask(()=>A());else T.addEventListener("abort",A,{__proto__:null,once:!0,[YV]:!0}),E=()=>{T.removeEventListener("abort",A)};return{__proto__:null,[$V](){var L;(L=E)===null||L===void 0||L()}}},AbortSignalAny:GV.any||function(T){if(T.length===1)return T[0];let A=new UV,E=()=>A.abort();return T.forEach((L)=>{HJ(L,"signals"),L.addEventListener("abort",E,{once:!0})}),A.signal.addEventListener("abort",()=>{T.forEach((L)=>L.removeEventListener("abort",E))},{once:!0}),A.signal}};A6.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var pT=W((Nf,MJ)=>{var{ArrayIsArray:L6,ArrayPrototypeIncludes:$J,ArrayPrototypeJoin:GJ,ArrayPrototypeMap:MV,NumberIsInteger:J6,NumberIsNaN:VV,NumberMAX_SAFE_INTEGER:zV,NumberMIN_SAFE_INTEGER:FV,NumberParseInt:CV,ObjectPrototypeHasOwnProperty:OV,RegExpPrototypeExec:UJ,String:RV,StringPrototypeToUpperCase:DV,StringPrototypeTrim:BV}=z_(),{hideStackFrames:C1,codes:{ERR_SOCKET_BAD_PORT:qV,ERR_INVALID_ARG_TYPE:n_,ERR_INVALID_ARG_VALUE:cT,ERR_OUT_OF_RANGE:KT,ERR_UNKNOWN_SIGNAL:ZJ}}=l_(),{normalizeEncoding:IV}=s_(),{isAsyncFunction:PV,isArrayBufferView:jV}=s_().types,YJ={};function xV(_){return _===(_|0)}function wV(_){return _===_>>>0}var SV=/^[0-7]+$/,yV="must be a 32-bit unsigned integer or an octal string";function vV(_,T,A){if(typeof _>"u")_=A;if(typeof _==="string"){if(UJ(SV,_)===null)throw new cT(T,_,yV);_=CV(_,8)}return WJ(_,T),_}var hV=C1((_,T,A=FV,E=zV)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!J6(_))throw new KT(T,"an integer",_);if(_<A||_>E)throw new KT(T,`>= ${A} && <= ${E}`,_)}),kV=C1((_,T,A=-2147483648,E=2147483647)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!J6(_))throw new KT(T,"an integer",_);if(_<A||_>E)throw new KT(T,`>= ${A} && <= ${E}`,_)}),WJ=C1((_,T,A=!1)=>{if(typeof _!=="number")throw new n_(T,"number",_);if(!J6(_))throw new KT(T,"an integer",_);let E=A?1:0,L=4294967295;if(_<E||_>L)throw new KT(T,`>= ${E} && <= ${L}`,_)});function X6(_,T){if(typeof _!=="string")throw new n_(T,"string",_)}function fV(_,T,A=void 0,E){if(typeof _!=="number")throw new n_(T,"number",_);if(A!=null&&_<A||E!=null&&_>E||(A!=null||E!=null)&&VV(_))throw new KT(T,`${A!=null?`>= ${A}`:""}${A!=null&&E!=null?" && ":""}${E!=null?`<= ${E}`:""}`,_)}var bV=C1((_,T,A)=>{if(!$J(A,_)){let L="must be one of: "+GJ(MV(A,(J)=>typeof J==="string"?`'${J}'`:RV(J)),", ");throw new cT(T,_,L)}});function NJ(_,T){if(typeof _!=="boolean")throw new n_(T,"boolean",_)}function E6(_,T,A){return _==null||!OV(_,T)?A:_[T]}var gV=C1((_,T,A=null)=>{let E=E6(A,"allowArray",!1),L=E6(A,"allowFunction",!1);if(!E6(A,"nullable",!1)&&_===null||!E&&L6(_)||typeof _!=="object"&&(!L||typeof _!=="function"))throw new n_(T,"Object",_)}),mV=C1((_,T)=>{if(_!=null&&typeof _!=="object"&&typeof _!=="function")throw new n_(T,"a dictionary",_)}),a8=C1((_,T,A=0)=>{if(!L6(_))throw new n_(T,"Array",_);if(_.length<A){let E=`must be longer than ${A}`;throw new cT(T,_,E)}});function uV(_,T){a8(_,T);for(let A=0;A<_.length;A++)X6(_[A],`${T}[${A}]`)}function dV(_,T){a8(_,T);for(let A=0;A<_.length;A++)NJ(_[A],`${T}[${A}]`)}function cV(_,T){a8(_,T);for(let A=0;A<_.length;A++){let E=_[A],L=`${T}[${A}]`;if(E==null)throw new n_(L,"AbortSignal",E);QJ(E,L)}}function pV(_,T="signal"){if(X6(_,T),YJ[_]===void 0){if(YJ[DV(_)]!==void 0)throw new ZJ(_+" (signals must use all capital letters)");throw new ZJ(_)}}var lV=C1((_,T="buffer")=>{if(!jV(_))throw new n_(T,["Buffer","TypedArray","DataView"],_)});function nV(_,T){let A=IV(T),E=_.length;if(A==="hex"&&E%2!==0)throw new cT("encoding",T,`is invalid for data of length ${E}`)}function iV(_,T="Port",A=!0){if(typeof _!=="number"&&typeof _!=="string"||typeof _==="string"&&BV(_).length===0||+_!==+_>>>0||_>65535||_===0&&!A)throw new qV(T,_,A);return _|0}var QJ=C1((_,T)=>{if(_!==void 0&&(_===null||typeof _!=="object"||!("aborted"in _)))throw new n_(T,"AbortSignal",_)}),aV=C1((_,T)=>{if(typeof _!=="function")throw new n_(T,"Function",_)}),oV=C1((_,T)=>{if(typeof _!=="function"||PV(_))throw new n_(T,"Function",_)}),rV=C1((_,T)=>{if(_!==void 0)throw new n_(T,"undefined",_)});function sV(_,T,A){if(!$J(A,_))throw new n_(T,`('${GJ(A,"|")}')`,_)}var tV=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function KJ(_,T){if(typeof _>"u"||!UJ(tV,_))throw new cT(T,_,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function eV(_){if(typeof _==="string")return KJ(_,"hints"),_;else if(L6(_)){let T=_.length,A="";if(T===0)return A;for(let E=0;E<T;E++){let L=_[E];if(KJ(L,"hints"),A+=L,E!==T-1)A+=", "}return A}throw new cT("hints",_,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}MJ.exports={isInt32:xV,isUint32:wV,parseFileMode:vV,validateArray:a8,validateStringArray:uV,validateBooleanArray:dV,validateAbortSignalArray:cV,validateBoolean:NJ,validateBuffer:lV,validateDictionary:mV,validateEncoding:nV,validateFunction:aV,validateInt32:kV,validateInteger:hV,validateNumber:fV,validateObject:gV,validateOneOf:bV,validatePlainFunction:oV,validatePort:iV,validateSignalName:pV,validateString:X6,validateUint32:WJ,validateUndefined:rV,validateUnion:sV,validateAbortSignal:QJ,validateLinkHeaderValue:eV}});var c0=W((Qf,VJ)=>{VJ.exports=global.process});var T0=W((Mf,yJ)=>{var{SymbolAsyncIterator:zJ,SymbolIterator:FJ,SymbolFor:$T}=z_(),CJ=$T("nodejs.stream.destroyed"),OJ=$T("nodejs.stream.errored"),H6=$T("nodejs.stream.readable"),Z6=$T("nodejs.stream.writable"),RJ=$T("nodejs.stream.disturbed"),_z=$T("nodejs.webstream.isClosedPromise"),Tz=$T("nodejs.webstream.controllerErrorFunction");function o8(_,T=!1){var A;return!!(_&&typeof _.pipe==="function"&&typeof _.on==="function"&&(!T||typeof _.pause==="function"&&typeof _.resume==="function")&&(!_._writableState||((A=_._readableState)===null||A===void 0?void 0:A.readable)!==!1)&&(!_._writableState||_._readableState))}function r8(_){var T;return!!(_&&typeof _.write==="function"&&typeof _.on==="function"&&(!_._readableState||((T=_._writableState)===null||T===void 0?void 0:T.writable)!==!1))}function Az(_){return!!(_&&typeof _.pipe==="function"&&_._readableState&&typeof _.on==="function"&&typeof _.write==="function")}function _0(_){return _&&(_._readableState||_._writableState||typeof _.write==="function"&&typeof _.on==="function"||typeof _.pipe==="function"&&typeof _.on==="function")}function DJ(_){return!!(_&&!_0(_)&&typeof _.pipeThrough==="function"&&typeof _.getReader==="function"&&typeof _.cancel==="function")}function BJ(_){return!!(_&&!_0(_)&&typeof _.getWriter==="function"&&typeof _.abort==="function")}function qJ(_){return!!(_&&!_0(_)&&typeof _.readable==="object"&&typeof _.writable==="object")}function Ez(_){return DJ(_)||BJ(_)||qJ(_)}function Lz(_,T){if(_==null)return!1;if(T===!0)return typeof _[zJ]==="function";if(T===!1)return typeof _[FJ]==="function";return typeof _[zJ]==="function"||typeof _[FJ]==="function"}function s8(_){if(!_0(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!!(_.destroyed||_[CJ]||E!==null&&E!==void 0&&E.destroyed)}function IJ(_){if(!r8(_))return null;if(_.writableEnded===!0)return!0;let T=_._writableState;if(T!==null&&T!==void 0&&T.errored)return!1;if(typeof(T===null||T===void 0?void 0:T.ended)!=="boolean")return null;return T.ended}function Jz(_,T){if(!r8(_))return null;if(_.writableFinished===!0)return!0;let A=_._writableState;if(A!==null&&A!==void 0&&A.errored)return!1;if(typeof(A===null||A===void 0?void 0:A.finished)!=="boolean")return null;return!!(A.finished||T===!1&&A.ended===!0&&A.length===0)}function Xz(_){if(!o8(_))return null;if(_.readableEnded===!0)return!0;let T=_._readableState;if(!T||T.errored)return!1;if(typeof(T===null||T===void 0?void 0:T.ended)!=="boolean")return null;return T.ended}function PJ(_,T){if(!o8(_))return null;let A=_._readableState;if(A!==null&&A!==void 0&&A.errored)return!1;if(typeof(A===null||A===void 0?void 0:A.endEmitted)!=="boolean")return null;return!!(A.endEmitted||T===!1&&A.ended===!0&&A.length===0)}function jJ(_){if(_&&_[H6]!=null)return _[H6];if(typeof(_===null||_===void 0?void 0:_.readable)!=="boolean")return null;if(s8(_))return!1;return o8(_)&&_.readable&&!PJ(_)}function xJ(_){if(_&&_[Z6]!=null)return _[Z6];if(typeof(_===null||_===void 0?void 0:_.writable)!=="boolean")return null;if(s8(_))return!1;return r8(_)&&_.writable&&!IJ(_)}function Hz(_,T){if(!_0(_))return null;if(s8(_))return!0;if((T===null||T===void 0?void 0:T.readable)!==!1&&jJ(_))return!1;if((T===null||T===void 0?void 0:T.writable)!==!1&&xJ(_))return!1;return!0}function Zz(_){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 Yz(_){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 Kz(_){if(!_0(_))return null;if(typeof _.closed==="boolean")return _.closed;let{_writableState:T,_readableState:A}=_;if(typeof(T===null||T===void 0?void 0:T.closed)==="boolean"||typeof(A===null||A===void 0?void 0:A.closed)==="boolean")return(T===null||T===void 0?void 0:T.closed)||(A===null||A===void 0?void 0:A.closed);if(typeof _._closed==="boolean"&&wJ(_))return _._closed;return null}function wJ(_){return typeof _._closed==="boolean"&&typeof _._defaultKeepAlive==="boolean"&&typeof _._removedConnection==="boolean"&&typeof _._removedContLen==="boolean"}function SJ(_){return typeof _._sent100==="boolean"&&wJ(_)}function $z(_){var T;return typeof _._consuming==="boolean"&&typeof _._dumped==="boolean"&&((T=_.req)===null||T===void 0?void 0:T.upgradeOrConnect)===void 0}function Gz(_){if(!_0(_))return null;let{_writableState:T,_readableState:A}=_,E=T||A;return!E&&SJ(_)||!!(E&&E.autoDestroy&&E.emitClose&&E.closed===!1)}function Uz(_){var T;return!!(_&&((T=_[RJ])!==null&&T!==void 0?T:_.readableDidRead||_.readableAborted))}function Wz(_){var T,A,E,L,J,X,H,Z,Y,K;return!!(_&&((T=(A=(E=(L=(J=(X=_[OJ])!==null&&X!==void 0?X:_.readableErrored)!==null&&J!==void 0?J:_.writableErrored)!==null&&L!==void 0?L:(H=_._readableState)===null||H===void 0?void 0:H.errorEmitted)!==null&&E!==void 0?E:(Z=_._writableState)===null||Z===void 0?void 0:Z.errorEmitted)!==null&&A!==void 0?A:(Y=_._readableState)===null||Y===void 0?void 0:Y.errored)!==null&&T!==void 0?T:(K=_._writableState)===null||K===void 0?void 0:K.errored))}yJ.exports={isDestroyed:s8,kIsDestroyed:CJ,isDisturbed:Uz,kIsDisturbed:RJ,isErrored:Wz,kIsErrored:OJ,isReadable:jJ,kIsReadable:H6,kIsClosedPromise:_z,kControllerErrorFunction:Tz,kIsWritable:Z6,isClosed:Kz,isDuplexNodeStream:Az,isFinished:Hz,isIterable:Lz,isReadableNodeStream:o8,isReadableStream:DJ,isReadableEnded:Xz,isReadableFinished:PJ,isReadableErrored:Yz,isNodeStream:_0,isWebStream:Ez,isWritable:xJ,isWritableNodeStream:r8,isWritableStream:BJ,isWritableEnded:IJ,isWritableFinished:Jz,isWritableErrored:Zz,isServerRequest:$z,isServerResponse:SJ,willEmitClose:Gz,isTransformStream:qJ}});var q0=W((Vf,U6)=>{var p0=c0(),{AbortError:dJ,codes:Nz}=l_(),{ERR_INVALID_ARG_TYPE:Qz,ERR_STREAM_PREMATURE_CLOSE:vJ}=Nz,{kEmptyObject:K6,once:$6}=s_(),{validateAbortSignal:Mz,validateFunction:Vz,validateObject:zz,validateBoolean:Fz}=pT(),{Promise:Cz,PromisePrototypeThen:Oz,SymbolDispose:cJ}=z_(),{isClosed:Rz,isReadable:hJ,isReadableNodeStream:Y6,isReadableStream:Dz,isReadableFinished:kJ,isReadableErrored:fJ,isWritable:bJ,isWritableNodeStream:gJ,isWritableStream:Bz,isWritableFinished:mJ,isWritableErrored:uJ,isNodeStream:qz,willEmitClose:Iz,kIsClosedPromise:Pz}=T0(),lT;function jz(_){return _.setHeader&&typeof _.abort==="function"}var G6=()=>{};function pJ(_,T,A){var E,L;if(arguments.length===2)A=T,T=K6;else if(T==null)T=K6;else zz(T,"options");if(Vz(A,"callback"),Mz(T.signal,"options.signal"),A=$6(A),Dz(_)||Bz(_))return xz(_,T,A);if(!qz(_))throw new Qz("stream",["ReadableStream","WritableStream","Stream"],_);let J=(E=T.readable)!==null&&E!==void 0?E:Y6(_),X=(L=T.writable)!==null&&L!==void 0?L:gJ(_),H=_._writableState,Z=_._readableState,Y=()=>{if(!_.writable)G()},K=Iz(_)&&Y6(_)===J&&gJ(_)===X,$=mJ(_,!1),G=()=>{if($=!0,_.destroyed)K=!1;if(K&&(!_.readable||J))return;if(!J||U)A.call(_)},U=kJ(_,!1),V=()=>{if(U=!0,_.destroyed)K=!1;if(K&&(!_.writable||X))return;if(!X||$)A.call(_)},N=(f)=>{A.call(_,f)},z=Rz(_),Q=()=>{z=!0;let f=uJ(_)||fJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);if(J&&!U&&Y6(_,!0)){if(!kJ(_,!1))return A.call(_,new vJ)}if(X&&!$){if(!mJ(_,!1))return A.call(_,new vJ)}A.call(_)},F=()=>{z=!0;let f=uJ(_)||fJ(_);if(f&&typeof f!=="boolean")return A.call(_,f);A.call(_)},R=()=>{_.req.on("finish",G)};if(jz(_)){if(_.on("complete",G),!K)_.on("abort",Q);if(_.req)R();else _.on("request",R)}else if(X&&!H)_.on("end",Y),_.on("close",Y);if(!K&&typeof _.aborted==="boolean")_.on("aborted",Q);if(_.on("end",V),_.on("finish",G),T.error!==!1)_.on("error",N);if(_.on("close",Q),z)p0.nextTick(Q);else if(H!==null&&H!==void 0&&H.errorEmitted||Z!==null&&Z!==void 0&&Z.errorEmitted){if(!K)p0.nextTick(F)}else if(!J&&(!K||hJ(_))&&($||bJ(_)===!1))p0.nextTick(F);else if(!X&&(!K||bJ(_))&&(U||hJ(_)===!1))p0.nextTick(F);else if(Z&&_.req&&_.aborted)p0.nextTick(F);let q=()=>{if(A=G6,_.removeListener("aborted",Q),_.removeListener("complete",G),_.removeListener("abort",Q),_.removeListener("request",R),_.req)_.req.removeListener("finish",G);_.removeListener("end",Y),_.removeListener("close",Y),_.removeListener("finish",G),_.removeListener("end",V),_.removeListener("error",N),_.removeListener("close",Q)};if(T.signal&&!z){let f=()=>{let h=A;q(),h.call(_,new dJ(void 0,{cause:T.signal.reason}))};if(T.signal.aborted)p0.nextTick(f);else{lT=lT||s_().addAbortListener;let h=lT(T.signal,f),b=A;A=$6((...l)=>{h[cJ](),b.apply(_,l)})}}return q}function xz(_,T,A){let E=!1,L=G6;if(T.signal)if(L=()=>{E=!0,A.call(_,new dJ(void 0,{cause:T.signal.reason}))},T.signal.aborted)p0.nextTick(L);else{lT=lT||s_().addAbortListener;let X=lT(T.signal,L),H=A;A=$6((...Z)=>{X[cJ](),H.apply(_,Z)})}let J=(...X)=>{if(!E)p0.nextTick(()=>A.apply(_,X))};return Oz(_[Pz].promise,J,J),G6}function wz(_,T){var A;let E=!1;if(T===null)T=K6;if((A=T)!==null&&A!==void 0&&A.cleanup)Fz(T.cleanup,"cleanup"),E=T.cleanup;return new Cz((L,J)=>{let X=pJ(_,T,(H)=>{if(E)X();if(H)J(H);else L()})})}U6.exports=pJ;U6.exports.finished=wz});var GT=W((zf,tJ)=>{var A0=c0(),{aggregateTwoErrors:Sz,codes:{ERR_MULTIPLE_CALLBACK:yz},AbortError:vz}=l_(),{Symbol:iJ}=z_(),{kIsDestroyed:hz,isDestroyed:kz,isFinished:fz,isServerRequest:bz}=T0(),aJ=iJ("kDestroy"),W6=iJ("kConstruct");function oJ(_,T,A){if(_){if(_.stack,T&&!T.errored)T.errored=_;if(A&&!A.errored)A.errored=_}}function gz(_,T){let A=this._readableState,E=this._writableState,L=E||A;if(E!==null&&E!==void 0&&E.destroyed||A!==null&&A!==void 0&&A.destroyed){if(typeof T==="function")T();return this}if(oJ(_,E,A),E)E.destroyed=!0;if(A)A.destroyed=!0;if(!L.constructed)this.once(aJ,function(J){lJ(this,Sz(J,_),T)});else lJ(this,_,T);return this}function lJ(_,T,A){let E=!1;function L(J){if(E)return;E=!0;let{_readableState:X,_writableState:H}=_;if(oJ(J,H,X),H)H.closed=!0;if(X)X.closed=!0;if(typeof A==="function")A(J);if(J)A0.nextTick(mz,_,J);else A0.nextTick(rJ,_)}try{_._destroy(T||null,L)}catch(J){L(J)}}function mz(_,T){N6(_,T),rJ(_)}function rJ(_){let{_readableState:T,_writableState:A}=_;if(A)A.closeEmitted=!0;if(T)T.closeEmitted=!0;if(A!==null&&A!==void 0&&A.emitClose||T!==null&&T!==void 0&&T.emitClose)_.emit("close")}function N6(_,T){let{_readableState:A,_writableState:E}=_;if(E!==null&&E!==void 0&&E.errorEmitted||A!==null&&A!==void 0&&A.errorEmitted)return;if(E)E.errorEmitted=!0;if(A)A.errorEmitted=!0;_.emit("error",T)}function uz(){let _=this._readableState,T=this._writableState;if(_)_.constructed=!0,_.closed=!1,_.closeEmitted=!1,_.destroyed=!1,_.errored=null,_.errorEmitted=!1,_.reading=!1,_.ended=_.readable===!1,_.endEmitted=_.readable===!1;if(T)T.constructed=!0,T.destroyed=!1,T.closed=!1,T.closeEmitted=!1,T.errored=null,T.errorEmitted=!1,T.finalCalled=!1,T.prefinished=!1,T.ended=T.writable===!1,T.ending=T.writable===!1,T.finished=T.writable===!1}function Q6(_,T,A){let{_readableState:E,_writableState:L}=_;if(L!==null&&L!==void 0&&L.destroyed||E!==null&&E!==void 0&&E.destroyed)return this;if(E!==null&&E!==void 0&&E.autoDestroy||L!==null&&L!==void 0&&L.autoDestroy)_.destroy(T);else if(T){if(T.stack,L&&!L.errored)L.errored=T;if(E&&!E.errored)E.errored=T;if(A)A0.nextTick(N6,_,T);else N6(_,T)}}function dz(_,T){if(typeof _._construct!=="function")return;let{_readableState:A,_writableState:E}=_;if(A)A.constructed=!1;if(E)E.constructed=!1;if(_.once(W6,T),_.listenerCount(W6)>1)return;A0.nextTick(cz,_)}function cz(_){let T=!1;function A(E){if(T){Q6(_,E!==null&&E!==void 0?E:new yz);return}T=!0;let{_readableState:L,_writableState:J}=_,X=J||L;if(L)L.constructed=!0;if(J)J.constructed=!0;if(X.destroyed)_.emit(aJ,E);else if(E)Q6(_,E,!0);else A0.nextTick(pz,_)}try{_._construct((E)=>{A0.nextTick(A,E)})}catch(E){A0.nextTick(A,E)}}function pz(_){_.emit(W6)}function nJ(_){return(_===null||_===void 0?void 0:_.setHeader)&&typeof _.abort==="function"}function sJ(_){_.emit("close")}function lz(_,T){_.emit("error",T),A0.nextTick(sJ,_)}function nz(_,T){if(!_||kz(_))return;if(!T&&!fz(_))T=new vz;if(bz(_))_.socket=null,_.destroy(T);else if(nJ(_))_.abort();else if(nJ(_.req))_.req.abort();else if(typeof _.destroy==="function")_.destroy(T);else if(typeof _.close==="function")_.close();else if(T)A0.nextTick(lz,_,T);else A0.nextTick(sJ,_);if(!_.destroyed)_[hz]=!0}tJ.exports={construct:dz,destroyer:nz,destroy:gz,undestroy:uz,errorOrDestroy:Q6}});var _A=W((Ff,_X)=>{var{ArrayIsArray:iz,ObjectSetPrototypeOf:eJ}=z_(),{EventEmitter:t8}=I("events");function e8(_){t8.call(this,_)}eJ(e8.prototype,t8.prototype);eJ(e8,t8);e8.prototype.pipe=function(_,T){let A=this;function E(K){if(_.writable&&_.write(K)===!1&&A.pause)A.pause()}A.on("data",E);function L(){if(A.readable&&A.resume)A.resume()}if(_.on("drain",L),!_._isStdio&&(!T||T.end!==!1))A.on("end",X),A.on("close",H);let J=!1;function X(){if(J)return;J=!0,_.end()}function H(){if(J)return;if(J=!0,typeof _.destroy==="function")_.destroy()}function Z(K){if(Y(),t8.listenerCount(this,"error")===0)this.emit("error",K)}M6(A,"error",Z),M6(_,"error",Z);function Y(){A.removeListener("data",E),_.removeListener("drain",L),A.removeListener("end",X),A.removeListener("close",H),A.removeListener("error",Z),_.removeListener("error",Z),A.removeListener("end",Y),A.removeListener("close",Y),_.removeListener("close",Y)}return A.on("end",Y),A.on("close",Y),_.on("close",Y),_.emit("pipe",A),_};function M6(_,T,A){if(typeof _.prependListener==="function")return _.prependListener(T,A);if(!_._events||!_._events[T])_.on(T,A);else if(iz(_._events[T]))_._events[T].unshift(A);else _._events[T]=[A,_._events[T]]}_X.exports={Stream:e8,prependListener:M6}});var w4=W((_F,TA)=>{var{SymbolDispose:az}=z_(),{AbortError:TX,codes:oz}=l_(),{isNodeStream:AX,isWebStream:rz,kControllerErrorFunction:sz}=T0(),tz=q0(),{ERR_INVALID_ARG_TYPE:EX}=oz,V6,ez=(_,T)=>{if(typeof _!=="object"||!("aborted"in _))throw new EX(T,"AbortSignal",_)};_F.addAbortSignal=function(T,A){if(ez(T,"signal"),!AX(A)&&!rz(A))throw new EX("stream",["ReadableStream","WritableStream","Stream"],A);return _F.addAbortSignalNoValidate(T,A)};_F.addAbortSignalNoValidate=function(_,T){if(typeof _!=="object"||!("aborted"in _))return T;let A=AX(T)?()=>{T.destroy(new TX(void 0,{cause:_.reason}))}:()=>{T[sz](new TX(void 0,{cause:_.reason}))};if(_.aborted)A();else{V6=V6||s_().addAbortListener;let E=V6(_,A);tz(T,E[az])}return T}});var XX=W((Cf,JX)=>{var{StringPrototypeSlice:LX,SymbolIterator:EF,TypedArrayPrototypeSet:AA,Uint8Array:LF}=z_(),{Buffer:z6}=I("buffer"),{inspect:JF}=s_();JX.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(T){let A={data:T,next:null};if(this.length>0)this.tail.next=A;else this.head=A;this.tail=A,++this.length}unshift(T){let A={data:T,next:this.head};if(this.length===0)this.tail=A;this.head=A,++this.length}shift(){if(this.length===0)return;let T=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,T}clear(){this.head=this.tail=null,this.length=0}join(T){if(this.length===0)return"";let A=this.head,E=""+A.data;while((A=A.next)!==null)E+=T+A.data;return E}concat(T){if(this.length===0)return z6.alloc(0);let A=z6.allocUnsafe(T>>>0),E=this.head,L=0;while(E)AA(A,E.data,L),L+=E.data.length,E=E.next;return A}consume(T,A){let E=this.head.data;if(T<E.length){let L=E.slice(0,T);return this.head.data=E.slice(T),L}if(T===E.length)return this.shift();return A?this._getString(T):this._getBuffer(T)}first(){return this.head.data}*[EF](){for(let T=this.head;T;T=T.next)yield T.data}_getString(T){let A="",E=this.head,L=0;do{let J=E.data;if(T>J.length)A+=J,T-=J.length;else{if(T===J.length)if(A+=J,++L,E.next)this.head=E.next;else this.head=this.tail=null;else A+=LX(J,0,T),this.head=E,E.data=LX(J,T);break}++L}while((E=E.next)!==null);return this.length-=L,A}_getBuffer(T){let A=z6.allocUnsafe(T),E=T,L=this.head,J=0;do{let X=L.data;if(T>X.length)AA(A,X,E-T),T-=X.length;else{if(T===X.length)if(AA(A,X,E-T),++J,L.next)this.head=L.next;else this.head=this.tail=null;else AA(A,new LF(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 JF(this,{...A,depth:0,customInspect:!1})}}});var S4=W((Of,KX)=>{var{MathFloor:XF,NumberIsInteger:HF}=z_(),{validateInteger:ZF}=pT(),{ERR_INVALID_ARG_VALUE:YF}=l_().codes,HX=16384,ZX=16;function KF(_,T,A){return _.highWaterMark!=null?_.highWaterMark:T?_[A]:null}function YX(_){return _?ZX:HX}function $F(_,T){if(ZF(T,"value",0),_)ZX=T;else HX=T}function GF(_,T,A,E){let L=KF(T,E,A);if(L!=null){if(!HF(L)||L<0){let J=E?`options.${A}`:"options.highWaterMark";throw new YF(J,L)}return XF(L)}return YX(_.objectMode)}KX.exports={getHighWaterMark:GF,getDefaultHighWaterMark:YX,setDefaultHighWaterMark:$F}});var UX=W((F6,GX)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var EA=I("buffer"),E0=EA.Buffer;function $X(_,T){for(var A in _)T[A]=_[A]}if(E0.from&&E0.alloc&&E0.allocUnsafe&&E0.allocUnsafeSlow)GX.exports=EA;else $X(EA,F6),F6.Buffer=UT;function UT(_,T,A){return E0(_,T,A)}UT.prototype=Object.create(E0.prototype);$X(E0,UT);UT.from=function(_,T,A){if(typeof _==="number")throw TypeError("Argument must not be a number");return E0(_,T,A)};UT.alloc=function(_,T,A){if(typeof _!=="number")throw TypeError("Argument must be a number");var E=E0(_);if(T!==void 0)if(typeof A==="string")E.fill(T,A);else E.fill(T);else E.fill(0);return E};UT.allocUnsafe=function(_){if(typeof _!=="number")throw TypeError("Argument must be a number");return E0(_)};UT.allocUnsafeSlow=function(_){if(typeof _!=="number")throw TypeError("Argument must be a number");return EA.SlowBuffer(_)}});var NX=W((qF)=>{var O6=UX().Buffer,WX=O6.isEncoding||function(_){switch(_=""+_,_&&_.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function UF(_){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 WF(_){var T=UF(_);if(typeof T!=="string"&&(O6.isEncoding===WX||!WX(_)))throw Error("Unknown encoding: "+_);return T||_}qF.StringDecoder=y4;function y4(_){this.encoding=WF(_);var T;switch(this.encoding){case"utf16le":this.text=FF,this.end=CF,T=4;break;case"utf8":this.fillLast=MF,T=4;break;case"base64":this.text=OF,this.end=RF,T=3;break;default:this.write=DF,this.end=BF;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=O6.allocUnsafe(T)}y4.prototype.write=function(_){if(_.length===0)return"";var T,A;if(this.lastNeed){if(T=this.fillLast(_),T===void 0)return"";A=this.lastNeed,this.lastNeed=0}else A=0;if(A<_.length)return T?T+this.text(_,A):this.text(_,A);return T||""};y4.prototype.end=zF;y4.prototype.text=VF;y4.prototype.fillLast=function(_){if(this.lastNeed<=_.length)return _.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);_.copy(this.lastChar,this.lastTotal-this.lastNeed,0,_.length),this.lastNeed-=_.length};function C6(_){if(_<=127)return 0;else if(_>>5===6)return 2;else if(_>>4===14)return 3;else if(_>>3===30)return 4;return _>>6===2?-1:-2}function NF(_,T,A){var E=T.length-1;if(E<A)return 0;var L=C6(T[E]);if(L>=0){if(L>0)_.lastNeed=L-1;return L}if(--E<A||L===-2)return 0;if(L=C6(T[E]),L>=0){if(L>0)_.lastNeed=L-2;return L}if(--E<A||L===-2)return 0;if(L=C6(T[E]),L>=0){if(L>0)if(L===2)L=0;else _.lastNeed=L-3;return L}return 0}function QF(_,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 MF(_){var T=this.lastTotal-this.lastNeed,A=QF(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 VF(_,T){var A=NF(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 zF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+"\uFFFD";return T}function FF(_,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 CF(_){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 OF(_,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 RF(_){var T=_&&_.length?this.write(_):"";if(this.lastNeed)return T+this.lastChar.toString("base64",0,3-this.lastNeed);return T}function DF(_){return _.toString(this.encoding)}function BF(_){return _&&_.length?this.write(_):""}});var R6=W((Df,zX)=>{var QX=c0(),{PromisePrototypeThen:PF,SymbolAsyncIterator:MX,SymbolIterator:VX}=z_(),{Buffer:jF}=I("buffer"),{ERR_INVALID_ARG_TYPE:xF,ERR_STREAM_NULL_VALUES:wF}=l_().codes;function SF(_,T,A){let E;if(typeof T==="string"||T instanceof jF)return new _({objectMode:!0,...A,read(){this.push(T),this.push(null)}});let L;if(T&&T[MX])L=!0,E=T[MX]();else if(T&&T[VX])L=!1,E=T[VX]();else throw new xF("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){PF(H(Y),()=>QX.nextTick(K,Y),($)=>QX.nextTick(K,$||Y))};async function H(Y){let K=Y!==void 0&&Y!==null,$=typeof E.throw==="function";if(K&&$){let{value:G,done:U}=await E.throw(Y);if(await G,U)return}if(typeof E.return==="function"){let{value:G}=await E.return();await G}}async function Z(){for(;;){try{let{value:Y,done:K}=L?await E.next():E.next();if(K)J.push(null);else{let $=Y&&typeof Y.then==="function"?await Y:Y;if($===null)throw X=!1,new wF;else if(J.push($))continue;else X=!1}}catch(Y){J.destroy(Y)}break}}return J}zX.exports=SF});var h4=W((Bf,fX)=>{var g1=c0(),{ArrayPrototypeIndexOf:yF,NumberIsInteger:vF,NumberIsNaN:hF,NumberParseInt:kF,ObjectDefineProperties:w6,ObjectKeys:fF,ObjectSetPrototypeOf:OX,Promise:RX,SafeSet:bF,SymbolAsyncDispose:gF,SymbolAsyncIterator:mF,Symbol:uF}=z_();fX.exports=s;s.ReadableState=HA;var{EventEmitter:dF}=I("events"),{Stream:l0,prependListener:cF}=_A(),{Buffer:D6}=I("buffer"),{addAbortSignal:pF}=w4(),DX=q0(),A_=s_().debuglog("stream",(_)=>{A_=_}),lF=XX(),aT=GT(),{getHighWaterMark:nF,getDefaultHighWaterMark:iF}=S4(),{aggregateTwoErrors:FX,codes:{ERR_INVALID_ARG_TYPE:aF,ERR_METHOD_NOT_IMPLEMENTED:oF,ERR_OUT_OF_RANGE:rF,ERR_STREAM_PUSH_AFTER_EOF:sF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:tF},AbortError:eF}=l_(),{validateObject:_C}=pT(),WT=uF("kPaused"),{StringDecoder:BX}=NX(),TC=R6();OX(s.prototype,l0.prototype);OX(s,l0);var B6=()=>{},{errorOrDestroy:nT}=aT,iT=1,AC=2,qX=4,v4=8,IX=16,LA=32,JA=64,PX=128,EC=256,LC=512,JC=1024,j6=2048,x6=4096,XC=8192,HC=16384,ZC=32768,jX=65536,YC=131072,KC=262144;function w_(_){return{enumerable:!1,get(){return(this.state&_)!==0},set(T){if(T)this.state|=_;else this.state&=~_}}}w6(HA.prototype,{objectMode:w_(iT),ended:w_(AC),endEmitted:w_(qX),reading:w_(v4),constructed:w_(IX),sync:w_(LA),needReadable:w_(JA),emittedReadable:w_(PX),readableListening:w_(EC),resumeScheduled:w_(LC),errorEmitted:w_(JC),emitClose:w_(j6),autoDestroy:w_(x6),destroyed:w_(XC),closed:w_(HC),closeEmitted:w_(ZC),multiAwaitDrain:w_(jX),readingMore:w_(YC),dataEmitted:w_(KC)});function HA(_,T,A){if(typeof A!=="boolean")A=T instanceof L0();if(this.state=j6|x6|IX|LA,_&&_.objectMode)this.state|=iT;if(A&&_&&_.readableObjectMode)this.state|=iT;if(this.highWaterMark=_?nF(this,_,"readableHighWaterMark",A):iF(!1),this.buffer=new lF,this.length=0,this.pipes=[],this.flowing=null,this[WT]=null,_&&_.emitClose===!1)this.state&=~j6;if(_&&_.autoDestroy===!1)this.state&=~x6;if(this.errored=null,this.defaultEncoding=_&&_.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,_&&_.encoding)this.decoder=new BX(_.encoding),this.encoding=_.encoding}function s(_){if(!(this instanceof s))return new s(_);let T=this instanceof L0();if(this._readableState=new HA(_,this,T),_){if(typeof _.read==="function")this._read=_.read;if(typeof _.destroy==="function")this._destroy=_.destroy;if(typeof _.construct==="function")this._construct=_.construct;if(_.signal&&!T)pF(_.signal,this)}l0.call(this,_),aT.construct(this,()=>{if(this._readableState.needReadable)XA(this,this._readableState)})}s.prototype.destroy=aT.destroy;s.prototype._undestroy=aT.undestroy;s.prototype._destroy=function(_,T){T(_)};s.prototype[dF.captureRejectionSymbol]=function(_){this.destroy(_)};s.prototype[gF]=function(){let _;if(!this.destroyed)_=this.readableEnded?null:new eF,this.destroy(_);return new RX((T,A)=>DX(this,(E)=>E&&E!==_?A(E):T(null)))};s.prototype.push=function(_,T){return xX(this,_,T,!1)};s.prototype.unshift=function(_,T){return xX(this,_,T,!0)};function xX(_,T,A,E){A_("readableAddChunk",T);let L=_._readableState,J;if((L.state&iT)===0){if(typeof T==="string"){if(A=A||L.defaultEncoding,L.encoding!==A)if(E&&L.encoding)T=D6.from(T,A).toString(L.encoding);else T=D6.from(T,A),A=""}else if(T instanceof D6)A="";else if(l0._isUint8Array(T))T=l0._uint8ArrayToBuffer(T),A="";else if(T!=null)J=new aF("chunk",["string","Buffer","Uint8Array"],T)}if(J)nT(_,J);else if(T===null)L.state&=~v4,UC(_,L);else if((L.state&iT)!==0||T&&T.length>0)if(E)if((L.state&qX)!==0)nT(_,new tF);else if(L.destroyed||L.errored)return!1;else q6(_,L,T,!0);else if(L.ended)nT(_,new sF);else if(L.destroyed||L.errored)return!1;else if(L.state&=~v4,L.decoder&&!A)if(T=L.decoder.write(T),L.objectMode||T.length!==0)q6(_,L,T,!1);else XA(_,L);else q6(_,L,T,!1);else if(!E)L.state&=~v4,XA(_,L);return!L.ended&&(L.length<L.highWaterMark||L.length===0)}function q6(_,T,A,E){if(T.flowing&&T.length===0&&!T.sync&&_.listenerCount("data")>0){if((T.state&jX)!==0)T.awaitDrainWriters.clear();else T.awaitDrainWriters=null;T.dataEmitted=!0,_.emit("data",A)}else{if(T.length+=T.objectMode?1:A.length,E)T.buffer.unshift(A);else T.buffer.push(A);if((T.state&JA)!==0)ZA(_)}XA(_,T)}s.prototype.isPaused=function(){let _=this._readableState;return _[WT]===!0||_.flowing===!1};s.prototype.setEncoding=function(_){let T=new BX(_);this._readableState.decoder=T,this._readableState.encoding=this._readableState.decoder.encoding;let A=this._readableState.buffer,E="";for(let L of A)E+=T.write(L);if(A.clear(),E!=="")A.push(E);return this._readableState.length=E.length,this};var $C=1073741824;function GC(_){if(_>$C)throw new rF("size","<= 1GiB",_);else _--,_|=_>>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++;return _}function CX(_,T){if(_<=0||T.length===0&&T.ended)return 0;if((T.state&iT)!==0)return 1;if(hF(_)){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(!vF(_))_=kF(_,10);let T=this._readableState,A=_;if(_>T.highWaterMark)T.highWaterMark=GC(_);if(_!==0)T.state&=~PX;if(_===0&&T.needReadable&&((T.highWaterMark!==0?T.length>=T.highWaterMark:T.length>0)||T.ended)){if(A_("read: emitReadable",T.length,T.ended),T.length===0&&T.ended)I6(this);else ZA(this);return null}if(_=CX(_,T),_===0&&T.ended){if(T.length===0)I6(this);return null}let E=(T.state&JA)!==0;if(A_("need readable",E),T.length===0||T.length-_<T.highWaterMark)E=!0,A_("length less than watermark",E);if(T.ended||T.reading||T.destroyed||T.errored||!T.constructed)E=!1,A_("reading, ended or constructing",E);else if(E){if(A_("do read"),T.state|=v4|LA,T.length===0)T.state|=JA;try{this._read(T.highWaterMark)}catch(J){nT(this,J)}if(T.state&=~LA,!T.reading)_=CX(A,T)}let L;if(_>0)L=hX(_,T);else L=null;if(L===null)T.needReadable=T.length<=T.highWaterMark,_=0;else if(T.length-=_,T.multiAwaitDrain)T.awaitDrainWriters.clear();else T.awaitDrainWriters=null;if(T.length===0){if(!T.ended)T.needReadable=!0;if(A!==_&&T.ended)I6(this)}if(L!==null&&!T.errorEmitted&&!T.closeEmitted)T.dataEmitted=!0,this.emit("data",L);return L};function UC(_,T){if(A_("onEofChunk"),T.ended)return;if(T.decoder){let A=T.decoder.end();if(A&&A.length)T.buffer.push(A),T.length+=T.objectMode?1:A.length}if(T.ended=!0,T.sync)ZA(_);else T.needReadable=!1,T.emittedReadable=!0,wX(_)}function ZA(_){let T=_._readableState;if(A_("emitReadable",T.needReadable,T.emittedReadable),T.needReadable=!1,!T.emittedReadable)A_("emitReadable",T.flowing),T.emittedReadable=!0,g1.nextTick(wX,_)}function wX(_){let T=_._readableState;if(A_("emitReadable_",T.destroyed,T.length,T.ended),!T.destroyed&&!T.errored&&(T.length||T.ended))_.emit("readable"),T.emittedReadable=!1;T.needReadable=!T.flowing&&!T.ended&&T.length<=T.highWaterMark,yX(_)}function XA(_,T){if(!T.readingMore&&T.constructed)T.readingMore=!0,g1.nextTick(WC,_,T)}function WC(_,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 oF("_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 bF(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=NC(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)}}cF(_,"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 NC(_,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=yF(T.pipes,_);if(E===-1)return this;if(T.pipes.splice(E,1),T.pipes.length===0)this.pause();return _.emit("unpipe",this,A),this};s.prototype.on=function(_,T){let A=l0.prototype.on.call(this,_,T),E=this._readableState;if(_==="data"){if(E.readableListening=this.listenerCount("readable")>0,E.flowing!==!1)this.resume()}else if(_==="readable"){if(!E.endEmitted&&!E.readableListening){if(E.readableListening=E.needReadable=!0,E.flowing=!1,E.emittedReadable=!1,A_("on readable",E.length,E.reading),E.length)ZA(this);else if(!E.reading)g1.nextTick(QC,this)}}return A};s.prototype.addListener=s.prototype.on;s.prototype.removeListener=function(_,T){let A=l0.prototype.removeListener.call(this,_,T);if(_==="readable")g1.nextTick(SX,this);return A};s.prototype.off=s.prototype.removeListener;s.prototype.removeAllListeners=function(_){let T=l0.prototype.removeAllListeners.apply(this,arguments);if(_==="readable"||_===void 0)g1.nextTick(SX,this);return T};function SX(_){let T=_._readableState;if(T.readableListening=_.listenerCount("readable")>0,T.resumeScheduled&&T[WT]===!1)T.flowing=!0;else if(_.listenerCount("data")>0)_.resume();else if(!T.readableListening)T.flowing=null}function QC(_){A_("readable nexttick read 0"),_.read(0)}s.prototype.resume=function(){let _=this._readableState;if(!_.flowing)A_("resume"),_.flowing=!_.readableListening,MC(this,_);return _[WT]=!1,this};function MC(_,T){if(!T.resumeScheduled)T.resumeScheduled=!0,g1.nextTick(VC,_,T)}function VC(_,T){if(A_("resume",T.reading),!T.reading)_.read(0);if(T.resumeScheduled=!1,_.emit("resume"),yX(_),T.flowing&&!T.reading)_.read(0)}s.prototype.pause=function(){if(A_("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)A_("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState[WT]=!0,this};function yX(_){let T=_._readableState;A_("flow",T.flowing);while(T.flowing&&_.read()!==null);}s.prototype.wrap=function(_){let T=!1;_.on("data",(E)=>{if(!this.push(E)&&_.pause)T=!0,_.pause()}),_.on("end",()=>{this.push(null)}),_.on("error",(E)=>{nT(this,E)}),_.on("close",()=>{this.destroy()}),_.on("destroy",()=>{this.destroy()}),this._read=()=>{if(T&&_.resume)T=!1,_.resume()};let A=fF(_);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[mF]=function(){return vX(this)};s.prototype.iterator=function(_){if(_!==void 0)_C(_,"options");return vX(this,_)};function vX(_,T){if(typeof _.read!=="function")_=s.wrap(_,{objectMode:!0});let A=zC(_,T);return A.stream=_,A}async function*zC(_,T){let A=B6;function E(X){if(this===_)A(),A=B6;else A=X}_.on("readable",E);let L,J=DX(_,{writable:!1},(X)=>{L=X?FX(L,X):null,A(),A=B6});try{while(!0){let X=_.destroyed?null:_.read();if(X!==null)yield X;else if(L)throw L;else if(L===null)return;else await new RX(E)}}catch(X){throw L=FX(L,X),L}finally{if((L||(T===null||T===void 0?void 0:T.destroyOnReturn)!==!1)&&(L===void 0||_._readableState.autoDestroy))aT.destroyer(_,null);else _.off("readable",E),J()}}w6(s.prototype,{readable:{__proto__:null,get(){let _=this._readableState;return!!_&&_.readable!==!1&&!_.destroyed&&!_.errorEmitted&&!_.endEmitted},set(_){if(this._readableState)this._readableState.readable=!!_}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(_){if(this._readableState)this._readableState.flowing=_}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(_){if(!this._readableState)return;this._readableState.destroyed=_}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});w6(HA.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[WT]!==!1},set(_){this[WT]=!!_}}});s._fromList=hX;function hX(_,T){if(T.length===0)return null;let A;if(T.objectMode)A=T.buffer.shift();else if(!_||_>=T.length){if(T.decoder)A=T.buffer.join("");else if(T.buffer.length===1)A=T.buffer.first();else A=T.buffer.concat(T.length);T.buffer.clear()}else A=T.buffer.consume(_,T.decoder);return A}function I6(_){let T=_._readableState;if(A_("endReadable",T.endEmitted),!T.endEmitted)T.ended=!0,g1.nextTick(FC,T,_)}function FC(_,T){if(A_("endReadableNT",_.endEmitted,_.length),!_.errored&&!_.closeEmitted&&!_.endEmitted&&_.length===0){if(_.endEmitted=!0,T.emit("end"),T.writable&&T.allowHalfOpen===!1)g1.nextTick(CC,T);else if(_.autoDestroy){let A=T._writableState;if(!A||A.autoDestroy&&(A.finished||A.writable===!1))T.destroy()}}}function CC(_){if(_.writable&&!_.writableEnded&&!_.destroyed)_.end()}s.from=function(_,T){return TC(s,_,T)};var P6;function kX(){if(P6===void 0)P6={};return P6}s.fromWeb=function(_,T){return kX().newStreamReadableFromReadableStream(_,T)};s.toWeb=function(_,T){return kX().newReadableStreamFromStreamReadable(_,T)};s.wrap=function(_,T){var A,E;return new s({objectMode:(A=(E=_.readableObjectMode)!==null&&E!==void 0?E:_.objectMode)!==null&&A!==void 0?A:!0,...T,destroy(L,J){aT.destroyer(_,L),J(L)}}).wrap(_)}});var UA=W((qf,oX)=>{var NT=c0(),{ArrayPrototypeSlice:mX,Error:OC,FunctionPrototypeSymbolHasInstance:uX,ObjectDefineProperty:dX,ObjectDefineProperties:RC,ObjectSetPrototypeOf:cX,StringPrototypeToLowerCase:DC,Symbol:BC,SymbolHasInstance:qC}=z_();oX.exports=O_;O_.WritableState=b4;var{EventEmitter:IC}=I("events"),k4=_A().Stream,{Buffer:YA}=I("buffer"),GA=GT(),{addAbortSignal:PC}=w4(),{getHighWaterMark:jC,getDefaultHighWaterMark:xC}=S4(),{ERR_INVALID_ARG_TYPE:wC,ERR_METHOD_NOT_IMPLEMENTED:SC,ERR_MULTIPLE_CALLBACK:pX,ERR_STREAM_CANNOT_PIPE:yC,ERR_STREAM_DESTROYED:f4,ERR_STREAM_ALREADY_FINISHED:vC,ERR_STREAM_NULL_VALUES:hC,ERR_STREAM_WRITE_AFTER_END:kC,ERR_UNKNOWN_ENCODING:lX}=l_().codes,{errorOrDestroy:oT}=GA;cX(O_.prototype,k4.prototype);cX(O_,k4);function v6(){}var rT=BC("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=_?jC(this,_,"writableHighWaterMark",A):xC(!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=bC.bind(void 0,T),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,$A(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!_||_.emitClose!==!1,this.autoDestroy=!_||_.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[rT]=[]}function $A(_){_.buffered=[],_.bufferedIndex=0,_.allBuffers=!0,_.allNoop=!0}b4.prototype.getBuffer=function(){return mX(this.buffered,this.bufferedIndex)};dX(b4.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function O_(_){let T=this instanceof L0();if(!T&&!uX(O_,this))return new O_(_);if(this._writableState=new b4(_,this,T),_){if(typeof _.write==="function")this._write=_.write;if(typeof _.writev==="function")this._writev=_.writev;if(typeof _.destroy==="function")this._destroy=_.destroy;if(typeof _.final==="function")this._final=_.final;if(typeof _.construct==="function")this._construct=_.construct;if(_.signal)PC(_.signal,this)}k4.call(this,_),GA.construct(this,()=>{let A=this._writableState;if(!A.writing)k6(this,A);f6(this,A)})}dX(O_,qC,{__proto__:null,value:function(_){if(uX(this,_))return!0;if(this!==O_)return!1;return _&&_._writableState instanceof b4}});O_.prototype.pipe=function(){oT(this,new yC)};function nX(_,T,A,E){let L=_._writableState;if(typeof A==="function")E=A,A=L.defaultEncoding;else{if(!A)A=L.defaultEncoding;else if(A!=="buffer"&&!YA.isEncoding(A))throw new lX(A);if(typeof E!=="function")E=v6}if(T===null)throw new hC;else if(!L.objectMode)if(typeof T==="string"){if(L.decodeStrings!==!1)T=YA.from(T,A),A="buffer"}else if(T instanceof YA)A="buffer";else if(k4._isUint8Array(T))T=k4._uint8ArrayToBuffer(T),A="buffer";else throw new wC("chunk",["string","Buffer","Uint8Array"],T);let J;if(L.ending)J=new kC;else if(L.destroyed)J=new f4("write");if(J)return NT.nextTick(E,J),oT(_,J,!0),J;return L.pendingcb++,fC(_,L,T,A,E)}O_.prototype.write=function(_,T,A){return nX(this,_,T,A)===!0};O_.prototype.cork=function(){this._writableState.corked++};O_.prototype.uncork=function(){let _=this._writableState;if(_.corked){if(_.corked--,!_.writing)k6(this,_)}};O_.prototype.setDefaultEncoding=function(T){if(typeof T==="string")T=DC(T);if(!YA.isEncoding(T))throw new lX(T);return this._writableState.defaultEncoding=T,this};function fC(_,T,A,E,L){let J=T.objectMode?1:A.length;T.length+=J;let X=T.length<T.highWaterMark;if(!X)T.needDrain=!0;if(T.writing||T.corked||T.errored||!T.constructed){if(T.buffered.push({chunk:A,encoding:E,callback:L}),T.allBuffers&&E!=="buffer")T.allBuffers=!1;if(T.allNoop&&L!==v6)T.allNoop=!1}else T.writelen=J,T.writecb=L,T.writing=!0,T.sync=!0,_._write(A,E,T.onwrite),T.sync=!1;return X&&!T.errored&&!T.destroyed}function bX(_,T,A,E,L,J,X){if(T.writelen=E,T.writecb=X,T.writing=!0,T.sync=!0,T.destroyed)T.onwrite(new f4("write"));else if(A)_._writev(L,T.onwrite);else _._write(L,J,T.onwrite);T.sync=!1}function gX(_,T,A,E){--T.pendingcb,E(A),h6(T),oT(_,A)}function bC(_,T){let A=_._writableState,E=A.sync,L=A.writecb;if(typeof L!=="function"){oT(_,new pX);return}if(A.writing=!1,A.writecb=null,A.length-=A.writelen,A.writelen=0,T){if(T.stack,!A.errored)A.errored=T;if(_._readableState&&!_._readableState.errored)_._readableState.errored=T;if(E)NT.nextTick(gX,_,A,T,L);else gX(_,A,T,L)}else{if(A.buffered.length>A.bufferedIndex)k6(_,A);if(E)if(A.afterWriteTickInfo!==null&&A.afterWriteTickInfo.cb===L)A.afterWriteTickInfo.count++;else A.afterWriteTickInfo={count:1,cb:L,stream:_,state:A},NT.nextTick(gC,A.afterWriteTickInfo);else iX(_,A,1,L)}}function gC({stream:_,state:T,count:A,cb:E}){return T.afterWriteTickInfo=null,iX(_,T,A,E)}function iX(_,T,A,E){if(!T.ending&&!_.destroyed&&T.length===0&&T.needDrain)T.needDrain=!1,_.emit("drain");while(A-- >0)T.pendingcb--,E();if(T.destroyed)h6(T);f6(_,T)}function h6(_){if(_.writing)return;for(let L=_.bufferedIndex;L<_.buffered.length;++L){var T;let{chunk:J,callback:X}=_.buffered[L],H=_.objectMode?1:J.length;_.length-=H,X((T=_.errored)!==null&&T!==void 0?T:new f4("write"))}let A=_[rT].splice(0);for(let L=0;L<A.length;L++){var E;A[L]((E=_.errored)!==null&&E!==void 0?E:new f4("end"))}$A(_)}function k6(_,T){if(T.corked||T.bufferProcessing||T.destroyed||!T.constructed)return;let{buffered:A,bufferedIndex:E,objectMode:L}=T,J=A.length-E;if(!J)return;let X=E;if(T.bufferProcessing=!0,J>1&&_._writev){T.pendingcb-=J-1;let H=T.allNoop?v6:(Y)=>{for(let K=X;K<A.length;++K)A[K].callback(Y)},Z=T.allNoop&&X===0?A:mX(A,X);Z.allBuffers=T.allBuffers,bX(_,T,!0,T.length,Z,"",H),$A(T)}else{do{let{chunk:H,encoding:Z,callback:Y}=A[X];A[X++]=null;let K=L?1:H.length;bX(_,T,!1,K,H,Z,Y)}while(X<A.length&&!T.writing);if(X===A.length)$A(T);else if(X>256)A.splice(0,X),T.bufferedIndex=0;else T.bufferedIndex=X}T.bufferProcessing=!1}O_.prototype._write=function(_,T,A){if(this._writev)this._writev([{chunk:_,encoding:T}],A);else throw new SC("_write()")};O_.prototype._writev=null;O_.prototype.end=function(_,T,A){let E=this._writableState;if(typeof _==="function")A=_,_=null,T=null;else if(typeof T==="function")A=T,T=null;let L;if(_!==null&&_!==void 0){let J=nX(this,_,T);if(J instanceof OC)L=J}if(E.corked)E.corked=1,this.uncork();if(L);else if(!E.errored&&!E.ending)E.ending=!0,f6(this,E,!0),E.ended=!0;else if(E.finished)L=new vC("end");else if(E.destroyed)L=new f4("end");if(typeof A==="function")if(L||E.finished)NT.nextTick(A,L);else E[rT].push(A);return this};function KA(_){return _.ending&&!_.destroyed&&_.constructed&&_.length===0&&!_.errored&&_.buffered.length===0&&!_.finished&&!_.writing&&!_.errorEmitted&&!_.closeEmitted}function mC(_,T){let A=!1;function E(L){if(A){oT(_,L!==null&&L!==void 0?L:pX());return}if(A=!0,T.pendingcb--,L){let J=T[rT].splice(0);for(let X=0;X<J.length;X++)J[X](L);oT(_,L,T.sync)}else if(KA(T))T.prefinished=!0,_.emit("prefinish"),T.pendingcb++,NT.nextTick(y6,_,T)}T.sync=!0,T.pendingcb++;try{_._final(E)}catch(L){E(L)}T.sync=!1}function uC(_,T){if(!T.prefinished&&!T.finalCalled)if(typeof _._final==="function"&&!T.destroyed)T.finalCalled=!0,mC(_,T);else T.prefinished=!0,_.emit("prefinish")}function f6(_,T,A){if(KA(T)){if(uC(_,T),T.pendingcb===0){if(A)T.pendingcb++,NT.nextTick((E,L)=>{if(KA(L))y6(E,L);else L.pendingcb--},_,T);else if(KA(T))T.pendingcb++,y6(_,T)}}}function y6(_,T){T.pendingcb--,T.finished=!0;let A=T[rT].splice(0);for(let E=0;E<A.length;E++)A[E]();if(_.emit("finish"),T.autoDestroy){let E=_._readableState;if(!E||E.autoDestroy&&(E.endEmitted||E.readable===!1))_.destroy()}}RC(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 dC=GA.destroy;O_.prototype.destroy=function(_,T){let A=this._writableState;if(!A.destroyed&&(A.bufferedIndex<A.buffered.length||A[rT].length))NT.nextTick(h6,A);return dC.call(this,_,T),this};O_.prototype._undestroy=GA.undestroy;O_.prototype._destroy=function(_,T){T(_)};O_.prototype[IC.captureRejectionSymbol]=function(_){this.destroy(_)};var S6;function aX(){if(S6===void 0)S6={};return S6}O_.fromWeb=function(_,T){return aX().newStreamWritableFromWritableStream(_,T)};O_.toWeb=function(_){return aX().newWritableStreamFromStreamWritable(_)}});var KH=W((If,YH)=>{var b6=c0(),cC=I("buffer"),{isReadable:pC,isWritable:lC,isIterable:rX,isNodeStream:nC,isReadableNodeStream:sX,isWritableNodeStream:tX,isDuplexNodeStream:iC,isReadableStream:eX,isWritableStream:_H}=T0(),TH=q0(),{AbortError:HH,codes:{ERR_INVALID_ARG_TYPE:aC,ERR_INVALID_RETURN_VALUE:AH}}=l_(),{destroyer:tT}=GT(),oC=L0(),ZH=h4(),rC=UA(),{createDeferredPromise:EH}=s_(),LH=R6(),JH=globalThis.Blob||cC.Blob,sC=typeof JH<"u"?function(T){return T instanceof JH}:function(T){return!1},tC=globalThis.AbortController||I("abort-controller").AbortController,{FunctionPrototypeCall:XH}=z_();class QT extends oC{constructor(_){super(_);if((_===null||_===void 0?void 0:_.readable)===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if((_===null||_===void 0?void 0:_.writable)===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}}YH.exports=function _(T,A){if(iC(T))return T;if(sX(T))return sT({readable:T});if(tX(T))return sT({writable:T});if(nC(T))return sT({writable:!1,readable:!1});if(eX(T))return sT({readable:ZH.fromWeb(T)});if(_H(T))return sT({writable:rC.fromWeb(T)});if(typeof T==="function"){let{value:L,write:J,final:X,destroy:H}=eC(T);if(rX(L))return LH(QT,L,{objectMode:!0,write:J,final:X,destroy:H});let Z=L===null||L===void 0?void 0:L.then;if(typeof Z==="function"){let Y,K=XH(Z,L,($)=>{if($!=null)throw new AH("nully","body",$)},($)=>{tT(Y,$)});return Y=new QT({objectMode:!0,readable:!1,write:J,final($){X(async()=>{try{await K,b6.nextTick($,null)}catch(G){b6.nextTick($,G)}})},destroy:H})}throw new AH("Iterable, AsyncIterable or AsyncFunction",A,L)}if(sC(T))return _(T.arrayBuffer());if(rX(T))return LH(QT,T,{objectMode:!0,writable:!1});if(eX(T===null||T===void 0?void 0:T.readable)&&_H(T===null||T===void 0?void 0:T.writable))return QT.fromWeb(T);if(typeof(T===null||T===void 0?void 0:T.writable)==="object"||typeof(T===null||T===void 0?void 0:T.readable)==="object"){let L=T!==null&&T!==void 0&&T.readable?sX(T===null||T===void 0?void 0:T.readable)?T===null||T===void 0?void 0:T.readable:_(T.readable):void 0,J=T!==null&&T!==void 0&&T.writable?tX(T===null||T===void 0?void 0:T.writable)?T===null||T===void 0?void 0:T.writable:_(T.writable):void 0;return sT({readable:L,writable:J})}let E=T===null||T===void 0?void 0:T.then;if(typeof E==="function"){let L;return XH(E,T,(J)=>{if(J!=null)L.push(J);L.push(null)},(J)=>{tT(L,J)}),L=new QT({objectMode:!0,writable:!1,read(){}})}throw new aC(A,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],T)};function eC(_){let{promise:T,resolve:A}=EH(),E=new tC,L=E.signal;return{value:_(async function*(){while(!0){let X=T;T=null;let{chunk:H,done:Z,cb:Y}=await X;if(b6.nextTick(Y),Z)return;if(L.aborted)throw new HH(void 0,{cause:L.reason});({promise:T,resolve:A}=EH()),yield H}}(),{signal:L}),write(X,H,Z){let Y=A;A=null,Y({chunk:X,done:!1,cb:Z})},final(X){let H=A;A=null,H({done:!0,cb:X})},destroy(X,H){E.abort(),H(X)}}}function sT(_){let T=_.readable&&typeof _.readable.read!=="function"?ZH.wrap(_.readable):_.readable,A=_.writable,E=!!pC(T),L=!!lC(A),J,X,H,Z,Y;function K($){let G=Z;if(Z=null,G)G($);else if($)Y.destroy($)}if(Y=new QT({readableObjectMode:!!(T!==null&&T!==void 0&&T.readableObjectMode),writableObjectMode:!!(A!==null&&A!==void 0&&A.writableObjectMode),readable:E,writable:L}),L)TH(A,($)=>{if(L=!1,$)tT(T,$);K($)}),Y._write=function($,G,U){if(A.write($,G))U();else J=U},Y._final=function($){A.end(),X=$},A.on("drain",function(){if(J){let $=J;J=null,$()}}),A.on("finish",function(){if(X){let $=X;X=null,$()}});if(E)TH(T,($)=>{if(E=!1,$)tT(T,$);K($)}),T.on("readable",function(){if(H){let $=H;H=null,$()}}),T.on("end",function(){Y.push(null)}),Y._read=function(){while(!0){let $=T.read();if($===null){H=Y._read;return}if(!Y.push($))return}};return Y._destroy=function($,G){if(!$&&Z!==null)$=new HH;if(H=null,J=null,X=null,Z===null)G($);else Z=G,tT(A,$),tT(T,$)},Y}});var L0=W((Pf,UH)=>{var{ObjectDefineProperties:_O,ObjectGetOwnPropertyDescriptor:I0,ObjectKeys:TO,ObjectSetPrototypeOf:$H}=z_();UH.exports=m1;var u6=h4(),O1=UA();$H(m1.prototype,u6.prototype);$H(m1,u6);{let _=TO(O1.prototype);for(let T=0;T<_.length;T++){let A=_[T];if(!m1.prototype[A])m1.prototype[A]=O1.prototype[A]}}function m1(_){if(!(this instanceof m1))return new m1(_);if(u6.call(this,_),O1.call(this,_),_){if(this.allowHalfOpen=_.allowHalfOpen!==!1,_.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(_.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}_O(m1.prototype,{writable:{__proto__:null,...I0(O1.prototype,"writable")},writableHighWaterMark:{__proto__:null,...I0(O1.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...I0(O1.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...I0(O1.prototype,"writableBuffer")},writableLength:{__proto__:null,...I0(O1.prototype,"writableLength")},writableFinished:{__proto__:null,...I0(O1.prototype,"writableFinished")},writableCorked:{__proto__:null,...I0(O1.prototype,"writableCorked")},writableEnded:{__proto__:null,...I0(O1.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...I0(O1.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(_){if(this._readableState&&this._writableState)this._readableState.destroyed=_,this._writableState.destroyed=_}}});var g6;function GH(){if(g6===void 0)g6={};return g6}m1.fromWeb=function(_,T){return GH().newStreamDuplexFromReadableWritablePair(_,T)};m1.toWeb=function(_){return GH().newReadableWritablePairFromDuplex(_)};var m6;m1.from=function(_){if(!m6)m6=KH();return m6(_,"body")}});var p6=W((jf,NH)=>{var{ObjectSetPrototypeOf:WH,Symbol:AO}=z_();NH.exports=P0;var{ERR_METHOD_NOT_IMPLEMENTED:EO}=l_().codes,c6=L0(),{getHighWaterMark:LO}=S4();WH(P0.prototype,c6.prototype);WH(P0,c6);var g4=AO("kCallback");function P0(_){if(!(this instanceof P0))return new P0(_);let T=_?LO(this,_,"readableHighWaterMark",!0):null;if(T===0)_={..._,highWaterMark:null,readableHighWaterMark:T,writableHighWaterMark:_.writableHighWaterMark||0};if(c6.call(this,_),this._readableState.sync=!1,this[g4]=null,_){if(typeof _.transform==="function")this._transform=_.transform;if(typeof _.flush==="function")this._flush=_.flush}this.on("prefinish",JO)}function d6(_){if(typeof this._flush==="function"&&!this.destroyed)this._flush((T,A)=>{if(T){if(_)_(T);else this.destroy(T);return}if(A!=null)this.push(A);if(this.push(null),_)_()});else if(this.push(null),_)_()}function JO(){if(this._final!==d6)d6.call(this)}P0.prototype._final=d6;P0.prototype._transform=function(_,T,A){throw new EO("_transform()")};P0.prototype._write=function(_,T,A){let E=this._readableState,L=this._writableState,J=E.length;this._transform(_,T,(X,H)=>{if(X){A(X);return}if(H!=null)this.push(H);if(L.ended||J===E.length||E.length<E.highWaterMark)A();else this[g4]=A})};P0.prototype._read=function(){if(this[g4]){let _=this[g4];this[g4]=null,_()}}});var n6=W((xf,MH)=>{var{ObjectSetPrototypeOf:QH}=z_();MH.exports=eT;var l6=p6();QH(eT.prototype,l6.prototype);QH(eT,l6);function eT(_){if(!(this instanceof eT))return new eT(_);l6.call(this,_)}eT.prototype._transform=function(_,T,A){A(null,_)}});var MA=W((wf,OH)=>{var m4=c0(),{ArrayIsArray:XO,Promise:HO,SymbolAsyncIterator:ZO,SymbolDispose:YO}=z_(),QA=q0(),{once:KO}=s_(),$O=GT(),VH=L0(),{aggregateTwoErrors:GO,codes:{ERR_INVALID_ARG_TYPE:TE,ERR_INVALID_RETURN_VALUE:i6,ERR_MISSING_ARGS:UO,ERR_STREAM_DESTROYED:WO,ERR_STREAM_PREMATURE_CLOSE:NO},AbortError:QO}=l_(),{validateFunction:MO,validateAbortSignal:VO}=pT(),{isIterable:MT,isReadable:a6,isReadableNodeStream:NA,isNodeStream:zH,isTransformStream:_4,isWebStream:zO,isReadableStream:o6,isReadableFinished:FO}=T0(),CO=globalThis.AbortController||I("abort-controller").AbortController,r6,s6,t6;function FH(_,T,A){let E=!1;_.on("close",()=>{E=!0});let L=QA(_,{readable:T,writable:A},(J)=>{E=!J});return{destroy:(J)=>{if(E)return;E=!0,$O.destroyer(_,J||new WO("pipe"))},cleanup:L}}function OO(_){return MO(_[_.length-1],"streams[stream.length - 1]"),_.pop()}function e6(_){if(MT(_))return _;else if(NA(_))return RO(_);throw new TE("val",["Readable","Iterable","AsyncIterable"],_)}async function*RO(_){if(!s6)s6=h4();yield*s6.prototype[ZO].call(_)}async function WA(_,T,A,{end:E}){let L,J=null,X=(Y)=>{if(Y)L=Y;if(J){let K=J;J=null,K()}},H=()=>new HO((Y,K)=>{if(L)K(L);else J=()=>{if(L)K(L);else Y()}});T.on("drain",X);let Z=QA(T,{readable:!1},X);try{if(T.writableNeedDrain)await H();for await(let Y of _)if(!T.write(Y))await H();if(E)T.end(),await H();A()}catch(Y){A(L!==Y?GO(L,Y):Y)}finally{Z(),T.off("drain",X)}}async function _E(_,T,A,{end:E}){if(_4(T))T=T.writable;let L=T.getWriter();try{for await(let J of _)await L.ready,L.write(J).catch(()=>{});if(await L.ready,E)await L.close();A()}catch(J){try{await L.abort(J),A(J)}catch(X){A(X)}}}function DO(..._){return CH(_,KO(OO(_)))}function CH(_,T,A){if(_.length===1&&XO(_[0]))_=_[0];if(_.length<2)throw new UO("streams");let E=new CO,L=E.signal,J=A===null||A===void 0?void 0:A.signal,X=[];VO(J,"options.signal");function H(){V(new QO)}t6=t6||s_().addAbortListener;let Z;if(J)Z=t6(J,H);let Y,K,$=[],G=0;function U(R){V(R,--G===0)}function V(R,q){var f;if(R&&(!Y||Y.code==="ERR_STREAM_PREMATURE_CLOSE"))Y=R;if(!Y&&!q)return;while($.length)$.shift()(Y);if((f=Z)===null||f===void 0||f[YO](),E.abort(),q){if(!Y)X.forEach((h)=>h());m4.nextTick(T,Y,K)}}let N;for(let R=0;R<_.length;R++){let q=_[R],f=R<_.length-1,h=R>0,b=f||(A===null||A===void 0?void 0:A.end)!==!1,l=R===_.length-1;if(zH(q)){let c=function(W_){if(W_&&W_.name!=="AbortError"&&W_.code!=="ERR_STREAM_PREMATURE_CLOSE")U(W_)};var F=c;if(b){let{destroy:W_,cleanup:c_}=FH(q,f,h);if($.push(W_),a6(q)&&l)X.push(c_)}if(q.on("error",c),a6(q)&&l)X.push(()=>{q.removeListener("error",c)})}if(R===0)if(typeof q==="function"){if(N=q({signal:L}),!MT(N))throw new i6("Iterable, AsyncIterable or Stream","source",N)}else if(MT(q)||NA(q)||_4(q))N=q;else N=VH.from(q);else if(typeof q==="function"){if(_4(N)){var z;N=e6((z=N)===null||z===void 0?void 0:z.readable)}else N=e6(N);if(N=q(N,{signal:L}),f){if(!MT(N,!0))throw new i6("AsyncIterable",`transform[${R-1}]`,N)}else{var Q;if(!r6)r6=n6();let c=new r6({objectMode:!0}),W_=(Q=N)===null||Q===void 0?void 0:Q.then;if(typeof W_==="function")G++,W_.call(N,(C_)=>{if(K=C_,C_!=null)c.write(C_);if(b)c.end();m4.nextTick(U)},(C_)=>{c.destroy(C_),m4.nextTick(U,C_)});else if(MT(N,!0))G++,WA(N,c,U,{end:b});else if(o6(N)||_4(N)){let C_=N.readable||N;G++,WA(C_,c,U,{end:b})}else throw new i6("AsyncIterable or Promise","destination",N);N=c;let{destroy:c_,cleanup:B_}=FH(N,!1,!0);if($.push(c_),l)X.push(B_)}}else if(zH(q)){if(NA(N)){G+=2;let c=BO(N,q,U,{end:b});if(a6(q)&&l)X.push(c)}else if(_4(N)||o6(N)){let c=N.readable||N;G++,WA(c,q,U,{end:b})}else if(MT(N))G++,WA(N,q,U,{end:b});else throw new TE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else if(zO(q)){if(NA(N))G++,_E(e6(N),q,U,{end:b});else if(o6(N)||MT(N))G++,_E(N,q,U,{end:b});else if(_4(N))G++,_E(N.readable,q,U,{end:b});else throw new TE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);N=q}else N=VH.from(q)}if(L!==null&&L!==void 0&&L.aborted||J!==null&&J!==void 0&&J.aborted)m4.nextTick(H);return N}function BO(_,T,A,{end:E}){let L=!1;if(T.on("close",()=>{if(!L)A(new NO)}),_.pipe(T,{end:!1}),E){let X=function(){L=!0,T.end()};var J=X;if(FO(_))m4.nextTick(X);else _.once("end",X)}else A();return QA(_,{readable:!0,writable:!1},(X)=>{let H=_._readableState;if(X&&X.code==="ERR_STREAM_PREMATURE_CLOSE"&&H&&H.ended&&!H.errored&&!H.errorEmitted)_.once("end",A).once("error",A);else A(X)}),QA(T,{readable:!1,writable:!0},A)}OH.exports={pipelineImpl:CH,pipeline:DO}});var EE=W((Sf,PH)=>{var{pipeline:qO}=MA(),VA=L0(),{destroyer:IO}=GT(),{isNodeStream:zA,isReadable:RH,isWritable:DH,isWebStream:AE,isTransformStream:VT,isWritableStream:BH,isReadableStream:qH}=T0(),{AbortError:PO,codes:{ERR_INVALID_ARG_VALUE:IH,ERR_MISSING_ARGS:jO}}=l_(),xO=q0();PH.exports=function(...T){if(T.length===0)throw new jO("streams");if(T.length===1)return VA.from(T[0]);let A=[...T];if(typeof T[0]==="function")T[0]=VA.from(T[0]);if(typeof T[T.length-1]==="function"){let U=T.length-1;T[U]=VA.from(T[U])}for(let U=0;U<T.length;++U){if(!zA(T[U])&&!AE(T[U]))continue;if(U<T.length-1&&!(RH(T[U])||qH(T[U])||VT(T[U])))throw new IH(`streams[${U}]`,A[U],"must be readable");if(U>0&&!(DH(T[U])||BH(T[U])||VT(T[U])))throw new IH(`streams[${U}]`,A[U],"must be writable")}let E,L,J,X,H;function Z(U){let V=X;if(X=null,V)V(U);else if(U)H.destroy(U);else if(!G&&!$)H.destroy()}let Y=T[0],K=qO(T,Z),$=!!(DH(Y)||BH(Y)||VT(Y)),G=!!(RH(K)||qH(K)||VT(K));if(H=new VA({writableObjectMode:!!(Y!==null&&Y!==void 0&&Y.writableObjectMode),readableObjectMode:!!(K!==null&&K!==void 0&&K.readableObjectMode),writable:$,readable:G}),$){if(zA(Y))H._write=function(V,N,z){if(Y.write(V,N))z();else E=z},H._final=function(V){Y.end(),L=V},Y.on("drain",function(){if(E){let V=E;E=null,V()}});else if(AE(Y)){let N=(VT(Y)?Y.writable:Y).getWriter();H._write=async function(z,Q,F){try{await N.ready,N.write(z).catch(()=>{}),F()}catch(R){F(R)}},H._final=async function(z){try{await N.ready,N.close().catch(()=>{}),L=z}catch(Q){z(Q)}}}let U=VT(K)?K.readable:K;xO(U,()=>{if(L){let V=L;L=null,V()}})}if(G){if(zA(K))K.on("readable",function(){if(J){let U=J;J=null,U()}}),K.on("end",function(){H.push(null)}),H._read=function(){while(!0){let U=K.read();if(U===null){J=H._read;return}if(!H.push(U))return}};else if(AE(K)){let V=(VT(K)?K.readable:K).getReader();H._read=async function(){while(!0)try{let{value:N,done:z}=await V.read();if(!H.push(N))return;if(z){H.push(null);return}}catch{return}}}}return H._destroy=function(U,V){if(!U&&X!==null)U=new PO;if(J=null,E=null,L=null,X===null)V(U);else if(X=V,zA(K))IO(K,U)},H}});var gH=W((LR,JE)=>{var wO=globalThis.AbortController||I("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:SO,ERR_INVALID_ARG_TYPE:u4,ERR_MISSING_ARGS:yO,ERR_OUT_OF_RANGE:vO},AbortError:J0}=l_(),{validateAbortSignal:zT,validateInteger:jH,validateObject:FT}=pT(),hO=z_().Symbol("kWeak"),kO=z_().Symbol("kResistStopPropagation"),{finished:fO}=q0(),bO=EE(),{addAbortSignalNoValidate:gO}=w4(),{isWritable:mO,isNodeStream:uO}=T0(),{deprecate:dO}=s_(),{ArrayPrototypePush:cO,Boolean:pO,MathFloor:xH,Number:lO,NumberIsNaN:nO,Promise:wH,PromiseReject:SH,PromiseResolve:iO,PromisePrototypeThen:yH,Symbol:hH}=z_(),FA=hH("kEmpty"),vH=hH("kEof");function aO(_,T){if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");if(uO(_)&&!mO(_))throw new SO("stream",_,"must be writable");let A=bO(this,_);if(T!==null&&T!==void 0&&T.signal)gO(T.signal,A);return A}function CA(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");let A=1;if((T===null||T===void 0?void 0:T.concurrency)!=null)A=xH(T.concurrency);let E=A-1;if((T===null||T===void 0?void 0:T.highWaterMark)!=null)E=xH(T.highWaterMark);return jH(A,"options.concurrency",1),jH(E,"options.highWaterMark",0),E+=A,async function*(){let J=s_().AbortSignalAny([T===null||T===void 0?void 0:T.signal].filter(pO)),X=this,H=[],Z={signal:J},Y,K,$=!1,G=0;function U(){$=!0,V()}function V(){G-=1,N()}function N(){if(K&&!$&&G<A&&H.length<E)K(),K=null}async function z(){try{for await(let Q of X){if($)return;if(J.aborted)throw new J0;try{if(Q=_(Q,Z),Q===FA)continue;Q=iO(Q)}catch(F){Q=SH(F)}if(G+=1,yH(Q,V,U),H.push(Q),Y)Y(),Y=null;if(!$&&(H.length>=E||G>=A))await new wH((F)=>{K=F})}H.push(vH)}catch(Q){let F=SH(Q);yH(F,V,U),H.push(F)}finally{if($=!0,Y)Y(),Y=null}}z();try{while(!0){while(H.length>0){let Q=await H[0];if(Q===vH)return;if(J.aborted)throw new J0;if(Q!==FA)yield Q;H.shift(),N()}await new wH((Q)=>{Y=Q})}}finally{if($=!0,K)K(),K=null}}.call(this)}function oO(_=void 0){if(_!=null)FT(_,"options");if((_===null||_===void 0?void 0:_.signal)!=null)zT(_.signal,"options.signal");return async function*(){let A=0;for await(let L of this){var E;if(_!==null&&_!==void 0&&(E=_.signal)!==null&&E!==void 0&&E.aborted)throw new J0({cause:_.signal.reason});yield[A++,L]}}.call(this)}async function kH(_,T=void 0){for await(let A of LE.call(this,_,T))return!0;return!1}async function rO(_,T=void 0){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);return!await kH.call(this,async(...A)=>{return!await _(...A)},T)}async function sO(_,T){for await(let A of LE.call(this,_,T))return A;return}async function tO(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){return await _(E,L),FA}for await(let E of CA.call(this,A,T));}function LE(_,T){if(typeof _!=="function")throw new u4("fn",["Function","AsyncFunction"],_);async function A(E,L){if(await _(E,L))return E;return FA}return CA.call(this,A,T)}class fH extends yO{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function eO(_,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 fO(this.destroy(Y)),Y}let J=new wO,X=J.signal;if(A!==null&&A!==void 0&&A.signal){let Y={once:!0,[hO]:this,[kO]:!0};A.signal.addEventListener("abort",()=>J.abort(),Y)}let H=!1;try{for await(let Y of this){var Z;if(H=!0,A!==null&&A!==void 0&&(Z=A.signal)!==null&&Z!==void 0&&Z.aborted)throw new J0;if(!L)T=Y,L=!0;else T=await _(T,Y,{signal:X})}if(!H&&!L)throw new fH}finally{J.abort()}return T}async function _R(_){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});cO(T,E)}return T}function TR(_,T){let A=CA.call(this,_,T);return async function*(){for await(let L of A)yield*L}.call(this)}function bH(_){if(_=lO(_),nO(_))return 0;if(_<0)throw new vO("number",">= 0",_);return _}function AR(_,T=void 0){if(T!=null)FT(T,"options");if((T===null||T===void 0?void 0:T.signal)!=null)zT(T.signal,"options.signal");return _=bH(_),async function*(){var E;if(T!==null&&T!==void 0&&(E=T.signal)!==null&&E!==void 0&&E.aborted)throw new J0;for await(let J of this){var L;if(T!==null&&T!==void 0&&(L=T.signal)!==null&&L!==void 0&&L.aborted)throw new J0;if(_--<=0)yield J}}.call(this)}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 _=bH(_),async function*(){var E;if(T!==null&&T!==void 0&&(E=T.signal)!==null&&E!==void 0&&E.aborted)throw new J0;for await(let J of this){var L;if(T!==null&&T!==void 0&&(L=T.signal)!==null&&L!==void 0&&L.aborted)throw new J0;if(_-- >0)yield J;if(_<=0)return}}.call(this)}LR.streamReturningOperators={asIndexedPairs:dO(oO,"readable.asIndexedPairs will be removed in a future version."),drop:AR,filter:LE,flatMap:TR,map:CA,take:ER,compose:aO};LR.promiseReturningOperators={every:rO,forEach:tO,reduce:eO,toArray:_R,some:kH,find:sO}});var XE=W((yf,mH)=>{var{ArrayPrototypePop:HR,Promise:ZR}=z_(),{isIterable:YR,isNodeStream:KR,isWebStream:$R}=T0(),{pipelineImpl:GR}=MA(),{finished:UR}=q0();HE();function WR(..._){return new ZR((T,A)=>{let E,L,J=_[_.length-1];if(J&&typeof J==="object"&&!KR(J)&&!YR(J)&&!$R(J)){let X=HR(_);E=X.signal,L=X.end}GR(_,(X,H)=>{if(X)A(X);else T(H)},{signal:E,end:L})})}mH.exports={finished:UR,pipeline:WR}});var HE=W((vf,oH)=>{var{Buffer:NR}=I("buffer"),{ObjectDefineProperty:j0,ObjectKeys:cH,ReflectApply:pH}=z_(),{promisify:{custom:lH}}=s_(),{streamReturningOperators:uH,promiseReturningOperators:dH}=gH(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:nH}}=l_(),QR=EE(),{setDefaultHighWaterMark:MR,getDefaultHighWaterMark:VR}=S4(),{pipeline:iH}=MA(),{destroyer:zR}=GT(),aH=q0(),ZE=XE(),d4=T0(),V_=oH.exports=_A().Stream;V_.isDestroyed=d4.isDestroyed;V_.isDisturbed=d4.isDisturbed;V_.isErrored=d4.isErrored;V_.isReadable=d4.isReadable;V_.isWritable=d4.isWritable;V_.Readable=h4();for(let _ of cH(uH)){let A=function(...E){if(new.target)throw nH();return V_.Readable.from(pH(T,this,E))},T=uH[_];j0(A,"name",{__proto__:null,value:T.name}),j0(A,"length",{__proto__:null,value:T.length}),j0(V_.Readable.prototype,_,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}for(let _ of cH(dH)){let A=function(...E){if(new.target)throw nH();return pH(T,this,E)},T=dH[_];j0(A,"name",{__proto__:null,value:T.name}),j0(A,"length",{__proto__:null,value:T.length}),j0(V_.Readable.prototype,_,{__proto__:null,value:A,enumerable:!1,configurable:!0,writable:!0})}V_.Writable=UA();V_.Duplex=L0();V_.Transform=p6();V_.PassThrough=n6();V_.pipeline=iH;var{addAbortSignal:FR}=w4();V_.addAbortSignal=FR;V_.finished=aH;V_.destroy=zR;V_.compose=QR;V_.setDefaultHighWaterMark=MR;V_.getDefaultHighWaterMark=VR;j0(V_,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return ZE}});j0(iH,lH,{__proto__:null,enumerable:!0,get(){return ZE.pipeline}});j0(aH,lH,{__proto__:null,enumerable:!0,get(){return ZE.finished}});V_.Stream=V_;V_._isUint8Array=function(T){return T instanceof Uint8Array};V_._uint8ArrayToBuffer=function(T){return NR.from(T.buffer,T.byteOffset,T.byteLength)}});var n0=W((hf,__)=>{var S_=I("stream");if(S_&&process.env.READABLE_STREAM==="disable"){let _=S_.promises;__.exports._uint8ArrayToBuffer=S_._uint8ArrayToBuffer,__.exports._isUint8Array=S_._isUint8Array,__.exports.isDisturbed=S_.isDisturbed,__.exports.isErrored=S_.isErrored,__.exports.isReadable=S_.isReadable,__.exports.Readable=S_.Readable,__.exports.Writable=S_.Writable,__.exports.Duplex=S_.Duplex,__.exports.Transform=S_.Transform,__.exports.PassThrough=S_.PassThrough,__.exports.addAbortSignal=S_.addAbortSignal,__.exports.finished=S_.finished,__.exports.destroy=S_.destroy,__.exports.pipeline=S_.pipeline,__.exports.compose=S_.compose,Object.defineProperty(S_,"promises",{configurable:!0,enumerable:!0,get(){return _}}),__.exports.Stream=S_.Stream}else{let _=HE(),T=XE(),A=_.Readable.destroy;__.exports=_.Readable,__.exports._uint8ArrayToBuffer=_._uint8ArrayToBuffer,__.exports._isUint8Array=_._isUint8Array,__.exports.isDisturbed=_.isDisturbed,__.exports.isErrored=_.isErrored,__.exports.isReadable=_.isReadable,__.exports.Readable=_.Readable,__.exports.Writable=_.Writable,__.exports.Duplex=_.Duplex,__.exports.Transform=_.Transform,__.exports.PassThrough=_.PassThrough,__.exports.addAbortSignal=_.addAbortSignal,__.exports.finished=_.finished,__.exports.destroy=_.destroy,__.exports.destroy=A,__.exports.pipeline=_.pipeline,__.exports.compose=_.compose,Object.defineProperty(_,"promises",{configurable:!0,enumerable:!0,get(){return T}}),__.exports.Stream=_.Stream}__.exports.default=__.exports});var rH=W((ef,YE)=>{if(typeof Object.create==="function")YE.exports=function(T,A){if(A)T.super_=A,T.prototype=Object.create(A.prototype,{constructor:{value:T,enumerable:!1,writable:!0,configurable:!0}})};else YE.exports=function(T,A){if(A){T.super_=A;var E=function(){};E.prototype=A.prototype,T.prototype=new E,T.prototype.constructor=T}}});var sH=W((_b,KE)=>{try{if(OA=I("util"),typeof OA.inherits!=="function")throw"";KE.exports=OA.inherits}catch(_){KE.exports=rH()}var OA});var _Z=W((Tb,eH)=>{var{Buffer:u1}=I("buffer"),tH=Symbol.for("BufferList");function H_(_){if(!(this instanceof H_))return new H_(_);H_._init.call(this,_)}H_._init=function(T){if(Object.defineProperty(this,tH,{value:!0}),this._bufs=[],this.length=0,T)this.append(T)};H_.prototype._new=function(T){return new H_(T)};H_.prototype._offset=function(T){if(T===0)return[0,0];let A=0;for(let E=0;E<this._bufs.length;E++){let L=A+this._bufs[E].length;if(T<L||E===this._bufs.length-1)return[E,T-A];A=L}};H_.prototype._reverseOffset=function(_){let T=_[0],A=_[1];for(let E=0;E<T;E++)A+=this._bufs[E].length;return A};H_.prototype.getBuffers=function(){return this._bufs};H_.prototype.get=function(T){if(T>this.length||T<0)return;let A=this._offset(T);return this._bufs[A[0]][A[1]]};H_.prototype.slice=function(T,A){if(typeof T==="number"&&T<0)T+=this.length;if(typeof A==="number"&&A<0)A+=this.length;return this.copy(null,0,T,A)};H_.prototype.copy=function(T,A,E,L){if(typeof E!=="number"||E<0)E=0;if(typeof L!=="number"||L>this.length)L=this.length;if(E>=this.length)return T||u1.alloc(0);if(L<=0)return T||u1.alloc(0);let J=!!T,X=this._offset(E),H=L-E,Z=H,Y=J&&A||0,K=X[1];if(E===0&&L===this.length){if(!J)return this._bufs.length===1?this._bufs[0]:u1.concat(this._bufs,this.length);for(let $=0;$<this._bufs.length;$++)this._bufs[$].copy(T,Y),Y+=this._bufs[$].length;return T}if(Z<=this._bufs[X[0]].length-K)return J?this._bufs[X[0]].copy(T,A,K,K+Z):this._bufs[X[0]].slice(K,K+Z);if(!J)T=u1.allocUnsafe(H);for(let $=X[0];$<this._bufs.length;$++){let G=this._bufs[$].length-K;if(Z>G)this._bufs[$].copy(T,Y,K),Y+=G;else{this._bufs[$].copy(T,Y,K,K+Z),Y+=G;break}if(Z-=G,K)K=0}if(T.length>Y)return T.slice(0,Y);return T};H_.prototype.shallowSlice=function(T,A){if(T=T||0,A=typeof A!=="number"?this.length:A,T<0)T+=this.length;if(A<0)A+=this.length;if(T===A)return this._new();let E=this._offset(T),L=this._offset(A),J=this._bufs.slice(E[0],L[0]+1);if(L[1]===0)J.pop();else J[J.length-1]=J[J.length-1].slice(0,L[1]);if(E[1]!==0)J[0]=J[0].slice(E[1]);return this._new(J)};H_.prototype.toString=function(T,A,E){return this.slice(A,E).toString(T)};H_.prototype.consume=function(T){if(T=Math.trunc(T),Number.isNaN(T)||T<=0)return this;while(this._bufs.length)if(T>=this._bufs[0].length)T-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(T),this.length-=T;break}return this};H_.prototype.duplicate=function(){let T=this._new();for(let A=0;A<this._bufs.length;A++)T.append(this._bufs[A]);return T};H_.prototype.append=function(T){return this._attach(T,H_.prototype._appendBuffer)};H_.prototype.prepend=function(T){return this._attach(T,H_.prototype._prependBuffer,!0)};H_.prototype._attach=function(T,A,E){if(T==null)return this;if(T.buffer)A.call(this,u1.from(T.buffer,T.byteOffset,T.byteLength));else if(Array.isArray(T)){let[L,J]=E?[T.length-1,-1]:[0,1];for(let X=L;X>=0&&X<T.length;X+=J)this._attach(T[X],A,E)}else if(this._isBufferList(T)){let[L,J]=E?[T._bufs.length-1,-1]:[0,1];for(let X=L;X>=0&&X<T._bufs.length;X+=J)this._attach(T._bufs[X],A,E)}else{if(typeof T==="number")T=T.toString();A.call(this,u1.from(T))}return this};H_.prototype._appendBuffer=function(T){this._bufs.push(T),this.length+=T.length};H_.prototype._prependBuffer=function(T){this._bufs.unshift(T),this.length+=T.length};H_.prototype.indexOf=function(_,T,A){if(A===void 0&&typeof T==="string")A=T,T=void 0;if(typeof _==="function"||Array.isArray(_))throw TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');else if(typeof _==="number")_=u1.from([_]);else if(typeof _==="string")_=u1.from(_,A);else if(this._isBufferList(_))_=_.slice();else if(Array.isArray(_.buffer))_=u1.from(_.buffer,_.byteOffset,_.byteLength);else if(!u1.isBuffer(_))_=u1.from(_);if(T=Number(T||0),isNaN(T))T=0;if(T<0)T=this.length+T;if(T<0)T=0;if(_.length===0)return T>this.length?this.length:T;let E=this._offset(T),L=E[0],J=E[1];for(;L<this._bufs.length;L++){let X=this._bufs[L];while(J<X.length)if(X.length-J>=_.length){let Z=X.indexOf(_,J);if(Z!==-1)return this._reverseOffset([L,Z]);J=X.length-_.length+1}else{let Z=this._reverseOffset([L,J]);if(this._match(Z,_))return Z;J++}J=0}return-1};H_.prototype._match=function(_,T){if(this.length-_<T.length)return!1;for(let A=0;A<T.length;A++)if(this.get(_+A)!==T[A])return!1;return!0};(function(){let _={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let T in _)(function(A){if(_[A]===null)H_.prototype[A]=function(E,L){return this.slice(E,E+L)[A](0,L)};else H_.prototype[A]=function(E=0){return this.slice(E,E+_[A])[A](0)}})(T)})();H_.prototype._isBufferList=function(T){return T instanceof H_||H_.isBufferList(T)};H_.isBufferList=function(T){return T!=null&&T[tH]};eH.exports=H_});var TZ=W((Ab,RA)=>{var $E=n0().Duplex,CR=sH(),c4=_Z();function i_(_){if(!(this instanceof i_))return new i_(_);if(typeof _==="function"){this._callback=_;let T=function(E){if(this._callback)this._callback(E),this._callback=null}.bind(this);this.on("pipe",function(E){E.on("error",T)}),this.on("unpipe",function(E){E.removeListener("error",T)}),_=null}c4._init.call(this,_),$E.call(this)}CR(i_,$E);Object.assign(i_.prototype,c4.prototype);i_.prototype._new=function(T){return new i_(T)};i_.prototype._write=function(T,A,E){if(this._appendBuffer(T),typeof E==="function")E()};i_.prototype._read=function(T){if(!this.length)return this.push(null);T=Math.min(T,this.length),this.push(this.slice(0,T)),this.consume(T)};i_.prototype.end=function(T){if($E.prototype.end.call(this,T),this._callback)this._callback(null,this.slice()),this._callback=null};i_.prototype._destroy=function(T,A){this._bufs.length=0,this.length=0,A(T)};i_.prototype._isBufferList=function(T){return T instanceof i_||T instanceof c4||i_.isBufferList(T)};i_.isBufferList=c4.isBufferList;RA.exports=i_;RA.exports.BufferListStream=i_;RA.exports.BufferList=c4});var LZ=W((Eb,EZ)=>{class AZ{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}EZ.exports=AZ});var GE=W((Lb,JZ)=>{var x=Lb,{Buffer:X1}=I("buffer");x.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};x.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0};x.requiredHeaderFlagsErrors={};for(let _ in x.requiredHeaderFlags){let T=x.requiredHeaderFlags[_];x.requiredHeaderFlagsErrors[_]="Invalid header flag bits, must be 0x"+T.toString(16)+" for "+x.types[_]+" packet"}x.codes={};for(let _ in x.types){let T=x.types[_];x.codes[T]=_}x.CMD_SHIFT=4;x.CMD_MASK=240;x.DUP_MASK=8;x.QOS_MASK=3;x.QOS_SHIFT=1;x.RETAIN_MASK=1;x.VARBYTEINT_MASK=127;x.VARBYTEINT_FIN_MASK=128;x.VARBYTEINT_MAX=268435455;x.SESSIONPRESENT_MASK=1;x.SESSIONPRESENT_HEADER=X1.from([x.SESSIONPRESENT_MASK]);x.CONNACK_HEADER=X1.from([x.codes.connack<<x.CMD_SHIFT]);x.USERNAME_MASK=128;x.PASSWORD_MASK=64;x.WILL_RETAIN_MASK=32;x.WILL_QOS_MASK=24;x.WILL_QOS_SHIFT=3;x.WILL_FLAG_MASK=4;x.CLEAN_SESSION_MASK=2;x.CONNECT_HEADER=X1.from([x.codes.connect<<x.CMD_SHIFT]);x.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11};x.propertiesCodes={};for(let _ in x.properties){let T=x.properties[_];x.propertiesCodes[T]=_}x.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function i0(_){return[0,1,2].map((T)=>{return[0,1].map((A)=>{return[0,1].map((E)=>{let L=X1.alloc(1);return L.writeUInt8(x.codes[_]<<x.CMD_SHIFT|(A?x.DUP_MASK:0)|T<<x.QOS_SHIFT|E,0,!0),L})})})}x.PUBLISH_HEADER=i0("publish");x.SUBSCRIBE_HEADER=i0("subscribe");x.SUBSCRIBE_OPTIONS_QOS_MASK=3;x.SUBSCRIBE_OPTIONS_NL_MASK=1;x.SUBSCRIBE_OPTIONS_NL_SHIFT=2;x.SUBSCRIBE_OPTIONS_RAP_MASK=1;x.SUBSCRIBE_OPTIONS_RAP_SHIFT=3;x.SUBSCRIBE_OPTIONS_RH_MASK=3;x.SUBSCRIBE_OPTIONS_RH_SHIFT=4;x.SUBSCRIBE_OPTIONS_RH=[0,16,32];x.SUBSCRIBE_OPTIONS_NL=4;x.SUBSCRIBE_OPTIONS_RAP=8;x.SUBSCRIBE_OPTIONS_QOS=[0,1,2];x.UNSUBSCRIBE_HEADER=i0("unsubscribe");x.ACKS={unsuback:i0("unsuback"),puback:i0("puback"),pubcomp:i0("pubcomp"),pubrel:i0("pubrel"),pubrec:i0("pubrec")};x.SUBACK_HEADER=X1.from([x.codes.suback<<x.CMD_SHIFT]);x.VERSION3=X1.from([3]);x.VERSION4=X1.from([4]);x.VERSION5=X1.from([5]);x.VERSION131=X1.from([131]);x.VERSION132=X1.from([132]);x.QOS=[0,1,2].map((_)=>{return X1.from([_])});x.EMPTY={pingreq:X1.from([x.codes.pingreq<<4,0]),pingresp:X1.from([x.codes.pingresp<<4,0]),disconnect:X1.from([x.codes.disconnect<<4,0])};x.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"};x.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"};x.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};x.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"};x.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};x.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}});var HZ=W((Jb,XZ)=>{var T4=1000,A4=T4*60,E4=A4*60,CT=E4*24,OR=CT*7,RR=CT*365.25;XZ.exports=function(_,T){T=T||{};var A=typeof _;if(A==="string"&&_.length>0)return DR(_);else if(A==="number"&&isFinite(_))return T.long?qR(_):BR(_);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(_))};function DR(_){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*RR;case"weeks":case"week":case"w":return A*OR;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 BR(_){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 qR(_){var T=Math.abs(_);if(T>=CT)return DA(_,T,CT,"day");if(T>=E4)return DA(_,T,E4,"hour");if(T>=A4)return DA(_,T,A4,"minute");if(T>=T4)return DA(_,T,T4,"second");return _+" ms"}function DA(_,T,A,E){var L=T>=A*1.5;return Math.round(_/A)+" "+E+(L?"s":"")}});var UE=W((Xb,ZZ)=>{function IR(_){A.debug=A,A.default=A,A.coerce=Z,A.disable=X,A.enable=L,A.enabled=H,A.humanize=HZ(),A.destroy=Y,Object.keys(_).forEach((K)=>{A[K]=_[K]}),A.names=[],A.skips=[],A.formatters={};function T(K){let $=0;for(let G=0;G<K.length;G++)$=($<<5)-$+K.charCodeAt(G),$|=0;return A.colors[Math.abs($)%A.colors.length]}A.selectColor=T;function A(K){let $,G=null,U,V;function N(...z){if(!N.enabled)return;let Q=N,F=Number(new Date),R=F-($||F);if(Q.diff=R,Q.prev=$,Q.curr=F,$=F,z[0]=A.coerce(z[0]),typeof z[0]!=="string")z.unshift("%O");let q=0;z[0]=z[0].replace(/%([a-zA-Z%])/g,(h,b)=>{if(h==="%%")return"%";q++;let l=A.formatters[b];if(typeof l==="function"){let c=z[q];h=l.call(Q,c),z.splice(q,1),q--}return h}),A.formatArgs.call(Q,z),(Q.log||A.log).apply(Q,z)}if(N.namespace=K,N.useColors=A.useColors(),N.color=A.selectColor(K),N.extend=E,N.destroy=A.destroy,Object.defineProperty(N,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(G!==null)return G;if(U!==A.namespaces)U=A.namespaces,V=A.enabled(K);return V},set:(z)=>{G=z}}),typeof A.init==="function")A.init(N);return N}function E(K,$){let G=A(this.namespace+(typeof $>"u"?":":$)+K);return G.log=this.log,G}function L(K){A.save(K),A.namespaces=K,A.names=[],A.skips=[];let $=(typeof K==="string"?K:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let G of $)if(G[0]==="-")A.skips.push(G.slice(1));else A.names.push(G)}function J(K,$){let G=0,U=0,V=-1,N=0;while(G<K.length)if(U<$.length&&($[U]===K[G]||$[U]==="*"))if($[U]==="*")V=U,N=G,U++;else G++,U++;else if(V!==-1)U=V+1,N++,G=N;else return!1;while(U<$.length&&$[U]==="*")U++;return U===$.length}function X(){let K=[...A.names,...A.skips.map(($)=>"-"+$)].join(",");return A.enable(""),K}function H(K){for(let $ of A.skips)if(J(K,$))return!1;for(let $ of A.names)if(J(K,$))return!0;return!1}function Z(K){if(K instanceof Error)return K.stack||K.message;return K}function Y(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return A.enable(A.load()),A}ZZ.exports=IR});var KZ=W((YZ,BA)=>{YZ.formatArgs=jR;YZ.save=xR;YZ.load=wR;YZ.useColors=PR;YZ.storage=SR();YZ.destroy=(()=>{let _=!1;return()=>{if(!_)_=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();YZ.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function PR(){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 jR(_){if(_[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+_[0]+(this.useColors?"%c ":" ")+"+"+BA.exports.humanize(this.diff),!this.useColors)return;let T="color: "+this.color;_.splice(1,0,T,"color: inherit");let A=0,E=0;_[0].replace(/%[a-zA-Z%]/g,(L)=>{if(L==="%%")return;if(A++,L==="%c")E=A}),_.splice(E,0,T)}YZ.log=console.debug||console.log||(()=>{});function xR(_){try{if(_)YZ.storage.setItem("debug",_);else YZ.storage.removeItem("debug")}catch(T){}}function wR(){let _;try{_=YZ.storage.getItem("debug")||YZ.storage.getItem("DEBUG")}catch(T){}if(!_&&typeof process<"u"&&"env"in process)_=process.env.DEBUG;return _}function SR(){try{return localStorage}catch(_){}}BA.exports=UE()(YZ);var{formatters:yR}=BA.exports;yR.j=function(_){try{return JSON.stringify(_)}catch(T){return"[UnexpectedJSONParseError]: "+T.message}}});var WZ=W((GZ,IA)=>{var uR=I("tty"),qA=I("util");GZ.init=aR;GZ.log=lR;GZ.formatArgs=cR;GZ.save=nR;GZ.load=iR;GZ.useColors=dR;GZ.destroy=qA.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");GZ.colors=[6,2,3,4,5,1];try{let _=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(_&&(_.stderr||_).level>=2)GZ.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(_){}GZ.inspectOpts=Object.keys(process.env).filter((_)=>{return/^debug_/i.test(_)}).reduce((_,T)=>{let A=T.substring(6).toLowerCase().replace(/_([a-z])/g,(L,J)=>{return J.toUpperCase()}),E=process.env[T];if(/^(yes|on|true|enabled)$/i.test(E))E=!0;else if(/^(no|off|false|disabled)$/i.test(E))E=!1;else if(E==="null")E=null;else E=Number(E);return _[A]=E,_},{});function dR(){return"colors"in GZ.inspectOpts?Boolean(GZ.inspectOpts.colors):uR.isatty(process.stderr.fd)}function cR(_){let{namespace:T,useColors:A}=this;if(A){let E=this.color,L="\x1B[3"+(E<8?E:"8;5;"+E),J=` ${L};1m${T} \x1B[0m`;_[0]=J+_[0].split(`
|
|
4
4
|
`).join(`
|
|
5
|
-
`+J),_.push(L+"m+"+IA.exports.humanize(this.diff)+"\x1B[0m")}else _[0]=
|
|
6
|
-
`)}function
|
|
7
|
-
`).map((T)=>T.trim()).join(" ")};H2.O=function(_){return this.inspectOpts.colors=this.useColors,qA.inspect(_,this.inspectOpts)}});var u1=W((Eb,$E)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)$E.exports=X2();else $E.exports=K2()});var U2=W((Lb,$2)=>{var eR=sH(),{EventEmitter:_D}=j("events"),G2=_2(),E_=KE(),n=u1()("mqtt-packet:parser");class PA extends _D{constructor(){super();this.parser=this.constructor.parser}static parser(_){if(!(this instanceof PA))return new PA().parser(_);return this.settings=_||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this}_resetState(){n("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new G2,this.error=null,this._list=eR(),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 G2,this._pos=0,!0}_emitError(_){n("_emitError",_),this.error=_,this.emit("error",_)}}$2.exports=PA});var M2=W((Jb,Q2)=>{var{Buffer:l4}=j("buffer"),W2={},TD=l4.isBuffer(l4.from([1,2]).subarray(0,1));function N2(_){let T=l4.allocUnsafe(2);return T.writeUInt8(_>>8,0),T.writeUInt8(_&255,1),T}function AD(){for(let _=0;_<65536;_++)W2[_]=N2(_)}function ED(_){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 TD?L.subarray(0,E):L.slice(0,E)}function LD(_){let T=l4.allocUnsafe(4);return T.writeUInt32BE(_,0),T}Q2.exports={cache:W2,generateCache:AD,generateNumber:N2,genBufVariableByteInt:ED,generate4ByteBuffer:LD}});var V2=W((Xb,UE)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)UE.exports={nextTick:JD};else UE.exports=process;function JD(_,T,A,E){if(typeof _!=="function")throw TypeError('"callback" argument must be a function');var L=arguments.length,J,X;switch(L){case 0:case 1:return process.nextTick(_);case 2:return process.nextTick(function(){_.call(null,T)});case 3:return process.nextTick(function(){_.call(null,T,A)});case 4:return process.nextTick(function(){_.call(null,T,A,E)});default:J=Array(L-1),X=0;while(X<J.length)J[X++]=arguments[X];return process.nextTick(function(){_.apply(null,J)})}}});var QE=W((Hb,q2)=>{var i=KE(),{Buffer:p}=j("buffer"),XD=p.allocUnsafe(0),HD=p.from([0]),n4=M2(),ZD=V2().nextTick,O1=u1()("mqtt-packet:writeToStream"),jA=n4.cache,YD=n4.generateNumber,KD=n4.generateCache,WE=n4.genBufVariableByteInt,GD=n4.generate4ByteBuffer,t_=NE,xA=!0;function D2(_,T,A){if(O1("generate called"),T.cork)T.cork(),ZD($D,T);if(xA)xA=!1,KD();switch(O1("generate: packet.cmd: %s",_.cmd),_.cmd){case"connect":return UD(_,T,A);case"connack":return WD(_,T,A);case"publish":return ND(_,T,A);case"puback":case"pubrec":case"pubrel":case"pubcomp":return QD(_,T,A);case"subscribe":return MD(_,T,A);case"suback":return VD(_,T,A);case"unsubscribe":return zD(_,T,A);case"unsuback":return FD(_,T,A);case"pingreq":case"pingresp":return CD(_,T,A);case"disconnect":return OD(_,T,A);case"auth":return RD(_,T,A);default:return T.destroy(Error("Unknown command")),!1}}Object.defineProperty(D2,"cacheNumbers",{get(){return t_===NE},set(_){if(_){if(!jA||Object.keys(jA).length===0)xA=!0;t_=NE}else xA=!1,t_=DD}});function $D(_){_.uncork()}function UD(_,T,A){let E=_||{},L=E.protocolId||"MQTT",J=E.protocolVersion||4,X=E.will,H=E.clean,Z=E.keepalive||0,Y=E.clientId||"",K=E.username,G=E.password,$=E.properties;if(H===void 0)H=!0;let U=0;if(!L||typeof L!=="string"&&!p.isBuffer(L))return T.destroy(Error("Invalid protocolId")),!1;else U+=L.length+2;if(J!==3&&J!==4&&J!==5)return T.destroy(Error("Invalid protocol version")),!1;else U+=1;if((typeof Y==="string"||p.isBuffer(Y))&&(Y||J>=4)&&(Y||H))U+=p.byteLength(Y)+2;else{if(J<4)return T.destroy(Error("clientId must be supplied before 3.1.1")),!1;if(H*1===0)return T.destroy(Error("clientId must be given if cleanSession set to 0")),!1}if(typeof Z!=="number"||Z<0||Z>65535||Z%1!==0)return T.destroy(Error("Invalid keepalive")),!1;else U+=2;U+=1;let V,N;if(J===5){if(V=a0(T,$),!V)return!1;U+=V.length}if(X){if(typeof X!=="object")return T.destroy(Error("Invalid will")),!1;if(!X.topic||typeof X.topic!=="string")return T.destroy(Error("Invalid will topic")),!1;else U+=p.byteLength(X.topic)+2;if(U+=2,X.payload)if(X.payload.length>=0)if(typeof X.payload==="string")U+=p.byteLength(X.payload);else U+=X.payload.length;else return T.destroy(Error("Invalid will payload")),!1;if(N={},J===5){if(N=a0(T,X.properties),!N)return!1;U+=N.length}}let z=!1;if(K!=null)if(R2(K))z=!0,U+=p.byteLength(K)+2;else return T.destroy(Error("Invalid username")),!1;if(G!=null){if(!z)return T.destroy(Error("Username is required to use password")),!1;if(R2(G))U+=B2(G)+2;else return T.destroy(Error("Invalid password")),!1}if(T.write(i.CONNECT_HEADER),R1(T,U),L4(T,L),E.bridgeMode)J+=128;T.write(J===131?i.VERSION131:J===132?i.VERSION132:J===4?i.VERSION4:J===5?i.VERSION5:i.VERSION3);let Q=0;if(Q|=K!=null?i.USERNAME_MASK:0,Q|=G!=null?i.PASSWORD_MASK:0,Q|=X&&X.retain?i.WILL_RETAIN_MASK:0,Q|=X&&X.qos?X.qos<<i.WILL_QOS_SHIFT:0,Q|=X?i.WILL_FLAG_MASK:0,Q|=H?i.CLEAN_SESSION_MASK:0,T.write(p.from([Q])),t_(T,Z),J===5)V.write();if(L4(T,Y),X){if(J===5)N.write();OT(T,X.topic),L4(T,X.payload)}if(K!=null)L4(T,K);if(G!=null)L4(T,G);return!0}function WD(_,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:HD),T.write(p.from([J])),Z!=null)Z.write();return!0}function ND(_,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||XD,Y=L.messageId,K=L.properties,G=0;if(typeof H==="string")G+=p.byteLength(H)+2;else if(p.isBuffer(H))G+=H.length+2;else return T.destroy(Error("Invalid topic")),!1;if(!p.isBuffer(Z))G+=p.byteLength(Z);else G+=Z.length;if(J&&typeof Y!=="number")return T.destroy(Error("Invalid messageId")),!1;else if(J)G+=2;let $=null;if(E===5){if($=a0(T,K),!$)return!1;G+=$.length}if(T.write(i.PUBLISH_HEADER[J][L.dup?1:0][X?1:0]),R1(T,G),t_(T,B2(H)),T.write(H),J>0)t_(T,Y);if($!=null)$.write();return O1("publish: payload: %o",Z),T.write(Z)}function QD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.cmd||"puback",X=L.messageId,H=L.dup&&J==="pubrel"?i.DUP_MASK:0,Z=0,Y=L.reasonCode,K=L.properties,G=E===5?3:2;if(J==="pubrel")Z=1;if(typeof X!=="number")return T.destroy(Error("Invalid messageId")),!1;let $=null;if(E===5){if(typeof K==="object"){if($=i4(T,K,A,G),!$)return!1;G+=$.length}}if(T.write(i.ACKS[J][Z][H][0]),G===3)G+=Y!==0?1:-1;if(R1(T,G),t_(T,X),E===5&&G!==2)T.write(p.from([Y]));if($!==null)$.write();else if(G===4)T.write(p.from([0]));return!0}function MD(_,T,A){O1("subscribe: packet: ");let E=A?A.protocolVersion:4,L=_||{},J=L.dup?i.DUP_MASK:0,X=L.messageId,H=L.subscriptions,Z=L.properties,Y=0;if(typeof X!=="number")return T.destroy(Error("Invalid messageId")),!1;else Y+=2;let K=null;if(E===5){if(K=a0(T,Z),!K)return!1;Y+=K.length}if(typeof H==="object"&&H.length)for(let $=0;$<H.length;$+=1){let U=H[$].topic,V=H[$].qos;if(typeof U!=="string")return T.destroy(Error("Invalid subscriptions - invalid topic")),!1;if(typeof V!=="number")return T.destroy(Error("Invalid subscriptions - invalid qos")),!1;if(E===5){if(typeof(H[$].nl||!1)!=="boolean")return T.destroy(Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(H[$].rap||!1)!=="boolean")return T.destroy(Error("Invalid subscriptions - invalid Retain as Published")),!1;let Q=H[$].rh||0;if(typeof Q!=="number"||Q>2)return T.destroy(Error("Invalid subscriptions - invalid Retain Handling")),!1}Y+=p.byteLength(U)+2+1}else return T.destroy(Error("Invalid subscriptions")),!1;if(O1("subscribe: writing to stream: %o",i.SUBSCRIBE_HEADER),T.write(i.SUBSCRIBE_HEADER[1][J?1:0][0]),R1(T,Y),t_(T,X),K!==null)K.write();let G=!0;for(let $ of H){let{topic:U,qos:V}=$,N=+$.nl,z=+$.rap,Q=$.rh,F;if(OT(T,U),F=i.SUBSCRIBE_OPTIONS_QOS[V],E===5)F|=N?i.SUBSCRIBE_OPTIONS_NL:0,F|=z?i.SUBSCRIBE_OPTIONS_RAP:0,F|=Q?i.SUBSCRIBE_OPTIONS_RH[Q]:0;G=T.write(p.from([F]))}return G}function VD(_,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 zD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.messageId,X=L.dup?i.DUP_MASK:0,H=L.unsubscriptions,Z=L.properties,Y=0;if(typeof J!=="number")return T.destroy(Error("Invalid messageId")),!1;else Y+=2;if(typeof H==="object"&&H.length)for(let $=0;$<H.length;$+=1){if(typeof H[$]!=="string")return T.destroy(Error("Invalid unsubscriptions")),!1;Y+=p.byteLength(H[$])+2}else return T.destroy(Error("Invalid unsubscriptions")),!1;let K=null;if(E===5){if(K=a0(T,Z),!K)return!1;Y+=K.length}if(T.write(i.UNSUBSCRIBE_HEADER[1][X?1:0][0]),R1(T,Y),t_(T,J),K!==null)K.write();let G=!0;for(let $=0;$<H.length;$++)G=OT(T,H[$]);return G}function FD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.messageId,X=L.dup?i.DUP_MASK:0,H=L.granted,Z=L.properties,Y=L.cmd,K=0,G=2;if(typeof J!=="number")return T.destroy(Error("Invalid messageId")),!1;if(E===5)if(typeof H==="object"&&H.length)for(let U=0;U<H.length;U+=1){if(typeof H[U]!=="number")return T.destroy(Error("Invalid qos vector")),!1;G+=1}else return T.destroy(Error("Invalid qos vector")),!1;let $=null;if(E===5){if($=i4(T,Z,A,G),!$)return!1;G+=$.length}if(T.write(i.ACKS[Y][0][X][0]),R1(T,G),t_(T,J),$!==null)$.write();if(E===5)T.write(p.from(H));return!0}function CD(_,T,A){return T.write(i.EMPTY[_.cmd])}function OD(_,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 RD(_,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 z2={};function R1(_,T){if(T>i.VARBYTEINT_MAX)return _.destroy(Error(`Invalid variable byte integer: ${T}`)),!1;let A=z2[T];if(!A){if(A=WE(T),T<16384)z2[T]=A}return O1("writeVarByteInt: writing to stream: %o",A),_.write(A)}function OT(_,T){let A=p.byteLength(T);return t_(_,A),O1("writeString: %s",T),_.write(T,"utf8")}function F2(_,T,A){OT(_,T),OT(_,A)}function NE(_,T){return O1("writeNumberCached: number: %d",T),O1("writeNumberCached: %o",jA[T]),_.write(jA[T])}function DD(_,T){let A=YD(T);return O1("writeNumberGenerated: %o",A),_.write(A)}function BD(_,T){let A=GD(T);return O1("write4ByteNumber: %o",A),_.write(A)}function L4(_,T){if(typeof T==="string")OT(_,T);else if(T)t_(_,T.length),_.write(T);else t_(_,0)}function a0(_,T){if(typeof T!=="object"||T.length!=null)return{length:1,write(){O2(_,{},0)}};let A=0;function E(J,X){let H=i.propertiesTypes[J],Z=0;switch(H){case"byte":{if(typeof X!=="boolean")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=2;break}case"int8":{if(typeof X!=="number"||X<0||X>255)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=2;break}case"binary":{if(X&&X===null)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=1+p.byteLength(X)+2;break}case"int16":{if(typeof X!=="number"||X<0||X>65535)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=3;break}case"int32":{if(typeof X!=="number"||X<0||X>4294967295)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=5;break}case"var":{if(typeof X!=="number"||X<0||X>268435455)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=1+p.byteLength(WE(X));break}case"string":{if(typeof X!=="string")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=3+p.byteLength(X.toString());break}case"pair":{if(typeof X!=="object")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=Object.getOwnPropertyNames(X).reduce((Y,K)=>{let G=X[K];if(Array.isArray(G))Y+=G.reduce(($,U)=>{return $+=3+p.byteLength(K.toString())+2+p.byteLength(U.toString()),$},0);else Y+=3+p.byteLength(K.toString())+2+p.byteLength(X[K].toString());return Y},0);break}default:return _.destroy(Error(`Invalid property ${J}: ${X}`)),!1}return Z}if(T)for(let J in T){let X=0,H=0,Z=T[J];if(Z===void 0)continue;else if(Array.isArray(Z))for(let Y=0;Y<Z.length;Y++){if(H=E(J,Z[Y]),!H)return!1;X+=H}else{if(H=E(J,Z),!H)return!1;X=H}if(!X)return!1;A+=X}return{length:p.byteLength(WE(A))+A,write(){O2(_,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 C2(_,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]])),BD(_,A);break}case"var":{_.write(p.from([i.properties[T]])),R1(_,A);break}case"string":{_.write(p.from([i.properties[T]])),OT(_,A);break}case"pair":{Object.getOwnPropertyNames(A).forEach((L)=>{let J=A[L];if(Array.isArray(J))J.forEach((X)=>{_.write(p.from([i.properties[T]])),F2(_,L.toString(),X.toString())});else _.write(p.from([i.properties[T]])),F2(_,L.toString(),J.toString())});break}default:return _.destroy(Error(`Invalid property ${T} value: ${A}`)),!1}}function O2(_,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++)C2(_,E,L[J]);else C2(_,E,L)}}function B2(_){if(!_)return 0;else if(_ instanceof p)return _.length;else return p.byteLength(_)}function R2(_){return typeof _==="string"||_ instanceof p}q2.exports=D2});var x2=W((Zb,j2)=>{var qD=QE(),{EventEmitter:ID}=j("events"),{Buffer:I2}=j("buffer");function PD(_,T){let A=new P2;return qD(_,A,T),A.concat()}class P2 extends ID{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]=I2.byteLength(A[L]);_+=T[L]}let J=I2.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",_)}}j2.exports=PD});var wA=W((jD)=>{jD.parser=U2().parser;jD.generate=x2();jD.writeToStream=QE()});var y2=W((Kb,S2)=>{S2.exports=w2;function w2(_,T){if(_&&T)return w2(_)(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 k2=W((Gb,ME)=>{var v2=y2();ME.exports=v2(SA);ME.exports.strict=v2(h2);SA.proto=SA(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return SA(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return h2(this)},configurable:!0})});function SA(_){var T=function(){if(T.called)return T.value;return T.called=!0,T.value=_.apply(this,arguments)};return T.called=!1,T}function h2(_){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 g2=W(($b,b2)=>{var yD=k2(),vD=function(){},hD=global.Bare?queueMicrotask:process.nextTick.bind(process),kD=function(_){return _.setHeader&&typeof _.abort==="function"},fD=function(_){return _.stdio&&Array.isArray(_.stdio)&&_.stdio.length===3},f2=function(_,T,A){if(typeof T==="function")return f2(_,null,T);if(!T)T={};A=yD(A||vD);var{_writableState:E,_readableState:L}=_,J=T.readable||T.readable!==!1&&_.readable,X=T.writable||T.writable!==!1&&_.writable,H=!1,Z=function(){if(!_.writable)Y()},Y=function(){if(X=!1,!J)A.call(_)},K=function(){if(J=!1,!X)A.call(_)},G=function(z){A.call(_,z?Error("exited with error code: "+z):null)},$=function(z){A.call(_,z)},U=function(){hD(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(kD(_))if(_.on("complete",Y),_.on("abort",U),_.req)N();else _.on("request",N);else if(X&&!E)_.on("end",Z),_.on("close",Z);if(fD(_))_.on("exit",G);if(_.on("end",K),_.on("finish",Y),T.error!==!1)_.on("error",$);return _.on("close",U),function(){if(H=!0,_.removeListener("complete",Y),_.removeListener("abort",U),_.removeListener("request",N),_.req)_.req.removeListener("finish",Y);_.removeListener("end",Z),_.removeListener("close",Z),_.removeListener("finish",Y),_.removeListener("exit",G),_.removeListener("end",K),_.removeListener("error",$),_.removeListener("close",U)}};b2.exports=f2});var j0=W((Ub,m2)=>{var bD=wA();function gD(_,T,A){let E=null;if(_.connecting||_.connected)try{if(!bD.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,_)}m2.exports=gD});var VE=W((Wb,c2)=>{var u2=uT(),mD=j("util");function d2(_,T){if(u2.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}mD.inherits(d2,u2);c2.exports=d2});var n2=W((Nb,l2)=>{var uD=k8(),p2=[];function dD(_,T){if(Array.isArray(_))T=_,_=null;var A=uD(cD);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 cD(){this.list=p2,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=p2,_.count=0,_.release(_)}}}l2.exports=dD});var RT=W((Qb,i2)=>{var{Transform:pD,Writable:lD}=j("stream");function nD(_,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 iD(_){return new pD({objectMode:!0,transform:_})}function aD(_){return new lD({objectMode:!0,writev:function(T,A){_(T.map((E)=>E.chunk),A)}})}i2.exports={validateTopic:nD,through:iD,bulk:aD,$SYS_PREFIX:"$SYS/"}});var yA=W((Mb,e2)=>{var o2=n2(),r2=uT(),{through:oD}=RT(),{validateTopic:rD,$SYS_PREFIX:sD}=RT(),tD=j0(),eD=o2([s2,ZB,t2]),_B=o2([s2,t2]);function TB(_,T){this.cmd="suback",this.messageId=_.messageId,this.granted=T}function a2(_,T,A,E,L){this.qos=_,this.func=T,this.rh=A,this.rap=E,this.nl=L}function AB(_,T,A,E){this.client=_,this.packet=T,this.actions=A?_B:eD,this.finish=E,this.subState=[]}function EB(_,T,A,E,L,J){this.client=_,this.packet=T,this.granted=A,this.rh=E,this.rap=L,this.nl=J}function LB(_){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 JB(_,T,A,E){T.subscriptions=T.subscriptions.length===1?T.subscriptions:LB(T.subscriptions),_.broker._parallel(new AB(_,T,A,E),XB,T.subscriptions,A?E:KB)}function XB(_,T){let A=new EB(this.client,this.packet,_.qos,_.rh,_.rap,_.nl);this.subState.push(A),this.actions.call(A,_,T)}function s2(_,T){let A=rD(_.topic,"SUBSCRIBE");if(A)return T(A);let E=this.client;E.broker.authorizeSubscribe(E,_,T)}function HB(_){return function(A,E){if(A.topic.charCodeAt(0)===36)E();else _(A,E)}}function ZB(_,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 t2(_,T){if(!_||typeof _!=="object")return T();let A=this.client,E=A.broker,L=_.topic,J=_.qos,X=this.rh,H=this.rap,Z=this.nl,Y=J>0?A.deliverQoS:A.deliver0,K=Y;if(Y=function($,U){if($=new r2($,E),$.nl=Z,!H)$.retain=!1;K($,U)},YB(L))Y=HB(Y);if(A.closed||A.broker.closed)return;if(!A.subscriptions[L])A.subscriptions[L]=new a2(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 a2(J,Y,X,H,Z),E.subscribe(L,Y,T);else T()}function YB(_){let T=_.charCodeAt(0);return T===43||T===35}function KB(_){let T=this.finish;if(_)return T(_);let A=this.packet,E=this.client;if(A.messageId!==void 0)tD(E,new TB(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:sD+L.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:E.id,subs:J}),"utf8")},GB),X.length>0)L.persistence.createRetainedStreamCombi(X).pipe(oD(function(K,G,$){K=new r2({cmd:K.cmd,qos:K.qos,topic:K.topic,payload:K.payload,retain:!0},L),K.brokerId=null,E.deliverQoS(K,$)}))}function GB(){}e2.exports=JB});var FE=W((Vb,_Z)=>{var $B=j0(),{validateTopic:UB,$SYS_PREFIX:WB}=RT();function NB(_){this.cmd="unsuback",this.messageId=_.messageId}function QB(_,T,A){this.client=_,this.packet=T,this.finish=A}function MB(_,T,A){let E=_.broker,L=T.unsubscriptions,J;for(let X=0;X<L.length;X++)if(J=UB(L[X],"UNSUBSCRIBE"),J)return A(J);if(T.messageId!==void 0){if(_.clean)return zE(_,T,A);E.persistence.removeSubscriptions(_,L,function(X){if(X)return A(X);zE(_,T,A)})}else zE(_,T,A)}function zE(_,T,A){_.broker._parallel(new QB(_,T,A),VB,T.unsubscriptions,zB)}function VB(_,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 zB(_){let T=this.client;if(_){T.emit("error",_);return}let A=this.packet,E=this.finish;if(A.messageId!==void 0)$B(T,new NB(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:WB+T.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:T.id,subs:A.unsubscriptions}),"utf8")},FB)}function FB(){}_Z.exports=MB});var AZ=W((zb,TZ)=>{TZ.exports=function(){let T=process.hrtime();return Math.floor(T[0]*1000+T[1]/1e6)}});var LZ=W((Fb,EZ)=>{EZ.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var HZ=W((Cb,OE)=>{var vA=AZ(),{clearTimeout:JZ,setTimeout:XZ}=LZ();class CE{constructor(_,T,A){let E=this;this._started=vA(),this._rescheduled=0,this._scheduled=T,this._args=A,this._triggered=!1,this._timerWrapper=()=>{if(E._rescheduled>0)E._scheduled=E._rescheduled-(vA()-E._started),E._schedule(E._scheduled);else E._triggered=!0,_.apply(null,E._args)},this._timer=XZ(this._timerWrapper,T)}reschedule(_){if(!_)_=this._scheduled;let T=vA();if(T+_-(this._started+this._scheduled)<0)JZ(this._timer),this._schedule(_);else if(!this._triggered)this._started=T,this._rescheduled=_;else this._schedule(_)}_schedule(_){this._triggered=!1,this._started=vA(),this._rescheduled=0,this._scheduled=_,this._timer=XZ(this._timerWrapper,_)}clear(){JZ(this._timer)}}function CB(){if(typeof arguments[0]!=="function")throw Error("callback needed");if(typeof arguments[1]!=="number")throw Error("timeout needed");let _;if(arguments.length>0){_=Array(arguments.length-2);for(var T=0;T<_.length;T++)_[T]=arguments[T+2]}return new CE(arguments[0],arguments[1],_)}OE.exports=CB;OE.exports.Retimer=CE});var RE=W((ZZ)=>{Object.defineProperty(ZZ,"__esModule",{value:!0});ZZ.default=DB;var OB=RB(j("crypto"));function RB(_){return _&&_.__esModule?_:{default:_}}var kA=new Uint8Array(256),hA=kA.length;function DB(){if(hA>kA.length-16)OB.default.randomFillSync(kA),hA=0;return kA.slice(hA,hA+=16)}});var GZ=W((YZ)=>{Object.defineProperty(YZ,"__esModule",{value:!0});YZ.default=void 0;var qB=/^(?:[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;YZ.default=qB});var o4=W(($Z)=>{Object.defineProperty($Z,"__esModule",{value:!0});$Z.default=void 0;var IB=PB(GZ());function PB(_){return _&&_.__esModule?_:{default:_}}function jB(_){return typeof _==="string"&&IB.default.test(_)}var xB=jB;$Z.default=xB});var r4=W((WZ)=>{Object.defineProperty(WZ,"__esModule",{value:!0});WZ.default=void 0;var wB=SB(o4());function SB(_){return _&&_.__esModule?_:{default:_}}var m_=[];for(let _=0;_<256;++_)m_.push((_+256).toString(16).substr(1));function yB(_,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,wB.default)(A))throw TypeError("Stringified UUID is invalid");return A}var vB=yB;WZ.default=vB});var FZ=W((VZ)=>{Object.defineProperty(VZ,"__esModule",{value:!0});VZ.default=void 0;var hB=MZ(RE()),kB=MZ(r4());function MZ(_){return _&&_.__esModule?_:{default:_}}var QZ,DE,BE=0,qE=0;function fB(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let J=_.node||QZ,X=_.clockseq!==void 0?_.clockseq:DE;if(J==null||X==null){let $=_.random||(_.rng||hB.default)();if(J==null)J=QZ=[$[0]|1,$[1],$[2],$[3],$[4],$[5]];if(X==null)X=DE=($[6]<<8|$[7])&16383}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:qE+1,Y=H-BE+(Z-qE)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>BE)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");BE=H,qE=Z,DE=X,H+=12219292800000;let K=((H&268435455)*1e4+Z)%4294967296;L[E++]=K>>>24&255,L[E++]=K>>>16&255,L[E++]=K>>>8&255,L[E++]=K&255;let G=H/4294967296*1e4&268435455;L[E++]=G>>>8&255,L[E++]=G&255,L[E++]=G>>>24&15|16,L[E++]=G>>>16&255,L[E++]=X>>>8|128,L[E++]=X&255;for(let $=0;$<6;++$)L[E+$]=J[$];return T||(0,kB.default)(L)}var bB=fB;VZ.default=bB});var IE=W((CZ)=>{Object.defineProperty(CZ,"__esModule",{value:!0});CZ.default=void 0;var gB=mB(o4());function mB(_){return _&&_.__esModule?_:{default:_}}function uB(_){if(!(0,gB.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 dB=uB;CZ.default=dB});var PE=W((qZ)=>{Object.defineProperty(qZ,"__esModule",{value:!0});qZ.default=nB;qZ.URL=qZ.DNS=void 0;var cB=RZ(r4()),pB=RZ(IE());function RZ(_){return _&&_.__esModule?_:{default:_}}function lB(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var DZ="6ba7b810-9dad-11d1-80b4-00c04fd430c8";qZ.DNS=DZ;var BZ="6ba7b811-9dad-11d1-80b4-00c04fd430c8";qZ.URL=BZ;function nB(_,T,A){function E(L,J,X,H){if(typeof L==="string")L=lB(L);if(typeof J==="string")J=(0,pB.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,cB.default)(Z)}try{E.name=_}catch(L){}return E.DNS=DZ,E.URL=BZ,E}});var xZ=W((PZ)=>{Object.defineProperty(PZ,"__esModule",{value:!0});PZ.default=void 0;var oB=rB(j("crypto"));function rB(_){return _&&_.__esModule?_:{default:_}}function sB(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return oB.default.createHash("md5").update(_).digest()}var tB=sB;PZ.default=tB});var vZ=W((SZ)=>{Object.defineProperty(SZ,"__esModule",{value:!0});SZ.default=void 0;var eB=wZ(PE()),_q=wZ(xZ());function wZ(_){return _&&_.__esModule?_:{default:_}}var Tq=(0,eB.default)("v3",48,_q.default),Aq=Tq;SZ.default=Aq});var bZ=W((kZ)=>{Object.defineProperty(kZ,"__esModule",{value:!0});kZ.default=void 0;var Eq=hZ(RE()),Lq=hZ(r4());function hZ(_){return _&&_.__esModule?_:{default:_}}function Jq(_,T,A){_=_||{};let E=_.random||(_.rng||Eq.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,Lq.default)(E)}var Xq=Jq;kZ.default=Xq});var uZ=W((gZ)=>{Object.defineProperty(gZ,"__esModule",{value:!0});gZ.default=void 0;var Hq=Zq(j("crypto"));function Zq(_){return _&&_.__esModule?_:{default:_}}function Yq(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return Hq.default.createHash("sha1").update(_).digest()}var Kq=Yq;gZ.default=Kq});var lZ=W((cZ)=>{Object.defineProperty(cZ,"__esModule",{value:!0});cZ.default=void 0;var Gq=dZ(PE()),$q=dZ(uZ());function dZ(_){return _&&_.__esModule?_:{default:_}}var Uq=(0,Gq.default)("v5",80,$q.default),Wq=Uq;cZ.default=Wq});var aZ=W((nZ)=>{Object.defineProperty(nZ,"__esModule",{value:!0});nZ.default=void 0;var Nq="00000000-0000-0000-0000-000000000000";nZ.default=Nq});var sZ=W((oZ)=>{Object.defineProperty(oZ,"__esModule",{value:!0});oZ.default=void 0;var Qq=Mq(o4());function Mq(_){return _&&_.__esModule?_:{default:_}}function Vq(_){if(!(0,Qq.default)(_))throw TypeError("Invalid UUID");return parseInt(_.substr(14,1),16)}var zq=Vq;oZ.default=zq});var tZ=W((d1)=>{Object.defineProperty(d1,"__esModule",{value:!0});Object.defineProperty(d1,"v1",{enumerable:!0,get:function(){return Fq.default}});Object.defineProperty(d1,"v3",{enumerable:!0,get:function(){return Cq.default}});Object.defineProperty(d1,"v4",{enumerable:!0,get:function(){return Oq.default}});Object.defineProperty(d1,"v5",{enumerable:!0,get:function(){return Rq.default}});Object.defineProperty(d1,"NIL",{enumerable:!0,get:function(){return Dq.default}});Object.defineProperty(d1,"version",{enumerable:!0,get:function(){return Bq.default}});Object.defineProperty(d1,"validate",{enumerable:!0,get:function(){return qq.default}});Object.defineProperty(d1,"stringify",{enumerable:!0,get:function(){return Iq.default}});Object.defineProperty(d1,"parse",{enumerable:!0,get:function(){return Pq.default}});var Fq=x0(FZ()),Cq=x0(vZ()),Oq=x0(bZ()),Rq=x0(lZ()),Dq=x0(aZ()),Bq=x0(sZ()),qq=x0(o4()),Iq=x0(r4()),Pq=x0(IE());function x0(_){return _&&_.__esModule?_:{default:_}}});var TY=W((fb,_Y)=>{var jq=tZ(),eZ=j("crypto");_Y.exports=typeof eZ.randomUUID==="function"?eZ.randomUUID:jq.v4});var LY=W((bb,EY)=>{var jE=[],AY={};for(o0=0;o0<256;o0++)jE[o0]=(o0+256).toString(16).substr(1),AY[jE[o0]]=o0;var o0;function xq(_,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++]=AY[J]});while(L<16)T[E+L++]=0;return T}function wq(_,T){var A=T||0,E=jE;return E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]}EY.exports={parse:xq,unparse:wq}});var XY=W((gq)=>{gq.byteLength=yq;gq.toByteArray=hq;gq.fromByteArray=bq;var J0=[],D1=[],Sq=typeof Uint8Array<"u"?Uint8Array:Array,xE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(r0=0,wE=xE.length;r0<wE;++r0)J0[r0]=xE[r0],D1[xE.charCodeAt(r0)]=r0;var r0,wE;D1[45]=62;D1[95]=63;function JY(_){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 yq(_){var T=JY(_),A=T[0],E=T[1];return(A+E)*3/4-E}function vq(_,T,A){return(T+A)*3/4-A}function hq(_){var T,A=JY(_),E=A[0],L=A[1],J=new Sq(vq(_,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 kq(_){return J0[_>>18&63]+J0[_>>12&63]+J0[_>>6&63]+J0[_&63]}function fq(_,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(kq(E));return L.join("")}function bq(_){var T,A=_.length,E=A%3,L=[],J=16383;for(var X=0,H=A-E;X<H;X+=J)L.push(fq(_,X,X+J>H?H:X+J));if(E===1)T=_[A-1],L.push(J0[T>>2]+J0[T<<4&63]+"==");else if(E===2)T=(_[A-2]<<8)+_[A-1],L.push(J0[T>>10]+J0[T>>4&63]+J0[T<<2&63]+"=");return L.join("")}});var HY=W((cq)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */cq.read=function(_,T,A,E,L){var J,X,H=L*8-E-1,Z=(1<<H)-1,Y=Z>>1,K=-7,G=A?L-1:0,$=A?-1:1,U=_[T+G];G+=$,J=U&(1<<-K)-1,U>>=-K,K+=H;for(;K>0;J=J*256+_[T+G],G+=$,K-=8);X=J&(1<<-K)-1,J>>=-K,K+=E;for(;K>0;X=X*256+_[T+G],G+=$,K-=8);if(J===0)J=1-Y;else if(J===Z)return X?NaN:(U?-1:1)*(1/0);else X=X+Math.pow(2,E),J=J-Y;return(U?-1:1)*X*Math.pow(2,J-E)};cq.write=function(_,T,A,E,L,J){var X,H,Z,Y=J*8-L-1,K=(1<<Y)-1,G=K>>1,$=L===23?Math.pow(2,-24)-Math.pow(2,-77):0,U=E?0:J-1,V=E?1:-1,N=T<0||T===0&&1/T<0?1:0;if(T=Math.abs(T),isNaN(T)||T===1/0)H=isNaN(T)?1:0,X=K;else{if(X=Math.floor(Math.log(T)/Math.LN2),T*(Z=Math.pow(2,-X))<1)X--,Z*=2;if(X+G>=1)T+=$/Z;else T+=$*Math.pow(2,1-G);if(T*Z>=2)X++,Z/=2;if(X+G>=K)H=0,X=K;else if(X+G>=1)H=(T*Z-1)*Math.pow(2,L),X=X+G;else H=T*Math.pow(2,G-1)*Math.pow(2,L),X=0}for(;L>=8;_[A+U]=H&255,U+=V,H/=256,L-=8);X=X<<L|H,Y+=L;for(;Y>0;_[A+U]=X&255,U+=V,X/=256,Y-=8);_[A+U-V]|=N*128}});var CY=W((NI)=>{/*!
|
|
5
|
+
`+J),_.push(L+"m+"+IA.exports.humanize(this.diff)+"\x1B[0m")}else _[0]=pR()+T+" "+_[0]}function pR(){if(GZ.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function lR(..._){return process.stderr.write(qA.formatWithOptions(GZ.inspectOpts,..._)+`
|
|
6
|
+
`)}function nR(_){if(_)process.env.DEBUG=_;else delete process.env.DEBUG}function iR(){return process.env.DEBUG}function aR(_){_.inspectOpts={};let T=Object.keys(GZ.inspectOpts);for(let A=0;A<T.length;A++)_.inspectOpts[T[A]]=GZ.inspectOpts[T[A]]}IA.exports=UE()(GZ);var{formatters:$Z}=IA.exports;$Z.o=function(_){return this.inspectOpts.colors=this.useColors,qA.inspect(_,this.inspectOpts).split(`
|
|
7
|
+
`).map((T)=>T.trim()).join(" ")};$Z.O=function(_){return this.inspectOpts.colors=this.useColors,qA.inspect(_,this.inspectOpts)}});var d1=W((Yb,WE)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)WE.exports=KZ();else WE.exports=WZ()});var MZ=W((Kb,QZ)=>{var AD=TZ(),{EventEmitter:ED}=I("events"),NZ=LZ(),E_=GE(),n=d1()("mqtt-packet:parser");class PA extends ED{constructor(){super();this.parser=this.constructor.parser}static parser(_){if(!(this instanceof PA))return new PA().parser(_);return this.settings=_||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this}_resetState(){n("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new NZ,this.error=null,this._list=AD(),this._stateCounter=0}parse(_){if(this.error)this._resetState();this._list.append(_),n("parse: current state: %s",this._states[this._stateCounter]);while((this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error)if(this._stateCounter++,n("parse: state complete. _stateCounter is now: %d",this._stateCounter),n("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length)this._stateCounter=0;return n("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let _=this._list.readUInt8(0),T=_>>E_.CMD_SHIFT;this.packet.cmd=E_.types[T];let A=_&15,E=E_.requiredHeaderFlags[T];if(E!=null&&A!==E)return this._emitError(Error(E_.requiredHeaderFlagsErrors[T]));if(this.packet.retain=(_&E_.RETAIN_MASK)!==0,this.packet.qos=_>>E_.QOS_SHIFT&E_.QOS_MASK,this.packet.qos>2)return this._emitError(Error("Packet must not have both QoS bits set to 1"));return this.packet.dup=(_&E_.DUP_MASK)!==0,n("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){let _=this._parseVarByteNum(!0);if(_)this.packet.length=_.value,this._list.consume(_.bytes);return n("_parseLength %d",_.value),!!_}_parsePayload(){n("_parsePayload: payload %O",this._list);let _=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(Error("Not supported"))}_=!0}return n("_parsePayload complete result: %s",_),_}_parseConnect(){n("_parseConnect");let _,T,A,E,L={},J=this.packet,X=this._parseString();if(X===null)return this._emitError(Error("Cannot parse protocolId"));if(X!=="MQTT"&&X!=="MQIsdp")return this._emitError(Error("Invalid protocolId"));if(J.protocolId=X,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(J.protocolVersion=this._list.readUInt8(this._pos),J.protocolVersion>=128)J.bridgeMode=!0,J.protocolVersion=J.protocolVersion-128;if(J.protocolVersion!==3&&J.protocolVersion!==4&&J.protocolVersion!==5)return this._emitError(Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(Error("Connect flag bit 0 must be 0, but got 1"));L.username=this._list.readUInt8(this._pos)&E_.USERNAME_MASK,L.password=this._list.readUInt8(this._pos)&E_.PASSWORD_MASK,L.will=this._list.readUInt8(this._pos)&E_.WILL_FLAG_MASK;let H=!!(this._list.readUInt8(this._pos)&E_.WILL_RETAIN_MASK),Z=(this._list.readUInt8(this._pos)&E_.WILL_QOS_MASK)>>E_.WILL_QOS_SHIFT;if(L.will)J.will={},J.will.retain=H,J.will.qos=Z;else{if(H)return this._emitError(Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(Z)return this._emitError(Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(J.clean=(this._list.readUInt8(this._pos)&E_.CLEAN_SESSION_MASK)!==0,this._pos++,J.keepalive=this._parseNum(),J.keepalive===-1)return this._emitError(Error("Packet too short"));if(J.protocolVersion===5){let K=this._parseProperties();if(Object.getOwnPropertyNames(K).length)J.properties=K}let Y=this._parseString();if(Y===null)return this._emitError(Error("Packet too short"));if(J.clientId=Y,n("_parseConnect: packet.clientId: %s",J.clientId),L.will){if(J.protocolVersion===5){let K=this._parseProperties();if(Object.getOwnPropertyNames(K).length)J.will.properties=K}if(_=this._parseString(),_===null)return this._emitError(Error("Cannot parse will topic"));if(J.will.topic=_,n("_parseConnect: packet.will.topic: %s",J.will.topic),T=this._parseBuffer(),T===null)return this._emitError(Error("Cannot parse will payload"));J.will.payload=T,n("_parseConnect: packet.will.paylaod: %s",J.will.payload)}if(L.username){if(E=this._parseString(),E===null)return this._emitError(Error("Cannot parse username"));J.username=E,n("_parseConnect: packet.username: %s",J.username)}if(L.password){if(A=this._parseBuffer(),A===null)return this._emitError(Error("Cannot parse password"));J.password=A}return this.settings=J,n("_parseConnect: complete"),J}_parseConnack(){n("_parseConnack");let _=this.packet;if(this._list.length<1)return null;let T=this._list.readUInt8(this._pos++);if(T>1)return this._emitError(Error("Invalid connack flags, bits 7-1 must be set to 0"));if(_.sessionPresent=!!(T&E_.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)if(this._list.length>=2)_.reasonCode=this._list.readUInt8(this._pos++);else _.reasonCode=0;else{if(this._list.length<2)return null;_.returnCode=this._list.readUInt8(this._pos++)}if(_.returnCode===-1||_.reasonCode===-1)return this._emitError(Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let A=this._parseProperties();if(Object.getOwnPropertyNames(A).length)_.properties=A}n("_parseConnack: complete")}_parsePublish(){n("_parsePublish");let _=this.packet;if(_.topic=this._parseString(),_.topic===null)return this._emitError(Error("Cannot parse topic"));if(_.qos>0){if(!this._parseMessageId())return}if(this.settings.protocolVersion===5){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}_.payload=this._list.slice(this._pos,_.length),n("_parsePublish: payload from buffer list: %o",_.payload)}_parseSubscribe(){n("_parseSubscribe");let _=this.packet,T,A,E,L,J,X,H;if(_.subscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let Z=this._parseProperties();if(Object.getOwnPropertyNames(Z).length)_.properties=Z}if(_.length<=0)return this._emitError(Error("Malformed subscribe, no payload specified"));while(this._pos<_.length){if(T=this._parseString(),T===null)return this._emitError(Error("Cannot parse topic"));if(this._pos>=_.length)return this._emitError(Error("Malformed Subscribe Payload"));if(A=this._parseByte(),this.settings.protocolVersion===5){if(A&192)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(A&252)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(E=A&E_.SUBSCRIBE_OPTIONS_QOS_MASK,E>2)return this._emitError(Error("Invalid subscribe QoS, must be <= 2"));if(X=(A>>E_.SUBSCRIBE_OPTIONS_NL_SHIFT&E_.SUBSCRIBE_OPTIONS_NL_MASK)!==0,J=(A>>E_.SUBSCRIBE_OPTIONS_RAP_SHIFT&E_.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,L=A>>E_.SUBSCRIBE_OPTIONS_RH_SHIFT&E_.SUBSCRIBE_OPTIONS_RH_MASK,L>2)return this._emitError(Error("Invalid retain handling, must be <= 2"));if(H={topic:T,qos:E},this.settings.protocolVersion===5)H.nl=X,H.rap=J,H.rh=L;else if(this.settings.bridgeMode)H.rh=0,H.rap=!0,H.nl=!0;n("_parseSubscribe: push subscription `%s` to subscription",H),_.subscriptions.push(H)}}_parseSuback(){n("_parseSuback");let _=this.packet;if(this.packet.granted=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}if(_.length<=0)return this._emitError(Error("Malformed suback, no payload specified"));while(this._pos<this.packet.length){let T=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!E_.MQTT5_SUBACK_CODES[T])return this._emitError(Error("Invalid suback code"))}else if(T>2&&T!==128)return this._emitError(Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(T)}}_parseUnsubscribe(){n("_parseUnsubscribe");let _=this.packet;if(_.unsubscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}if(_.length<=0)return this._emitError(Error("Malformed unsubscribe, no payload specified"));while(this._pos<_.length){let T=this._parseString();if(T===null)return this._emitError(Error("Cannot parse topic"));n("_parseUnsubscribe: push topic `%s` to unsubscriptions",T),_.unsubscriptions.push(T)}}_parseUnsuback(){n("_parseUnsuback");let _=this.packet;if(!this._parseMessageId())return this._emitError(Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&_.length!==2)return this._emitError(Error("Malformed unsuback, payload length must be 2"));if(_.length<=0)return this._emitError(Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T;_.granted=[];while(this._pos<this.packet.length){let A=this._list.readUInt8(this._pos++);if(!E_.MQTT5_UNSUBACK_CODES[A])return this._emitError(Error("Invalid unsuback code"));this.packet.granted.push(A)}}}_parseConfirmation(){n("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let _=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(_.length>2){switch(_.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!E_.MQTT5_PUBACK_PUBREC_CODES[_.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!E_.MQTT5_PUBREL_PUBCOMP_CODES[_.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break}n("_parseConfirmation: packet.reasonCode `%d`",_.reasonCode)}else _.reasonCode=0;if(_.length>3){let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}}return!0}_parseDisconnect(){let _=this.packet;if(n("_parseDisconnect"),this.settings.protocolVersion===5){if(this._list.length>0){if(_.reasonCode=this._parseByte(),!E_.MQTT5_DISCONNECT_CODES[_.reasonCode])this._emitError(Error("Invalid disconnect reason code"))}else _.reasonCode=0;let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T}return n("_parseDisconnect result: true"),!0}_parseAuth(){n("_parseAuth");let _=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(Error("Not supported auth packet for this version MQTT"));if(_.reasonCode=this._parseByte(),!E_.MQTT5_AUTH_CODES[_.reasonCode])return this._emitError(Error("Invalid auth reason code"));let T=this._parseProperties();if(Object.getOwnPropertyNames(T).length)_.properties=T;return n("_parseAuth: result: true"),!0}_parseMessageId(){let _=this.packet;if(_.messageId=this._parseNum(),_.messageId===null)return this._emitError(Error("Cannot parse messageId")),!1;return n("_parseMessageId: packet.messageId %d",_.messageId),!0}_parseString(_){let T=this._parseNum(),A=T+this._pos;if(T===-1||A>this._list.length||A>this.packet.length)return null;let E=this._list.toString("utf8",this._pos,A);return this._pos+=T,n("_parseString: result: %s",E),E}_parseStringPair(){return n("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let _=this._parseNum(),T=_+this._pos;if(_===-1||T>this._list.length||T>this.packet.length)return null;let A=this._list.slice(this._pos,T);return this._pos+=_,n("_parseBuffer: result: %o",A),A}_parseNum(){if(this._list.length-this._pos<2)return-1;let _=this._list.readUInt16BE(this._pos);return this._pos+=2,n("_parseNum: result: %s",_),_}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let _=this._list.readUInt32BE(this._pos);return this._pos+=4,n("_parse4ByteNum: result: %s",_),_}_parseVarByteNum(_){n("_parseVarByteNum");let T=4,A=0,E=1,L=0,J=!1,X,H=this._pos?this._pos:0;while(A<T&&H+A<this._list.length){if(X=this._list.readUInt8(H+A++),L+=E*(X&E_.VARBYTEINT_MASK),E*=128,(X&E_.VARBYTEINT_FIN_MASK)===0){J=!0;break}if(this._list.length<=A)break}if(!J&&A===T&&this._list.length>=A)this._emitError(Error("Invalid variable byte integer"));if(H)this._pos+=A;if(J)if(_)J={bytes:A,value:L};else J=L;else J=!1;return n("_parseVarByteNum: result: %o",J),J}_parseByte(){let _;if(this._pos<this._list.length)_=this._list.readUInt8(this._pos),this._pos++;return n("_parseByte: result: %o",_),_}_parseByType(_){switch(n("_parseByType: type: %s",_),_){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){n("_parseProperties");let _=this._parseVarByteNum(),A=this._pos+_,E={};while(this._pos<A){let L=this._parseByte();if(!L)return this._emitError(Error("Cannot parse property code type")),!1;let J=E_.propertiesCodes[L];if(!J)return this._emitError(Error("Unknown property")),!1;if(J==="userProperties"){if(!E[J])E[J]=Object.create(null);let X=this._parseByType(E_.propertiesTypes[J]);if(E[J][X.name])if(Array.isArray(E[J][X.name]))E[J][X.name].push(X.value);else{let H=E[J][X.name];E[J][X.name]=[H],E[J][X.name].push(X.value)}else E[J][X.name]=X.value;continue}if(E[J])if(Array.isArray(E[J]))E[J].push(this._parseByType(E_.propertiesTypes[J]));else E[J]=[E[J]],E[J].push(this._parseByType(E_.propertiesTypes[J]));else E[J]=this._parseByType(E_.propertiesTypes[J])}return E}_newPacket(){if(n("_newPacket"),this.packet)this._list.consume(this.packet.length),n("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet);return n("_newPacket: new packet"),this.packet=new NZ,this._pos=0,!0}_emitError(_){n("_emitError",_),this.error=_,this.emit("error",_)}}QZ.exports=PA});var CZ=W(($b,FZ)=>{var{Buffer:l4}=I("buffer"),VZ={},LD=l4.isBuffer(l4.from([1,2]).subarray(0,1));function zZ(_){let T=l4.allocUnsafe(2);return T.writeUInt8(_>>8,0),T.writeUInt8(_&255,1),T}function JD(){for(let _=0;_<65536;_++)VZ[_]=zZ(_)}function XD(_){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 LD?L.subarray(0,E):L.slice(0,E)}function HD(_){let T=l4.allocUnsafe(4);return T.writeUInt32BE(_,0),T}FZ.exports={cache:VZ,generateCache:JD,generateNumber:zZ,genBufVariableByteInt:XD,generate4ByteBuffer:HD}});var OZ=W((Gb,NE)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)NE.exports={nextTick:ZD};else NE.exports=process;function ZD(_,T,A,E){if(typeof _!=="function")throw TypeError('"callback" argument must be a function');var L=arguments.length,J,X;switch(L){case 0:case 1:return process.nextTick(_);case 2:return process.nextTick(function(){_.call(null,T)});case 3:return process.nextTick(function(){_.call(null,T,A)});case 4:return process.nextTick(function(){_.call(null,T,A,E)});default:J=Array(L-1),X=0;while(X<J.length)J[X++]=arguments[X];return process.nextTick(function(){_.apply(null,J)})}}});var VE=W((Ub,xZ)=>{var i=GE(),{Buffer:p}=I("buffer"),YD=p.allocUnsafe(0),KD=p.from([0]),n4=CZ(),$D=OZ().nextTick,R1=d1()("mqtt-packet:writeToStream"),jA=n4.cache,GD=n4.generateNumber,UD=n4.generateCache,QE=n4.genBufVariableByteInt,WD=n4.generate4ByteBuffer,t_=ME,xA=!0;function PZ(_,T,A){if(R1("generate called"),T.cork)T.cork(),$D(ND,T);if(xA)xA=!1,UD();switch(R1("generate: packet.cmd: %s",_.cmd),_.cmd){case"connect":return QD(_,T,A);case"connack":return MD(_,T,A);case"publish":return VD(_,T,A);case"puback":case"pubrec":case"pubrel":case"pubcomp":return zD(_,T,A);case"subscribe":return FD(_,T,A);case"suback":return CD(_,T,A);case"unsubscribe":return OD(_,T,A);case"unsuback":return RD(_,T,A);case"pingreq":case"pingresp":return DD(_,T,A);case"disconnect":return BD(_,T,A);case"auth":return qD(_,T,A);default:return T.destroy(Error("Unknown command")),!1}}Object.defineProperty(PZ,"cacheNumbers",{get(){return t_===ME},set(_){if(_){if(!jA||Object.keys(jA).length===0)xA=!0;t_=ME}else xA=!1,t_=ID}});function ND(_){_.uncork()}function QD(_,T,A){let E=_||{},L=E.protocolId||"MQTT",J=E.protocolVersion||4,X=E.will,H=E.clean,Z=E.keepalive||0,Y=E.clientId||"",K=E.username,$=E.password,G=E.properties;if(H===void 0)H=!0;let U=0;if(!L||typeof L!=="string"&&!p.isBuffer(L))return T.destroy(Error("Invalid protocolId")),!1;else U+=L.length+2;if(J!==3&&J!==4&&J!==5)return T.destroy(Error("Invalid protocol version")),!1;else U+=1;if((typeof Y==="string"||p.isBuffer(Y))&&(Y||J>=4)&&(Y||H))U+=p.byteLength(Y)+2;else{if(J<4)return T.destroy(Error("clientId must be supplied before 3.1.1")),!1;if(H*1===0)return T.destroy(Error("clientId must be given if cleanSession set to 0")),!1}if(typeof Z!=="number"||Z<0||Z>65535||Z%1!==0)return T.destroy(Error("Invalid keepalive")),!1;else U+=2;U+=1;let V,N;if(J===5){if(V=a0(T,G),!V)return!1;U+=V.length}if(X){if(typeof X!=="object")return T.destroy(Error("Invalid will")),!1;if(!X.topic||typeof X.topic!=="string")return T.destroy(Error("Invalid will topic")),!1;else U+=p.byteLength(X.topic)+2;if(U+=2,X.payload)if(X.payload.length>=0)if(typeof X.payload==="string")U+=p.byteLength(X.payload);else U+=X.payload.length;else return T.destroy(Error("Invalid will payload")),!1;if(N={},J===5){if(N=a0(T,X.properties),!N)return!1;U+=N.length}}let z=!1;if(K!=null)if(IZ(K))z=!0,U+=p.byteLength(K)+2;else return T.destroy(Error("Invalid username")),!1;if($!=null){if(!z)return T.destroy(Error("Username is required to use password")),!1;if(IZ($))U+=jZ($)+2;else return T.destroy(Error("Invalid password")),!1}if(T.write(i.CONNECT_HEADER),D1(T,U),L4(T,L),E.bridgeMode)J+=128;T.write(J===131?i.VERSION131:J===132?i.VERSION132:J===4?i.VERSION4:J===5?i.VERSION5:i.VERSION3);let Q=0;if(Q|=K!=null?i.USERNAME_MASK:0,Q|=$!=null?i.PASSWORD_MASK:0,Q|=X&&X.retain?i.WILL_RETAIN_MASK:0,Q|=X&&X.qos?X.qos<<i.WILL_QOS_SHIFT:0,Q|=X?i.WILL_FLAG_MASK:0,Q|=H?i.CLEAN_SESSION_MASK:0,T.write(p.from([Q])),t_(T,Z),J===5)V.write();if(L4(T,Y),X){if(J===5)N.write();RT(T,X.topic),L4(T,X.payload)}if(K!=null)L4(T,K);if($!=null)L4(T,$);return!0}function MD(_,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:KD),T.write(p.from([J])),Z!=null)Z.write();return!0}function VD(_,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||YD,Y=L.messageId,K=L.properties,$=0;if(typeof H==="string")$+=p.byteLength(H)+2;else if(p.isBuffer(H))$+=H.length+2;else return T.destroy(Error("Invalid topic")),!1;if(!p.isBuffer(Z))$+=p.byteLength(Z);else $+=Z.length;if(J&&typeof Y!=="number")return T.destroy(Error("Invalid messageId")),!1;else if(J)$+=2;let G=null;if(E===5){if(G=a0(T,K),!G)return!1;$+=G.length}if(T.write(i.PUBLISH_HEADER[J][L.dup?1:0][X?1:0]),D1(T,$),t_(T,jZ(H)),T.write(H),J>0)t_(T,Y);if(G!=null)G.write();return R1("publish: payload: %o",Z),T.write(Z)}function zD(_,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 FD(_,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 CD(_,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 OD(_,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 RD(_,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 DD(_,T,A){return T.write(i.EMPTY[_.cmd])}function BD(_,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 qD(_,T,A){let E=A?A.protocolVersion:4,L=_||{},J=L.reasonCode,X=L.properties,H=E===5?1:0;if(E!==5)T.destroy(Error("Invalid mqtt version for auth packet"));let Z=i4(T,X,A,H);if(!Z)return!1;if(H+=Z.length,T.write(p.from([i.codes.auth<<4])),D1(T,H),T.write(p.from([J])),Z!==null)Z.write();return!0}var RZ={};function D1(_,T){if(T>i.VARBYTEINT_MAX)return _.destroy(Error(`Invalid variable byte integer: ${T}`)),!1;let A=RZ[T];if(!A){if(A=QE(T),T<16384)RZ[T]=A}return R1("writeVarByteInt: writing to stream: %o",A),_.write(A)}function RT(_,T){let A=p.byteLength(T);return t_(_,A),R1("writeString: %s",T),_.write(T,"utf8")}function DZ(_,T,A){RT(_,T),RT(_,A)}function ME(_,T){return R1("writeNumberCached: number: %d",T),R1("writeNumberCached: %o",jA[T]),_.write(jA[T])}function ID(_,T){let A=GD(T);return R1("writeNumberGenerated: %o",A),_.write(A)}function PD(_,T){let A=WD(T);return R1("write4ByteNumber: %o",A),_.write(A)}function L4(_,T){if(typeof T==="string")RT(_,T);else if(T)t_(_,T.length),_.write(T);else t_(_,0)}function a0(_,T){if(typeof T!=="object"||T.length!=null)return{length:1,write(){qZ(_,{},0)}};let A=0;function E(J,X){let H=i.propertiesTypes[J],Z=0;switch(H){case"byte":{if(typeof X!=="boolean")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=2;break}case"int8":{if(typeof X!=="number"||X<0||X>255)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=2;break}case"binary":{if(X&&X===null)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=1+p.byteLength(X)+2;break}case"int16":{if(typeof X!=="number"||X<0||X>65535)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=3;break}case"int32":{if(typeof X!=="number"||X<0||X>4294967295)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=5;break}case"var":{if(typeof X!=="number"||X<0||X>268435455)return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=1+p.byteLength(QE(X));break}case"string":{if(typeof X!=="string")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=3+p.byteLength(X.toString());break}case"pair":{if(typeof X!=="object")return _.destroy(Error(`Invalid ${J}: ${X}`)),!1;Z+=Object.getOwnPropertyNames(X).reduce((Y,K)=>{let $=X[K];if(Array.isArray($))Y+=$.reduce((G,U)=>{return G+=3+p.byteLength(K.toString())+2+p.byteLength(U.toString()),G},0);else Y+=3+p.byteLength(K.toString())+2+p.byteLength(X[K].toString());return Y},0);break}default:return _.destroy(Error(`Invalid property ${J}: ${X}`)),!1}return Z}if(T)for(let J in T){let X=0,H=0,Z=T[J];if(Z===void 0)continue;else if(Array.isArray(Z))for(let Y=0;Y<Z.length;Y++){if(H=E(J,Z[Y]),!H)return!1;X+=H}else{if(H=E(J,Z),!H)return!1;X=H}if(!X)return!1;A+=X}return{length:p.byteLength(QE(A))+A,write(){qZ(_,T,A)}}}function i4(_,T,A,E){let L=["reasonString","userProperties"],J=A&&A.properties&&A.properties.maximumPacketSize?A.properties.maximumPacketSize:0,X=a0(_,T);if(J)while(E+X.length>J){let H=L.shift();if(H&&T[H])delete T[H],X=a0(_,T);else return!1}return X}function BZ(_,T,A){switch(i.propertiesTypes[T]){case"byte":{_.write(p.from([i.properties[T]])),_.write(p.from([+A]));break}case"int8":{_.write(p.from([i.properties[T]])),_.write(p.from([A]));break}case"binary":{_.write(p.from([i.properties[T]])),L4(_,A);break}case"int16":{_.write(p.from([i.properties[T]])),t_(_,A);break}case"int32":{_.write(p.from([i.properties[T]])),PD(_,A);break}case"var":{_.write(p.from([i.properties[T]])),D1(_,A);break}case"string":{_.write(p.from([i.properties[T]])),RT(_,A);break}case"pair":{Object.getOwnPropertyNames(A).forEach((L)=>{let J=A[L];if(Array.isArray(J))J.forEach((X)=>{_.write(p.from([i.properties[T]])),DZ(_,L.toString(),X.toString())});else _.write(p.from([i.properties[T]])),DZ(_,L.toString(),J.toString())});break}default:return _.destroy(Error(`Invalid property ${T} value: ${A}`)),!1}}function qZ(_,T,A){D1(_,A);for(let E in T)if(Object.prototype.hasOwnProperty.call(T,E)&&T[E]!=null){let L=T[E];if(Array.isArray(L))for(let J=0;J<L.length;J++)BZ(_,E,L[J]);else BZ(_,E,L)}}function jZ(_){if(!_)return 0;else if(_ instanceof p)return _.length;else return p.byteLength(_)}function IZ(_){return typeof _==="string"||_ instanceof p}xZ.exports=PZ});var vZ=W((Wb,yZ)=>{var jD=VE(),{EventEmitter:xD}=I("events"),{Buffer:wZ}=I("buffer");function wD(_,T){let A=new SZ;return jD(_,A,T),A.concat()}class SZ extends xD{constructor(){super();this._array=Array(20),this._i=0}write(_){return this._array[this._i++]=_,!0}concat(){let _=0,T=Array(this._array.length),A=this._array,E=0,L;for(L=0;L<A.length&&A[L]!==void 0;L++){if(typeof A[L]!=="string")T[L]=A[L].length;else T[L]=wZ.byteLength(A[L]);_+=T[L]}let J=wZ.allocUnsafe(_);for(L=0;L<A.length&&A[L]!==void 0;L++)if(typeof A[L]!=="string")A[L].copy(J,E),E+=T[L];else J.write(A[L],E),E+=T[L];return J}destroy(_){if(_)this.emit("error",_)}}yZ.exports=wD});var wA=W((SD)=>{SD.parser=MZ().parser;SD.generate=vZ();SD.writeToStream=VE()});var fZ=W((Qb,kZ)=>{kZ.exports=hZ;function hZ(_,T){if(_&&T)return hZ(_)(T);if(typeof _!=="function")throw TypeError("need wrapper function");return Object.keys(_).forEach(function(E){A[E]=_[E]}),A;function A(){var E=Array(arguments.length);for(var L=0;L<E.length;L++)E[L]=arguments[L];var J=_.apply(this,E),X=E[E.length-1];if(typeof J==="function"&&J!==X)Object.keys(X).forEach(function(H){J[H]=X[H]});return J}}});var mZ=W((Mb,zE)=>{var bZ=fZ();zE.exports=bZ(SA);zE.exports.strict=bZ(gZ);SA.proto=SA(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return SA(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return gZ(this)},configurable:!0})});function SA(_){var T=function(){if(T.called)return T.value;return T.called=!0,T.value=_.apply(this,arguments)};return T.called=!1,T}function gZ(_){var T=function(){if(T.called)throw Error(T.onceError);return T.called=!0,T.value=_.apply(this,arguments)},A=_.name||"Function wrapped with `once`";return T.onceError=A+" shouldn't be called more than once",T.called=!1,T}});var cZ=W((Vb,dZ)=>{var kD=mZ(),fD=function(){},bD=global.Bare?queueMicrotask:process.nextTick.bind(process),gD=function(_){return _.setHeader&&typeof _.abort==="function"},mD=function(_){return _.stdio&&Array.isArray(_.stdio)&&_.stdio.length===3},uZ=function(_,T,A){if(typeof T==="function")return uZ(_,null,T);if(!T)T={};A=kD(A||fD);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(){bD(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(gD(_))if(_.on("complete",Y),_.on("abort",U),_.req)N();else _.on("request",N);else if(X&&!E)_.on("end",Z),_.on("close",Z);if(mD(_))_.on("exit",$);if(_.on("end",K),_.on("finish",Y),T.error!==!1)_.on("error",G);return _.on("close",U),function(){if(H=!0,_.removeListener("complete",Y),_.removeListener("abort",U),_.removeListener("request",N),_.req)_.req.removeListener("finish",Y);_.removeListener("end",Z),_.removeListener("close",Z),_.removeListener("finish",Y),_.removeListener("exit",$),_.removeListener("end",K),_.removeListener("error",G),_.removeListener("close",U)}};dZ.exports=uZ});var x0=W((zb,pZ)=>{var uD=wA();function dD(_,T,A){let E=null;if(_.connecting||_.connected)try{if(!uD.writeToStream(T,_.conn)&&!_.errored){_.conn.once("drain",A);return}}catch(L){E=Error("packet received not valid")}else E=Error("connection closed");setImmediate(A,E,_)}pZ.exports=dD});var FE=W((Fb,iZ)=>{var lZ=uT(),cD=I("util");function nZ(_,T){if(lZ.call(this,_,T.broker),this.writeCallback=T._onError.bind(T),!_.messageId)if(this.messageId=T._nextId,T._nextId>=65535)T._nextId=1;else T._nextId++;else this.messageId=_.messageId}cD.inherits(nZ,lZ);iZ.exports=nZ});var rZ=W((Cb,oZ)=>{var pD=k8(),aZ=[];function lD(_,T){if(Array.isArray(_))T=_,_=null;var A=pD(nD);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 nD(){this.list=aZ,this.callback=a4,this.count=0,this.context=void 0,this.release=a4;var _=this;this.work=function T(){if(arguments.length>0&&arguments[0])return _.callback.call(_.context,arguments[0]);var A=arguments.length,E,L,J;if(_.count<_.list.length)switch(J=_.list[_.count++],A){case 0:case 1:return J.call(_.context,T);case 2:return J.call(_.context,arguments[1],T);case 3:return J.call(_.context,arguments[1],arguments[2],T);case 4:return J.call(_.context,arguments[1],arguments[2],arguments[3],T);default:L=Array(A);for(E=1;E<A;E++)L[E-1]=arguments[E];L[A-1]=T,J.apply(_.context,L)}else{switch(A){case 0:_.callback.call(_.context);break;case 1:_.callback.call(_.context,arguments[0]);break;case 2:_.callback.call(_.context,arguments[0],arguments[1]);break;case 3:_.callback.call(_.context,arguments[0],arguments[1],arguments[2]);break;case 4:_.callback.call(_.context,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:L=Array(A);for(E=0;E<A;E++)L[E]=arguments[E];_.callback.apply(_.context,L)}_.context=void 0,_.list=aZ,_.count=0,_.release(_)}}}oZ.exports=lD});var DT=W((Ob,sZ)=>{var{Transform:iD,Writable:aD}=I("stream");function oD(_,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 rD(_){return new iD({objectMode:!0,transform:_})}function sD(_){return new aD({objectMode:!0,writev:function(T,A){_(T.map((E)=>E.chunk),A)}})}sZ.exports={validateTopic:oD,through:rD,bulk:sD,$SYS_PREFIX:"$SYS/"}});var yA=W((Rb,E2)=>{var eZ=rZ(),_2=uT(),{through:tD}=DT(),{validateTopic:eD,$SYS_PREFIX:_B}=DT(),TB=x0(),AB=eZ([T2,$B,A2]),EB=eZ([T2,A2]);function LB(_,T){this.cmd="suback",this.messageId=_.messageId,this.granted=T}function tZ(_,T,A,E,L){this.qos=_,this.func=T,this.rh=A,this.rap=E,this.nl=L}function JB(_,T,A,E){this.client=_,this.packet=T,this.actions=A?EB:AB,this.finish=E,this.subState=[]}function XB(_,T,A,E,L,J){this.client=_,this.packet=T,this.granted=A,this.rh=E,this.rap=L,this.nl=J}function HB(_){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 ZB(_,T,A,E){T.subscriptions=T.subscriptions.length===1?T.subscriptions:HB(T.subscriptions),_.broker._parallel(new JB(_,T,A,E),YB,T.subscriptions,A?E:UB)}function YB(_,T){let A=new XB(this.client,this.packet,_.qos,_.rh,_.rap,_.nl);this.subState.push(A),this.actions.call(A,_,T)}function T2(_,T){let A=eD(_.topic,"SUBSCRIBE");if(A)return T(A);let E=this.client;E.broker.authorizeSubscribe(E,_,T)}function KB(_){return function(A,E){if(A.topic.charCodeAt(0)===36)E();else _(A,E)}}function $B(_,T){if(!_||typeof _!=="object")return this.granted=128,T(null,null);let A=this.packet,E=this.client;if(E.clean)return T(null,_);E.broker.persistence.addSubscriptions(E,A.subscriptions,function(J){T(J,_)})}function A2(_,T){if(!_||typeof _!=="object")return T();let A=this.client,E=A.broker,L=_.topic,J=_.qos,X=this.rh,H=this.rap,Z=this.nl,Y=J>0?A.deliverQoS:A.deliver0,K=Y;if(Y=function(G,U){if(G=new _2(G,E),G.nl=Z,!H)G.retain=!1;K(G,U)},GB(L))Y=KB(Y);if(A.closed||A.broker.closed)return;if(!A.subscriptions[L])A.subscriptions[L]=new tZ(J,Y,X,H,Z),E.subscribe(L,Y,T);else if(A.subscriptions[L].qos!==J||A.subscriptions[L].rh!==X||A.subscriptions[L].rap!==H||A.subscriptions[L].nl!==Z)E.unsubscribe(L,A.subscriptions[L].func),A.subscriptions[L]=new tZ(J,Y,X,H,Z),E.subscribe(L,Y,T);else T()}function GB(_){let T=_.charCodeAt(0);return T===43||T===35}function UB(_){let T=this.finish;if(_)return T(_);let A=this.packet,E=this.client;if(A.messageId!==void 0)TB(E,new LB(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:_B+L.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:E.id,subs:J}),"utf8")},WB),X.length>0)L.persistence.createRetainedStreamCombi(X).pipe(tD(function(K,$,G){K=new _2({cmd:K.cmd,qos:K.qos,topic:K.topic,payload:K.payload,retain:!0},L),K.brokerId=null,E.deliverQoS(K,G)}))}function WB(){}E2.exports=ZB});var OE=W((Db,L2)=>{var NB=x0(),{validateTopic:QB,$SYS_PREFIX:MB}=DT();function VB(_){this.cmd="unsuback",this.messageId=_.messageId}function zB(_,T,A){this.client=_,this.packet=T,this.finish=A}function FB(_,T,A){let E=_.broker,L=T.unsubscriptions,J;for(let X=0;X<L.length;X++)if(J=QB(L[X],"UNSUBSCRIBE"),J)return A(J);if(T.messageId!==void 0){if(_.clean)return CE(_,T,A);E.persistence.removeSubscriptions(_,L,function(X){if(X)return A(X);CE(_,T,A)})}else CE(_,T,A)}function CE(_,T,A){_.broker._parallel(new zB(_,T,A),CB,T.unsubscriptions,OB)}function CB(_,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 OB(_){let T=this.client;if(_){T.emit("error",_);return}let A=this.packet,E=this.finish;if(A.messageId!==void 0)NB(T,new VB(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:MB+T.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:T.id,subs:A.unsubscriptions}),"utf8")},RB)}function RB(){}L2.exports=FB});var X2=W((Bb,J2)=>{J2.exports=function(){let T=process.hrtime();return Math.floor(T[0]*1000+T[1]/1e6)}});var Z2=W((qb,H2)=>{H2.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var $2=W((Ib,DE)=>{var vA=X2(),{clearTimeout:Y2,setTimeout:K2}=Z2();class RE{constructor(_,T,A){let E=this;this._started=vA(),this._rescheduled=0,this._scheduled=T,this._args=A,this._triggered=!1,this._timerWrapper=()=>{if(E._rescheduled>0)E._scheduled=E._rescheduled-(vA()-E._started),E._schedule(E._scheduled);else E._triggered=!0,_.apply(null,E._args)},this._timer=K2(this._timerWrapper,T)}reschedule(_){if(!_)_=this._scheduled;let T=vA();if(T+_-(this._started+this._scheduled)<0)Y2(this._timer),this._schedule(_);else if(!this._triggered)this._started=T,this._rescheduled=_;else this._schedule(_)}_schedule(_){this._triggered=!1,this._started=vA(),this._rescheduled=0,this._scheduled=_,this._timer=K2(this._timerWrapper,_)}clear(){Y2(this._timer)}}function DB(){if(typeof arguments[0]!=="function")throw Error("callback needed");if(typeof arguments[1]!=="number")throw Error("timeout needed");let _;if(arguments.length>0){_=Array(arguments.length-2);for(var T=0;T<_.length;T++)_[T]=arguments[T+2]}return new RE(arguments[0],arguments[1],_)}DE.exports=DB;DE.exports.Retimer=RE});var BE=W((G2)=>{Object.defineProperty(G2,"__esModule",{value:!0});G2.default=IB;var BB=qB(I("crypto"));function qB(_){return _&&_.__esModule?_:{default:_}}var kA=new Uint8Array(256),hA=kA.length;function IB(){if(hA>kA.length-16)BB.default.randomFillSync(kA),hA=0;return kA.slice(hA,hA+=16)}});var N2=W((U2)=>{Object.defineProperty(U2,"__esModule",{value:!0});U2.default=void 0;var jB=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;U2.default=jB});var o4=W((Q2)=>{Object.defineProperty(Q2,"__esModule",{value:!0});Q2.default=void 0;var xB=wB(N2());function wB(_){return _&&_.__esModule?_:{default:_}}function SB(_){return typeof _==="string"&&xB.default.test(_)}var yB=SB;Q2.default=yB});var r4=W((V2)=>{Object.defineProperty(V2,"__esModule",{value:!0});V2.default=void 0;var vB=hB(o4());function hB(_){return _&&_.__esModule?_:{default:_}}var m_=[];for(let _=0;_<256;++_)m_.push((_+256).toString(16).substr(1));function kB(_,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,vB.default)(A))throw TypeError("Stringified UUID is invalid");return A}var fB=kB;V2.default=fB});var D2=W((O2)=>{Object.defineProperty(O2,"__esModule",{value:!0});O2.default=void 0;var bB=C2(BE()),gB=C2(r4());function C2(_){return _&&_.__esModule?_:{default:_}}var F2,qE,IE=0,PE=0;function mB(_,T,A){let E=T&&A||0,L=T||Array(16);_=_||{};let J=_.node||F2,X=_.clockseq!==void 0?_.clockseq:qE;if(J==null||X==null){let G=_.random||(_.rng||bB.default)();if(J==null)J=F2=[G[0]|1,G[1],G[2],G[3],G[4],G[5]];if(X==null)X=qE=(G[6]<<8|G[7])&16383}let H=_.msecs!==void 0?_.msecs:Date.now(),Z=_.nsecs!==void 0?_.nsecs:PE+1,Y=H-IE+(Z-PE)/1e4;if(Y<0&&_.clockseq===void 0)X=X+1&16383;if((Y<0||H>IE)&&_.nsecs===void 0)Z=0;if(Z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");IE=H,PE=Z,qE=X,H+=12219292800000;let K=((H&268435455)*1e4+Z)%4294967296;L[E++]=K>>>24&255,L[E++]=K>>>16&255,L[E++]=K>>>8&255,L[E++]=K&255;let $=H/4294967296*1e4&268435455;L[E++]=$>>>8&255,L[E++]=$&255,L[E++]=$>>>24&15|16,L[E++]=$>>>16&255,L[E++]=X>>>8|128,L[E++]=X&255;for(let G=0;G<6;++G)L[E+G]=J[G];return T||(0,gB.default)(L)}var uB=mB;O2.default=uB});var jE=W((B2)=>{Object.defineProperty(B2,"__esModule",{value:!0});B2.default=void 0;var dB=cB(o4());function cB(_){return _&&_.__esModule?_:{default:_}}function pB(_){if(!(0,dB.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 lB=pB;B2.default=lB});var xE=W((x2)=>{Object.defineProperty(x2,"__esModule",{value:!0});x2.default=oB;x2.URL=x2.DNS=void 0;var nB=I2(r4()),iB=I2(jE());function I2(_){return _&&_.__esModule?_:{default:_}}function aB(_){_=unescape(encodeURIComponent(_));let T=[];for(let A=0;A<_.length;++A)T.push(_.charCodeAt(A));return T}var P2="6ba7b810-9dad-11d1-80b4-00c04fd430c8";x2.DNS=P2;var j2="6ba7b811-9dad-11d1-80b4-00c04fd430c8";x2.URL=j2;function oB(_,T,A){function E(L,J,X,H){if(typeof L==="string")L=aB(L);if(typeof J==="string")J=(0,iB.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,nB.default)(Z)}try{E.name=_}catch(L){}return E.DNS=P2,E.URL=j2,E}});var v2=W((S2)=>{Object.defineProperty(S2,"__esModule",{value:!0});S2.default=void 0;var tB=eB(I("crypto"));function eB(_){return _&&_.__esModule?_:{default:_}}function _q(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return tB.default.createHash("md5").update(_).digest()}var Tq=_q;S2.default=Tq});var b2=W((k2)=>{Object.defineProperty(k2,"__esModule",{value:!0});k2.default=void 0;var Aq=h2(xE()),Eq=h2(v2());function h2(_){return _&&_.__esModule?_:{default:_}}var Lq=(0,Aq.default)("v3",48,Eq.default),Jq=Lq;k2.default=Jq});var d2=W((m2)=>{Object.defineProperty(m2,"__esModule",{value:!0});m2.default=void 0;var Xq=g2(BE()),Hq=g2(r4());function g2(_){return _&&_.__esModule?_:{default:_}}function Zq(_,T,A){_=_||{};let E=_.random||(_.rng||Xq.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,Hq.default)(E)}var Yq=Zq;m2.default=Yq});var l2=W((c2)=>{Object.defineProperty(c2,"__esModule",{value:!0});c2.default=void 0;var Kq=$q(I("crypto"));function $q(_){return _&&_.__esModule?_:{default:_}}function Gq(_){if(Array.isArray(_))_=Buffer.from(_);else if(typeof _==="string")_=Buffer.from(_,"utf8");return Kq.default.createHash("sha1").update(_).digest()}var Uq=Gq;c2.default=Uq});var o2=W((i2)=>{Object.defineProperty(i2,"__esModule",{value:!0});i2.default=void 0;var Wq=n2(xE()),Nq=n2(l2());function n2(_){return _&&_.__esModule?_:{default:_}}var Qq=(0,Wq.default)("v5",80,Nq.default),Mq=Qq;i2.default=Mq});var t2=W((r2)=>{Object.defineProperty(r2,"__esModule",{value:!0});r2.default=void 0;var Vq="00000000-0000-0000-0000-000000000000";r2.default=Vq});var TY=W((e2)=>{Object.defineProperty(e2,"__esModule",{value:!0});e2.default=void 0;var zq=Fq(o4());function Fq(_){return _&&_.__esModule?_:{default:_}}function Cq(_){if(!(0,zq.default)(_))throw TypeError("Invalid UUID");return parseInt(_.substr(14,1),16)}var Oq=Cq;e2.default=Oq});var AY=W((c1)=>{Object.defineProperty(c1,"__esModule",{value:!0});Object.defineProperty(c1,"v1",{enumerable:!0,get:function(){return Rq.default}});Object.defineProperty(c1,"v3",{enumerable:!0,get:function(){return Dq.default}});Object.defineProperty(c1,"v4",{enumerable:!0,get:function(){return Bq.default}});Object.defineProperty(c1,"v5",{enumerable:!0,get:function(){return qq.default}});Object.defineProperty(c1,"NIL",{enumerable:!0,get:function(){return Iq.default}});Object.defineProperty(c1,"version",{enumerable:!0,get:function(){return Pq.default}});Object.defineProperty(c1,"validate",{enumerable:!0,get:function(){return jq.default}});Object.defineProperty(c1,"stringify",{enumerable:!0,get:function(){return xq.default}});Object.defineProperty(c1,"parse",{enumerable:!0,get:function(){return wq.default}});var Rq=w0(D2()),Dq=w0(b2()),Bq=w0(d2()),qq=w0(o2()),Iq=w0(t2()),Pq=w0(TY()),jq=w0(o4()),xq=w0(r4()),wq=w0(jE());function w0(_){return _&&_.__esModule?_:{default:_}}});var JY=W((cb,LY)=>{var Sq=AY(),EY=I("crypto");LY.exports=typeof EY.randomUUID==="function"?EY.randomUUID:Sq.v4});var ZY=W((pb,HY)=>{var wE=[],XY={};for(o0=0;o0<256;o0++)wE[o0]=(o0+256).toString(16).substr(1),XY[wE[o0]]=o0;var o0;function yq(_,T,A){var E=T&&A||0,L=0;T=T||[],_.toLowerCase().replace(/[0-9a-f]{2}/g,function(J){if(L<16)T[E+L++]=XY[J]});while(L<16)T[E+L++]=0;return T}function vq(_,T){var A=T||0,E=wE;return E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+"-"+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]+E[_[A++]]}HY.exports={parse:yq,unparse:vq}});var KY=W((dq)=>{dq.byteLength=kq;dq.toByteArray=bq;dq.fromByteArray=uq;var X0=[],B1=[],hq=typeof Uint8Array<"u"?Uint8Array:Array,SE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(r0=0,yE=SE.length;r0<yE;++r0)X0[r0]=SE[r0],B1[SE.charCodeAt(r0)]=r0;var r0,yE;B1[45]=62;B1[95]=63;function YY(_){var T=_.length;if(T%4>0)throw Error("Invalid string. Length must be a multiple of 4");var A=_.indexOf("=");if(A===-1)A=T;var E=A===T?0:4-A%4;return[A,E]}function kq(_){var T=YY(_),A=T[0],E=T[1];return(A+E)*3/4-E}function fq(_,T,A){return(T+A)*3/4-A}function bq(_){var T,A=YY(_),E=A[0],L=A[1],J=new hq(fq(_,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 gq(_){return X0[_>>18&63]+X0[_>>12&63]+X0[_>>6&63]+X0[_&63]}function mq(_,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(gq(E));return L.join("")}function uq(_){var T,A=_.length,E=A%3,L=[],J=16383;for(var X=0,H=A-E;X<H;X+=J)L.push(mq(_,X,X+J>H?H:X+J));if(E===1)T=_[A-1],L.push(X0[T>>2]+X0[T<<4&63]+"==");else if(E===2)T=(_[A-2]<<8)+_[A-1],L.push(X0[T>>10]+X0[T>>4&63]+X0[T<<2&63]+"=");return L.join("")}});var $Y=W((nq)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */nq.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)};nq.write=function(_,T,A,E,L,J){var X,H,Z,Y=J*8-L-1,K=(1<<Y)-1,$=K>>1,G=L===23?Math.pow(2,-24)-Math.pow(2,-77):0,U=E?0:J-1,V=E?1:-1,N=T<0||T===0&&1/T<0?1:0;if(T=Math.abs(T),isNaN(T)||T===1/0)H=isNaN(T)?1:0,X=K;else{if(X=Math.floor(Math.log(T)/Math.LN2),T*(Z=Math.pow(2,-X))<1)X--,Z*=2;if(X+$>=1)T+=G/Z;else T+=G*Math.pow(2,1-$);if(T*Z>=2)X++,Z/=2;if(X+$>=K)H=0,X=K;else if(X+$>=1)H=(T*Z-1)*Math.pow(2,L),X=X+$;else H=T*Math.pow(2,$-1)*Math.pow(2,L),X=0}for(;L>=8;_[A+U]=H&255,U+=V,H/=256,L-=8);X=X<<L|H,Y+=L;for(;Y>0;_[A+U]=X&255,U+=V,X/=256,Y-=8);_[A+U-V]|=N*128}});var BY=W((VI)=>{/*!
|
|
8
8
|
* The buffer module from node.js, for the browser.
|
|
9
9
|
*
|
|
10
10
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
11
11
|
* @license MIT
|
|
12
|
-
*/var SE=XY(),J4=HY(),ZY=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;NI.Buffer=B;NI.SlowBuffer=sq;NI.INSPECT_MAX_BYTES=50;var fA=2147483647;NI.kMaxLength=fA;B.TYPED_ARRAY_SUPPORT=nq();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 nq(){try{var _=new Uint8Array(1),T={foo:function(){return 42}};return Object.setPrototypeOf(T,Uint8Array.prototype),Object.setPrototypeOf(_,T),_.foo()===42}catch(A){return!1}}Object.defineProperty(B.prototype,"parent",{enumerable:!0,get:function(){if(!B.isBuffer(this))return;return this.buffer}});Object.defineProperty(B.prototype,"offset",{enumerable:!0,get:function(){if(!B.isBuffer(this))return;return this.byteOffset}});function w0(_){if(_>fA)throw RangeError('The value "'+_+'" is invalid for option "size"');var T=new Uint8Array(_);return Object.setPrototypeOf(T,B.prototype),T}function B(_,T,A){if(typeof _==="number"){if(typeof T==="string")throw TypeError('The "string" argument must be of type string. Received type number');return kE(_)}return GY(_,T,A)}B.poolSize=8192;function GY(_,T,A){if(typeof _==="string")return aq(_,T);if(ArrayBuffer.isView(_))return oq(_);if(_==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _);if(X0(_,ArrayBuffer)||_&&X0(_.buffer,ArrayBuffer))return vE(_,T,A);if(typeof SharedArrayBuffer<"u"&&(X0(_,SharedArrayBuffer)||_&&X0(_.buffer,SharedArrayBuffer)))return vE(_,T,A);if(typeof _==="number")throw TypeError('The "value" argument must not be of type number. Received type number');var E=_.valueOf&&_.valueOf();if(E!=null&&E!==_)return B.from(E,T,A);var L=rq(_);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 GY(_,T,A)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function $Y(_){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 iq(_,T,A){if($Y(_),_<=0)return w0(_);if(T!==void 0)return typeof A==="string"?w0(_).fill(T,A):w0(_).fill(T);return w0(_)}B.alloc=function(_,T,A){return iq(_,T,A)};function kE(_){return $Y(_),w0(_<0?0:fE(_)|0)}B.allocUnsafe=function(_){return kE(_)};B.allocUnsafeSlow=function(_){return kE(_)};function aq(_,T){if(typeof T!=="string"||T==="")T="utf8";if(!B.isEncoding(T))throw TypeError("Unknown encoding: "+T);var A=UY(_,T)|0,E=w0(A),L=E.write(_,T);if(L!==A)E=E.slice(0,L);return E}function yE(_){var T=_.length<0?0:fE(_.length)|0,A=w0(T);for(var E=0;E<T;E+=1)A[E]=_[E]&255;return A}function oq(_){if(X0(_,Uint8Array)){var T=new Uint8Array(_);return vE(T.buffer,T.byteOffset,T.byteLength)}return yE(_)}function vE(_,T,A){if(T<0||_.byteLength<T)throw RangeError('"offset" is outside of buffer bounds');if(_.byteLength<T+(A||0))throw RangeError('"length" is outside of buffer bounds');var E;if(T===void 0&&A===void 0)E=new Uint8Array(_);else if(A===void 0)E=new Uint8Array(_,T);else E=new Uint8Array(_,T,A);return Object.setPrototypeOf(E,B.prototype),E}function rq(_){if(B.isBuffer(_)){var T=fE(_.length)|0,A=w0(T);if(A.length===0)return A;return _.copy(A,0,0,T),A}if(_.length!==void 0){if(typeof _.length!=="number"||bE(_.length))return w0(0);return yE(_)}if(_.type==="Buffer"&&Array.isArray(_.data))return yE(_.data)}function fE(_){if(_>=fA)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+fA.toString(16)+" bytes");return _|0}function sq(_){if(+_!=_)_=0;return B.alloc(+_)}B.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==B.prototype};B.compare=function(T,A){if(X0(T,Uint8Array))T=B.from(T,T.offset,T.byteLength);if(X0(A,Uint8Array))A=B.from(A,A.offset,A.byteLength);if(!B.isBuffer(T)||!B.isBuffer(A))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===A)return 0;var E=T.length,L=A.length;for(var J=0,X=Math.min(E,L);J<X;++J)if(T[J]!==A[J]){E=T[J],L=A[J];break}if(E<L)return-1;if(L<E)return 1;return 0};B.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};B.concat=function(T,A){if(!Array.isArray(T))throw TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return B.alloc(0);var E;if(A===void 0){A=0;for(E=0;E<T.length;++E)A+=T[E].length}var L=B.allocUnsafe(A),J=0;for(E=0;E<T.length;++E){var X=T[E];if(X0(X,Uint8Array))if(J+X.length>L.length)B.from(X).copy(L,J);else Uint8Array.prototype.set.call(L,X,J);else if(!B.isBuffer(X))throw TypeError('"list" argument must be an Array of Buffers');else X.copy(L,J);J+=X.length}return L};function UY(_,T){if(B.isBuffer(_))return _.length;if(ArrayBuffer.isView(_)||X0(_,ArrayBuffer))return _.byteLength;if(typeof _!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof _);var A=_.length,E=arguments.length>2&&arguments[2]===!0;if(!E&&A===0)return 0;var L=!1;for(;;)switch(T){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return hE(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return zY(_).length;default:if(L)return E?-1:hE(_).length;T=(""+T).toLowerCase(),L=!0}}B.byteLength=UY;function tq(_,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 ZI(this,T,A);case"utf8":case"utf-8":return NY(this,T,A);case"ascii":return XI(this,T,A);case"latin1":case"binary":return HI(this,T,A);case"base64":return LI(this,T,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return YI(this,T,A);default:if(E)throw TypeError("Unknown encoding: "+_);_=(_+"").toLowerCase(),E=!0}}B.prototype._isBuffer=!0;function DT(_,T,A){var E=_[T];_[T]=_[A],_[A]=E}B.prototype.swap16=function(){var T=this.length;if(T%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var A=0;A<T;A+=2)DT(this,A,A+1);return this};B.prototype.swap32=function(){var T=this.length;if(T%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var A=0;A<T;A+=4)DT(this,A,A+3),DT(this,A+1,A+2);return this};B.prototype.swap64=function(){var T=this.length;if(T%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var A=0;A<T;A+=8)DT(this,A,A+7),DT(this,A+1,A+6),DT(this,A+2,A+5),DT(this,A+3,A+4);return this};B.prototype.toString=function(){var T=this.length;if(T===0)return"";if(arguments.length===0)return NY(this,0,T);return tq.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=NI.INSPECT_MAX_BYTES;if(T=this.toString("hex",0,A).replace(/(.{2})/g,"$1 ").trim(),this.length>A)T+=" ... ";return"<Buffer "+T+">"};if(ZY)B.prototype[ZY]=B.prototype.inspect;B.prototype.compare=function(T,A,E,L,J){if(X0(T,Uint8Array))T=B.from(T,T.offset,T.byteLength);if(!B.isBuffer(T))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(A===void 0)A=0;if(E===void 0)E=T?T.length:0;if(L===void 0)L=0;if(J===void 0)J=this.length;if(A<0||E>T.length||L<0||J>this.length)throw RangeError("out of range index");if(L>=J&&A>=E)return 0;if(L>=J)return-1;if(A>=E)return 1;if(A>>>=0,E>>>=0,L>>>=0,J>>>=0,this===T)return 0;var X=J-L,H=E-A,Z=Math.min(X,H),Y=this.slice(L,J),K=T.slice(A,E);for(var G=0;G<Z;++G)if(Y[G]!==K[G]){X=Y[G],H=K[G];break}if(X<H)return-1;if(H<X)return 1;return 0};function WY(_,T,A,E,L){if(_.length===0)return-1;if(typeof A==="string")E=A,A=0;else if(A>2147483647)A=2147483647;else if(A<-2147483648)A=-2147483648;if(A=+A,bE(A))A=L?0:_.length-1;if(A<0)A=_.length+A;if(A>=_.length)if(L)return-1;else A=_.length-1;else if(A<0)if(L)A=0;else return-1;if(typeof T==="string")T=B.from(T,E);if(B.isBuffer(T)){if(T.length===0)return-1;return YY(_,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 YY(_,[T],A,E,L)}throw TypeError("val must be string, number or Buffer")}function YY(_,T,A,E,L){var J=1,X=_.length,H=T.length;if(E!==void 0){if(E=String(E).toLowerCase(),E==="ucs2"||E==="ucs-2"||E==="utf16le"||E==="utf-16le"){if(_.length<2||T.length<2)return-1;J=2,X/=2,H/=2,A/=2}}function Z(U,V){if(J===1)return U[V];else return U.readUInt16BE(V*J)}var Y;if(L){var K=-1;for(Y=A;Y<X;Y++)if(Z(_,Y)===Z(T,K===-1?0:Y-K)){if(K===-1)K=Y;if(Y-K+1===H)return K*J}else{if(K!==-1)Y-=Y-K;K=-1}}else{if(A+H>X)A=X-H;for(Y=A;Y>=0;Y--){var G=!0;for(var $=0;$<H;$++)if(Z(_,Y+$)!==Z(T,$)){G=!1;break}if(G)return Y}}return-1}B.prototype.includes=function(T,A,E){return this.indexOf(T,A,E)!==-1};B.prototype.indexOf=function(T,A,E){return WY(this,T,A,E,!0)};B.prototype.lastIndexOf=function(T,A,E){return WY(this,T,A,E,!1)};function eq(_,T,A,E){A=Number(A)||0;var L=_.length-A;if(!E)E=L;else if(E=Number(E),E>L)E=L;var J=T.length;if(E>J/2)E=J/2;for(var X=0;X<E;++X){var H=parseInt(T.substr(X*2,2),16);if(bE(H))return X;_[A+X]=H}return X}function _I(_,T,A,E){return bA(hE(T,_.length-A),_,A,E)}function TI(_,T,A,E){return bA($I(T),_,A,E)}function AI(_,T,A,E){return bA(zY(T),_,A,E)}function EI(_,T,A,E){return bA(UI(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 eq(this,T,A,E);case"utf8":case"utf-8":return _I(this,T,A,E);case"ascii":case"latin1":case"binary":return TI(this,T,A,E);case"base64":return AI(this,T,A,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return EI(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 LI(_,T,A){if(T===0&&A===_.length)return SE.fromByteArray(_);else return SE.fromByteArray(_.slice(T,A))}function NY(_,T,A){A=Math.min(_.length,A);var E=[],L=T;while(L<A){var J=_[L],X=null,H=J>239?4:J>223?3:J>191?2:1;if(L+H<=A){var Z,Y,K,G;switch(H){case 1:if(J<128)X=J;break;case 2:if(Z=_[L+1],(Z&192)===128){if(G=(J&31)<<6|Z&63,G>127)X=G}break;case 3:if(Z=_[L+1],Y=_[L+2],(Z&192)===128&&(Y&192)===128){if(G=(J&15)<<12|(Z&63)<<6|Y&63,G>2047&&(G<55296||G>57343))X=G}break;case 4:if(Z=_[L+1],Y=_[L+2],K=_[L+3],(Z&192)===128&&(Y&192)===128&&(K&192)===128){if(G=(J&15)<<18|(Z&63)<<12|(Y&63)<<6|K&63,G>65535&&G<1114112)X=G}}}if(X===null)X=65533,H=1;else if(X>65535)X-=65536,E.push(X>>>10&1023|55296),X=56320|X&1023;E.push(X),L+=H}return JI(E)}var KY=4096;function JI(_){var T=_.length;if(T<=KY)return String.fromCharCode.apply(String,_);var A="",E=0;while(E<T)A+=String.fromCharCode.apply(String,_.slice(E,E+=KY));return A}function XI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]&127);return E}function HI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]);return E}function ZI(_,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+=WI[_[J]];return L}function YI(_,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 QY(_,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 MY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)QY(_,T,A,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return J4.write(_,T,A,E,23,4),A+4}B.prototype.writeFloatLE=function(T,A,E){return MY(this,T,A,!0,E)};B.prototype.writeFloatBE=function(T,A,E){return MY(this,T,A,!1,E)};function VY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)QY(_,T,A,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return J4.write(_,T,A,E,52,8),A+8}B.prototype.writeDoubleLE=function(T,A,E){return VY(this,T,A,!0,E)};B.prototype.writeDoubleBE=function(T,A,E){return VY(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 KI=/[^+/0-9A-Za-z-_]/g;function GI(_){if(_=_.split("=")[0],_=_.trim().replace(KI,""),_.length<2)return"";while(_.length%4!==0)_=_+"=";return _}function hE(_,T){T=T||1/0;var A,E=_.length,L=null,J=[];for(var X=0;X<E;++X){if(A=_.charCodeAt(X),A>55295&&A<57344){if(!L){if(A>56319){if((T-=3)>-1)J.push(239,191,189);continue}else if(X+1===E){if((T-=3)>-1)J.push(239,191,189);continue}L=A;continue}if(A<56320){if((T-=3)>-1)J.push(239,191,189);L=A;continue}A=(L-55296<<10|A-56320)+65536}else if(L){if((T-=3)>-1)J.push(239,191,189)}if(L=null,A<128){if((T-=1)<0)break;J.push(A)}else if(A<2048){if((T-=2)<0)break;J.push(A>>6|192,A&63|128)}else if(A<65536){if((T-=3)<0)break;J.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((T-=4)<0)break;J.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw Error("Invalid code point")}return J}function $I(_){var T=[];for(var A=0;A<_.length;++A)T.push(_.charCodeAt(A)&255);return T}function UI(_,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 zY(_){return SE.toByteArray(GI(_))}function bA(_,T,A,E){for(var L=0;L<E;++L){if(L+A>=T.length||L>=_.length)break;T[L+A]=_[L]}return L}function X0(_,T){return _ instanceof T||_!=null&&_.constructor!=null&&_.constructor.name!=null&&_.constructor.name===T.name}function bE(_){return _!==_}var WI=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 qY=W((db,gE)=>{var OY=TY(),DY=LY(),gA=zI();function zI(){let _=j("buffer");return _&&_.Buffer?_.Buffer:CY().Buffer}var FI=gA.from("==","base64");function CI(_){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=OY(),X.decode=BY;let L=RY(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=OY(),L=RY(X.uuid,A),J=0;if(T)H=L+`0000000000${J}`.slice(-10);else H=L+J;return J=J+1|0,H}}function RY(_,T){let A=gA.concat([gA.from(DY.parse(_)),FI]).toString("base64");if(T)return A.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"-");return A.replace(/=+$/,"/")}function BY(_,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:DY.unparse(gA.from(L+"==","base64")),count:J}}gE.exports=CI;gE.exports.decode=BY});var jY=W((cb,PY)=>{var OI=HZ(),{pipeline:RI}=j("stream"),IY=j0(),DI=VE(),{through:BI}=RT(),qI=yA(),II=qY()();function PI(_){this.cmd="connack",this.returnCode=_.returnCode,this.sessionPresent=_.sessionPresent}function jI(_,T){this.client=_,this.packet=T}var xI=[yI,vI,hI,fI,bI,gI,uE,mI],mE=["","unacceptable protocol version","identifier rejected","Server unavailable","bad user name or password","not authorized","keep alive limit exceeded"];function wI(_,T,A){clearTimeout(_._connectTimer),_._connectTimer=null,_.connecting=!0,_.broker.preConnect(_,T,E);function E(L,J){if(!L&&J===!0)setImmediate(SI,_,T,A);else _.connecting=!1,A(L)}}function SI(_,T,A){let E=T.clientId,L=0;if(T.protocolVersion<3||T.protocolVersion>4)L=1;if(T.protocolVersion===3&&E.length>_.broker.maxClientsIdLength)L=2;if(_.broker.keepaliveLimit&&(!T.keepalive||T.keepalive>_.broker.keepaliveLimit))L=6;if(L>0){let J=Error(mE[L]);J.errorCode=L,uE({client:_,returnCode:L,sessionPresent:!1},A.bind(this,J));return}_.id=E||"aedes_"+II(),_.clean=T.clean,_.version=T.protocolVersion,_._will=T.will,_.broker._series(new jI(_,T),xI,{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 yI(_,T){let A=this.client;A.pause(),A.broker.authenticate(A,this.packet.username,this.packet.password,E);function E(L,J){if(A.closed||A.broker.closed)return;if(!L&&J)return A._authorized=!0,T();if(L){let X=L.returnCode;if(X&&(X>=2&&X<=5))_.returnCode=X;else _.returnCode=5;if(!L.message)L.message=mE[_.returnCode]}else _.returnCode=5,L=Error(mE[_.returnCode]);L.errorCode=_.returnCode,_.client=A,uE(_,A.close.bind(A,T.bind(this,L)))}}function vI(_,T){if(this.packet.keepalive>0){let A=this.client;A._keepaliveInterval=this.packet.keepalive*1500+1,A._keepaliveTimer=OI(function(){A.broker.emit("keepaliveTimeout",A),A.emit("error",Error("keep alive timeout"))},A._keepaliveInterval)}T()}function hI(_,T){let A=this.client;if(!this.packet.clean){A.broker.persistence.subscriptionsByClient({id:A.id,done:T,arg:_},kI);return}_.sessionPresent=!1,A.broker.persistence.cleanSubscriptions(A,T)}function kI(_,T,A){if(_)return A.done(_);A.arg.subs=T,A.done()}function fI(_,T){if(_.subs){qI(this.client,{subscriptions:_.subs},!0,T),_.sessionPresent=!!_.subs;return}_.sessionPresent=!1,T()}function bI(_,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 gI(_,T){let A=this.client;A.broker.registerClient(A),T()}function uE(_,T){let A=_.client||this.client,E=new PI(_);IY(A,E,function(L){if(!L)A.broker.emit("connackSent",E,A),A.connackSent=!0;T(L)})}function mI(_,T){let A=this.client,E=A.broker.persistence,L=E.outgoingStream(A);A.resume(),RI(L,BI(function(X,H,Z){let Y=new DI(X,A);Y.writeCallback=(K,G)=>Z(K),E.outgoingUpdate(A,Y,uI)}),T)}function uI(_,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 IY(T,A,E)}PY.exports=wI});var SY=W((pb,wY)=>{var xY=j0();function dI(_){this.cmd="puback",this.messageId=_.messageId}function cI(_){this.cmd="pubrec",this.messageId=_.messageId}var pI=[iI,nI];function lI(_,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(_,pI,T,A)}function nI(_,T){let A=this;switch(_.qos){case 2:A.broker.persistence.incomingStorePacket(A,_,function(E){if(E)return T(E);xY(A,new cI(_),T)});break;case 1:xY(A,new dI(_),function(E){if(E)return T(E);A.broker.publish(_,A,T)});break;case 0:A.broker.publish(_,A,T);break;default:}}function iI(_,T){this.broker.authorizePublish(this,_,T)}wY.exports=lI});var vY=W((lb,yY)=>{function aI(_,T,A){_.broker.persistence.outgoingClearMessageId(_,T,function(L,J){_.broker.emit("ack",J,_),A(L)})}yY.exports=aI});var kY=W((nb,hY)=>{var oI=j0();function rI(_,T){this.client=_,this.packet=T}function sI(_){this.cmd="pubcomp",this.messageId=_.messageId}var tI=[_P,TP,AP,EP];function eI(_,T,A){_.broker._series(new rI(_,T),tI,{},A)}function _P(_,T){this.client.broker.persistence.incomingGetPacket(this.client,this.packet,E);function E(L,J){_.packet=J,T(L)}}function TP(_,T){this.client.broker.publish(_.packet,this.client,T)}function AP(_,T){oI(this.client,new sI(_.packet),T)}function EP(_,T){this.client.broker.persistence.incomingDelPacket(this.client,_.packet,T)}hY.exports=eI});var gY=W((ib,bY)=>{var fY=j0();function LP(_){this.cmd="pubrel",this.messageId=_.messageId}function JP(_,T,A){let E=new LP(T);if(_.clean){fY(_,E,A);return}_.broker.persistence.outgoingUpdate(_,E,L);function L(J){if(J)A(J);else fY(_,E,A)}}bY.exports=JP});var uY=W((ab,mY)=>{var XP=j0(),HP={cmd:"pingresp"};function ZP(_,T,A){_.broker.emit("ping",T,_),XP(_,HP,A)}mY.exports=ZP});var pY=W((ob,cY)=>{var YP=jY(),KP=yA(),GP=FE(),$P=SY(),UP=vY(),WP=kY(),NP=gY(),QP=uY();function MP(_,T,A){if(T.cmd==="connect"){if(_.connecting||_.connected){dY(_.conn,T,A);return}YP(_,T,A);return}if(!_.connecting&&!_.connected){dY(_.conn,T,A);return}switch(T.cmd){case"publish":$P(_,T,A);break;case"subscribe":KP(_,T,!1,A);break;case"unsubscribe":GP(_,T,A);break;case"pubcomp":case"puback":UP(_,T,A);break;case"pubrel":WP(_,T,A);break;case"pubrec":NP(_,T,A);break;case"pingreq":QP(_,T,A);break;case"disconnect":_._disconnected=!0,_.conn.destroy(),A();return;default:_.conn.destroy(),A();return}if(_._keepaliveInterval>0)_._keepaliveTimer.reschedule(_._keepaliveInterval)}function dY(_,T,A){_.destroy();let E=Error("Invalid protocol");E.info=T,A(E)}cY.exports=MP});var tY=W((rb,sY)=>{var VP=wA(),zP=j("events"),FP=j("util"),CP=g2(),nY=uT(),iY=j0(),OP=VE(),RP=yA(),aY=FE(),oY=pY(),{pipeline:DP}=j("stream"),{through:BP}=RT();sY.exports=H0;function H0(_,T,A){let E=this;this.closed=!1,this.connecting=!1,this.connected=!1,this.connackSent=!1,this.errored=!1,this.id=null,this.clean=!0,this.version=null,this.subscriptions={},this.duplicates={},this.broker=_,this.conn=T,T.client=this,this._disconnected=!1,this._authorized=!1,this._parsingBatch=1,this._nextId=Math.ceil(Math.random()*65535),this.req=A,this.connDetails=A?A.connDetails:null,this.will=null,this._will=null,this._parser=VP.parser(),this._parser.client=this,this._parser._queue=[],this._parser.on("packet",PP),this.once("connected",jP);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",rY),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=CP(this.conn,this.close.bind(this));let J=(X)=>{if(X.clientId===E.id&&X.nl)return;return qP(E,X)&&E.broker.authorizeForward(E,X)};this.deliver0=function(H,Z){let Y=J(H);if(Y)setImmediate(()=>{let K=new nY(Y,_);K.qos=0,iY(E,K,function(G){E._onError(G),Z()})});else setImmediate(Z)},this.deliverQoS=function(H,Z){if(H.qos===0){E.deliver0(H,Z);return}let Y=J(H);if(Y)setImmediate(()=>{let K=new OP(Y,E),G=E.subscriptions[K.topic];if(G&&(G.qos||0)<K.qos)K.qos=G.qos;if(K.writeCallback=Z,E.clean||K.retain)lY(null,E,K);else _.persistence.outgoingUpdate(E,K,lY)});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 qP(_,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 lY(_,T,A){if(_)T.emit("error",_),A.writeCallback();else iY(T,A,function(E){if(E)T.emit("error",E);A.writeCallback()})}function IP(_){_.callback()}function rY(_){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(IP),this.broker.emit(this.id?"clientError":"connectionError",this,_),this.close()}FP.inherits(H0,zP);H0.prototype._onError=rY;H0.prototype.publish=function(_,T){let A=new nY(_,this.broker),E=this;if(A.qos===0){this.deliver0(A,T);return}if(!this.clean&&this.id)this.broker.persistence.outgoingEnqueue({clientId:this.id},A,function(J){if(J)return T(J);E.deliverQoS(A,T)});else E.deliverQoS(A,T)};H0.prototype.subscribe=function(_,T){if(!_.subscriptions){if(!Array.isArray(_))_=[_];_={subscriptions:_}}RP(this,_,!1,T)};H0.prototype.unsubscribe=function(_,T){if(!_.unsubscriptions){if(!Array.isArray(_))_=[_];_={unsubscriptions:_}}aY(this,_,T)};H0.prototype.close=function(_){if(this.closed){if(typeof _==="function")_();return}let T=this,A=this.conn;if(this.closed=!0,this._parser.removeAllListeners("packet"),A.removeAllListeners("readable"),this._parser._queue=null,this._keepaliveTimer)this._keepaliveTimer.clear(),this._keepaliveInterval=-1,this._keepaliveTimer=null;if(this._connectTimer)clearTimeout(this._connectTimer),this._connectTimer=null;this._eos(),this._eos=X4,aY(this,{unsubscriptions:Object.keys(this.subscriptions)},E);function E(){let L=T.will;if(!T._disconnected&&L)T.broker.authorizePublish(T,L,function(J){if(J)return X();T.broker.publish(L,T,X);function X(){T.broker.persistence.delWill({id:T.id,brokerId:T.broker.id},X4)}});else if(L)T.broker.persistence.delWill({id:T.id,brokerId:T.broker.id},X4);if(T.will=null,T._will=null,T.connected=!1,T.connecting=!1,A.removeAllListeners("error"),A.on("error",X4),T.broker.clients[T.id]&&T._authorized)T.broker.unregisterClient(T);if(T.conn.emit("drain"),T.conn.removeAllListeners("drain"),A.destroy(),typeof _==="function")_()}};H0.prototype.pause=function(){this._paused=!0};H0.prototype.resume=function(){this._paused=!1,this._nextBatch()};function PP(_){let T=this.client;if(T._parsingBatch++,T.connackSent||T._parsingBatch===1)oY(T,_,T._nextBatch);else if(this._queue.length<T.broker.queueLimit)this._queue.push(_);else this.emit("error",Error("Client queue limit reached"))}function jP(){let _=this._parser._queue;if(_){for(let T=0,A=_.length;T<A;T++)oY(this,_[T],this._nextBatch);this._parser._queue=null}}H0.prototype.emptyOutgoingQueue=function(_){let T=this,A=T.broker.persistence;function E(L,J,X){A.outgoingClearMessageId(T,L,X)}DP(A.outgoingStream(T),BP(E),_)};function X4(){}});var eY=W((sb,xP)=>{xP.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 LK=W((tb,EK)=>{var wP=j("events"),SP=j("util"),yP=h5(),vP=P9(),{v4:hP}=S7(),kP=k8(),{pipeline:fP}=j("stream"),bP=uT(),gP=u7(),mP=a7(),uP=tY(),{$SYS_PREFIX:Z0,bulk:dP}=RT();EK.exports=Z1.createBroker=Z1;var cP={concurrency:100,heartbeatInterval:60000,connectTimeout:30000,decodeProtocol:null,preConnect:rP,authenticate:sP,authorizePublish:tP,authorizeSubscribe:eP,authorizeForward:_j,published:Tj,trustProxy:!1,trustedProxies:[],queueLimit:42,maxClientsIdLength:23,keepaliveLimit:0};function Z1(_){let T=this;if(!(this instanceof Z1))return new Z1(_);_=Object.assign({},cP,_),this.id=_.id||hP(),this.counter=0,this.queueLimit=_.queueLimit,this.connectTimeout=_.connectTimeout,this.keepaliveLimit=_.keepaliveLimit,this.maxClientsIdLength=_.maxClientsIdLength,this.mq=_.mq||mP({concurrency:_.concurrency,matchEmptyLevels:!0}),this.handle=function(K,G){return K.setMaxListeners(_.concurrency*2),new uP(T,K,G)},this.persistence=_.persistence||gP(),this.persistence.broker=this,this._parallel=yP(),this._series=vP(),this._enqueuers=kP(lP),this.preConnect=_.preConnect,this.authenticate=_.authenticate,this.authorizePublish=_.authorizePublish,this.authorizeSubscribe=_.authorizeSubscribe,this.authorizeForward=_.authorizeForward,this.published=_.published,this.decodeProtocol=_.decodeProtocol,this.trustProxy=_.trustProxy,this.trustedProxies=_.trustedProxies,this.clients={},this.brokers={};let A=Z0+T.id+"/heartbeat",E=Z0+T.id+"/birth";this._heartbeatInterval=setInterval(J,_.heartbeatInterval);let L=Buffer.from(T.id,"utf8");T.publish({topic:E,payload:L},s4);function J(){T.publish({topic:A,payload:L},s4)}function X(Y){if(T.brokers[Y]+3*_.heartbeatInterval<Date.now())delete T.brokers[Y]}this._clearWillInterval=setInterval(function(){Object.keys(T.brokers).forEach(X),fP(T.persistence.streamWill(T.brokers),dP(H),function(K){if(K)T.emit("error",K)})},_.heartbeatInterval*4);function H(Y,K){T._parallel(T,Z,Y,K)}function Z(Y,K){if(T.brokers[Y.brokerId]!==void 0&&T.brokers[Y.brokerId]+3*_.heartbeatInterval>=Date.now())return K();this.authorizePublish(T.clients[Y.clientId]||null,Y,function($){if($)return U();T.publish(Y,U);function U(V){if(V)return K(V);T.persistence.delWill({id:Y.clientId,brokerId:Y.brokerId},K)}})}this.mq.on(Z0+"+/heartbeat",function(K,G){T.brokers[K.payload.toString()]=Date.now(),G()}),this.mq.on(Z0+"+/birth",function(K,G){let $=K.payload.toString();if($!==T.id)for(let U in T.clients)delete T.clients[U].duplicates[$];G()}),this.mq.on(Z0+"+/new/clients",function(K,G){let $=K.topic.split("/")[1],U=K.payload.toString();if(T.clients[U]&&$!==T.id)if(T.clients[U].closed)T.deleteClient(U),G();else T.clients[U].close(G);else G()}),this.connectedClients=0,this.closed=!1}SP.inherits(Z1,wP);function _K(_,T){if(_.retain)this.broker.persistence.storeRetained(_,T);else T()}function TK(_,T){if(this.client)_.clientId=this.client.id;this.broker.mq.emit(_,T)}function pP(_,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 lP(){this.next=null,this.complete=null,this.packet=null,this.topic=null,this.broker=null;let _=this;this.done=function(A,E){let L=_.broker;if(A){L.emit("error",A);return}if(_.topic.indexOf(Z0)===0)E=E.filter(nP);let{packet:J,complete:X}=_;_.packet=null,_.complete=null,_.topic=null,L.persistence.outgoingEnqueueCombi(E,J,X),L._enqueuers.release(_)}}function nP(_){let T=_.topic.charCodeAt(0);return T!==43&&T!==35}function AK(_,T){this.broker.published(this.packet,this.client,T),this.broker.emit("publish",this.packet,this.client)}var iP=[_K,TK,AK],aP=[_K,pP,TK,AK];Z1.prototype.publish=function(_,T,A){if(typeof T==="function")A=T,T=null;let E=new bP(_,this),L=E.qos>0?aP:iP;this._series(new Aj(this,T,_),L,E,A)};Z1.prototype.subscribe=function(_,T,A){this.mq.on(_,T,A)};Z1.prototype.unsubscribe=function(_,T,A){this.mq.removeListener(_,T,A)};Z1.prototype.registerClient=function(_){let T=this;if(this.clients[_.id])this.clients[_.id].close(function(){T._finishRegisterClient(_)});else this._finishRegisterClient(_)};Z1.prototype._finishRegisterClient=function(_){this.connectedClients++,this.clients[_.id]=_,this.emit("client",_),this.publish({topic:Z0+this.id+"/new/clients",payload:Buffer.from(_.id,"utf8")},s4)};Z1.prototype.unregisterClient=function(_){this.deleteClient(_.id),this.emit("clientDisconnect",_),this.publish({topic:Z0+this.id+"/disconnect/clients",payload:Buffer.from(_.id,"utf8")},s4)};Z1.prototype.deleteClient=function(_){this.connectedClients--,delete this.clients[_]};function oP(_,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,oP,Object.keys(this.clients),A);function A(){T.emit("closed"),T.mq.close(_)}};Z1.prototype.version=eY().version;function rP(_,T,A){A(null,!0)}function sP(_,T,A,E){E(null,!0)}function tP(_,T,A){if(T.topic.startsWith(Z0))return A(Error(Z0+" topic is reserved"));A(null)}function eP(_,T,A){A(null,T)}function _j(_,T){return T}function Tj(_,T,A){A(null)}function Aj(_,T,A){this.broker=_,this.client=T,this.packet=A}function s4(){}});var ZK=W((Hg,HK)=>{HK.exports=Lj;function H4(_){if(_ instanceof Buffer)return Buffer.from(_);return new _.constructor(_.buffer.slice(),_.byteOffset,_.length)}function Lj(_){if(_=_||{},_.circles)return Jj(_);let T=new Map;if(T.set(Date,(X)=>new Date(X)),T.set(Map,(X,H)=>new Map(E(Array.from(X),H))),T.set(Set,(X,H)=>new Set(E(Array.from(X),H))),_.constructorHandlers)for(let X of _.constructorHandlers)T.set(X[0],X[1]);let A=null;return _.proto?J:L;function E(X,H){let Z=Object.keys(X),Y=Array(Z.length);for(let K=0;K<Z.length;K++){let G=Z[K],$=X[G];if(typeof $!=="object"||$===null)Y[G]=$;else if($.constructor!==Object&&(A=T.get($.constructor)))Y[G]=A($,H);else if(ArrayBuffer.isView($))Y[G]=H4($);else Y[G]=H($)}return Y}function L(X){if(typeof X!=="object"||X===null)return X;if(Array.isArray(X))return E(X,L);if(X.constructor!==Object&&(A=T.get(X.constructor)))return A(X,L);let H={};for(let Z in X){if(Object.hasOwnProperty.call(X,Z)===!1)continue;let Y=X[Z];if(typeof Y!=="object"||Y===null)H[Z]=Y;else if(Y.constructor!==Object&&(A=T.get(Y.constructor)))H[Z]=A(Y,L);else if(ArrayBuffer.isView(Y))H[Z]=H4(Y);else H[Z]=L(Y)}return H}function J(X){if(typeof X!=="object"||X===null)return X;if(Array.isArray(X))return E(X,J);if(X.constructor!==Object&&(A=T.get(X.constructor)))return A(X,J);let H={};for(let Z in X){let Y=X[Z];if(typeof Y!=="object"||Y===null)H[Z]=Y;else if(Y.constructor!==Object&&(A=T.get(Y.constructor)))H[Z]=A(Y,J);else if(ArrayBuffer.isView(Y))H[Z]=H4(Y);else H[Z]=J(Y)}return H}}function Jj(_){let T=[],A=[],E=new Map;if(E.set(Date,(Z)=>new Date(Z)),E.set(Map,(Z,Y)=>new Map(J(Array.from(Z),Y))),E.set(Set,(Z,Y)=>new Set(J(Array.from(Z),Y))),_.constructorHandlers)for(let Z of _.constructorHandlers)E.set(Z[0],Z[1]);let L=null;return _.proto?H:X;function J(Z,Y){let K=Object.keys(Z),G=Array(K.length);for(let $=0;$<K.length;$++){let U=K[$],V=Z[U];if(typeof V!=="object"||V===null)G[U]=V;else if(V.constructor!==Object&&(L=E.get(V.constructor)))G[U]=L(V,Y);else if(ArrayBuffer.isView(V))G[U]=H4(V);else{let N=T.indexOf(V);if(N!==-1)G[U]=A[N];else G[U]=Y(V)}}return G}function X(Z){if(typeof Z!=="object"||Z===null)return Z;if(Array.isArray(Z))return J(Z,X);if(Z.constructor!==Object&&(L=E.get(Z.constructor)))return L(Z,X);let Y={};T.push(Z),A.push(Y);for(let K in Z){if(Object.hasOwnProperty.call(Z,K)===!1)continue;let G=Z[K];if(typeof G!=="object"||G===null)Y[K]=G;else if(G.constructor!==Object&&(L=E.get(G.constructor)))Y[K]=L(G,X);else if(ArrayBuffer.isView(G))Y[K]=H4(G);else{let $=T.indexOf(G);if($!==-1)Y[K]=A[$];else Y[K]=X(G)}}return T.pop(),A.pop(),Y}function H(Z){if(typeof Z!=="object"||Z===null)return Z;if(Array.isArray(Z))return J(Z,H);if(Z.constructor!==Object&&(L=E.get(Z.constructor)))return L(Z,H);let Y={};T.push(Z),A.push(Y);for(let K in Z){let G=Z[K];if(typeof G!=="object"||G===null)Y[K]=G;else if(G.constructor!==Object&&(L=E.get(G.constructor)))Y[K]=L(G,H);else if(ArrayBuffer.isView(G))Y[K]=H4(G);else{let $=T.indexOf(G);if($!==-1)Y[K]=A[$];else Y[K]=H(G)}}return T.pop(),A.pop(),Y}}});var KK=W((Zg,YK)=>{YK.exports=ZK()()});var UK=W(($K)=>{Object.defineProperty($K,"__esModule",{value:!0});$K.validateTopic=GK;$K.validateTopics=Xj;function GK(_){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 Xj(_){if(_.length===0)return"empty_topic_list";for(let T=0;T<_.length;T++)if(!GK(_[T]))return _[T];return null}});var dE=W((NK)=>{Object.defineProperty(NK,"__esModule",{value:!0});var Yj=n0(),Kj={objectMode:!0},Gj={clean:!0};class WK{options;_inflights;constructor(_){this.options=_||{},this.options={...Gj,..._},this._inflights=new Map}put(_,T){if(this._inflights.set(_.messageId,_),T)T();return this}createStream(){let _=new Yj.Readable(Kj),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(_)_()}}NK.default=WK});var VK=W((MK)=>{Object.defineProperty(MK,"__esModule",{value:!0});var QK=[0,16,128,131,135,144,145,151,153],Uj=(_,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(QK.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(QK.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}};MK.default=Uj});var zK=W(($g,Nj)=>{Nj.exports={name:"mqtt",description:"A library for the MQTT protocol",version:"5.14.1",contributors:["Adam Rudd <adamvrr@gmail.com>","Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)","Siarhei Buntsevich <scarry0506@gmail.com> (https://github.com/scarry1992)","Yoseph Maguire <yomaguir@microsoft.com> (https://github.com/YoDaMa)","Daniel Lando <daniel.sorridi@gmail.com> (https://github.com/robertsLando)"],keywords:["mqtt","publish/subscribe","publish","subscribe"],license:"MIT",repository:{type:"git",url:"git://github.com/mqttjs/MQTT.js.git"},main:"./build/index.js",module:"./dist/mqtt.esm.js",bin:{mqtt_pub:"./build/bin/pub.js",mqtt_sub:"./build/bin/sub.js",mqtt:"./build/bin/mqtt.js"},files:["dist/","CONTRIBUTING.md","LICENSE.md","help/","build/"],exports:{".":{"react-native":"./dist/mqtt.esm.js",browser:{import:"./dist/mqtt.esm.js",default:"./dist/mqtt.min.js"},default:"./build/index.js"},"./package.json":"./package.json","./*.map":"./build/*.js.map","./dist/*":"./dist/*.js","./*":"./build/*.js"},types:"build/index.d.ts",typesVersions:{"*":{"*":["./build/index.d.ts"]}},scripts:{lint:"eslint --ext .ts .","lint-fix":"eslint --fix --ext .ts .","build:ts":"rimraf build/ && tsc -p tsconfig.build.json","build:browser":"node esbuild.js",build:"npm run build:ts && npm run build:browser",prepare:"npm run build","unit-test:node":"node -r esbuild-register --test-concurrency 4 --test-reporter=junit --test-reporter-destination=junit.xml --test-reporter=spec --test-reporter-destination=stdout --test test/node/*.ts ","unit-test:browser":"wtr","test:node":"node_modules/.bin/nyc npm run unit-test:node","test:browser":"npm run build && npm run unit-test:browser",test:"npm run test:node",changelog:"conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md","changelog-init":"conventional-changelog -p angular -i CHANGELOG.md -s -r 0",release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it"},"release-it":{github:{release:!0},git:{tagName:"v${version}",commitMessage:"chore(release): ${version}"},hooks:{"before:init":["npm run test"]},npm:{publish:!0},plugins:{"@release-it/conventional-changelog":{preset:"angular",infile:"CHANGELOG.md"}}},publishConfig:{provenance:!0},"pre-commit":["lint"],engines:{node:">=16.0.0"},browser:{"./mqtt.js":"./dist/mqtt.js",fs:!1,tls:!1,net:!1},dependencies:{"@types/readable-stream":"^4.0.21","@types/ws":"^8.18.1",commist:"^3.2.0","concat-stream":"^2.0.0",debug:"^4.4.1","help-me":"^5.0.0","lru-cache":"^10.4.3",minimist:"^1.2.8","mqtt-packet":"^9.0.2","number-allocator":"^1.0.14","readable-stream":"^4.7.0",rfdc:"^1.4.1",socks:"^2.8.6",split2:"^4.2.0","worker-timers":"^8.0.23",ws:"^8.18.3"},devDependencies:{"@eslint/eslintrc":"^3.3.1","@eslint/js":"^9.32.0","@esm-bundle/chai":"^4.3.4","@release-it/conventional-changelog":"^10.0.1","@tsconfig/node20":"^20.1.6","@types/chai":"^5.2.2","@types/node":"^20.17.16","@types/sinon":"^17.0.4","@types/tape":"^5.8.1","@typescript-eslint/eslint-plugin":"^8.38.0","@typescript-eslint/parser":"^8.38.0","@web/test-runner":"^0.20.2","@web/test-runner-playwright":"^0.11.1","aedes-cli":"^0.8.0",chai:"^5.2.1",chokidar:"^4.0.3","conventional-changelog-cli":"^5.0.0","end-of-stream":"^1.4.5",esbuild:"^0.25.8","esbuild-plugin-polyfill-node":"^0.3.0","esbuild-register":"^3.6.0",eslint:"^9.32.0","eslint-config-prettier":"^10.1.8","eslint-plugin-import":"^2.32.0","eslint-plugin-prettier":"^5.5.3",global:"^4.4.0",globals:"^16.3.0","leaked-handles":"^5.2.0",mkdirp:"^3.0.1","mqtt-connection":"^4.1.0","mqtt-level-store":"^3.1.0",nyc:"^17.1.0","pre-commit":"^1.2.2",prettier:"^3.6.2","release-it":"^19.0.4",rimraf:"^6.0.1",should:"^13.2.3",sinon:"^17.0.2",snazzy:"^9.0.0",tape:"^5.9.0","ts-node":"^10.9.2",typescript:"^5.8.3"}}});var BT=W((FK)=>{Object.defineProperty(FK,"__esModule",{value:!0});FK.MQTTJS_VERSION=FK.nextTick=FK.ErrorWithSubackPacket=FK.ErrorWithReasonCode=void 0;FK.applyMixin=Qj;class cE extends Error{code;constructor(_,T){super(_);this.code=T,Object.setPrototypeOf(this,cE.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}FK.ErrorWithReasonCode=cE;class pE extends Error{packet;constructor(_,T){super(_);this.packet=T,Object.setPrototypeOf(this,pE.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}FK.ErrorWithSubackPacket=pE;function Qj(_,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))}FK.nextTick=typeof process?.nextTick==="function"?process.nextTick:(_)=>{setTimeout(_,0)};FK.MQTTJS_VERSION=zK().version});var e4=W((RK)=>{Object.defineProperty(RK,"__esModule",{value:!0});RK.ReasonCodes=void 0;var OK=BT();RK.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 Cj=(_,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 OK.ErrorWithReasonCode(`Publish error: ${RK.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 OK.ErrorWithReasonCode(`Publish error: ${RK.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: ${RK.ReasonCodes[Y]}`),X.code=Y;let K=_.messageIdToTopic[A];if(K)K.forEach((G)=>{delete _._resubscribeTopics[G]})}}delete _.messageIdToTopic[A],_._invokeStoreProcessingQueue(),J(X,T);break}case"unsuback":{delete _.outgoing[A],_.messageIdProvider.deallocate(A),_._invokeStoreProcessingQueue(),J(null,T);break}default:_.emit("error",Error("unrecognized packet type"))}if(_.disconnecting&&Object.keys(_.outgoing).length===0)_.emit("outgoingEmpty")};RK.default=Cj});var qK=W((BK)=>{Object.defineProperty(BK,"__esModule",{value:!0});var DK=BT(),Rj=e4(),Dj=(_,T)=>{let{options:A}=_,E=A.protocolVersion,L=E===5?T.reasonCode:T.returnCode;if(E!==5){let J=new DK.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 DK.ErrorWithReasonCode(`Connection refused: ${Rj.ReasonCodes[L]}`,L);_.emit("error",H)}})};BK.default=Dj});var yK=W((wK)=>{Object.defineProperty(wK,"__esModule",{value:!0});wK.LRUCache=void 0;var Z4=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,PK=new Set,lE=typeof process==="object"&&!!process?process:{},jK=(_,T,A,E)=>{typeof lE.emitWarning==="function"?lE.emitWarning(_,T,A,E):console.error(`[${A}] ${T}: ${_}`)},uA=globalThis.AbortController,IK=globalThis.AbortSignal;if(typeof uA>"u"){IK=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(E,L){this._onabort.push(L)}},uA=class{constructor(){T()}signal=new IK;abort(E){if(this.signal.aborted)return;this.signal.reason=E,this.signal.aborted=!0;for(let L of this.signal._onabort)L(E);this.signal.onabort?.(E)}};let _=lE.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",T=()=>{if(!_)return;_=!1,jK("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 qj=(_)=>!PK.has(_),Qg=Symbol("type"),s0=(_)=>_&&_===Math.floor(_)&&_>0&&isFinite(_),xK=(_)=>!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=xK(_);if(!T)return[];Y4.#J=!0;let A=new Y4(_,T);return Y4.#J=!1,A}constructor(_,T){if(!Y4.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new T(_),this.length=0}push(_){this.heap[this.length++]=_}pop(){return this.heap[--this.length]}}class nE{#J;#L;#Y;#K;#N;#z;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#A;#W;#X;#E;#_;#$;#Q;#G;#H;#F;#Z;#C;#O;#M;#R;#P;#U;static unsafeExposeInternals(_){return{starts:_.#O,ttls:_.#M,sizes:_.#C,keyMap:_.#X,keyList:_.#E,valList:_.#_,next:_.#$,prev:_.#Q,get head(){return _.#G},get tail(){return _.#H},free:_.#F,isBackgroundFetch:(T)=>_.#T(T),backgroundFetch:(T,A,E,L)=>_.#v(T,A,E,L),moveToTail:(T)=>_.#w(T),indexes:(T)=>_.#D(T),rindexes:(T)=>_.#B(T),isStale:(T)=>_.#V(T)}}get max(){return this.#J}get maxSize(){return this.#L}get calculatedSize(){return this.#W}get size(){return this.#A}get fetchMethod(){return this.#N}get memoMethod(){return this.#z}get dispose(){return this.#Y}get disposeAfter(){return this.#K}constructor(_){let{max:T=0,ttl:A,ttlResolution:E=1,ttlAutopurge:L,updateAgeOnGet:J,updateAgeOnHas:X,allowStale:H,dispose:Z,disposeAfter:Y,noDisposeOnSet:K,noUpdateTTL:G,maxSize:$=0,maxEntrySize:U=0,sizeCalculation:V,fetchMethod:N,memoMethod:z,noDeleteOnFetchRejection:Q,noDeleteOnStaleGet:F,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:q,ignoreFetchAbort:f}=_;if(T!==0&&!s0(T))throw TypeError("max option must be a nonnegative integer");let h=T?xK(T):Array;if(!h)throw Error("invalid max value: "+T);if(this.#J=T,this.#L=$,this.maxEntrySize=U||this.#L,this.sizeCalculation=V,this.sizeCalculation){if(!this.#L&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(z!==void 0&&typeof z!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#z=z,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#N=N,this.#P=!!N,this.#X=new Map,this.#E=Array(T).fill(void 0),this.#_=Array(T).fill(void 0),this.#$=new h(T),this.#Q=new h(T),this.#G=0,this.#H=0,this.#F=Y4.create(T),this.#A=0,this.#W=0,typeof Z==="function")this.#Y=Z;if(typeof Y==="function")this.#K=Y,this.#Z=[];else this.#K=void 0,this.#Z=void 0;if(this.#R=!!this.#Y,this.#U=!!this.#K,this.noDisposeOnSet=!!K,this.noUpdateTTL=!!G,this.noDeleteOnFetchRejection=!!Q,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!q,this.ignoreFetchAbort=!!f,this.maxEntrySize!==0){if(this.#L!==0){if(!s0(this.#L))throw TypeError("maxSize must be a positive integer if specified")}if(!s0(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#u()}if(this.allowStale=!!H,this.noDeleteOnStaleGet=!!F,this.updateAgeOnGet=!!J,this.updateAgeOnHas=!!X,this.ttlResolution=s0(E)||E===0?E:1,this.ttlAutopurge=!!L,this.ttl=A||0,this.ttl){if(!s0(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#h()}if(this.#J===0&&this.ttl===0&&this.#L===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#L){if(qj("LRU_CACHE_UNBOUNDED"))PK.add("LRU_CACHE_UNBOUNDED"),jK("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",nE)}}getRemainingTTL(_){return this.#X.has(_)?1/0:0}#h(){let _=new _8(this.#J),T=new _8(this.#J);this.#M=_,this.#O=T,this.#k=(L,J,X=Z4.now())=>{if(T[L]=J!==0?X:0,_[L]=J,J!==0&&this.ttlAutopurge){let H=setTimeout(()=>{if(this.#V(L))this.#q(this.#E[L],"expire")},J+1);if(H.unref)H.unref()}},this.#j=(L)=>{T[L]=_[L]!==0?Z4.now():0},this.#I=(L,J)=>{if(_[J]){let X=_[J],H=T[J];if(!X||!H)return;L.ttl=X,L.start=H,L.now=A||E();let Z=L.now-H;L.remainingTTL=X-Z}};let A=0,E=()=>{let L=Z4.now();if(this.ttlResolution>0){A=L;let J=setTimeout(()=>A=0,this.ttlResolution);if(J.unref)J.unref()}return L};this.getRemainingTTL=(L)=>{let J=this.#X.get(L);if(J===void 0)return 0;let X=_[J],H=T[J];if(!X||!H)return 1/0;let Z=(A||E())-H;return X-Z},this.#V=(L)=>{let J=T[L],X=_[L];return!!X&&!!J&&(A||E())-J>X}}#j=()=>{};#I=()=>{};#k=()=>{};#V=()=>!1;#u(){let _=new _8(this.#J);this.#W=0,this.#C=_,this.#x=(T)=>{this.#W-=_[T],_[T]=0},this.#f=(T,A,E,L)=>{if(this.#T(A))return 0;if(!s0(E))if(L){if(typeof L!=="function")throw TypeError("sizeCalculation must be a function");if(E=L(A,T),!s0(E))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return E},this.#S=(T,A,E)=>{if(_[T]=A,this.#L){let L=this.#L-_[T];while(this.#W>L)this.#y(!0)}if(this.#W+=_[T],E)E.entrySize=A,E.totalCalculatedSize=this.#W}}#x=(_)=>{};#S=(_,T,A)=>{};#f=(_,T,A,E)=>{if(A||E)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#D({allowStale:_=this.allowStale}={}){if(this.#A)for(let T=this.#H;;){if(!this.#b(T))break;if(_||!this.#V(T))yield T;if(T===this.#G)break;else T=this.#Q[T]}}*#B({allowStale:_=this.allowStale}={}){if(this.#A)for(let T=this.#G;;){if(!this.#b(T))break;if(_||!this.#V(T))yield T;if(T===this.#H)break;else T=this.#$[T]}}#b(_){return _!==void 0&&this.#X.get(this.#E[_])===_}*entries(){for(let _ of this.#D())if(this.#_[_]!==void 0&&this.#E[_]!==void 0&&!this.#T(this.#_[_]))yield[this.#E[_],this.#_[_]]}*rentries(){for(let _ of this.#B())if(this.#_[_]!==void 0&&this.#E[_]!==void 0&&!this.#T(this.#_[_]))yield[this.#E[_],this.#_[_]]}*keys(){for(let _ of this.#D()){let T=this.#E[_];if(T!==void 0&&!this.#T(this.#_[_]))yield T}}*rkeys(){for(let _ of this.#B()){let T=this.#E[_];if(T!==void 0&&!this.#T(this.#_[_]))yield T}}*values(){for(let _ of this.#D())if(this.#_[_]!==void 0&&!this.#T(this.#_[_]))yield this.#_[_]}*rvalues(){for(let _ of this.#B())if(this.#_[_]!==void 0&&!this.#T(this.#_[_]))yield this.#_[_]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(_,T={}){for(let A of this.#D()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;if(_(L,this.#E[A],this))return this.get(this.#E[A],T)}}forEach(_,T=this){for(let A of this.#D()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;_.call(T,L,this.#E[A],this)}}rforEach(_,T=this){for(let A of this.#B()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;_.call(T,L,this.#E[A],this)}}purgeStale(){let _=!1;for(let T of this.#B({allowStale:!0}))if(this.#V(T))this.#q(this.#E[T],"expire"),_=!0;return _}info(_){let T=this.#X.get(_);if(T===void 0)return;let A=this.#_[T],E=this.#T(A)?A.__staleWhileFetching:A;if(E===void 0)return;let L={value:E};if(this.#M&&this.#O){let J=this.#M[T],X=this.#O[T];if(J&&X){let H=J-(Z4.now()-X);L.ttl=H,L.start=Date.now()}}if(this.#C)L.size=this.#C[T];return L}dump(){let _=[];for(let T of this.#D({allowStale:!0})){let A=this.#E[T],E=this.#_[T],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0||A===void 0)continue;let J={value:L};if(this.#M&&this.#O){J.ttl=this.#M[T];let X=Z4.now()-this.#O[T];J.start=Math.floor(Date.now()-X)}if(this.#C)J.size=this.#C[T];_.unshift([A,J])}return _}load(_){this.clear();for(let[T,A]of _){if(A.start){let E=Date.now()-A.start;A.start=Z4.now()-E}this.set(T,A.value,A)}}set(_,T,A={}){if(T===void 0)return this.delete(_),this;let{ttl:E=this.ttl,start:L,noDisposeOnSet:J=this.noDisposeOnSet,sizeCalculation:X=this.sizeCalculation,status:H}=A,{noUpdateTTL:Z=this.noUpdateTTL}=A,Y=this.#f(_,T,A.size||0,X);if(this.maxEntrySize&&Y>this.maxEntrySize){if(H)H.set="miss",H.maxEntrySizeExceeded=!0;return this.#q(_,"set"),this}let K=this.#A===0?void 0:this.#X.get(_);if(K===void 0){if(K=this.#A===0?this.#H:this.#F.length!==0?this.#F.pop():this.#A===this.#J?this.#y(!1):this.#A,this.#E[K]=_,this.#_[K]=T,this.#X.set(_,K),this.#$[this.#H]=K,this.#Q[K]=this.#H,this.#H=K,this.#A++,this.#S(K,Y,H),H)H.set="add";Z=!1}else{this.#w(K);let G=this.#_[K];if(T!==G){if(this.#P&&this.#T(G)){G.__abortController.abort(Error("replaced"));let{__staleWhileFetching:$}=G;if($!==void 0&&!J){if(this.#R)this.#Y?.($,_,"set");if(this.#U)this.#Z?.push([$,_,"set"])}}else if(!J){if(this.#R)this.#Y?.(G,_,"set");if(this.#U)this.#Z?.push([G,_,"set"])}if(this.#x(K),this.#S(K,Y,H),this.#_[K]=T,H){H.set="replace";let $=G&&this.#T(G)?G.__staleWhileFetching:G;if($!==void 0)H.oldValue=$}}else if(H)H.set="update"}if(E!==0&&!this.#M)this.#h();if(this.#M){if(!Z)this.#k(K,E,L);if(H)this.#I(H,K)}if(!J&&this.#U&&this.#Z){let G=this.#Z,$;while($=G?.shift())this.#K?.(...$)}return this}pop(){try{while(this.#A){let _=this.#_[this.#G];if(this.#y(!0),this.#T(_)){if(_.__staleWhileFetching)return _.__staleWhileFetching}else if(_!==void 0)return _}}finally{if(this.#U&&this.#Z){let _=this.#Z,T;while(T=_?.shift())this.#K?.(...T)}}}#y(_){let T=this.#G,A=this.#E[T],E=this.#_[T];if(this.#P&&this.#T(E))E.__abortController.abort(Error("evicted"));else if(this.#R||this.#U){if(this.#R)this.#Y?.(E,A,"evict");if(this.#U)this.#Z?.push([E,A,"evict"])}if(this.#x(T),_)this.#E[T]=void 0,this.#_[T]=void 0,this.#F.push(T);if(this.#A===1)this.#G=this.#H=0,this.#F.length=0;else this.#G=this.#$[T];return this.#X.delete(A),this.#A--,T}has(_,T={}){let{updateAgeOnHas:A=this.updateAgeOnHas,status:E}=T,L=this.#X.get(_);if(L!==void 0){let J=this.#_[L];if(this.#T(J)&&J.__staleWhileFetching===void 0)return!1;if(!this.#V(L)){if(A)this.#j(L);if(E)E.has="hit",this.#I(E,L);return!0}else if(E)E.has="stale",this.#I(E,L)}else if(E)E.has="miss";return!1}peek(_,T={}){let{allowStale:A=this.allowStale}=T,E=this.#X.get(_);if(E===void 0||!A&&this.#V(E))return;let L=this.#_[E];return this.#T(L)?L.__staleWhileFetching:L}#v(_,T,A,E){let L=T===void 0?void 0:this.#_[T];if(this.#T(L))return L;let J=new uA,{signal:X}=A;X?.addEventListener("abort",()=>J.abort(X.reason),{signal:J.signal});let H={signal:J.signal,options:A,context:E},Z=(V,N=!1)=>{let{aborted:z}=J.signal,Q=A.ignoreFetchAbort&&V!==void 0;if(A.status)if(z&&!N){if(A.status.fetchAborted=!0,A.status.fetchError=J.signal.reason,Q)A.status.fetchAbortIgnored=!0}else A.status.fetchResolved=!0;if(z&&!Q&&!N)return K(J.signal.reason);let F=$;if(this.#_[T]===$)if(V===void 0)if(F.__staleWhileFetching)this.#_[T]=F.__staleWhileFetching;else this.#q(_,"fetch");else{if(A.status)A.status.fetchUpdated=!0;this.set(_,V,H.options)}return V},Y=(V)=>{if(A.status)A.status.fetchRejected=!0,A.status.fetchError=V;return K(V)},K=(V)=>{let{aborted:N}=J.signal,z=N&&A.allowStaleOnFetchAbort,Q=z||A.allowStaleOnFetchRejection,F=Q||A.noDeleteOnFetchRejection,R=$;if(this.#_[T]===$){if(!F||R.__staleWhileFetching===void 0)this.#q(_,"fetch");else if(!z)this.#_[T]=R.__staleWhileFetching}if(Q){if(A.status&&R.__staleWhileFetching!==void 0)A.status.returnedStale=!0;return R.__staleWhileFetching}else if(R.__returned===R)throw V},G=(V,N)=>{let z=this.#N?.(_,L,H);if(z&&z instanceof Promise)z.then((Q)=>V(Q===void 0?void 0:Q),N);J.signal.addEventListener("abort",()=>{if(!A.ignoreFetchAbort||A.allowStaleOnFetchAbort){if(V(void 0),A.allowStaleOnFetchAbort)V=(Q)=>Z(Q,!0)}})};if(A.status)A.status.fetchDispatched=!0;let $=new Promise(G).then(Z,Y),U=Object.assign($,{__abortController:J,__staleWhileFetching:L,__returned:void 0});if(T===void 0)this.set(_,U,{...H.options,status:void 0}),T=this.#X.get(_);else this.#_[T]=U;return U}#T(_){if(!this.#P)return!1;let T=_;return!!T&&T instanceof Promise&&T.hasOwnProperty("__staleWhileFetching")&&T.__abortController instanceof uA}async fetch(_,T={}){let{allowStale:A=this.allowStale,updateAgeOnGet:E=this.updateAgeOnGet,noDeleteOnStaleGet:L=this.noDeleteOnStaleGet,ttl:J=this.ttl,noDisposeOnSet:X=this.noDisposeOnSet,size:H=0,sizeCalculation:Z=this.sizeCalculation,noUpdateTTL:Y=this.noUpdateTTL,noDeleteOnFetchRejection:K=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:G=this.allowStaleOnFetchRejection,ignoreFetchAbort:$=this.ignoreFetchAbort,allowStaleOnFetchAbort:U=this.allowStaleOnFetchAbort,context:V,forceRefresh:N=!1,status:z,signal:Q}=T;if(!this.#P){if(z)z.fetch="get";return this.get(_,{allowStale:A,updateAgeOnGet:E,noDeleteOnStaleGet:L,status:z})}let F={allowStale:A,updateAgeOnGet:E,noDeleteOnStaleGet:L,ttl:J,noDisposeOnSet:X,size:H,sizeCalculation:Z,noUpdateTTL:Y,noDeleteOnFetchRejection:K,allowStaleOnFetchRejection:G,allowStaleOnFetchAbort:U,ignoreFetchAbort:$,status:z,signal:Q},R=this.#X.get(_);if(R===void 0){if(z)z.fetch="miss";let q=this.#v(_,R,F,V);return q.__returned=q}else{let q=this.#_[R];if(this.#T(q)){let c=A&&q.__staleWhileFetching!==void 0;if(z){if(z.fetch="inflight",c)z.returnedStale=!0}return c?q.__staleWhileFetching:q.__returned=q}let f=this.#V(R);if(!N&&!f){if(z)z.fetch="hit";if(this.#w(R),E)this.#j(R);if(z)this.#I(z,R);return q}let h=this.#v(_,R,F,V),l=h.__staleWhileFetching!==void 0&&A;if(z){if(z.fetch=f?"stale":"refresh",l&&f)z.returnedStale=!0}return l?h.__staleWhileFetching:h.__returned=h}}async forceFetch(_,T={}){let A=await this.fetch(_,T);if(A===void 0)throw Error("fetch() returned undefined");return A}memo(_,T={}){let A=this.#z;if(!A)throw Error("no memoMethod provided to constructor");let{context:E,forceRefresh:L,...J}=T,X=this.get(_,J);if(!L&&X!==void 0)return X;let H=A(_,X,{options:J,context:E});return this.set(_,H,J),H}get(_,T={}){let{allowStale:A=this.allowStale,updateAgeOnGet:E=this.updateAgeOnGet,noDeleteOnStaleGet:L=this.noDeleteOnStaleGet,status:J}=T,X=this.#X.get(_);if(X!==void 0){let H=this.#_[X],Z=this.#T(H);if(J)this.#I(J,X);if(this.#V(X)){if(J)J.get="stale";if(!Z){if(!L)this.#q(_,"expire");if(J&&A)J.returnedStale=!0;return A?H:void 0}else{if(J&&A&&H.__staleWhileFetching!==void 0)J.returnedStale=!0;return A?H.__staleWhileFetching:void 0}}else{if(J)J.get="hit";if(Z)return H.__staleWhileFetching;if(this.#w(X),E)this.#j(X);return H}}else if(J)J.get="miss"}#g(_,T){this.#Q[T]=_,this.#$[_]=T}#w(_){if(_!==this.#H){if(_===this.#G)this.#G=this.#$[_];else this.#g(this.#Q[_],this.#$[_]);this.#g(this.#H,_),this.#H=_}}delete(_){return this.#q(_,"delete")}#q(_,T){let A=!1;if(this.#A!==0){let E=this.#X.get(_);if(E!==void 0)if(A=!0,this.#A===1)this.#m(T);else{this.#x(E);let L=this.#_[E];if(this.#T(L))L.__abortController.abort(Error("deleted"));else if(this.#R||this.#U){if(this.#R)this.#Y?.(L,_,T);if(this.#U)this.#Z?.push([L,_,T])}if(this.#X.delete(_),this.#E[E]=void 0,this.#_[E]=void 0,E===this.#H)this.#H=this.#Q[E];else if(E===this.#G)this.#G=this.#$[E];else{let J=this.#Q[E];this.#$[J]=this.#$[E];let X=this.#$[E];this.#Q[X]=this.#Q[E]}this.#A--,this.#F.push(E)}}if(this.#U&&this.#Z?.length){let E=this.#Z,L;while(L=E?.shift())this.#K?.(...L)}return A}clear(){return this.#m("delete")}#m(_){for(let T of this.#B({allowStale:!0})){let A=this.#_[T];if(this.#T(A))A.__abortController.abort(Error("deleted"));else{let E=this.#E[T];if(this.#R)this.#Y?.(A,E,_);if(this.#U)this.#Z?.push([A,E,_])}}if(this.#X.clear(),this.#_.fill(void 0),this.#E.fill(void 0),this.#M&&this.#O)this.#M.fill(0),this.#O.fill(0);if(this.#C)this.#C.fill(0);if(this.#G=0,this.#H=0,this.#F.length=0,this.#W=0,this.#A=0,this.#U&&this.#Z){let T=this.#Z,A;while(A=T?.shift())this.#K?.(...A)}}}wK.LRUCache=nE});var Y0=W((kK)=>{Object.defineProperty(kK,"t",{value:!0});kK.ContainerIterator=kK.Container=kK.Base=void 0;class vK{constructor(_=0){this.iteratorType=_}equals(_){return this.o===_.o}}kK.ContainerIterator=vK;class iE{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}}kK.Base=iE;class hK extends iE{}kK.Container=hK});var uK=W((gK)=>{Object.defineProperty(gK,"t",{value:!0});gK.default=void 0;var jj=Y0();class bK extends jj.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 xj=bK;gK.default=xj});var lK=W((cK)=>{Object.defineProperty(cK,"t",{value:!0});cK.default=void 0;var wj=Y0();class dK extends wj.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 Sj=dK;cK.default=Sj});var oK=W((iK)=>{Object.defineProperty(iK,"t",{value:!0});iK.default=void 0;var yj=Y0();class nK extends yj.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 vj=nK;iK.default=vj});var dA=W((sK)=>{Object.defineProperty(sK,"t",{value:!0});sK.default=void 0;var hj=Y0();class rK extends hj.Container{}var kj=rK;sK.default=kj});var K0=W((eK)=>{Object.defineProperty(eK,"t",{value:!0});eK.throwIteratorAccessError=fj;function fj(){throw RangeError("Iterator access denied!")}});var aE=W((T3)=>{Object.defineProperty(T3,"t",{value:!0});T3.RandomIterator=void 0;var gj=Y0(),cA=K0();class _3 extends gj.ContainerIterator{constructor(_,T){super(T);if(this.o=_,this.iteratorType===0)this.pre=function(){if(this.o===0)(0,cA.throwIteratorAccessError)();return this.o-=1,this},this.next=function(){if(this.o===this.container.size())(0,cA.throwIteratorAccessError)();return this.o+=1,this};else this.pre=function(){if(this.o===this.container.size()-1)(0,cA.throwIteratorAccessError)();return this.o+=1,this},this.next=function(){if(this.o===-1)(0,cA.throwIteratorAccessError)();return this.o-=1,this}}get pointer(){return this.container.getElementByPos(this.o)}set pointer(_){this.container.setElementByPos(this.o,_)}}T3.RandomIterator=_3});var X3=W((L3)=>{Object.defineProperty(L3,"t",{value:!0});L3.default=void 0;var mj=dj(dA()),uj=aE();function dj(_){return _&&_.t?_:{default:_}}class qT extends uj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new qT(this.o,this.container,this.iteratorType)}}class E3 extends mj.default{constructor(_=[],T=!0){super();if(Array.isArray(_))this.J=T?[..._]:_,this.i=_.length;else{this.J=[];let A=this;_.forEach(function(E){A.pushBack(E)})}}clear(){this.i=0,this.J.length=0}begin(){return new qT(0,this)}end(){return new qT(this.i,this)}rBegin(){return new qT(this.i-1,this,1)}rEnd(){return new qT(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();return this.J[_]}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();return this.J.splice(_,1),this.i-=1,this.i}eraseElementByValue(_){let T=0;for(let A=0;A<this.i;++A)if(this.J[A]!==_)this.J[T++]=this.J[A];return this.i=this.J.length=T,this.i}eraseElementByIterator(_){let T=_.o;return _=_.next(),this.eraseElementByPos(T),_}pushBack(_){return this.J.push(_),this.i+=1,this.i}popBack(){if(this.i===0)return;return this.i-=1,this.J.pop()}setElementByPos(_,T){if(_<0||_>this.i-1)throw RangeError();this.J[_]=T}insert(_,T,A=1){if(_<0||_>this.i)throw RangeError();return this.J.splice(_,0,...Array(A).fill(T)),this.i+=A,this.i}find(_){for(let T=0;T<this.i;++T)if(this.J[T]===_)return new qT(T,this);return this.end()}reverse(){this.J.reverse()}unique(){let _=1;for(let T=1;T<this.i;++T)if(this.J[T]!==this.J[T-1])this.J[_++]=this.J[T];return this.i=this.J.length=_,this.i}sort(_){this.J.sort(_)}forEach(_){for(let T=0;T<this.i;++T)_(this.J[T],T,this)}[Symbol.iterator](){return function*(){yield*this.J}.bind(this)()}}var cj=E3;L3.default=cj});var K3=W((Z3)=>{Object.defineProperty(Z3,"t",{value:!0});Z3.default=void 0;var pj=nj(dA()),lj=Y0(),IT=K0();function nj(_){return _&&_.t?_:{default:_}}class PT extends lj.ContainerIterator{constructor(_,T,A,E){super(E);if(this.o=_,this.h=T,this.container=A,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,IT.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,IT.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,IT.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,IT.throwIteratorAccessError)();return this.o=this.o.L,this}}get pointer(){if(this.o===this.h)(0,IT.throwIteratorAccessError)();return this.o.l}set pointer(_){if(this.o===this.h)(0,IT.throwIteratorAccessError)();this.o.l=_}copy(){return new PT(this.o,this.h,this.container,this.iteratorType)}}class H3 extends pj.default{constructor(_=[]){super();this.h={},this.p=this._=this.h.L=this.h.B=this.h;let T=this;_.forEach(function(A){T.pushBack(A)})}V(_){let{L:T,B:A}=_;if(T.B=A,A.L=T,_===this.p)this.p=A;if(_===this._)this._=T;this.i-=1}G(_,T){let A=T.B,E={l:_,L:T,B:A};if(T.B=E,A.L=E,T===this.h)this.p=E;if(A===this.h)this._=E;this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new PT(this.p,this.h,this)}end(){return new PT(this.h,this.h,this)}rBegin(){return new PT(this._,this.h,this,1)}rEnd(){return new PT(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return T.l}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return this.V(T),this.i}eraseElementByValue(_){let T=this.p;while(T!==this.h){if(T.l===_)this.V(T);T=T.B}return this.i}eraseElementByIterator(_){let T=_.o;if(T===this.h)(0,IT.throwIteratorAccessError)();return _=_.next(),this.V(T),_}pushBack(_){return this.G(_,this._),this.i}popBack(){if(this.i===0)return;let _=this._.l;return this.V(this._),_}pushFront(_){return this.G(_,this.h),this.i}popFront(){if(this.i===0)return;let _=this.p.l;return this.V(this.p),_}setElementByPos(_,T){if(_<0||_>this.i-1)throw RangeError();let A=this.p;while(_--)A=A.B;A.l=T}insert(_,T,A=1){if(_<0||_>this.i)throw RangeError();if(A<=0)return this.i;if(_===0)while(A--)this.pushFront(T);else if(_===this.i)while(A--)this.pushBack(T);else{let E=this.p;for(let J=1;J<_;++J)E=E.B;let L=E.B;this.i+=A;while(A--)E.B={l:T,L:E},E.B.L=E,E=E.B;E.B=L,L.L=E}return this.i}find(_){let T=this.p;while(T!==this.h){if(T.l===_)return new PT(T,this.h,this);T=T.B}return this.end()}reverse(){if(this.i<=1)return;let _=this.p,T=this._,A=0;while(A<<1<this.i){let E=_.l;_.l=T.l,T.l=E,_=_.B,T=T.L,A+=1}}unique(){if(this.i<=1)return this.i;let _=this.p;while(_!==this.h){let T=_;while(T.B!==this.h&&T.l===T.B.l)T=T.B,this.i-=1;_.B=T.B,_.B.L=_,_=_.B}return this.i}sort(_){if(this.i<=1)return;let T=[];this.forEach(function(E){T.push(E)}),T.sort(_);let A=this.p;T.forEach(function(E){A.l=E,A=A.B})}merge(_){let T=this;if(this.i===0)_.forEach(function(A){T.pushBack(A)});else{let A=this.p;_.forEach(function(E){while(A!==T.h&&A.l<=E)A=A.B;T.G(E,A.L)})}return this.i}forEach(_){let T=this.p,A=0;while(T!==this.h)_(T.l,A++,this),T=T.B}[Symbol.iterator](){return function*(){if(this.i===0)return;let _=this.p;while(_!==this.h)yield _.l,_=_.B}.bind(this)()}}var ij=H3;Z3.default=ij});var W3=W(($3)=>{Object.defineProperty($3,"t",{value:!0});$3.default=void 0;var aj=rj(dA()),oj=aE();function rj(_){return _&&_.t?_:{default:_}}class jT extends oj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new jT(this.o,this.container,this.iteratorType)}}class G3 extends aj.default{constructor(_=[],T=4096){super();this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let A=(()=>{if(typeof _.length==="number")return _.length;if(typeof _.size==="number")return _.size;if(typeof _.size==="function")return _.size();throw TypeError("Cannot get the length or size of the container")})();this.F=T,this.P=Math.max(Math.ceil(A/this.F),1);for(let J=0;J<this.P;++J)this.A.push(Array(this.F));let E=Math.ceil(A/this.F);this.j=this.R=(this.P>>1)-(E>>1),this.D=this.N=this.F-A%this.F>>1;let L=this;_.forEach(function(J){L.pushBack(J)})}T(){let _=[],T=Math.max(this.P>>1,1);for(let A=0;A<T;++A)_[A]=Array(this.F);for(let A=this.j;A<this.P;++A)_[_.length]=this.A[A];for(let A=0;A<this.R;++A)_[_.length]=this.A[A];_[_.length]=[...this.A[this.R]],this.j=T,this.R=_.length-1;for(let A=0;A<T;++A)_[_.length]=Array(this.F);this.A=_,this.P=_.length}O(_){let T=this.D+_+1,A=T%this.F,E=A-1,L=this.j+(T-A)/this.F;if(A===0)L-=1;if(L%=this.P,E<0)E+=this.F;return{curNodeBucketIndex:L,curNodePointerIndex:E}}clear(){this.A=[Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new jT(0,this)}end(){return new jT(this.i,this)}rBegin(){return new jT(this.i-1,this,1)}rEnd(){return new jT(-1,this,1)}front(){if(this.i===0)return;return this.A[this.j][this.D]}back(){if(this.i===0)return;return this.A[this.R][this.N]}pushBack(_){if(this.i){if(this.N<this.F-1)this.N+=1;else if(this.R<this.P-1)this.R+=1,this.N=0;else this.R=0,this.N=0;if(this.R===this.j&&this.N===this.D)this.T()}return this.i+=1,this.A[this.R][this.N]=_,this.i}popBack(){if(this.i===0)return;let _=this.A[this.R][this.N];if(this.i!==1)if(this.N>0)this.N-=1;else if(this.R>0)this.R-=1,this.N=this.F-1;else this.R=this.P-1,this.N=this.F-1;return this.i-=1,_}pushFront(_){if(this.i){if(this.D>0)this.D-=1;else if(this.j>0)this.j-=1,this.D=this.F-1;else this.j=this.P-1,this.D=this.F-1;if(this.j===this.R&&this.D===this.N)this.T()}return this.i+=1,this.A[this.j][this.D]=_,this.i}popFront(){if(this.i===0)return;let _=this.A[this.j][this.D];if(this.i!==1)if(this.D<this.F-1)this.D+=1;else if(this.j<this.P-1)this.j+=1,this.D=0;else this.j=0,this.D=0;return this.i-=1,_}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let{curNodeBucketIndex:T,curNodePointerIndex:A}=this.O(_);return this.A[T][A]}setElementByPos(_,T){if(_<0||_>this.i-1)throw RangeError();let{curNodeBucketIndex:A,curNodePointerIndex:E}=this.O(_);this.A[A][E]=T}insert(_,T,A=1){if(_<0||_>this.i)throw RangeError();if(_===0)while(A--)this.pushFront(T);else if(_===this.i)while(A--)this.pushBack(T);else{let E=[];for(let L=_;L<this.i;++L)E.push(this.getElementByPos(L));this.cut(_-1);for(let L=0;L<A;++L)this.pushBack(T);for(let L=0;L<E.length;++L)this.pushBack(E[L])}return this.i}cut(_){if(_<0)return this.clear(),0;let{curNodeBucketIndex:T,curNodePointerIndex:A}=this.O(_);return this.R=T,this.N=A,this.i=_+1,this.i}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();if(_===0)this.popFront();else if(_===this.i-1)this.popBack();else{let T=[];for(let E=_+1;E<this.i;++E)T.push(this.getElementByPos(E));this.cut(_),this.popBack();let A=this;T.forEach(function(E){A.pushBack(E)})}return this.i}eraseElementByValue(_){if(this.i===0)return 0;let T=[];for(let E=0;E<this.i;++E){let L=this.getElementByPos(E);if(L!==_)T.push(L)}let A=T.length;for(let E=0;E<A;++E)this.setElementByPos(E,T[E]);return this.cut(A-1)}eraseElementByIterator(_){let T=_.o;return this.eraseElementByPos(T),_=_.next(),_}find(_){for(let T=0;T<this.i;++T)if(this.getElementByPos(T)===_)return new jT(T,this);return this.end()}reverse(){let _=0,T=this.i-1;while(_<T){let A=this.getElementByPos(_);this.setElementByPos(_,this.getElementByPos(T)),this.setElementByPos(T,A),_+=1,T-=1}}unique(){if(this.i<=1)return this.i;let _=1,T=this.getElementByPos(0);for(let A=1;A<this.i;++A){let E=this.getElementByPos(A);if(E!==T)T=E,this.setElementByPos(_++,E)}while(this.i>_)this.popBack();return this.i}sort(_){let T=[];for(let A=0;A<this.i;++A)T.push(this.getElementByPos(A));T.sort(_);for(let A=0;A<this.i;++A)this.setElementByPos(A,T[A])}shrinkToFit(){if(this.i===0)return;let _=[];this.forEach(function(T){_.push(T)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let T=0;T<this.P;++T)this.A.push(Array(this.F));for(let T=0;T<_.length;++T)this.pushBack(_[T])}forEach(_){for(let T=0;T<this.i;++T)_(this.getElementByPos(T),T,this)}[Symbol.iterator](){return function*(){for(let _=0;_<this.i;++_)yield this.getElementByPos(_)}.bind(this)()}}var sj=G3;$3.default=sj});var V3=W((Q3)=>{Object.defineProperty(Q3,"t",{value:!0});Q3.TreeNodeEnableIndex=Q3.TreeNode=void 0;class oE{constructor(_,T){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=_,this.l=T}L(){let _=this;if(_.ee===1&&_.tt.tt===_)_=_.W;else if(_.U){_=_.U;while(_.W)_=_.W}else{let T=_.tt;while(T.U===_)_=T,T=_.tt;_=T}return _}B(){let _=this;if(_.W){_=_.W;while(_.U)_=_.U;return _}else{let T=_.tt;while(T.W===_)_=T,T=_.tt;if(_.W!==T)return T;else return _}}te(){let _=this.tt,T=this.W,A=T.U;if(_.tt===this)_.tt=T;else if(_.U===this)_.U=T;else _.W=T;if(T.tt=_,T.U=this,this.tt=T,this.W=A,A)A.tt=this;return T}se(){let _=this.tt,T=this.U,A=T.W;if(_.tt===this)_.tt=T;else if(_.U===this)_.U=T;else _.W=T;if(T.tt=_,T.W=this,this.tt=T,this.U=A,A)A.tt=this;return T}}Q3.TreeNode=oE;class N3 extends oE{constructor(){super(...arguments);this.rt=1}te(){let _=super.te();return this.ie(),_.ie(),_}se(){let _=super.se();return this.ie(),_.ie(),_}ie(){if(this.rt=1,this.U)this.rt+=this.U.rt;if(this.W)this.rt+=this.W.rt}}Q3.TreeNodeEnableIndex=N3});var rE=W((O3)=>{Object.defineProperty(O3,"t",{value:!0});O3.default=void 0;var z3=V3(),ej=Y0(),F3=K0();class C3 extends ej.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=z3.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=z3.TreeNode,this.M=function(A,E,L){let J=this.ne(A,E,L);if(J)this.he(J);return this.i},this.V=this.fe;this.h=new this.re}X(_,T){let A=this.h;while(_){let E=this.v(_.u,T);if(E<0)_=_.W;else if(E>0)A=_,_=_.U;else return _}return A}Z(_,T){let A=this.h;while(_)if(this.v(_.u,T)<=0)_=_.W;else A=_,_=_.U;return A}$(_,T){let A=this.h;while(_){let E=this.v(_.u,T);if(E<0)A=_,_=_.W;else if(E>0)_=_.U;else return _}return A}rr(_,T){let A=this.h;while(_)if(this.v(_.u,T)<0)A=_,_=_.W;else _=_.U;return A}ue(_){while(!0){let T=_.tt;if(T===this.h)return;if(_.ee===1){_.ee=0;return}if(_===T.U){let A=T.W;if(A.ee===1)if(A.ee=0,T.ee=1,T===this.Y)this.Y=T.te();else T.te();else if(A.W&&A.W.ee===1){if(A.ee=T.ee,T.ee=0,A.W.ee=0,T===this.Y)this.Y=T.te();else T.te();return}else if(A.U&&A.U.ee===1)A.ee=1,A.U.ee=0,A.se();else A.ee=1,_=T}else{let A=T.U;if(A.ee===1)if(A.ee=0,T.ee=1,T===this.Y)this.Y=T.se();else T.se();else if(A.U&&A.U.ee===1){if(A.ee=T.ee,T.ee=0,A.U.ee=0,T===this.Y)this.Y=T.se();else T.se();return}else if(A.W&&A.W.ee===1)A.ee=1,A.W.ee=0,A.te();else A.ee=1,_=T}}}fe(_){if(this.i===1)return this.clear(),this.h;let T=_;while(T.U||T.W){if(T.W){T=T.W;while(T.U)T=T.U}else T=T.U;[_.u,T.u]=[T.u,_.u],[_.l,T.l]=[T.l,_.l],_=T}if(this.h.U===T)this.h.U=T.tt;else if(this.h.W===T)this.h.W=T.tt;this.ue(T);let A=T.tt;if(T===A.U)A.U=void 0;else A.W=void 0;return this.i-=1,this.Y.ee=0,A}oe(_,T){if(_===void 0)return!1;if(this.oe(_.U,T))return!0;if(T(_))return!0;return this.oe(_.W,T)}he(_){while(!0){let T=_.tt;if(T.ee===0)return;let A=T.tt;if(T===A.U){let E=A.W;if(E&&E.ee===1){if(E.ee=T.ee=0,A===this.Y)return;A.ee=1,_=A;continue}else if(_===T.W){if(_.ee=0,_.U)_.U.tt=T;if(_.W)_.W.tt=A;if(T.W=_.U,A.U=_.W,_.U=T,_.W=A,A===this.Y)this.Y=_,this.h.tt=_;else{let L=A.tt;if(L.U===A)L.U=_;else L.W=_}return _.tt=A.tt,T.tt=_,A.tt=_,A.ee=1,{parentNode:T,grandParent:A,curNode:_}}else{if(T.ee=0,A===this.Y)this.Y=A.se();else A.se();A.ee=1}}else{let E=A.U;if(E&&E.ee===1){if(E.ee=T.ee=0,A===this.Y)return;A.ee=1,_=A;continue}else if(_===T.U){if(_.ee=0,_.U)_.U.tt=A;if(_.W)_.W.tt=T;if(A.W=_.U,T.U=_.W,_.U=A,_.W=T,A===this.Y)this.Y=_,this.h.tt=_;else{let L=A.tt;if(L.U===A)L.U=_;else L.W=_}return _.tt=A.tt,T.tt=_,A.tt=_,A.ee=1,{parentNode:T,grandParent:A,curNode:_}}else{if(T.ee=0,A===this.Y)this.Y=A.te();else A.te();A.ee=1}}return}}ne(_,T,A){if(this.Y===void 0){this.i+=1,this.Y=new this.re(_,T),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let E,L=this.h.U,J=this.v(L.u,_);if(J===0){L.l=T;return}else if(J>0)L.U=new this.re(_,T),L.U.tt=L,E=L.U,this.h.U=E;else{let X=this.h.W,H=this.v(X.u,_);if(H===0){X.l=T;return}else if(H<0)X.W=new this.re(_,T),X.W.tt=X,E=X.W,this.h.W=E;else{if(A!==void 0){let Z=A.o;if(Z!==this.h){let Y=this.v(Z.u,_);if(Y===0){Z.l=T;return}else if(Y>0){let K=Z.L(),G=this.v(K.u,_);if(G===0){K.l=T;return}else if(G<0)if(E=new this.re(_,T),K.W===void 0)K.W=E,E.tt=K;else Z.U=E,E.tt=Z}}}if(E===void 0){E=this.Y;while(!0){let Z=this.v(E.u,_);if(Z>0){if(E.U===void 0){E.U=new this.re(_,T),E.U.tt=E,E=E.U;break}E=E.U}else if(Z<0){if(E.W===void 0){E.W=new this.re(_,T),E.W.tt=E,E=E.W;break}E=E.W}else{E.l=T;return}}}}}return this.i+=1,E}I(_,T){while(_){let A=this.v(_.u,T);if(A<0)_=_.W;else if(A>0)_=_.U;else return _}return _||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(_,T){let A=_.o;if(A===this.h)(0,F3.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,F3.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 _x=C3;O3.default=_x});var sE=W((B3)=>{Object.defineProperty(B3,"t",{value:!0});B3.default=void 0;var Tx=Y0(),pA=K0();class D3 extends Tx.ContainerIterator{constructor(_,T,A){super(A);if(this.o=_,this.h=T,this.iteratorType===0)this.pre=function(){if(this.o===this.h.U)(0,pA.throwIteratorAccessError)();return this.o=this.o.L(),this},this.next=function(){if(this.o===this.h)(0,pA.throwIteratorAccessError)();return this.o=this.o.B(),this};else this.pre=function(){if(this.o===this.h.W)(0,pA.throwIteratorAccessError)();return this.o=this.o.B(),this},this.next=function(){if(this.o===this.h)(0,pA.throwIteratorAccessError)();return this.o=this.o.L(),this}}get index(){let _=this.o,T=this.h.tt;if(_===this.h){if(T)return T.rt-1;return 0}let A=0;if(_.U)A+=_.U.rt;while(_!==T){let E=_.tt;if(_===E.W){if(A+=1,E.U)A+=E.U.rt}_=E}return A}}var Ax=D3;B3.default=Ax});var w3=W((j3)=>{Object.defineProperty(j3,"t",{value:!0});j3.default=void 0;var Ex=I3(rE()),Lx=I3(sE()),Jx=K0();function I3(_){return _&&_.t?_:{default:_}}class c1 extends Lx.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Jx.throwIteratorAccessError)();return this.o.u}copy(){return new c1(this.o,this.h,this.container,this.iteratorType)}}class P3 extends Ex.default{constructor(_=[],T,A){super(T,A);let E=this;_.forEach(function(L){E.insert(L)})}*K(_){if(_===void 0)return;yield*this.K(_.U),yield _.u,yield*this.K(_.W)}begin(){return new c1(this.h.U||this.h,this.h,this)}end(){return new c1(this.h,this.h,this)}rBegin(){return new c1(this.h.W||this.h,this.h,this,1)}rEnd(){return new c1(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(_,T){return this.M(_,void 0,T)}find(_){let T=this.I(this.Y,_);return new c1(T,this.h,this)}lowerBound(_){let T=this.X(this.Y,_);return new c1(T,this.h,this)}upperBound(_){let T=this.Z(this.Y,_);return new c1(T,this.h,this)}reverseLowerBound(_){let T=this.$(this.Y,_);return new c1(T,this.h,this)}reverseUpperBound(_){let T=this.rr(this.Y,_);return new c1(T,this.h,this)}union(_){let T=this;return _.forEach(function(A){T.insert(A)}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var Xx=P3;j3.default=Xx});var k3=W((v3)=>{Object.defineProperty(v3,"t",{value:!0});v3.default=void 0;var Hx=S3(rE()),Zx=S3(sE()),Yx=K0();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)();let _=this;return new Proxy([],{get(T,A){if(A==="0")return _.o.u;else if(A==="1")return _.o.l},set(T,A,E){if(A!=="1")throw TypeError("props must be 1");return _.o.l=E,!0}})}copy(){return new p1(this.o,this.h,this.container,this.iteratorType)}}class y3 extends Hx.default{constructor(_=[],T,A){super(T,A);let E=this;_.forEach(function(L){E.setElement(L[0],L[1])})}*K(_){if(_===void 0)return;yield*this.K(_.U),yield[_.u,_.l],yield*this.K(_.W)}begin(){return new p1(this.h.U||this.h,this.h,this)}end(){return new p1(this.h,this.h,this)}rBegin(){return new p1(this.h.W||this.h,this.h,this,1)}rEnd(){return new p1(this.h,this.h,this,1)}front(){if(this.i===0)return;let _=this.h.U;return[_.u,_.l]}back(){if(this.i===0)return;let _=this.h.W;return[_.u,_.l]}lowerBound(_){let T=this.X(this.Y,_);return new p1(T,this.h,this)}upperBound(_){let T=this.Z(this.Y,_);return new p1(T,this.h,this)}reverseLowerBound(_){let T=this.$(this.Y,_);return new p1(T,this.h,this)}reverseUpperBound(_){let T=this.rr(this.Y,_);return new p1(T,this.h,this)}setElement(_,T,A){return this.M(_,T,A)}find(_){let T=this.I(this.Y,_);return new p1(T,this.h,this)}getElementByKey(_){return this.I(this.Y,_).l}union(_){let T=this;return _.forEach(function(A){T.setElement(A[0],A[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var Kx=y3;v3.default=Kx});var tE=W((f3)=>{Object.defineProperty(f3,"t",{value:!0});f3.default=Gx;function Gx(_){let T=typeof _;return T==="object"&&_!==null||T==="function"}});var _L=W((u3)=>{Object.defineProperty(u3,"t",{value:!0});u3.HashContainerIterator=u3.HashContainer=void 0;var b3=Y0(),eE=Ux(tE()),T8=K0();function Ux(_){return _&&_.t?_:{default:_}}class g3 extends b3.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}}}u3.HashContainerIterator=g3;class m3 extends b3.Container{constructor(){super();this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(_){let{L:T,B:A}=_;if(T.B=A,A.L=T,_===this.p)this.p=A;if(_===this._)this._=T;this.i-=1}M(_,T,A){if(A===void 0)A=(0,eE.default)(_);let E;if(A){let L=_[this.HASH_TAG];if(L!==void 0)return this.H[L].l=T,this.i;Object.defineProperty(_,this.HASH_TAG,{value:this.H.length,configurable:!0}),E={u:_,l:T,L:this._,B:this.h},this.H.push(E)}else{let L=this.g[_];if(L)return L.l=T,this.i;E={u:_,l:T,L:this._,B:this.h},this.g[_]=E}if(this.i===0)this.p=E,this.h.B=E;else this._.B=E;return this._=E,this.h.L=E,++this.i}I(_,T){if(T===void 0)T=(0,eE.default)(_);if(T){let A=_[this.HASH_TAG];if(A===void 0)return this.h;return this.H[A]}else return this.g[_]||this.h}clear(){let _=this.HASH_TAG;this.H.forEach(function(T){delete T.u[_]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(_,T){let A;if(T===void 0)T=(0,eE.default)(_);if(T){let E=_[this.HASH_TAG];if(E===void 0)return!1;delete _[this.HASH_TAG],A=this.H[E],delete this.H[E]}else{if(A=this.g[_],A===void 0)return!1;delete this.g[_]}return this.V(A),!0}eraseElementByIterator(_){let T=_.o;if(T===this.h)(0,T8.throwIteratorAccessError)();return this.V(T),_.next()}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return this.V(T),this.i}}u3.HashContainer=m3});var i3=W((l3)=>{Object.defineProperty(l3,"t",{value:!0});l3.default=void 0;var c3=_L(),Nx=K0();class xT extends c3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Nx.throwIteratorAccessError)();return this.o.u}copy(){return new xT(this.o,this.h,this.container,this.iteratorType)}}class p3 extends c3.HashContainer{constructor(_=[]){super();let T=this;_.forEach(function(A){T.insert(A)})}begin(){return new xT(this.p,this.h,this)}end(){return new xT(this.h,this.h,this)}rBegin(){return new xT(this._,this.h,this,1)}rEnd(){return new xT(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(_,T){return this.M(_,void 0,T)}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return T.u}find(_,T){let A=this.I(_,T);return new xT(A,this.h,this)}forEach(_){let T=0,A=this.p;while(A!==this.h)_(A.u,T++,this),A=A.B}[Symbol.iterator](){return function*(){let _=this.p;while(_!==this.h)yield _.u,_=_.B}.bind(this)()}}var Qx=p3;l3.default=Qx});var t3=W((r3)=>{Object.defineProperty(r3,"t",{value:!0});r3.default=void 0;var a3=_L(),Mx=zx(tE()),Vx=K0();function zx(_){return _&&_.t?_:{default:_}}class wT extends a3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Vx.throwIteratorAccessError)();let _=this;return new Proxy([],{get(T,A){if(A==="0")return _.o.u;else if(A==="1")return _.o.l},set(T,A,E){if(A!=="1")throw TypeError("props must be 1");return _.o.l=E,!0}})}copy(){return new wT(this.o,this.h,this.container,this.iteratorType)}}class o3 extends a3.HashContainer{constructor(_=[]){super();let T=this;_.forEach(function(A){T.setElement(A[0],A[1])})}begin(){return new wT(this.p,this.h,this)}end(){return new wT(this.h,this.h,this)}rBegin(){return new wT(this._,this.h,this,1)}rEnd(){return new wT(this.h,this.h,this,1)}front(){if(this.i===0)return;return[this.p.u,this.p.l]}back(){if(this.i===0)return;return[this._.u,this._.l]}setElement(_,T,A){return this.M(_,T,A)}getElementByKey(_,T){if(T===void 0)T=(0,Mx.default)(_);if(T){let E=_[this.HASH_TAG];return E!==void 0?this.H[E].l:void 0}let A=this.g[_];return A?A.l:void 0}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return[T.u,T.l]}find(_,T){let A=this.I(_,T);return new wT(A,this.h,this)}forEach(_){let T=0,A=this.p;while(A!==this.h)_([A.u,A.l],T++,this),A=A.B}[Symbol.iterator](){return function*(){let _=this.p;while(_!==this.h)yield[_.u,_.l],_=_.B}.bind(this)()}}var Fx=o3;r3.default=Fx});var e3=W((B1)=>{Object.defineProperty(B1,"t",{value:!0});Object.defineProperty(B1,"Deque",{enumerable:!0,get:function(){return qx.default}});Object.defineProperty(B1,"HashMap",{enumerable:!0,get:function(){return xx.default}});Object.defineProperty(B1,"HashSet",{enumerable:!0,get:function(){return jx.default}});Object.defineProperty(B1,"LinkList",{enumerable:!0,get:function(){return Bx.default}});Object.defineProperty(B1,"OrderedMap",{enumerable:!0,get:function(){return Px.default}});Object.defineProperty(B1,"OrderedSet",{enumerable:!0,get:function(){return Ix.default}});Object.defineProperty(B1,"PriorityQueue",{enumerable:!0,get:function(){return Rx.default}});Object.defineProperty(B1,"Queue",{enumerable:!0,get:function(){return Ox.default}});Object.defineProperty(B1,"Stack",{enumerable:!0,get:function(){return Cx.default}});Object.defineProperty(B1,"Vector",{enumerable:!0,get:function(){return Dx.default}});var Cx=G0(uK()),Ox=G0(lK()),Rx=G0(oK()),Dx=G0(X3()),Bx=G0(K3()),qx=G0(W3()),Ix=G0(w3()),Px=G0(k3()),jx=G0(i3()),xx=G0(t3());function G0(_){return _&&_.t?_:{default:_}}});var TG=W((bg,_G)=>{var Sx=e3().OrderedSet,$0=u1()("number-allocator:trace"),yx=u1()("number-allocator:error");function e_(_,T){this.low=_,this.high=T}e_.prototype.equals=function(_){return this.low===_.low&&this.high===_.high};e_.prototype.compare=function(_){if(this.low<_.low&&this.high<_.low)return-1;if(_.low<this.low&&_.high<this.low)return 1;return 0};function U0(_,T){if(!(this instanceof U0))return new U0(_,T);this.min=_,this.max=T,this.ss=new Sx([],(A,E)=>{return A.compare(E)}),$0("Create"),this.clear()}U0.prototype.firstVacant=function(){if(this.ss.size()===0)return null;return this.ss.front().low};U0.prototype.alloc=function(){if(this.ss.size()===0)return $0("alloc():empty"),null;let _=this.ss.begin(),T=_.pointer.low,A=_.pointer.high,E=T;if(E+1<=A)this.ss.updateKeyByIterator(_,new e_(T+1,A));else this.ss.eraseElementByPos(0);return $0("alloc():"+E),E};U0.prototype.use=function(_){let T=new e_(_,_),A=this.ss.lowerBound(T);if(!A.equals(this.ss.end())){let E=A.pointer.low,L=A.pointer.high;if(A.pointer.equals(T))return this.ss.eraseElementByIterator(A),$0("use():"+_),!0;if(E>_)return!1;if(E===_)return this.ss.updateKeyByIterator(A,new e_(E+1,L)),$0("use():"+_),!0;if(L===_)return this.ss.updateKeyByIterator(A,new e_(E,L-1)),$0("use():"+_),!0;return this.ss.updateKeyByIterator(A,new e_(_+1,L)),this.ss.insert(new e_(E,_-1)),$0("use():"+_),!0}return $0("use():failed"),!1};U0.prototype.free=function(_){if(_<this.min||_>this.max){yx("free():"+_+" is out of range");return}let T=new e_(_,_),A=this.ss.upperBound(T);if(A.equals(this.ss.end())){if(A.equals(this.ss.begin())){this.ss.insert(T);return}A.pre();let E=A.pointer.high;if(A.pointer.high+1===_)this.ss.updateKeyByIterator(A,new e_(E,_));else this.ss.insert(T)}else if(A.equals(this.ss.begin()))if(_+1===A.pointer.low){let E=A.pointer.high;this.ss.updateKeyByIterator(A,new e_(_,E))}else this.ss.insert(T);else{let E=A.pointer.low,L=A.pointer.high;A.pre();let J=A.pointer.low;if(A.pointer.high+1===_)if(_+1===E)this.ss.eraseElementByIterator(A),this.ss.updateKeyByIterator(A,new e_(J,L));else this.ss.updateKeyByIterator(A,new e_(J,_));else if(_+1===E)this.ss.eraseElementByIterator(A.next()),this.ss.insert(new e_(_,L));else this.ss.insert(T)}$0("free():"+_)};U0.prototype.clear=function(){$0("clear()"),this.ss.clear(),this.ss.insert(new e_(this.min,this.max))};U0.prototype.intervalCount=function(){return this.ss.size()};U0.prototype.dump=function(){console.log("length:"+this.ss.size());for(let _ of this.ss)console.log(_)};_G.exports=U0});var TL=W((hx,AG)=>{var vx=TG();hx.NumberAllocator=vx});var JG=W((LG)=>{Object.defineProperty(LG,"__esModule",{value:!0});var fx=yK(),bx=TL();class EG{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(_){if(_>0)this.aliasToTopic=new fx.LRUCache({max:_}),this.topicToAlias={},this.numberAllocator=new bx.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]}}LG.default=EG});var XG=W((A8)=>{var mx=A8&&A8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(A8,"__esModule",{value:!0});var ux=e4(),dx=mx(JG()),cx=BT(),px=(_,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 dx.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 cx.ErrorWithReasonCode(`Connection refused: ${ux.ReasonCodes[L]}`,L);if(_.emit("error",J),_.options.reconnectOnConnackError)_._cleanUp(!0)}};A8.default=px});var ZG=W((HG)=>{Object.defineProperty(HG,"__esModule",{value:!0});var lx=(_,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)})};HG.default=lx});var YG=W((E8)=>{var L8=E8&&E8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(E8,"__esModule",{value:!0});var ix=L8(VK()),ax=L8(qK()),ox=L8(XG()),rx=L8(e4()),sx=L8(ZG()),tx=(_,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,ix.default)(_,T,A);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":_.reschedulePing(),(0,rx.default)(_,T),A();break;case"pubrel":_.reschedulePing(),(0,sx.default)(_,T,A);break;case"connack":(0,ox.default)(_,T),A();break;case"auth":_.reschedulePing(),(0,ax.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=tx});var AL=W((GG)=>{Object.defineProperty(GG,"__esModule",{value:!0});class KG{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(){}}GG.default=KG});var WG=W((UG)=>{Object.defineProperty(UG,"__esModule",{value:!0});class $G{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={}}}UG.default=$G});var NG=W((K4)=>{var Tw=K4&&K4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(K4,"__esModule",{value:!0});K4.TypedEventEmitter=void 0;var Aw=Tw(j("events")),Ew=BT();class EL{}K4.TypedEventEmitter=EL;(0,Ew.applyMixin)(EL,Aw.default)});var J8=W((ng,S0)=>{function LL(_){return S0.exports=LL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(T){return typeof T}:function(T){return T&&typeof Symbol=="function"&&T.constructor===Symbol&&T!==Symbol.prototype?"symbol":typeof T},S0.exports.__esModule=!0,S0.exports.default=S0.exports,LL(_)}S0.exports=LL,S0.exports.__esModule=!0,S0.exports.default=S0.exports});var MG=W((ig,X8)=>{var QG=J8().default;function Lw(_,T){if(QG(_)!="object"||!_)return _;var A=_[Symbol.toPrimitive];if(A!==void 0){var E=A.call(_,T||"default");if(QG(E)!="object")return E;throw TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(_)}X8.exports=Lw,X8.exports.__esModule=!0,X8.exports.default=X8.exports});var VG=W((ag,H8)=>{var Jw=J8().default,Xw=MG();function Hw(_){var T=Xw(_,"string");return Jw(T)=="symbol"?T:T+""}H8.exports=Hw,H8.exports.__esModule=!0,H8.exports.default=H8.exports});var zG=W((og,Z8)=>{var Zw=VG();function Yw(_,T,A){return(T=Zw(T))in _?Object.defineProperty(_,T,{value:A,enumerable:!0,configurable:!0,writable:!0}):_[T]=A,_}Z8.exports=Yw,Z8.exports.__esModule=!0,Z8.exports.default=Z8.exports});var FG=W((rg,Y8)=>{function Kw(_){if(Array.isArray(_))return _}Y8.exports=Kw,Y8.exports.__esModule=!0,Y8.exports.default=Y8.exports});var CG=W((sg,K8)=>{function Gw(_,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=Gw,K8.exports.__esModule=!0,K8.exports.default=K8.exports});var OG=W((tg,G8)=>{function $w(_,T){(T==null||T>_.length)&&(T=_.length);for(var A=0,E=Array(T);A<T;A++)E[A]=_[A];return E}G8.exports=$w,G8.exports.__esModule=!0,G8.exports.default=G8.exports});var DG=W((eg,$8)=>{var RG=OG();function Uw(_,T){if(_){if(typeof _=="string")return RG(_,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)?RG(_,T):void 0}}$8.exports=Uw,$8.exports.__esModule=!0,$8.exports.default=$8.exports});var BG=W((_m,U8)=>{function Ww(){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=Ww,U8.exports.__esModule=!0,U8.exports.default=U8.exports});var qG=W((Tm,W8)=>{var Nw=FG(),Qw=CG(),Mw=DG(),Vw=BG();function zw(_,T){return Nw(_)||Qw(_,T)||Mw(_,T)||Vw()}W8.exports=zw,W8.exports.__esModule=!0,W8.exports.default=W8.exports});var jG=W((IG)=>{Object.defineProperty(IG,"__esModule",{value:!0});IG.createAddUniqueNumber=void 0;var Fw=(_)=>{return(T)=>{let A=_(T);return T.add(A),A}};IG.createAddUniqueNumber=Fw});var SG=W((xG)=>{Object.defineProperty(xG,"__esModule",{value:!0});xG.createCache=void 0;var Cw=(_)=>{return(T,A)=>{return _.set(T,A),A}};xG.createCache=Cw});var bG=W((kG)=>{Object.defineProperty(kG,"__esModule",{value:!0});kG.createGenerateUniqueNumber=void 0;var yG=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,hG=536870912,vG=hG*2,Ow=(_,T)=>{return(A)=>{let E=T.get(A),L=E===void 0?A.size:E<vG?E+1:0;if(!A.has(L))return _(A,L);if(A.size<hG){while(A.has(L))L=Math.floor(Math.random()*vG);return _(A,L)}if(A.size>yG)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(A.has(L))L=Math.floor(Math.random()*yG);return _(A,L)}};kG.createGenerateUniqueNumber=Ow});var JL=W((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});mG.generateUniqueNumber=mG.addUniqueNumber=void 0;var Rw=jG(),Dw=SG(),Bw=bG(),gG=new WeakMap,qw=(0,Dw.createCache)(gG),Iw=mG.generateUniqueNumber=(0,Bw.createGenerateUniqueNumber)(qw,gG),Jm=mG.addUniqueNumber=(0,Rw.createAddUniqueNumber)(Iw)});var cG=W((Hm,N8)=>{function dG(_,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 jw(_){return function(){var T=this,A=arguments;return new Promise(function(E,L){var J=_.apply(T,A);function X(Z){dG(J,E,L,X,H,"next",Z)}function H(Z){dG(J,E,L,X,H,"throw",Z)}X(void 0)})}}N8.exports=jw,N8.exports.__esModule=!0,N8.exports.default=N8.exports});var XL=W((Zm,Q8)=>{function xw(_,T){this.v=_,this.k=T}Q8.exports=xw,Q8.exports.__esModule=!0,Q8.exports.default=Q8.exports});var HL=W((Ym,y0)=>{function lA(_,T,A,E){var L=Object.defineProperty;try{L({},"",{})}catch(J){L=0}y0.exports=lA=function(X,H,Z,Y){function K(G,$){lA(X,G,function(U){return this._invoke(G,$,U)})}H?L?L(X,H,{value:Z,enumerable:!Y,configurable:!Y,writable:!Y}):X[H]=Z:(K("next",0),K("throw",1),K("return",2))},y0.exports.__esModule=!0,y0.exports.default=y0.exports,lA(_,T,A,E)}y0.exports=lA,y0.exports.__esModule=!0,y0.exports.default=y0.exports});var ZL=W((Km,v0)=>{var W0=HL();function pG(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var _,T,A=typeof Symbol=="function"?Symbol:{},E=A.iterator||"@@iterator",L=A.toStringTag||"@@toStringTag";function J(U,V,N,z){var Q=V&&V.prototype instanceof H?V:H,F=Object.create(Q.prototype);return W0(F,"_invoke",function(R,q,f){var h,b,l,c=0,W_=f||[],c_=!1,B_={p:0,n:0,v:_,a:C_,f:C_.bind(_,4),d:function(M_,q_){return h=M_,b=0,l=_,B_.n=q_,X}};function C_(K_,M_){for(b=K_,l=M_,T=0;!c_&&c&&!q_&&T<W_.length;T++){var q_,P_=W_[T],O0=B_.p,S1=P_[2];K_>3?(q_=S1===M_)&&(l=P_[(b=P_[4])?5:(b=3,3)],P_[4]=P_[5]=_):P_[0]<=O0&&((q_=K_<2&&O0<P_[1])?(b=0,B_.v=M_,B_.n=P_[1]):O0<S1&&(q_=K_<3||P_[0]>M_||M_>S1)&&(P_[4]=K_,P_[5]=M_,B_.n=S1,b=0))}if(q_||K_>1)return X;throw c_=!0,M_}return function(K_,M_,q_){if(c>1)throw TypeError("Generator is already running");for(c_&&M_===1&&C_(M_,q_),b=M_,l=q_;(T=b<2?_:l)||!c_;){h||(b?b<3?(b>1&&(B_.n=-1),C_(b,l)):B_.n=l:B_.v=l);try{if(c=2,h){if(b||(K_="next"),T=h[K_]){if(!(T=T.call(h,l)))throw TypeError("iterator result is not an object");if(!T.done)return T;l=T.value,b<2&&(b=0)}else b===1&&(T=h.return)&&T.call(h),b<2&&(l=TypeError("The iterator does not provide a '"+K_+"' method"),b=1);h=_}else if((T=(c_=B_.n<0)?l:R.call(q,B_))!==X)break}catch(P_){h=_,b=1,l=P_}finally{c=1}}return{value:T,done:c_}}}(U,N,z),!0),F}var X={};function H(){}function Z(){}function Y(){}T=Object.getPrototypeOf;var K=[][E]?T(T([][E]())):(W0(T={},E,function(){return this}),T),G=Y.prototype=H.prototype=Object.create(K);function $(U){return Object.setPrototypeOf?Object.setPrototypeOf(U,Y):(U.__proto__=Y,W0(U,L,"GeneratorFunction")),U.prototype=Object.create(G),U}return Z.prototype=Y,W0(G,"constructor",Y),W0(Y,"constructor",Z),Z.displayName="GeneratorFunction",W0(Y,L,"GeneratorFunction"),W0(G),W0(G,L,"Generator"),W0(G,E,function(){return this}),W0(G,"toString",function(){return"[object Generator]"}),(v0.exports=pG=function(){return{w:J,m:$}},v0.exports.__esModule=!0,v0.exports.default=v0.exports)()}v0.exports=pG,v0.exports.__esModule=!0,v0.exports.default=v0.exports});var GL=W((Gm,M8)=>{var ww=XL(),YL=HL();function KL(_,T){function A(L,J,X,H){try{var Z=_[L](J),Y=Z.value;return Y instanceof ww?T.resolve(Y.v).then(function(K){A("next",K,X,H)},function(K){A("throw",K,X,H)}):T.resolve(Y).then(function(K){Z.value=K,X(Z)},function(K){return A("throw",K,X,H)})}catch(K){H(K)}}var E;this.next||(YL(KL.prototype),YL(KL.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),YL(this,"_invoke",function(L,J,X){function H(){return new T(function(Z,Y){A(L,X,Z,Y)})}return E=E?E.then(H,H):H()},!0)}M8.exports=KL,M8.exports.__esModule=!0,M8.exports.default=M8.exports});var $L=W(($m,V8)=>{var Sw=ZL(),yw=GL();function vw(_,T,A,E,L){return new yw(Sw().w(_,T,A,E),L||Promise)}V8.exports=vw,V8.exports.__esModule=!0,V8.exports.default=V8.exports});var lG=W((Um,z8)=>{var hw=$L();function kw(_,T,A,E,L){var J=hw(_,T,A,E,L);return J.next().then(function(X){return X.done?X.value:J.next()})}z8.exports=kw,z8.exports.__esModule=!0,z8.exports.default=z8.exports});var nG=W((Wm,F8)=>{function fw(_){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=fw,F8.exports.__esModule=!0,F8.exports.default=F8.exports});var iG=W((Nm,C8)=>{var bw=J8().default;function gw(_){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(bw(_)+" is not iterable")}C8.exports=gw,C8.exports.__esModule=!0,C8.exports.default=C8.exports});var oG=W((Qm,h0)=>{var mw=XL(),uw=ZL(),dw=lG(),cw=$L(),pw=GL(),lw=nG(),aG=iG();function UL(){var _=uw(),T=_.m(UL),A=(Object.getPrototypeOf?Object.getPrototypeOf(T):T.__proto__).constructor;function E(X){var H=typeof X=="function"&&X.constructor;return!!H&&(H===A||(H.displayName||H.name)==="GeneratorFunction")}var L={throw:1,return:2,break:3,continue:3};function J(X){var H,Z;return function(Y){H||(H={stop:function(){return Z(Y.a,2)},catch:function(){return Y.v},abrupt:function(G,$){return Z(Y.a,L[G],$)},delegateYield:function(G,$,U){return H.resultName=$,Z(Y.d,aG(G),U)},finish:function(G){return Z(Y.f,G)}},Z=function(G,$,U){Y.p=H.prev,Y.n=H.next;try{return G($,U)}finally{H.next=Y.n}}),H.resultName&&(H[H.resultName]=Y.v,H.resultName=void 0),H.sent=Y.v,H.next=Y.n;try{return X.call(this,H)}finally{Y.p=H.prev,Y.n=H.next}}}return(h0.exports=UL=function(){return{wrap:function(Z,Y,K,G){return _.w(J(Z),Y,K,G&&G.reverse())},isGeneratorFunction:E,mark:_.m,awrap:function(Z,Y){return new mw(Z,Y)},AsyncIterator:pw,async:function(Z,Y,K,G,$){return(E(Y)?cw:dw)(J(Z),Y,K,G,$)},keys:lw,values:aG}},h0.exports.__esModule=!0,h0.exports.default=h0.exports)()}h0.exports=UL,h0.exports.__esModule=!0,h0.exports.default=h0.exports});var sG=W((Mm,rG)=>{var nA=oG()();rG.exports=nA;try{regeneratorRuntime=nA}catch(_){if(typeof globalThis==="object")globalThis.regeneratorRuntime=nA;else Function("r","regeneratorRuntime = r")(nA)}});var eG=W((iA,tG)=>{(function(_,T){typeof iA==="object"&&typeof tG<"u"?T(iA,zG(),qG(),JL(),cG(),sG()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.brokerFactory={},_._defineProperty,_._slicedToArray,_.fastUniqueNumbers,_._asyncToGenerator,_._regeneratorRuntime))})(iA,function(_,T,A,E,L,J){var X=function(Q){return typeof Q.start==="function"},H=new WeakMap;function Z(z,Q){var F=Object.keys(z);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(z);Q&&(R=R.filter(function(q){return Object.getOwnPropertyDescriptor(z,q).enumerable})),F.push.apply(F,R)}return F}function Y(z){for(var Q=1;Q<arguments.length;Q++){var F=arguments[Q]!=null?arguments[Q]:{};Q%2?Z(Object(F),!0).forEach(function(R){T(z,R,F[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(z,Object.getOwnPropertyDescriptors(F)):Z(Object(F)).forEach(function(R){Object.defineProperty(z,R,Object.getOwnPropertyDescriptor(F,R))})}return z}var K=function(Q){return Y(Y({},Q),{},{connect:function(R){var q=R.call;return L(J.mark(function f(){var h,b,l,c;return J.wrap(function(W_){while(!0)switch(W_.prev=W_.next){case 0:return h=new MessageChannel,b=h.port1,l=h.port2,W_.next=1,q("connect",{port:b},[b]);case 1:return c=W_.sent,H.set(l,c),W_.abrupt("return",l);case 2:case"end":return W_.stop()}},f)}))},disconnect:function(R){var q=R.call;return function(){var f=L(J.mark(function h(b){var l;return J.wrap(function(c){while(!0)switch(c.prev=c.next){case 0:if(l=H.get(b),l!==void 0){c.next=1;break}throw Error("The given port is not connected.");case 1:return c.next=2,q("disconnect",{portId:l});case 2:case"end":return c.stop()}},h)}));return function(h){return f.apply(this,arguments)}}()},isSupported:function(R){var q=R.call;return function(){return q("isSupported")}}})};function G(z,Q){var F=Object.keys(z);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(z);Q&&(R=R.filter(function(q){return Object.getOwnPropertyDescriptor(z,q).enumerable})),F.push.apply(F,R)}return F}function $(z){for(var Q=1;Q<arguments.length;Q++){var F=arguments[Q]!=null?arguments[Q]:{};Q%2?G(Object(F),!0).forEach(function(R){T(z,R,F[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(z,Object.getOwnPropertyDescriptors(F)):G(Object(F)).forEach(function(R){Object.defineProperty(z,R,Object.getOwnPropertyDescriptor(F,R))})}return z}var U=new WeakMap,V=function(Q){if(U.has(Q))return U.get(Q);var F=new Map;return U.set(Q,F),F},N=function(Q){var F=K(Q);return function(R){var q=V(R);if(R.addEventListener("message",function(C_){var K_=C_.data,M_=K_.id;if(M_!==null&&q.has(M_)){var q_=q.get(M_),P_=q_.reject,O0=q_.resolve;if(q.delete(M_),K_.error===void 0)O0(K_.result);else P_(Error(K_.error.message))}}),X(R))R.start();var f=function(K_){var M_=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,q_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(P_,O0){var S1=E.generateUniqueNumber(q);if(q.set(S1,{reject:O0,resolve:P_}),M_===null)R.postMessage({id:S1,method:K_},q_);else R.postMessage({id:S1,method:K_,params:M_},q_)})},h=function(K_,M_){var q_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];R.postMessage({id:null,method:K_,params:M_},q_)},b={};for(var l=0,c=Object.entries(F);l<c.length;l++){var W_=A(c[l],2),c_=W_[0],B_=W_[1];b=$($({},b),{},T({},c_,B_({call:f,notify:h})))}return $({},b)}};_.createBroker=N})});var T$=W((aA,_$)=>{(function(_,T){typeof aA==="object"&&typeof _$<"u"?T(aA,J8(),eG(),JL()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.workerTimersBroker={},_._typeof,_.brokerFactory,_.fastUniqueNumbers))})(aA,function(_,T,A,E){var L=new Map([[0,null]]),J=new Map([[0,null]]),X=A.createBroker({clearInterval:function(Y){var K=Y.call;return function(G){if(T(L.get(G))==="symbol")L.set(G,null),K("clear",{timerId:G,timerType:"interval"}).then(function(){L.delete(G)})}},clearTimeout:function(Y){var K=Y.call;return function(G){if(T(J.get(G))==="symbol")J.set(G,null),K("clear",{timerId:G,timerType:"timeout"}).then(function(){J.delete(G)})}},setInterval:function(Y){var K=Y.call;return function(G){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var U=arguments.length,V=Array(U>2?U-2:0),N=2;N<U;N++)V[N-2]=arguments[N];var z=Symbol(),Q=E.generateUniqueNumber(L);L.set(Q,z);var F=function(){return K("set",{delay:$,now:performance.timeOrigin+performance.now(),timerId:Q,timerType:"interval"}).then(function(){var q=L.get(Q);if(q===void 0)throw Error("The timer is in an undefined state.");if(q===z){if(G.apply(void 0,V),L.get(Q)===z)F()}})};return F(),Q}},setTimeout:function(Y){var K=Y.call;return function(G){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var U=arguments.length,V=Array(U>2?U-2:0),N=2;N<U;N++)V[N-2]=arguments[N];var z=Symbol(),Q=E.generateUniqueNumber(J);return J.set(Q,z),K("set",{delay:$,now:performance.timeOrigin+performance.now(),timerId:Q,timerType:"timeout"}).then(function(){var F=J.get(Q);if(F===void 0)throw Error("The timer is in an undefined state.");if(F===z)J.delete(Q),G.apply(void 0,V)}),Q}}}),H=function(Y){var K=new Worker(Y);return X(K)};_.load=H,_.wrap=X})});var E$=W((oA,A$)=>{(function(_,T){typeof oA==="object"&&typeof A$<"u"?T(oA,T$()):typeof define==="function"&&define.amd?define(["exports","worker-timers-broker"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.workerTimers={},_.workerTimersBroker))})(oA,function(_,T){var A=function(K,G){var $=null;return function(){if($!==null)return $;var U=new Blob([G],{type:"application/javascript; charset=utf-8"}),V=URL.createObjectURL(U);return $=K(V),setTimeout(function(){return URL.revokeObjectURL(V)}),$}},E='(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise(function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)})}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise(function(t){e.set(a,[r(n,s,i,e,t,a),t])})}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark(function e(r){var n,o,u;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark(function e(r){var n,o,u,a,i;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){function u(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n:(u("next",0),u("throw",1),u("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a(\'The requested method called "\'.concat(e,\'" is not supported.\'),u.METHOD_NOT_FOUND)},s=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned no required result.\'),u.INTERNAL_ERROR)},c=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned an unexpected result.\'),u.INTERNAL_ERROR)},f=function(e){return a(\'The specified parameter called "portId" with the given value "\'.concat(e,\'" does not identify a port connected to this worker.\'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark(function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}},t,null,[[1,11]])}));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise(function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])})};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach(function(t){n(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,function(){u(),r.close(),x.delete(a)}),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark(function e(){var t,n,o;return r.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}},e)}));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then(function(e){u("next",e,a,i)},function(e){u("throw",e,a,i)}):r.resolve(c).then(function(e){s.value=e,a(s)},function(e){return u("throw",e,a,i)})}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),o(this,"_invoke",function(e,t,n){function o(){return new r(function(t,r){u(e,n,t,r)})}return a=a?a.then(o,o):o()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a \'"+o+"\' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,function(){return this}),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,function(){return this}),n(v,"toString",function(){return"[object Generator]"}),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();',L=A(T.load,E),J=function(K){return L().clearInterval(K)},X=function(K){return L().clearTimeout(K)},H=function(){var K;return(K=L()).setInterval.apply(K,arguments)},Z=function(){var K;return(K=L()).setTimeout.apply(K,arguments)};_.clearInterval=J,_.clearTimeout=X,_.setInterval=H,_.setTimeout=Z})});var O8=W((X$)=>{Object.defineProperty(X$,"__esModule",{value:!0});X$.isReactNativeBrowser=X$.isWebWorker=void 0;var nw=()=>{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},L$=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),J$=()=>typeof navigator<"u"&&navigator.product==="ReactNative",iw=nw()||L$()||J$();X$.isWebWorker=L$();X$.isReactNativeBrowser=J$();X$.default=iw});var G$=W((k0)=>{var rw=k0&&k0.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),sw=k0&&k0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),tw=k0&&k0.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")rw(A,T,E[L])}return sw(A,T),A}}();Object.defineProperty(k0,"__esModule",{value:!0});var Z$=E$(),WL=tw(O8()),Y$={set:Z$.setInterval,clear:Z$.clearInterval},K$={set:(_,T)=>setInterval(_,T),clear:(_)=>clearInterval(_)},ew=(_)=>{switch(_){case"native":return K$;case"worker":return Y$;case"auto":default:return WL.default&&!WL.isWebWorker&&!WL.isReactNativeBrowser?Y$:K$}};k0.default=ew});var NL=W((R8)=>{var _S=R8&&R8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(R8,"__esModule",{value:!0});var TS=_S(G$());class $${_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,TS.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=$$});var sA=W((l1)=>{var AS=l1&&l1.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),ES=l1&&l1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),M$=l1&&l1.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")AS(A,T,E[L])}return ES(A,T),A}}(),t0=l1&&l1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(l1,"__esModule",{value:!0});var QL=t0(wA()),LS=n0(),U$=t0(KK()),JS=t0(u1()),W$=M$(UK()),G4=t0(dE()),XS=t0(YG()),HS=t0(AL()),ZS=t0(WG()),D8=BT(),YS=NG(),KS=t0(NL()),N$=M$(O8()),ML=globalThis.setImmediate||((..._)=>{let T=_.shift();(0,D8.nextTick)(()=>{T(..._)})}),Q$={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1000,connectTimeout:30000,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class rA extends YS.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 Q$)if(typeof this.options[A]>"u")this.options[A]=Q$[A];else this.options[A]=T[A];if(this.log=this.options.log||(0,JS.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",rA.VERSION),N$.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",N$.default?"browser":"node");if(this.log("MqttClient :: options.protocol",T.protocol),this.log("MqttClient :: options.protocolVersion",T.protocolVersion),this.log("MqttClient :: options.username",T.username),this.log("MqttClient :: options.keepalive",T.keepalive),this.log("MqttClient :: options.reconnectPeriod",T.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",T.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",T.properties?T.properties.topicAliasMaximum:void 0),this.options.clientId=typeof T.clientId==="string"?T.clientId:rA.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=T.protocolVersion===5&&T.customHandleAcks?T.customHandleAcks:(...A)=>{A[3](null,0)},!this.options.writeCache)QL.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=_,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new HS.default:this.options.messageIdProvider,this.outgoingStore=T.outgoingStore||new G4.default,this.incomingStore=T.incomingStore||new G4.default,this.queueQoSZero=T.queueQoSZero===void 0?!0:T.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,T.properties&&T.properties.topicAliasMaximum>0)if(T.properties.topicAliasMaximum>65535)this.log("MqttClient :: options.properties.topicAliasMaximum is out of range");else this.topicAliasRecv=new ZS.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 LS.Writable,T=QL.default.parser(this.options),A=null,E=[];if(this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting)this.incomingStore=this.options.incomingStore||new G4.default,this.outgoingStore=this.options.outgoingStore||new G4.default,this.disconnecting=!1,this.disconnected=!1;this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),T.on("packet",(Z)=>{this.log("parser :: on packet push to packets array."),E.push(Z)});let L=()=>{this.log("work :: getting next packet in queue");let Z=E.shift();if(Z)this.log("work :: packet pulled from queue"),(0,XS.default)(this,Z,J);else{this.log("work :: no packets in queue");let Y=A;if(A=null,this.log("work :: done flag is %s",!!Y),Y)Y()}},J=()=>{if(E.length)(0,D8.nextTick)(L);else{let Z=A;A=null,Z()}};_._write=(Z,Y,K)=>{A=K,this.log("writable stream :: parsing buffer"),T.parse(Z),L()};let X=(Z)=>{if(this.log("streamErrorHandler :: error",Z.message),Z.code)this.log("streamErrorHandler :: emitting error"),this.emit("error",Z);else this.noop(Z)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(_),this.stream.on("error",X),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let H={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will)H.will={...this.options.will,payload:this.options.will?.payload};if(this.topicAliasRecv){if(!H.properties)H.properties={};if(this.topicAliasRecv)H.properties.topicAliasMaximum=this.topicAliasRecv.max}if(this._writePacket(H),T.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket==="object"){let Z={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(Z)}}return this.stream.setMaxListeners(1000),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(_,T,A,E){this.log("publish :: message `%s` to topic `%s`",T,_);let{options:L}=this;if(typeof A==="function")E=A,A=null;A=A||{},A={...{qos:0,retain:!1,dup:!1},...A};let{qos:X,retain:H,dup:Z,properties:Y,cbStorePut:K}=A;if(this._checkDisconnecting(E))return this;let G=()=>{let $=0;if(X===1||X===2){if($=this._nextId(),$===null)return this.log("No messageId left"),!1}let U={cmd:"publish",topic:_,payload:T,qos:X,retain:H,messageId:$,dup:Z};if(L.protocolVersion===5)U.properties=Y;switch(this.log("publish :: qos",X),X){case 1:case 2:this.outgoing[U.messageId]={volatile:!1,cb:E||this.noop},this.log("MqttClient:publish: packet cmd: %s",U.cmd),this._sendPacket(U,void 0,K);break;default:this.log("MqttClient:publish: packet cmd: %s",U.cmd),this._sendPacket(U,E,K);break}return!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!G())this._storeProcessingQueue.push({invoke:G,cbStorePut:A.cbStorePut,callback:E});return this}publishAsync(_,T,A){return new Promise((E,L)=>{this.publish(_,T,A,(J,X)=>{if(J)L(J);else E(X)})})}subscribe(_,T,A){let E=this.options.protocolVersion;if(typeof T==="function")A=T;A=A||this.noop;let L=!1,J=[];if(typeof _==="string")_=[_],J=_;else if(Array.isArray(_))J=_;else if(typeof _==="object")L=_.resubscribe,delete _.resubscribe,J=Object.keys(_);let X=W$.validateTopics(J);if(X!==null)return ML(A,Error(`Invalid topic ${X}`)),this;if(this._checkDisconnecting(A))return this.log("subscribe: discconecting true"),this;let H={qos:0};if(E===5)H.nl=!1,H.rap=!1,H.rh=0;T={...H,...T};let{properties:Z}=T,Y=[],K=(U,V)=>{if(V=V||T,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,U)||this._resubscribeTopics[U].qos<V.qos||L){let N={topic:U,qos:V.qos};if(E===5)N.nl=V.nl,N.rap=V.rap,N.rh=V.rh,N.properties=Z;this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",N.topic,N.qos),Y.push(N)}};if(Array.isArray(_))_.forEach((U)=>{this.log("subscribe: array topic %s",U),K(U)});else Object.keys(_).forEach((U)=>{this.log("subscribe: object topic %s, %o",U,_[U]),K(U,_[U])});if(!Y.length)return A(null,[]),this;let G=(U,V)=>{let N={cmd:"subscribe",subscriptions:U,messageId:V};if(Z)N.properties=Z;if(this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];U.forEach((F)=>{if(this.options.reconnectPeriod>0){let R={qos:F.qos};if(E===5)R.nl=F.nl||!1,R.rap=F.rap||!1,R.rh=F.rh||0,R.properties=F.properties;this._resubscribeTopics[F.topic]=R,Q.push(F.topic)}}),this.messageIdToTopic[N.messageId]=Q}let z=new Promise((Q,F)=>{this.outgoing[N.messageId]={volatile:!0,cb(R,q){if(!R){let{granted:f}=q;for(let h=0;h<f.length;h+=1)U[h].qos=f[h]}if(!R)Q(q);else F(new D8.ErrorWithSubackPacket(R.message,q))}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(N),z},$=()=>{let U=this.options.subscribeBatchSize??Y.length,V=[];for(let N=0;N<Y.length;N+=U){let z=Y.slice(N,N+U),Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;V.push(G(z,Q))}return Promise.all(V).then((N)=>{A(null,Y,N.at(-1))}).catch((N)=>{A(N,Y,N.packet)}),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!$())this._storeProcessingQueue.push({invoke:$,callback:A});return this}subscribeAsync(_,T){return new Promise((A,E)=>{this.subscribe(_,T,(L,J)=>{if(L)E(L);else A(J)})})}unsubscribe(_,T,A){if(typeof _==="string")_=[_];if(typeof T==="function")A=T;A=A||this.noop;let E=W$.validateTopics(_);if(E!==null)return ML(A,Error(`Invalid topic ${E}`)),this;if(this._checkDisconnecting(A))return this;let L=()=>{let J=this._nextId();if(J===null)return this.log("No messageId left"),!1;let X={cmd:"unsubscribe",messageId:J,unsubscriptions:[]};if(typeof _==="string")X.unsubscriptions=[_];else if(Array.isArray(_))X.unsubscriptions=_;if(this.options.resubscribe)X.unsubscriptions.forEach((H)=>{delete this._resubscribeTopics[H]});if(typeof T==="object"&&T.properties)X.properties=T.properties;return this.outgoing[X.messageId]={volatile:!0,cb:A},this.log("unsubscribe: call _sendPacket"),this._sendPacket(X),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!L())this._storeProcessingQueue.push({invoke:L,callback:A});return this}unsubscribeAsync(_,T){return new Promise((A,E)=>{this.unsubscribe(_,T,(L,J)=>{if(L)E(L);else A(J)})})}end(_,T,A){if(this.log("end :: (%s)",this.options.clientId),_==null||typeof _!=="boolean")A=A||T,T=_,_=!1;if(typeof T!=="object")A=A||T,T=null;if(this.log("end :: cb? %s",!!A),!A||typeof A!=="function")A=this.noop;let E=()=>{if(this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close((J)=>{this.outgoingStore.close((X)=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),A){let H=J||X;this.log("end :: closeStores: invoking callback with args"),A(H)}})}),this._deferredReconnect)this._deferredReconnect();else if(this.options.reconnectPeriod===0||this.options.manualConnect)this.disconnecting=!1},L=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,_),this._cleanUp(_,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,D8.nextTick)(E)},T)};if(this.disconnecting)return A(),this;if(this._clearReconnect(),this.disconnecting=!0,!_&&Object.keys(this.outgoing).length>0)this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,L,10));else this.log("end :: (%s) :: immediately calling finish",this.options.clientId),L();return this}endAsync(_,T){return new Promise((A,E)=>{this.end(_,T,(L)=>{if(L)E(L);else A()})})}removeOutgoingMessage(_){if(this.outgoing[_]){let{cb:T}=this.outgoing[_];this._removeOutgoingAndStoreMessage(_,()=>{T(Error("Message removed"))})}return this}reconnect(_){this.log("client reconnect");let T=()=>{if(_)this.options.incomingStore=_.incomingStore,this.options.outgoingStore=_.outgoingStore;else this.options.incomingStore=null,this.options.outgoingStore=null;this.incomingStore=this.options.incomingStore||new G4.default,this.outgoingStore=this.options.outgoingStore||new G4.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};if(this.disconnecting&&!this.disconnected)this._deferredReconnect=T;else T();return this}_flushVolatile(){if(this.outgoing)this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach((_)=>{if(this.outgoing[_].volatile&&typeof this.outgoing[_].cb==="function")this.outgoing[_].cb(Error("Connection closed")),delete this.outgoing[_]})}_flush(){if(this.outgoing)this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach((_)=>{if(typeof this.outgoing[_].cb==="function")this.outgoing[_].cb(Error("Connection closed")),delete this.outgoing[_]})}_removeTopicAliasAndRecoverTopicName(_){let T;if(_.properties)T=_.properties.topicAlias;let A=_.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",T,A),A.length===0){if(typeof T>"u")return Error("Unregistered Topic Alias");if(A=this.topicAliasSend.getTopicByAlias(T),typeof A>"u")return Error("Unregistered Topic Alias");_.topic=A}if(T)delete _.properties.topicAlias}_checkDisconnecting(_){if(this.disconnecting)if(_&&_!==this.noop)_(Error("client disconnecting"));else this.emit("error",Error("client disconnecting"));return this.disconnecting}_reconnect(){if(this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected)this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.");else this.log("_reconnect: calling connect"),this.connect()}_setupReconnect(){if(!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0){if(!this.reconnecting)this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0;this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)}else this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){if(this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer)clearInterval(this.reconnectTimer),this.reconnectTimer=null}_cleanUp(_,T,A={}){if(T)this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",T);if(this.log("_cleanUp :: forced? %s",_),_){if(this.options.reconnectPeriod===0&&this.options.clean)this._flush();this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy()}else{let E={cmd:"disconnect",...A};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(E,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),ML(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}if(!this.disconnecting&&!this.reconnecting)this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect();if(this._destroyKeepaliveManager(),T&&!this.connected)this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",T),T()}_storeAndSend(_,T,A){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",_.cmd);let E=_,L;if(E.cmd==="publish"){if(E=(0,U$.default)(_),L=this._removeTopicAliasAndRecoverTopicName(E),L)return T&&T(L)}this.outgoingStore.put(E,(J)=>{if(J)return T&&T(J);A(),this._writePacket(_,T)})}_applyTopicAlias(_){if(this.options.protocolVersion===5){if(_.cmd==="publish"){let T;if(_.properties)T=_.properties.topicAlias;let A=_.topic.toString();if(this.topicAliasSend){if(T){if(A.length!==0){if(this.log("applyTopicAlias :: register topic: %s - alias: %d",A,T),!this.topicAliasSend.put(A,T))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,T),Error("Sending Topic Alias out of range")}}else if(A.length!==0){if(this.options.autoAssignTopicAlias)if(T=this.topicAliasSend.getAliasByTopic(A),T)_.topic="",_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",A,T);else T=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(A,T),_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",A,T);else if(this.options.autoUseTopicAlias){if(T=this.topicAliasSend.getAliasByTopic(A),T)_.topic="",_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",A,T)}}}else if(T)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,T),Error("Sending Topic Alias out of range")}}}_noop(_){this.log("noop ::",_)}_writePacket(_,T){this.log("_writePacket :: packet: %O",_),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",_),this.log("_writePacket :: writing to stream");let A=QL.default.writeToStream(_,this.stream,this.options);if(this.log("_writePacket :: writeToStream result %s",A),!A&&T&&T!==this.noop)this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",T);else if(T)this.log("_writePacket :: invoking cb"),T()}_sendPacket(_,T,A,E){this.log("_sendPacket :: (%s) :: start",this.options.clientId),A=A||this.noop,T=T||this.noop;let L=this._applyTopicAlias(_);if(L){T(L);return}if(!this.connected){if(_.cmd==="auth"){this._writePacket(_,T);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(_,T,A);return}if(E){this._writePacket(_,T);return}switch(_.cmd){case"publish":break;case"pubrel":this._storeAndSend(_,T,A);return;default:this._writePacket(_,T);return}switch(_.qos){case 2:case 1:this._storeAndSend(_,T,A);break;case 0:default:this._writePacket(_,T);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(_,T,A){this.log("_storePacket :: packet: %o",_),this.log("_storePacket :: cb? %s",!!T),A=A||this.noop;let E=_;if(E.cmd==="publish"){E=(0,U$.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 KS.default(this,this.options.timerVariant)}_destroyKeepaliveManager(){if(this.keepaliveManager)this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null}reschedulePing(_=!1){if(this.keepaliveManager&&this.options.keepalive&&(_||this.options.reschedulePings))this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let _=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&_.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let T=0;T<_.length;T++){let A={};A[_[T]]=this._resubscribeTopics[_[T]],A.resubscribe=!0,this.subscribe(A,{properties:A[_[T]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(_){if(this.disconnected){this.emit("connect",_);return}this.connackPacket=_,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let T=()=>{let A=this.outgoingStore.createStream(),E=()=>{A.destroy(),A=null,this._flushStoreProcessingQueue(),L()},L=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",E),A.on("error",(X)=>{L(),this._flushStoreProcessingQueue(),this.removeListener("close",E),this.emit("error",X)});let J=()=>{if(!A)return;let X=A.read(1),H;if(!X){A.once("readable",J);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[X.messageId]){J();return}if(!this.disconnecting&&!this.reconnectTimer)if(H=this.outgoing[X.messageId]?this.outgoing[X.messageId].cb:null,this.outgoing[X.messageId]={volatile:!1,cb(Z,Y){if(H)H(Z,Y);J()}},this._packetIdsDuringStoreProcessing[X.messageId]=!0,this.messageIdProvider.register(X.messageId))this._sendPacket(X,void 0,void 0,!0);else this.log("messageId: %d has already used.",X.messageId);else if(A.destroy)A.destroy()};A.on("end",()=>{let X=!0;for(let H in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[H]){X=!1;break}if(this.removeListener("close",E),X)L(),this._invokeAllStoreProcessingQueue(),this.emit("connect",_);else T()}),J()};T()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let _=this._storeProcessingQueue[0];if(_&&_.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){while(this._invokeStoreProcessingQueue());}_flushStoreProcessingQueue(){for(let _ of this._storeProcessingQueue){if(_.cbStorePut)_.cbStorePut(Error("Connection closed"));if(_.callback)_.callback(Error("Connection closed"))}this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(_,T){delete this.outgoing[_],this.outgoingStore.del({messageId:_},(A,E)=>{T(A,E),this.messageIdProvider.deallocate(_),this._invokeStoreProcessingQueue()})}}l1.default=rA});var F$=W((z$)=>{Object.defineProperty(z$,"__esModule",{value:!0});var GS=TL();class V${numberAllocator;lastId;constructor(){this.numberAllocator=new GS.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()}}z$.default=V$});var tA=W((D$)=>{Object.defineProperty(D$,"__esModule",{value:!0});D$.BufferedDuplex=void 0;D$.writev=O$;var US=n0(),C$=j("buffer");function O$(_,T){let A=Array(_.length);for(let E=0;E<_.length;E++)if(typeof _[E].chunk==="string")A[E]=C$.Buffer.from(_[E].chunk,"utf8");else A[E]=_[E].chunk;this._write(C$.Buffer.concat(A),"binary",T)}class R$ extends US.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(_,T,A){super({objectMode:!0});if(this.proxy=T,this.socket=A,this.writeQueue=[],!_.objectMode)this._writev=O$.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)}}}D$.BufferedDuplex=R$});var B8=W((_T)=>{var zL=_T&&_T.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(_T,"__esModule",{value:!0});_T.streamBuilder=_T.browserStreamBuilder=void 0;var eA=j("buffer"),q$=zL(j("ws")),NS=zL(u1()),QS=n0(),MS=zL(O8()),VL=tA(),e0=(0,NS.default)("mqttjs:ws"),VS=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function I$(_,T){let A=`${_.protocol}://${_.hostname}:${_.port}${_.path}`;if(typeof _.transformWsUrl==="function")A=_.transformWsUrl(A,_,T);return A}function P$(_){let T=_;if(!_.port)if(_.protocol==="wss")T.port=443;else T.port=80;if(!_.path)T.path="/";if(!_.wsOptions)T.wsOptions={};if(!MS.default&&!_.forceNativeWebSocket&&_.protocol==="wss")VS.forEach((A)=>{if(Object.prototype.hasOwnProperty.call(_,A)&&!Object.prototype.hasOwnProperty.call(_.wsOptions,A))T.wsOptions[A]=_[A]});return T}function zS(_){let T=P$(_);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 FS(_,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 q$.default(T,[E],A.wsOptions);return L}function CS(_,T){let A=T.protocolId==="MQIsdp"&&T.protocolVersion===3?"mqttv3.1":"mqtt",E=I$(T,_),L;if(T.createWebsocket)L=T.createWebsocket(E,[A],T);else L=new WebSocket(E,[A]);return L.binaryType="arraybuffer",L}var OS=(_,T)=>{e0("streamBuilder");let A=P$(T);A.hostname=A.hostname||A.host||"localhost";let E=I$(A,_),L=FS(_,E,A),J=q$.default.createWebSocketStream(L,A.wsOptions);return J.url=E,L.on("close",()=>{J.destroy()}),J};_T.streamBuilder=OS;var RS=(_,T)=>{e0("browserStreamBuilder");let A,L=zS(T).browserBufferSize||524288,J=T.browserBufferTimeout||1000,X=!T.objectMode,H=CS(_,T),Z=K(T,N,z);if(!T.objectMode)Z._writev=VL.writev.bind(Z);Z.on("close",()=>{H.close()});let Y=typeof H.addEventListener<"u";if(H.readyState===H.OPEN)A=Z,A.socket=H;else if(A=new VL.BufferedDuplex(T,Z,H),Y)H.addEventListener("open",G);else H.onopen=G;if(Y)H.addEventListener("close",$),H.addEventListener("error",U),H.addEventListener("message",V);else H.onclose=$,H.onerror=U,H.onmessage=V;function K(Q,F,R){let q=new QS.Transform({objectMode:Q.objectMode});return q._write=F,q._flush=R,q}function G(){if(e0("WebSocket onOpen"),A instanceof VL.BufferedDuplex)A.socketReady()}function $(Q){e0("WebSocket onClose",Q),A.end(),A.destroy()}function U(Q){e0("WebSocket onError",Q);let F=Error("WebSocket error");F.event=Q,A.destroy(F)}async function V(Q){if(!Z||!Z.readable||!Z.writable)return;let{data:F}=Q;if(F instanceof ArrayBuffer)F=eA.Buffer.from(F);else if(F instanceof Blob)F=eA.Buffer.from(await new Response(F).arrayBuffer());else F=eA.Buffer.from(F,"utf8");Z.push(F)}function N(Q,F,R){if(H.bufferedAmount>L){setTimeout(N,J,Q,F,R);return}if(X&&typeof Q==="string")Q=eA.Buffer.from(Q,"utf8");try{H.send(Q)}catch(q){return R(q)}R()}function z(Q){H.close(),Q()}return A};_T.browserStreamBuilder=RS});var y$=W((S$)=>{Object.defineProperty(S$,"__esModule",{value:!0});var j$=j("buffer"),ST={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};S$.ERRORS=ST;function DS(_){if(!j$.Buffer.isEncoding(_))throw Error(ST.INVALID_ENCODING)}S$.checkEncoding=DS;function x$(_){return typeof _==="number"&&isFinite(_)&&PS(_)}S$.isFiniteInteger=x$;function w$(_,T){if(typeof _==="number"){if(!x$(_)||_<0)throw Error(T?ST.INVALID_OFFSET:ST.INVALID_LENGTH)}else throw Error(T?ST.INVALID_OFFSET_NON_NUMBER:ST.INVALID_LENGTH_NON_NUMBER)}function BS(_){w$(_,!1)}S$.checkLengthValue=BS;function qS(_){w$(_,!0)}S$.checkOffsetValue=qS;function IS(_,T){if(_<0||_>T.length)throw Error(ST.INVALID_TARGET_OFFSET)}S$.checkTargetOffset=IS;function PS(_){return typeof _==="number"&&isFinite(_)&&Math.floor(_)===_}function jS(_){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof j$.Buffer.prototype[_]>"u")throw Error(`Platform does not support Buffer.prototype.${_}.`)}S$.bigIntAndBufferInt64Check=jS});var k$=W((h$)=>{Object.defineProperty(h$,"__esModule",{value:!0});var t=y$(),v$=4096,fS="utf8";class FL{constructor(_){if(this.length=0,this._encoding=fS,this._writeOffset=0,this._readOffset=0,FL.isSmartBufferOptions(_)){if(_.encoding)t.checkEncoding(_.encoding),this._encoding=_.encoding;if(_.size)if(t.isFiniteInteger(_.size)&&_.size>0)this._buff=Buffer.allocUnsafe(_.size);else throw Error(t.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(_.buff)if(Buffer.isBuffer(_.buff))this._buff=_.buff,this.length=_.buff.length;else throw Error(t.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(v$)}else{if(typeof _<"u")throw Error(t.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(v$)}}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}}h$.SmartBuffer=FL});var CL=W((c$)=>{Object.defineProperty(c$,"__esModule",{value:!0});c$.SOCKS5_NO_ACCEPTABLE_AUTH=c$.SOCKS5_CUSTOM_AUTH_END=c$.SOCKS5_CUSTOM_AUTH_START=c$.SOCKS_INCOMING_PACKET_SIZES=c$.SocksClientState=c$.Socks5Response=c$.Socks5HostType=c$.Socks5Auth=c$.Socks4Response=c$.SocksCommand=c$.ERRORS=c$.DEFAULT_TIMEOUT=void 0;var gS=30000;c$.DEFAULT_TIMEOUT=gS;var mS={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"};c$.ERRORS=mS;var uS={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(_)=>_+7,Socks4Response:8};c$.SOCKS_INCOMING_PACKET_SIZES=uS;var f$;(function(_){_[_.connect=1]="connect",_[_.bind=2]="bind",_[_.associate=3]="associate"})(f$||(c$.SocksCommand=f$={}));var b$;(function(_){_[_.Granted=90]="Granted",_[_.Failed=91]="Failed",_[_.Rejected=92]="Rejected",_[_.RejectedIdent=93]="RejectedIdent"})(b$||(c$.Socks4Response=b$={}));var g$;(function(_){_[_.NoAuth=0]="NoAuth",_[_.GSSApi=1]="GSSApi",_[_.UserPass=2]="UserPass"})(g$||(c$.Socks5Auth=g$={}));var dS=128;c$.SOCKS5_CUSTOM_AUTH_START=dS;var cS=254;c$.SOCKS5_CUSTOM_AUTH_END=cS;var pS=255;c$.SOCKS5_NO_ACCEPTABLE_AUTH=pS;var m$;(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"})(m$||(c$.Socks5Response=m$={}));var u$;(function(_){_[_.IPv4=1]="IPv4",_[_.Hostname=3]="Hostname",_[_.IPv6=4]="IPv6"})(u$||(c$.Socks5HostType=u$={}));var d$;(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"})(d$||(c$.SocksClientState=d$={}))});var OL=W((n$)=>{Object.defineProperty(n$,"__esModule",{value:!0});n$.shuffleArray=n$.SocksClientError=void 0;class l$ extends Error{constructor(_,T){super(_);this.options=T}}n$.SocksClientError=l$;function Ay(_){for(let T=_.length-1;T>0;T--){let A=Math.floor(Math.random()*(T+1));[_[T],_[A]]=[_[A],_[T]]}}n$.shuffleArray=Ay});var _5=W((o$)=>{Object.defineProperty(o$,"__esModule",{value:!0});o$.isInSubnet=Ly;o$.isCorrect=Jy;o$.numberToPaddedHex=a$;o$.stringToPaddedHex=Xy;o$.testBit=Hy;function Ly(_){if(this.subnetMask<_.subnetMask)return!1;if(this.mask(_.subnetMask)===_.mask())return!0;return!1}function Jy(_){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===_&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function a$(_){return _.toString(16).padStart(2,"0")}function Xy(_){return a$(parseInt(_,10))}function Hy(_,T){let{length:A}=_;if(T>A)return!1;let E=A-T;return _.substring(E,E+1)==="1"}});var RL=W((r$)=>{Object.defineProperty(r$,"__esModule",{value:!0});r$.RE_SUBNET_STRING=r$.RE_ADDRESS=r$.GROUPS=r$.BITS=void 0;r$.BITS=32;r$.GROUPS=4;r$.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;r$.RE_SUBNET_STRING=/\/\d{1,2}$/});var T5=W((e$)=>{Object.defineProperty(e$,"__esModule",{value:!0});e$.AddressError=void 0;class t$ extends Error{constructor(_,T){super(_);this.name="AddressError",this.parseMessage=T}}e$.AddressError=t$});var DL=W((N0)=>{var Qy=N0&&N0.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),My=N0&&N0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),TU=N0&&N0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))Qy(T,_,A)}return My(T,_),T};Object.defineProperty(N0,"__esModule",{value:!0});N0.Address4=void 0;var $4=TU(_5()),n1=TU(RL()),q8=T5();class $1{constructor(_){this.groups=n1.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=$4.isCorrect(n1.BITS),this.isInSubnet=$4.isInSubnet,this.address=_;let T=n1.RE_SUBNET_STRING.exec(_);if(T){if(this.parsedSubnet=T[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>n1.BITS)throw new q8.AddressError("Invalid subnet mask.");_=_.replace(n1.RE_SUBNET_STRING,"")}this.addressMinusSuffix=_,this.parsedAddress=this.parse(_)}static isValid(_){try{return new $1(_),!0}catch(T){return!1}}parse(_){let T=_.split(".");if(!_.match(n1.RE_ADDRESS))throw new q8.AddressError("Invalid IPv4 address.");return T}correctForm(){return this.parsedAddress.map((_)=>parseInt(_,10)).join(".")}static fromHex(_){let T=_.replace(/:/g,"").padStart(8,"0"),A=[],E;for(E=0;E<8;E+=2){let L=T.slice(E,E+2);A.push(parseInt(L,16))}return new $1(A.join("."))}static fromInteger(_){return $1.fromHex(_.toString(16))}static fromArpa(_){let A=_.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new $1(A)}toHex(){return this.parsedAddress.map((_)=>$4.stringToPaddedHex(_)).join(":")}toArray(){return this.parsedAddress.map((_)=>parseInt(_,10))}toGroup6(){let _=[],T;for(T=0;T<n1.GROUPS;T+=2)_.push(`${$4.stringToPaddedHex(this.parsedAddress[T])}${$4.stringToPaddedHex(this.parsedAddress[T+1])}`);return _.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map((_)=>$4.stringToPaddedHex(_)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(n1.BITS-this.subnetMask)}`)}startAddress(){return $1.fromBigInt(this._startAddress())}startAddressExclusive(){let _=BigInt("1");return $1.fromBigInt(this._startAddress()+_)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(n1.BITS-this.subnetMask)}`)}endAddress(){return $1.fromBigInt(this._endAddress())}endAddressExclusive(){let _=BigInt("1");return $1.fromBigInt(this._endAddress()-_)}static fromBigInt(_){return $1.fromHex(_.toString(16))}static fromByteArray(_){if(_.length!==4)throw new q8.AddressError("IPv4 addresses require exactly 4 bytes");for(let T=0;T<_.length;T++)if(!Number.isInteger(_[T])||_[T]<0||_[T]>255)throw new q8.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(_)}static fromUnsignedByteArray(_){if(_.length!==4)throw new q8.AddressError("IPv4 addresses require exactly 4 bytes");let T=_.join(".");return new $1(T)}mask(_){if(_===void 0)_=this.subnetMask;return this.getBitsBase2(0,_)}getBitsBase2(_,T){return this.binaryZeroPad().slice(_,T)}reverseForm(_){if(!_)_={};let T=this.correctForm().split(".").reverse().join(".");if(_.omitSuffix)return T;return`${T}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new $1("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(n1.BITS,"0")}groupForV6(){let _=this.parsedAddress;return this.address.replace(n1.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${_.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${_.slice(2,4).join(".")}</span>`)}}N0.Address4=$1});var BL=W((AU)=>{Object.defineProperty(AU,"__esModule",{value:!0});AU.RE_URL_WITH_PORT=AU.RE_URL=AU.RE_ZONE_STRING=AU.RE_SUBNET_STRING=AU.RE_BAD_ADDRESS=AU.RE_BAD_CHARACTERS=AU.TYPES=AU.SCOPES=AU.GROUPS=AU.BITS=void 0;AU.BITS=128;AU.GROUPS=8;AU.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};AU.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"};AU.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;AU.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;AU.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;AU.RE_ZONE_STRING=/%.*$/;AU.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;AU.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var qL=W((XU)=>{Object.defineProperty(XU,"__esModule",{value:!0});XU.spanAllZeroes=LU;XU.spanAll=Iy;XU.spanLeadingZeroes=Py;XU.simpleGroup=jy;function LU(_){return _.replace(/(0+)/g,'<span class="zero">$1</span>')}function Iy(_,T=0){return _.split("").map((E,L)=>`<span class="digit value-${E} position-${L+T}">${LU(E)}</span>`).join("")}function JU(_){return _.replace(/^(0+)/,'<span class="zero">$1</span>')}function Py(_){return _.split(":").map((A)=>JU(A)).join(":")}function jy(_,T=0){return _.split(":").map((E,L)=>{if(/group-v4/.test(E))return E;return`<span class="hover-group group-${L+T}">${JU(E)}</span>`})}});var HU=W((Y1)=>{var vy=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]}),hy=Y1&&Y1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),ky=Y1&&Y1.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))vy(T,_,A)}return hy(T,_),T};Object.defineProperty(Y1,"__esModule",{value:!0});Y1.ADDRESS_BOUNDARY=void 0;Y1.groupPossibilities=E5;Y1.padGroup=A5;Y1.simpleRegularExpression=by;Y1.possibleElisions=gy;var fy=ky(BL());function E5(_){return`(${_.join("|")})`}function A5(_){if(_.length<4)return`0{0,${4-_.length}}${_}`;return _}Y1.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function by(_){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===fy.GROUPS-1?":":"";return E5([A5(L),X])}return A5(L)}).join(":"));return A.push(_.map(A5).join(":")),E5(A)}function gy(_,T,A){let E=T?"":":",L=A?"":":",J=[];if(!T&&!A)J.push("::");if(T&&A)J.push("");if(A&&!T||!A&&T)J.push(":");J.push(`${E}(:0{1,4}){1,${_-1}}`),J.push(`(0{1,4}:){1,${_-1}}${L}`),J.push(`(0{1,4}:){${_-1}}0{1,4}`);for(let X=1;X<_-1;X++)for(let H=1;H<_-X;H++)J.push(`(0{1,4}:){${H}}:(0{1,4}:){${_-H-X-1}}0{1,4}`);return E5(J)}});var GU=W((Q0)=>{var my=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]}),uy=Q0&&Q0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),X5=Q0&&Q0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))my(T,_,A)}return uy(T,_),T};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.Address6=void 0;var ZU=X5(_5()),IL=X5(RL()),N_=X5(BL()),PL=X5(qL()),yT=DL(),vT=HU(),f0=T5(),L5=_5();function J5(_){if(!_)throw Error("Assertion failed.")}function dy(_){let T=/(\d+)(\d{3})/;while(T.test(_))_=_.replace(T,"$1,$2");return _}function cy(_){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 py(_,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 YU(_){return parseInt(_,16).toString(16).padStart(4,"0")}function KU(_){return _&255}class k_{constructor(_,T){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=ZU.isInSubnet,this.isCorrect=ZU.isCorrect(N_.BITS),T===void 0)this.groups=N_.GROUPS;else this.groups=T;this.address=_;let A=N_.RE_SUBNET_STRING.exec(_);if(A){if(this.parsedSubnet=A[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>N_.BITS)throw new f0.AddressError("Invalid subnet mask.");_=_.replace(N_.RE_SUBNET_STRING,"")}else if(/\//.test(_))throw new f0.AddressError("Invalid subnet mask.");let E=N_.RE_ZONE_STRING.exec(_);if(E)this.zone=E[0],_=_.replace(N_.RE_ZONE_STRING,"");this.addressMinusSuffix=_,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(_){try{return new k_(_),!0}catch(T){return!1}}static fromBigInt(_){let T=_.toString(16).padStart(32,"0"),A=[],E;for(E=0;E<N_.GROUPS;E++)A.push(T.slice(E*4,(E+1)*4));return new k_(A.join(":"))}static fromURL(_){let T,A=null,E;if(_.indexOf("[")!==-1&&_.indexOf("]:")!==-1){if(E=N_.RE_URL_WITH_PORT.exec(_),E===null)return{error:"failed to parse address with port",address:null,port:null};T=E[1],A=E[2]}else if(_.indexOf("/")!==-1){if(_=_.replace(/^[a-z0-9]+:\/\//,""),E=N_.RE_URL.exec(_),E===null)return{error:"failed to parse address from URL",address:null,port:null};T=E[1]}else T=_;if(A){if(A=parseInt(A,10),A<0||A>65536)A=null}else A=null;return{address:new k_(T),port:A}}static fromAddress4(_){let T=new yT.Address4(_),A=N_.BITS-(IL.BITS-T.subnetMask);return new k_(`::ffff:${T.correctForm()}/${A}`)}static fromArpa(_){let T=_.replace(/(\.ip6\.arpa)?\.$/,""),A=7;if(T.length!==63)throw new f0.AddressError("Invalid 'ip6.arpa' form.");let E=T.split(".").reverse();for(let L=A;L>0;L--){let J=L*4;E.splice(J,0,":")}return T=E.join(""),new k_(T)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(_=this.subnetMask){return this.getBitsBase2(0,_)}possibleSubnets(_=128){let T=N_.BITS-this.subnetMask,A=Math.abs(_-N_.BITS),E=T-A;if(E<0)return"0";return dy((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=py(this.parsedAddress,E[X])}else T=this.parsedAddress;for(_=0;_<T.length;_++)if(T[_]!=="compact")T[_]=parseInt(T[_],16).toString(16);let J=T.join(":");return J=J.replace(/^compact$/,"::"),J=J.replace(/(^compact)|(compact$)/,":"),J=J.replace(/compact/,""),J}binaryZeroPad(){return this.bigInt().toString(2).padStart(N_.BITS,"0")}parse4in6(_){let T=_.split(":"),E=T.slice(-1)[0].match(IL.RE_ADDRESS);if(E){this.parsedAddress4=E[0],this.address4=new yT.Address4(this.parsedAddress4);for(let L=0;L<this.address4.groups;L++)if(/^0[0-9]+/.test(this.address4.parsedAddress[L]))throw new f0.AddressError("IPv4 addresses can't have leading zeroes.",_.replace(IL.RE_ADDRESS,this.address4.parsedAddress.map(cy).join(".")));this.v4=!0,T[T.length-1]=this.address4.toGroup6(),_=T.join(":")}return _}parse(_){_=this.parse4in6(_);let T=_.match(N_.RE_BAD_CHARACTERS);if(T)throw new f0.AddressError(`Bad character${T.length>1?"s":""} detected in address: ${T.join("")}`,_.replace(N_.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let A=_.match(N_.RE_BAD_ADDRESS);if(A)throw new f0.AddressError(`Address failed regex: ${A.join("")}`,_.replace(N_.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let E=[],L=_.split("::");if(L.length===2){let J=L[0].split(":"),X=L[1].split(":");if(J.length===1&&J[0]==="")J=[];if(X.length===1&&X[0]==="")X=[];let H=this.groups-(J.length+X.length);if(!H)throw new f0.AddressError("Error parsing groups");this.elidedGroups=H,this.elisionBegin=J.length,this.elisionEnd=J.length+this.elidedGroups,E=E.concat(J);for(let Z=0;Z<H;Z++)E.push("0");E=E.concat(X)}else if(L.length===1)E=_.split(":"),this.elidedGroups=0;else throw new f0.AddressError("Too many :: groups found");if(E=E.map((J)=>parseInt(J,16).toString(16)),E.length!==this.groups)throw new f0.AddressError("Incorrect number of groups found");return E}canonicalForm(){return this.parsedAddress.map(YU).join(":")}decimal(){return this.parsedAddress.map((_)=>parseInt(_,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(YU).join("")}`)}to4(){let _=this.binaryZeroPad().split("");return yT.Address4.fromHex(BigInt(`0b${_.slice(96,128).join("")}`).toString(16))}to4in6(){let _=this.to4(),A=new k_(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),E="";if(!/:$/.test(A))E=":";return A+E+_.address}inspectTeredo(){let _=this.getBitsBase16(0,32),A=(this.getBits(80,96)^BigInt("0xffff")).toString(),E=yT.Address4.fromHex(this.getBitsBase16(32,64)),L=this.getBits(96,128),J=yT.Address4.fromHex((L^BigInt("0xffffffff")).toString(16)),X=this.getBitsBase2(64,80),H=(0,L5.testBit)(X,15),Z=(0,L5.testBit)(X,14),Y=(0,L5.testBit)(X,8),K=(0,L5.testBit)(X,9),G=BigInt(`0b${X.slice(2,6)+X.slice(8,16)}`).toString(10);return{prefix:`${_.slice(0,4)}:${_.slice(4,8)}`,server4:E.address,client4:J.address,flags:X,coneNat:H,microsoft:{reserved:Z,universalLocal:K,groupIndividual:Y,nonce:G},udpPort:A}}inspect6to4(){let _=this.getBitsBase16(0,16),T=yT.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:_.slice(0,4),gateway:T.address}}to6to4(){if(!this.is4())return null;let _=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new k_(_)}toByteArray(){let _=this.bigInt().toString(16),A=`${"0".repeat(_.length%2)}${_}`,E=[];for(let L=0,J=A.length;L<J;L+=2)E.push(parseInt(A.substring(L,L+2),16));return E}toUnsignedByteArray(){return this.toByteArray().map(KU)}static fromByteArray(_){return this.fromUnsignedByteArray(_.map(KU))}static fromUnsignedByteArray(_){let T=BigInt("256"),A=BigInt("0"),E=BigInt("1");for(let L=_.length-1;L>=0;L--)A+=E*BigInt(_[L].toString(10)),E*=T;return k_.fromBigInt(A)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){if(this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000")return!0;return!1}isMulticast(){return this.getType()==="Multicast"}is4(){return this.v4}isTeredo(){return this.isInSubnet(new k_("2001::/32"))}is6to4(){return this.isInSubnet(new k_("2002::/16"))}isLoopback(){return this.getType()==="Loopback"}href(_){if(_===void 0)_="";else _=`:${_}`;return`http://[${this.correctForm()}]${_}/`}link(_){if(!_)_={};if(_.className===void 0)_.className="";if(_.prefix===void 0)_.prefix="/#address=";if(_.v4===void 0)_.v4=!1;let T=this.correctForm;if(_.v4)T=this.to4in6;let A=T.call(this);if(_.className)return`<a href="${_.prefix}${A}" class="${_.className}">${A}</a>`;return`<a href="${_.prefix}${A}">${A}</a>`}group(){if(this.elidedGroups===0)return PL.simpleGroup(this.address).join(":");J5(typeof this.elidedGroups==="number"),J5(typeof this.elisionBegin==="number");let _=[],[T,A]=this.address.split("::");if(T.length)_.push(...PL.simpleGroup(T));else _.push("");let E=["hover-group"];for(let L=this.elisionBegin;L<this.elisionBegin+this.elidedGroups;L++)E.push(`group-${L}`);if(_.push(`<span class="${E.join(" ")}"></span>`),A.length)_.push(...PL.simpleGroup(A,this.elisionEnd));else _.push("");if(this.is4())J5(this.address4 instanceof yT.Address4),_.pop(),_.push(this.address4.groupForV6());return _.join(":")}regularExpressionString(_=!1){let T=[],A=new k_(this.correctForm());if(A.elidedGroups===0)T.push((0,vT.simpleRegularExpression)(A.parsedAddress));else if(A.elidedGroups===N_.GROUPS)T.push((0,vT.possibleElisions)(N_.GROUPS));else{let E=A.address.split("::");if(E[0].length)T.push((0,vT.simpleRegularExpression)(E[0].split(":")));if(J5(typeof A.elidedGroups==="number"),T.push((0,vT.possibleElisions)(A.elidedGroups,E[0].length!==0,E[1].length!==0)),E[1].length)T.push((0,vT.simpleRegularExpression)(E[1].split(":")));T=[T.join(":")]}if(!_)T=["(?=^|",vT.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...T,")(?=[^\\w\\:]|",vT.ADDRESS_BOUNDARY,"|$)"];return T.join("")}regularExpression(_=!1){return new RegExp(this.regularExpressionString(_),"i")}}Q0.Address6=k_});var jL=W((a_)=>{var ly=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]}),ny=a_&&a_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),iy=a_&&a_.__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(a_,"__esModule",{value:!0});a_.v6=a_.AddressError=a_.Address6=a_.Address4=void 0;var ay=DL();Object.defineProperty(a_,"Address4",{enumerable:!0,get:function(){return ay.Address4}});var oy=GU();Object.defineProperty(a_,"Address6",{enumerable:!0,get:function(){return oy.Address6}});var ry=T5();Object.defineProperty(a_,"AddressError",{enumerable:!0,get:function(){return ry.AddressError}});var sy=iy(qL());a_.v6={helpers:sy}});var zU=W((MU)=>{Object.defineProperty(MU,"__esModule",{value:!0});MU.ipToBuffer=MU.int32ToIpv4=MU.ipv4ToInt32=MU.validateSocksClientChainOptions=MU.validateSocksClientOptions=void 0;var _1=OL(),f_=CL(),ty=j("stream"),xL=jL(),$U=j("net");function ey(_,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(!WU(_.destination))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsDestination,_);if(!NU(_.proxy))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);if(UU(_.proxy,_),_.timeout&&!QU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_);if(_.existing_socket&&!(_.existing_socket instanceof ty.Duplex))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsExistingSocket,_)}MU.validateSocksClientOptions=ey;function _v(_){if(_.command!=="connect")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommandChain,_);if(!WU(_.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(!NU(T))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);UU(T,_)}),_.timeout&&!QU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_)}MU.validateSocksClientChainOptions=_v;function UU(_,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 WU(_){return _&&typeof _.host==="string"&&Buffer.byteLength(_.host)<256&&typeof _.port==="number"&&_.port>=0&&_.port<=65535}function NU(_){return _&&(typeof _.host==="string"||typeof _.ipaddress==="string")&&typeof _.port==="number"&&_.port>=0&&_.port<=65535&&(_.type===4||_.type===5)}function QU(_){return typeof _==="number"&&_>0}function Tv(_){return new xL.Address4(_).toArray().reduce((A,E)=>(A<<8)+E,0)>>>0}MU.ipv4ToInt32=Tv;function Av(_){let T=_>>>24&255,A=_>>>16&255,E=_>>>8&255,L=_&255;return[T,A,E,L].join(".")}MU.int32ToIpv4=Av;function Ev(_){if($U.isIPv4(_)){let T=new xL.Address4(_);return Buffer.from(T.toArray())}else if($U.isIPv6(_)){let T=new xL.Address6(_);return Buffer.from(T.canonicalForm().split(":").map((A)=>A.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}MU.ipToBuffer=Ev});var RU=W((CU)=>{Object.defineProperty(CU,"__esModule",{value:!0});CU.ReceiveBuffer=void 0;class FU{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}}CU.ReceiveBuffer=FU});var DU=W((TT)=>{var U4=TT&&TT.__awaiter||function(_,T,A,E){function L(J){return J instanceof A?J:new A(function(X){X(J)})}return new(A||(A=Promise))(function(J,X){function H(K){try{Y(E.next(K))}catch(G){X(G)}}function Z(K){try{Y(E.throw(K))}catch(G){X(G)}}function Y(K){K.done?J(K.value):L(K.value).then(H,Z)}Y((E=E.apply(_,T||[])).next())})};Object.defineProperty(TT,"__esModule",{value:!0});TT.SocksClientError=TT.SocksClient=void 0;var Zv=j("events"),W4=j("net"),K1=k$(),I=CL(),U1=zU(),Yv=RU(),SL=OL();Object.defineProperty(TT,"SocksClientError",{enumerable:!0,get:function(){return SL.SocksClientError}});var wL=jL();class H5 extends Zv.EventEmitter{constructor(_){super();this.options=Object.assign({},_),(0,U1.validateSocksClientOptions)(_),this.setState(I.SocksClientState.Created)}static createConnection(_,T){return new Promise((A,E)=>{try{(0,U1.validateSocksClientOptions)(_,["connect"])}catch(J){if(typeof T==="function")return T(J),A(J);else return E(J)}let L=new H5(_);L.connect(_.existing_socket),L.once("established",(J)=>{if(L.removeAllListeners(),typeof T==="function")T(null,J),A(J);else A(J)}),L.once("error",(J)=>{if(L.removeAllListeners(),typeof T==="function")T(J),A(J);else E(J)})})}static createConnectionChain(_,T){return new Promise((A,E)=>U4(this,void 0,void 0,function*(){try{(0,U1.validateSocksClientChainOptions)(_)}catch(L){if(typeof T==="function")return T(L),A(L);else return E(L)}if(_.randomizeChain)(0,SL.shuffleArray)(_.proxies);try{let L;for(let J=0;J<_.proxies.length;J++){let X=_.proxies[J],H=J===_.proxies.length-1?_.destination:{host:_.proxies[J+1].host||_.proxies[J+1].ipaddress,port:_.proxies[J+1].port},Z=yield H5.createConnection({command:"connect",proxy:X,destination:H,existing_socket:L});L=L||Z.socket}if(typeof T==="function")T(null,{socket:L}),A({socket:L});else A({socket:L})}catch(L){if(typeof T==="function")T(L),A(L);else E(L)}}))}static createUDPFrame(_){let T=new K1.SmartBuffer;if(T.writeUInt16BE(0),T.writeUInt8(_.frameNumber||0),W4.isIPv4(_.remoteHost.host))T.writeUInt8(I.Socks5HostType.IPv4),T.writeUInt32BE((0,U1.ipv4ToInt32)(_.remoteHost.host));else if(W4.isIPv6(_.remoteHost.host))T.writeUInt8(I.Socks5HostType.IPv6),T.writeBuffer((0,U1.ipToBuffer)(_.remoteHost.host));else T.writeUInt8(I.Socks5HostType.Hostname),T.writeUInt8(Buffer.byteLength(_.remoteHost.host)),T.writeString(_.remoteHost.host);return T.writeUInt16BE(_.remoteHost.port),T.writeBuffer(_.data),T.toBuffer()}static parseUDPFrame(_){let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A=T.readUInt8(),E=T.readUInt8(),L;if(E===I.Socks5HostType.IPv4)L=(0,U1.int32ToIpv4)(T.readUInt32BE());else if(E===I.Socks5HostType.IPv6)L=wL.Address6.fromByteArray(Array.from(T.readBuffer(16))).canonicalForm();else L=T.readString(T.readUInt8());let J=T.readUInt16BE();return{frameNumber:A,remoteHost:{host:L,port:J},data:T.readBuffer()}}setState(_){if(this.state!==I.SocksClientState.Error)this.state=_}connect(_){this.onDataReceived=(A)=>this.onDataReceivedHandler(A),this.onClose=()=>this.onCloseHandler(),this.onError=(A)=>this.onErrorHandler(A),this.onConnect=()=>this.onConnectHandler();let T=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||I.DEFAULT_TIMEOUT);if(T.unref&&typeof T.unref==="function")T.unref();if(_)this.socket=_;else this.socket=new W4.Socket;if(this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(I.SocksClientState.Connecting),this.receiveBuffer=new Yv.ReceiveBuffer,_)this.socket.emit("connect");else if(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null)this.socket.setNoDelay(!!this.options.set_tcp_nodelay);this.prependOnceListener("established",(A)=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let E=this.receiveBuffer.get(this.receiveBuffer.length);A.socket.emit("data",E)}A.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){if(this.state!==I.SocksClientState.Established&&this.state!==I.SocksClientState.BoundWaitingForConnection)this.closeSocket(I.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){if(this.setState(I.SocksClientState.Connected),this.options.proxy.type===4)this.sendSocks4InitialHandshake();else this.sendSocks5InitialHandshake();this.setState(I.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(_){this.receiveBuffer.append(_),this.processData()}processData(){while(this.state!==I.SocksClientState.Established&&this.state!==I.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize)if(this.state===I.SocksClientState.SentInitialHandshake)if(this.options.proxy.type===4)this.handleSocks4FinalHandshakeResponse();else this.handleInitialSocks5HandshakeResponse();else if(this.state===I.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===I.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===I.SocksClientState.BoundWaitingForConnection)if(this.options.proxy.type===4)this.handleSocks4IncomingConnectionResponse();else this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(I.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(I.ERRORS.SocketClosed)}onErrorHandler(_){this.closeSocket(_.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(_){if(this.state!==I.SocksClientState.Error)this.setState(I.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new SL.SocksClientError(_,this.options))}sendSocks4InitialHandshake(){let _=this.options.proxy.userId||"",T=new K1.SmartBuffer;if(T.writeUInt8(4),T.writeUInt8(I.SocksCommand[this.options.command]),T.writeUInt16BE(this.options.destination.port),W4.isIPv4(this.options.destination.host))T.writeBuffer((0,U1.ipToBuffer)(this.options.destination.host)),T.writeStringNT(_);else T.writeUInt8(0),T.writeUInt8(0),T.writeUInt8(0),T.writeUInt8(1),T.writeStringNT(_),T.writeStringNT(this.options.destination.host);this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(T.toBuffer())}handleSocks4FinalHandshakeResponse(){let _=this.receiveBuffer.get(8);if(_[1]!==I.Socks4Response.Granted)this.closeSocket(`${I.ERRORS.Socks4ProxyRejectedConnection} - (${I.Socks4Response[_[1]]})`);else if(I.SocksCommand[this.options.command]===I.SocksCommand.bind){let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A={port:T.readUInt16BE(),host:(0,U1.int32ToIpv4)(T.readUInt32BE())};if(A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress;this.setState(I.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:A,socket:this.socket})}else this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let _=this.receiveBuffer.get(8);if(_[1]!==I.Socks4Response.Granted)this.closeSocket(`${I.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${I.Socks4Response[_[1]]})`);else{let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A={port:T.readUInt16BE(),host:(0,U1.int32ToIpv4)(T.readUInt32BE())};this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}sendSocks5InitialHandshake(){let _=new K1.SmartBuffer,T=[I.Socks5Auth.NoAuth];if(this.options.proxy.userId||this.options.proxy.password)T.push(I.Socks5Auth.UserPass);if(this.options.proxy.custom_auth_method!==void 0)T.push(this.options.proxy.custom_auth_method);_.writeUInt8(5),_.writeUInt8(T.length);for(let A of T)_.writeUInt8(A);this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(_.toBuffer()),this.setState(I.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let _=this.receiveBuffer.get(2);if(_[0]!==5)this.closeSocket(I.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);else if(_[1]===I.SOCKS5_NO_ACCEPTABLE_AUTH)this.closeSocket(I.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);else if(_[1]===I.Socks5Auth.NoAuth)this.socks5ChosenAuthType=I.Socks5Auth.NoAuth,this.sendSocks5CommandRequest();else if(_[1]===I.Socks5Auth.UserPass)this.socks5ChosenAuthType=I.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication();else if(_[1]===this.options.proxy.custom_auth_method)this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication();else this.closeSocket(I.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let _=this.options.proxy.userId||"",T=this.options.proxy.password||"",A=new K1.SmartBuffer;A.writeUInt8(1),A.writeUInt8(Buffer.byteLength(_)),A.writeString(_),A.writeUInt8(Buffer.byteLength(T)),A.writeString(T),this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(A.toBuffer()),this.setState(I.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return U4(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(I.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(_)})}handleSocks5AuthenticationNoAuthHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return _[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return _[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return U4(this,void 0,void 0,function*(){this.setState(I.SocksClientState.ReceivedAuthenticationResponse);let _=!1;if(this.socks5ChosenAuthType===I.Socks5Auth.NoAuth)_=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===I.Socks5Auth.UserPass)_=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===this.options.proxy.custom_auth_method)_=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));if(!_)this.closeSocket(I.ERRORS.Socks5AuthenticationFailed);else this.sendSocks5CommandRequest()})}sendSocks5CommandRequest(){let _=new K1.SmartBuffer;if(_.writeUInt8(5),_.writeUInt8(I.SocksCommand[this.options.command]),_.writeUInt8(0),W4.isIPv4(this.options.destination.host))_.writeUInt8(I.Socks5HostType.IPv4),_.writeBuffer((0,U1.ipToBuffer)(this.options.destination.host));else if(W4.isIPv6(this.options.destination.host))_.writeUInt8(I.Socks5HostType.IPv6),_.writeBuffer((0,U1.ipToBuffer)(this.options.destination.host));else _.writeUInt8(I.Socks5HostType.Hostname),_.writeUInt8(this.options.destination.host.length),_.writeString(this.options.destination.host);_.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(_.toBuffer()),this.setState(I.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let _=this.receiveBuffer.peek(5);if(_[0]!==5||_[1]!==I.Socks5Response.Granted)this.closeSocket(`${I.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${I.Socks5Response[_[1]]}`);else{let T=_[3],A,E;if(T===I.Socks5HostType.IPv4){let L=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}if(E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:(0,U1.int32ToIpv4)(E.readUInt32BE()),port:E.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if(T===I.Socks5HostType.Hostname){let L=_[4],J=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(L);if(this.receiveBuffer.length<J){this.nextRequiredPacketBufferSize=J;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(J).slice(5)),A={host:E.readString(L),port:E.readUInt16BE()}}else if(T===I.Socks5HostType.IPv6){let L=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:wL.Address6.fromByteArray(Array.from(E.readBuffer(16))).canonicalForm(),port:E.readUInt16BE()}}if(this.setState(I.SocksClientState.ReceivedFinalResponse),I.SocksCommand[this.options.command]===I.SocksCommand.connect)this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket});else if(I.SocksCommand[this.options.command]===I.SocksCommand.bind)this.setState(I.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:A,socket:this.socket});else if(I.SocksCommand[this.options.command]===I.SocksCommand.associate)this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}handleSocks5IncomingConnectionResponse(){let _=this.receiveBuffer.peek(5);if(_[0]!==5||_[1]!==I.Socks5Response.Granted)this.closeSocket(`${I.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${I.Socks5Response[_[1]]}`);else{let T=_[3],A,E;if(T===I.Socks5HostType.IPv4){let L=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}if(E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:(0,U1.int32ToIpv4)(E.readUInt32BE()),port:E.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if(T===I.Socks5HostType.Hostname){let L=_[4],J=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(L);if(this.receiveBuffer.length<J){this.nextRequiredPacketBufferSize=J;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(J).slice(5)),A={host:E.readString(L),port:E.readUInt16BE()}}else if(T===I.Socks5HostType.IPv6){let L=I.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:wL.Address6.fromByteArray(Array.from(E.readBuffer(16))).canonicalForm(),port:E.readUInt16BE()}}this.setState(I.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}TT.SocksClient=H5});var BU=W((hT)=>{var Kv=hT&&hT.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),Gv=hT&&hT.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))Kv(T,_,A)};Object.defineProperty(hT,"__esModule",{value:!0});Gv(DU(),hT)});var vL=W((i1)=>{var $v=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]}),Uv=i1&&i1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Wv=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")$v(A,T,E[L])}return Uv(A,T),A}}(),qU=i1&&i1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(i1,"__esModule",{value:!0});i1.default=Rv;var Nv=qU(u1()),Qv=j("stream"),Mv=BU(),Vv=Wv(j("dns")),zv=j("util"),yL=qU(j("assert")),b0=(0,Nv.default)("mqttjs:socks");class IU extends Qv.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(_){if(b0("proxy stream started"),(0,yL.default)(!this._socket),this.destroyed){_.destroy(this.errored);return}if(this._socket=_,!this._flowing)_.pause();_.on("data",this._onData),_.on("end",this._onEnd),_.on("error",this._onError),_.on("close",this._onClose),_.emit("connect"),this.uncork()}_write(_,T,A){(0,yL.default)(this._socket),this._socket.write(_,A)}_read(_){this._flowing=!0,this._socket?.resume?.()}_destroy(_,T){this._socket?.destroy?.(_),T(_)}_onData=(_)=>{if((0,yL.default)(this._socket),this._flowing=this.push(_),!this._flowing)this._socket.pause()};_onEnd=()=>{b0("proxy stream received EOF"),this.push(null)};_onClose=()=>{b0("proxy stream closed"),this.destroy()};_onError=(_)=>{b0("proxy stream died with error %s",_),this.destroy(_)}}function Z5(_){try{if(_.code===void 0)_.code="SOCKS";return _}catch{return _}}function Fv(_){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 Cv(_){let T=new URL(_);if(T.pathname||T.hash||T.search)throw Z5(Error("bad SOCKS URL"));let[A,E]=Fv(T.protocol);if(!A)throw Z5(Error("bad SOCKS URL: invalid protocol"));let L=parseInt(T.port,10);if(Number.isNaN(L))throw Z5(Error("bad SOCKS URL: invalid port"));return[{host:T.hostname,port:L,type:A},E]}async function Ov(_,T,A,E,L={}){let J=L.lookup??(0,zv.promisify)(Vv.lookup),[X,H]=Cv(A);if(!H)b0("resolving %s locally",_),_=(await J(_,{family:X.type===4?4:0})).address;b0("establishing SOCKS%d connection to %s:%d via %s:%d",X.type,_,T,X.host,X.port);let Z=new Mv.SocksClient({command:"connect",destination:{host:_,port:T},proxy:{...X},timeout:L.timeout});Z.connect(),Z.on("established",({socket:Y})=>E._start(Y)),Z.on("error",(Y)=>{b0("SOCKS failed: %s",Y),E.destroy(Z5(Y))})}function Rv(_,T,A,E){b0("SOCKS connection to %s:%d via %s",_,T,A);let L=new IU;return Ov(_,T,A,L,E).catch((J)=>{b0("SOCKS failed: %s",J),L.destroy(J)}),L}});var kL=W((I8)=>{var hL=I8&&I8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(I8,"__esModule",{value:!0});var Dv=hL(j("net")),Bv=hL(u1()),qv=hL(vL()),Iv=(0,Bv.default)("mqttjs:tcp"),Pv=(_,T)=>{if(T.port=T.port||1883,T.hostname=T.hostname||T.host||"localhost",T.socksProxy)return(0,qv.default)(T.hostname,T.port,T.socksProxy,{timeout:T.socksTimeout});let{port:A,path:E}=T,L=T.hostname;return Iv("port %d and host %s",A,L),Dv.default.createConnection({port:A,host:L,path:E})};I8.default=Pv});var bL=W((P8)=>{var fL=P8&&P8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(P8,"__esModule",{value:!0});var PU=j("tls"),jv=fL(j("net")),xv=fL(u1()),wv=fL(vL()),Sv=(0,xv.default)("mqttjs:tls");function yv(_){let{host:T,port:A,socksProxy:E,...L}=_;if(E!==void 0){let J=(0,wv.default)(T,A,E,{timeout:_.socksTimeout});return(0,PU.connect)({...L,socket:J})}return(0,PU.connect)(_)}var vv=(_,T)=>{if(T.port=T.port||8883,T.host=T.hostname||T.host||"localhost",jv.default.isIP(T.host)===0)T.servername=T.host;T.rejectUnauthorized=T.rejectUnauthorized!==!1,delete T.path,Sv("port %d host %s rejectUnauthorized %b",T.port,T.host,T.rejectUnauthorized);let A=yv(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=vv});var mL=W((xU)=>{Object.defineProperty(xU,"__esModule",{value:!0});var jU=j("buffer"),hv=n0(),kv=tA(),M0,gL,W1;function fv(){let _=new hv.Transform;return _._write=(T,A,E)=>{M0.send({data:T.buffer,success(){E()},fail(L){E(Error(L))}})},_._flush=(T)=>{M0.close({success(){T()}})},_}function bv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function gv(_,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 mv(){M0.onOpen(()=>{W1.socketReady()}),M0.onMessage((_)=>{let{data:T}=_;if(T instanceof ArrayBuffer)T=jU.Buffer.from(T);else T=jU.Buffer.from(T,"utf8");gL.push(T)}),M0.onClose(()=>{W1.emit("close"),W1.end(),W1.destroy()}),M0.onError((_)=>{let T=Error(_.errMsg);W1.destroy(T)})}var uv=(_,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";bv(T);let E=gv(T,_);M0=wx.connectSocket({url:E,protocols:[A]}),gL=fv(),W1=new kv.BufferedDuplex(T,gL,M0),W1._destroy=(J,X)=>{M0.close({success(){if(X)X(J)}})};let L=W1.destroy;return W1.destroy=(J,X)=>{return W1.destroy=L,setTimeout(()=>{M0.close({fail(){W1._destroy(J,X)}})},0),W1},mv(),W1};xU.default=uv});var dL=W((SU)=>{Object.defineProperty(SU,"__esModule",{value:!0});var uL=j("buffer"),cv=n0(),pv=tA(),g0,j8,N4,wU=!1;function lv(){let _=new cv.Transform;return _._write=(T,A,E)=>{g0.sendSocketMessage({data:T.buffer,success(){E()},fail(){E(Error())}})},_._flush=(T)=>{g0.closeSocket({success(){T()}})},_}function nv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function iv(_,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 av(){if(wU)return;wU=!0,g0.onSocketOpen(()=>{N4.socketReady()}),g0.onSocketMessage((_)=>{if(typeof _.data==="string"){let T=uL.Buffer.from(_.data,"base64");j8.push(T)}else{let T=new FileReader;T.addEventListener("load",()=>{if(T.result instanceof ArrayBuffer){j8.push(uL.Buffer.from(T.result));return}j8.push(uL.Buffer.from(T.result,"utf-8"))}),T.readAsArrayBuffer(_.data)}}),g0.onSocketClose(()=>{N4.end(),N4.destroy()}),g0.onSocketError((_)=>{N4.destroy(_)})}var ov=(_,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";nv(T);let E=iv(T,_);return g0=T.my,g0.connectSocket({url:E,protocols:A}),j8=lv(),N4=new pv.BufferedDuplex(T,j8,g0),av(),N4};SU.default=ov});var kU=W((Q4)=>{var Y5=Q4&&Q4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(Q4,"__esModule",{value:!0});Q4.connectAsync=Th;var sv=Y5(u1()),tv=Y5(j("url")),ev=Y5(sA()),yU=Y5(O8());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var vU=(0,sv.default)("mqttjs"),S_=null;function _h(_){let T;if(_.auth)if(T=_.auth.match(/^(.+):(.+)$/),T){let[,A,E]=T;_.username=A,_.password=E}else _.username=_.auth}function hU(_,T){if(vU("connecting to an MQTT broker..."),typeof _==="object"&&!T)T=_,_="";if(T=T||{},_&&typeof _==="string"){let L=tv.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(_h(T),T.query&&typeof T.query.clientId==="string")T.clientId=T.query.clientId;if(yU.default||T.unixSocket)T.socksProxy=void 0;else if(T.socksProxy===void 0&&typeof process<"u")T.socksProxy=process.env.MQTTJS_SOCKS_PROXY;if(T.cert&&T.key)if(T.protocol){if(["mqtts","wss","wxs","alis"].indexOf(T.protocol)===-1)switch(T.protocol){case"mqtt":T.protocol="mqtts";break;case"ws":T.protocol="wss";break;case"wx":T.protocol="wxs";break;case"ali":T.protocol="alis";break;default:throw Error(`Unknown protocol for secure connection: "${T.protocol}"!`)}}else throw Error("Missing secure protocol key");if(!S_)if(S_={},!yU.default&&!T.forceNativeWebSocket)S_.ws=B8().streamBuilder,S_.wss=B8().streamBuilder,S_.mqtt=kL().default,S_.tcp=kL().default,S_.ssl=bL().default,S_.tls=S_.ssl,S_.mqtts=bL().default;else S_.ws=B8().browserStreamBuilder,S_.wss=B8().browserStreamBuilder,S_.wx=mL().default,S_.wxs=mL().default,S_.ali=dL().default,S_.alis=dL().default;if(!S_[T.protocol]){let L=["mqtts","wss"].indexOf(T.protocol)!==-1;T.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((J,X)=>{if(L&&X%2===0)return!1;return typeof S_[J]==="function"})[0]}if(T.clean===!1&&!T.clientId)throw Error("Missing clientId for unclean clients");if(T.protocol)T.defaultProtocol=T.protocol;function A(L){if(T.servers){if(!L._reconnectCount||L._reconnectCount===T.servers.length)L._reconnectCount=0;T.host=T.servers[L._reconnectCount].host,T.port=T.servers[L._reconnectCount].port,T.protocol=!T.servers[L._reconnectCount].protocol?T.defaultProtocol:T.servers[L._reconnectCount].protocol,T.hostname=T.host,L._reconnectCount++}return vU("calling streambuilder for",T.protocol),S_[T.protocol](L,T)}let E=new ev.default(A,T);return E.on("error",()=>{}),E}function Th(_,T,A=!0){return new Promise((E,L)=>{let J=hU(_,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=hU});var cL=W((Z_)=>{var fU=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]}),Ah=Z_&&Z_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Eh=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")fU(A,T,E[L])}return Ah(A,T),A}}(),bU=Z_&&Z_.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))fU(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 gU=x8(sA());Z_.MqttClient=gU.default;var Lh=x8(AL());Z_.DefaultMessageIdProvider=Lh.default;var Jh=x8(F$());Z_.UniqueMessageIdProvider=Jh.default;var Xh=x8(dE());Z_.Store=Xh.default;var mU=Eh(kU());Z_.connect=mU.default;Object.defineProperty(Z_,"connectAsync",{enumerable:!0,get:function(){return mU.connectAsync}});var Hh=x8(NL());Z_.KeepaliveManager=Hh.default;Z_.Client=gU.default;bU(sA(),Z_);bU(BT(),Z_);var Zh=e4();Object.defineProperty(Z_,"ReasonCodes",{enumerable:!0,get:function(){return Zh.ReasonCodes}})});var dU=W((q1)=>{var uU=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]}),Yh=q1&&q1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Kh=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")uU(A,T,E[L])}return Yh(A,T),A}}(),Gh=q1&&q1.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))uU(T,_,A)};Object.defineProperty(q1,"__esModule",{value:!0});var $h=Kh(cL());q1.default=$h;Gh(cL(),q1)});var nL=W((Iu,oU)=>{oU.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var tU=W((Pu,sU)=>{var zh=nL();function rU(_){this.mode=zh.MODE_8BIT_BYTE,this.data=_}rU.prototype={getLength:function(){return this.data.length},write:function(_){for(var T=0;T<this.data.length;T++)_.put(this.data.charCodeAt(T),8)}};sU.exports=rU});var iL=W((ju,eU)=>{var a1={glog:function(_){if(_<1)throw Error("glog("+_+")");return a1.LOG_TABLE[_]},gexp:function(_){while(_<0)_+=255;while(_>=256)_-=255;return a1.EXP_TABLE[_]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(R_=0;R_<8;R_++)a1.EXP_TABLE[R_]=1<<R_;var R_;for(R_=8;R_<256;R_++)a1.EXP_TABLE[R_]=a1.EXP_TABLE[R_-4]^a1.EXP_TABLE[R_-5]^a1.EXP_TABLE[R_-6]^a1.EXP_TABLE[R_-8];var R_;for(R_=0;R_<255;R_++)a1.LOG_TABLE[a1.EXP_TABLE[R_]]=R_;var R_;eU.exports=a1});var aL=W((xu,_W)=>{var kT=iL();function N5(_,T){if(_.length===void 0)throw Error(_.length+"/"+T);var A=0;while(A<_.length&&_[A]===0)A++;this.num=Array(_.length-A+T);for(var E=0;E<_.length-A;E++)this.num[E]=_[E+A]}N5.prototype={get:function(_){return this.num[_]},getLength:function(){return this.num.length},multiply:function(_){var T=Array(this.getLength()+_.getLength()-1);for(var A=0;A<this.getLength();A++)for(var E=0;E<_.getLength();E++)T[A+E]^=kT.gexp(kT.glog(this.get(A))+kT.glog(_.get(E)));return new N5(T,0)},mod:function(_){if(this.getLength()-_.getLength()<0)return this;var T=kT.glog(this.get(0))-kT.glog(_.get(0)),A=Array(this.getLength());for(var E=0;E<this.getLength();E++)A[E]=this.get(E);for(var L=0;L<_.getLength();L++)A[L]^=kT.gexp(kT.glog(_.get(L))+T);return new N5(A,0).mod(_)}};_W.exports=N5});var AW=W((wu,TW)=>{TW.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var JW=W((Su,LW)=>{var P1=nL(),EW=aL(),Fh=iL(),AT=AW(),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 EW([1],0);for(var A=0;A<_;A++)T=T.multiply(new EW([1,Fh.gexp(A)],0));return T},getLengthInBits:function(_,T){if(1<=T&&T<10)switch(_){case P1.MODE_NUMBER:return 10;case P1.MODE_ALPHA_NUM:return 9;case P1.MODE_8BIT_BYTE:return 8;case P1.MODE_KANJI:return 8;default:throw Error("mode:"+_)}else if(T<27)switch(_){case P1.MODE_NUMBER:return 12;case P1.MODE_ALPHA_NUM:return 11;case P1.MODE_8BIT_BYTE:return 16;case P1.MODE_KANJI:return 10;default:throw Error("mode:"+_)}else if(T<41)switch(_){case P1.MODE_NUMBER:return 14;case P1.MODE_ALPHA_NUM:return 13;case P1.MODE_8BIT_BYTE:return 16;case P1.MODE_KANJI:return 12;default:throw Error("mode:"+_)}else throw Error("type:"+T)},getLostPoint:function(_){var T=_.getModuleCount(),A=0,E=0,L=0;for(E=0;E<T;E++)for(L=0;L<T;L++){var J=0,X=_.isDark(E,L);for(var H=-1;H<=1;H++){if(E+H<0||T<=E+H)continue;for(var Z=-1;Z<=1;Z++){if(L+Z<0||T<=L+Z)continue;if(H===0&&Z===0)continue;if(X===_.isDark(E+H,L+Z))J++}}if(J>5)A+=3+J-5}for(E=0;E<T-1;E++)for(L=0;L<T-1;L++){var Y=0;if(_.isDark(E,L))Y++;if(_.isDark(E+1,L))Y++;if(_.isDark(E,L+1))Y++;if(_.isDark(E+1,L+1))Y++;if(Y===0||Y===4)A+=3}for(E=0;E<T;E++)for(L=0;L<T-6;L++)if(_.isDark(E,L)&&!_.isDark(E,L+1)&&_.isDark(E,L+2)&&_.isDark(E,L+3)&&_.isDark(E,L+4)&&!_.isDark(E,L+5)&&_.isDark(E,L+6))A+=40;for(L=0;L<T;L++)for(E=0;E<T-6;E++)if(_.isDark(E,L)&&!_.isDark(E+1,L)&&_.isDark(E+2,L)&&_.isDark(E+3,L)&&_.isDark(E+4,L)&&!_.isDark(E+5,L)&&_.isDark(E+6,L))A+=40;var K=0;for(L=0;L<T;L++)for(E=0;E<T;E++)if(_.isDark(E,L))K++;var G=Math.abs(100*K/T/T-50)/5;return A+=G*10,A}};LW.exports=u_});var oL=W((yu,XW)=>{XW.exports={L:1,M:0,Q:3,H:2}});var ZW=W((vu,HW)=>{var Q5=oL();function V0(_,T){this.totalCount=_,this.dataCount=T}V0.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];V0.getRSBlocks=function(_,T){var A=V0.getRsBlockTable(_,T);if(A===void 0)throw Error("bad rs block @ typeNumber:"+_+"/errorCorrectLevel:"+T);var E=A.length/3,L=[];for(var J=0;J<E;J++){var X=A[J*3+0],H=A[J*3+1],Z=A[J*3+2];for(var Y=0;Y<X;Y++)L.push(new V0(H,Z))}return L};V0.getRsBlockTable=function(_,T){switch(T){case Q5.L:return V0.RS_BLOCK_TABLE[(_-1)*4+0];case Q5.M:return V0.RS_BLOCK_TABLE[(_-1)*4+1];case Q5.Q:return V0.RS_BLOCK_TABLE[(_-1)*4+2];case Q5.H:return V0.RS_BLOCK_TABLE[(_-1)*4+3];default:return}};HW.exports=V0});var GW=W((hu,KW)=>{function YW(){this.buffer=[],this.length=0}YW.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++}};KW.exports=YW});var NW=W((ku,WW)=>{var Ch=tU(),ET=JW(),Oh=aL(),$W=ZW(),UW=GW();function z0(_,T){this.typeNumber=_,this.errorCorrectLevel=T,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}z0.prototype={addData:function(_){var T=new Ch(_);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=$W.getRSBlocks(_,this.errorCorrectLevel),A=new UW,E=0;for(var L=0;L<T.length;L++)E+=T[L].dataCount;for(var J=0;J<this.dataList.length;J++){var X=this.dataList[J];A.put(X.mode,4),A.put(X.getLength(),ET.getLengthInBits(X.mode,_)),X.write(A)}if(A.getLengthInBits()<=E*8)break}this.typeNumber=_}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(_,T){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var A=0;A<this.moduleCount;A++){this.modules[A]=Array(this.moduleCount);for(var E=0;E<this.moduleCount;E++)this.modules[A][E]=null}if(this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(_,T),this.typeNumber>=7)this.setupTypeNumber(_);if(this.dataCache===null)this.dataCache=z0.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);this.mapData(this.dataCache,T)},setupPositionProbePattern:function(_,T){for(var A=-1;A<=7;A++){if(_+A<=-1||this.moduleCount<=_+A)continue;for(var E=-1;E<=7;E++){if(T+E<=-1||this.moduleCount<=T+E)continue;if(0<=A&&A<=6&&(E===0||E===6)||0<=E&&E<=6&&(A===0||A===6)||2<=A&&A<=4&&2<=E&&E<=4)this.modules[_+A][T+E]=!0;else this.modules[_+A][T+E]=!1}}},getBestMaskPattern:function(){var _=0,T=0;for(var A=0;A<8;A++){this.makeImpl(!0,A);var E=ET.getLostPoint(this);if(A===0||_>E)_=E,T=A}return T},createMovieClip:function(_,T,A){var E=_.createEmptyMovieClip(T,A),L=1;this.make();for(var J=0;J<this.modules.length;J++){var X=J*L;for(var H=0;H<this.modules[J].length;H++){var Z=H*L,Y=this.modules[J][H];if(Y)E.beginFill(0,100),E.moveTo(Z,X),E.lineTo(Z+L,X),E.lineTo(Z+L,X+L),E.lineTo(Z,X+L),E.endFill()}}return E},setupTimingPattern:function(){for(var _=8;_<this.moduleCount-8;_++){if(this.modules[_][6]!==null)continue;this.modules[_][6]=_%2===0}for(var T=8;T<this.moduleCount-8;T++){if(this.modules[6][T]!==null)continue;this.modules[6][T]=T%2===0}},setupPositionAdjustPattern:function(){var _=ET.getPatternPosition(this.typeNumber);for(var T=0;T<_.length;T++)for(var A=0;A<_.length;A++){var E=_[T],L=_[A];if(this.modules[E][L]!==null)continue;for(var J=-2;J<=2;J++)for(var X=-2;X<=2;X++)if(Math.abs(J)===2||Math.abs(X)===2||J===0&&X===0)this.modules[E+J][L+X]=!0;else this.modules[E+J][L+X]=!1}},setupTypeNumber:function(_){var T=ET.getBCHTypeNumber(this.typeNumber),A;for(var E=0;E<18;E++)A=!_&&(T>>E&1)===1,this.modules[Math.floor(E/3)][E%3+this.moduleCount-8-3]=A;for(var L=0;L<18;L++)A=!_&&(T>>L&1)===1,this.modules[L%3+this.moduleCount-8-3][Math.floor(L/3)]=A},setupTypeInfo:function(_,T){var A=this.errorCorrectLevel<<3|T,E=ET.getBCHTypeInfo(A),L;for(var J=0;J<15;J++)if(L=!_&&(E>>J&1)===1,J<6)this.modules[J][8]=L;else if(J<8)this.modules[J+1][8]=L;else this.modules[this.moduleCount-15+J][8]=L;for(var X=0;X<15;X++)if(L=!_&&(E>>X&1)===1,X<8)this.modules[8][this.moduleCount-X-1]=L;else if(X<9)this.modules[8][15-X-1+1]=L;else this.modules[8][15-X-1]=L;this.modules[this.moduleCount-8][8]=!_},mapData:function(_,T){var A=-1,E=this.moduleCount-1,L=7,J=0;for(var X=this.moduleCount-1;X>0;X-=2){if(X===6)X--;while(!0){for(var H=0;H<2;H++)if(this.modules[E][X-H]===null){var Z=!1;if(J<_.length)Z=(_[J]>>>L&1)===1;var Y=ET.getMask(T,E,X-H);if(Y)Z=!Z;if(this.modules[E][X-H]=Z,L--,L===-1)J++,L=7}if(E+=A,E<0||this.moduleCount<=E){E-=A,A=-A;break}}}}};z0.PAD0=236;z0.PAD1=17;z0.createData=function(_,T,A){var E=$W.getRSBlocks(_,T),L=new UW;for(var J=0;J<A.length;J++){var X=A[J];L.put(X.mode,4),L.put(X.getLength(),ET.getLengthInBits(X.mode,_)),X.write(L)}var H=0;for(var Z=0;Z<E.length;Z++)H+=E[Z].dataCount;if(L.getLengthInBits()>H*8)throw Error("code length overflow. ("+L.getLengthInBits()+">"+H*8+")");if(L.getLengthInBits()+4<=H*8)L.put(0,4);while(L.getLengthInBits()%8!==0)L.putBit(!1);while(!0){if(L.getLengthInBits()>=H*8)break;if(L.put(z0.PAD0,8),L.getLengthInBits()>=H*8)break;L.put(z0.PAD1,8)}return z0.createBytes(L,E)};z0.createBytes=function(_,T){var A=0,E=0,L=0,J=Array(T.length),X=Array(T.length);for(var H=0;H<T.length;H++){var Z=T[H].dataCount,Y=T[H].totalCount-Z;E=Math.max(E,Z),L=Math.max(L,Y),J[H]=Array(Z);for(var K=0;K<J[H].length;K++)J[H][K]=255&_.buffer[K+A];A+=Z;var G=ET.getErrorCorrectPolynomial(Y),$=new Oh(J[H],G.getLength()-1),U=$.mod(G);X[H]=Array(G.getLength()-1);for(var V=0;V<X[H].length;V++){var N=V+U.getLength()-X[H].length;X[H][V]=N>=0?U.get(N):0}}var z=0;for(var Q=0;Q<T.length;Q++)z+=T[Q].totalCount;var F=Array(z),R=0;for(var q=0;q<E;q++)for(var f=0;f<T.length;f++)if(q<J[f].length)F[R++]=J[f][q];for(var h=0;h<L;h++)for(var b=0;b<T.length;b++)if(h<X[b].length)F[R++]=X[b][h];return F};WW.exports=z0});var VW=W((fu,MW)=>{var Rh=NW(),QW=oL(),Dh="\x1B[40m \x1B[0m",M5="\x1B[47m \x1B[0m",Bh=function(_){return _?Dh:M5},rL=function(_){return{times:function(T){return Array(T).join(_)}}},qh=function(_,T){var A=Array(_);for(var E=0;E<_;E++)A[E]=T;return A};MW.exports={error:QW.L,generate:function(_,T,A){if(typeof T==="function")A=T,T={};var E=new Rh(-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(qh(H,X));var K={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},G=rL(K.BLACK_WHITE).times(H+3),$=rL(K.WHITE_BLACK).times(H+3);L+=G+`
|
|
12
|
+
*/var vE=KY(),J4=$Y(),GY=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;VI.Buffer=B;VI.SlowBuffer=_I;VI.INSPECT_MAX_BYTES=50;var fA=2147483647;VI.kMaxLength=fA;B.TYPED_ARRAY_SUPPORT=oq();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 oq(){try{var _=new Uint8Array(1),T={foo:function(){return 42}};return Object.setPrototypeOf(T,Uint8Array.prototype),Object.setPrototypeOf(_,T),_.foo()===42}catch(A){return!1}}Object.defineProperty(B.prototype,"parent",{enumerable:!0,get:function(){if(!B.isBuffer(this))return;return this.buffer}});Object.defineProperty(B.prototype,"offset",{enumerable:!0,get:function(){if(!B.isBuffer(this))return;return this.byteOffset}});function S0(_){if(_>fA)throw RangeError('The value "'+_+'" is invalid for option "size"');var T=new Uint8Array(_);return Object.setPrototypeOf(T,B.prototype),T}function B(_,T,A){if(typeof _==="number"){if(typeof T==="string")throw TypeError('The "string" argument must be of type string. Received type number');return bE(_)}return NY(_,T,A)}B.poolSize=8192;function NY(_,T,A){if(typeof _==="string")return sq(_,T);if(ArrayBuffer.isView(_))return tq(_);if(_==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _);if(H0(_,ArrayBuffer)||_&&H0(_.buffer,ArrayBuffer))return kE(_,T,A);if(typeof SharedArrayBuffer<"u"&&(H0(_,SharedArrayBuffer)||_&&H0(_.buffer,SharedArrayBuffer)))return kE(_,T,A);if(typeof _==="number")throw TypeError('The "value" argument must not be of type number. Received type number');var E=_.valueOf&&_.valueOf();if(E!=null&&E!==_)return B.from(E,T,A);var L=eq(_);if(L)return L;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof _[Symbol.toPrimitive]==="function")return B.from(_[Symbol.toPrimitive]("string"),T,A);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _)}B.from=function(_,T,A){return NY(_,T,A)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function QY(_){if(typeof _!=="number")throw TypeError('"size" argument must be of type number');else if(_<0)throw RangeError('The value "'+_+'" is invalid for option "size"')}function rq(_,T,A){if(QY(_),_<=0)return S0(_);if(T!==void 0)return typeof A==="string"?S0(_).fill(T,A):S0(_).fill(T);return S0(_)}B.alloc=function(_,T,A){return rq(_,T,A)};function bE(_){return QY(_),S0(_<0?0:gE(_)|0)}B.allocUnsafe=function(_){return bE(_)};B.allocUnsafeSlow=function(_){return bE(_)};function sq(_,T){if(typeof T!=="string"||T==="")T="utf8";if(!B.isEncoding(T))throw TypeError("Unknown encoding: "+T);var A=MY(_,T)|0,E=S0(A),L=E.write(_,T);if(L!==A)E=E.slice(0,L);return E}function hE(_){var T=_.length<0?0:gE(_.length)|0,A=S0(T);for(var E=0;E<T;E+=1)A[E]=_[E]&255;return A}function tq(_){if(H0(_,Uint8Array)){var T=new Uint8Array(_);return kE(T.buffer,T.byteOffset,T.byteLength)}return hE(_)}function kE(_,T,A){if(T<0||_.byteLength<T)throw RangeError('"offset" is outside of buffer bounds');if(_.byteLength<T+(A||0))throw RangeError('"length" is outside of buffer bounds');var E;if(T===void 0&&A===void 0)E=new Uint8Array(_);else if(A===void 0)E=new Uint8Array(_,T);else E=new Uint8Array(_,T,A);return Object.setPrototypeOf(E,B.prototype),E}function eq(_){if(B.isBuffer(_)){var T=gE(_.length)|0,A=S0(T);if(A.length===0)return A;return _.copy(A,0,0,T),A}if(_.length!==void 0){if(typeof _.length!=="number"||mE(_.length))return S0(0);return hE(_)}if(_.type==="Buffer"&&Array.isArray(_.data))return hE(_.data)}function gE(_){if(_>=fA)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+fA.toString(16)+" bytes");return _|0}function _I(_){if(+_!=_)_=0;return B.alloc(+_)}B.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==B.prototype};B.compare=function(T,A){if(H0(T,Uint8Array))T=B.from(T,T.offset,T.byteLength);if(H0(A,Uint8Array))A=B.from(A,A.offset,A.byteLength);if(!B.isBuffer(T)||!B.isBuffer(A))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===A)return 0;var E=T.length,L=A.length;for(var J=0,X=Math.min(E,L);J<X;++J)if(T[J]!==A[J]){E=T[J],L=A[J];break}if(E<L)return-1;if(L<E)return 1;return 0};B.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};B.concat=function(T,A){if(!Array.isArray(T))throw TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return B.alloc(0);var E;if(A===void 0){A=0;for(E=0;E<T.length;++E)A+=T[E].length}var L=B.allocUnsafe(A),J=0;for(E=0;E<T.length;++E){var X=T[E];if(H0(X,Uint8Array))if(J+X.length>L.length)B.from(X).copy(L,J);else Uint8Array.prototype.set.call(L,X,J);else if(!B.isBuffer(X))throw TypeError('"list" argument must be an Array of Buffers');else X.copy(L,J);J+=X.length}return L};function MY(_,T){if(B.isBuffer(_))return _.length;if(ArrayBuffer.isView(_)||H0(_,ArrayBuffer))return _.byteLength;if(typeof _!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof _);var A=_.length,E=arguments.length>2&&arguments[2]===!0;if(!E&&A===0)return 0;var L=!1;for(;;)switch(T){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return fE(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return RY(_).length;default:if(L)return E?-1:fE(_).length;T=(""+T).toLowerCase(),L=!0}}B.byteLength=MY;function TI(_,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 $I(this,T,A);case"utf8":case"utf-8":return zY(this,T,A);case"ascii":return YI(this,T,A);case"latin1":case"binary":return KI(this,T,A);case"base64":return HI(this,T,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return GI(this,T,A);default:if(E)throw TypeError("Unknown encoding: "+_);_=(_+"").toLowerCase(),E=!0}}B.prototype._isBuffer=!0;function BT(_,T,A){var E=_[T];_[T]=_[A],_[A]=E}B.prototype.swap16=function(){var T=this.length;if(T%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var A=0;A<T;A+=2)BT(this,A,A+1);return this};B.prototype.swap32=function(){var T=this.length;if(T%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var A=0;A<T;A+=4)BT(this,A,A+3),BT(this,A+1,A+2);return this};B.prototype.swap64=function(){var T=this.length;if(T%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var A=0;A<T;A+=8)BT(this,A,A+7),BT(this,A+1,A+6),BT(this,A+2,A+5),BT(this,A+3,A+4);return this};B.prototype.toString=function(){var T=this.length;if(T===0)return"";if(arguments.length===0)return zY(this,0,T);return TI.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=VI.INSPECT_MAX_BYTES;if(T=this.toString("hex",0,A).replace(/(.{2})/g,"$1 ").trim(),this.length>A)T+=" ... ";return"<Buffer "+T+">"};if(GY)B.prototype[GY]=B.prototype.inspect;B.prototype.compare=function(T,A,E,L,J){if(H0(T,Uint8Array))T=B.from(T,T.offset,T.byteLength);if(!B.isBuffer(T))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(A===void 0)A=0;if(E===void 0)E=T?T.length:0;if(L===void 0)L=0;if(J===void 0)J=this.length;if(A<0||E>T.length||L<0||J>this.length)throw RangeError("out of range index");if(L>=J&&A>=E)return 0;if(L>=J)return-1;if(A>=E)return 1;if(A>>>=0,E>>>=0,L>>>=0,J>>>=0,this===T)return 0;var X=J-L,H=E-A,Z=Math.min(X,H),Y=this.slice(L,J),K=T.slice(A,E);for(var $=0;$<Z;++$)if(Y[$]!==K[$]){X=Y[$],H=K[$];break}if(X<H)return-1;if(H<X)return 1;return 0};function VY(_,T,A,E,L){if(_.length===0)return-1;if(typeof A==="string")E=A,A=0;else if(A>2147483647)A=2147483647;else if(A<-2147483648)A=-2147483648;if(A=+A,mE(A))A=L?0:_.length-1;if(A<0)A=_.length+A;if(A>=_.length)if(L)return-1;else A=_.length-1;else if(A<0)if(L)A=0;else return-1;if(typeof T==="string")T=B.from(T,E);if(B.isBuffer(T)){if(T.length===0)return-1;return UY(_,T,A,E,L)}else if(typeof T==="number"){if(T=T&255,typeof Uint8Array.prototype.indexOf==="function")if(L)return Uint8Array.prototype.indexOf.call(_,T,A);else return Uint8Array.prototype.lastIndexOf.call(_,T,A);return UY(_,[T],A,E,L)}throw TypeError("val must be string, number or Buffer")}function UY(_,T,A,E,L){var J=1,X=_.length,H=T.length;if(E!==void 0){if(E=String(E).toLowerCase(),E==="ucs2"||E==="ucs-2"||E==="utf16le"||E==="utf-16le"){if(_.length<2||T.length<2)return-1;J=2,X/=2,H/=2,A/=2}}function Z(U,V){if(J===1)return U[V];else return U.readUInt16BE(V*J)}var Y;if(L){var K=-1;for(Y=A;Y<X;Y++)if(Z(_,Y)===Z(T,K===-1?0:Y-K)){if(K===-1)K=Y;if(Y-K+1===H)return K*J}else{if(K!==-1)Y-=Y-K;K=-1}}else{if(A+H>X)A=X-H;for(Y=A;Y>=0;Y--){var $=!0;for(var G=0;G<H;G++)if(Z(_,Y+G)!==Z(T,G)){$=!1;break}if($)return Y}}return-1}B.prototype.includes=function(T,A,E){return this.indexOf(T,A,E)!==-1};B.prototype.indexOf=function(T,A,E){return VY(this,T,A,E,!0)};B.prototype.lastIndexOf=function(T,A,E){return VY(this,T,A,E,!1)};function AI(_,T,A,E){A=Number(A)||0;var L=_.length-A;if(!E)E=L;else if(E=Number(E),E>L)E=L;var J=T.length;if(E>J/2)E=J/2;for(var X=0;X<E;++X){var H=parseInt(T.substr(X*2,2),16);if(mE(H))return X;_[A+X]=H}return X}function EI(_,T,A,E){return bA(fE(T,_.length-A),_,A,E)}function LI(_,T,A,E){return bA(NI(T),_,A,E)}function JI(_,T,A,E){return bA(RY(T),_,A,E)}function XI(_,T,A,E){return bA(QI(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 AI(this,T,A,E);case"utf8":case"utf-8":return EI(this,T,A,E);case"ascii":case"latin1":case"binary":return LI(this,T,A,E);case"base64":return JI(this,T,A,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return XI(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 HI(_,T,A){if(T===0&&A===_.length)return vE.fromByteArray(_);else return vE.fromByteArray(_.slice(T,A))}function zY(_,T,A){A=Math.min(_.length,A);var E=[],L=T;while(L<A){var J=_[L],X=null,H=J>239?4:J>223?3:J>191?2:1;if(L+H<=A){var Z,Y,K,$;switch(H){case 1:if(J<128)X=J;break;case 2:if(Z=_[L+1],(Z&192)===128){if($=(J&31)<<6|Z&63,$>127)X=$}break;case 3:if(Z=_[L+1],Y=_[L+2],(Z&192)===128&&(Y&192)===128){if($=(J&15)<<12|(Z&63)<<6|Y&63,$>2047&&($<55296||$>57343))X=$}break;case 4:if(Z=_[L+1],Y=_[L+2],K=_[L+3],(Z&192)===128&&(Y&192)===128&&(K&192)===128){if($=(J&15)<<18|(Z&63)<<12|(Y&63)<<6|K&63,$>65535&&$<1114112)X=$}}}if(X===null)X=65533,H=1;else if(X>65535)X-=65536,E.push(X>>>10&1023|55296),X=56320|X&1023;E.push(X),L+=H}return ZI(E)}var WY=4096;function ZI(_){var T=_.length;if(T<=WY)return String.fromCharCode.apply(String,_);var A="",E=0;while(E<T)A+=String.fromCharCode.apply(String,_.slice(E,E+=WY));return A}function YI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]&127);return E}function KI(_,T,A){var E="";A=Math.min(_.length,A);for(var L=T;L<A;++L)E+=String.fromCharCode(_[L]);return E}function $I(_,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+=MI[_[J]];return L}function GI(_,T,A){var E=_.slice(T,A),L="";for(var J=0;J<E.length-1;J+=2)L+=String.fromCharCode(E[J]+E[J+1]*256);return L}B.prototype.slice=function(T,A){var E=this.length;if(T=~~T,A=A===void 0?E:~~A,T<0){if(T+=E,T<0)T=0}else if(T>E)T=E;if(A<0){if(A+=E,A<0)A=0}else if(A>E)A=E;if(A<T)A=T;var L=this.subarray(T,A);return Object.setPrototypeOf(L,B.prototype),L};function h_(_,T,A){if(_%1!==0||_<0)throw RangeError("offset is not uint");if(_+T>A)throw RangeError("Trying to access beyond buffer length")}B.prototype.readUintLE=B.prototype.readUIntLE=function(T,A,E){if(T=T>>>0,A=A>>>0,!E)h_(T,A,this.length);var L=this[T],J=1,X=0;while(++X<A&&(J*=256))L+=this[T+X]*J;return L};B.prototype.readUintBE=B.prototype.readUIntBE=function(T,A,E){if(T=T>>>0,A=A>>>0,!E)h_(T,A,this.length);var L=this[T+--A],J=1;while(A>0&&(J*=256))L+=this[T+--A]*J;return L};B.prototype.readUint8=B.prototype.readUInt8=function(T,A){if(T=T>>>0,!A)h_(T,1,this.length);return this[T]};B.prototype.readUint16LE=B.prototype.readUInt16LE=function(T,A){if(T=T>>>0,!A)h_(T,2,this.length);return this[T]|this[T+1]<<8};B.prototype.readUint16BE=B.prototype.readUInt16BE=function(T,A){if(T=T>>>0,!A)h_(T,2,this.length);return this[T]<<8|this[T+1]};B.prototype.readUint32LE=B.prototype.readUInt32LE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216};B.prototype.readUint32BE=B.prototype.readUInt32BE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])};B.prototype.readIntLE=function(T,A,E){if(T=T>>>0,A=A>>>0,!E)h_(T,A,this.length);var L=this[T],J=1,X=0;while(++X<A&&(J*=256))L+=this[T+X]*J;if(J*=128,L>=J)L-=Math.pow(2,8*A);return L};B.prototype.readIntBE=function(T,A,E){if(T=T>>>0,A=A>>>0,!E)h_(T,A,this.length);var L=A,J=1,X=this[T+--L];while(L>0&&(J*=256))X+=this[T+--L]*J;if(J*=128,X>=J)X-=Math.pow(2,8*A);return X};B.prototype.readInt8=function(T,A){if(T=T>>>0,!A)h_(T,1,this.length);if(!(this[T]&128))return this[T];return(255-this[T]+1)*-1};B.prototype.readInt16LE=function(T,A){if(T=T>>>0,!A)h_(T,2,this.length);var E=this[T]|this[T+1]<<8;return E&32768?E|4294901760:E};B.prototype.readInt16BE=function(T,A){if(T=T>>>0,!A)h_(T,2,this.length);var E=this[T+1]|this[T]<<8;return E&32768?E|4294901760:E};B.prototype.readInt32LE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24};B.prototype.readInt32BE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]};B.prototype.readFloatLE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return J4.read(this,T,!0,23,4)};B.prototype.readFloatBE=function(T,A){if(T=T>>>0,!A)h_(T,4,this.length);return J4.read(this,T,!1,23,4)};B.prototype.readDoubleLE=function(T,A){if(T=T>>>0,!A)h_(T,8,this.length);return J4.read(this,T,!0,52,8)};B.prototype.readDoubleBE=function(T,A){if(T=T>>>0,!A)h_(T,8,this.length);return J4.read(this,T,!1,52,8)};function H1(_,T,A,E,L,J){if(!B.isBuffer(_))throw TypeError('"buffer" argument must be a Buffer instance');if(T>L||T<J)throw RangeError('"value" argument is out of bounds');if(A+E>_.length)throw RangeError("Index out of range")}B.prototype.writeUintLE=B.prototype.writeUIntLE=function(T,A,E,L){if(T=+T,A=A>>>0,E=E>>>0,!L){var J=Math.pow(2,8*E)-1;H1(this,T,A,E,J,0)}var X=1,H=0;this[A]=T&255;while(++H<E&&(X*=256))this[A+H]=T/X&255;return A+E};B.prototype.writeUintBE=B.prototype.writeUIntBE=function(T,A,E,L){if(T=+T,A=A>>>0,E=E>>>0,!L){var J=Math.pow(2,8*E)-1;H1(this,T,A,E,J,0)}var X=E-1,H=1;this[A+X]=T&255;while(--X>=0&&(H*=256))this[A+X]=T/H&255;return A+E};B.prototype.writeUint8=B.prototype.writeUInt8=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,1,255,0);return this[A]=T&255,A+1};B.prototype.writeUint16LE=B.prototype.writeUInt16LE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,2,65535,0);return this[A]=T&255,this[A+1]=T>>>8,A+2};B.prototype.writeUint16BE=B.prototype.writeUInt16BE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,2,65535,0);return this[A]=T>>>8,this[A+1]=T&255,A+2};B.prototype.writeUint32LE=B.prototype.writeUInt32LE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,4,4294967295,0);return this[A+3]=T>>>24,this[A+2]=T>>>16,this[A+1]=T>>>8,this[A]=T&255,A+4};B.prototype.writeUint32BE=B.prototype.writeUInt32BE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,4,4294967295,0);return this[A]=T>>>24,this[A+1]=T>>>16,this[A+2]=T>>>8,this[A+3]=T&255,A+4};B.prototype.writeIntLE=function(T,A,E,L){if(T=+T,A=A>>>0,!L){var J=Math.pow(2,8*E-1);H1(this,T,A,E,J-1,-J)}var X=0,H=1,Z=0;this[A]=T&255;while(++X<E&&(H*=256)){if(T<0&&Z===0&&this[A+X-1]!==0)Z=1;this[A+X]=(T/H>>0)-Z&255}return A+E};B.prototype.writeIntBE=function(T,A,E,L){if(T=+T,A=A>>>0,!L){var J=Math.pow(2,8*E-1);H1(this,T,A,E,J-1,-J)}var X=E-1,H=1,Z=0;this[A+X]=T&255;while(--X>=0&&(H*=256)){if(T<0&&Z===0&&this[A+X+1]!==0)Z=1;this[A+X]=(T/H>>0)-Z&255}return A+E};B.prototype.writeInt8=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,1,127,-128);if(T<0)T=255+T+1;return this[A]=T&255,A+1};B.prototype.writeInt16LE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,2,32767,-32768);return this[A]=T&255,this[A+1]=T>>>8,A+2};B.prototype.writeInt16BE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,2,32767,-32768);return this[A]=T>>>8,this[A+1]=T&255,A+2};B.prototype.writeInt32LE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,4,2147483647,-2147483648);return this[A]=T&255,this[A+1]=T>>>8,this[A+2]=T>>>16,this[A+3]=T>>>24,A+4};B.prototype.writeInt32BE=function(T,A,E){if(T=+T,A=A>>>0,!E)H1(this,T,A,4,2147483647,-2147483648);if(T<0)T=4294967295+T+1;return this[A]=T>>>24,this[A+1]=T>>>16,this[A+2]=T>>>8,this[A+3]=T&255,A+4};function FY(_,T,A,E,L,J){if(A+E>_.length)throw RangeError("Index out of range");if(A<0)throw RangeError("Index out of range")}function CY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)FY(_,T,A,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return J4.write(_,T,A,E,23,4),A+4}B.prototype.writeFloatLE=function(T,A,E){return CY(this,T,A,!0,E)};B.prototype.writeFloatBE=function(T,A,E){return CY(this,T,A,!1,E)};function OY(_,T,A,E,L){if(T=+T,A=A>>>0,!L)FY(_,T,A,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return J4.write(_,T,A,E,52,8),A+8}B.prototype.writeDoubleLE=function(T,A,E){return OY(this,T,A,!0,E)};B.prototype.writeDoubleBE=function(T,A,E){return OY(this,T,A,!1,E)};B.prototype.copy=function(T,A,E,L){if(!B.isBuffer(T))throw TypeError("argument should be a Buffer");if(!E)E=0;if(!L&&L!==0)L=this.length;if(A>=T.length)A=T.length;if(!A)A=0;if(L>0&&L<E)L=E;if(L===E)return 0;if(T.length===0||this.length===0)return 0;if(A<0)throw RangeError("targetStart out of bounds");if(E<0||E>=this.length)throw RangeError("Index out of range");if(L<0)throw RangeError("sourceEnd out of bounds");if(L>this.length)L=this.length;if(T.length-A<L-E)L=T.length-A+E;var J=L-E;if(this===T&&typeof Uint8Array.prototype.copyWithin==="function")this.copyWithin(A,E,L);else Uint8Array.prototype.set.call(T,this.subarray(E,L),A);return J};B.prototype.fill=function(T,A,E,L){if(typeof T==="string"){if(typeof A==="string")L=A,A=0,E=this.length;else if(typeof E==="string")L=E,E=this.length;if(L!==void 0&&typeof L!=="string")throw TypeError("encoding must be a string");if(typeof L==="string"&&!B.isEncoding(L))throw TypeError("Unknown encoding: "+L);if(T.length===1){var J=T.charCodeAt(0);if(L==="utf8"&&J<128||L==="latin1")T=J}}else if(typeof T==="number")T=T&255;else if(typeof T==="boolean")T=Number(T);if(A<0||this.length<A||this.length<E)throw RangeError("Out of range index");if(E<=A)return this;if(A=A>>>0,E=E===void 0?this.length:E>>>0,!T)T=0;var X;if(typeof T==="number")for(X=A;X<E;++X)this[X]=T;else{var H=B.isBuffer(T)?T:B.from(T,L),Z=H.length;if(Z===0)throw TypeError('The value "'+T+'" is invalid for argument "value"');for(X=0;X<E-A;++X)this[X+A]=H[X%Z]}return this};var UI=/[^+/0-9A-Za-z-_]/g;function WI(_){if(_=_.split("=")[0],_=_.trim().replace(UI,""),_.length<2)return"";while(_.length%4!==0)_=_+"=";return _}function fE(_,T){T=T||1/0;var A,E=_.length,L=null,J=[];for(var X=0;X<E;++X){if(A=_.charCodeAt(X),A>55295&&A<57344){if(!L){if(A>56319){if((T-=3)>-1)J.push(239,191,189);continue}else if(X+1===E){if((T-=3)>-1)J.push(239,191,189);continue}L=A;continue}if(A<56320){if((T-=3)>-1)J.push(239,191,189);L=A;continue}A=(L-55296<<10|A-56320)+65536}else if(L){if((T-=3)>-1)J.push(239,191,189)}if(L=null,A<128){if((T-=1)<0)break;J.push(A)}else if(A<2048){if((T-=2)<0)break;J.push(A>>6|192,A&63|128)}else if(A<65536){if((T-=3)<0)break;J.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((T-=4)<0)break;J.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw Error("Invalid code point")}return J}function NI(_){var T=[];for(var A=0;A<_.length;++A)T.push(_.charCodeAt(A)&255);return T}function QI(_,T){var A,E,L,J=[];for(var X=0;X<_.length;++X){if((T-=2)<0)break;A=_.charCodeAt(X),E=A>>8,L=A%256,J.push(L),J.push(E)}return J}function RY(_){return vE.toByteArray(WI(_))}function bA(_,T,A,E){for(var L=0;L<E;++L){if(L+A>=T.length||L>=_.length)break;T[L+A]=_[L]}return L}function H0(_,T){return _ instanceof T||_!=null&&_.constructor!=null&&_.constructor.name!=null&&_.constructor.name===T.name}function mE(_){return _!==_}var MI=function(){var _="0123456789abcdef",T=Array(256);for(var A=0;A<16;++A){var E=A*16;for(var L=0;L<16;++L)T[E+L]=_[A]+_[L]}return T}()});var xY=W((ab,uE)=>{var qY=JY(),PY=ZY(),gA=OI();function OI(){let _=I("buffer");return _&&_.Buffer?_.Buffer:BY().Buffer}var RI=gA.from("==","base64");function DI(_){let T=!1,A=!1,E=Math.pow(2,31)-1;if(typeof _==="boolean")T=_;else _=_||{},E=_.maxInt||Math.pow(2,31)-1,A=!!_.urlSafe,T=!!_.fixedLength;X.uuid=qY(),X.decode=jY;let L=IY(X.uuid,A),J=Math.floor(_.startFrom||0);if(isNaN(E))throw Error(`maxInt must be a number. recieved ${_.maxInt}`);if(isNaN(J)||!(E>J&&J>=0))throw Error([`when passed, opts.startFrom must be a number between 0 and ${E}.`,"Only the integer part matters.",`- got: ${_.startFrom}`].join(`
|
|
13
|
+
`));return X;function X(){let H;if(J===E)X.uuid=qY(),L=IY(X.uuid,A),J=0;if(T)H=L+`0000000000${J}`.slice(-10);else H=L+J;return J=J+1|0,H}}function IY(_,T){let A=gA.concat([gA.from(PY.parse(_)),RI]).toString("base64");if(T)return A.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"-");return A.replace(/=+$/,"/")}function jY(_,T){if(T=T||{},!!T.urlSafe)_=_.replace(/-([^-]*)$/,"/$1").replace(/-/g,"+").replace(/_/g,"/");if(_.length<22)return null;let E=_.lastIndexOf("/");if(E===-1)return null;let L=_.substring(0,E),J=Number(_.substring(E+1));if(!L||isNaN(J))return null;return{uuid:PY.unparse(gA.from(L+"==","base64")),count:J}}uE.exports=DI;uE.exports.decode=jY});var yY=W((ob,SY)=>{var BI=$2(),{pipeline:qI}=I("stream"),wY=x0(),II=FE(),{through:PI}=DT(),jI=yA(),xI=xY()();function wI(_){this.cmd="connack",this.returnCode=_.returnCode,this.sessionPresent=_.sessionPresent}function SI(_,T){this.client=_,this.packet=T}var yI=[kI,fI,bI,mI,uI,dI,cE,cI],dE=["","unacceptable protocol version","identifier rejected","Server unavailable","bad user name or password","not authorized","keep alive limit exceeded"];function vI(_,T,A){clearTimeout(_._connectTimer),_._connectTimer=null,_.connecting=!0,_.broker.preConnect(_,T,E);function E(L,J){if(!L&&J===!0)setImmediate(hI,_,T,A);else _.connecting=!1,A(L)}}function hI(_,T,A){let E=T.clientId,L=0;if(T.protocolVersion<3||T.protocolVersion>4)L=1;if(T.protocolVersion===3&&E.length>_.broker.maxClientsIdLength)L=2;if(_.broker.keepaliveLimit&&(!T.keepalive||T.keepalive>_.broker.keepaliveLimit))L=6;if(L>0){let J=Error(dE[L]);J.errorCode=L,cE({client:_,returnCode:L,sessionPresent:!1},A.bind(this,J));return}_.id=E||"aedes_"+xI(),_.clean=T.clean,_.version=T.protocolVersion,_._will=T.will,_.broker._series(new SI(_,T),yI,{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 kI(_,T){let A=this.client;A.pause(),A.broker.authenticate(A,this.packet.username,this.packet.password,E);function E(L,J){if(A.closed||A.broker.closed)return;if(!L&&J)return A._authorized=!0,T();if(L){let X=L.returnCode;if(X&&(X>=2&&X<=5))_.returnCode=X;else _.returnCode=5;if(!L.message)L.message=dE[_.returnCode]}else _.returnCode=5,L=Error(dE[_.returnCode]);L.errorCode=_.returnCode,_.client=A,cE(_,A.close.bind(A,T.bind(this,L)))}}function fI(_,T){if(this.packet.keepalive>0){let A=this.client;A._keepaliveInterval=this.packet.keepalive*1500+1,A._keepaliveTimer=BI(function(){A.broker.emit("keepaliveTimeout",A),A.emit("error",Error("keep alive timeout"))},A._keepaliveInterval)}T()}function bI(_,T){let A=this.client;if(!this.packet.clean){A.broker.persistence.subscriptionsByClient({id:A.id,done:T,arg:_},gI);return}_.sessionPresent=!1,A.broker.persistence.cleanSubscriptions(A,T)}function gI(_,T,A){if(_)return A.done(_);A.arg.subs=T,A.done()}function mI(_,T){if(_.subs){jI(this.client,{subscriptions:_.subs},!0,T),_.sessionPresent=!!_.subs;return}_.sessionPresent=!1,T()}function uI(_,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 dI(_,T){let A=this.client;A.broker.registerClient(A),T()}function cE(_,T){let A=_.client||this.client,E=new wI(_);wY(A,E,function(L){if(!L)A.broker.emit("connackSent",E,A),A.connackSent=!0;T(L)})}function cI(_,T){let A=this.client,E=A.broker.persistence,L=E.outgoingStream(A);A.resume(),qI(L,PI(function(X,H,Z){let Y=new II(X,A);Y.writeCallback=(K,$)=>Z(K),E.outgoingUpdate(A,Y,pI)}),T)}function pI(_,T,A){let E=A.writeCallback;if(_)return T.emit("error",_),E();let L=A.cmd==="publish"?T.broker.authorizeForward(T,A):!0,J=T.broker.persistence;if(T.clean||!L)J.outgoingClearMessageId(T,A,E);else wY(T,A,E)}SY.exports=vI});var kY=W((rb,hY)=>{var vY=x0();function lI(_){this.cmd="puback",this.messageId=_.messageId}function nI(_){this.cmd="pubrec",this.messageId=_.messageId}var iI=[rI,oI];function aI(_,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(_,iI,T,A)}function oI(_,T){let A=this;switch(_.qos){case 2:A.broker.persistence.incomingStorePacket(A,_,function(E){if(E)return T(E);vY(A,new nI(_),T)});break;case 1:vY(A,new lI(_),function(E){if(E)return T(E);A.broker.publish(_,A,T)});break;case 0:A.broker.publish(_,A,T);break;default:}}function rI(_,T){this.broker.authorizePublish(this,_,T)}hY.exports=aI});var bY=W((sb,fY)=>{function sI(_,T,A){_.broker.persistence.outgoingClearMessageId(_,T,function(L,J){_.broker.emit("ack",J,_),A(L)})}fY.exports=sI});var mY=W((tb,gY)=>{var tI=x0();function eI(_,T){this.client=_,this.packet=T}function _P(_){this.cmd="pubcomp",this.messageId=_.messageId}var TP=[EP,LP,JP,XP];function AP(_,T,A){_.broker._series(new eI(_,T),TP,{},A)}function EP(_,T){this.client.broker.persistence.incomingGetPacket(this.client,this.packet,E);function E(L,J){_.packet=J,T(L)}}function LP(_,T){this.client.broker.publish(_.packet,this.client,T)}function JP(_,T){tI(this.client,new _P(_.packet),T)}function XP(_,T){this.client.broker.persistence.incomingDelPacket(this.client,_.packet,T)}gY.exports=AP});var cY=W((eb,dY)=>{var uY=x0();function HP(_){this.cmd="pubrel",this.messageId=_.messageId}function ZP(_,T,A){let E=new HP(T);if(_.clean){uY(_,E,A);return}_.broker.persistence.outgoingUpdate(_,E,L);function L(J){if(J)A(J);else uY(_,E,A)}}dY.exports=ZP});var lY=W((_g,pY)=>{var YP=x0(),KP={cmd:"pingresp"};function $P(_,T,A){_.broker.emit("ping",T,_),YP(_,KP,A)}pY.exports=$P});var aY=W((Tg,iY)=>{var GP=yY(),UP=yA(),WP=OE(),NP=kY(),QP=bY(),MP=mY(),VP=cY(),zP=lY();function FP(_,T,A){if(T.cmd==="connect"){if(_.connecting||_.connected){nY(_.conn,T,A);return}GP(_,T,A);return}if(!_.connecting&&!_.connected){nY(_.conn,T,A);return}switch(T.cmd){case"publish":NP(_,T,A);break;case"subscribe":UP(_,T,!1,A);break;case"unsubscribe":WP(_,T,A);break;case"pubcomp":case"puback":QP(_,T,A);break;case"pubrel":MP(_,T,A);break;case"pubrec":VP(_,T,A);break;case"pingreq":zP(_,T,A);break;case"disconnect":_._disconnected=!0,_.conn.destroy(),A();return;default:_.conn.destroy(),A();return}if(_._keepaliveInterval>0)_._keepaliveTimer.reschedule(_._keepaliveInterval)}function nY(_,T,A){_.destroy();let E=Error("Invalid protocol");E.info=T,A(E)}iY.exports=FP});var AK=W((Ag,TK)=>{var CP=wA(),OP=I("events"),RP=I("util"),DP=cZ(),rY=uT(),sY=x0(),BP=FE(),qP=yA(),tY=OE(),eY=aY(),{pipeline:IP}=I("stream"),{through:PP}=DT();TK.exports=Z0;function Z0(_,T,A){let E=this;this.closed=!1,this.connecting=!1,this.connected=!1,this.connackSent=!1,this.errored=!1,this.id=null,this.clean=!0,this.version=null,this.subscriptions={},this.duplicates={},this.broker=_,this.conn=T,T.client=this,this._disconnected=!1,this._authorized=!1,this._parsingBatch=1,this._nextId=Math.ceil(Math.random()*65535),this.req=A,this.connDetails=A?A.connDetails:null,this.will=null,this._will=null,this._parser=CP.parser(),this._parser.client=this,this._parser._queue=[],this._parser.on("packet",wP),this.once("connected",SP);function L(X){if(X){E.emit("error",X);return}let H=E;if(H._paused)return;if(E._parsingBatch--,E._parsingBatch<=0){E._parsingBatch=0;let Z=H.conn.read(null);if(Z)H._parser.parse(Z)}}this._nextBatch=L,T.on("readable",L),this.on("error",_K),T.on("error",this.emit.bind(this,"error")),this._parser.on("error",this.emit.bind(this,"error")),T.on("end",this.close.bind(this)),this._eos=DP(this.conn,this.close.bind(this));let J=(X)=>{if(X.clientId===E.id&&X.nl)return;return jP(E,X)&&E.broker.authorizeForward(E,X)};this.deliver0=function(H,Z){let Y=J(H);if(Y)setImmediate(()=>{let K=new rY(Y,_);K.qos=0,sY(E,K,function($){E._onError($),Z()})});else setImmediate(Z)},this.deliverQoS=function(H,Z){if(H.qos===0){E.deliver0(H,Z);return}let Y=J(H);if(Y)setImmediate(()=>{let K=new BP(Y,E),$=E.subscriptions[K.topic];if($&&($.qos||0)<K.qos)K.qos=$.qos;if(K.writeCallback=Z,E.clean||K.retain)oY(null,E,K);else _.persistence.outgoingUpdate(E,K,oY)});else if(E.clean===!1)E.broker.persistence.outgoingClearMessageId(E,H,X4),setImmediate(Z);else setImmediate(Z)},this._keepaliveTimer=null,this._keepaliveInterval=-1,this._connectTimer=setTimeout(function(){E.emit("error",Error("connect did not arrive in time"))},_.connectTimeout)}function jP(_,T){let A=T.brokerId;if(!A)return!0;let E=_.duplicates,L=T.brokerCounter,J=(E[A]||0)<L;if(J)E[A]=L;return J}function oY(_,T,A){if(_)T.emit("error",_),A.writeCallback();else sY(T,A,function(E){if(E)T.emit("error",E);A.writeCallback()})}function xP(_){_.callback()}function _K(_){if(!_)return;this.errored=!0,this.conn.removeAllListeners("error"),this.conn.on("error",X4);let T=this.conn._writableState;(typeof T.getBuffer==="function"?T.getBuffer():T.buffer).forEach(xP),this.broker.emit(this.id?"clientError":"connectionError",this,_),this.close()}RP.inherits(Z0,OP);Z0.prototype._onError=_K;Z0.prototype.publish=function(_,T){let A=new rY(_,this.broker),E=this;if(A.qos===0){this.deliver0(A,T);return}if(!this.clean&&this.id)this.broker.persistence.outgoingEnqueue({clientId:this.id},A,function(J){if(J)return T(J);E.deliverQoS(A,T)});else E.deliverQoS(A,T)};Z0.prototype.subscribe=function(_,T){if(!_.subscriptions){if(!Array.isArray(_))_=[_];_={subscriptions:_}}qP(this,_,!1,T)};Z0.prototype.unsubscribe=function(_,T){if(!_.unsubscriptions){if(!Array.isArray(_))_=[_];_={unsubscriptions:_}}tY(this,_,T)};Z0.prototype.close=function(_){if(this.closed){if(typeof _==="function")_();return}let T=this,A=this.conn;if(this.closed=!0,this._parser.removeAllListeners("packet"),A.removeAllListeners("readable"),this._parser._queue=null,this._keepaliveTimer)this._keepaliveTimer.clear(),this._keepaliveInterval=-1,this._keepaliveTimer=null;if(this._connectTimer)clearTimeout(this._connectTimer),this._connectTimer=null;this._eos(),this._eos=X4,tY(this,{unsubscriptions:Object.keys(this.subscriptions)},E);function E(){let L=T.will;if(!T._disconnected&&L)T.broker.authorizePublish(T,L,function(J){if(J)return X();T.broker.publish(L,T,X);function X(){T.broker.persistence.delWill({id:T.id,brokerId:T.broker.id},X4)}});else if(L)T.broker.persistence.delWill({id:T.id,brokerId:T.broker.id},X4);if(T.will=null,T._will=null,T.connected=!1,T.connecting=!1,A.removeAllListeners("error"),A.on("error",X4),T.broker.clients[T.id]&&T._authorized)T.broker.unregisterClient(T);if(T.conn.emit("drain"),T.conn.removeAllListeners("drain"),A.destroy(),typeof _==="function")_()}};Z0.prototype.pause=function(){this._paused=!0};Z0.prototype.resume=function(){this._paused=!1,this._nextBatch()};function wP(_){let T=this.client;if(T._parsingBatch++,T.connackSent||T._parsingBatch===1)eY(T,_,T._nextBatch);else if(this._queue.length<T.broker.queueLimit)this._queue.push(_);else this.emit("error",Error("Client queue limit reached"))}function SP(){let _=this._parser._queue;if(_){for(let T=0,A=_.length;T<A;T++)eY(this,_[T],this._nextBatch);this._parser._queue=null}}Z0.prototype.emptyOutgoingQueue=function(_){let T=this,A=T.broker.persistence;function E(L,J,X){A.outgoingClearMessageId(T,L,X)}IP(A.outgoingStream(T),PP(E),_)};function X4(){}});var EK=W((Eg,yP)=>{yP.exports={name:"aedes",version:"0.51.3",description:"Stream-based MQTT broker",main:"aedes.js",types:"aedes.d.ts",scripts:{lint:"npm run lint:standard && npm run lint:typescript && npm run lint:markdown","lint:fix":"standard --fix && eslint -c types/.eslintrc.json --fix aedes.d.ts types/**/*.ts test/types/**/*.test-d.ts","lint:standard":"standard --verbose | snazzy","lint:typescript":"eslint -c types/.eslintrc.json aedes.d.ts types/**/*.ts test/types/**/*.test-d.ts","lint:markdown":"markdownlint docs/*.md README.md",test:"npm run lint && npm run unit && npm run test:typescript","test:ci":"npm run lint && npm run unit -- --cov --no-check-coverage --coverage-report=lcovonly && npm run test:typescript","test:report":"npm run lint && npm run unit:report && npm run test:typescript","test:typescript":"tsd",unit:"tap -J test/*.js","unit:report":"tap -J test/*.js --cov --coverage-report=html --coverage-report=cobertura | tee out.tap","license-checker":'license-checker --production --onlyAllow="MIT;ISC;BSD-3-Clause;BSD-2-Clause;0BSD"',release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it --disable-metrics"},"release-it":{github:{release:!0},git:{tagName:"v${version}"},hooks:{"before:init":["npm run test:ci"]},npm:{publish:!0}},"pre-commit":["test"],tsd:{directory:"test/types"},standard:{ignore:["types/*","test/types/*"]},repository:{type:"git",url:"git+https://github.com/moscajs/aedes.git"},keywords:["mqtt","broker","server","mqtt-server","stream","streams","publish","subscribe","pubsub","messaging","mosca","mosquitto","iot","internet","of","things"],author:"Matteo Collina <hello@matteocollina.com>",contributors:[{name:"Gavin D'mello",url:"https://github.com/GavinDmello"},{name:"Behrad Zari",url:"https://github.com/behrad"},{name:"Gnought",url:"https://github.com/gnought"},{name:"Daniel Lando",url:"https://github.com/robertsLando"}],license:"MIT",funding:{type:"opencollective",url:"https://opencollective.com/aedes"},bugs:{url:"https://github.com/moscajs/aedes/issues"},homepage:"https://github.com/moscajs/aedes#readme",engines:{node:">=16"},devDependencies:{"@sinonjs/fake-timers":"^11.2.2","@types/node":"^20.11.17","@typescript-eslint/eslint-plugin":"^7.0.1","@typescript-eslint/parser":"^7.0.1","concat-stream":"^2.0.0",duplexify:"^4.1.2","license-checker":"^25.0.1","markdownlint-cli":"^0.41.0",mqtt:"^5.3.5","mqtt-connection":"^4.1.0","pre-commit":"^1.2.2",proxyquire:"^2.1.3","release-it":"^17.0.5",snazzy:"^9.0.0",standard:"^17.1.0",tap:"^16.3.10",tsd:"^0.31.0",typescript:"^5.3.3","websocket-stream":"^5.5.2"},dependencies:{"aedes-packet":"^3.0.0","aedes-persistence":"^9.1.2","end-of-stream":"^1.4.4",fastfall:"^1.5.1",fastparallel:"^2.4.1",fastseries:"^2.0.0",hyperid:"^3.2.0",mqemitter:"^6.0.0","mqtt-packet":"^9.0.0",retimer:"^4.0.0",reusify:"^1.0.4",uuid:"^10.0.0"}}});var ZK=W((Lg,HK)=>{var vP=I("events"),hP=I("util"),kP=f5(),fP=S9(),{v4:bP}=k7(),gP=k8(),{pipeline:mP}=I("stream"),uP=uT(),dP=l7(),cP=t7(),pP=AK(),{$SYS_PREFIX:Y0,bulk:lP}=DT();HK.exports=Z1.createBroker=Z1;var nP={concurrency:100,heartbeatInterval:60000,connectTimeout:30000,decodeProtocol:null,preConnect:eP,authenticate:_j,authorizePublish:Tj,authorizeSubscribe:Aj,authorizeForward:Ej,published:Lj,trustProxy:!1,trustedProxies:[],queueLimit:42,maxClientsIdLength:23,keepaliveLimit:0};function Z1(_){let T=this;if(!(this instanceof Z1))return new Z1(_);_=Object.assign({},nP,_),this.id=_.id||bP(),this.counter=0,this.queueLimit=_.queueLimit,this.connectTimeout=_.connectTimeout,this.keepaliveLimit=_.keepaliveLimit,this.maxClientsIdLength=_.maxClientsIdLength,this.mq=_.mq||cP({concurrency:_.concurrency,matchEmptyLevels:!0}),this.handle=function(K,$){return K.setMaxListeners(_.concurrency*2),new pP(T,K,$)},this.persistence=_.persistence||dP(),this.persistence.broker=this,this._parallel=kP(),this._series=fP(),this._enqueuers=gP(aP),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),mP(T.persistence.streamWill(T.brokers),lP(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}hP.inherits(Z1,vP);function LK(_,T){if(_.retain)this.broker.persistence.storeRetained(_,T);else T()}function JK(_,T){if(this.client)_.clientId=this.client.id;this.broker.mq.emit(_,T)}function iP(_,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 aP(){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(oP);let{packet:J,complete:X}=_;_.packet=null,_.complete=null,_.topic=null,L.persistence.outgoingEnqueueCombi(E,J,X),L._enqueuers.release(_)}}function oP(_){let T=_.topic.charCodeAt(0);return T!==43&&T!==35}function XK(_,T){this.broker.published(this.packet,this.client,T),this.broker.emit("publish",this.packet,this.client)}var rP=[LK,JK,XK],sP=[LK,iP,JK,XK];Z1.prototype.publish=function(_,T,A){if(typeof T==="function")A=T,T=null;let E=new uP(_,this),L=E.qos>0?sP:rP;this._series(new Jj(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 tP(_,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,tP,Object.keys(this.clients),A);function A(){T.emit("closed"),T.mq.close(_)}};Z1.prototype.version=EK().version;function eP(_,T,A){A(null,!0)}function _j(_,T,A,E){E(null,!0)}function Tj(_,T,A){if(T.topic.startsWith(Y0))return A(Error(Y0+" topic is reserved"));A(null)}function Aj(_,T,A){A(null,T)}function Ej(_,T){return T}function Lj(_,T,A){A(null)}function Jj(_,T,A){this.broker=_,this.client=T,this.packet=A}function s4(){}});var GK=W((Ug,$K)=>{$K.exports=Hj;function H4(_){if(_ instanceof Buffer)return Buffer.from(_);return new _.constructor(_.buffer.slice(),_.byteOffset,_.length)}function Hj(_){if(_=_||{},_.circles)return Zj(_);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 Zj(_){let T=[],A=[],E=new Map;if(E.set(Date,(Z)=>new Date(Z)),E.set(Map,(Z,Y)=>new Map(J(Array.from(Z),Y))),E.set(Set,(Z,Y)=>new Set(J(Array.from(Z),Y))),_.constructorHandlers)for(let Z of _.constructorHandlers)E.set(Z[0],Z[1]);let L=null;return _.proto?H:X;function J(Z,Y){let K=Object.keys(Z),$=Array(K.length);for(let G=0;G<K.length;G++){let U=K[G],V=Z[U];if(typeof V!=="object"||V===null)$[U]=V;else if(V.constructor!==Object&&(L=E.get(V.constructor)))$[U]=L(V,Y);else if(ArrayBuffer.isView(V))$[U]=H4(V);else{let N=T.indexOf(V);if(N!==-1)$[U]=A[N];else $[U]=Y(V)}}return $}function X(Z){if(typeof Z!=="object"||Z===null)return Z;if(Array.isArray(Z))return J(Z,X);if(Z.constructor!==Object&&(L=E.get(Z.constructor)))return L(Z,X);let Y={};T.push(Z),A.push(Y);for(let K in Z){if(Object.hasOwnProperty.call(Z,K)===!1)continue;let $=Z[K];if(typeof $!=="object"||$===null)Y[K]=$;else if($.constructor!==Object&&(L=E.get($.constructor)))Y[K]=L($,X);else if(ArrayBuffer.isView($))Y[K]=H4($);else{let G=T.indexOf($);if(G!==-1)Y[K]=A[G];else Y[K]=X($)}}return T.pop(),A.pop(),Y}function H(Z){if(typeof Z!=="object"||Z===null)return Z;if(Array.isArray(Z))return J(Z,H);if(Z.constructor!==Object&&(L=E.get(Z.constructor)))return L(Z,H);let Y={};T.push(Z),A.push(Y);for(let K in Z){let $=Z[K];if(typeof $!=="object"||$===null)Y[K]=$;else if($.constructor!==Object&&(L=E.get($.constructor)))Y[K]=L($,H);else if(ArrayBuffer.isView($))Y[K]=H4($);else{let G=T.indexOf($);if(G!==-1)Y[K]=A[G];else Y[K]=H($)}}return T.pop(),A.pop(),Y}}});var WK=W((Wg,UK)=>{UK.exports=GK()()});var MK=W((QK)=>{Object.defineProperty(QK,"__esModule",{value:!0});QK.validateTopic=NK;QK.validateTopics=Yj;function NK(_){let T=_.split("/");for(let A=0;A<T.length;A++){if(T[A]==="+")continue;if(T[A]==="#")return A===T.length-1;if(T[A].indexOf("+")!==-1||T[A].indexOf("#")!==-1)return!1}return!0}function Yj(_){if(_.length===0)return"empty_topic_list";for(let T=0;T<_.length;T++)if(!NK(_[T]))return _[T];return null}});var pE=W((zK)=>{Object.defineProperty(zK,"__esModule",{value:!0});var Gj=n0(),Uj={objectMode:!0},Wj={clean:!0};class VK{options;_inflights;constructor(_){this.options=_||{},this.options={...Wj,..._},this._inflights=new Map}put(_,T){if(this._inflights.set(_.messageId,_),T)T();return this}createStream(){let _=new Gj.Readable(Uj),T=[],A=!1,E=0;return this._inflights.forEach((L,J)=>{T.push(L)}),_._read=()=>{if(!A&&E<T.length)_.push(T[E++]);else _.push(null)},_.destroy=(L)=>{if(A)return;return A=!0,setTimeout(()=>{_.emit("close")},0),_},_}del(_,T){let A=this._inflights.get(_.messageId);if(A)this._inflights.delete(_.messageId),T(null,A);else if(T)T(Error("missing packet"));return this}get(_,T){let A=this._inflights.get(_.messageId);if(A)T(null,A);else if(T)T(Error("missing packet"));return this}close(_){if(this.options.clean)this._inflights=null;if(_)_()}}zK.default=VK});var OK=W((CK)=>{Object.defineProperty(CK,"__esModule",{value:!0});var FK=[0,16,128,131,135,144,145,151,153],Qj=(_,T,A)=>{_.log("handlePublish: packet %o",T),A=typeof A<"u"?A:_.noop;let E=T.topic.toString(),L=T.payload,{qos:J}=T,{messageId:X}=T,{options:H}=_;if(_.options.protocolVersion===5){let Z;if(T.properties)Z=T.properties.topicAlias;if(typeof Z<"u")if(E.length===0)if(Z>0&&Z<=65535){let Y=_.topicAliasRecv.getTopicByAlias(Z);if(Y)E=Y,_.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",E,Z);else{_.log("handlePublish :: unregistered topic alias. alias: %d",Z),_.emit("error",Error("Received unregistered Topic Alias"));return}}else{_.log("handlePublish :: topic alias out of range. alias: %d",Z),_.emit("error",Error("Received Topic Alias is out of range"));return}else if(_.topicAliasRecv.put(E,Z))_.log("handlePublish :: registered topic: %s - alias: %d",E,Z);else{_.log("handlePublish :: topic alias out of range. alias: %d",Z),_.emit("error",Error("Received Topic Alias is out of range"));return}}switch(_.log("handlePublish: qos %d",J),J){case 2:{H.customHandleAcks(E,L,T,(Z,Y)=>{if(typeof Z==="number")Y=Z,Z=null;if(Z)return _.emit("error",Z);if(FK.indexOf(Y)===-1)return _.emit("error",Error("Wrong reason code for pubrec"));if(Y)_._sendPacket({cmd:"pubrec",messageId:X,reasonCode:Y},A);else _.incomingStore.put(T,()=>{_._sendPacket({cmd:"pubrec",messageId:X},A)})});break}case 1:{H.customHandleAcks(E,L,T,(Z,Y)=>{if(typeof Z==="number")Y=Z,Z=null;if(Z)return _.emit("error",Z);if(FK.indexOf(Y)===-1)return _.emit("error",Error("Wrong reason code for puback"));if(!Y)_.emit("message",E,L,T);_.handleMessage(T,(K)=>{if(K)return A&&A(K);_._sendPacket({cmd:"puback",messageId:X,reasonCode:Y},A)})});break}case 0:_.emit("message",E,L,T),_.handleMessage(T,A);break;default:_.log("handlePublish: unknown QoS. Doing nothing.");break}};CK.default=Qj});var RK=W((Vg,Vj)=>{Vj.exports={name:"mqtt",description:"A library for the MQTT protocol",version:"5.14.1",contributors:["Adam Rudd <adamvrr@gmail.com>","Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)","Siarhei Buntsevich <scarry0506@gmail.com> (https://github.com/scarry1992)","Yoseph Maguire <yomaguir@microsoft.com> (https://github.com/YoDaMa)","Daniel Lando <daniel.sorridi@gmail.com> (https://github.com/robertsLando)"],keywords:["mqtt","publish/subscribe","publish","subscribe"],license:"MIT",repository:{type:"git",url:"git://github.com/mqttjs/MQTT.js.git"},main:"./build/index.js",module:"./dist/mqtt.esm.js",bin:{mqtt_pub:"./build/bin/pub.js",mqtt_sub:"./build/bin/sub.js",mqtt:"./build/bin/mqtt.js"},files:["dist/","CONTRIBUTING.md","LICENSE.md","help/","build/"],exports:{".":{"react-native":"./dist/mqtt.esm.js",browser:{import:"./dist/mqtt.esm.js",default:"./dist/mqtt.min.js"},default:"./build/index.js"},"./package.json":"./package.json","./*.map":"./build/*.js.map","./dist/*":"./dist/*.js","./*":"./build/*.js"},types:"build/index.d.ts",typesVersions:{"*":{"*":["./build/index.d.ts"]}},scripts:{lint:"eslint --ext .ts .","lint-fix":"eslint --fix --ext .ts .","build:ts":"rimraf build/ && tsc -p tsconfig.build.json","build:browser":"node esbuild.js",build:"npm run build:ts && npm run build:browser",prepare:"npm run build","unit-test:node":"node -r esbuild-register --test-concurrency 4 --test-reporter=junit --test-reporter-destination=junit.xml --test-reporter=spec --test-reporter-destination=stdout --test test/node/*.ts ","unit-test:browser":"wtr","test:node":"node_modules/.bin/nyc npm run unit-test:node","test:browser":"npm run build && npm run unit-test:browser",test:"npm run test:node",changelog:"conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md","changelog-init":"conventional-changelog -p angular -i CHANGELOG.md -s -r 0",release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it"},"release-it":{github:{release:!0},git:{tagName:"v${version}",commitMessage:"chore(release): ${version}"},hooks:{"before:init":["npm run test"]},npm:{publish:!0},plugins:{"@release-it/conventional-changelog":{preset:"angular",infile:"CHANGELOG.md"}}},publishConfig:{provenance:!0},"pre-commit":["lint"],engines:{node:">=16.0.0"},browser:{"./mqtt.js":"./dist/mqtt.js",fs:!1,tls:!1,net:!1},dependencies:{"@types/readable-stream":"^4.0.21","@types/ws":"^8.18.1",commist:"^3.2.0","concat-stream":"^2.0.0",debug:"^4.4.1","help-me":"^5.0.0","lru-cache":"^10.4.3",minimist:"^1.2.8","mqtt-packet":"^9.0.2","number-allocator":"^1.0.14","readable-stream":"^4.7.0",rfdc:"^1.4.1",socks:"^2.8.6",split2:"^4.2.0","worker-timers":"^8.0.23",ws:"^8.18.3"},devDependencies:{"@eslint/eslintrc":"^3.3.1","@eslint/js":"^9.32.0","@esm-bundle/chai":"^4.3.4","@release-it/conventional-changelog":"^10.0.1","@tsconfig/node20":"^20.1.6","@types/chai":"^5.2.2","@types/node":"^20.17.16","@types/sinon":"^17.0.4","@types/tape":"^5.8.1","@typescript-eslint/eslint-plugin":"^8.38.0","@typescript-eslint/parser":"^8.38.0","@web/test-runner":"^0.20.2","@web/test-runner-playwright":"^0.11.1","aedes-cli":"^0.8.0",chai:"^5.2.1",chokidar:"^4.0.3","conventional-changelog-cli":"^5.0.0","end-of-stream":"^1.4.5",esbuild:"^0.25.8","esbuild-plugin-polyfill-node":"^0.3.0","esbuild-register":"^3.6.0",eslint:"^9.32.0","eslint-config-prettier":"^10.1.8","eslint-plugin-import":"^2.32.0","eslint-plugin-prettier":"^5.5.3",global:"^4.4.0",globals:"^16.3.0","leaked-handles":"^5.2.0",mkdirp:"^3.0.1","mqtt-connection":"^4.1.0","mqtt-level-store":"^3.1.0",nyc:"^17.1.0","pre-commit":"^1.2.2",prettier:"^3.6.2","release-it":"^19.0.4",rimraf:"^6.0.1",should:"^13.2.3",sinon:"^17.0.2",snazzy:"^9.0.0",tape:"^5.9.0","ts-node":"^10.9.2",typescript:"^5.8.3"}}});var qT=W((DK)=>{Object.defineProperty(DK,"__esModule",{value:!0});DK.MQTTJS_VERSION=DK.nextTick=DK.ErrorWithSubackPacket=DK.ErrorWithReasonCode=void 0;DK.applyMixin=zj;class lE extends Error{code;constructor(_,T){super(_);this.code=T,Object.setPrototypeOf(this,lE.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}DK.ErrorWithReasonCode=lE;class nE extends Error{packet;constructor(_,T){super(_);this.packet=T,Object.setPrototypeOf(this,nE.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}DK.ErrorWithSubackPacket=nE;function zj(_,T,A=!1){let E=[T];while(!0){let L=E[0],J=Object.getPrototypeOf(L);if(J?.prototype)E.unshift(J);else break}for(let L of E)for(let J of Object.getOwnPropertyNames(L.prototype))if(A||J!=="constructor")Object.defineProperty(_.prototype,J,Object.getOwnPropertyDescriptor(L.prototype,J)??Object.create(null))}DK.nextTick=typeof process?.nextTick==="function"?process.nextTick:(_)=>{setTimeout(_,0)};DK.MQTTJS_VERSION=RK().version});var e4=W((IK)=>{Object.defineProperty(IK,"__esModule",{value:!0});IK.ReasonCodes=void 0;var qK=qT();IK.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var Dj=(_,T)=>{let{messageId:A}=T,E=T.cmd,L=null,J=_.outgoing[A]?_.outgoing[A].cb:null,X=null;if(!J){_.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(_.log("_handleAck :: packet type",E),E){case"pubcomp":case"puback":{let H=T.reasonCode;if(H&&H>0&&H!==16)X=new qK.ErrorWithReasonCode(`Publish error: ${IK.ReasonCodes[H]}`,H),_._removeOutgoingAndStoreMessage(A,()=>{J(X,T)});else _._removeOutgoingAndStoreMessage(A,J);break}case"pubrec":{L={cmd:"pubrel",qos:2,messageId:A};let H=T.reasonCode;if(H&&H>0&&H!==16)X=new qK.ErrorWithReasonCode(`Publish error: ${IK.ReasonCodes[H]}`,H),_._removeOutgoingAndStoreMessage(A,()=>{J(X,T)});else _._sendPacket(L);break}case"suback":{delete _.outgoing[A],_.messageIdProvider.deallocate(A);let H=T.granted;for(let Z=0;Z<H.length;Z++){let Y=H[Z];if((Y&128)!==0){X=Error(`Subscribe error: ${IK.ReasonCodes[Y]}`),X.code=Y;let K=_.messageIdToTopic[A];if(K)K.forEach(($)=>{delete _._resubscribeTopics[$]})}}delete _.messageIdToTopic[A],_._invokeStoreProcessingQueue(),J(X,T);break}case"unsuback":{delete _.outgoing[A],_.messageIdProvider.deallocate(A),_._invokeStoreProcessingQueue(),J(null,T);break}default:_.emit("error",Error("unrecognized packet type"))}if(_.disconnecting&&Object.keys(_.outgoing).length===0)_.emit("outgoingEmpty")};IK.default=Dj});var xK=W((jK)=>{Object.defineProperty(jK,"__esModule",{value:!0});var PK=qT(),qj=e4(),Ij=(_,T)=>{let{options:A}=_,E=A.protocolVersion,L=E===5?T.reasonCode:T.returnCode;if(E!==5){let J=new PK.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${E}`,L);_.emit("error",J);return}_.handleAuth(T,(J,X)=>{if(J){_.emit("error",J);return}if(L===24)_.reconnecting=!1,_._sendPacket(X);else{let H=new PK.ErrorWithReasonCode(`Connection refused: ${qj.ReasonCodes[L]}`,L);_.emit("error",H)}})};jK.default=Ij});var fK=W((hK)=>{Object.defineProperty(hK,"__esModule",{value:!0});hK.LRUCache=void 0;var Z4=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,SK=new Set,iE=typeof process==="object"&&!!process?process:{},yK=(_,T,A,E)=>{typeof iE.emitWarning==="function"?iE.emitWarning(_,T,A,E):console.error(`[${A}] ${T}: ${_}`)},uA=globalThis.AbortController,wK=globalThis.AbortSignal;if(typeof uA>"u"){wK=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(E,L){this._onabort.push(L)}},uA=class{constructor(){T()}signal=new wK;abort(E){if(this.signal.aborted)return;this.signal.reason=E,this.signal.aborted=!0;for(let L of this.signal._onabort)L(E);this.signal.onabort?.(E)}};let _=iE.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",T=()=>{if(!_)return;_=!1,yK("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",T)}}var jj=(_)=>!SK.has(_),Og=Symbol("type"),s0=(_)=>_&&_===Math.floor(_)&&_>0&&isFinite(_),vK=(_)=>!s0(_)?null:_<=Math.pow(2,8)?Uint8Array:_<=Math.pow(2,16)?Uint16Array:_<=Math.pow(2,32)?Uint32Array:_<=Number.MAX_SAFE_INTEGER?_8:null;class _8 extends Array{constructor(_){super(_);this.fill(0)}}class Y4{heap;length;static#J=!1;static create(_){let T=vK(_);if(!T)return[];Y4.#J=!0;let A=new Y4(_,T);return Y4.#J=!1,A}constructor(_,T){if(!Y4.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new T(_),this.length=0}push(_){this.heap[this.length++]=_}pop(){return this.heap[--this.length]}}class aE{#J;#L;#Y;#K;#N;#z;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#A;#W;#X;#E;#_;#G;#Q;#$;#H;#F;#Z;#C;#O;#M;#R;#P;#U;static unsafeExposeInternals(_){return{starts:_.#O,ttls:_.#M,sizes:_.#C,keyMap:_.#X,keyList:_.#E,valList:_.#_,next:_.#G,prev:_.#Q,get head(){return _.#$},get tail(){return _.#H},free:_.#F,isBackgroundFetch:(T)=>_.#T(T),backgroundFetch:(T,A,E,L)=>_.#v(T,A,E,L),moveToTail:(T)=>_.#w(T),indexes:(T)=>_.#D(T),rindexes:(T)=>_.#B(T),isStale:(T)=>_.#V(T)}}get max(){return this.#J}get maxSize(){return this.#L}get calculatedSize(){return this.#W}get size(){return this.#A}get fetchMethod(){return this.#N}get memoMethod(){return this.#z}get dispose(){return this.#Y}get disposeAfter(){return this.#K}constructor(_){let{max:T=0,ttl:A,ttlResolution:E=1,ttlAutopurge:L,updateAgeOnGet:J,updateAgeOnHas:X,allowStale:H,dispose:Z,disposeAfter:Y,noDisposeOnSet:K,noUpdateTTL:$,maxSize:G=0,maxEntrySize:U=0,sizeCalculation:V,fetchMethod:N,memoMethod:z,noDeleteOnFetchRejection:Q,noDeleteOnStaleGet:F,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:q,ignoreFetchAbort:f}=_;if(T!==0&&!s0(T))throw TypeError("max option must be a nonnegative integer");let h=T?vK(T):Array;if(!h)throw Error("invalid max value: "+T);if(this.#J=T,this.#L=G,this.maxEntrySize=U||this.#L,this.sizeCalculation=V,this.sizeCalculation){if(!this.#L&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(z!==void 0&&typeof z!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#z=z,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#N=N,this.#P=!!N,this.#X=new Map,this.#E=Array(T).fill(void 0),this.#_=Array(T).fill(void 0),this.#G=new h(T),this.#Q=new h(T),this.#$=0,this.#H=0,this.#F=Y4.create(T),this.#A=0,this.#W=0,typeof Z==="function")this.#Y=Z;if(typeof Y==="function")this.#K=Y,this.#Z=[];else this.#K=void 0,this.#Z=void 0;if(this.#R=!!this.#Y,this.#U=!!this.#K,this.noDisposeOnSet=!!K,this.noUpdateTTL=!!$,this.noDeleteOnFetchRejection=!!Q,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!q,this.ignoreFetchAbort=!!f,this.maxEntrySize!==0){if(this.#L!==0){if(!s0(this.#L))throw TypeError("maxSize must be a positive integer if specified")}if(!s0(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#u()}if(this.allowStale=!!H,this.noDeleteOnStaleGet=!!F,this.updateAgeOnGet=!!J,this.updateAgeOnHas=!!X,this.ttlResolution=s0(E)||E===0?E:1,this.ttlAutopurge=!!L,this.ttl=A||0,this.ttl){if(!s0(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#h()}if(this.#J===0&&this.ttl===0&&this.#L===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#L){if(jj("LRU_CACHE_UNBOUNDED"))SK.add("LRU_CACHE_UNBOUNDED"),yK("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",aE)}}getRemainingTTL(_){return this.#X.has(_)?1/0:0}#h(){let _=new _8(this.#J),T=new _8(this.#J);this.#M=_,this.#O=T,this.#k=(L,J,X=Z4.now())=>{if(T[L]=J!==0?X:0,_[L]=J,J!==0&&this.ttlAutopurge){let H=setTimeout(()=>{if(this.#V(L))this.#q(this.#E[L],"expire")},J+1);if(H.unref)H.unref()}},this.#j=(L)=>{T[L]=_[L]!==0?Z4.now():0},this.#I=(L,J)=>{if(_[J]){let X=_[J],H=T[J];if(!X||!H)return;L.ttl=X,L.start=H,L.now=A||E();let Z=L.now-H;L.remainingTTL=X-Z}};let A=0,E=()=>{let L=Z4.now();if(this.ttlResolution>0){A=L;let J=setTimeout(()=>A=0,this.ttlResolution);if(J.unref)J.unref()}return L};this.getRemainingTTL=(L)=>{let J=this.#X.get(L);if(J===void 0)return 0;let X=_[J],H=T[J];if(!X||!H)return 1/0;let Z=(A||E())-H;return X-Z},this.#V=(L)=>{let J=T[L],X=_[L];return!!X&&!!J&&(A||E())-J>X}}#j=()=>{};#I=()=>{};#k=()=>{};#V=()=>!1;#u(){let _=new _8(this.#J);this.#W=0,this.#C=_,this.#x=(T)=>{this.#W-=_[T],_[T]=0},this.#f=(T,A,E,L)=>{if(this.#T(A))return 0;if(!s0(E))if(L){if(typeof L!=="function")throw TypeError("sizeCalculation must be a function");if(E=L(A,T),!s0(E))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return E},this.#S=(T,A,E)=>{if(_[T]=A,this.#L){let L=this.#L-_[T];while(this.#W>L)this.#y(!0)}if(this.#W+=_[T],E)E.entrySize=A,E.totalCalculatedSize=this.#W}}#x=(_)=>{};#S=(_,T,A)=>{};#f=(_,T,A,E)=>{if(A||E)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#D({allowStale:_=this.allowStale}={}){if(this.#A)for(let T=this.#H;;){if(!this.#b(T))break;if(_||!this.#V(T))yield T;if(T===this.#$)break;else T=this.#Q[T]}}*#B({allowStale:_=this.allowStale}={}){if(this.#A)for(let T=this.#$;;){if(!this.#b(T))break;if(_||!this.#V(T))yield T;if(T===this.#H)break;else T=this.#G[T]}}#b(_){return _!==void 0&&this.#X.get(this.#E[_])===_}*entries(){for(let _ of this.#D())if(this.#_[_]!==void 0&&this.#E[_]!==void 0&&!this.#T(this.#_[_]))yield[this.#E[_],this.#_[_]]}*rentries(){for(let _ of this.#B())if(this.#_[_]!==void 0&&this.#E[_]!==void 0&&!this.#T(this.#_[_]))yield[this.#E[_],this.#_[_]]}*keys(){for(let _ of this.#D()){let T=this.#E[_];if(T!==void 0&&!this.#T(this.#_[_]))yield T}}*rkeys(){for(let _ of this.#B()){let T=this.#E[_];if(T!==void 0&&!this.#T(this.#_[_]))yield T}}*values(){for(let _ of this.#D())if(this.#_[_]!==void 0&&!this.#T(this.#_[_]))yield this.#_[_]}*rvalues(){for(let _ of this.#B())if(this.#_[_]!==void 0&&!this.#T(this.#_[_]))yield this.#_[_]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(_,T={}){for(let A of this.#D()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;if(_(L,this.#E[A],this))return this.get(this.#E[A],T)}}forEach(_,T=this){for(let A of this.#D()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;_.call(T,L,this.#E[A],this)}}rforEach(_,T=this){for(let A of this.#B()){let E=this.#_[A],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0)continue;_.call(T,L,this.#E[A],this)}}purgeStale(){let _=!1;for(let T of this.#B({allowStale:!0}))if(this.#V(T))this.#q(this.#E[T],"expire"),_=!0;return _}info(_){let T=this.#X.get(_);if(T===void 0)return;let A=this.#_[T],E=this.#T(A)?A.__staleWhileFetching:A;if(E===void 0)return;let L={value:E};if(this.#M&&this.#O){let J=this.#M[T],X=this.#O[T];if(J&&X){let H=J-(Z4.now()-X);L.ttl=H,L.start=Date.now()}}if(this.#C)L.size=this.#C[T];return L}dump(){let _=[];for(let T of this.#D({allowStale:!0})){let A=this.#E[T],E=this.#_[T],L=this.#T(E)?E.__staleWhileFetching:E;if(L===void 0||A===void 0)continue;let J={value:L};if(this.#M&&this.#O){J.ttl=this.#M[T];let X=Z4.now()-this.#O[T];J.start=Math.floor(Date.now()-X)}if(this.#C)J.size=this.#C[T];_.unshift([A,J])}return _}load(_){this.clear();for(let[T,A]of _){if(A.start){let E=Date.now()-A.start;A.start=Z4.now()-E}this.set(T,A.value,A)}}set(_,T,A={}){if(T===void 0)return this.delete(_),this;let{ttl:E=this.ttl,start:L,noDisposeOnSet:J=this.noDisposeOnSet,sizeCalculation:X=this.sizeCalculation,status:H}=A,{noUpdateTTL:Z=this.noUpdateTTL}=A,Y=this.#f(_,T,A.size||0,X);if(this.maxEntrySize&&Y>this.maxEntrySize){if(H)H.set="miss",H.maxEntrySizeExceeded=!0;return this.#q(_,"set"),this}let K=this.#A===0?void 0:this.#X.get(_);if(K===void 0){if(K=this.#A===0?this.#H:this.#F.length!==0?this.#F.pop():this.#A===this.#J?this.#y(!1):this.#A,this.#E[K]=_,this.#_[K]=T,this.#X.set(_,K),this.#G[this.#H]=K,this.#Q[K]=this.#H,this.#H=K,this.#A++,this.#S(K,Y,H),H)H.set="add";Z=!1}else{this.#w(K);let $=this.#_[K];if(T!==$){if(this.#P&&this.#T($)){$.__abortController.abort(Error("replaced"));let{__staleWhileFetching:G}=$;if(G!==void 0&&!J){if(this.#R)this.#Y?.(G,_,"set");if(this.#U)this.#Z?.push([G,_,"set"])}}else if(!J){if(this.#R)this.#Y?.($,_,"set");if(this.#U)this.#Z?.push([$,_,"set"])}if(this.#x(K),this.#S(K,Y,H),this.#_[K]=T,H){H.set="replace";let G=$&&this.#T($)?$.__staleWhileFetching:$;if(G!==void 0)H.oldValue=G}}else if(H)H.set="update"}if(E!==0&&!this.#M)this.#h();if(this.#M){if(!Z)this.#k(K,E,L);if(H)this.#I(H,K)}if(!J&&this.#U&&this.#Z){let $=this.#Z,G;while(G=$?.shift())this.#K?.(...G)}return this}pop(){try{while(this.#A){let _=this.#_[this.#$];if(this.#y(!0),this.#T(_)){if(_.__staleWhileFetching)return _.__staleWhileFetching}else if(_!==void 0)return _}}finally{if(this.#U&&this.#Z){let _=this.#Z,T;while(T=_?.shift())this.#K?.(...T)}}}#y(_){let T=this.#$,A=this.#E[T],E=this.#_[T];if(this.#P&&this.#T(E))E.__abortController.abort(Error("evicted"));else if(this.#R||this.#U){if(this.#R)this.#Y?.(E,A,"evict");if(this.#U)this.#Z?.push([E,A,"evict"])}if(this.#x(T),_)this.#E[T]=void 0,this.#_[T]=void 0,this.#F.push(T);if(this.#A===1)this.#$=this.#H=0,this.#F.length=0;else this.#$=this.#G[T];return this.#X.delete(A),this.#A--,T}has(_,T={}){let{updateAgeOnHas:A=this.updateAgeOnHas,status:E}=T,L=this.#X.get(_);if(L!==void 0){let J=this.#_[L];if(this.#T(J)&&J.__staleWhileFetching===void 0)return!1;if(!this.#V(L)){if(A)this.#j(L);if(E)E.has="hit",this.#I(E,L);return!0}else if(E)E.has="stale",this.#I(E,L)}else if(E)E.has="miss";return!1}peek(_,T={}){let{allowStale:A=this.allowStale}=T,E=this.#X.get(_);if(E===void 0||!A&&this.#V(E))return;let L=this.#_[E];return this.#T(L)?L.__staleWhileFetching:L}#v(_,T,A,E){let L=T===void 0?void 0:this.#_[T];if(this.#T(L))return L;let J=new uA,{signal:X}=A;X?.addEventListener("abort",()=>J.abort(X.reason),{signal:J.signal});let H={signal:J.signal,options:A,context:E},Z=(V,N=!1)=>{let{aborted:z}=J.signal,Q=A.ignoreFetchAbort&&V!==void 0;if(A.status)if(z&&!N){if(A.status.fetchAborted=!0,A.status.fetchError=J.signal.reason,Q)A.status.fetchAbortIgnored=!0}else A.status.fetchResolved=!0;if(z&&!Q&&!N)return K(J.signal.reason);let F=G;if(this.#_[T]===G)if(V===void 0)if(F.__staleWhileFetching)this.#_[T]=F.__staleWhileFetching;else this.#q(_,"fetch");else{if(A.status)A.status.fetchUpdated=!0;this.set(_,V,H.options)}return V},Y=(V)=>{if(A.status)A.status.fetchRejected=!0,A.status.fetchError=V;return K(V)},K=(V)=>{let{aborted:N}=J.signal,z=N&&A.allowStaleOnFetchAbort,Q=z||A.allowStaleOnFetchRejection,F=Q||A.noDeleteOnFetchRejection,R=G;if(this.#_[T]===G){if(!F||R.__staleWhileFetching===void 0)this.#q(_,"fetch");else if(!z)this.#_[T]=R.__staleWhileFetching}if(Q){if(A.status&&R.__staleWhileFetching!==void 0)A.status.returnedStale=!0;return R.__staleWhileFetching}else if(R.__returned===R)throw V},$=(V,N)=>{let z=this.#N?.(_,L,H);if(z&&z instanceof Promise)z.then((Q)=>V(Q===void 0?void 0:Q),N);J.signal.addEventListener("abort",()=>{if(!A.ignoreFetchAbort||A.allowStaleOnFetchAbort){if(V(void 0),A.allowStaleOnFetchAbort)V=(Q)=>Z(Q,!0)}})};if(A.status)A.status.fetchDispatched=!0;let G=new Promise($).then(Z,Y),U=Object.assign(G,{__abortController:J,__staleWhileFetching:L,__returned:void 0});if(T===void 0)this.set(_,U,{...H.options,status:void 0}),T=this.#X.get(_);else this.#_[T]=U;return U}#T(_){if(!this.#P)return!1;let T=_;return!!T&&T instanceof Promise&&T.hasOwnProperty("__staleWhileFetching")&&T.__abortController instanceof uA}async fetch(_,T={}){let{allowStale:A=this.allowStale,updateAgeOnGet:E=this.updateAgeOnGet,noDeleteOnStaleGet:L=this.noDeleteOnStaleGet,ttl:J=this.ttl,noDisposeOnSet:X=this.noDisposeOnSet,size:H=0,sizeCalculation:Z=this.sizeCalculation,noUpdateTTL:Y=this.noUpdateTTL,noDeleteOnFetchRejection:K=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:$=this.allowStaleOnFetchRejection,ignoreFetchAbort:G=this.ignoreFetchAbort,allowStaleOnFetchAbort:U=this.allowStaleOnFetchAbort,context:V,forceRefresh:N=!1,status:z,signal:Q}=T;if(!this.#P){if(z)z.fetch="get";return this.get(_,{allowStale:A,updateAgeOnGet:E,noDeleteOnStaleGet:L,status:z})}let F={allowStale:A,updateAgeOnGet:E,noDeleteOnStaleGet:L,ttl:J,noDisposeOnSet:X,size:H,sizeCalculation:Z,noUpdateTTL:Y,noDeleteOnFetchRejection:K,allowStaleOnFetchRejection:$,allowStaleOnFetchAbort:U,ignoreFetchAbort:G,status:z,signal:Q},R=this.#X.get(_);if(R===void 0){if(z)z.fetch="miss";let q=this.#v(_,R,F,V);return q.__returned=q}else{let q=this.#_[R];if(this.#T(q)){let c=A&&q.__staleWhileFetching!==void 0;if(z){if(z.fetch="inflight",c)z.returnedStale=!0}return c?q.__staleWhileFetching:q.__returned=q}let f=this.#V(R);if(!N&&!f){if(z)z.fetch="hit";if(this.#w(R),E)this.#j(R);if(z)this.#I(z,R);return q}let h=this.#v(_,R,F,V),l=h.__staleWhileFetching!==void 0&&A;if(z){if(z.fetch=f?"stale":"refresh",l&&f)z.returnedStale=!0}return l?h.__staleWhileFetching:h.__returned=h}}async forceFetch(_,T={}){let A=await this.fetch(_,T);if(A===void 0)throw Error("fetch() returned undefined");return A}memo(_,T={}){let A=this.#z;if(!A)throw Error("no memoMethod provided to constructor");let{context:E,forceRefresh:L,...J}=T,X=this.get(_,J);if(!L&&X!==void 0)return X;let H=A(_,X,{options:J,context:E});return this.set(_,H,J),H}get(_,T={}){let{allowStale:A=this.allowStale,updateAgeOnGet:E=this.updateAgeOnGet,noDeleteOnStaleGet:L=this.noDeleteOnStaleGet,status:J}=T,X=this.#X.get(_);if(X!==void 0){let H=this.#_[X],Z=this.#T(H);if(J)this.#I(J,X);if(this.#V(X)){if(J)J.get="stale";if(!Z){if(!L)this.#q(_,"expire");if(J&&A)J.returnedStale=!0;return A?H:void 0}else{if(J&&A&&H.__staleWhileFetching!==void 0)J.returnedStale=!0;return A?H.__staleWhileFetching:void 0}}else{if(J)J.get="hit";if(Z)return H.__staleWhileFetching;if(this.#w(X),E)this.#j(X);return H}}else if(J)J.get="miss"}#g(_,T){this.#Q[T]=_,this.#G[_]=T}#w(_){if(_!==this.#H){if(_===this.#$)this.#$=this.#G[_];else this.#g(this.#Q[_],this.#G[_]);this.#g(this.#H,_),this.#H=_}}delete(_){return this.#q(_,"delete")}#q(_,T){let A=!1;if(this.#A!==0){let E=this.#X.get(_);if(E!==void 0)if(A=!0,this.#A===1)this.#m(T);else{this.#x(E);let L=this.#_[E];if(this.#T(L))L.__abortController.abort(Error("deleted"));else if(this.#R||this.#U){if(this.#R)this.#Y?.(L,_,T);if(this.#U)this.#Z?.push([L,_,T])}if(this.#X.delete(_),this.#E[E]=void 0,this.#_[E]=void 0,E===this.#H)this.#H=this.#Q[E];else if(E===this.#$)this.#$=this.#G[E];else{let J=this.#Q[E];this.#G[J]=this.#G[E];let X=this.#G[E];this.#Q[X]=this.#Q[E]}this.#A--,this.#F.push(E)}}if(this.#U&&this.#Z?.length){let E=this.#Z,L;while(L=E?.shift())this.#K?.(...L)}return A}clear(){return this.#m("delete")}#m(_){for(let T of this.#B({allowStale:!0})){let A=this.#_[T];if(this.#T(A))A.__abortController.abort(Error("deleted"));else{let E=this.#E[T];if(this.#R)this.#Y?.(A,E,_);if(this.#U)this.#Z?.push([A,E,_])}}if(this.#X.clear(),this.#_.fill(void 0),this.#E.fill(void 0),this.#M&&this.#O)this.#M.fill(0),this.#O.fill(0);if(this.#C)this.#C.fill(0);if(this.#$=0,this.#H=0,this.#F.length=0,this.#W=0,this.#A=0,this.#U&&this.#Z){let T=this.#Z,A;while(A=T?.shift())this.#K?.(...A)}}}hK.LRUCache=aE});var K0=W((mK)=>{Object.defineProperty(mK,"t",{value:!0});mK.ContainerIterator=mK.Container=mK.Base=void 0;class bK{constructor(_=0){this.iteratorType=_}equals(_){return this.o===_.o}}mK.ContainerIterator=bK;class oE{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}}mK.Base=oE;class gK extends oE{}mK.Container=gK});var lK=W((cK)=>{Object.defineProperty(cK,"t",{value:!0});cK.default=void 0;var Sj=K0();class dK extends Sj.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 yj=dK;cK.default=yj});var oK=W((iK)=>{Object.defineProperty(iK,"t",{value:!0});iK.default=void 0;var vj=K0();class nK extends vj.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 hj=nK;iK.default=hj});var eK=W((sK)=>{Object.defineProperty(sK,"t",{value:!0});sK.default=void 0;var kj=K0();class rK extends kj.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 fj=rK;sK.default=fj});var dA=W((T3)=>{Object.defineProperty(T3,"t",{value:!0});T3.default=void 0;var bj=K0();class _3 extends bj.Container{}var gj=_3;T3.default=gj});var $0=W((E3)=>{Object.defineProperty(E3,"t",{value:!0});E3.throwIteratorAccessError=mj;function mj(){throw RangeError("Iterator access denied!")}});var rE=W((J3)=>{Object.defineProperty(J3,"t",{value:!0});J3.RandomIterator=void 0;var dj=K0(),cA=$0();class L3 extends dj.ContainerIterator{constructor(_,T){super(T);if(this.o=_,this.iteratorType===0)this.pre=function(){if(this.o===0)(0,cA.throwIteratorAccessError)();return this.o-=1,this},this.next=function(){if(this.o===this.container.size())(0,cA.throwIteratorAccessError)();return this.o+=1,this};else this.pre=function(){if(this.o===this.container.size()-1)(0,cA.throwIteratorAccessError)();return this.o+=1,this},this.next=function(){if(this.o===-1)(0,cA.throwIteratorAccessError)();return this.o-=1,this}}get pointer(){return this.container.getElementByPos(this.o)}set pointer(_){this.container.setElementByPos(this.o,_)}}J3.RandomIterator=L3});var K3=W((Z3)=>{Object.defineProperty(Z3,"t",{value:!0});Z3.default=void 0;var cj=lj(dA()),pj=rE();function lj(_){return _&&_.t?_:{default:_}}class IT extends pj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new IT(this.o,this.container,this.iteratorType)}}class H3 extends cj.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 nj=H3;Z3.default=nj});var W3=W((G3)=>{Object.defineProperty(G3,"t",{value:!0});G3.default=void 0;var ij=oj(dA()),aj=K0(),PT=$0();function oj(_){return _&&_.t?_:{default:_}}class jT extends aj.ContainerIterator{constructor(_,T,A,E){super(E);if(this.o=_,this.h=T,this.container=A,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,PT.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,PT.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,PT.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,PT.throwIteratorAccessError)();return this.o=this.o.L,this}}get pointer(){if(this.o===this.h)(0,PT.throwIteratorAccessError)();return this.o.l}set pointer(_){if(this.o===this.h)(0,PT.throwIteratorAccessError)();this.o.l=_}copy(){return new jT(this.o,this.h,this.container,this.iteratorType)}}class $3 extends ij.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 rj=$3;G3.default=rj});var V3=W((Q3)=>{Object.defineProperty(Q3,"t",{value:!0});Q3.default=void 0;var sj=ej(dA()),tj=rE();function ej(_){return _&&_.t?_:{default:_}}class xT extends tj.RandomIterator{constructor(_,T,A){super(_,A);this.container=T}copy(){return new xT(this.o,this.container,this.iteratorType)}}class N3 extends sj.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 _x=N3;Q3.default=_x});var O3=W((F3)=>{Object.defineProperty(F3,"t",{value:!0});F3.TreeNodeEnableIndex=F3.TreeNode=void 0;class sE{constructor(_,T){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=_,this.l=T}L(){let _=this;if(_.ee===1&&_.tt.tt===_)_=_.W;else if(_.U){_=_.U;while(_.W)_=_.W}else{let T=_.tt;while(T.U===_)_=T,T=_.tt;_=T}return _}B(){let _=this;if(_.W){_=_.W;while(_.U)_=_.U;return _}else{let T=_.tt;while(T.W===_)_=T,T=_.tt;if(_.W!==T)return T;else return _}}te(){let _=this.tt,T=this.W,A=T.U;if(_.tt===this)_.tt=T;else if(_.U===this)_.U=T;else _.W=T;if(T.tt=_,T.U=this,this.tt=T,this.W=A,A)A.tt=this;return T}se(){let _=this.tt,T=this.U,A=T.W;if(_.tt===this)_.tt=T;else if(_.U===this)_.U=T;else _.W=T;if(T.tt=_,T.W=this,this.tt=T,this.U=A,A)A.tt=this;return T}}F3.TreeNode=sE;class z3 extends sE{constructor(){super(...arguments);this.rt=1}te(){let _=super.te();return this.ie(),_.ie(),_}se(){let _=super.se();return this.ie(),_.ie(),_}ie(){if(this.rt=1,this.U)this.rt+=this.U.rt;if(this.W)this.rt+=this.W.rt}}F3.TreeNodeEnableIndex=z3});var tE=W((q3)=>{Object.defineProperty(q3,"t",{value:!0});q3.default=void 0;var R3=O3(),Ax=K0(),D3=$0();class B3 extends Ax.Container{constructor(_=function(A,E){if(A<E)return-1;if(A>E)return 1;return 0},T=!1){super();if(this.Y=void 0,this.v=_,T)this.re=R3.TreeNodeEnableIndex,this.M=function(A,E,L){let J=this.ne(A,E,L);if(J){let X=J.tt;while(X!==this.h)X.rt+=1,X=X.tt;let H=this.he(J);if(H){let{parentNode:Z,grandParent:Y,curNode:K}=H;Z.ie(),Y.ie(),K.ie()}}return this.i},this.V=function(A){let E=this.fe(A);while(E!==this.h)E.rt-=1,E=E.tt};else this.re=R3.TreeNode,this.M=function(A,E,L){let J=this.ne(A,E,L);if(J)this.he(J);return this.i},this.V=this.fe;this.h=new this.re}X(_,T){let A=this.h;while(_){let E=this.v(_.u,T);if(E<0)_=_.W;else if(E>0)A=_,_=_.U;else return _}return A}Z(_,T){let A=this.h;while(_)if(this.v(_.u,T)<=0)_=_.W;else A=_,_=_.U;return A}$(_,T){let A=this.h;while(_){let E=this.v(_.u,T);if(E<0)A=_,_=_.W;else if(E>0)_=_.U;else return _}return A}rr(_,T){let A=this.h;while(_)if(this.v(_.u,T)<0)A=_,_=_.W;else _=_.U;return A}ue(_){while(!0){let T=_.tt;if(T===this.h)return;if(_.ee===1){_.ee=0;return}if(_===T.U){let A=T.W;if(A.ee===1)if(A.ee=0,T.ee=1,T===this.Y)this.Y=T.te();else T.te();else if(A.W&&A.W.ee===1){if(A.ee=T.ee,T.ee=0,A.W.ee=0,T===this.Y)this.Y=T.te();else T.te();return}else if(A.U&&A.U.ee===1)A.ee=1,A.U.ee=0,A.se();else A.ee=1,_=T}else{let A=T.U;if(A.ee===1)if(A.ee=0,T.ee=1,T===this.Y)this.Y=T.se();else T.se();else if(A.U&&A.U.ee===1){if(A.ee=T.ee,T.ee=0,A.U.ee=0,T===this.Y)this.Y=T.se();else T.se();return}else if(A.W&&A.W.ee===1)A.ee=1,A.W.ee=0,A.te();else A.ee=1,_=T}}}fe(_){if(this.i===1)return this.clear(),this.h;let T=_;while(T.U||T.W){if(T.W){T=T.W;while(T.U)T=T.U}else T=T.U;[_.u,T.u]=[T.u,_.u],[_.l,T.l]=[T.l,_.l],_=T}if(this.h.U===T)this.h.U=T.tt;else if(this.h.W===T)this.h.W=T.tt;this.ue(T);let A=T.tt;if(T===A.U)A.U=void 0;else A.W=void 0;return this.i-=1,this.Y.ee=0,A}oe(_,T){if(_===void 0)return!1;if(this.oe(_.U,T))return!0;if(T(_))return!0;return this.oe(_.W,T)}he(_){while(!0){let T=_.tt;if(T.ee===0)return;let A=T.tt;if(T===A.U){let E=A.W;if(E&&E.ee===1){if(E.ee=T.ee=0,A===this.Y)return;A.ee=1,_=A;continue}else if(_===T.W){if(_.ee=0,_.U)_.U.tt=T;if(_.W)_.W.tt=A;if(T.W=_.U,A.U=_.W,_.U=T,_.W=A,A===this.Y)this.Y=_,this.h.tt=_;else{let L=A.tt;if(L.U===A)L.U=_;else L.W=_}return _.tt=A.tt,T.tt=_,A.tt=_,A.ee=1,{parentNode:T,grandParent:A,curNode:_}}else{if(T.ee=0,A===this.Y)this.Y=A.se();else A.se();A.ee=1}}else{let E=A.U;if(E&&E.ee===1){if(E.ee=T.ee=0,A===this.Y)return;A.ee=1,_=A;continue}else if(_===T.U){if(_.ee=0,_.U)_.U.tt=A;if(_.W)_.W.tt=T;if(A.W=_.U,T.U=_.W,_.U=A,_.W=T,A===this.Y)this.Y=_,this.h.tt=_;else{let L=A.tt;if(L.U===A)L.U=_;else L.W=_}return _.tt=A.tt,T.tt=_,A.tt=_,A.ee=1,{parentNode:T,grandParent:A,curNode:_}}else{if(T.ee=0,A===this.Y)this.Y=A.te();else A.te();A.ee=1}}return}}ne(_,T,A){if(this.Y===void 0){this.i+=1,this.Y=new this.re(_,T),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let E,L=this.h.U,J=this.v(L.u,_);if(J===0){L.l=T;return}else if(J>0)L.U=new this.re(_,T),L.U.tt=L,E=L.U,this.h.U=E;else{let X=this.h.W,H=this.v(X.u,_);if(H===0){X.l=T;return}else if(H<0)X.W=new this.re(_,T),X.W.tt=X,E=X.W,this.h.W=E;else{if(A!==void 0){let Z=A.o;if(Z!==this.h){let Y=this.v(Z.u,_);if(Y===0){Z.l=T;return}else if(Y>0){let K=Z.L(),$=this.v(K.u,_);if($===0){K.l=T;return}else if($<0)if(E=new this.re(_,T),K.W===void 0)K.W=E,E.tt=K;else Z.U=E,E.tt=Z}}}if(E===void 0){E=this.Y;while(!0){let Z=this.v(E.u,_);if(Z>0){if(E.U===void 0){E.U=new this.re(_,T),E.U.tt=E,E=E.U;break}E=E.U}else if(Z<0){if(E.W===void 0){E.W=new this.re(_,T),E.W.tt=E,E=E.W;break}E=E.W}else{E.l=T;return}}}}}return this.i+=1,E}I(_,T){while(_){let A=this.v(_.u,T);if(A<0)_=_.W;else if(A>0)_=_.U;else return _}return _||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(_,T){let A=_.o;if(A===this.h)(0,D3.throwIteratorAccessError)();if(this.i===1)return A.u=T,!0;if(A===this.h.U){if(this.v(A.B().u,T)>0)return A.u=T,!0;return!1}if(A===this.h.W){if(this.v(A.L().u,T)<0)return A.u=T,!0;return!1}let E=A.L().u;if(this.v(E,T)>=0)return!1;let L=A.B().u;if(this.v(L,T)<=0)return!1;return A.u=T,!0}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=0,A=this;return this.oe(this.Y,function(E){if(_===T)return A.V(E),!0;return T+=1,!1}),this.i}eraseElementByKey(_){if(this.i===0)return!1;let T=this.I(this.Y,_);if(T===this.h)return!1;return this.V(T),!0}eraseElementByIterator(_){let T=_.o;if(T===this.h)(0,D3.throwIteratorAccessError)();let A=T.W===void 0;if(_.iteratorType===0){if(A)_.next()}else if(!A||T.U===void 0)_.next();return this.V(T),_}forEach(_){let T=0;for(let A of this)_(A,T++,this)}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T,A=0;for(let E of this){if(A===_){T=E;break}A+=1}return T}getHeight(){if(this.i===0)return 0;let _=function(T){if(!T)return 0;return Math.max(_(T.U),_(T.W))+1};return _(this.Y)}}var Ex=B3;q3.default=Ex});var eE=W((j3)=>{Object.defineProperty(j3,"t",{value:!0});j3.default=void 0;var Lx=K0(),pA=$0();class P3 extends Lx.ContainerIterator{constructor(_,T,A){super(A);if(this.o=_,this.h=T,this.iteratorType===0)this.pre=function(){if(this.o===this.h.U)(0,pA.throwIteratorAccessError)();return this.o=this.o.L(),this},this.next=function(){if(this.o===this.h)(0,pA.throwIteratorAccessError)();return this.o=this.o.B(),this};else this.pre=function(){if(this.o===this.h.W)(0,pA.throwIteratorAccessError)();return this.o=this.o.B(),this},this.next=function(){if(this.o===this.h)(0,pA.throwIteratorAccessError)();return this.o=this.o.L(),this}}get index(){let _=this.o,T=this.h.tt;if(_===this.h){if(T)return T.rt-1;return 0}let A=0;if(_.U)A+=_.U.rt;while(_!==T){let E=_.tt;if(_===E.W){if(A+=1,E.U)A+=E.U.rt}_=E}return A}}var Jx=P3;j3.default=Jx});var h3=W((y3)=>{Object.defineProperty(y3,"t",{value:!0});y3.default=void 0;var Xx=w3(tE()),Hx=w3(eE()),Zx=$0();function w3(_){return _&&_.t?_:{default:_}}class p1 extends Hx.default{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 p1(this.o,this.h,this.container,this.iteratorType)}}class S3 extends Xx.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 Yx=S3;y3.default=Yx});var m3=W((b3)=>{Object.defineProperty(b3,"t",{value:!0});b3.default=void 0;var Kx=k3(tE()),$x=k3(eE()),Gx=$0();function k3(_){return _&&_.t?_:{default:_}}class l1 extends $x.default{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Gx.throwIteratorAccessError)();let _=this;return new Proxy([],{get(T,A){if(A==="0")return _.o.u;else if(A==="1")return _.o.l},set(T,A,E){if(A!=="1")throw TypeError("props must be 1");return _.o.l=E,!0}})}copy(){return new l1(this.o,this.h,this.container,this.iteratorType)}}class f3 extends Kx.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 Ux=f3;b3.default=Ux});var _L=W((u3)=>{Object.defineProperty(u3,"t",{value:!0});u3.default=Wx;function Wx(_){let T=typeof _;return T==="object"&&_!==null||T==="function"}});var AL=W((l3)=>{Object.defineProperty(l3,"t",{value:!0});l3.HashContainerIterator=l3.HashContainer=void 0;var d3=K0(),TL=Qx(_L()),T8=$0();function Qx(_){return _&&_.t?_:{default:_}}class c3 extends d3.ContainerIterator{constructor(_,T,A){super(A);if(this.o=_,this.h=T,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,T8.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,T8.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,T8.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,T8.throwIteratorAccessError)();return this.o=this.o.L,this}}}l3.HashContainerIterator=c3;class p3 extends d3.Container{constructor(){super();this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(_){let{L:T,B:A}=_;if(T.B=A,A.L=T,_===this.p)this.p=A;if(_===this._)this._=T;this.i-=1}M(_,T,A){if(A===void 0)A=(0,TL.default)(_);let E;if(A){let L=_[this.HASH_TAG];if(L!==void 0)return this.H[L].l=T,this.i;Object.defineProperty(_,this.HASH_TAG,{value:this.H.length,configurable:!0}),E={u:_,l:T,L:this._,B:this.h},this.H.push(E)}else{let L=this.g[_];if(L)return L.l=T,this.i;E={u:_,l:T,L:this._,B:this.h},this.g[_]=E}if(this.i===0)this.p=E,this.h.B=E;else this._.B=E;return this._=E,this.h.L=E,++this.i}I(_,T){if(T===void 0)T=(0,TL.default)(_);if(T){let A=_[this.HASH_TAG];if(A===void 0)return this.h;return this.H[A]}else return this.g[_]||this.h}clear(){let _=this.HASH_TAG;this.H.forEach(function(T){delete T.u[_]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(_,T){let A;if(T===void 0)T=(0,TL.default)(_);if(T){let E=_[this.HASH_TAG];if(E===void 0)return!1;delete _[this.HASH_TAG],A=this.H[E],delete this.H[E]}else{if(A=this.g[_],A===void 0)return!1;delete this.g[_]}return this.V(A),!0}eraseElementByIterator(_){let T=_.o;if(T===this.h)(0,T8.throwIteratorAccessError)();return this.V(T),_.next()}eraseElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return this.V(T),this.i}}l3.HashContainer=p3});var s3=W((o3)=>{Object.defineProperty(o3,"t",{value:!0});o3.default=void 0;var i3=AL(),Vx=$0();class wT extends i3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Vx.throwIteratorAccessError)();return this.o.u}copy(){return new wT(this.o,this.h,this.container,this.iteratorType)}}class a3 extends i3.HashContainer{constructor(_=[]){super();let T=this;_.forEach(function(A){T.insert(A)})}begin(){return new wT(this.p,this.h,this)}end(){return new wT(this.h,this.h,this)}rBegin(){return new wT(this._,this.h,this,1)}rEnd(){return new wT(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(_,T){return this.M(_,void 0,T)}getElementByPos(_){if(_<0||_>this.i-1)throw RangeError();let T=this.p;while(_--)T=T.B;return T.u}find(_,T){let A=this.I(_,T);return new wT(A,this.h,this)}forEach(_){let T=0,A=this.p;while(A!==this.h)_(A.u,T++,this),A=A.B}[Symbol.iterator](){return function*(){let _=this.p;while(_!==this.h)yield _.u,_=_.B}.bind(this)()}}var zx=a3;o3.default=zx});var A$=W((_$)=>{Object.defineProperty(_$,"t",{value:!0});_$.default=void 0;var t3=AL(),Fx=Ox(_L()),Cx=$0();function Ox(_){return _&&_.t?_:{default:_}}class ST extends t3.HashContainerIterator{constructor(_,T,A,E){super(_,T,E);this.container=A}get pointer(){if(this.o===this.h)(0,Cx.throwIteratorAccessError)();let _=this;return new Proxy([],{get(T,A){if(A==="0")return _.o.u;else if(A==="1")return _.o.l},set(T,A,E){if(A!=="1")throw TypeError("props must be 1");return _.o.l=E,!0}})}copy(){return new ST(this.o,this.h,this.container,this.iteratorType)}}class e3 extends t3.HashContainer{constructor(_=[]){super();let T=this;_.forEach(function(A){T.setElement(A[0],A[1])})}begin(){return new ST(this.p,this.h,this)}end(){return new ST(this.h,this.h,this)}rBegin(){return new ST(this._,this.h,this,1)}rEnd(){return new ST(this.h,this.h,this,1)}front(){if(this.i===0)return;return[this.p.u,this.p.l]}back(){if(this.i===0)return;return[this._.u,this._.l]}setElement(_,T,A){return this.M(_,T,A)}getElementByKey(_,T){if(T===void 0)T=(0,Fx.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 Rx=e3;_$.default=Rx});var E$=W((q1)=>{Object.defineProperty(q1,"t",{value:!0});Object.defineProperty(q1,"Deque",{enumerable:!0,get:function(){return jx.default}});Object.defineProperty(q1,"HashMap",{enumerable:!0,get:function(){return vx.default}});Object.defineProperty(q1,"HashSet",{enumerable:!0,get:function(){return yx.default}});Object.defineProperty(q1,"LinkList",{enumerable:!0,get:function(){return Px.default}});Object.defineProperty(q1,"OrderedMap",{enumerable:!0,get:function(){return Sx.default}});Object.defineProperty(q1,"OrderedSet",{enumerable:!0,get:function(){return xx.default}});Object.defineProperty(q1,"PriorityQueue",{enumerable:!0,get:function(){return qx.default}});Object.defineProperty(q1,"Queue",{enumerable:!0,get:function(){return Bx.default}});Object.defineProperty(q1,"Stack",{enumerable:!0,get:function(){return Dx.default}});Object.defineProperty(q1,"Vector",{enumerable:!0,get:function(){return Ix.default}});var Dx=G0(lK()),Bx=G0(oK()),qx=G0(eK()),Ix=G0(K3()),Px=G0(W3()),jx=G0(V3()),xx=G0(h3()),Sx=G0(m3()),yx=G0(s3()),vx=G0(A$());function G0(_){return _&&_.t?_:{default:_}}});var J$=W((pg,L$)=>{var hx=E$().OrderedSet,U0=d1()("number-allocator:trace"),kx=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 hx([],(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){kx("free():"+_+" is out of range");return}let T=new e_(_,_),A=this.ss.upperBound(T);if(A.equals(this.ss.end())){if(A.equals(this.ss.begin())){this.ss.insert(T);return}A.pre();let E=A.pointer.high;if(A.pointer.high+1===_)this.ss.updateKeyByIterator(A,new e_(E,_));else this.ss.insert(T)}else if(A.equals(this.ss.begin()))if(_+1===A.pointer.low){let E=A.pointer.high;this.ss.updateKeyByIterator(A,new e_(_,E))}else this.ss.insert(T);else{let E=A.pointer.low,L=A.pointer.high;A.pre();let J=A.pointer.low;if(A.pointer.high+1===_)if(_+1===E)this.ss.eraseElementByIterator(A),this.ss.updateKeyByIterator(A,new e_(J,L));else this.ss.updateKeyByIterator(A,new e_(J,_));else if(_+1===E)this.ss.eraseElementByIterator(A.next()),this.ss.insert(new e_(_,L));else this.ss.insert(T)}U0("free():"+_)};W0.prototype.clear=function(){U0("clear()"),this.ss.clear(),this.ss.insert(new e_(this.min,this.max))};W0.prototype.intervalCount=function(){return this.ss.size()};W0.prototype.dump=function(){console.log("length:"+this.ss.size());for(let _ of this.ss)console.log(_)};L$.exports=W0});var EL=W((bx,X$)=>{var fx=J$();bx.NumberAllocator=fx});var Y$=W((Z$)=>{Object.defineProperty(Z$,"__esModule",{value:!0});var mx=fK(),ux=EL();class H${aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(_){if(_>0)this.aliasToTopic=new mx.LRUCache({max:_}),this.topicToAlias={},this.numberAllocator=new ux.NumberAllocator(1,_),this.max=_,this.length=0}put(_,T){if(T===0||T>this.max)return!1;let A=this.aliasToTopic.get(T);if(A)delete this.topicToAlias[A];return this.aliasToTopic.set(T,_),this.topicToAlias[_]=T,this.numberAllocator.use(T),this.length=this.aliasToTopic.size,!0}getTopicByAlias(_){return this.aliasToTopic.get(_)}getAliasByTopic(_){let T=this.topicToAlias[_];if(typeof T<"u")this.aliasToTopic.get(T);return T}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){let _=this.numberAllocator.firstVacant();if(_)return _;return[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}}Z$.default=H$});var K$=W((A8)=>{var cx=A8&&A8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(A8,"__esModule",{value:!0});var px=e4(),lx=cx(Y$()),nx=qT(),ix=(_,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 lx.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 nx.ErrorWithReasonCode(`Connection refused: ${px.ReasonCodes[L]}`,L);if(_.emit("error",J),_.options.reconnectOnConnackError)_._cleanUp(!0)}};A8.default=ix});var G$=W(($$)=>{Object.defineProperty($$,"__esModule",{value:!0});var ax=(_,T,A)=>{_.log("handling pubrel packet");let E=typeof A<"u"?A:_.noop,{messageId:L}=T,J={cmd:"pubcomp",messageId:L};_.incomingStore.get(T,(X,H)=>{if(!X)_.emit("message",H.topic,H.payload,H),_.handleMessage(H,(Z)=>{if(Z)return E(Z);_.incomingStore.del(H,_.noop),_._sendPacket(J,E)});else _._sendPacket(J,E)})};$$.default=ax});var U$=W((E8)=>{var L8=E8&&E8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(E8,"__esModule",{value:!0});var rx=L8(OK()),sx=L8(xK()),tx=L8(K$()),ex=L8(e4()),_w=L8(G$()),Tw=(_,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,rx.default)(_,T,A);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":_.reschedulePing(),(0,ex.default)(_,T),A();break;case"pubrel":_.reschedulePing(),(0,_w.default)(_,T,A);break;case"connack":(0,tx.default)(_,T),A();break;case"auth":_.reschedulePing(),(0,sx.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=Tw});var LL=W((N$)=>{Object.defineProperty(N$,"__esModule",{value:!0});class W${nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let _=this.nextId++;if(this.nextId===65536)this.nextId=1;return _}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(_){return!0}deallocate(_){}clear(){}}N$.default=W$});var V$=W((M$)=>{Object.defineProperty(M$,"__esModule",{value:!0});class Q${aliasToTopic;max;length;constructor(_){this.aliasToTopic={},this.max=_}put(_,T){if(T===0||T>this.max)return!1;return this.aliasToTopic[T]=_,this.length=Object.keys(this.aliasToTopic).length,!0}getTopicByAlias(_){return this.aliasToTopic[_]}clear(){this.aliasToTopic={}}}M$.default=Q$});var z$=W((K4)=>{var Lw=K4&&K4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(K4,"__esModule",{value:!0});K4.TypedEventEmitter=void 0;var Jw=Lw(I("events")),Xw=qT();class JL{}K4.TypedEventEmitter=JL;(0,Xw.applyMixin)(JL,Jw.default)});var J8=W((tg,y0)=>{function XL(_){return y0.exports=XL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(T){return typeof T}:function(T){return T&&typeof Symbol=="function"&&T.constructor===Symbol&&T!==Symbol.prototype?"symbol":typeof T},y0.exports.__esModule=!0,y0.exports.default=y0.exports,XL(_)}y0.exports=XL,y0.exports.__esModule=!0,y0.exports.default=y0.exports});var C$=W((eg,X8)=>{var F$=J8().default;function Hw(_,T){if(F$(_)!="object"||!_)return _;var A=_[Symbol.toPrimitive];if(A!==void 0){var E=A.call(_,T||"default");if(F$(E)!="object")return E;throw TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(_)}X8.exports=Hw,X8.exports.__esModule=!0,X8.exports.default=X8.exports});var O$=W((_m,H8)=>{var Zw=J8().default,Yw=C$();function Kw(_){var T=Yw(_,"string");return Zw(T)=="symbol"?T:T+""}H8.exports=Kw,H8.exports.__esModule=!0,H8.exports.default=H8.exports});var R$=W((Tm,Z8)=>{var $w=O$();function Gw(_,T,A){return(T=$w(T))in _?Object.defineProperty(_,T,{value:A,enumerable:!0,configurable:!0,writable:!0}):_[T]=A,_}Z8.exports=Gw,Z8.exports.__esModule=!0,Z8.exports.default=Z8.exports});var D$=W((Am,Y8)=>{function Uw(_){if(Array.isArray(_))return _}Y8.exports=Uw,Y8.exports.__esModule=!0,Y8.exports.default=Y8.exports});var B$=W((Em,K8)=>{function Ww(_,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=Ww,K8.exports.__esModule=!0,K8.exports.default=K8.exports});var q$=W((Lm,$8)=>{function Nw(_,T){(T==null||T>_.length)&&(T=_.length);for(var A=0,E=Array(T);A<T;A++)E[A]=_[A];return E}$8.exports=Nw,$8.exports.__esModule=!0,$8.exports.default=$8.exports});var P$=W((Jm,G8)=>{var I$=q$();function Qw(_,T){if(_){if(typeof _=="string")return I$(_,T);var A={}.toString.call(_).slice(8,-1);return A==="Object"&&_.constructor&&(A=_.constructor.name),A==="Map"||A==="Set"?Array.from(_):A==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(A)?I$(_,T):void 0}}G8.exports=Qw,G8.exports.__esModule=!0,G8.exports.default=G8.exports});var j$=W((Xm,U8)=>{function Mw(){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=Mw,U8.exports.__esModule=!0,U8.exports.default=U8.exports});var x$=W((Hm,W8)=>{var Vw=D$(),zw=B$(),Fw=P$(),Cw=j$();function Ow(_,T){return Vw(_)||zw(_,T)||Fw(_,T)||Cw()}W8.exports=Ow,W8.exports.__esModule=!0,W8.exports.default=W8.exports});var y$=W((w$)=>{Object.defineProperty(w$,"__esModule",{value:!0});w$.createAddUniqueNumber=void 0;var Rw=(_)=>{return(T)=>{let A=_(T);return T.add(A),A}};w$.createAddUniqueNumber=Rw});var k$=W((v$)=>{Object.defineProperty(v$,"__esModule",{value:!0});v$.createCache=void 0;var Dw=(_)=>{return(T,A)=>{return _.set(T,A),A}};v$.createCache=Dw});var d$=W((m$)=>{Object.defineProperty(m$,"__esModule",{value:!0});m$.createGenerateUniqueNumber=void 0;var f$=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,g$=536870912,b$=g$*2,Bw=(_,T)=>{return(A)=>{let E=T.get(A),L=E===void 0?A.size:E<b$?E+1:0;if(!A.has(L))return _(A,L);if(A.size<g$){while(A.has(L))L=Math.floor(Math.random()*b$);return _(A,L)}if(A.size>f$)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(A.has(L))L=Math.floor(Math.random()*f$);return _(A,L)}};m$.createGenerateUniqueNumber=Bw});var HL=W((p$)=>{Object.defineProperty(p$,"__esModule",{value:!0});p$.generateUniqueNumber=p$.addUniqueNumber=void 0;var qw=y$(),Iw=k$(),Pw=d$(),c$=new WeakMap,jw=(0,Iw.createCache)(c$),xw=p$.generateUniqueNumber=(0,Pw.createGenerateUniqueNumber)(jw,c$),$m=p$.addUniqueNumber=(0,qw.createAddUniqueNumber)(xw)});var i$=W((Um,N8)=>{function n$(_,T,A,E,L,J,X){try{var H=_[J](X),Z=H.value}catch(Y){return void A(Y)}H.done?T(Z):Promise.resolve(Z).then(E,L)}function Sw(_){return function(){var T=this,A=arguments;return new Promise(function(E,L){var J=_.apply(T,A);function X(Z){n$(J,E,L,X,H,"next",Z)}function H(Z){n$(J,E,L,X,H,"throw",Z)}X(void 0)})}}N8.exports=Sw,N8.exports.__esModule=!0,N8.exports.default=N8.exports});var ZL=W((Wm,Q8)=>{function yw(_,T){this.v=_,this.k=T}Q8.exports=yw,Q8.exports.__esModule=!0,Q8.exports.default=Q8.exports});var YL=W((Nm,v0)=>{function lA(_,T,A,E){var L=Object.defineProperty;try{L({},"",{})}catch(J){L=0}v0.exports=lA=function(X,H,Z,Y){function K($,G){lA(X,$,function(U){return this._invoke($,G,U)})}H?L?L(X,H,{value:Z,enumerable:!Y,configurable:!Y,writable:!Y}):X[H]=Z:(K("next",0),K("throw",1),K("return",2))},v0.exports.__esModule=!0,v0.exports.default=v0.exports,lA(_,T,A,E)}v0.exports=lA,v0.exports.__esModule=!0,v0.exports.default=v0.exports});var KL=W((Qm,h0)=>{var N0=YL();function a$(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var _,T,A=typeof Symbol=="function"?Symbol:{},E=A.iterator||"@@iterator",L=A.toStringTag||"@@toStringTag";function J(U,V,N,z){var Q=V&&V.prototype instanceof H?V:H,F=Object.create(Q.prototype);return N0(F,"_invoke",function(R,q,f){var h,b,l,c=0,W_=f||[],c_=!1,B_={p:0,n:0,v:_,a:C_,f:C_.bind(_,4),d:function(M_,I_){return h=M_,b=0,l=_,B_.n=I_,X}};function C_(K_,M_){for(b=K_,l=M_,T=0;!c_&&c&&!I_&&T<W_.length;T++){var I_,j_=W_[T],R0=B_.p,y1=j_[2];K_>3?(I_=y1===M_)&&(l=j_[(b=j_[4])?5:(b=3,3)],j_[4]=j_[5]=_):j_[0]<=R0&&((I_=K_<2&&R0<j_[1])?(b=0,B_.v=M_,B_.n=j_[1]):R0<y1&&(I_=K_<3||j_[0]>M_||M_>y1)&&(j_[4]=K_,j_[5]=M_,B_.n=y1,b=0))}if(I_||K_>1)return X;throw c_=!0,M_}return function(K_,M_,I_){if(c>1)throw TypeError("Generator is already running");for(c_&&M_===1&&C_(M_,I_),b=M_,l=I_;(T=b<2?_:l)||!c_;){h||(b?b<3?(b>1&&(B_.n=-1),C_(b,l)):B_.n=l:B_.v=l);try{if(c=2,h){if(b||(K_="next"),T=h[K_]){if(!(T=T.call(h,l)))throw TypeError("iterator result is not an object");if(!T.done)return T;l=T.value,b<2&&(b=0)}else b===1&&(T=h.return)&&T.call(h),b<2&&(l=TypeError("The iterator does not provide a '"+K_+"' method"),b=1);h=_}else if((T=(c_=B_.n<0)?l:R.call(q,B_))!==X)break}catch(j_){h=_,b=1,l=j_}finally{c=1}}return{value:T,done:c_}}}(U,N,z),!0),F}var X={};function H(){}function Z(){}function Y(){}T=Object.getPrototypeOf;var K=[][E]?T(T([][E]())):(N0(T={},E,function(){return this}),T),$=Y.prototype=H.prototype=Object.create(K);function G(U){return Object.setPrototypeOf?Object.setPrototypeOf(U,Y):(U.__proto__=Y,N0(U,L,"GeneratorFunction")),U.prototype=Object.create($),U}return Z.prototype=Y,N0($,"constructor",Y),N0(Y,"constructor",Z),Z.displayName="GeneratorFunction",N0(Y,L,"GeneratorFunction"),N0($),N0($,L,"Generator"),N0($,E,function(){return this}),N0($,"toString",function(){return"[object Generator]"}),(h0.exports=a$=function(){return{w:J,m:G}},h0.exports.__esModule=!0,h0.exports.default=h0.exports)()}h0.exports=a$,h0.exports.__esModule=!0,h0.exports.default=h0.exports});var UL=W((Mm,M8)=>{var vw=ZL(),$L=YL();function GL(_,T){function A(L,J,X,H){try{var Z=_[L](J),Y=Z.value;return Y instanceof vw?T.resolve(Y.v).then(function(K){A("next",K,X,H)},function(K){A("throw",K,X,H)}):T.resolve(Y).then(function(K){Z.value=K,X(Z)},function(K){return A("throw",K,X,H)})}catch(K){H(K)}}var E;this.next||($L(GL.prototype),$L(GL.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),$L(this,"_invoke",function(L,J,X){function H(){return new T(function(Z,Y){A(L,X,Z,Y)})}return E=E?E.then(H,H):H()},!0)}M8.exports=GL,M8.exports.__esModule=!0,M8.exports.default=M8.exports});var WL=W((Vm,V8)=>{var hw=KL(),kw=UL();function fw(_,T,A,E,L){return new kw(hw().w(_,T,A,E),L||Promise)}V8.exports=fw,V8.exports.__esModule=!0,V8.exports.default=V8.exports});var o$=W((zm,z8)=>{var bw=WL();function gw(_,T,A,E,L){var J=bw(_,T,A,E,L);return J.next().then(function(X){return X.done?X.value:J.next()})}z8.exports=gw,z8.exports.__esModule=!0,z8.exports.default=z8.exports});var r$=W((Fm,F8)=>{function mw(_){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=mw,F8.exports.__esModule=!0,F8.exports.default=F8.exports});var s$=W((Cm,C8)=>{var uw=J8().default;function dw(_){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(uw(_)+" is not iterable")}C8.exports=dw,C8.exports.__esModule=!0,C8.exports.default=C8.exports});var e$=W((Om,k0)=>{var cw=ZL(),pw=KL(),lw=o$(),nw=WL(),iw=UL(),aw=r$(),t$=s$();function NL(){var _=pw(),T=_.m(NL),A=(Object.getPrototypeOf?Object.getPrototypeOf(T):T.__proto__).constructor;function E(X){var H=typeof X=="function"&&X.constructor;return!!H&&(H===A||(H.displayName||H.name)==="GeneratorFunction")}var L={throw:1,return:2,break:3,continue:3};function J(X){var H,Z;return function(Y){H||(H={stop:function(){return Z(Y.a,2)},catch:function(){return Y.v},abrupt:function($,G){return Z(Y.a,L[$],G)},delegateYield:function($,G,U){return H.resultName=G,Z(Y.d,t$($),U)},finish:function($){return Z(Y.f,$)}},Z=function($,G,U){Y.p=H.prev,Y.n=H.next;try{return $(G,U)}finally{H.next=Y.n}}),H.resultName&&(H[H.resultName]=Y.v,H.resultName=void 0),H.sent=Y.v,H.next=Y.n;try{return X.call(this,H)}finally{Y.p=H.prev,Y.n=H.next}}}return(k0.exports=NL=function(){return{wrap:function(Z,Y,K,$){return _.w(J(Z),Y,K,$&&$.reverse())},isGeneratorFunction:E,mark:_.m,awrap:function(Z,Y){return new cw(Z,Y)},AsyncIterator:iw,async:function(Z,Y,K,$,G){return(E(Y)?nw:lw)(J(Z),Y,K,$,G)},keys:aw,values:t$}},k0.exports.__esModule=!0,k0.exports.default=k0.exports)()}k0.exports=NL,k0.exports.__esModule=!0,k0.exports.default=k0.exports});var TG=W((Rm,_G)=>{var nA=e$()();_G.exports=nA;try{regeneratorRuntime=nA}catch(_){if(typeof globalThis==="object")globalThis.regeneratorRuntime=nA;else Function("r","regeneratorRuntime = r")(nA)}});var EG=W((iA,AG)=>{(function(_,T){typeof iA==="object"&&typeof AG<"u"?T(iA,R$(),x$(),HL(),i$(),TG()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.brokerFactory={},_._defineProperty,_._slicedToArray,_.fastUniqueNumbers,_._asyncToGenerator,_._regeneratorRuntime))})(iA,function(_,T,A,E,L,J){var X=function(Q){return typeof Q.start==="function"},H=new WeakMap;function Z(z,Q){var F=Object.keys(z);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(z);Q&&(R=R.filter(function(q){return Object.getOwnPropertyDescriptor(z,q).enumerable})),F.push.apply(F,R)}return F}function Y(z){for(var Q=1;Q<arguments.length;Q++){var F=arguments[Q]!=null?arguments[Q]:{};Q%2?Z(Object(F),!0).forEach(function(R){T(z,R,F[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(z,Object.getOwnPropertyDescriptors(F)):Z(Object(F)).forEach(function(R){Object.defineProperty(z,R,Object.getOwnPropertyDescriptor(F,R))})}return z}var K=function(Q){return Y(Y({},Q),{},{connect:function(R){var q=R.call;return L(J.mark(function f(){var h,b,l,c;return J.wrap(function(W_){while(!0)switch(W_.prev=W_.next){case 0:return h=new MessageChannel,b=h.port1,l=h.port2,W_.next=1,q("connect",{port:b},[b]);case 1:return c=W_.sent,H.set(l,c),W_.abrupt("return",l);case 2:case"end":return W_.stop()}},f)}))},disconnect:function(R){var q=R.call;return function(){var f=L(J.mark(function h(b){var l;return J.wrap(function(c){while(!0)switch(c.prev=c.next){case 0:if(l=H.get(b),l!==void 0){c.next=1;break}throw Error("The given port is not connected.");case 1:return c.next=2,q("disconnect",{portId:l});case 2:case"end":return c.stop()}},h)}));return function(h){return f.apply(this,arguments)}}()},isSupported:function(R){var q=R.call;return function(){return q("isSupported")}}})};function $(z,Q){var F=Object.keys(z);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(z);Q&&(R=R.filter(function(q){return Object.getOwnPropertyDescriptor(z,q).enumerable})),F.push.apply(F,R)}return F}function G(z){for(var Q=1;Q<arguments.length;Q++){var F=arguments[Q]!=null?arguments[Q]:{};Q%2?$(Object(F),!0).forEach(function(R){T(z,R,F[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(z,Object.getOwnPropertyDescriptors(F)):$(Object(F)).forEach(function(R){Object.defineProperty(z,R,Object.getOwnPropertyDescriptor(F,R))})}return z}var U=new WeakMap,V=function(Q){if(U.has(Q))return U.get(Q);var F=new Map;return U.set(Q,F),F},N=function(Q){var F=K(Q);return function(R){var q=V(R);if(R.addEventListener("message",function(C_){var K_=C_.data,M_=K_.id;if(M_!==null&&q.has(M_)){var I_=q.get(M_),j_=I_.reject,R0=I_.resolve;if(q.delete(M_),K_.error===void 0)R0(K_.result);else j_(Error(K_.error.message))}}),X(R))R.start();var f=function(K_){var M_=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,I_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(j_,R0){var y1=E.generateUniqueNumber(q);if(q.set(y1,{reject:R0,resolve:j_}),M_===null)R.postMessage({id:y1,method:K_},I_);else R.postMessage({id:y1,method:K_,params:M_},I_)})},h=function(K_,M_){var I_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];R.postMessage({id:null,method:K_,params:M_},I_)},b={};for(var l=0,c=Object.entries(F);l<c.length;l++){var W_=A(c[l],2),c_=W_[0],B_=W_[1];b=G(G({},b),{},T({},c_,B_({call:f,notify:h})))}return G({},b)}};_.createBroker=N})});var JG=W((aA,LG)=>{(function(_,T){typeof aA==="object"&&typeof LG<"u"?T(aA,J8(),EG(),HL()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.workerTimersBroker={},_._typeof,_.brokerFactory,_.fastUniqueNumbers))})(aA,function(_,T,A,E){var L=new Map([[0,null]]),J=new Map([[0,null]]),X=A.createBroker({clearInterval:function(Y){var K=Y.call;return function($){if(T(L.get($))==="symbol")L.set($,null),K("clear",{timerId:$,timerType:"interval"}).then(function(){L.delete($)})}},clearTimeout:function(Y){var K=Y.call;return function($){if(T(J.get($))==="symbol")J.set($,null),K("clear",{timerId:$,timerType:"timeout"}).then(function(){J.delete($)})}},setInterval:function(Y){var K=Y.call;return function($){var G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var U=arguments.length,V=Array(U>2?U-2:0),N=2;N<U;N++)V[N-2]=arguments[N];var z=Symbol(),Q=E.generateUniqueNumber(L);L.set(Q,z);var F=function(){return K("set",{delay:G,now:performance.timeOrigin+performance.now(),timerId:Q,timerType:"interval"}).then(function(){var q=L.get(Q);if(q===void 0)throw Error("The timer is in an undefined state.");if(q===z){if($.apply(void 0,V),L.get(Q)===z)F()}})};return F(),Q}},setTimeout:function(Y){var K=Y.call;return function($){var G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var U=arguments.length,V=Array(U>2?U-2:0),N=2;N<U;N++)V[N-2]=arguments[N];var z=Symbol(),Q=E.generateUniqueNumber(J);return J.set(Q,z),K("set",{delay:G,now:performance.timeOrigin+performance.now(),timerId:Q,timerType:"timeout"}).then(function(){var F=J.get(Q);if(F===void 0)throw Error("The timer is in an undefined state.");if(F===z)J.delete(Q),$.apply(void 0,V)}),Q}}}),H=function(Y){var K=new Worker(Y);return X(K)};_.load=H,_.wrap=X})});var HG=W((oA,XG)=>{(function(_,T){typeof oA==="object"&&typeof XG<"u"?T(oA,JG()):typeof define==="function"&&define.amd?define(["exports","worker-timers-broker"],T):(_=typeof globalThis<"u"?globalThis:_||self,T(_.workerTimers={},_.workerTimersBroker))})(oA,function(_,T){var A=function(K,$){var G=null;return function(){if(G!==null)return G;var U=new Blob([$],{type:"application/javascript; charset=utf-8"}),V=URL.createObjectURL(U);return G=K(V),setTimeout(function(){return URL.revokeObjectURL(V)}),G}},E='(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise(function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)})}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise(function(t){e.set(a,[r(n,s,i,e,t,a),t])})}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark(function e(r){var n,o,u;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark(function e(r){var n,o,u,a,i;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){function u(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n:(u("next",0),u("throw",1),u("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a(\'The requested method called "\'.concat(e,\'" is not supported.\'),u.METHOD_NOT_FOUND)},s=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned no required result.\'),u.INTERNAL_ERROR)},c=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned an unexpected result.\'),u.INTERNAL_ERROR)},f=function(e){return a(\'The specified parameter called "portId" with the given value "\'.concat(e,\'" does not identify a port connected to this worker.\'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark(function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}},t,null,[[1,11]])}));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise(function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])})};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach(function(t){n(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,function(){u(),r.close(),x.delete(a)}),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark(function e(){var t,n,o;return r.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}},e)}));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then(function(e){u("next",e,a,i)},function(e){u("throw",e,a,i)}):r.resolve(c).then(function(e){s.value=e,a(s)},function(e){return u("throw",e,a,i)})}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),o(this,"_invoke",function(e,t,n){function o(){return new r(function(t,r){u(e,n,t,r)})}return a=a?a.then(o,o):o()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a \'"+o+"\' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,function(){return this}),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,function(){return this}),n(v,"toString",function(){return"[object Generator]"}),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();',L=A(T.load,E),J=function(K){return L().clearInterval(K)},X=function(K){return L().clearTimeout(K)},H=function(){var K;return(K=L()).setInterval.apply(K,arguments)},Z=function(){var K;return(K=L()).setTimeout.apply(K,arguments)};_.clearInterval=J,_.clearTimeout=X,_.setInterval=H,_.setTimeout=Z})});var O8=W((KG)=>{Object.defineProperty(KG,"__esModule",{value:!0});KG.isReactNativeBrowser=KG.isWebWorker=void 0;var ow=()=>{if(typeof window<"u"){if(typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&process?.versions)return!Object.prototype.hasOwnProperty.call(process.versions,"electron");return typeof window.document<"u"}return!1},ZG=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),YG=()=>typeof navigator<"u"&&navigator.product==="ReactNative",rw=ow()||ZG()||YG();KG.isWebWorker=ZG();KG.isReactNativeBrowser=YG();KG.default=rw});var NG=W((f0)=>{var ew=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]}),_S=f0&&f0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),TS=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")ew(A,T,E[L])}return _S(A,T),A}}();Object.defineProperty(f0,"__esModule",{value:!0});var GG=HG(),QL=TS(O8()),UG={set:GG.setInterval,clear:GG.clearInterval},WG={set:(_,T)=>setInterval(_,T),clear:(_)=>clearInterval(_)},AS=(_)=>{switch(_){case"native":return WG;case"worker":return UG;case"auto":default:return QL.default&&!QL.isWebWorker&&!QL.isReactNativeBrowser?UG:WG}};f0.default=AS});var ML=W((R8)=>{var ES=R8&&R8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(R8,"__esModule",{value:!0});var LS=ES(NG());class QG{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(_,T){this.client=_,this.timer=typeof T==="object"&&"set"in T&&"clear"in T?T:(0,LS.default)(T),this.setKeepalive(_.options.keepalive)}clear(){if(this.timerId)this.timer.clear(this.timerId),this.timerId=null}setKeepalive(_){if(_*=1000,isNaN(_)||_<=0||_>2147483647)throw Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${_}`);this._keepalive=_,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${_}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let _=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+_,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{if(this.destroyed)return;if(this.counter+=1,this.counter===2)this.client.sendPing();else if(this.counter>2)this.client.onKeepaliveTimeout()},this._intervalEvery)}}R8.default=QG});var sA=W((n1)=>{var JS=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]}),XS=n1&&n1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),CG=n1&&n1.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")JS(A,T,E[L])}return XS(A,T),A}}(),t0=n1&&n1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(n1,"__esModule",{value:!0});var VL=t0(wA()),HS=n0(),MG=t0(WK()),ZS=t0(d1()),VG=CG(MK()),$4=t0(pE()),YS=t0(U$()),KS=t0(LL()),$S=t0(V$()),D8=qT(),GS=z$(),US=t0(ML()),zG=CG(O8()),zL=globalThis.setImmediate||((..._)=>{let T=_.shift();(0,D8.nextTick)(()=>{T(..._)})}),FG={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1000,connectTimeout:30000,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class rA extends GS.TypedEventEmitter{static VERSION=D8.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(_,T){super();this.options=T||{};for(let A in FG)if(typeof this.options[A]>"u")this.options[A]=FG[A];else this.options[A]=T[A];if(this.log=this.options.log||(0,ZS.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",rA.VERSION),zG.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",zG.default?"browser":"node");if(this.log("MqttClient :: options.protocol",T.protocol),this.log("MqttClient :: options.protocolVersion",T.protocolVersion),this.log("MqttClient :: options.username",T.username),this.log("MqttClient :: options.keepalive",T.keepalive),this.log("MqttClient :: options.reconnectPeriod",T.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",T.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",T.properties?T.properties.topicAliasMaximum:void 0),this.options.clientId=typeof T.clientId==="string"?T.clientId:rA.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=T.protocolVersion===5&&T.customHandleAcks?T.customHandleAcks:(...A)=>{A[3](null,0)},!this.options.writeCache)VL.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=_,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new KS.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 $S.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 HS.Writable,T=VL.default.parser(this.options),A=null,E=[];if(this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting)this.incomingStore=this.options.incomingStore||new $4.default,this.outgoingStore=this.options.outgoingStore||new $4.default,this.disconnecting=!1,this.disconnected=!1;this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),T.on("packet",(Z)=>{this.log("parser :: on packet push to packets array."),E.push(Z)});let L=()=>{this.log("work :: getting next packet in queue");let Z=E.shift();if(Z)this.log("work :: packet pulled from queue"),(0,YS.default)(this,Z,J);else{this.log("work :: no packets in queue");let Y=A;if(A=null,this.log("work :: done flag is %s",!!Y),Y)Y()}},J=()=>{if(E.length)(0,D8.nextTick)(L);else{let Z=A;A=null,Z()}};_._write=(Z,Y,K)=>{A=K,this.log("writable stream :: parsing buffer"),T.parse(Z),L()};let X=(Z)=>{if(this.log("streamErrorHandler :: error",Z.message),Z.code)this.log("streamErrorHandler :: emitting error"),this.emit("error",Z);else this.noop(Z)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(_),this.stream.on("error",X),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let H={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will)H.will={...this.options.will,payload:this.options.will?.payload};if(this.topicAliasRecv){if(!H.properties)H.properties={};if(this.topicAliasRecv)H.properties.topicAliasMaximum=this.topicAliasRecv.max}if(this._writePacket(H),T.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket==="object"){let Z={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(Z)}}return this.stream.setMaxListeners(1000),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(_,T,A,E){this.log("publish :: message `%s` to topic `%s`",T,_);let{options:L}=this;if(typeof A==="function")E=A,A=null;A=A||{},A={...{qos:0,retain:!1,dup:!1},...A};let{qos:X,retain:H,dup:Z,properties:Y,cbStorePut:K}=A;if(this._checkDisconnecting(E))return this;let $=()=>{let G=0;if(X===1||X===2){if(G=this._nextId(),G===null)return this.log("No messageId left"),!1}let U={cmd:"publish",topic:_,payload:T,qos:X,retain:H,messageId:G,dup:Z};if(L.protocolVersion===5)U.properties=Y;switch(this.log("publish :: qos",X),X){case 1:case 2:this.outgoing[U.messageId]={volatile:!1,cb:E||this.noop},this.log("MqttClient:publish: packet cmd: %s",U.cmd),this._sendPacket(U,void 0,K);break;default:this.log("MqttClient:publish: packet cmd: %s",U.cmd),this._sendPacket(U,E,K);break}return!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!$())this._storeProcessingQueue.push({invoke:$,cbStorePut:A.cbStorePut,callback:E});return this}publishAsync(_,T,A){return new Promise((E,L)=>{this.publish(_,T,A,(J,X)=>{if(J)L(J);else E(X)})})}subscribe(_,T,A){let E=this.options.protocolVersion;if(typeof T==="function")A=T;A=A||this.noop;let L=!1,J=[];if(typeof _==="string")_=[_],J=_;else if(Array.isArray(_))J=_;else if(typeof _==="object")L=_.resubscribe,delete _.resubscribe,J=Object.keys(_);let X=VG.validateTopics(J);if(X!==null)return zL(A,Error(`Invalid topic ${X}`)),this;if(this._checkDisconnecting(A))return this.log("subscribe: discconecting true"),this;let H={qos:0};if(E===5)H.nl=!1,H.rap=!1,H.rh=0;T={...H,...T};let{properties:Z}=T,Y=[],K=(U,V)=>{if(V=V||T,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,U)||this._resubscribeTopics[U].qos<V.qos||L){let N={topic:U,qos:V.qos};if(E===5)N.nl=V.nl,N.rap=V.rap,N.rh=V.rh,N.properties=Z;this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",N.topic,N.qos),Y.push(N)}};if(Array.isArray(_))_.forEach((U)=>{this.log("subscribe: array topic %s",U),K(U)});else Object.keys(_).forEach((U)=>{this.log("subscribe: object topic %s, %o",U,_[U]),K(U,_[U])});if(!Y.length)return A(null,[]),this;let $=(U,V)=>{let N={cmd:"subscribe",subscriptions:U,messageId:V};if(Z)N.properties=Z;if(this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];U.forEach((F)=>{if(this.options.reconnectPeriod>0){let R={qos:F.qos};if(E===5)R.nl=F.nl||!1,R.rap=F.rap||!1,R.rh=F.rh||0,R.properties=F.properties;this._resubscribeTopics[F.topic]=R,Q.push(F.topic)}}),this.messageIdToTopic[N.messageId]=Q}let z=new Promise((Q,F)=>{this.outgoing[N.messageId]={volatile:!0,cb(R,q){if(!R){let{granted:f}=q;for(let h=0;h<f.length;h+=1)U[h].qos=f[h]}if(!R)Q(q);else F(new D8.ErrorWithSubackPacket(R.message,q))}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(N),z},G=()=>{let U=this.options.subscribeBatchSize??Y.length,V=[];for(let N=0;N<Y.length;N+=U){let z=Y.slice(N,N+U),Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;V.push($(z,Q))}return Promise.all(V).then((N)=>{A(null,Y,N.at(-1))}).catch((N)=>{A(N,Y,N.packet)}),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!G())this._storeProcessingQueue.push({invoke:G,callback:A});return this}subscribeAsync(_,T){return new Promise((A,E)=>{this.subscribe(_,T,(L,J)=>{if(L)E(L);else A(J)})})}unsubscribe(_,T,A){if(typeof _==="string")_=[_];if(typeof T==="function")A=T;A=A||this.noop;let E=VG.validateTopics(_);if(E!==null)return zL(A,Error(`Invalid topic ${E}`)),this;if(this._checkDisconnecting(A))return this;let L=()=>{let J=this._nextId();if(J===null)return this.log("No messageId left"),!1;let X={cmd:"unsubscribe",messageId:J,unsubscriptions:[]};if(typeof _==="string")X.unsubscriptions=[_];else if(Array.isArray(_))X.unsubscriptions=_;if(this.options.resubscribe)X.unsubscriptions.forEach((H)=>{delete this._resubscribeTopics[H]});if(typeof T==="object"&&T.properties)X.properties=T.properties;return this.outgoing[X.messageId]={volatile:!0,cb:A},this.log("unsubscribe: call _sendPacket"),this._sendPacket(X),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!L())this._storeProcessingQueue.push({invoke:L,callback:A});return this}unsubscribeAsync(_,T){return new Promise((A,E)=>{this.unsubscribe(_,T,(L,J)=>{if(L)E(L);else A(J)})})}end(_,T,A){if(this.log("end :: (%s)",this.options.clientId),_==null||typeof _!=="boolean")A=A||T,T=_,_=!1;if(typeof T!=="object")A=A||T,T=null;if(this.log("end :: cb? %s",!!A),!A||typeof A!=="function")A=this.noop;let E=()=>{if(this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close((J)=>{this.outgoingStore.close((X)=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),A){let H=J||X;this.log("end :: closeStores: invoking callback with args"),A(H)}})}),this._deferredReconnect)this._deferredReconnect();else if(this.options.reconnectPeriod===0||this.options.manualConnect)this.disconnecting=!1},L=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,_),this._cleanUp(_,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,D8.nextTick)(E)},T)};if(this.disconnecting)return A(),this;if(this._clearReconnect(),this.disconnecting=!0,!_&&Object.keys(this.outgoing).length>0)this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,L,10));else this.log("end :: (%s) :: immediately calling finish",this.options.clientId),L();return this}endAsync(_,T){return new Promise((A,E)=>{this.end(_,T,(L)=>{if(L)E(L);else A()})})}removeOutgoingMessage(_){if(this.outgoing[_]){let{cb:T}=this.outgoing[_];this._removeOutgoingAndStoreMessage(_,()=>{T(Error("Message removed"))})}return this}reconnect(_){this.log("client reconnect");let T=()=>{if(_)this.options.incomingStore=_.incomingStore,this.options.outgoingStore=_.outgoingStore;else this.options.incomingStore=null,this.options.outgoingStore=null;this.incomingStore=this.options.incomingStore||new $4.default,this.outgoingStore=this.options.outgoingStore||new $4.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};if(this.disconnecting&&!this.disconnected)this._deferredReconnect=T;else T();return this}_flushVolatile(){if(this.outgoing)this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach((_)=>{if(this.outgoing[_].volatile&&typeof this.outgoing[_].cb==="function")this.outgoing[_].cb(Error("Connection closed")),delete this.outgoing[_]})}_flush(){if(this.outgoing)this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach((_)=>{if(typeof this.outgoing[_].cb==="function")this.outgoing[_].cb(Error("Connection closed")),delete this.outgoing[_]})}_removeTopicAliasAndRecoverTopicName(_){let T;if(_.properties)T=_.properties.topicAlias;let A=_.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",T,A),A.length===0){if(typeof T>"u")return Error("Unregistered Topic Alias");if(A=this.topicAliasSend.getTopicByAlias(T),typeof A>"u")return Error("Unregistered Topic Alias");_.topic=A}if(T)delete _.properties.topicAlias}_checkDisconnecting(_){if(this.disconnecting)if(_&&_!==this.noop)_(Error("client disconnecting"));else this.emit("error",Error("client disconnecting"));return this.disconnecting}_reconnect(){if(this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected)this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.");else this.log("_reconnect: calling connect"),this.connect()}_setupReconnect(){if(!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0){if(!this.reconnecting)this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0;this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)}else this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){if(this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer)clearInterval(this.reconnectTimer),this.reconnectTimer=null}_cleanUp(_,T,A={}){if(T)this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",T);if(this.log("_cleanUp :: forced? %s",_),_){if(this.options.reconnectPeriod===0&&this.options.clean)this._flush();this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy()}else{let E={cmd:"disconnect",...A};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(E,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),zL(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}if(!this.disconnecting&&!this.reconnecting)this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect();if(this._destroyKeepaliveManager(),T&&!this.connected)this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",T),T()}_storeAndSend(_,T,A){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",_.cmd);let E=_,L;if(E.cmd==="publish"){if(E=(0,MG.default)(_),L=this._removeTopicAliasAndRecoverTopicName(E),L)return T&&T(L)}this.outgoingStore.put(E,(J)=>{if(J)return T&&T(J);A(),this._writePacket(_,T)})}_applyTopicAlias(_){if(this.options.protocolVersion===5){if(_.cmd==="publish"){let T;if(_.properties)T=_.properties.topicAlias;let A=_.topic.toString();if(this.topicAliasSend){if(T){if(A.length!==0){if(this.log("applyTopicAlias :: register topic: %s - alias: %d",A,T),!this.topicAliasSend.put(A,T))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,T),Error("Sending Topic Alias out of range")}}else if(A.length!==0){if(this.options.autoAssignTopicAlias)if(T=this.topicAliasSend.getAliasByTopic(A),T)_.topic="",_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",A,T);else T=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(A,T),_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",A,T);else if(this.options.autoUseTopicAlias){if(T=this.topicAliasSend.getAliasByTopic(A),T)_.topic="",_.properties={..._.properties,topicAlias:T},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",A,T)}}}else if(T)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,T),Error("Sending Topic Alias out of range")}}}_noop(_){this.log("noop ::",_)}_writePacket(_,T){this.log("_writePacket :: packet: %O",_),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",_),this.log("_writePacket :: writing to stream");let A=VL.default.writeToStream(_,this.stream,this.options);if(this.log("_writePacket :: writeToStream result %s",A),!A&&T&&T!==this.noop)this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",T);else if(T)this.log("_writePacket :: invoking cb"),T()}_sendPacket(_,T,A,E){this.log("_sendPacket :: (%s) :: start",this.options.clientId),A=A||this.noop,T=T||this.noop;let L=this._applyTopicAlias(_);if(L){T(L);return}if(!this.connected){if(_.cmd==="auth"){this._writePacket(_,T);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(_,T,A);return}if(E){this._writePacket(_,T);return}switch(_.cmd){case"publish":break;case"pubrel":this._storeAndSend(_,T,A);return;default:this._writePacket(_,T);return}switch(_.qos){case 2:case 1:this._storeAndSend(_,T,A);break;case 0:default:this._writePacket(_,T);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(_,T,A){this.log("_storePacket :: packet: %o",_),this.log("_storePacket :: cb? %s",!!T),A=A||this.noop;let E=_;if(E.cmd==="publish"){E=(0,MG.default)(_);let J=this._removeTopicAliasAndRecoverTopicName(E);if(J)return T&&T(J)}let L=E.qos||0;if(L===0&&this.queueQoSZero||E.cmd!=="publish")this.queue.push({packet:E,cb:T});else if(L>0)T=this.outgoing[E.messageId]?this.outgoing[E.messageId].cb:null,this.outgoingStore.put(E,(J)=>{if(J)return T&&T(J);A()});else if(T)T(Error("No connection to broker"))}_setupKeepaliveManager(){if(this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive)this.keepaliveManager=new US.default(this,this.options.timerVariant)}_destroyKeepaliveManager(){if(this.keepaliveManager)this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null}reschedulePing(_=!1){if(this.keepaliveManager&&this.options.keepalive&&(_||this.options.reschedulePings))this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let _=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&_.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let T=0;T<_.length;T++){let A={};A[_[T]]=this._resubscribeTopics[_[T]],A.resubscribe=!0,this.subscribe(A,{properties:A[_[T]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(_){if(this.disconnected){this.emit("connect",_);return}this.connackPacket=_,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let T=()=>{let A=this.outgoingStore.createStream(),E=()=>{A.destroy(),A=null,this._flushStoreProcessingQueue(),L()},L=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",E),A.on("error",(X)=>{L(),this._flushStoreProcessingQueue(),this.removeListener("close",E),this.emit("error",X)});let J=()=>{if(!A)return;let X=A.read(1),H;if(!X){A.once("readable",J);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[X.messageId]){J();return}if(!this.disconnecting&&!this.reconnectTimer)if(H=this.outgoing[X.messageId]?this.outgoing[X.messageId].cb:null,this.outgoing[X.messageId]={volatile:!1,cb(Z,Y){if(H)H(Z,Y);J()}},this._packetIdsDuringStoreProcessing[X.messageId]=!0,this.messageIdProvider.register(X.messageId))this._sendPacket(X,void 0,void 0,!0);else this.log("messageId: %d has already used.",X.messageId);else if(A.destroy)A.destroy()};A.on("end",()=>{let X=!0;for(let H in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[H]){X=!1;break}if(this.removeListener("close",E),X)L(),this._invokeAllStoreProcessingQueue(),this.emit("connect",_);else T()}),J()};T()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let _=this._storeProcessingQueue[0];if(_&&_.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){while(this._invokeStoreProcessingQueue());}_flushStoreProcessingQueue(){for(let _ of this._storeProcessingQueue){if(_.cbStorePut)_.cbStorePut(Error("Connection closed"));if(_.callback)_.callback(Error("Connection closed"))}this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(_,T){delete this.outgoing[_],this.outgoingStore.del({messageId:_},(A,E)=>{T(A,E),this.messageIdProvider.deallocate(_),this._invokeStoreProcessingQueue()})}}n1.default=rA});var DG=W((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});var WS=EL();class OG{numberAllocator;lastId;constructor(){this.numberAllocator=new WS.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(_){return this.numberAllocator.use(_)}deallocate(_){this.numberAllocator.free(_)}clear(){this.numberAllocator.clear()}}RG.default=OG});var tA=W((PG)=>{Object.defineProperty(PG,"__esModule",{value:!0});PG.BufferedDuplex=void 0;PG.writev=qG;var QS=n0(),BG=I("buffer");function qG(_,T){let A=Array(_.length);for(let E=0;E<_.length;E++)if(typeof _[E].chunk==="string")A[E]=BG.Buffer.from(_[E].chunk,"utf8");else A[E]=_[E].chunk;this._write(BG.Buffer.concat(A),"binary",T)}class IG extends QS.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(_,T,A){super({objectMode:!0});if(this.proxy=T,this.socket=A,this.writeQueue=[],!_.objectMode)this._writev=qG.bind(this);this.isSocketOpen=!1,this.proxy.on("data",(E)=>{if(!this.destroyed&&this.readable)this.push(E)})}_read(_){this.proxy.read(_)}_write(_,T,A){if(!this.isSocketOpen)this.writeQueue.push({chunk:_,encoding:T,cb:A});else this.writeToProxy(_,T,A)}_final(_){this.writeQueue=[],this.proxy.end(_)}_destroy(_,T){this.writeQueue=[],this.proxy.destroy(),T(_)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(_,T,A){if(this.proxy.write(_,T)===!1)this.proxy.once("drain",A);else A()}processWriteQueue(){while(this.writeQueue.length>0){let{chunk:_,encoding:T,cb:A}=this.writeQueue.shift();this.writeToProxy(_,T,A)}}}PG.BufferedDuplex=IG});var B8=W((_T)=>{var CL=_T&&_T.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(_T,"__esModule",{value:!0});_T.streamBuilder=_T.browserStreamBuilder=void 0;var eA=I("buffer"),xG=CL(I("ws")),VS=CL(d1()),zS=n0(),FS=CL(O8()),FL=tA(),e0=(0,VS.default)("mqttjs:ws"),CS=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function wG(_,T){let A=`${_.protocol}://${_.hostname}:${_.port}${_.path}`;if(typeof _.transformWsUrl==="function")A=_.transformWsUrl(A,_,T);return A}function SG(_){let T=_;if(!_.port)if(_.protocol==="wss")T.port=443;else T.port=80;if(!_.path)T.path="/";if(!_.wsOptions)T.wsOptions={};if(!FS.default&&!_.forceNativeWebSocket&&_.protocol==="wss")CS.forEach((A)=>{if(Object.prototype.hasOwnProperty.call(_,A)&&!Object.prototype.hasOwnProperty.call(_.wsOptions,A))T.wsOptions[A]=_[A]});return T}function OS(_){let T=SG(_);if(!T.hostname)T.hostname=T.host;if(!T.hostname){if(typeof document>"u")throw Error("Could not determine host. Specify host manually.");let A=new URL(document.URL);if(T.hostname=A.hostname,!T.port)T.port=Number(A.port)}if(T.objectMode===void 0)T.objectMode=!(T.binary===!0||T.binary===void 0);return T}function RS(_,T,A){e0("createWebSocket"),e0(`protocol: ${A.protocolId} ${A.protocolVersion}`);let E=A.protocolId==="MQIsdp"&&A.protocolVersion===3?"mqttv3.1":"mqtt";e0(`creating new Websocket for url: ${T} and protocol: ${E}`);let L;if(A.createWebsocket)L=A.createWebsocket(T,[E],A);else L=new xG.default(T,[E],A.wsOptions);return L}function DS(_,T){let A=T.protocolId==="MQIsdp"&&T.protocolVersion===3?"mqttv3.1":"mqtt",E=wG(T,_),L;if(T.createWebsocket)L=T.createWebsocket(E,[A],T);else L=new WebSocket(E,[A]);return L.binaryType="arraybuffer",L}var BS=(_,T)=>{e0("streamBuilder");let A=SG(T);A.hostname=A.hostname||A.host||"localhost";let E=wG(A,_),L=RS(_,E,A),J=xG.default.createWebSocketStream(L,A.wsOptions);return J.url=E,L.on("close",()=>{J.destroy()}),J};_T.streamBuilder=BS;var qS=(_,T)=>{e0("browserStreamBuilder");let A,L=OS(T).browserBufferSize||524288,J=T.browserBufferTimeout||1000,X=!T.objectMode,H=DS(_,T),Z=K(T,N,z);if(!T.objectMode)Z._writev=FL.writev.bind(Z);Z.on("close",()=>{H.close()});let Y=typeof H.addEventListener<"u";if(H.readyState===H.OPEN)A=Z,A.socket=H;else if(A=new FL.BufferedDuplex(T,Z,H),Y)H.addEventListener("open",$);else H.onopen=$;if(Y)H.addEventListener("close",G),H.addEventListener("error",U),H.addEventListener("message",V);else H.onclose=G,H.onerror=U,H.onmessage=V;function K(Q,F,R){let q=new zS.Transform({objectMode:Q.objectMode});return q._write=F,q._flush=R,q}function $(){if(e0("WebSocket onOpen"),A instanceof FL.BufferedDuplex)A.socketReady()}function G(Q){e0("WebSocket onClose",Q),A.end(),A.destroy()}function U(Q){e0("WebSocket onError",Q);let F=Error("WebSocket error");F.event=Q,A.destroy(F)}async function V(Q){if(!Z||!Z.readable||!Z.writable)return;let{data:F}=Q;if(F instanceof ArrayBuffer)F=eA.Buffer.from(F);else if(F instanceof Blob)F=eA.Buffer.from(await new Response(F).arrayBuffer());else F=eA.Buffer.from(F,"utf8");Z.push(F)}function N(Q,F,R){if(H.bufferedAmount>L){setTimeout(N,J,Q,F,R);return}if(X&&typeof Q==="string")Q=eA.Buffer.from(Q,"utf8");try{H.send(Q)}catch(q){return R(q)}R()}function z(Q){H.close(),Q()}return A};_T.browserStreamBuilder=qS});var fG=W((kG)=>{Object.defineProperty(kG,"__esModule",{value:!0});var yG=I("buffer"),yT={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};kG.ERRORS=yT;function IS(_){if(!yG.Buffer.isEncoding(_))throw Error(yT.INVALID_ENCODING)}kG.checkEncoding=IS;function vG(_){return typeof _==="number"&&isFinite(_)&&wS(_)}kG.isFiniteInteger=vG;function hG(_,T){if(typeof _==="number"){if(!vG(_)||_<0)throw Error(T?yT.INVALID_OFFSET:yT.INVALID_LENGTH)}else throw Error(T?yT.INVALID_OFFSET_NON_NUMBER:yT.INVALID_LENGTH_NON_NUMBER)}function PS(_){hG(_,!1)}kG.checkLengthValue=PS;function jS(_){hG(_,!0)}kG.checkOffsetValue=jS;function xS(_,T){if(_<0||_>T.length)throw Error(yT.INVALID_TARGET_OFFSET)}kG.checkTargetOffset=xS;function wS(_){return typeof _==="number"&&isFinite(_)&&Math.floor(_)===_}function SS(_){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof yG.Buffer.prototype[_]>"u")throw Error(`Platform does not support Buffer.prototype.${_}.`)}kG.bigIntAndBufferInt64Check=SS});var mG=W((gG)=>{Object.defineProperty(gG,"__esModule",{value:!0});var t=fG(),bG=4096,mS="utf8";class OL{constructor(_){if(this.length=0,this._encoding=mS,this._writeOffset=0,this._readOffset=0,OL.isSmartBufferOptions(_)){if(_.encoding)t.checkEncoding(_.encoding),this._encoding=_.encoding;if(_.size)if(t.isFiniteInteger(_.size)&&_.size>0)this._buff=Buffer.allocUnsafe(_.size);else throw Error(t.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(_.buff)if(Buffer.isBuffer(_.buff))this._buff=_.buff,this.length=_.buff.length;else throw Error(t.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(bG)}else{if(typeof _<"u")throw Error(t.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(bG)}}static fromSize(_,T){return new this({size:_,encoding:T})}static fromBuffer(_,T){return new this({buff:_,encoding:T})}static fromOptions(_){return new this(_)}static isSmartBufferOptions(_){let T=_;return T&&(T.encoding!==void 0||T.size!==void 0||T.buff!==void 0)}readInt8(_){return this._readNumberValue(Buffer.prototype.readInt8,1,_)}readInt16BE(_){return this._readNumberValue(Buffer.prototype.readInt16BE,2,_)}readInt16LE(_){return this._readNumberValue(Buffer.prototype.readInt16LE,2,_)}readInt32BE(_){return this._readNumberValue(Buffer.prototype.readInt32BE,4,_)}readInt32LE(_){return this._readNumberValue(Buffer.prototype.readInt32LE,4,_)}readBigInt64BE(_){return t.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,_)}readBigInt64LE(_){return t.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,_)}writeInt8(_,T){return this._writeNumberValue(Buffer.prototype.writeInt8,1,_,T),this}insertInt8(_,T){return this._insertNumberValue(Buffer.prototype.writeInt8,1,_,T)}writeInt16BE(_,T){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,_,T)}insertInt16BE(_,T){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,_,T)}writeInt16LE(_,T){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,_,T)}insertInt16LE(_,T){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,_,T)}writeInt32BE(_,T){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,_,T)}insertInt32BE(_,T){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,_,T)}writeInt32LE(_,T){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,_,T)}insertInt32LE(_,T){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,_,T)}writeBigInt64BE(_,T){return t.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,_,T)}insertBigInt64BE(_,T){return t.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,_,T)}writeBigInt64LE(_,T){return t.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,_,T)}insertBigInt64LE(_,T){return t.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,_,T)}readUInt8(_){return this._readNumberValue(Buffer.prototype.readUInt8,1,_)}readUInt16BE(_){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,_)}readUInt16LE(_){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,_)}readUInt32BE(_){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,_)}readUInt32LE(_){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,_)}readBigUInt64BE(_){return t.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,_)}readBigUInt64LE(_){return t.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,_)}writeUInt8(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,_,T)}insertUInt8(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,_,T)}writeUInt16BE(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,_,T)}insertUInt16BE(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,_,T)}writeUInt16LE(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,_,T)}insertUInt16LE(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,_,T)}writeUInt32BE(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,_,T)}insertUInt32BE(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,_,T)}writeUInt32LE(_,T){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,_,T)}insertUInt32LE(_,T){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,_,T)}writeBigUInt64BE(_,T){return t.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,_,T)}insertBigUInt64BE(_,T){return t.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,_,T)}writeBigUInt64LE(_,T){return t.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,_,T)}insertBigUInt64LE(_,T){return t.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,_,T)}readFloatBE(_){return this._readNumberValue(Buffer.prototype.readFloatBE,4,_)}readFloatLE(_){return this._readNumberValue(Buffer.prototype.readFloatLE,4,_)}writeFloatBE(_,T){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,_,T)}insertFloatBE(_,T){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,_,T)}writeFloatLE(_,T){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,_,T)}insertFloatLE(_,T){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,_,T)}readDoubleBE(_){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,_)}readDoubleLE(_){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,_)}writeDoubleBE(_,T){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,_,T)}insertDoubleBE(_,T){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,_,T)}writeDoubleLE(_,T){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,_,T)}insertDoubleLE(_,T){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,_,T)}readString(_,T){let A;if(typeof _==="number")t.checkLengthValue(_),A=Math.min(_,this.length-this._readOffset);else T=_,A=this.length-this._readOffset;if(typeof T<"u")t.checkEncoding(T);let E=this._buff.slice(this._readOffset,this._readOffset+A).toString(T||this._encoding);return this._readOffset+=A,E}insertString(_,T,A){return t.checkOffsetValue(T),this._handleString(_,!0,T,A)}writeString(_,T,A){return this._handleString(_,!1,T,A)}readStringNT(_){if(typeof _<"u")t.checkEncoding(_);let T=this.length;for(let E=this._readOffset;E<this.length;E++)if(this._buff[E]===0){T=E;break}let A=this._buff.slice(this._readOffset,T);return this._readOffset=T+1,A.toString(_||this._encoding)}insertStringNT(_,T,A){return t.checkOffsetValue(T),this.insertString(_,T,A),this.insertUInt8(0,T+_.length),this}writeStringNT(_,T,A){return this.writeString(_,T,A),this.writeUInt8(0,typeof T==="number"?T+_.length:this.writeOffset),this}readBuffer(_){if(typeof _<"u")t.checkLengthValue(_);let T=typeof _==="number"?_:this.length,A=Math.min(this.length,this._readOffset+T),E=this._buff.slice(this._readOffset,A);return this._readOffset=A,E}insertBuffer(_,T){return t.checkOffsetValue(T),this._handleBuffer(_,!0,T)}writeBuffer(_,T){return this._handleBuffer(_,!1,T)}readBufferNT(){let _=this.length;for(let A=this._readOffset;A<this.length;A++)if(this._buff[A]===0){_=A;break}let T=this._buff.slice(this._readOffset,_);return this._readOffset=_+1,T}insertBufferNT(_,T){return t.checkOffsetValue(T),this.insertBuffer(_,T),this.insertUInt8(0,T+_.length),this}writeBufferNT(_,T){if(typeof T<"u")t.checkOffsetValue(T);return this.writeBuffer(_,T),this.writeUInt8(0,typeof T==="number"?T+_.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(_){t.checkOffsetValue(_),t.checkTargetOffset(_,this),this._readOffset=_}get writeOffset(){return this._writeOffset}set writeOffset(_){t.checkOffsetValue(_),t.checkTargetOffset(_,this),this._writeOffset=_}get encoding(){return this._encoding}set encoding(_){t.checkEncoding(_),this._encoding=_}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(_){let T=typeof _==="string"?_:this._encoding;return t.checkEncoding(T),this._buff.toString(T,0,this.length)}destroy(){return this.clear(),this}_handleString(_,T,A,E){let L=this._writeOffset,J=this._encoding;if(typeof A==="number")L=A;else if(typeof A==="string")t.checkEncoding(A),J=A;if(typeof E==="string")t.checkEncoding(E),J=E;let X=Buffer.byteLength(_,J);if(T)this.ensureInsertable(X,L);else this._ensureWriteable(X,L);if(this._buff.write(_,L,X,J),T)this._writeOffset+=X;else if(typeof A==="number")this._writeOffset=Math.max(this._writeOffset,L+X);else this._writeOffset+=X;return this}_handleBuffer(_,T,A){let E=typeof A==="number"?A:this._writeOffset;if(T)this.ensureInsertable(_.length,E);else this._ensureWriteable(_.length,E);if(_.copy(this._buff,E),T)this._writeOffset+=_.length;else if(typeof A==="number")this._writeOffset=Math.max(this._writeOffset,E+_.length);else this._writeOffset+=_.length;return this}ensureReadable(_,T){let A=this._readOffset;if(typeof T<"u")t.checkOffsetValue(T),A=T;if(A<0||A+_>this.length)throw Error(t.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(_,T){if(t.checkOffsetValue(T),this._ensureCapacity(this.length+_),T<this.length)this._buff.copy(this._buff,T+_,T,this._buff.length);if(T+_>this.length)this.length=T+_;else this.length+=_}_ensureWriteable(_,T){let A=typeof T==="number"?T:this._writeOffset;if(this._ensureCapacity(A+_),A+_>this.length)this.length=A+_}_ensureCapacity(_){let T=this._buff.length;if(_>T){let A=this._buff,E=T*3/2+1;if(E<_)E=_;this._buff=Buffer.allocUnsafe(E),A.copy(this._buff,0,0,T)}}_readNumberValue(_,T,A){this.ensureReadable(T,A);let E=_.call(this._buff,typeof A==="number"?A:this._readOffset);if(typeof A>"u")this._readOffset+=T;return E}_insertNumberValue(_,T,A,E){return t.checkOffsetValue(E),this.ensureInsertable(T,E),_.call(this._buff,A,E),this._writeOffset+=T,this}_writeNumberValue(_,T,A,E){if(typeof E==="number"){if(E<0)throw Error(t.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);t.checkOffsetValue(E)}let L=typeof E==="number"?E:this._writeOffset;if(this._ensureWriteable(T,L),_.call(this._buff,A,L),typeof E==="number")this._writeOffset=Math.max(this._writeOffset,L+T);else this._writeOffset+=T;return this}}gG.SmartBuffer=OL});var RL=W((iG)=>{Object.defineProperty(iG,"__esModule",{value:!0});iG.SOCKS5_NO_ACCEPTABLE_AUTH=iG.SOCKS5_CUSTOM_AUTH_END=iG.SOCKS5_CUSTOM_AUTH_START=iG.SOCKS_INCOMING_PACKET_SIZES=iG.SocksClientState=iG.Socks5Response=iG.Socks5HostType=iG.Socks5Auth=iG.Socks4Response=iG.SocksCommand=iG.ERRORS=iG.DEFAULT_TIMEOUT=void 0;var dS=30000;iG.DEFAULT_TIMEOUT=dS;var cS={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};iG.ERRORS=cS;var pS={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(_)=>_+7,Socks4Response:8};iG.SOCKS_INCOMING_PACKET_SIZES=pS;var uG;(function(_){_[_.connect=1]="connect",_[_.bind=2]="bind",_[_.associate=3]="associate"})(uG||(iG.SocksCommand=uG={}));var dG;(function(_){_[_.Granted=90]="Granted",_[_.Failed=91]="Failed",_[_.Rejected=92]="Rejected",_[_.RejectedIdent=93]="RejectedIdent"})(dG||(iG.Socks4Response=dG={}));var cG;(function(_){_[_.NoAuth=0]="NoAuth",_[_.GSSApi=1]="GSSApi",_[_.UserPass=2]="UserPass"})(cG||(iG.Socks5Auth=cG={}));var lS=128;iG.SOCKS5_CUSTOM_AUTH_START=lS;var nS=254;iG.SOCKS5_CUSTOM_AUTH_END=nS;var iS=255;iG.SOCKS5_NO_ACCEPTABLE_AUTH=iS;var pG;(function(_){_[_.Granted=0]="Granted",_[_.Failure=1]="Failure",_[_.NotAllowed=2]="NotAllowed",_[_.NetworkUnreachable=3]="NetworkUnreachable",_[_.HostUnreachable=4]="HostUnreachable",_[_.ConnectionRefused=5]="ConnectionRefused",_[_.TTLExpired=6]="TTLExpired",_[_.CommandNotSupported=7]="CommandNotSupported",_[_.AddressNotSupported=8]="AddressNotSupported"})(pG||(iG.Socks5Response=pG={}));var lG;(function(_){_[_.IPv4=1]="IPv4",_[_.Hostname=3]="Hostname",_[_.IPv6=4]="IPv6"})(lG||(iG.Socks5HostType=lG={}));var nG;(function(_){_[_.Created=0]="Created",_[_.Connecting=1]="Connecting",_[_.Connected=2]="Connected",_[_.SentInitialHandshake=3]="SentInitialHandshake",_[_.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",_[_.SentAuthentication=5]="SentAuthentication",_[_.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",_[_.SentFinalHandshake=7]="SentFinalHandshake",_[_.ReceivedFinalResponse=8]="ReceivedFinalResponse",_[_.BoundWaitingForConnection=9]="BoundWaitingForConnection",_[_.Established=10]="Established",_[_.Disconnected=11]="Disconnected",_[_.Error=99]="Error"})(nG||(iG.SocksClientState=nG={}))});var DL=W((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});rG.shuffleArray=rG.SocksClientError=void 0;class oG extends Error{constructor(_,T){super(_);this.options=T}}rG.SocksClientError=oG;function Jy(_){for(let T=_.length-1;T>0;T--){let A=Math.floor(Math.random()*(T+1));[_[T],_[A]]=[_[A],_[T]]}}rG.shuffleArray=Jy});var _5=W((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});eG.isInSubnet=Hy;eG.isCorrect=Zy;eG.numberToPaddedHex=tG;eG.stringToPaddedHex=Yy;eG.testBit=Ky;function Hy(_){if(this.subnetMask<_.subnetMask)return!1;if(this.mask(_.subnetMask)===_.mask())return!0;return!1}function Zy(_){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===_&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function tG(_){return _.toString(16).padStart(2,"0")}function Yy(_){return tG(parseInt(_,10))}function Ky(_,T){let{length:A}=_;if(T>A)return!1;let E=A-T;return _.substring(E,E+1)==="1"}});var BL=W((_U)=>{Object.defineProperty(_U,"__esModule",{value:!0});_U.RE_SUBNET_STRING=_U.RE_ADDRESS=_U.GROUPS=_U.BITS=void 0;_U.BITS=32;_U.GROUPS=4;_U.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;_U.RE_SUBNET_STRING=/\/\d{1,2}$/});var T5=W((EU)=>{Object.defineProperty(EU,"__esModule",{value:!0});EU.AddressError=void 0;class AU extends Error{constructor(_,T){super(_);this.name="AddressError",this.parseMessage=T}}EU.AddressError=AU});var qL=W((Q0)=>{var zy=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]}),Fy=Q0&&Q0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),JU=Q0&&Q0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))zy(T,_,A)}return Fy(T,_),T};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.Address4=void 0;var G4=JU(_5()),i1=JU(BL()),q8=T5();class U1{constructor(_){this.groups=i1.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=G4.isCorrect(i1.BITS),this.isInSubnet=G4.isInSubnet,this.address=_;let T=i1.RE_SUBNET_STRING.exec(_);if(T){if(this.parsedSubnet=T[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>i1.BITS)throw new q8.AddressError("Invalid subnet mask.");_=_.replace(i1.RE_SUBNET_STRING,"")}this.addressMinusSuffix=_,this.parsedAddress=this.parse(_)}static isValid(_){try{return new U1(_),!0}catch(T){return!1}}parse(_){let T=_.split(".");if(!_.match(i1.RE_ADDRESS))throw new q8.AddressError("Invalid IPv4 address.");return T}correctForm(){return this.parsedAddress.map((_)=>parseInt(_,10)).join(".")}static fromHex(_){let T=_.replace(/:/g,"").padStart(8,"0"),A=[],E;for(E=0;E<8;E+=2){let L=T.slice(E,E+2);A.push(parseInt(L,16))}return new U1(A.join("."))}static fromInteger(_){return U1.fromHex(_.toString(16))}static fromArpa(_){let A=_.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new U1(A)}toHex(){return this.parsedAddress.map((_)=>G4.stringToPaddedHex(_)).join(":")}toArray(){return this.parsedAddress.map((_)=>parseInt(_,10))}toGroup6(){let _=[],T;for(T=0;T<i1.GROUPS;T+=2)_.push(`${G4.stringToPaddedHex(this.parsedAddress[T])}${G4.stringToPaddedHex(this.parsedAddress[T+1])}`);return _.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map((_)=>G4.stringToPaddedHex(_)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(i1.BITS-this.subnetMask)}`)}startAddress(){return U1.fromBigInt(this._startAddress())}startAddressExclusive(){let _=BigInt("1");return U1.fromBigInt(this._startAddress()+_)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(i1.BITS-this.subnetMask)}`)}endAddress(){return U1.fromBigInt(this._endAddress())}endAddressExclusive(){let _=BigInt("1");return U1.fromBigInt(this._endAddress()-_)}static fromBigInt(_){return U1.fromHex(_.toString(16))}static fromByteArray(_){if(_.length!==4)throw new q8.AddressError("IPv4 addresses require exactly 4 bytes");for(let T=0;T<_.length;T++)if(!Number.isInteger(_[T])||_[T]<0||_[T]>255)throw new q8.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(_)}static fromUnsignedByteArray(_){if(_.length!==4)throw new q8.AddressError("IPv4 addresses require exactly 4 bytes");let T=_.join(".");return new U1(T)}mask(_){if(_===void 0)_=this.subnetMask;return this.getBitsBase2(0,_)}getBitsBase2(_,T){return this.binaryZeroPad().slice(_,T)}reverseForm(_){if(!_)_={};let T=this.correctForm().split(".").reverse().join(".");if(_.omitSuffix)return T;return`${T}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new U1("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(i1.BITS,"0")}groupForV6(){let _=this.parsedAddress;return this.address.replace(i1.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${_.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${_.slice(2,4).join(".")}</span>`)}}Q0.Address4=U1});var IL=W((XU)=>{Object.defineProperty(XU,"__esModule",{value:!0});XU.RE_URL_WITH_PORT=XU.RE_URL=XU.RE_ZONE_STRING=XU.RE_SUBNET_STRING=XU.RE_BAD_ADDRESS=XU.RE_BAD_CHARACTERS=XU.TYPES=XU.SCOPES=XU.GROUPS=XU.BITS=void 0;XU.BITS=128;XU.GROUPS=8;XU.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};XU.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"};XU.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;XU.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;XU.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;XU.RE_ZONE_STRING=/%.*$/;XU.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;XU.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var PL=W((KU)=>{Object.defineProperty(KU,"__esModule",{value:!0});KU.spanAllZeroes=ZU;KU.spanAll=xy;KU.spanLeadingZeroes=wy;KU.simpleGroup=Sy;function ZU(_){return _.replace(/(0+)/g,'<span class="zero">$1</span>')}function xy(_,T=0){return _.split("").map((E,L)=>`<span class="digit value-${E} position-${L+T}">${ZU(E)}</span>`).join("")}function YU(_){return _.replace(/^(0+)/,'<span class="zero">$1</span>')}function wy(_){return _.split(":").map((A)=>YU(A)).join(":")}function Sy(_,T=0){return _.split(":").map((E,L)=>{if(/group-v4/.test(E))return E;return`<span class="hover-group group-${L+T}">${YU(E)}</span>`})}});var $U=W((Y1)=>{var fy=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]}),by=Y1&&Y1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),gy=Y1&&Y1.__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 by(T,_),T};Object.defineProperty(Y1,"__esModule",{value:!0});Y1.ADDRESS_BOUNDARY=void 0;Y1.groupPossibilities=E5;Y1.padGroup=A5;Y1.simpleRegularExpression=uy;Y1.possibleElisions=dy;var my=gy(IL());function E5(_){return`(${_.join("|")})`}function A5(_){if(_.length<4)return`0{0,${4-_.length}}${_}`;return _}Y1.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function uy(_){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===my.GROUPS-1?":":"";return E5([A5(L),X])}return A5(L)}).join(":"));return A.push(_.map(A5).join(":")),E5(A)}function dy(_,T,A){let E=T?"":":",L=A?"":":",J=[];if(!T&&!A)J.push("::");if(T&&A)J.push("");if(A&&!T||!A&&T)J.push(":");J.push(`${E}(:0{1,4}){1,${_-1}}`),J.push(`(0{1,4}:){1,${_-1}}${L}`),J.push(`(0{1,4}:){${_-1}}0{1,4}`);for(let X=1;X<_-1;X++)for(let H=1;H<_-X;H++)J.push(`(0{1,4}:){${H}}:(0{1,4}:){${_-H-X-1}}0{1,4}`);return E5(J)}});var NU=W((M0)=>{var cy=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]}),py=M0&&M0.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),X5=M0&&M0.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))cy(T,_,A)}return py(T,_),T};Object.defineProperty(M0,"__esModule",{value:!0});M0.Address6=void 0;var GU=X5(_5()),jL=X5(BL()),N_=X5(IL()),xL=X5(PL()),vT=qL(),hT=$U(),b0=T5(),L5=_5();function J5(_){if(!_)throw Error("Assertion failed.")}function ly(_){let T=/(\d+)(\d{3})/;while(T.test(_))_=_.replace(T,"$1,$2");return _}function ny(_){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 iy(_,T){let A=[],E=[],L;for(L=0;L<_.length;L++)if(L<T[0])A.push(_[L]);else if(L>T[1])E.push(_[L]);return A.concat(["compact"]).concat(E)}function UU(_){return parseInt(_,16).toString(16).padStart(4,"0")}function WU(_){return _&255}class k_{constructor(_,T){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=GU.isInSubnet,this.isCorrect=GU.isCorrect(N_.BITS),T===void 0)this.groups=N_.GROUPS;else this.groups=T;this.address=_;let A=N_.RE_SUBNET_STRING.exec(_);if(A){if(this.parsedSubnet=A[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>N_.BITS)throw new b0.AddressError("Invalid subnet mask.");_=_.replace(N_.RE_SUBNET_STRING,"")}else if(/\//.test(_))throw new b0.AddressError("Invalid subnet mask.");let E=N_.RE_ZONE_STRING.exec(_);if(E)this.zone=E[0],_=_.replace(N_.RE_ZONE_STRING,"");this.addressMinusSuffix=_,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(_){try{return new k_(_),!0}catch(T){return!1}}static fromBigInt(_){let T=_.toString(16).padStart(32,"0"),A=[],E;for(E=0;E<N_.GROUPS;E++)A.push(T.slice(E*4,(E+1)*4));return new k_(A.join(":"))}static fromURL(_){let T,A=null,E;if(_.indexOf("[")!==-1&&_.indexOf("]:")!==-1){if(E=N_.RE_URL_WITH_PORT.exec(_),E===null)return{error:"failed to parse address with port",address:null,port:null};T=E[1],A=E[2]}else if(_.indexOf("/")!==-1){if(_=_.replace(/^[a-z0-9]+:\/\//,""),E=N_.RE_URL.exec(_),E===null)return{error:"failed to parse address from URL",address:null,port:null};T=E[1]}else T=_;if(A){if(A=parseInt(A,10),A<0||A>65536)A=null}else A=null;return{address:new k_(T),port:A}}static fromAddress4(_){let T=new vT.Address4(_),A=N_.BITS-(jL.BITS-T.subnetMask);return new k_(`::ffff:${T.correctForm()}/${A}`)}static fromArpa(_){let T=_.replace(/(\.ip6\.arpa)?\.$/,""),A=7;if(T.length!==63)throw new b0.AddressError("Invalid 'ip6.arpa' form.");let E=T.split(".").reverse();for(let L=A;L>0;L--){let J=L*4;E.splice(J,0,":")}return T=E.join(""),new k_(T)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(_=this.subnetMask){return this.getBitsBase2(0,_)}possibleSubnets(_=128){let T=N_.BITS-this.subnetMask,A=Math.abs(_-N_.BITS),E=T-A;if(E<0)return"0";return ly((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=iy(this.parsedAddress,E[X])}else T=this.parsedAddress;for(_=0;_<T.length;_++)if(T[_]!=="compact")T[_]=parseInt(T[_],16).toString(16);let J=T.join(":");return J=J.replace(/^compact$/,"::"),J=J.replace(/(^compact)|(compact$)/,":"),J=J.replace(/compact/,""),J}binaryZeroPad(){return this.bigInt().toString(2).padStart(N_.BITS,"0")}parse4in6(_){let T=_.split(":"),E=T.slice(-1)[0].match(jL.RE_ADDRESS);if(E){this.parsedAddress4=E[0],this.address4=new vT.Address4(this.parsedAddress4);for(let L=0;L<this.address4.groups;L++)if(/^0[0-9]+/.test(this.address4.parsedAddress[L]))throw new b0.AddressError("IPv4 addresses can't have leading zeroes.",_.replace(jL.RE_ADDRESS,this.address4.parsedAddress.map(ny).join(".")));this.v4=!0,T[T.length-1]=this.address4.toGroup6(),_=T.join(":")}return _}parse(_){_=this.parse4in6(_);let T=_.match(N_.RE_BAD_CHARACTERS);if(T)throw new b0.AddressError(`Bad character${T.length>1?"s":""} detected in address: ${T.join("")}`,_.replace(N_.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let A=_.match(N_.RE_BAD_ADDRESS);if(A)throw new b0.AddressError(`Address failed regex: ${A.join("")}`,_.replace(N_.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let E=[],L=_.split("::");if(L.length===2){let J=L[0].split(":"),X=L[1].split(":");if(J.length===1&&J[0]==="")J=[];if(X.length===1&&X[0]==="")X=[];let H=this.groups-(J.length+X.length);if(!H)throw new b0.AddressError("Error parsing groups");this.elidedGroups=H,this.elisionBegin=J.length,this.elisionEnd=J.length+this.elidedGroups,E=E.concat(J);for(let Z=0;Z<H;Z++)E.push("0");E=E.concat(X)}else if(L.length===1)E=_.split(":"),this.elidedGroups=0;else throw new b0.AddressError("Too many :: groups found");if(E=E.map((J)=>parseInt(J,16).toString(16)),E.length!==this.groups)throw new b0.AddressError("Incorrect number of groups found");return E}canonicalForm(){return this.parsedAddress.map(UU).join(":")}decimal(){return this.parsedAddress.map((_)=>parseInt(_,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(UU).join("")}`)}to4(){let _=this.binaryZeroPad().split("");return vT.Address4.fromHex(BigInt(`0b${_.slice(96,128).join("")}`).toString(16))}to4in6(){let _=this.to4(),A=new k_(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),E="";if(!/:$/.test(A))E=":";return A+E+_.address}inspectTeredo(){let _=this.getBitsBase16(0,32),A=(this.getBits(80,96)^BigInt("0xffff")).toString(),E=vT.Address4.fromHex(this.getBitsBase16(32,64)),L=this.getBits(96,128),J=vT.Address4.fromHex((L^BigInt("0xffffffff")).toString(16)),X=this.getBitsBase2(64,80),H=(0,L5.testBit)(X,15),Z=(0,L5.testBit)(X,14),Y=(0,L5.testBit)(X,8),K=(0,L5.testBit)(X,9),$=BigInt(`0b${X.slice(2,6)+X.slice(8,16)}`).toString(10);return{prefix:`${_.slice(0,4)}:${_.slice(4,8)}`,server4:E.address,client4:J.address,flags:X,coneNat:H,microsoft:{reserved:Z,universalLocal:K,groupIndividual:Y,nonce:$},udpPort:A}}inspect6to4(){let _=this.getBitsBase16(0,16),T=vT.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:_.slice(0,4),gateway:T.address}}to6to4(){if(!this.is4())return null;let _=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new k_(_)}toByteArray(){let _=this.bigInt().toString(16),A=`${"0".repeat(_.length%2)}${_}`,E=[];for(let L=0,J=A.length;L<J;L+=2)E.push(parseInt(A.substring(L,L+2),16));return E}toUnsignedByteArray(){return this.toByteArray().map(WU)}static fromByteArray(_){return this.fromUnsignedByteArray(_.map(WU))}static fromUnsignedByteArray(_){let T=BigInt("256"),A=BigInt("0"),E=BigInt("1");for(let L=_.length-1;L>=0;L--)A+=E*BigInt(_[L].toString(10)),E*=T;return k_.fromBigInt(A)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){if(this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000")return!0;return!1}isMulticast(){return this.getType()==="Multicast"}is4(){return this.v4}isTeredo(){return this.isInSubnet(new k_("2001::/32"))}is6to4(){return this.isInSubnet(new k_("2002::/16"))}isLoopback(){return this.getType()==="Loopback"}href(_){if(_===void 0)_="";else _=`:${_}`;return`http://[${this.correctForm()}]${_}/`}link(_){if(!_)_={};if(_.className===void 0)_.className="";if(_.prefix===void 0)_.prefix="/#address=";if(_.v4===void 0)_.v4=!1;let T=this.correctForm;if(_.v4)T=this.to4in6;let A=T.call(this);if(_.className)return`<a href="${_.prefix}${A}" class="${_.className}">${A}</a>`;return`<a href="${_.prefix}${A}">${A}</a>`}group(){if(this.elidedGroups===0)return xL.simpleGroup(this.address).join(":");J5(typeof this.elidedGroups==="number"),J5(typeof this.elisionBegin==="number");let _=[],[T,A]=this.address.split("::");if(T.length)_.push(...xL.simpleGroup(T));else _.push("");let E=["hover-group"];for(let L=this.elisionBegin;L<this.elisionBegin+this.elidedGroups;L++)E.push(`group-${L}`);if(_.push(`<span class="${E.join(" ")}"></span>`),A.length)_.push(...xL.simpleGroup(A,this.elisionEnd));else _.push("");if(this.is4())J5(this.address4 instanceof vT.Address4),_.pop(),_.push(this.address4.groupForV6());return _.join(":")}regularExpressionString(_=!1){let T=[],A=new k_(this.correctForm());if(A.elidedGroups===0)T.push((0,hT.simpleRegularExpression)(A.parsedAddress));else if(A.elidedGroups===N_.GROUPS)T.push((0,hT.possibleElisions)(N_.GROUPS));else{let E=A.address.split("::");if(E[0].length)T.push((0,hT.simpleRegularExpression)(E[0].split(":")));if(J5(typeof A.elidedGroups==="number"),T.push((0,hT.possibleElisions)(A.elidedGroups,E[0].length!==0,E[1].length!==0)),E[1].length)T.push((0,hT.simpleRegularExpression)(E[1].split(":")));T=[T.join(":")]}if(!_)T=["(?=^|",hT.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...T,")(?=[^\\w\\:]|",hT.ADDRESS_BOUNDARY,"|$)"];return T.join("")}regularExpression(_=!1){return new RegExp(this.regularExpressionString(_),"i")}}M0.Address6=k_});var wL=W((a_)=>{var ay=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]}),oy=a_&&a_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),ry=a_&&a_.__importStar||function(_){if(_&&_.__esModule)return _;var T={};if(_!=null){for(var A in _)if(A!=="default"&&Object.prototype.hasOwnProperty.call(_,A))ay(T,_,A)}return oy(T,_),T};Object.defineProperty(a_,"__esModule",{value:!0});a_.v6=a_.AddressError=a_.Address6=a_.Address4=void 0;var sy=qL();Object.defineProperty(a_,"Address4",{enumerable:!0,get:function(){return sy.Address4}});var ty=NU();Object.defineProperty(a_,"Address6",{enumerable:!0,get:function(){return ty.Address6}});var ey=T5();Object.defineProperty(a_,"AddressError",{enumerable:!0,get:function(){return ey.AddressError}});var _v=ry(PL());a_.v6={helpers:_v}});var RU=W((CU)=>{Object.defineProperty(CU,"__esModule",{value:!0});CU.ipToBuffer=CU.int32ToIpv4=CU.ipv4ToInt32=CU.validateSocksClientChainOptions=CU.validateSocksClientOptions=void 0;var _1=DL(),f_=RL(),Tv=I("stream"),SL=wL(),QU=I("net");function Av(_,T=["connect","bind","associate"]){if(!f_.SocksCommand[_.command])throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommand,_);if(T.indexOf(_.command)===-1)throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommandForOperation,_);if(!VU(_.destination))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsDestination,_);if(!zU(_.proxy))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);if(MU(_.proxy,_),_.timeout&&!FU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_);if(_.existing_socket&&!(_.existing_socket instanceof Tv.Duplex))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsExistingSocket,_)}CU.validateSocksClientOptions=Av;function Ev(_){if(_.command!=="connect")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksCommandChain,_);if(!VU(_.destination))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsDestination,_);if(!(_.proxies&&Array.isArray(_.proxies)&&_.proxies.length>=2))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxiesLength,_);if(_.proxies.forEach((T)=>{if(!zU(T))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsProxy,_);MU(T,_)}),_.timeout&&!FU(_.timeout))throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsTimeout,_)}CU.validateSocksClientChainOptions=Ev;function MU(_,T){if(_.custom_auth_method!==void 0){if(_.custom_auth_method<f_.SOCKS5_CUSTOM_AUTH_START||_.custom_auth_method>f_.SOCKS5_CUSTOM_AUTH_END)throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsCustomAuthRange,T);if(_.custom_auth_request_handler===void 0||typeof _.custom_auth_request_handler!=="function")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,T);if(_.custom_auth_response_size===void 0)throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,T);if(_.custom_auth_response_handler===void 0||typeof _.custom_auth_response_handler!=="function")throw new _1.SocksClientError(f_.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,T)}}function VU(_){return _&&typeof _.host==="string"&&Buffer.byteLength(_.host)<256&&typeof _.port==="number"&&_.port>=0&&_.port<=65535}function zU(_){return _&&(typeof _.host==="string"||typeof _.ipaddress==="string")&&typeof _.port==="number"&&_.port>=0&&_.port<=65535&&(_.type===4||_.type===5)}function FU(_){return typeof _==="number"&&_>0}function Lv(_){return new SL.Address4(_).toArray().reduce((A,E)=>(A<<8)+E,0)>>>0}CU.ipv4ToInt32=Lv;function Jv(_){let T=_>>>24&255,A=_>>>16&255,E=_>>>8&255,L=_&255;return[T,A,E,L].join(".")}CU.int32ToIpv4=Jv;function Xv(_){if(QU.isIPv4(_)){let T=new SL.Address4(_);return Buffer.from(T.toArray())}else if(QU.isIPv6(_)){let T=new SL.Address6(_);return Buffer.from(T.canonicalForm().split(":").map((A)=>A.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}CU.ipToBuffer=Xv});var IU=W((BU)=>{Object.defineProperty(BU,"__esModule",{value:!0});BU.ReceiveBuffer=void 0;class DU{constructor(_=4096){this.buffer=Buffer.allocUnsafe(_),this.offset=0,this.originalSize=_}get length(){return this.offset}append(_){if(!Buffer.isBuffer(_))throw Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+_.length>=this.buffer.length){let T=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+_.length)),T.copy(this.buffer)}return _.copy(this.buffer,this.offset),this.offset+=_.length}peek(_){if(_>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,_)}get(_){if(_>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");let T=Buffer.allocUnsafe(_);return this.buffer.slice(0,_).copy(T),this.buffer.copyWithin(0,_,_+this.offset-_),this.offset-=_,T}}BU.ReceiveBuffer=DU});var PU=W((TT)=>{var U4=TT&&TT.__awaiter||function(_,T,A,E){function L(J){return J instanceof A?J:new A(function(X){X(J)})}return new(A||(A=Promise))(function(J,X){function H(K){try{Y(E.next(K))}catch($){X($)}}function Z(K){try{Y(E.throw(K))}catch($){X($)}}function Y(K){K.done?J(K.value):L(K.value).then(H,Z)}Y((E=E.apply(_,T||[])).next())})};Object.defineProperty(TT,"__esModule",{value:!0});TT.SocksClientError=TT.SocksClient=void 0;var $v=I("events"),W4=I("net"),K1=mG(),P=RL(),W1=RU(),Gv=IU(),vL=DL();Object.defineProperty(TT,"SocksClientError",{enumerable:!0,get:function(){return vL.SocksClientError}});var yL=wL();class H5 extends $v.EventEmitter{constructor(_){super();this.options=Object.assign({},_),(0,W1.validateSocksClientOptions)(_),this.setState(P.SocksClientState.Created)}static createConnection(_,T){return new Promise((A,E)=>{try{(0,W1.validateSocksClientOptions)(_,["connect"])}catch(J){if(typeof T==="function")return T(J),A(J);else return E(J)}let L=new H5(_);L.connect(_.existing_socket),L.once("established",(J)=>{if(L.removeAllListeners(),typeof T==="function")T(null,J),A(J);else A(J)}),L.once("error",(J)=>{if(L.removeAllListeners(),typeof T==="function")T(J),A(J);else E(J)})})}static createConnectionChain(_,T){return new Promise((A,E)=>U4(this,void 0,void 0,function*(){try{(0,W1.validateSocksClientChainOptions)(_)}catch(L){if(typeof T==="function")return T(L),A(L);else return E(L)}if(_.randomizeChain)(0,vL.shuffleArray)(_.proxies);try{let L;for(let J=0;J<_.proxies.length;J++){let X=_.proxies[J],H=J===_.proxies.length-1?_.destination:{host:_.proxies[J+1].host||_.proxies[J+1].ipaddress,port:_.proxies[J+1].port},Z=yield H5.createConnection({command:"connect",proxy:X,destination:H,existing_socket:L});L=L||Z.socket}if(typeof T==="function")T(null,{socket:L}),A({socket:L});else A({socket:L})}catch(L){if(typeof T==="function")T(L),A(L);else E(L)}}))}static createUDPFrame(_){let T=new K1.SmartBuffer;if(T.writeUInt16BE(0),T.writeUInt8(_.frameNumber||0),W4.isIPv4(_.remoteHost.host))T.writeUInt8(P.Socks5HostType.IPv4),T.writeUInt32BE((0,W1.ipv4ToInt32)(_.remoteHost.host));else if(W4.isIPv6(_.remoteHost.host))T.writeUInt8(P.Socks5HostType.IPv6),T.writeBuffer((0,W1.ipToBuffer)(_.remoteHost.host));else T.writeUInt8(P.Socks5HostType.Hostname),T.writeUInt8(Buffer.byteLength(_.remoteHost.host)),T.writeString(_.remoteHost.host);return T.writeUInt16BE(_.remoteHost.port),T.writeBuffer(_.data),T.toBuffer()}static parseUDPFrame(_){let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A=T.readUInt8(),E=T.readUInt8(),L;if(E===P.Socks5HostType.IPv4)L=(0,W1.int32ToIpv4)(T.readUInt32BE());else if(E===P.Socks5HostType.IPv6)L=yL.Address6.fromByteArray(Array.from(T.readBuffer(16))).canonicalForm();else L=T.readString(T.readUInt8());let J=T.readUInt16BE();return{frameNumber:A,remoteHost:{host:L,port:J},data:T.readBuffer()}}setState(_){if(this.state!==P.SocksClientState.Error)this.state=_}connect(_){this.onDataReceived=(A)=>this.onDataReceivedHandler(A),this.onClose=()=>this.onCloseHandler(),this.onError=(A)=>this.onErrorHandler(A),this.onConnect=()=>this.onConnectHandler();let T=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||P.DEFAULT_TIMEOUT);if(T.unref&&typeof T.unref==="function")T.unref();if(_)this.socket=_;else this.socket=new W4.Socket;if(this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(P.SocksClientState.Connecting),this.receiveBuffer=new Gv.ReceiveBuffer,_)this.socket.emit("connect");else if(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null)this.socket.setNoDelay(!!this.options.set_tcp_nodelay);this.prependOnceListener("established",(A)=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let E=this.receiveBuffer.get(this.receiveBuffer.length);A.socket.emit("data",E)}A.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){if(this.state!==P.SocksClientState.Established&&this.state!==P.SocksClientState.BoundWaitingForConnection)this.closeSocket(P.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){if(this.setState(P.SocksClientState.Connected),this.options.proxy.type===4)this.sendSocks4InitialHandshake();else this.sendSocks5InitialHandshake();this.setState(P.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(_){this.receiveBuffer.append(_),this.processData()}processData(){while(this.state!==P.SocksClientState.Established&&this.state!==P.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize)if(this.state===P.SocksClientState.SentInitialHandshake)if(this.options.proxy.type===4)this.handleSocks4FinalHandshakeResponse();else this.handleInitialSocks5HandshakeResponse();else if(this.state===P.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===P.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===P.SocksClientState.BoundWaitingForConnection)if(this.options.proxy.type===4)this.handleSocks4IncomingConnectionResponse();else this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(P.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(P.ERRORS.SocketClosed)}onErrorHandler(_){this.closeSocket(_.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(_){if(this.state!==P.SocksClientState.Error)this.setState(P.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new vL.SocksClientError(_,this.options))}sendSocks4InitialHandshake(){let _=this.options.proxy.userId||"",T=new K1.SmartBuffer;if(T.writeUInt8(4),T.writeUInt8(P.SocksCommand[this.options.command]),T.writeUInt16BE(this.options.destination.port),W4.isIPv4(this.options.destination.host))T.writeBuffer((0,W1.ipToBuffer)(this.options.destination.host)),T.writeStringNT(_);else T.writeUInt8(0),T.writeUInt8(0),T.writeUInt8(0),T.writeUInt8(1),T.writeStringNT(_),T.writeStringNT(this.options.destination.host);this.nextRequiredPacketBufferSize=P.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(T.toBuffer())}handleSocks4FinalHandshakeResponse(){let _=this.receiveBuffer.get(8);if(_[1]!==P.Socks4Response.Granted)this.closeSocket(`${P.ERRORS.Socks4ProxyRejectedConnection} - (${P.Socks4Response[_[1]]})`);else if(P.SocksCommand[this.options.command]===P.SocksCommand.bind){let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A={port:T.readUInt16BE(),host:(0,W1.int32ToIpv4)(T.readUInt32BE())};if(A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress;this.setState(P.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:A,socket:this.socket})}else this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let _=this.receiveBuffer.get(8);if(_[1]!==P.Socks4Response.Granted)this.closeSocket(`${P.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${P.Socks4Response[_[1]]})`);else{let T=K1.SmartBuffer.fromBuffer(_);T.readOffset=2;let A={port:T.readUInt16BE(),host:(0,W1.int32ToIpv4)(T.readUInt32BE())};this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}sendSocks5InitialHandshake(){let _=new K1.SmartBuffer,T=[P.Socks5Auth.NoAuth];if(this.options.proxy.userId||this.options.proxy.password)T.push(P.Socks5Auth.UserPass);if(this.options.proxy.custom_auth_method!==void 0)T.push(this.options.proxy.custom_auth_method);_.writeUInt8(5),_.writeUInt8(T.length);for(let A of T)_.writeUInt8(A);this.nextRequiredPacketBufferSize=P.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(_.toBuffer()),this.setState(P.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let _=this.receiveBuffer.get(2);if(_[0]!==5)this.closeSocket(P.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);else if(_[1]===P.SOCKS5_NO_ACCEPTABLE_AUTH)this.closeSocket(P.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);else if(_[1]===P.Socks5Auth.NoAuth)this.socks5ChosenAuthType=P.Socks5Auth.NoAuth,this.sendSocks5CommandRequest();else if(_[1]===P.Socks5Auth.UserPass)this.socks5ChosenAuthType=P.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication();else if(_[1]===this.options.proxy.custom_auth_method)this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication();else this.closeSocket(P.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let _=this.options.proxy.userId||"",T=this.options.proxy.password||"",A=new K1.SmartBuffer;A.writeUInt8(1),A.writeUInt8(Buffer.byteLength(_)),A.writeString(_),A.writeUInt8(Buffer.byteLength(T)),A.writeString(T),this.nextRequiredPacketBufferSize=P.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(A.toBuffer()),this.setState(P.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return U4(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(P.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(_)})}handleSocks5AuthenticationNoAuthHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return _[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(_){return U4(this,void 0,void 0,function*(){return _[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return U4(this,void 0,void 0,function*(){this.setState(P.SocksClientState.ReceivedAuthenticationResponse);let _=!1;if(this.socks5ChosenAuthType===P.Socks5Auth.NoAuth)_=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===P.Socks5Auth.UserPass)_=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===this.options.proxy.custom_auth_method)_=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));if(!_)this.closeSocket(P.ERRORS.Socks5AuthenticationFailed);else this.sendSocks5CommandRequest()})}sendSocks5CommandRequest(){let _=new K1.SmartBuffer;if(_.writeUInt8(5),_.writeUInt8(P.SocksCommand[this.options.command]),_.writeUInt8(0),W4.isIPv4(this.options.destination.host))_.writeUInt8(P.Socks5HostType.IPv4),_.writeBuffer((0,W1.ipToBuffer)(this.options.destination.host));else if(W4.isIPv6(this.options.destination.host))_.writeUInt8(P.Socks5HostType.IPv6),_.writeBuffer((0,W1.ipToBuffer)(this.options.destination.host));else _.writeUInt8(P.Socks5HostType.Hostname),_.writeUInt8(this.options.destination.host.length),_.writeString(this.options.destination.host);_.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(_.toBuffer()),this.setState(P.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let _=this.receiveBuffer.peek(5);if(_[0]!==5||_[1]!==P.Socks5Response.Granted)this.closeSocket(`${P.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${P.Socks5Response[_[1]]}`);else{let T=_[3],A,E;if(T===P.Socks5HostType.IPv4){let L=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}if(E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:(0,W1.int32ToIpv4)(E.readUInt32BE()),port:E.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if(T===P.Socks5HostType.Hostname){let L=_[4],J=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(L);if(this.receiveBuffer.length<J){this.nextRequiredPacketBufferSize=J;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(J).slice(5)),A={host:E.readString(L),port:E.readUInt16BE()}}else if(T===P.Socks5HostType.IPv6){let L=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:yL.Address6.fromByteArray(Array.from(E.readBuffer(16))).canonicalForm(),port:E.readUInt16BE()}}if(this.setState(P.SocksClientState.ReceivedFinalResponse),P.SocksCommand[this.options.command]===P.SocksCommand.connect)this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket});else if(P.SocksCommand[this.options.command]===P.SocksCommand.bind)this.setState(P.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:A,socket:this.socket});else if(P.SocksCommand[this.options.command]===P.SocksCommand.associate)this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}handleSocks5IncomingConnectionResponse(){let _=this.receiveBuffer.peek(5);if(_[0]!==5||_[1]!==P.Socks5Response.Granted)this.closeSocket(`${P.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${P.Socks5Response[_[1]]}`);else{let T=_[3],A,E;if(T===P.Socks5HostType.IPv4){let L=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}if(E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:(0,W1.int32ToIpv4)(E.readUInt32BE()),port:E.readUInt16BE()},A.host==="0.0.0.0")A.host=this.options.proxy.ipaddress}else if(T===P.Socks5HostType.Hostname){let L=_[4],J=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(L);if(this.receiveBuffer.length<J){this.nextRequiredPacketBufferSize=J;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(J).slice(5)),A={host:E.readString(L),port:E.readUInt16BE()}}else if(T===P.Socks5HostType.IPv6){let L=P.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<L){this.nextRequiredPacketBufferSize=L;return}E=K1.SmartBuffer.fromBuffer(this.receiveBuffer.get(L).slice(4)),A={host:yL.Address6.fromByteArray(Array.from(E.readBuffer(16))).canonicalForm(),port:E.readUInt16BE()}}this.setState(P.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:A,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}TT.SocksClient=H5});var jU=W((kT)=>{var Uv=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]}),Wv=kT&&kT.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))Uv(T,_,A)};Object.defineProperty(kT,"__esModule",{value:!0});Wv(PU(),kT)});var kL=W((a1)=>{var Nv=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]}),Qv=a1&&a1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Mv=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")Nv(A,T,E[L])}return Qv(A,T),A}}(),xU=a1&&a1.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(a1,"__esModule",{value:!0});a1.default=qv;var Vv=xU(d1()),zv=I("stream"),Fv=jU(),Cv=Mv(I("dns")),Ov=I("util"),hL=xU(I("assert")),g0=(0,Vv.default)("mqttjs:socks");class wU extends zv.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(_){if(g0("proxy stream started"),(0,hL.default)(!this._socket),this.destroyed){_.destroy(this.errored);return}if(this._socket=_,!this._flowing)_.pause();_.on("data",this._onData),_.on("end",this._onEnd),_.on("error",this._onError),_.on("close",this._onClose),_.emit("connect"),this.uncork()}_write(_,T,A){(0,hL.default)(this._socket),this._socket.write(_,A)}_read(_){this._flowing=!0,this._socket?.resume?.()}_destroy(_,T){this._socket?.destroy?.(_),T(_)}_onData=(_)=>{if((0,hL.default)(this._socket),this._flowing=this.push(_),!this._flowing)this._socket.pause()};_onEnd=()=>{g0("proxy stream received EOF"),this.push(null)};_onClose=()=>{g0("proxy stream closed"),this.destroy()};_onError=(_)=>{g0("proxy stream died with error %s",_),this.destroy(_)}}function Z5(_){try{if(_.code===void 0)_.code="SOCKS";return _}catch{return _}}function Rv(_){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 Dv(_){let T=new URL(_);if(T.pathname||T.hash||T.search)throw Z5(Error("bad SOCKS URL"));let[A,E]=Rv(T.protocol);if(!A)throw Z5(Error("bad SOCKS URL: invalid protocol"));let L=parseInt(T.port,10);if(Number.isNaN(L))throw Z5(Error("bad SOCKS URL: invalid port"));return[{host:T.hostname,port:L,type:A},E]}async function Bv(_,T,A,E,L={}){let J=L.lookup??(0,Ov.promisify)(Cv.lookup),[X,H]=Dv(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 Fv.SocksClient({command:"connect",destination:{host:_,port:T},proxy:{...X},timeout:L.timeout});Z.connect(),Z.on("established",({socket:Y})=>E._start(Y)),Z.on("error",(Y)=>{g0("SOCKS failed: %s",Y),E.destroy(Z5(Y))})}function qv(_,T,A,E){g0("SOCKS connection to %s:%d via %s",_,T,A);let L=new wU;return Bv(_,T,A,L,E).catch((J)=>{g0("SOCKS failed: %s",J),L.destroy(J)}),L}});var bL=W((I8)=>{var fL=I8&&I8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(I8,"__esModule",{value:!0});var Iv=fL(I("net")),Pv=fL(d1()),jv=fL(kL()),xv=(0,Pv.default)("mqttjs:tcp"),wv=(_,T)=>{if(T.port=T.port||1883,T.hostname=T.hostname||T.host||"localhost",T.socksProxy)return(0,jv.default)(T.hostname,T.port,T.socksProxy,{timeout:T.socksTimeout});let{port:A,path:E}=T,L=T.hostname;return xv("port %d and host %s",A,L),Iv.default.createConnection({port:A,host:L,path:E})};I8.default=wv});var mL=W((P8)=>{var gL=P8&&P8.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(P8,"__esModule",{value:!0});var SU=I("tls"),Sv=gL(I("net")),yv=gL(d1()),vv=gL(kL()),hv=(0,yv.default)("mqttjs:tls");function kv(_){let{host:T,port:A,socksProxy:E,...L}=_;if(E!==void 0){let J=(0,vv.default)(T,A,E,{timeout:_.socksTimeout});return(0,SU.connect)({...L,socket:J})}return(0,SU.connect)(_)}var fv=(_,T)=>{if(T.port=T.port||8883,T.host=T.hostname||T.host||"localhost",Sv.default.isIP(T.host)===0)T.servername=T.host;T.rejectUnauthorized=T.rejectUnauthorized!==!1,delete T.path,hv("port %d host %s rejectUnauthorized %b",T.port,T.host,T.rejectUnauthorized);let A=kv(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=fv});var dL=W((vU)=>{Object.defineProperty(vU,"__esModule",{value:!0});var yU=I("buffer"),bv=n0(),gv=tA(),V0,uL,N1;function mv(){let _=new bv.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 uv(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function dv(_,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 cv(){V0.onOpen(()=>{N1.socketReady()}),V0.onMessage((_)=>{let{data:T}=_;if(T instanceof ArrayBuffer)T=yU.Buffer.from(T);else T=yU.Buffer.from(T,"utf8");uL.push(T)}),V0.onClose(()=>{N1.emit("close"),N1.end(),N1.destroy()}),V0.onError((_)=>{let T=Error(_.errMsg);N1.destroy(T)})}var pv=(_,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";uv(T);let E=dv(T,_);V0=wx.connectSocket({url:E,protocols:[A]}),uL=mv(),N1=new gv.BufferedDuplex(T,uL,V0),N1._destroy=(J,X)=>{V0.close({success(){if(X)X(J)}})};let L=N1.destroy;return N1.destroy=(J,X)=>{return N1.destroy=L,setTimeout(()=>{V0.close({fail(){N1._destroy(J,X)}})},0),N1},cv(),N1};vU.default=pv});var pL=W((kU)=>{Object.defineProperty(kU,"__esModule",{value:!0});var cL=I("buffer"),nv=n0(),iv=tA(),m0,j8,N4,hU=!1;function av(){let _=new nv.Transform;return _._write=(T,A,E)=>{m0.sendSocketMessage({data:T.buffer,success(){E()},fail(){E(Error())}})},_._flush=(T)=>{m0.closeSocket({success(){T()}})},_}function ov(_){if(!_.hostname)_.hostname="localhost";if(!_.path)_.path="/";if(!_.wsOptions)_.wsOptions={}}function rv(_,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 sv(){if(hU)return;hU=!0,m0.onSocketOpen(()=>{N4.socketReady()}),m0.onSocketMessage((_)=>{if(typeof _.data==="string"){let T=cL.Buffer.from(_.data,"base64");j8.push(T)}else{let T=new FileReader;T.addEventListener("load",()=>{if(T.result instanceof ArrayBuffer){j8.push(cL.Buffer.from(T.result));return}j8.push(cL.Buffer.from(T.result,"utf-8"))}),T.readAsArrayBuffer(_.data)}}),m0.onSocketClose(()=>{N4.end(),N4.destroy()}),m0.onSocketError((_)=>{N4.destroy(_)})}var tv=(_,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";ov(T);let E=rv(T,_);return m0=T.my,m0.connectSocket({url:E,protocols:A}),j8=av(),N4=new iv.BufferedDuplex(T,j8,m0),sv(),N4};kU.default=tv});var mU=W((Q4)=>{var Y5=Q4&&Q4.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(Q4,"__esModule",{value:!0});Q4.connectAsync=Lh;var _h=Y5(d1()),Th=Y5(I("url")),Ah=Y5(sA()),fU=Y5(O8());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var bU=(0,_h.default)("mqttjs"),y_=null;function Eh(_){let T;if(_.auth)if(T=_.auth.match(/^(.+):(.+)$/),T){let[,A,E]=T;_.username=A,_.password=E}else _.username=_.auth}function gU(_,T){if(bU("connecting to an MQTT broker..."),typeof _==="object"&&!T)T=_,_="";if(T=T||{},_&&typeof _==="string"){let L=Th.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(Eh(T),T.query&&typeof T.query.clientId==="string")T.clientId=T.query.clientId;if(fU.default||T.unixSocket)T.socksProxy=void 0;else if(T.socksProxy===void 0&&typeof process<"u")T.socksProxy=process.env.MQTTJS_SOCKS_PROXY;if(T.cert&&T.key)if(T.protocol){if(["mqtts","wss","wxs","alis"].indexOf(T.protocol)===-1)switch(T.protocol){case"mqtt":T.protocol="mqtts";break;case"ws":T.protocol="wss";break;case"wx":T.protocol="wxs";break;case"ali":T.protocol="alis";break;default:throw Error(`Unknown protocol for secure connection: "${T.protocol}"!`)}}else throw Error("Missing secure protocol key");if(!y_)if(y_={},!fU.default&&!T.forceNativeWebSocket)y_.ws=B8().streamBuilder,y_.wss=B8().streamBuilder,y_.mqtt=bL().default,y_.tcp=bL().default,y_.ssl=mL().default,y_.tls=y_.ssl,y_.mqtts=mL().default;else y_.ws=B8().browserStreamBuilder,y_.wss=B8().browserStreamBuilder,y_.wx=dL().default,y_.wxs=dL().default,y_.ali=pL().default,y_.alis=pL().default;if(!y_[T.protocol]){let L=["mqtts","wss"].indexOf(T.protocol)!==-1;T.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((J,X)=>{if(L&&X%2===0)return!1;return typeof y_[J]==="function"})[0]}if(T.clean===!1&&!T.clientId)throw Error("Missing clientId for unclean clients");if(T.protocol)T.defaultProtocol=T.protocol;function A(L){if(T.servers){if(!L._reconnectCount||L._reconnectCount===T.servers.length)L._reconnectCount=0;T.host=T.servers[L._reconnectCount].host,T.port=T.servers[L._reconnectCount].port,T.protocol=!T.servers[L._reconnectCount].protocol?T.defaultProtocol:T.servers[L._reconnectCount].protocol,T.hostname=T.host,L._reconnectCount++}return bU("calling streambuilder for",T.protocol),y_[T.protocol](L,T)}let E=new Ah.default(A,T);return E.on("error",()=>{}),E}function Lh(_,T,A=!0){return new Promise((E,L)=>{let J=gU(_,T),X={connect:(Z)=>{H(),E(J)},end:()=>{H(),E(J)},error:(Z)=>{H(),J.end(),L(Z)}};if(A===!1)X.close=()=>{X.error(Error("Couldn't connect to server"))};function H(){Object.keys(X).forEach((Z)=>{J.off(Z,X[Z])})}Object.keys(X).forEach((Z)=>{J.on(Z,X[Z])})})}Q4.default=gU});var lL=W((Z_)=>{var uU=Z_&&Z_.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),Jh=Z_&&Z_.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Xh=Z_&&Z_.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")uU(A,T,E[L])}return Jh(A,T),A}}(),dU=Z_&&Z_.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))uU(T,_,A)},x8=Z_&&Z_.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(Z_,"__esModule",{value:!0});Z_.ReasonCodes=Z_.KeepaliveManager=Z_.UniqueMessageIdProvider=Z_.DefaultMessageIdProvider=Z_.Store=Z_.MqttClient=Z_.connectAsync=Z_.connect=Z_.Client=void 0;var cU=x8(sA());Z_.MqttClient=cU.default;var Hh=x8(LL());Z_.DefaultMessageIdProvider=Hh.default;var Zh=x8(DG());Z_.UniqueMessageIdProvider=Zh.default;var Yh=x8(pE());Z_.Store=Yh.default;var pU=Xh(mU());Z_.connect=pU.default;Object.defineProperty(Z_,"connectAsync",{enumerable:!0,get:function(){return pU.connectAsync}});var Kh=x8(ML());Z_.KeepaliveManager=Kh.default;Z_.Client=cU.default;dU(sA(),Z_);dU(qT(),Z_);var $h=e4();Object.defineProperty(Z_,"ReasonCodes",{enumerable:!0,get:function(){return $h.ReasonCodes}})});var nU=W((I1)=>{var lU=I1&&I1.__createBinding||(Object.create?function(_,T,A,E){if(E===void 0)E=A;var L=Object.getOwnPropertyDescriptor(T,A);if(!L||("get"in L?!T.__esModule:L.writable||L.configurable))L={enumerable:!0,get:function(){return T[A]}};Object.defineProperty(_,E,L)}:function(_,T,A,E){if(E===void 0)E=A;_[E]=T[A]}),Gh=I1&&I1.__setModuleDefault||(Object.create?function(_,T){Object.defineProperty(_,"default",{enumerable:!0,value:T})}:function(_,T){_.default=T}),Uh=I1&&I1.__importStar||function(){var _=function(T){return _=Object.getOwnPropertyNames||function(A){var E=[];for(var L in A)if(Object.prototype.hasOwnProperty.call(A,L))E[E.length]=L;return E},_(T)};return function(T){if(T&&T.__esModule)return T;var A={};if(T!=null){for(var E=_(T),L=0;L<E.length;L++)if(E[L]!=="default")lU(A,T,E[L])}return Gh(A,T),A}}(),Wh=I1&&I1.__exportStar||function(_,T){for(var A in _)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(T,A))lU(T,_,A)};Object.defineProperty(I1,"__esModule",{value:!0});var Nh=Uh(lL());I1.default=Nh;Wh(lL(),I1)});var rL=W((wu,eU)=>{eU.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var AW=W((Su,TW)=>{var Oh=rL();function _W(_){this.mode=Oh.MODE_8BIT_BYTE,this.data=_}_W.prototype={getLength:function(){return this.data.length},write:function(_){for(var T=0;T<this.data.length;T++)_.put(this.data.charCodeAt(T),8)}};TW.exports=_W});var sL=W((yu,EW)=>{var o1={glog:function(_){if(_<1)throw Error("glog("+_+")");return o1.LOG_TABLE[_]},gexp:function(_){while(_<0)_+=255;while(_>=256)_-=255;return o1.EXP_TABLE[_]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(R_=0;R_<8;R_++)o1.EXP_TABLE[R_]=1<<R_;var R_;for(R_=8;R_<256;R_++)o1.EXP_TABLE[R_]=o1.EXP_TABLE[R_-4]^o1.EXP_TABLE[R_-5]^o1.EXP_TABLE[R_-6]^o1.EXP_TABLE[R_-8];var R_;for(R_=0;R_<255;R_++)o1.LOG_TABLE[o1.EXP_TABLE[R_]]=R_;var R_;EW.exports=o1});var tL=W((vu,LW)=>{var fT=sL();function N5(_,T){if(_.length===void 0)throw Error(_.length+"/"+T);var A=0;while(A<_.length&&_[A]===0)A++;this.num=Array(_.length-A+T);for(var E=0;E<_.length-A;E++)this.num[E]=_[E+A]}N5.prototype={get:function(_){return this.num[_]},getLength:function(){return this.num.length},multiply:function(_){var T=Array(this.getLength()+_.getLength()-1);for(var A=0;A<this.getLength();A++)for(var E=0;E<_.getLength();E++)T[A+E]^=fT.gexp(fT.glog(this.get(A))+fT.glog(_.get(E)));return new N5(T,0)},mod:function(_){if(this.getLength()-_.getLength()<0)return this;var T=fT.glog(this.get(0))-fT.glog(_.get(0)),A=Array(this.getLength());for(var E=0;E<this.getLength();E++)A[E]=this.get(E);for(var L=0;L<_.getLength();L++)A[L]^=fT.gexp(fT.glog(_.get(L))+T);return new N5(A,0).mod(_)}};LW.exports=N5});var XW=W((hu,JW)=>{JW.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var YW=W((ku,ZW)=>{var j1=rL(),HW=tL(),Rh=sL(),AT=XW(),u_={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(_){var T=_<<10;while(u_.getBCHDigit(T)-u_.getBCHDigit(u_.G15)>=0)T^=u_.G15<<u_.getBCHDigit(T)-u_.getBCHDigit(u_.G15);return(_<<10|T)^u_.G15_MASK},getBCHTypeNumber:function(_){var T=_<<12;while(u_.getBCHDigit(T)-u_.getBCHDigit(u_.G18)>=0)T^=u_.G18<<u_.getBCHDigit(T)-u_.getBCHDigit(u_.G18);return _<<12|T},getBCHDigit:function(_){var T=0;while(_!==0)T++,_>>>=1;return T},getPatternPosition:function(_){return u_.PATTERN_POSITION_TABLE[_-1]},getMask:function(_,T,A){switch(_){case AT.PATTERN000:return(T+A)%2===0;case AT.PATTERN001:return T%2===0;case AT.PATTERN010:return A%3===0;case AT.PATTERN011:return(T+A)%3===0;case AT.PATTERN100:return(Math.floor(T/2)+Math.floor(A/3))%2===0;case AT.PATTERN101:return T*A%2+T*A%3===0;case AT.PATTERN110:return(T*A%2+T*A%3)%2===0;case AT.PATTERN111:return(T*A%3+(T+A)%2)%2===0;default:throw Error("bad maskPattern:"+_)}},getErrorCorrectPolynomial:function(_){var T=new HW([1],0);for(var A=0;A<_;A++)T=T.multiply(new HW([1,Rh.gexp(A)],0));return T},getLengthInBits:function(_,T){if(1<=T&&T<10)switch(_){case j1.MODE_NUMBER:return 10;case j1.MODE_ALPHA_NUM:return 9;case j1.MODE_8BIT_BYTE:return 8;case j1.MODE_KANJI:return 8;default:throw Error("mode:"+_)}else if(T<27)switch(_){case j1.MODE_NUMBER:return 12;case j1.MODE_ALPHA_NUM:return 11;case j1.MODE_8BIT_BYTE:return 16;case j1.MODE_KANJI:return 10;default:throw Error("mode:"+_)}else if(T<41)switch(_){case j1.MODE_NUMBER:return 14;case j1.MODE_ALPHA_NUM:return 13;case j1.MODE_8BIT_BYTE:return 16;case j1.MODE_KANJI:return 12;default:throw Error("mode:"+_)}else throw Error("type:"+T)},getLostPoint:function(_){var T=_.getModuleCount(),A=0,E=0,L=0;for(E=0;E<T;E++)for(L=0;L<T;L++){var J=0,X=_.isDark(E,L);for(var H=-1;H<=1;H++){if(E+H<0||T<=E+H)continue;for(var Z=-1;Z<=1;Z++){if(L+Z<0||T<=L+Z)continue;if(H===0&&Z===0)continue;if(X===_.isDark(E+H,L+Z))J++}}if(J>5)A+=3+J-5}for(E=0;E<T-1;E++)for(L=0;L<T-1;L++){var Y=0;if(_.isDark(E,L))Y++;if(_.isDark(E+1,L))Y++;if(_.isDark(E,L+1))Y++;if(_.isDark(E+1,L+1))Y++;if(Y===0||Y===4)A+=3}for(E=0;E<T;E++)for(L=0;L<T-6;L++)if(_.isDark(E,L)&&!_.isDark(E,L+1)&&_.isDark(E,L+2)&&_.isDark(E,L+3)&&_.isDark(E,L+4)&&!_.isDark(E,L+5)&&_.isDark(E,L+6))A+=40;for(L=0;L<T;L++)for(E=0;E<T-6;E++)if(_.isDark(E,L)&&!_.isDark(E+1,L)&&_.isDark(E+2,L)&&_.isDark(E+3,L)&&_.isDark(E+4,L)&&!_.isDark(E+5,L)&&_.isDark(E+6,L))A+=40;var K=0;for(L=0;L<T;L++)for(E=0;E<T;E++)if(_.isDark(E,L))K++;var $=Math.abs(100*K/T/T-50)/5;return A+=$*10,A}};ZW.exports=u_});var eL=W((fu,KW)=>{KW.exports={L:1,M:0,Q:3,H:2}});var GW=W((bu,$W)=>{var Q5=eL();function z0(_,T){this.totalCount=_,this.dataCount=T}z0.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];z0.getRSBlocks=function(_,T){var A=z0.getRsBlockTable(_,T);if(A===void 0)throw Error("bad rs block @ typeNumber:"+_+"/errorCorrectLevel:"+T);var E=A.length/3,L=[];for(var J=0;J<E;J++){var X=A[J*3+0],H=A[J*3+1],Z=A[J*3+2];for(var Y=0;Y<X;Y++)L.push(new z0(H,Z))}return L};z0.getRsBlockTable=function(_,T){switch(T){case Q5.L:return z0.RS_BLOCK_TABLE[(_-1)*4+0];case Q5.M:return z0.RS_BLOCK_TABLE[(_-1)*4+1];case Q5.Q:return z0.RS_BLOCK_TABLE[(_-1)*4+2];case Q5.H:return z0.RS_BLOCK_TABLE[(_-1)*4+3];default:return}};$W.exports=z0});var NW=W((gu,WW)=>{function UW(){this.buffer=[],this.length=0}UW.prototype={get:function(_){var T=Math.floor(_/8);return(this.buffer[T]>>>7-_%8&1)==1},put:function(_,T){for(var A=0;A<T;A++)this.putBit((_>>>T-A-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(_){var T=Math.floor(this.length/8);if(this.buffer.length<=T)this.buffer.push(0);if(_)this.buffer[T]|=128>>>this.length%8;this.length++}};WW.exports=UW});var zW=W((mu,VW)=>{var Dh=AW(),ET=YW(),Bh=tL(),QW=GW(),MW=NW();function F0(_,T){this.typeNumber=_,this.errorCorrectLevel=T,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}F0.prototype={addData:function(_){var T=new Dh(_);this.dataList.push(T),this.dataCache=null},isDark:function(_,T){if(_<0||this.moduleCount<=_||T<0||this.moduleCount<=T)throw Error(_+","+T);return this.modules[_][T]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var _=1;for(_=1;_<40;_++){var T=QW.getRSBlocks(_,this.errorCorrectLevel),A=new MW,E=0;for(var L=0;L<T.length;L++)E+=T[L].dataCount;for(var J=0;J<this.dataList.length;J++){var X=this.dataList[J];A.put(X.mode,4),A.put(X.getLength(),ET.getLengthInBits(X.mode,_)),X.write(A)}if(A.getLengthInBits()<=E*8)break}this.typeNumber=_}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(_,T){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var A=0;A<this.moduleCount;A++){this.modules[A]=Array(this.moduleCount);for(var E=0;E<this.moduleCount;E++)this.modules[A][E]=null}if(this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(_,T),this.typeNumber>=7)this.setupTypeNumber(_);if(this.dataCache===null)this.dataCache=F0.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);this.mapData(this.dataCache,T)},setupPositionProbePattern:function(_,T){for(var A=-1;A<=7;A++){if(_+A<=-1||this.moduleCount<=_+A)continue;for(var E=-1;E<=7;E++){if(T+E<=-1||this.moduleCount<=T+E)continue;if(0<=A&&A<=6&&(E===0||E===6)||0<=E&&E<=6&&(A===0||A===6)||2<=A&&A<=4&&2<=E&&E<=4)this.modules[_+A][T+E]=!0;else this.modules[_+A][T+E]=!1}}},getBestMaskPattern:function(){var _=0,T=0;for(var A=0;A<8;A++){this.makeImpl(!0,A);var E=ET.getLostPoint(this);if(A===0||_>E)_=E,T=A}return T},createMovieClip:function(_,T,A){var E=_.createEmptyMovieClip(T,A),L=1;this.make();for(var J=0;J<this.modules.length;J++){var X=J*L;for(var H=0;H<this.modules[J].length;H++){var Z=H*L,Y=this.modules[J][H];if(Y)E.beginFill(0,100),E.moveTo(Z,X),E.lineTo(Z+L,X),E.lineTo(Z+L,X+L),E.lineTo(Z,X+L),E.endFill()}}return E},setupTimingPattern:function(){for(var _=8;_<this.moduleCount-8;_++){if(this.modules[_][6]!==null)continue;this.modules[_][6]=_%2===0}for(var T=8;T<this.moduleCount-8;T++){if(this.modules[6][T]!==null)continue;this.modules[6][T]=T%2===0}},setupPositionAdjustPattern:function(){var _=ET.getPatternPosition(this.typeNumber);for(var T=0;T<_.length;T++)for(var A=0;A<_.length;A++){var E=_[T],L=_[A];if(this.modules[E][L]!==null)continue;for(var J=-2;J<=2;J++)for(var X=-2;X<=2;X++)if(Math.abs(J)===2||Math.abs(X)===2||J===0&&X===0)this.modules[E+J][L+X]=!0;else this.modules[E+J][L+X]=!1}},setupTypeNumber:function(_){var T=ET.getBCHTypeNumber(this.typeNumber),A;for(var E=0;E<18;E++)A=!_&&(T>>E&1)===1,this.modules[Math.floor(E/3)][E%3+this.moduleCount-8-3]=A;for(var L=0;L<18;L++)A=!_&&(T>>L&1)===1,this.modules[L%3+this.moduleCount-8-3][Math.floor(L/3)]=A},setupTypeInfo:function(_,T){var A=this.errorCorrectLevel<<3|T,E=ET.getBCHTypeInfo(A),L;for(var J=0;J<15;J++)if(L=!_&&(E>>J&1)===1,J<6)this.modules[J][8]=L;else if(J<8)this.modules[J+1][8]=L;else this.modules[this.moduleCount-15+J][8]=L;for(var X=0;X<15;X++)if(L=!_&&(E>>X&1)===1,X<8)this.modules[8][this.moduleCount-X-1]=L;else if(X<9)this.modules[8][15-X-1+1]=L;else this.modules[8][15-X-1]=L;this.modules[this.moduleCount-8][8]=!_},mapData:function(_,T){var A=-1,E=this.moduleCount-1,L=7,J=0;for(var X=this.moduleCount-1;X>0;X-=2){if(X===6)X--;while(!0){for(var H=0;H<2;H++)if(this.modules[E][X-H]===null){var Z=!1;if(J<_.length)Z=(_[J]>>>L&1)===1;var Y=ET.getMask(T,E,X-H);if(Y)Z=!Z;if(this.modules[E][X-H]=Z,L--,L===-1)J++,L=7}if(E+=A,E<0||this.moduleCount<=E){E-=A,A=-A;break}}}}};F0.PAD0=236;F0.PAD1=17;F0.createData=function(_,T,A){var E=QW.getRSBlocks(_,T),L=new MW;for(var J=0;J<A.length;J++){var X=A[J];L.put(X.mode,4),L.put(X.getLength(),ET.getLengthInBits(X.mode,_)),X.write(L)}var H=0;for(var Z=0;Z<E.length;Z++)H+=E[Z].dataCount;if(L.getLengthInBits()>H*8)throw Error("code length overflow. ("+L.getLengthInBits()+">"+H*8+")");if(L.getLengthInBits()+4<=H*8)L.put(0,4);while(L.getLengthInBits()%8!==0)L.putBit(!1);while(!0){if(L.getLengthInBits()>=H*8)break;if(L.put(F0.PAD0,8),L.getLengthInBits()>=H*8)break;L.put(F0.PAD1,8)}return F0.createBytes(L,E)};F0.createBytes=function(_,T){var A=0,E=0,L=0,J=Array(T.length),X=Array(T.length);for(var H=0;H<T.length;H++){var Z=T[H].dataCount,Y=T[H].totalCount-Z;E=Math.max(E,Z),L=Math.max(L,Y),J[H]=Array(Z);for(var K=0;K<J[H].length;K++)J[H][K]=255&_.buffer[K+A];A+=Z;var $=ET.getErrorCorrectPolynomial(Y),G=new Bh(J[H],$.getLength()-1),U=G.mod($);X[H]=Array($.getLength()-1);for(var V=0;V<X[H].length;V++){var N=V+U.getLength()-X[H].length;X[H][V]=N>=0?U.get(N):0}}var z=0;for(var Q=0;Q<T.length;Q++)z+=T[Q].totalCount;var F=Array(z),R=0;for(var q=0;q<E;q++)for(var f=0;f<T.length;f++)if(q<J[f].length)F[R++]=J[f][q];for(var h=0;h<L;h++)for(var b=0;b<T.length;b++)if(h<X[b].length)F[R++]=X[b][h];return F};VW.exports=F0});var OW=W((uu,CW)=>{var qh=zW(),FW=eL(),Ih="\x1B[40m \x1B[0m",M5="\x1B[47m \x1B[0m",Ph=function(_){return _?Ih:M5},_9=function(_){return{times:function(T){return Array(T).join(_)}}},jh=function(_,T){var A=Array(_);for(var E=0;E<_;E++)A[E]=T;return A};CW.exports={error:FW.L,generate:function(_,T,A){if(typeof T==="function")A=T,T={};var E=new qh(-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(jh(H,X));var K={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},$=_9(K.BLACK_WHITE).times(H+3),G=_9(K.WHITE_BLACK).times(H+3);L+=$+`
|
|
15
15
|
`;for(var U=0;U<H;U+=2){L+=K.WHITE_ALL;for(var V=0;V<H;V++)if(Z[U][V]===X&&Z[U+1][V]===X)L+=K.WHITE_ALL;else if(Z[U][V]===X&&Z[U+1][V]===J)L+=K.WHITE_BLACK;else if(Z[U][V]===J&&Z[U+1][V]===X)L+=K.BLACK_WHITE;else L+=K.BLACK_ALL;L+=K.WHITE_ALL+`
|
|
16
|
-
`}if(!Y)L
|
|
17
|
-
`,E.modules.forEach(function(z){L+=M5,L+=z.map(
|
|
18
|
-
`}),L+=N}if(A)A(L);else console.log(L)},setErrorLevel:function(_){this.error=
|
|
16
|
+
`}if(!Y)L+=G}else{var N=_9(M5).times(E.getModuleCount()+3);L+=N+`
|
|
17
|
+
`,E.modules.forEach(function(z){L+=M5,L+=z.map(Ph).join(""),L+=M5+`
|
|
18
|
+
`}),L+=N}if(A)A(L);else console.log(L)},setErrorLevel:function(_){this.error=FW[_]||this.error}}});import{readFileSync as Q9}from"fs";import{join as M9}from"path";function G1(){return"2.0.0-alpha.5"}function S5(_){let[T,A]=_.split("-"),E=(T||"0.0.0").split(".").map(Number);return{major:E[0]||0,minor:E[1]||0,patch:E[2]||0,preRelease:A||null}}function XT(_){let T=S5(_);if(!T.preRelease)return"stable";if(T.preRelease.startsWith("alpha"))return"alpha";return"beta"}function y5(_,T){try{let A=S5(_),E=S5(T);if(A.major>E.major)return!1;if(A.major<E.major)return!1;if(E.preRelease&&!A.preRelease)return!1;if(!E.preRelease&&A.preRelease)return!1;if(E.preRelease&&A.preRelease){if(A.minor<E.minor)return!1;if(A.minor===E.minor&&A.patch===E.patch)return A.preRelease>E.preRelease;if(A.minor>E.minor||A.patch>E.patch)return!0;return!1}if(A.minor>E.minor)return!0;if(A.minor<E.minor)return!1;if(A.patch>E.patch)return!0;return!1}catch(A){return!1}}import{parseArgs as qN}from"util";var IN={debug:{type:"boolean",short:"d",default:!1,description:"Enable debug logging"},"mqtt-port":{type:"string",default:"8884",description:"MQTT broker port"},"terminal-port":{type:"string",default:"3001",description:"Terminal server port"},"router-port":{type:"string",default:"8883",description:"Router port"},username:{type:"string",description:"MQTT broker username (optional)"},password:{type:"string",description:"MQTT broker password (optional)"},"ngrok-token":{type:"string",description:"ngrok authentication token (optional)"},"ngrok-domain":{type:"string",description:"ngrok static domain (optional, paid plan)"},"no-auto-update":{type:"boolean",default:!1,description:"Disable auto-update checking"},"auto-update-check-interval":{type:"string",default:"60",description:"Auto-update check interval in minutes (default: 60)"},help:{type:"boolean",short:"h",default:!1,description:"Show help message"},version:{type:"boolean",short:"v",default:!1,description:"Show version"}};function V9(){let _=qN({options:IN,allowPositionals:!1,strict:!0});if(_.values.version)console.log(`ccc v${G1()}`),process.exit(0);if(_.values.help)PN(),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 PN(){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 v8 extends B4{constructor(_){super(_,"MQTT_BROKER_ERROR",500);this.name="MQTTBrokerError"}}class XT extends B4{constructor(_){super(_,"TERMINAL_SERVER_ERROR",500);this.name="TerminalServerError"}}class S5 extends B4{constructor(_){super(_,"ROUTER_ERROR",500);this.name="RouterError"}}class h8 extends B4{constructor(_="Authentication failed"){super(_,"AUTH_ERROR",401);this.name="AuthenticationError"}}function N9(_){return qN(_),IN(_),{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 qN(_){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 IN(_){if(_.ngrokToken&&(!_.username||!_.password))throw new q4("Error: MQTT authentication (--username and --password) is required when using ngrok tunnels for security.")}class y5{isDev;constructor(_=!1){this.isDev=_}debug(_,T){if(this.isDev)console.log(`[DEBUG] ${_}`,T||"")}info(_,T){console.log(`[INFO] ${_}`,T||"")}warn(_,T){console.warn(`[WARN] ${_}`,T||"")}error(_,T){console.error(`[ERROR] ${_}`,T||"")}}var I4=null;function Q9(_=!1){return I4=new y5(_),I4}function v(){if(!I4)I4=new y5(!1);return I4}import*as d0 from"fs";import*as mT from"path";var PN={FULL_WIDTH:0,FITTING:1,SMUSHING:2,CONTROLLED_SMUSHING:3};class M9{constructor(){this.comment="",this.numChars=0,this.options={}}}var v5=["1Row","3-D","3D Diagonal","3D-ASCII","3x5","4Max","5 Line Oblique","AMC 3 Line","AMC 3 Liv1","AMC AAA01","AMC Neko","AMC Razor","AMC Razor2","AMC Slash","AMC Slider","AMC Thin","AMC Tubes","AMC Untitled","ANSI Regular","ANSI Shadow","ANSI-Compact","ASCII 12","ASCII 9","ASCII New Roman","Acrobatic","Alligator","Alligator2","Alpha","Alphabet","Arrows","Avatar","B1FF","Babyface Lame","Babyface Leet","Banner","Banner3-D","Banner3","Banner4","Barbwire","Basic","Bear","Bell","Benjamin","Big ASCII 12","Big ASCII 9","Big Chief","Big Money-ne","Big Money-nw","Big Money-se","Big Money-sw","Big Mono 12","Big Mono 9","Big","Bigfig","Binary","Block","Blocks","Bloody","BlurVision ASCII","Bolger","Braced","Bright","Broadway KB","Broadway","Bubble","Bulbhead","Caligraphy","Caligraphy2","Calvin S","Cards","Catwalk","Chiseled","Chunky","Circle","Coinstak","Cola","Colossal","Computer","Contessa","Contrast","Cosmike","Cosmike2","Crawford","Crawford2","Crazy","Cricket","Cursive","Cyberlarge","Cybermedium","Cybersmall","Cygnet","DANC4","DOS Rebel","DWhistled","Dancing Font","Decimal","Def Leppard","Delta Corps Priest 1","DiamFont","Diamond","Diet Cola","Digital","Doh","Doom","Dot Matrix","Double Shorts","Double","Dr Pepper","Efti Chess","Efti Font","Efti Italic","Efti Piti","Efti Robot","Efti Wall","Efti Water","Electronic","Elite","Emboss 2","Emboss","Epic","Fender","Filter","Fire Font-k","Fire Font-s","Flipped","Flower Power","Four Tops","Fraktur","Fun Face","Fun Faces","Future","Fuzzy","Georgi16","Georgia11","Ghost","Ghoulish","Glenyn","Goofy","Gothic","Graceful","Gradient","Graffiti","Greek","Heart Left","Heart Right","Henry 3D","Hex","Hieroglyphs","Hollywood","Horizontal Left","Horizontal Right","ICL-1900","Impossible","Invita","Isometric1","Isometric2","Isometric3","Isometric4","Italic","Ivrit","JS Block Letters","JS Bracket Letters","JS Capital Curves","JS Cursive","JS Stick Letters","Jacky","Jazmine","Jerusalem","Katakana","Kban","Keyboard","Knob","Konto Slant","Konto","LCD","Larry 3D 2","Larry 3D","Lean","Letter","Letters","Lil Devil","Line Blocks","Linux","Lockergnome","Madrid","Marquee","Maxfour","Merlin1","Merlin2","Mike","Mini","Mirror","Mnemonic","Modular","Mono 12","Mono 9","Morse","Morse2","Moscow","Mshebrew210","Muzzle","NScript","NT Greek","NV Script","Nancyj-Fancy","Nancyj-Improved","Nancyj-Underlined","Nancyj","Nipples","O8","OS2","Octal","Ogre","Old Banner","Pagga","Patorjk's Cheese","Patorjk-HeX","Pawp","Peaks Slant","Peaks","Pebbles","Pepper","Poison","Puffy","Puzzle","Pyramid","Rammstein","Rebel","Rectangles","Red Phoenix","Relief","Relief2","Reverse","Roman","Rot13","Rotated","Rounded","Rowan Cap","Rozzo","RubiFont","Runic","Runyc","S Blood","SL Script","Santa Clara","Script","Serifcap","Shaded Blocky","Shadow","Shimrod","Short","Slant Relief","Slant","Slide","Small ASCII 12","Small ASCII 9","Small Block","Small Braille","Small Caps","Small Isometric1","Small Keyboard","Small Mono 12","Small Mono 9","Small Poison","Small Script","Small Shadow","Small Slant","Small Tengwar","Small","Soft","Speed","Spliff","Stacey","Stampate","Stampatello","Standard","Star Strips","Star Wars","Stellar","Stforek","Stick Letters","Stop","Straight","Stronger Than All","Sub-Zero","Swamp Land","Swan","Sweet","THIS","Tanja","Tengwar","Term","Terrace","Test1","The Edge","Thick","Thin","Thorned","Three Point","Ticks Slant","Ticks","Tiles","Tinker-Toy","Tmplr","Tombstone","Train","Trek","Tsalagi","Tubular","Twisted","Two Point","USA Flag","Univers","Upside Down Text","Varsity","Wavescape","Wavy","Weird","Wet Letter","Whimsy","WideTerm","Wow","miniwi"];function jN(_){return/[.*+?^${}()|[\]\\]/.test(_)?"\\"+_:_}var V9=(()=>{let{FULL_WIDTH:_=0,FITTING:T,SMUSHING:A,CONTROLLED_SMUSHING:E}=PN,L={},J={font:"Standard",fontPath:"./fonts",fetchFontIfMissing:!0};function X(O,D,M){let C=jN(O.trim().slice(-1))||"@",P=D===M-1?new RegExp(C+C+"?\\s*$"):new RegExp(C+"\\s*$");return O.replace(P,"")}function H(O=-1,D=null){let M={},C,P=[[16384,"vLayout",A],[8192,"vLayout",T],[4096,"vRule5",!0],[2048,"vRule4",!0],[1024,"vRule3",!0],[512,"vRule2",!0],[256,"vRule1",!0],[128,"hLayout",A],[64,"hLayout",T],[32,"hRule6",!0],[16,"hRule5",!0],[8,"hRule4",!0],[4,"hRule3",!0],[2,"hRule2",!0],[1,"hRule1",!0]];C=D!==null?D:O;for(let[w,y,S]of P)if(C>=w){if(C-=w,M[y]===void 0)M[y]=S}else if(y!=="vLayout"&&y!=="hLayout")M[y]=!1;if(typeof M.hLayout>"u")if(O===0)M.hLayout=T;else if(O===-1)M.hLayout=_;else if(M.hRule1||M.hRule2||M.hRule3||M.hRule4||M.hRule5||M.hRule6)M.hLayout=E;else M.hLayout=A;else if(M.hLayout===A){if(M.hRule1||M.hRule2||M.hRule3||M.hRule4||M.hRule5||M.hRule6)M.hLayout=E}if(typeof M.vLayout>"u")if(M.vRule1||M.vRule2||M.vRule3||M.vRule4||M.vRule5)M.vLayout=E;else M.vLayout=_;else if(M.vLayout===A){if(M.vRule1||M.vRule2||M.vRule3||M.vRule4||M.vRule5)M.vLayout=E}return M}function Z(O,D,M=""){if(O===D&&O!==M)return O;return!1}function Y(O,D){let M="|/\\[]{}()<>";if(O==="_"){if(M.indexOf(D)!==-1)return D}else if(D==="_"){if(M.indexOf(O)!==-1)return O}return!1}function K(O,D){let M="| /\\ [] {} () <>",C=M.indexOf(O),P=M.indexOf(D);if(C!==-1&&P!==-1){if(C!==P&&Math.abs(C-P)!==1){let w=Math.max(C,P),y=w+1;return M.substring(w,y)}}return!1}function G(O,D){let M="[] {} ()",C=M.indexOf(O),P=M.indexOf(D);if(C!==-1&&P!==-1){if(Math.abs(C-P)<=1)return"|"}return!1}function $(O,D){return{"/\\":"|","\\/":"Y","><":"X"}[O+D]||!1}function U(O,D,M=""){if(O===M&&D===M)return M;return!1}function V(O,D){if(O===D)return O;return!1}function N(O,D){return Y(O,D)}function z(O,D){return K(O,D)}function Q(O,D){if(O==="-"&&D==="_"||O==="_"&&D==="-")return"=";return!1}function F(O,D){if(O==="|"&&D==="|")return"|";return!1}function R(O,D,M){if(D===" "||D==="")return O;else if(D===M&&O!==" ")return O;else return D}function q(O,D,M){if(M.fittingRules&&M.fittingRules.vLayout===_)return"invalid";let C,P=Math.min(O.length,D.length),w,y,S=!1,k;if(P===0)return"invalid";for(C=0;C<P;C++)if(w=O.substring(C,C+1),y=D.substring(C,C+1),w!==" "&&y!==" ")if(M.fittingRules&&M.fittingRules.vLayout===T)return"invalid";else if(M.fittingRules&&M.fittingRules.vLayout===A)return"end";else{if(F(w,y)){S=S||!1;continue}if(k=!1,k=M.fittingRules&&M.fittingRules.vRule1?V(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule2?N(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule3?z(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule4?Q(w,y):k,S=!0,!k)return"invalid"}if(S)return"end";else return"valid"}function f(O,D,M){let{length:C,length:P}=O,w,y,S,k=1,d,o,a;while(k<=C){w=O.slice(Math.max(0,P-k),P),y=D.slice(0,Math.min(C,k)),S=y.length,a="";for(d=0;d<S;d++)if(o=q(w[d],y[d],M),o==="end")a=o;else if(o==="invalid"){a=o;break}else if(a==="")a="valid";if(a==="invalid"){k--;break}if(a==="end")break;if(a==="valid")k++}return Math.min(C,k)}function h(O,D,M){let C,P=Math.min(O.length,D.length),w,y,S="",k,d=M.fittingRules||{};for(C=0;C<P;C++)if(w=O.substring(C,C+1),y=D.substring(C,C+1),w!==" "&&y!==" ")if(d.vLayout===T)S+=R(w,y);else if(d.vLayout===A)S+=R(w,y);else k=!1,k=d.vRule5?F(w,y):k,k=!k&&d.vRule1?V(w,y):k,k=!k&&d.vRule2?N(w,y):k,k=!k&&d.vRule3?z(w,y):k,k=!k&&d.vRule4?Q(w,y):k,S+=k;else S+=R(w,y);return S}function b(O,D,M,C){let P=O.length,w=D.length,y=O.slice(0,Math.max(0,P-M)),S=O.slice(Math.max(0,P-M),P),k=D.slice(0,Math.min(M,w)),d,o,a,r=[],T_;o=S.length;for(d=0;d<o;d++){if(d>=w)a=S[d];else a=h(S[d],k[d],C);r.push(a)}return T_=D.slice(Math.min(M,w),w),[...y,...r,...T_]}function l(O,D){let M=" ".repeat(D);return O.map((C)=>C+M)}function c(O,D,M){let C=O[0].length,P=D[0].length,w;if(C>P)D=l(D,C-P);else if(P>C)O=l(O,P-C);return w=f(O,D,M),b(O,D,w,M)}function W_(O,D,M){let C=M.fittingRules||{};if(C.hLayout===_)return 0;let P,w=O.length,y=D.length,S=w,k=1,d=!1,o,a,r,T_;if(w===0)return 0;_:while(k<=S){let y1=w-k;o=O.substring(y1,y1+k),a=D.substring(0,Math.min(k,y));for(P=0;P<Math.min(k,y);P++)if(r=o.substring(P,P+1),T_=a.substring(P,P+1),r!==" "&&T_!==" "){if(C.hLayout===T){k=k-1;break _}else if(C.hLayout===A){if(r===M.hardBlank||T_===M.hardBlank)k=k-1;break _}else if(d=!0,!(C.hRule1&&Z(r,T_,M.hardBlank)||C.hRule2&&Y(r,T_)||C.hRule3&&K(r,T_)||C.hRule4&&G(r,T_)||C.hRule5&&$(r,T_)||C.hRule6&&U(r,T_,M.hardBlank))){k=k-1;break _}}if(d)break;k++}return Math.min(S,k)}function c_(O,D,M,C){let P,w,y=[],S,k,d,o,a,r,T_,y1,E1=C.fittingRules||{};if(typeof C.height!=="number")throw Error("height is not defined.");for(P=0;P<C.height;P++){T_=O[P],y1=D[P],a=T_.length,r=y1.length,S=a-M,k=T_.slice(0,Math.max(0,S)),d="";let D4=Math.max(0,a-M),v1=T_.substring(D4,D4+M),JT=y1.substring(0,Math.min(M,r));for(w=0;w<M;w++){let Q1=w<a?v1.substring(w,w+1):" ",L1=w<r?JT.substring(w,w+1):" ";if(Q1!==" "&&L1!==" ")if(E1.hLayout===T||E1.hLayout===A)d+=R(Q1,L1,C.hardBlank);else{let MN=E1.hRule1&&Z(Q1,L1,C.hardBlank)||E1.hRule2&&Y(Q1,L1)||E1.hRule3&&K(Q1,L1)||E1.hRule4&&G(Q1,L1)||E1.hRule5&&$(Q1,L1)||E1.hRule6&&U(Q1,L1,C.hardBlank)||R(Q1,L1,C.hardBlank);d+=MN}else d+=R(Q1,L1,C.hardBlank)}if(M>=r)o="";else o=y1.substring(M,M+Math.max(0,r-M));y[P]=k+d+o}return y}function B_(O){return Array(O).fill("")}let C_=function(O){return Math.max(...O.map((D)=>D.length))};function K_(O,D,M){return O.reduce(function(C,P){return c_(C,P.fig,P.overlap||0,M)},B_(D))}function M_(O,D,M){for(let C=O.length-1;C>0;C--){let P=K_(O.slice(0,C),D,M);if(C_(P)<=M.width)return{outputFigText:P,chars:O.slice(C)}}return{outputFigText:B_(D),chars:O}}function q_(O,D,M){let C,P,w=0,y,S,k,d=M.height,o=[],a,r={chars:[],overlap:w},T_=[],y1,E1,D4,v1,JT;if(typeof d!=="number")throw Error("height is not defined.");S=B_(d);let Q1=M.fittingRules||{};if(M.printDirection===1)O=O.split("").reverse().join("");k=O.length;for(C=0;C<k;C++)if(y1=O.substring(C,C+1),E1=y1.match(/\s/),P=D[y1.charCodeAt(0)],v1=null,P){if(Q1.hLayout!==_){w=1e4;for(y=0;y<d;y++)w=Math.min(w,W_(S[y],P[y],M));w=w===1e4?0:w}if(M.width>0){if(M.whitespaceBreak)D4=K_(r.chars.concat([{fig:P,overlap:w}]),d,M),v1=K_(T_.concat([{fig:D4,overlap:r.overlap}]),d,M),a=C_(v1);else v1=c_(S,P,w,M),a=C_(v1);if(a>=M.width&&C>0)if(M.whitespaceBreak){if(S=K_(T_.slice(0,-1),d,M),T_.length>1)o.push(S),S=B_(d);T_=[]}else o.push(S),S=B_(d)}if(M.width>0&&M.whitespaceBreak){if(!E1||C===k-1)r.chars.push({fig:P,overlap:w});if(E1||C===k-1){JT=null;while(!0)if(v1=K_(r.chars,d,M),a=C_(v1),a>=M.width)JT=M_(r.chars,d,M),r={chars:JT.chars},o.push(JT.outputFigText);else break;if(a>0)if(JT)T_.push({fig:v1,overlap:1});else T_.push({fig:v1,overlap:r.overlap});if(E1)T_.push({fig:P,overlap:w}),S=B_(d);if(C===k-1)S=K_(T_,d,M);r={chars:[],overlap:w};continue}}S=c_(S,P,w,M)}if(C_(S)>0)o.push(S);if(!M.showHardBlanks)o.forEach(function(L1){k=L1.length;for(y=0;y<k;y++)L1[y]=L1[y].replace(new RegExp("\\"+M.hardBlank,"g")," ")});if(O===""&&o.length===0)o.push(Array(d).fill(""));return o}let P_=function(O,D){let M,C=D.fittingRules||{};if(O==="default")M={hLayout:C.hLayout,hRule1:C.hRule1,hRule2:C.hRule2,hRule3:C.hRule3,hRule4:C.hRule4,hRule5:C.hRule5,hRule6:C.hRule6};else if(O==="full")M={hLayout:_,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else if(O==="fitted")M={hLayout:T,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else if(O==="controlled smushing")M={hLayout:E,hRule1:!0,hRule2:!0,hRule3:!0,hRule4:!0,hRule5:!0,hRule6:!0};else if(O==="universal smushing")M={hLayout:A,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else return;return M},O0=function(O,D){let M={},C=D.fittingRules||{};if(O==="default")M={vLayout:C.vLayout,vRule1:C.vRule1,vRule2:C.vRule2,vRule3:C.vRule3,vRule4:C.vRule4,vRule5:C.vRule5};else if(O==="full")M={vLayout:_,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else if(O==="fitted")M={vLayout:T,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else if(O==="controlled smushing")M={vLayout:E,vRule1:!0,vRule2:!0,vRule3:!0,vRule4:!0,vRule5:!0};else if(O==="universal smushing")M={vLayout:A,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else return;return M},S1=function(O,D,M){M=M.replace(/\r\n/g,`
|
|
37
|
+
`)}class B4 extends Error{code;statusCode;constructor(_,T="SERVICE_ERROR",A=500){super(_);this.code=T;this.statusCode=A;this.name="ServiceError"}}class q4 extends Error{constructor(_){super(_);this.name="ConfigError"}}class v8 extends B4{constructor(_){super(_,"MQTT_BROKER_ERROR",500);this.name="MQTTBrokerError"}}class HT extends B4{constructor(_){super(_,"TERMINAL_SERVER_ERROR",500);this.name="TerminalServerError"}}class v5 extends B4{constructor(_){super(_,"ROUTER_ERROR",500);this.name="RouterError"}}class h8 extends B4{constructor(_="Authentication failed"){super(_,"AUTH_ERROR",401);this.name="AuthenticationError"}}function z9(_){return jN(_),xN(_),{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 jN(_){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 xN(_){if(_.ngrokToken&&(!_.username||!_.password))throw new q4("Error: MQTT authentication (--username and --password) is required when using ngrok tunnels for security.")}class h5{isDev;constructor(_=!1){this.isDev=_}debug(_,T){if(this.isDev)console.log(`[DEBUG] ${_}`,T||"")}info(_,T){console.log(`[INFO] ${_}`,T||"")}warn(_,T){console.warn(`[WARN] ${_}`,T||"")}error(_,T){console.error(`[ERROR] ${_}`,T||"")}}var I4=null;function F9(_=!1){return I4=new h5(_),I4}function v(){if(!I4)I4=new h5(!1);return I4}import*as d0 from"fs";import*as mT from"path";var wN={FULL_WIDTH:0,FITTING:1,SMUSHING:2,CONTROLLED_SMUSHING:3};class C9{constructor(){this.comment="",this.numChars=0,this.options={}}}var k5=["1Row","3-D","3D Diagonal","3D-ASCII","3x5","4Max","5 Line Oblique","AMC 3 Line","AMC 3 Liv1","AMC AAA01","AMC Neko","AMC Razor","AMC Razor2","AMC Slash","AMC Slider","AMC Thin","AMC Tubes","AMC Untitled","ANSI Regular","ANSI Shadow","ANSI-Compact","ASCII 12","ASCII 9","ASCII New Roman","Acrobatic","Alligator","Alligator2","Alpha","Alphabet","Arrows","Avatar","B1FF","Babyface Lame","Babyface Leet","Banner","Banner3-D","Banner3","Banner4","Barbwire","Basic","Bear","Bell","Benjamin","Big ASCII 12","Big ASCII 9","Big Chief","Big Money-ne","Big Money-nw","Big Money-se","Big Money-sw","Big Mono 12","Big Mono 9","Big","Bigfig","Binary","Block","Blocks","Bloody","BlurVision ASCII","Bolger","Braced","Bright","Broadway KB","Broadway","Bubble","Bulbhead","Caligraphy","Caligraphy2","Calvin S","Cards","Catwalk","Chiseled","Chunky","Circle","Coinstak","Cola","Colossal","Computer","Contessa","Contrast","Cosmike","Cosmike2","Crawford","Crawford2","Crazy","Cricket","Cursive","Cyberlarge","Cybermedium","Cybersmall","Cygnet","DANC4","DOS Rebel","DWhistled","Dancing Font","Decimal","Def Leppard","Delta Corps Priest 1","DiamFont","Diamond","Diet Cola","Digital","Doh","Doom","Dot Matrix","Double Shorts","Double","Dr Pepper","Efti Chess","Efti Font","Efti Italic","Efti Piti","Efti Robot","Efti Wall","Efti Water","Electronic","Elite","Emboss 2","Emboss","Epic","Fender","Filter","Fire Font-k","Fire Font-s","Flipped","Flower Power","Four Tops","Fraktur","Fun Face","Fun Faces","Future","Fuzzy","Georgi16","Georgia11","Ghost","Ghoulish","Glenyn","Goofy","Gothic","Graceful","Gradient","Graffiti","Greek","Heart Left","Heart Right","Henry 3D","Hex","Hieroglyphs","Hollywood","Horizontal Left","Horizontal Right","ICL-1900","Impossible","Invita","Isometric1","Isometric2","Isometric3","Isometric4","Italic","Ivrit","JS Block Letters","JS Bracket Letters","JS Capital Curves","JS Cursive","JS Stick Letters","Jacky","Jazmine","Jerusalem","Katakana","Kban","Keyboard","Knob","Konto Slant","Konto","LCD","Larry 3D 2","Larry 3D","Lean","Letter","Letters","Lil Devil","Line Blocks","Linux","Lockergnome","Madrid","Marquee","Maxfour","Merlin1","Merlin2","Mike","Mini","Mirror","Mnemonic","Modular","Mono 12","Mono 9","Morse","Morse2","Moscow","Mshebrew210","Muzzle","NScript","NT Greek","NV Script","Nancyj-Fancy","Nancyj-Improved","Nancyj-Underlined","Nancyj","Nipples","O8","OS2","Octal","Ogre","Old Banner","Pagga","Patorjk's Cheese","Patorjk-HeX","Pawp","Peaks Slant","Peaks","Pebbles","Pepper","Poison","Puffy","Puzzle","Pyramid","Rammstein","Rebel","Rectangles","Red Phoenix","Relief","Relief2","Reverse","Roman","Rot13","Rotated","Rounded","Rowan Cap","Rozzo","RubiFont","Runic","Runyc","S Blood","SL Script","Santa Clara","Script","Serifcap","Shaded Blocky","Shadow","Shimrod","Short","Slant Relief","Slant","Slide","Small ASCII 12","Small ASCII 9","Small Block","Small Braille","Small Caps","Small Isometric1","Small Keyboard","Small Mono 12","Small Mono 9","Small Poison","Small Script","Small Shadow","Small Slant","Small Tengwar","Small","Soft","Speed","Spliff","Stacey","Stampate","Stampatello","Standard","Star Strips","Star Wars","Stellar","Stforek","Stick Letters","Stop","Straight","Stronger Than All","Sub-Zero","Swamp Land","Swan","Sweet","THIS","Tanja","Tengwar","Term","Terrace","Test1","The Edge","Thick","Thin","Thorned","Three Point","Ticks Slant","Ticks","Tiles","Tinker-Toy","Tmplr","Tombstone","Train","Trek","Tsalagi","Tubular","Twisted","Two Point","USA Flag","Univers","Upside Down Text","Varsity","Wavescape","Wavy","Weird","Wet Letter","Whimsy","WideTerm","Wow","miniwi"];function SN(_){return/[.*+?^${}()|[\]\\]/.test(_)?"\\"+_:_}var O9=(()=>{let{FULL_WIDTH:_=0,FITTING:T,SMUSHING:A,CONTROLLED_SMUSHING:E}=wN,L={},J={font:"Standard",fontPath:"./fonts",fetchFontIfMissing:!0};function X(O,D,M){let C=SN(O.trim().slice(-1))||"@",j=D===M-1?new RegExp(C+C+"?\\s*$"):new RegExp(C+"\\s*$");return O.replace(j,"")}function H(O=-1,D=null){let M={},C,j=[[16384,"vLayout",A],[8192,"vLayout",T],[4096,"vRule5",!0],[2048,"vRule4",!0],[1024,"vRule3",!0],[512,"vRule2",!0],[256,"vRule1",!0],[128,"hLayout",A],[64,"hLayout",T],[32,"hRule6",!0],[16,"hRule5",!0],[8,"hRule4",!0],[4,"hRule3",!0],[2,"hRule2",!0],[1,"hRule1",!0]];C=D!==null?D:O;for(let[w,y,S]of j)if(C>=w){if(C-=w,M[y]===void 0)M[y]=S}else if(y!=="vLayout"&&y!=="hLayout")M[y]=!1;if(typeof M.hLayout>"u")if(O===0)M.hLayout=T;else if(O===-1)M.hLayout=_;else if(M.hRule1||M.hRule2||M.hRule3||M.hRule4||M.hRule5||M.hRule6)M.hLayout=E;else M.hLayout=A;else if(M.hLayout===A){if(M.hRule1||M.hRule2||M.hRule3||M.hRule4||M.hRule5||M.hRule6)M.hLayout=E}if(typeof M.vLayout>"u")if(M.vRule1||M.vRule2||M.vRule3||M.vRule4||M.vRule5)M.vLayout=E;else M.vLayout=_;else if(M.vLayout===A){if(M.vRule1||M.vRule2||M.vRule3||M.vRule4||M.vRule5)M.vLayout=E}return M}function Z(O,D,M=""){if(O===D&&O!==M)return O;return!1}function Y(O,D){let M="|/\\[]{}()<>";if(O==="_"){if(M.indexOf(D)!==-1)return D}else if(D==="_"){if(M.indexOf(O)!==-1)return O}return!1}function K(O,D){let M="| /\\ [] {} () <>",C=M.indexOf(O),j=M.indexOf(D);if(C!==-1&&j!==-1){if(C!==j&&Math.abs(C-j)!==1){let w=Math.max(C,j),y=w+1;return M.substring(w,y)}}return!1}function $(O,D){let M="[] {} ()",C=M.indexOf(O),j=M.indexOf(D);if(C!==-1&&j!==-1){if(Math.abs(C-j)<=1)return"|"}return!1}function G(O,D){return{"/\\":"|","\\/":"Y","><":"X"}[O+D]||!1}function U(O,D,M=""){if(O===M&&D===M)return M;return!1}function V(O,D){if(O===D)return O;return!1}function N(O,D){return Y(O,D)}function z(O,D){return K(O,D)}function Q(O,D){if(O==="-"&&D==="_"||O==="_"&&D==="-")return"=";return!1}function F(O,D){if(O==="|"&&D==="|")return"|";return!1}function R(O,D,M){if(D===" "||D==="")return O;else if(D===M&&O!==" ")return O;else return D}function q(O,D,M){if(M.fittingRules&&M.fittingRules.vLayout===_)return"invalid";let C,j=Math.min(O.length,D.length),w,y,S=!1,k;if(j===0)return"invalid";for(C=0;C<j;C++)if(w=O.substring(C,C+1),y=D.substring(C,C+1),w!==" "&&y!==" ")if(M.fittingRules&&M.fittingRules.vLayout===T)return"invalid";else if(M.fittingRules&&M.fittingRules.vLayout===A)return"end";else{if(F(w,y)){S=S||!1;continue}if(k=!1,k=M.fittingRules&&M.fittingRules.vRule1?V(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule2?N(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule3?z(w,y):k,k=!k&&M.fittingRules&&M.fittingRules.vRule4?Q(w,y):k,S=!0,!k)return"invalid"}if(S)return"end";else return"valid"}function f(O,D,M){let{length:C,length:j}=O,w,y,S,k=1,d,o,a;while(k<=C){w=O.slice(Math.max(0,j-k),j),y=D.slice(0,Math.min(C,k)),S=y.length,a="";for(d=0;d<S;d++)if(o=q(w[d],y[d],M),o==="end")a=o;else if(o==="invalid"){a=o;break}else if(a==="")a="valid";if(a==="invalid"){k--;break}if(a==="end")break;if(a==="valid")k++}return Math.min(C,k)}function h(O,D,M){let C,j=Math.min(O.length,D.length),w,y,S="",k,d=M.fittingRules||{};for(C=0;C<j;C++)if(w=O.substring(C,C+1),y=D.substring(C,C+1),w!==" "&&y!==" ")if(d.vLayout===T)S+=R(w,y);else if(d.vLayout===A)S+=R(w,y);else k=!1,k=d.vRule5?F(w,y):k,k=!k&&d.vRule1?V(w,y):k,k=!k&&d.vRule2?N(w,y):k,k=!k&&d.vRule3?z(w,y):k,k=!k&&d.vRule4?Q(w,y):k,S+=k;else S+=R(w,y);return S}function b(O,D,M,C){let j=O.length,w=D.length,y=O.slice(0,Math.max(0,j-M)),S=O.slice(Math.max(0,j-M),j),k=D.slice(0,Math.min(M,w)),d,o,a,r=[],T_;o=S.length;for(d=0;d<o;d++){if(d>=w)a=S[d];else a=h(S[d],k[d],C);r.push(a)}return T_=D.slice(Math.min(M,w),w),[...y,...r,...T_]}function l(O,D){let M=" ".repeat(D);return O.map((C)=>C+M)}function c(O,D,M){let C=O[0].length,j=D[0].length,w;if(C>j)D=l(D,C-j);else if(j>C)O=l(O,j-C);return w=f(O,D,M),b(O,D,w,M)}function W_(O,D,M){let C=M.fittingRules||{};if(C.hLayout===_)return 0;let j,w=O.length,y=D.length,S=w,k=1,d=!1,o,a,r,T_;if(w===0)return 0;_:while(k<=S){let v1=w-k;o=O.substring(v1,v1+k),a=D.substring(0,Math.min(k,y));for(j=0;j<Math.min(k,y);j++)if(r=o.substring(j,j+1),T_=a.substring(j,j+1),r!==" "&&T_!==" "){if(C.hLayout===T){k=k-1;break _}else if(C.hLayout===A){if(r===M.hardBlank||T_===M.hardBlank)k=k-1;break _}else if(d=!0,!(C.hRule1&&Z(r,T_,M.hardBlank)||C.hRule2&&Y(r,T_)||C.hRule3&&K(r,T_)||C.hRule4&&$(r,T_)||C.hRule5&&G(r,T_)||C.hRule6&&U(r,T_,M.hardBlank))){k=k-1;break _}}if(d)break;k++}return Math.min(S,k)}function c_(O,D,M,C){let j,w,y=[],S,k,d,o,a,r,T_,v1,E1=C.fittingRules||{};if(typeof C.height!=="number")throw Error("height is not defined.");for(j=0;j<C.height;j++){T_=O[j],v1=D[j],a=T_.length,r=v1.length,S=a-M,k=T_.slice(0,Math.max(0,S)),d="";let D4=Math.max(0,a-M),h1=T_.substring(D4,D4+M),JT=v1.substring(0,Math.min(M,r));for(w=0;w<M;w++){let M1=w<a?h1.substring(w,w+1):" ",L1=w<r?JT.substring(w,w+1):" ";if(M1!==" "&&L1!==" ")if(E1.hLayout===T||E1.hLayout===A)d+=R(M1,L1,C.hardBlank);else{let CN=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+=CN}else d+=R(M1,L1,C.hardBlank)}if(M>=r)o="";else o=v1.substring(M,M+Math.max(0,r-M));y[j]=k+d+o}return y}function B_(O){return Array(O).fill("")}let C_=function(O){return Math.max(...O.map((D)=>D.length))};function K_(O,D,M){return O.reduce(function(C,j){return c_(C,j.fig,j.overlap||0,M)},B_(D))}function M_(O,D,M){for(let C=O.length-1;C>0;C--){let j=K_(O.slice(0,C),D,M);if(C_(j)<=M.width)return{outputFigText:j,chars:O.slice(C)}}return{outputFigText:B_(D),chars:O}}function I_(O,D,M){let C,j,w=0,y,S,k,d=M.height,o=[],a,r={chars:[],overlap:w},T_=[],v1,E1,D4,h1,JT;if(typeof d!=="number")throw Error("height is not defined.");S=B_(d);let M1=M.fittingRules||{};if(M.printDirection===1)O=O.split("").reverse().join("");k=O.length;for(C=0;C<k;C++)if(v1=O.substring(C,C+1),E1=v1.match(/\s/),j=D[v1.charCodeAt(0)],h1=null,j){if(M1.hLayout!==_){w=1e4;for(y=0;y<d;y++)w=Math.min(w,W_(S[y],j[y],M));w=w===1e4?0:w}if(M.width>0){if(M.whitespaceBreak)D4=K_(r.chars.concat([{fig:j,overlap:w}]),d,M),h1=K_(T_.concat([{fig:D4,overlap:r.overlap}]),d,M),a=C_(h1);else h1=c_(S,j,w,M),a=C_(h1);if(a>=M.width&&C>0)if(M.whitespaceBreak){if(S=K_(T_.slice(0,-1),d,M),T_.length>1)o.push(S),S=B_(d);T_=[]}else o.push(S),S=B_(d)}if(M.width>0&&M.whitespaceBreak){if(!E1||C===k-1)r.chars.push({fig:j,overlap:w});if(E1||C===k-1){JT=null;while(!0)if(h1=K_(r.chars,d,M),a=C_(h1),a>=M.width)JT=M_(r.chars,d,M),r={chars:JT.chars},o.push(JT.outputFigText);else break;if(a>0)if(JT)T_.push({fig:h1,overlap:1});else T_.push({fig:h1,overlap:r.overlap});if(E1)T_.push({fig:j,overlap:w}),S=B_(d);if(C===k-1)S=K_(T_,d,M);r={chars:[],overlap:w};continue}}S=c_(S,j,w,M)}if(C_(S)>0)o.push(S);if(!M.showHardBlanks)o.forEach(function(L1){k=L1.length;for(y=0;y<k;y++)L1[y]=L1[y].replace(new RegExp("\\"+M.hardBlank,"g")," ")});if(O===""&&o.length===0)o.push(Array(d).fill(""));return o}let j_=function(O,D){let M,C=D.fittingRules||{};if(O==="default")M={hLayout:C.hLayout,hRule1:C.hRule1,hRule2:C.hRule2,hRule3:C.hRule3,hRule4:C.hRule4,hRule5:C.hRule5,hRule6:C.hRule6};else if(O==="full")M={hLayout:_,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else if(O==="fitted")M={hLayout:T,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else if(O==="controlled smushing")M={hLayout:E,hRule1:!0,hRule2:!0,hRule3:!0,hRule4:!0,hRule5:!0,hRule6:!0};else if(O==="universal smushing")M={hLayout:A,hRule1:!1,hRule2:!1,hRule3:!1,hRule4:!1,hRule5:!1,hRule6:!1};else return;return M},R0=function(O,D){let M={},C=D.fittingRules||{};if(O==="default")M={vLayout:C.vLayout,vRule1:C.vRule1,vRule2:C.vRule2,vRule3:C.vRule3,vRule4:C.vRule4,vRule5:C.vRule5};else if(O==="full")M={vLayout:_,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else if(O==="fitted")M={vLayout:T,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else if(O==="controlled smushing")M={vLayout:E,vRule1:!0,vRule2:!0,vRule3:!0,vRule4:!0,vRule5:!0};else if(O==="universal smushing")M={vLayout:A,vRule1:!1,vRule2:!1,vRule3:!1,vRule4:!1,vRule5:!1};else return;return M},y1=function(O,D,M){M=M.replace(/\r\n/g,`
|
|
38
38
|
`).replace(/\r/g,`
|
|
39
39
|
`);let C=M.split(`
|
|
40
|
-
`),
|
|
41
|
-
`):""};function
|
|
40
|
+
`),j=[],w,y,S;y=C.length;for(w=0;w<y;w++)j=j.concat(I_(C[w],L[O],D));y=j.length,S=j[0];for(w=1;w<y;w++)S=c(S,j[w],D);return S?S.join(`
|
|
41
|
+
`):""};function W9(O,D){let M;if(typeof structuredClone<"u")M=structuredClone(O);else M=JSON.parse(JSON.stringify(O));if(M.showHardBlanks=D.showHardBlanks||!1,M.width=D.width||-1,M.whitespaceBreak=D.whitespaceBreak||!1,D.horizontalLayout){let C=j_(D.horizontalLayout,O);if(C)Object.assign(M.fittingRules,C)}if(D.verticalLayout){let C=R0(D.verticalLayout,O);if(C)Object.assign(M.fittingRules,C)}return M.printDirection=D.printDirection!==null&&D.printDirection!==void 0?D.printDirection:O.printDirection,M}let P_=async function(O,D,M){return P_.text(O,D,M)};return P_.text=async function(O,D,M){O=O+"";let C,j;if(typeof D==="function")j=D,C={font:J.font};else if(typeof D==="string")C={font:D},j=M;else if(D)C=D,j=M;else C={font:J.font},j=M;let w=C.font||J.font;try{let y=await P_.loadFont(w),S=y?y1(w,W9(y,C),O):"";if(j)j(null,S);return S}catch(y){let S=y instanceof Error?y:Error(String(y));if(j)return j(S),"";throw S}},P_.textSync=function(O,D){if(O=O+"",typeof D==="string")D={font:D};else D=D||{};let M=D.font||J.font,C=W9(P_.loadFontSync(M),D);return y1(M,C,O)},P_.metadata=async function(O,D){O=O+"";try{let M=await P_.loadFont(O);if(!M)throw Error("Error loading font.");let C=L[O]||{},j=[M,C.comment||""];if(D)D(null,M,C.comment);return j}catch(M){let C=M instanceof Error?M:Error(String(M));if(D)return D(C),null;throw C}},P_.defaults=function(O){if(O&&typeof O==="object")Object.assign(J,O);if(typeof structuredClone<"u")return structuredClone(J);else return JSON.parse(JSON.stringify(J))},P_.parseFont=function(O,D,M=!0){if(L[O]&&!M)return L[O].options;D=D.replace(/\r\n/g,`
|
|
42
42
|
`).replace(/\r/g,`
|
|
43
|
-
`);let C=new
|
|
44
|
-
`),w=
|
|
45
|
-
`),C.numChars=0;while(
|
|
43
|
+
`);let C=new C9,j=D.split(`
|
|
44
|
+
`),w=j.shift();if(!w)throw Error("Invalid font file: missing header");let y=w.split(" "),S={hardBlank:y[0].substring(5,6),height:parseInt(y[1],10),baseline:parseInt(y[2],10),maxLength:parseInt(y[3],10),oldLayout:parseInt(y[4],10),numCommentLines:parseInt(y[5],10),printDirection:y[6]?parseInt(y[6],10):0,fullLayout:y[7]?parseInt(y[7],10):null,codeTagCount:y[8]?parseInt(y[8],10):null};if((S.hardBlank||"").length!==1||[S.height,S.baseline,S.maxLength,S.oldLayout,S.numCommentLines].some((o)=>o===null||o===void 0||isNaN(o)))throw Error("FIGlet header contains invalid values.");if(S.height==null||S.numCommentLines==null)throw Error("FIGlet header contains invalid values.");S.fittingRules=H(S.oldLayout,S.fullLayout),C.options=S;let d=[];for(let o=32;o<=126;o++)d.push(o);if(d.push(196,214,220,228,246,252,223),j.length<S.numCommentLines+S.height*d.length)throw Error(`FIGlet file is missing data. Line length: ${j.length}. Comment lines: ${S.numCommentLines}. Height: ${S.height}. Num chars: ${d.length}.`);C.comment=j.splice(0,S.numCommentLines).join(`
|
|
45
|
+
`),C.numChars=0;while(j.length>0&&C.numChars<d.length){let o=d[C.numChars];C[o]=j.splice(0,S.height);for(let a=0;a<S.height;a++)if(typeof C[o][a]>"u")C[o][a]="";else C[o][a]=X(C[o][a],a,S.height);C.numChars++}while(j.length>0){let o=j.shift();if(!o||o.trim()==="")break;let a=o.split(" ")[0],r;if(/^-?0[xX][0-9a-fA-F]+$/.test(a))r=parseInt(a,16);else if(/^-?0[0-7]+$/.test(a))r=parseInt(a,8);else if(/^-?[0-9]+$/.test(a))r=parseInt(a,10);else throw Error(`Error parsing data. Invalid data: ${a}`);if(r===-1||r<-2147483648||r>2147483647){let T_=r===-1?"The char code -1 is not permitted.":`The char code cannot be ${r<-2147483648?"less than -2147483648":"greater than 2147483647"}.`;throw Error(`Error parsing data. ${T_}`)}C[r]=j.splice(0,S.height);for(let T_=0;T_<S.height;T_++)if(typeof C[r][T_]>"u")C[r][T_]="";else C[r][T_]=X(C[r][T_],T_,S.height);C.numChars++}return L[O]=C,S},P_.loadedFonts=()=>{return Object.keys(L)},P_.clearLoadedFonts=()=>{Object.keys(L).forEach((O)=>{delete L[O]})},P_.loadFont=async function(O,D){if(L[O]){let M=L[O].options;if(D)D(null,M);return Promise.resolve(M)}try{if(!J.fetchFontIfMissing)throw Error(`Font is not loaded: ${O}`);let M=await fetch(`${J.fontPath}/${O}.flf`);if(!M.ok)throw Error(`Network response was not ok: ${M.status}`);let C=await M.text(),j=P_.parseFont(O,C);if(D)D(null,j);return j}catch(M){let C=M instanceof Error?M:Error(String(M));if(D)return D(C),null;throw C}},P_.loadFontSync=function(O){if(L[O])return L[O].options;throw Error("Synchronous font loading is not implemented for the browser, it will only work for fonts already loaded.")},P_.preloadFonts=async function(O,D){try{for(let M of O){let C=await fetch(`${J.fontPath}/${M}.flf`);if(!C.ok)throw Error(`Failed to preload fonts. Error fetching font: ${M}, status code: ${C.statusText}`);let j=await C.text();P_.parseFont(M,j)}if(D)D()}catch(M){let C=M instanceof Error?M:Error(String(M));if(D){D(C);return}throw M}},P_.fonts=function(O){return new Promise(function(D,M){if(D(k5),O)O(null,k5)})},P_.fontsSync=function(){return k5},P_.figFonts=L,P_})();import{fileURLToPath as yN}from"url";var vN=yN(import.meta.url),hN=mT.dirname(vN),kN=mT.join(hN,"/../fonts/"),x_=O9;x_.defaults({fontPath:kN});x_.loadFont=function(_,T){return new Promise((A,E)=>{if(x_.figFonts[_]){if(T)T(null,x_.figFonts[_].options);A(x_.figFonts[_].options);return}d0.readFile(mT.join(x_.defaults().fontPath,_+".flf"),{encoding:"utf-8"},(L,J)=>{if(L){if(T)T(L);E(L);return}J=J+"";try{let X=x_.parseFont(_,J);if(T)T(null,X);A(X)}catch(X){let H=X instanceof Error?X:Error(String(X));if(T)T(H);E(H)}})})};x_.loadFontSync=function(_){if(x_.figFonts[_])return x_.figFonts[_].options;let T=d0.readFileSync(mT.join(x_.defaults().fontPath,_+".flf"),{encoding:"utf-8"})+"";return x_.parseFont(_,T)};x_.fonts=function(_){return new Promise((T,A)=>{let E=[];d0.readdir(x_.defaults().fontPath,(L,J)=>{if(L){_&&_(L),A(L);return}J.forEach((X)=>{if(/\.flf$/.test(X))E.push(X.replace(/\.flf$/,""))}),_&&_(null,E),T(E)})})};x_.fontsSync=function(){let _=[];return d0.readdirSync(x_.defaults().fontPath).forEach((T)=>{if(/\.flf$/.test(T))_.push(T.replace(/\.flf$/,""))}),_};var R9=`flf2a$ 6 5 16 15 13 0 24463 229
|
|
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
|
|
@@ -2278,9 +2278,9 @@ Font modified May 20, 2012 by patorjk to add the 0xCA0 character
|
|
|
2278
2278
|
| (_) | @
|
|
2279
2279
|
$\\___/$ @
|
|
2280
2280
|
@@
|
|
2281
|
-
`;
|
|
2281
|
+
`;x_.parseFont("Standard",R9);function D9(){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 XK=v_(LK(),1);import{Duplex as Ej}from"stream";async function JK(_,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 Ej({read(){},write(Z,Y,K){X.write(Z,Y,K)}});X.on("data",(Z)=>{H.push(Z)}),X.on("end",()=>{H.push(null),J.delete(X)}),X.on("error",(Z)=>{A.debug("[MQTT TCP] Socket error",{error:Z.message}),H.destroy(Z),J.delete(X)}),X.on("close",()=>{J.delete(X)}),H.on("error",(Z)=>{A.debug("[MQTT TCP] Stream error",{error:Z.message}),X.destroy()});try{_.handle(H)}catch(Z){A.error("[MQTT TCP] Error handling connection",{error:Z}),X.destroy()}}),{server:null,tcpServer:E,listen:async(X,H)=>{return new Promise((Z,Y)=>{let K=($)=>{A.error("[MQTT TCP] Server error",{error:$.message,code:$.code,port:X,hostname:H}),Y($)},G=()=>{A.debug("[MQTT TCP] Server listening",{port:X,hostname:H}),E.removeListener("error",K),Z()};E.once("error",K),E.once("listening",G),E.listen(X,H)})},close:async()=>{return new Promise((X)=>{if(E){for(let Z of J)try{Z.destroy()}catch(Y){A.debug("[MQTT TCP] Error destroying socket",{error:Y})}J.clear();let H=setTimeout(()=>{A.warn("[MQTT TCP] Server close timeout, forcing shutdown"),X()},500);E.close(()=>{clearTimeout(H),A.debug("[MQTT] TCP server closed"),X()})}else X()})}}}class mA{servers=null;broker=null;running=!1;startedAt;config;name="CCC MQTT Broker";constructor(_){this.config=_,this.createBrokerInstance()}createBrokerInstance(){this.broker=XK.default({id:"ccc-mqtt-broker",heartbeatInterval:this.config.heartbeatInterval||30000,connectTimeout:this.config.connectTimeout||30000,authenticate:this.authenticate.bind(this)}),this.setupBrokerEvents()}setupBrokerEvents(){let _=v();this.broker.on("client",(T)=>{_.debug("MQTT client connected",{clientId:T.id,clean:T.clean})}),this.broker.on("clientDisconnect",(T)=>{_.debug("MQTT client disconnected",{clientId:T.id})}),this.broker.on("subscribe",(T,A)=>{_.debug("MQTT client subscribed",{clientId:A?.id,topics:T.map((E)=>E.topic)})}),this.broker.on("unsubscribe",(T,A)=>{_.debug("MQTT client unsubscribed",{clientId:A?.id,topics:T})}),this.broker.on("publish",(T,A)=>{if(A)_.debug("MQTT message published",{clientId:A.id,topic:T.topic,qos:T.qos,size:T.payload?.length||0})}),this.broker.on("clientError",(T,A)=>{_.error("MQTT client error",{clientId:T?.id,error:A.message})}),this.broker.on("connectionError",(T,A)=>{_.error("MQTT connection error",{clientId:T?.id,error:A.message})})}async start(){try{let _=v();this.servers=await JK(this.broker,{port:this.config.port,hostname:"localhost"},_),await this.servers.listen(this.config.port,"localhost"),this.running=!0,this.startedAt=new Date,_.debug("MQTT Broker started (TCP only)",{tcpPort:this.config.port,protocols:["mqtt/tcp"]})}catch(_){throw new v8(`Failed to start MQTT broker: ${_ instanceof Error?_.message:String(_)}`)}}async stop(){try{let _=v();if(!this.running)return;if(_.debug("Stopping MQTT Broker"),this.broker?.clients)for(let T of Object.keys(this.broker.clients)){let A=this.broker.clients[T];try{A.close()}catch(E){_.debug("Error closing MQTT client",{clientId:T,error:E})}}if(this.servers)try{await this.servers.close()}catch(T){_.error("Error closing servers",{error:T})}try{await new Promise((T)=>{let A=setTimeout(()=>{_.debug("MQTT broker close timeout, forcing shutdown"),T()},1000);if(this.broker)this.broker.close(()=>{clearTimeout(A),_.debug("MQTT broker closed"),T()});else clearTimeout(A),T()})}catch(T){_.error("Error closing MQTT broker",{error:T})}this.running=!1,_.info("\u2713 MQTT Broker stopped")}catch(_){throw this.running=!1,new v8(`Failed to stop MQTT broker: ${_ instanceof Error?_.message:String(_)}`)}}getStatus(){return{name:"MQTT Broker",running:this.running,port:this.config.port,startedAt:this.startedAt,clientCount:this.broker?.clients?Object.keys(this.broker.clients).length:0}}authenticate(_,T,A,E){let L=v();if(!this.config.auth){L.debug("No authentication configured, allowing MQTT connection",{clientId:_.id}),E(null,!0);return}let J=A?.toString();if(T===this.config.auth.username&&J===this.config.auth.password)L.debug("MQTT client authenticated successfully",{clientId:_.id,username:T}),E(null,!0);else L.warn("MQTT client authentication failed",{clientId:_.id,username:T}),E(Error("Invalid credentials"),!1)}}var cU=v_(dU(),1);var I1=v();class K5{name="Backend MQTT Client";client=null;running=!1;connected=!1;startedAt;config;subscriptions=new Map;constructor(_){this.config=_}async start(){return new Promise((_,T)=>{try{let A=`mqtt://${this.config.host}:${this.config.port}`;this.client=cU.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 pU=5,Uh=900000;class pL{credentials;failedAttempts=new Map;blockedIPs=new Map;logger=v();constructor(){this.credentials=this.generateCredentials(),this.logger.debug("Terminal credentials generated",{username:this.credentials.username})}getCredentials(){return this.credentials}authenticate(_,T,A){let E=this.blockedIPs.get(A);if(E&&E>Date.now())throw new h8("IP temporarily blocked due to too many failed attempts");if(_===this.credentials.username&&T===this.credentials.password)return this.failedAttempts.delete(A),this.blockedIPs.delete(A),!0;let L=(this.failedAttempts.get(A)||0)+1;if(this.failedAttempts.set(A,L),L>=pU)this.blockedIPs.set(A,Date.now()+Uh),this.failedAttempts.delete(A),this.logger.warn(`IP blocked after ${pU} failed attempts`,{ip:A});throw new h8("Invalid credentials")}generateCredentials(){let _=this.generateRandomString(32),T=this.generateRandomString(480);return{username:_,password:T}}generateRandomString(_){let A="",E=new Uint8Array(_);crypto.getRandomValues(E);for(let L=0;L<_;L++){let J=E[L]??0;A+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;,.<>?"[J%87]}return A}}import{spawn as Wh}from"bun-pty";var lU=5,Nh=300000,Qh=102400;class lL{sessions=new Map;projectPath=process.cwd();logger=v();createSession(_,T=80,A=24){if(Array.from(this.sessions.values()).filter((L)=>!L.disconnectedAt).length>=lU)throw new XT(`Maximum concurrent sessions (${lU}) reached`);try{let L=process.platform==="win32"?"powershell.exe":"bash",J=Wh(L,[],{name:"xterm-256color",cols:T,rows:A,cwd:this.projectPath,env:process.env}),X={id:_,createdAt:new Date,lastActivityAt:new Date};this.sessions.set(_,{pty:J,session:X,cwd:this.projectPath,outputBuffer:[]}),this.logger.debug(`PTY session created: ${_}`,{cols:T,rows:A,cwd:this.projectPath,pid:J.pid})}catch(L){throw this.logger.error("Failed to create PTY session",L),new XT(`Failed to create PTY session: ${L instanceof Error?L.message:String(L)}`)}}getSession(_){let T=this.sessions.get(_);if(T)return T.session.lastActivityAt=new Date,T.pty;return null}writeToSession(_,T){let A=this.sessions.get(_);if(!A)return!1;try{return A.pty.write(T),!0}catch(E){return this.logger.debug("PTY write failed (session may be closing)",{sessionId:_,error:E instanceof Error?E.message:String(E)}),!1}}setupDataHandler(_,T){let A=this.sessions.get(_);if(A)A.dataHandler=T,A.pty.onData((E)=>{let L=this.sessions.get(_);if(!L)return;if(L.disconnectedAt){if(L.outputBuffer.reduce((X,H)=>X+H.length,0)<Qh)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(_)},Nh),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 nU(_){return`<!DOCTYPE html>
|
|
2283
|
+
`)}var KK=q_(ZK(),1);import{Duplex as Xj}from"stream";async function YK(_,T,A){let E=null,L=await import("net"),J=new Set;return E=L.createServer((X)=>{A.debug("[MQTT TCP] Client socket connected"),J.add(X);let H=new Xj({read(){},write(Z,Y,K){X.write(Z,Y,K)}});X.on("data",(Z)=>{H.push(Z)}),X.on("end",()=>{H.push(null),J.delete(X)}),X.on("error",(Z)=>{A.debug("[MQTT TCP] Socket error",{error:Z.message}),H.destroy(Z),J.delete(X)}),X.on("close",()=>{J.delete(X)}),H.on("error",(Z)=>{A.debug("[MQTT TCP] Stream error",{error:Z.message}),X.destroy()});try{_.handle(H)}catch(Z){A.error("[MQTT TCP] Error handling connection",{error:Z}),X.destroy()}}),{server:null,tcpServer:E,listen:async(X,H)=>{return new Promise((Z,Y)=>{let K=(G)=>{A.error("[MQTT TCP] Server error",{error:G.message,code:G.code,port:X,hostname:H}),Y(G)},$=()=>{A.debug("[MQTT TCP] Server listening",{port:X,hostname:H}),E.removeListener("error",K),Z()};E.once("error",K),E.once("listening",$),E.listen(X,H)})},close:async()=>{return new Promise((X)=>{if(E){for(let Z of J)try{Z.destroy()}catch(Y){A.debug("[MQTT TCP] Error destroying socket",{error:Y})}J.clear();let H=setTimeout(()=>{A.warn("[MQTT TCP] Server close timeout, forcing shutdown"),X()},500);E.close(()=>{clearTimeout(H),A.debug("[MQTT] TCP server closed"),X()})}else X()})}}}class mA{servers=null;broker=null;running=!1;startedAt;config;name="CCC MQTT Broker";constructor(_){this.config=_,this.createBrokerInstance()}createBrokerInstance(){this.broker=KK.default({id:"ccc-mqtt-broker",heartbeatInterval:this.config.heartbeatInterval||30000,connectTimeout:this.config.connectTimeout||30000,authenticate:this.authenticate.bind(this)}),this.setupBrokerEvents()}setupBrokerEvents(){let _=v();this.broker.on("client",(T)=>{_.debug("MQTT client connected",{clientId:T.id,clean:T.clean})}),this.broker.on("clientDisconnect",(T)=>{_.debug("MQTT client disconnected",{clientId:T.id})}),this.broker.on("subscribe",(T,A)=>{_.debug("MQTT client subscribed",{clientId:A?.id,topics:T.map((E)=>E.topic)})}),this.broker.on("unsubscribe",(T,A)=>{_.debug("MQTT client unsubscribed",{clientId:A?.id,topics:T})}),this.broker.on("publish",(T,A)=>{if(A)_.debug("MQTT message published",{clientId:A.id,topic:T.topic,qos:T.qos,size:T.payload?.length||0})}),this.broker.on("clientError",(T,A)=>{_.error("MQTT client error",{clientId:T?.id,error:A.message})}),this.broker.on("connectionError",(T,A)=>{_.error("MQTT connection error",{clientId:T?.id,error:A.message})})}async start(){try{let _=v();this.servers=await YK(this.broker,{port:this.config.port,hostname:"localhost"},_),await this.servers.listen(this.config.port,"localhost"),this.running=!0,this.startedAt=new Date,_.debug("MQTT Broker started (TCP only)",{tcpPort:this.config.port,protocols:["mqtt/tcp"]})}catch(_){throw new v8(`Failed to start MQTT broker: ${_ instanceof Error?_.message:String(_)}`)}}async stop(){try{let _=v();if(!this.running)return;if(_.debug("Stopping MQTT Broker"),this.broker?.clients)for(let T of Object.keys(this.broker.clients)){let A=this.broker.clients[T];try{A.close()}catch(E){_.debug("Error closing MQTT client",{clientId:T,error:E})}}if(this.servers)try{await this.servers.close()}catch(T){_.error("Error closing servers",{error:T})}try{await new Promise((T)=>{let A=setTimeout(()=>{_.debug("MQTT broker close timeout, forcing shutdown"),T()},1000);if(this.broker)this.broker.close(()=>{clearTimeout(A),_.debug("MQTT broker closed"),T()});else clearTimeout(A),T()})}catch(T){_.error("Error closing MQTT broker",{error:T})}this.running=!1,_.info("\u2713 MQTT Broker stopped")}catch(_){throw this.running=!1,new v8(`Failed to stop MQTT broker: ${_ instanceof Error?_.message:String(_)}`)}}getStatus(){return{name:"MQTT Broker",running:this.running,port:this.config.port,startedAt:this.startedAt,clientCount:this.broker?.clients?Object.keys(this.broker.clients).length:0}}authenticate(_,T,A,E){let L=v();if(!this.config.auth){L.debug("No authentication configured, allowing MQTT connection",{clientId:_.id}),E(null,!0);return}let J=A?.toString();if(T===this.config.auth.username&&J===this.config.auth.password)L.debug("MQTT client authenticated successfully",{clientId:_.id,username:T}),E(null,!0);else L.warn("MQTT client authentication failed",{clientId:_.id,username:T}),E(Error("Invalid credentials"),!1)}}var iU=q_(nU(),1);var P1=v();class K5{name="Backend MQTT Client";client=null;running=!1;connected=!1;startedAt;config;subscriptions=new Map;constructor(_){this.config=_}async start(){return new Promise((_,T)=>{try{let A=`mqtt://${this.config.host}:${this.config.port}`;this.client=iU.default.connect(A,{clientId:"backend-client",clean:!0,connectTimeout:5000,username:this.config.username,password:this.config.password}),this.client.on("connect",()=>{this.connected=!0,this.running=!0,this.startedAt=new Date,P1.info("[BackendClient] Connected to MQTT broker"),_()}),this.client.on("error",(E)=>{if(P1.error("[BackendClient] MQTT error",{error:E.message}),!this.connected)T(E)}),this.client.on("close",()=>{this.connected=!1,P1.debug("[BackendClient] Disconnected from MQTT broker")}),this.client.on("message",(E,L)=>{this.handleMessage(E,L)})}catch(A){P1.error("[BackendClient] Failed to start",A),T(A)}})}async stop(){return new Promise((_)=>{if(!this.client){this.running=!1,_();return}this.client.end(!1,{},()=>{this.running=!1,this.connected=!1,this.subscriptions.clear(),P1.info("[BackendClient] Stopped"),_()})})}subscribe(_,T){if(!this.client)throw Error("MQTT client not initialized");if(!this.subscriptions.has(_))this.subscriptions.set(_,new Set),this.client.subscribe(_,{qos:1},(A)=>{if(A)P1.error(`[BackendClient] Failed to subscribe to ${_}`,{error:A.message});else P1.debug(`[BackendClient] Subscribed to ${_}`)});this.subscriptions.get(_).add(T)}unsubscribe(_,T){if(!this.client)return;let A=this.subscriptions.get(_);if(!A)return;if(A.delete(T),A.size===0)this.subscriptions.delete(_),this.client.unsubscribe(_,(E)=>{if(E)P1.error(`[BackendClient] Failed to unsubscribe from ${_}`,{error:E.message});else P1.debug(`[BackendClient] Unsubscribed from ${_}`)})}publish(_,T,A){return new Promise((E,L)=>{if(!this.client){L(Error("MQTT client not initialized"));return}this.client.publish(_,T,{qos:A?.qos||1},(J)=>{if(J)P1.error(`[BackendClient] Failed to publish to ${_}`,{error:J.message}),L(J);else P1.debug(`[BackendClient] Published to ${_}`),E()})})}topicToRegex(_){let T=_.replace(/[.\\^${}|[\]()]/g,"\\$&").replace(/\+/g,"[^/]+").replace(/#/g,".*");return new RegExp(`^${T}$`)}handleMessage(_,T){this.subscriptions.forEach((A,E)=>{if(this.topicToRegex(E).test(_))A.forEach((J)=>{try{J(_,T)}catch(X){P1.error(`[BackendClient] Error in message handler for ${_}`,{error:X instanceof Error?X.message:"Unknown error"})}})})}getStatus(){return{name:this.name,running:this.running,connected:this.connected,startedAt:this.startedAt}}}var aU=5,Qh=900000;class nL{credentials;failedAttempts=new Map;blockedIPs=new Map;logger=v();constructor(){this.credentials=this.generateCredentials(),this.logger.debug("Terminal credentials generated",{username:this.credentials.username})}getCredentials(){return this.credentials}authenticate(_,T,A){let E=this.blockedIPs.get(A);if(E&&E>Date.now())throw new h8("IP temporarily blocked due to too many failed attempts");if(_===this.credentials.username&&T===this.credentials.password)return this.failedAttempts.delete(A),this.blockedIPs.delete(A),!0;let L=(this.failedAttempts.get(A)||0)+1;if(this.failedAttempts.set(A,L),L>=aU)this.blockedIPs.set(A,Date.now()+Qh),this.failedAttempts.delete(A),this.logger.warn(`IP blocked after ${aU} failed attempts`,{ip:A});throw new h8("Invalid credentials")}generateCredentials(){let _=this.generateRandomString(32),T=this.generateRandomString(480);return{username:_,password:T}}generateRandomString(_){let A="",E=new Uint8Array(_);crypto.getRandomValues(E);for(let L=0;L<_;L++){let J=E[L]??0;A+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;,.<>?"[J%87]}return A}}var iL=null;async function Mh(){if(!iL)iL=await import("bun-pty");return iL}var oU=5,Vh=300000,zh=102400;class aL{sessions=new Map;projectPath=process.cwd();logger=v();async createSession(_,T=80,A=24){if(Array.from(this.sessions.values()).filter((L)=>!L.disconnectedAt).length>=oU)throw new HT(`Maximum concurrent sessions (${oU}) reached`);try{let{spawn:L}=await Mh(),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)<zh)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(_)},Vh),this.logger.debug(`PTY session disconnected: ${_}`)}}resumeSession(_,T,A){let E=this.sessions.get(_);if(!E)return this.logger.warn(`Cannot resume - session not found: ${_}`),null;if(E.disconnectTimeout)clearTimeout(E.disconnectTimeout),E.disconnectTimeout=void 0;E.disconnectedAt=void 0,E.session.lastActivityAt=new Date;try{E.pty.resize(T,A)}catch(J){this.logger.debug(`Resize on resume failed: ${_}`,{error:J})}let L=E.outputBuffer;return E.outputBuffer=[],this.logger.debug(`PTY session resumed: ${_}`),L}canResumeSession(_){return this.sessions.get(_)!==void 0}findSessionByCwd(_){for(let[T,A]of this.sessions.entries())if(A.cwd===_)return T;return null}getSessionInfo(_){let T=this.sessions.get(_);if(!T)return null;return{id:_,cwd:T.cwd,disconnected:!!T.disconnectedAt,createdAt:T.session.createdAt}}closeSession(_){let T=this.sessions.get(_);if(T){if(T.disconnectTimeout)clearTimeout(T.disconnectTimeout);this.sessions.delete(_);try{T.pty.kill(),this.logger.debug(`PTY session closed: ${_}`)}catch(A){this.logger.debug(`PTY cleanup (may be expected): ${_}`,{error:A instanceof Error?A.message:String(A)})}}}closeAllSessions(){for(let _ of this.sessions.keys())this.closeSession(_)}setProjectPath(_){this.projectPath=_,this.logger.debug(`Terminal project path set to: ${_}`)}getActiveSessionCount(){return this.sessions.size}resizeSession(_,T,A){let E=this.sessions.get(_);if(E)try{E.pty.resize(T,A)}catch(L){this.logger.error(`Error resizing session ${_}`,L)}}}function rU(_){return`<!DOCTYPE html>
|
|
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
|
|
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();this.ptyManager.createSession(K,X,H),this.sessionMap.set(_,K),this.ptyManager.setupDataHandler(K,(
|
|
2609
|
+
</html>`}class $5{server=null;authenticator;ptyManager;running=!1;startedAt;config;logger=v();sessionMap=new Map;name="CCC Terminal Service";constructor(_){this.config=_,this.authenticator=new nL,this.ptyManager=new aL}async start(){try{this.server=Bun.serve({hostname:"localhost",port:this.config.port,fetch:(_,T)=>this.handleRequest(_,T),websocket:{open:(_)=>this.handleWebSocketOpen(_),message:(_,T)=>this.handleWebSocketMessage(_,T),close:(_)=>this.handleWebSocketClose(_)}}),this.running=!0,this.startedAt=new Date,this.logger.debug(`Terminal Server started on localhost:${this.config.port}`)}catch(_){throw new HT(`Failed to start terminal server: ${_ instanceof Error?_.message:String(_)}`)}}async stop(){try{if(!this.running)return;if(this.ptyManager.closeAllSessions(),this.server)this.server.stop();this.running=!1,this.logger.debug("Terminal Server stopped")}catch(_){throw new HT(`Failed to stop terminal server: ${_ instanceof Error?_.message:String(_)}`)}}getStatus(){return{name:"Terminal Server",running:this.running,port:this.config.port,startedAt:this.startedAt,credentials:this.authenticator.getCredentials(),activeSessions:this.ptyManager.getActiveSessionCount()}}setProjectPath(_){this.ptyManager.setProjectPath(_)}findSessionByProjectPath(_){return this.ptyManager.findSessionByCwd(_)}getSessionInfo(_){return this.ptyManager.getSessionInfo(_)}authenticateRequest(_){let T=new URL(_.url),A="unknown",E=T.searchParams.get("auth");if(E)try{let J=Buffer.from(E,"base64").toString("utf-8"),X=J.indexOf(":");if(X===-1)return this.logger.debug("Auth param missing colon delimiter"),!1;let H=J.substring(0,X),Z=J.substring(X+1);return this.logger.debug("Auth via query param",{username:H.substring(0,8)+"..."}),this.authenticator.authenticate(H,Z,"unknown")}catch(J){return this.logger.debug("Auth param error",{error:String(J)}),!1}let L=_.headers.get("authorization");if(L?.startsWith("Basic "))try{let J=L.slice(6),X=Buffer.from(J,"base64").toString("utf-8"),H=X.indexOf(":");if(H===-1)return this.logger.debug("Auth header missing colon delimiter"),!1;let Z=X.substring(0,H),Y=X.substring(H+1);return this.logger.debug("Auth via header",{username:Z.substring(0,8)+"..."}),this.authenticator.authenticate(Z,Y,"unknown")}catch(J){return this.logger.debug("Auth header error",{error:String(J)}),!1}return this.logger.debug("No auth credentials provided",{hasAuthParam:!!E,hasAuthHeader:!!L}),!1}handleRequest(_,T){let A=new URL(_.url);if(A.pathname==="/terminal/ws"||A.pathname==="/terminal"){if(_.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!this.authenticateRequest(_))return new Response("Unauthorized",{status:401});if(T.upgrade(_,{data:{type:"terminal-ws",url:A.toString(),authenticated:!0}}))return new Response;return new Response("WebSocket upgrade failed",{status:400})}}if(A.pathname==="/terminal"&&_.method==="GET"){if(!this.authenticateRequest(_))return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":'Basic realm="Terminal"',"Content-Type":"text/plain"}});let E=this.authenticator.getCredentials(),L=rU(E);return new Response(L,{headers:{"Content-Type":"text/html; charset=utf-8","Content-Length":Buffer.byteLength(L).toString(),"Cache-Control":"no-cache, no-store, must-revalidate"}})}return new Response("Not Found",{status:404})}handleWebSocketOpen(_){this.logger.debug("WebSocket connection opened (authenticated)")}async handleWebSocketMessage(_,T){try{let A;if(typeof T==="string")A=T;else if(T instanceof ArrayBuffer)A=new TextDecoder().decode(T);else if(T instanceof Uint8Array)A=new TextDecoder().decode(T);else return;let E=this.sessionMap.get(_);if(A.startsWith("INIT:")||A.startsWith("RESIZE:")||A.startsWith("RESUME:")){let L=A.startsWith("INIT:")?"INIT:":A.startsWith("RESUME:")?"RESUME:":"RESIZE:",J=JSON.parse(A.substring(L.length)),{cols:X,rows:H,cwd:Z,sessionId:Y}=J;if(!X||!H){this.logger.warn("Invalid dimensions received",{cols:X,rows:H});return}if(L==="RESUME:"&&Y){if(this.ptyManager.canResumeSession(Y)){this.logger.debug(`Resuming session: ${Y}`),this.sessionMap.set(_,Y),this.ptyManager.updateDataHandler(Y,($)=>{try{if(_.readyState===1)_.send($)}catch(G){}});let K=this.ptyManager.resumeSession(Y,X,H);if(_.send(`SESSION:${Y}`),K&&K.length>0)for(let $ of K)try{if(_.readyState===1)_.send($)}catch(G){break}_.send(`\x1B[38;5;209m\u2713 Session resumed\x1B[0m\r
|
|
2610
|
+
`)}else this.logger.debug(`Session not found for resume: ${Y}`),_.send("SESSION_NOT_FOUND");return}if(!E&&L==="INIT:"){if(Z)this.ptyManager.setProjectPath(Z),this.logger.debug(`Terminal working directory set to: ${Z}`);let K=crypto.randomUUID();await this.ptyManager.createSession(K,X,H),this.sessionMap.set(_,K),this.ptyManager.setupDataHandler(K,($)=>{try{if(_.readyState===1)_.send($)}catch(G){}}),_.send(`SESSION:${K}`),_.send(`\x1B[38;5;209m\u2713 Connected to CCC Terminal\x1B[0m\r
|
|
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
|
|
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=
|
|
2612
|
+
`)}else if(E&&L==="RESIZE:")this.ptyManager.resizeSession(E,X,H);return}if(E)if(this.ptyManager.getSession(E))this.ptyManager.writeToSession(E,A);else this.logger.warn("PTY session not found",{sessionId:E})}catch(A){this.logger.error("Error handling WebSocket message",A)}}handleWebSocketClose(_){let T=this.sessionMap.get(_);if(T)this.sessionMap.delete(_),this.ptyManager.disconnectSession(T)}}import*as G5 from"http";import*as tU from"net";import{WebSocketServer as Fh,WebSocket as sU}from"ws";class U5{server=null;wss=null;running=!1;startedAt;config;logger=v();routes=[{path:"/mqtt",target:"localhost:8884"},{path:"/terminal",target:"localhost:3001"}];activeBrokerSockets=new Set;name="CCC Router Service";constructor(_){this.config=_}async start(){return new Promise((_,T)=>{try{this.server=G5.createServer((A,E)=>{this.handleHttpRequest(A,E)}),this.wss=new Fh({noServer:!0}),this.server.on("upgrade",(A,E,L)=>{this.handleWebSocketUpgrade(A,E,L)}),this.server.on("error",(A)=>{this.logger.error("Router error",{error:A instanceof Error?A.message:String(A)}),T(A)}),this.server.listen(this.config.port,"0.0.0.0",()=>{this.running=!0,this.startedAt=new Date,this.logger.debug(`Router started on 0.0.0.0:${this.config.port}`),this.logger.debug(`Routes: ${this.routes.map((A)=>`${A.path} -> ${A.target}`).join(", ")}`),_()})}catch(A){T(new v5(`Failed to start router: ${A instanceof Error?A.message:String(A)}`))}})}handleHttpRequest(_,T){let A=_.url||"/",E=this.findRoute(A);if(!E){T.writeHead(404,{"Content-Type":"text/plain"}),T.end("Not Found");return}this.forwardHttpRequest(_,T,E)}forwardHttpRequest(_,T,A){let[E,L]=A.target.split(":"),J=parseInt(L||"8883",10),X={hostname:E||"localhost",port:J,path:_.url,method:_.method,headers:_.headers},H=G5.request(X,(Z)=>{T.writeHead(Z.statusCode||200,Z.headers),Z.pipe(T)});H.on("error",(Z)=>{this.logger.error("HTTP proxy error",{error:Z instanceof Error?Z.message:String(Z),target:A.target,path:_.url,method:_.method,code:Z.code}),T.writeHead(502,{"Content-Type":"text/plain"}),T.end(`Bad Gateway - Unable to connect to backend service
|
|
2613
|
+
`)}),_.pipe(H)}async stop(){if(!this.server&&!this.wss)return;return new Promise((_)=>{for(let T of this.activeBrokerSockets)try{T.destroy()}catch(A){this.logger.debug("Error destroying broker socket",{error:A})}if(this.activeBrokerSockets.clear(),this.wss)this.wss.clients?.forEach((T)=>{T.close(1000,"Server shutting down")}),this.wss.close(),this.wss=null;if(this.server){let T=setTimeout(()=>{this.logger.warn("Server close timeout, forcing shutdown"),this.running=!1,this.server=null,_()},500);this.server.close(()=>{clearTimeout(T),this.logger.debug("Router stopped"),this.running=!1,this.server=null,_()})}else _()})}getStatus(){return{name:"Router",running:this.running,port:this.config.port,startedAt:this.startedAt,routes:this.routes}}addRoute(_,T){let A=this.routes.findIndex((E)=>E.path===_);if(A>=0&&this.routes[A])this.routes[A].target=T;else this.routes.push({path:_,target:T});if(this.config.debug)this.logger.debug(`Route added: ${_} -> ${T}`)}handleWebSocketUpgrade(_,T,A){let E=_.url||"/";this.logger.debug("WebSocket upgrade request",{url:E});let L=this.findRoute(E);if(!L){this.logger.warn("WebSocket upgrade to unknown path",{url:E}),T.destroy();return}this.wss?.handleUpgrade(_,T,A,(J)=>{if(E.startsWith("/mqtt"))this.bridgeWebSocketToTcp(J,L);else this.bridgeWebSocketToWebSocket(J,L,E)})}bridgeWebSocketToTcp(_,T){let[A,E]=T.target.split(":"),L=parseInt(E||"8883",10);this.logger.debug("WebSocket-to-TCP bridge established",{target:T.target});let J=tU.connect(L,A||"localhost",()=>{this.logger.debug("Connected to MQTT broker",{target:T.target})});this.activeBrokerSockets.add(J),_.on("message",(X)=>{if(!J.destroyed&&J.writable)J.write(X);else this.logger.warn("Broker socket not writable")}),J.on("data",(X)=>{_.send(X,(H)=>{if(H)this.logger.error("Error sending WebSocket message",{error:H instanceof Error?H.message:String(H)})})}),_.on("close",()=>{this.logger.debug("WebSocket client closed"),J.destroy()}),_.on("error",(X)=>{this.logger.error("WebSocket error",{error:X.message}),J.destroy()}),J.on("close",()=>{this.logger.debug("MQTT broker connection closed"),this.activeBrokerSockets.delete(J),_.close()}),J.on("error",(X)=>{this.logger.error("MQTT broker error",{error:X.message,target:T.target}),this.activeBrokerSockets.delete(J),_.close()})}bridgeWebSocketToWebSocket(_,T,A){let[E,L]=T.target.split(":"),J=parseInt(L||"3001",10),H=`ws://${E||"localhost"}:${J}${A}`;this.logger.debug("WebSocket-to-WebSocket bridge connecting",{target:H});let Z=new sU(H),Y=[],K=!1;Z.on("open",()=>{K=!0;while(Y.length>0){let $=Y.shift();Z.send($)}}),_.on("message",($)=>{let G=typeof $==="string"?$:$.toString("utf-8");if(K&&Z.readyState===sU.OPEN)Z.send(G);else Y.push(G)}),Z.on("message",($)=>{let G=typeof $==="string"?$:$.toString("utf-8");if(_.readyState===1)_.send(G)}),_.on("close",()=>{Z.close()}),_.on("error",($)=>{this.logger.error("Client WebSocket error",{error:$.message}),Z.close()}),Z.on("close",()=>{_.close()}),Z.on("error",($)=>{this.logger.error("Target WebSocket error",{error:$.message}),_.close()})}findRoute(_){let T=_.split("?")[0]||_,A=this.routes.find((E)=>E.path===T);if(A)return A;return this.routes.find((E)=>T.startsWith(E.path+"/")||T===E.path)}}var oL=null;async function Ch(){if(!oL)oL=await import("@ngrok/ngrok");return oL.default}class W5{listener;tunnelUrl=null;running=!1;startedAt;config;name="CCC Ngrok Service";constructor(_){this.config=_}async start(){try{let _=v();_.debug("Starting ngrok tunnel",{port:this.config.routerPort,domain:this.config.domain||"(auto)"});let T={authtoken:this.config.authToken,addr:`localhost:${this.config.routerPort}`};if(this.config.domain)T.domain=this.config.domain;let A=await Ch();this.listener=await A.forward(T),this.tunnelUrl=this.listener.url(),this.running=!0,this.startedAt=new Date;let E=this.tunnelUrl?.replace(/^https?:\/\//,"");_.debug("ngrok tunnel established",{url:E,fullUrl:this.tunnelUrl})}catch(_){let T=v(),A=_ instanceof Error?_.message:String(_);throw T.error("Failed to start ngrok tunnel",_),Error(`ngrok tunnel failed: ${A}`)}}async stop(){try{let _=v();if(!this.running)return;if(_.debug("Stopping ngrok tunnel"),this.listener)await Promise.race([this.listener.close(),new Promise((T)=>{setTimeout(()=>{_.warn("ngrok listener close timeout, forcing shutdown"),T()},3000)})]);this.running=!1,this.tunnelUrl=null,_.debug("ngrok tunnel closed")}catch(_){v().error("Error stopping ngrok tunnel",_)}}getStatus(){return{name:this.name,running:this.running,active:this.isActive(),tunnelUrl:this.tunnelUrl?this.tunnelUrl.replace(/^https?:\/\//,""):void 0,routerPort:this.config.routerPort,startedAt:this.startedAt}}getUrl(){return this.tunnelUrl}isActive(){return!!this.listener&&!!this.tunnelUrl}}var RW=q_(OW(),1);class V5{running=!1;startedAt;config;codesGenerated=0;name="CCC QR Code Service";constructor(_){this.config=_}async start(){try{let _=v();_.debug("QR Code Service starting"),this.running=!0,this.startedAt=new Date,this.display(),_.debug("QR Code Service started")}catch(_){throw v().error("Failed to start QR Code service",_),this.running=!1,_}}async stop(){try{let _=v();if(!this.running)return;this.running=!1,_.debug("QR Code Service stopped")}catch(_){v().error("Error stopping QR Code service",_)}}getStatus(){return{name:this.name,running:this.running,codesGenerated:this.codesGenerated,urls:{mdns:this.config.mdnsUrl,ipBased:this.config.ipBasedUrl,ngrok:this.config.ngrokUrl},startedAt:this.startedAt}}display(){let _=v();try{if(this.codesGenerated=0,console.log(`
|
|
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);
|
|
2616
|
-
`),Z=[];for(let K of H)try{if(!K.trim())continue;let
|
|
2615
|
+
`)}catch(T){_.error("Error displaying QR codes",T)}}updateConfig(_){if(this.config={...this.config,..._},this.running)this.display()}displayQRCode(_,T,A,E,L){let J={serverUrl:_,useSSL:E,profileName:L};if(T)J.username=T;if(A)J.password=A;let X=JSON.stringify(J);RW.default.generate(X,{small:!0});let H=this.getLabel(_,E);console.log(`${H}`),console.log(` Server: ${_}`),console.log(` Profile: ${L}`),console.log(` Username: ${T?`${T.substring(0,8)}...`:"(none)"}`),console.log(` Password: ${A?"***":"(none)"}`),console.log(` SSL/TLS: ${E?"Yes (wss)":"No (ws)"}`)}getLabel(_,T){if(_.includes("ngrok"))return"\uD83C\uDF10 REMOTE CONNECTION (ngrok)";if(_.includes(".")){let A=_?.split(":")[0]?.split(".")||[];if(A.length===4&&A.every((E)=>!isNaN(Number(E))))return"\uD83D\uDD04 IP-BASED CONNECTION"}return"\uD83D\uDCF1 LOCAL NETWORK CONNECTION (mDNS)"}}var x1=v();function DW(_){switch(_){case"alpha":return"alpha";case"beta":return"beta";default:return"latest"}}async function BW(_){let T=G1(),A=XT(T);x1.debug("Checking for updates",{currentVersion:T,releaseChannel:A,packageName:_});try{let E=DW(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=y5(X,T);return x1.debug("Version comparison result",{currentVersion:T,latestVersion:X,updateAvailable:H,isNewer:y5(X,T)}),x1.debug("Update check completed",{currentVersion:T,latestVersion:X,updateAvailable:H,releaseChannel:A,distTag:E}),{updateAvailable:H,currentVersion:T,latestVersion:X,releaseChannel:A}}catch(E){return x1.error("Error checking for updates",{error:E}),{updateAvailable:!1,currentVersion:T,latestVersion:T,releaseChannel:A}}}async function qW(_){let T=G1(),A=XT(T),E=DW(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 z5{name="CCC Auto-Update Service";config;running=!1;enabled=!1;logger=v();checkInterval=null;lastCheckTime;nextCheckTime;updateAvailable=!1;latestVersion;startedAt;constructor(_){this.config={checkIntervalMinutes:60,..._},this.enabled=_.enabled}async start(){try{if(this.logger.debug("Starting Auto-Update Service",{enabled:this.enabled,packageName:this.config.packageName,checkIntervalMinutes:this.config.checkIntervalMinutes}),!this.enabled){this.logger.info("Auto-Update Service disabled"),this.running=!1;return}this.running=!0,this.startedAt=new Date,this.logger.info("Performing initial update check"),await this.performUpdateCheck(),this.scheduleNextCheck(),this.logger.info("Auto-Update Service started",{nextCheckTime:this.nextCheckTime})}catch(_){throw this.logger.error("Failed to start Auto-Update Service",_),_}}async stop(){try{if(!this.running)return;if(this.checkInterval)clearInterval(this.checkInterval),this.checkInterval=null;this.running=!1,this.logger.debug("Auto-Update Service stopped")}catch(_){throw this.logger.error("Failed to stop Auto-Update Service",_),_}}getStatus(){return{name:this.name,running:this.running,enabled:this.enabled,lastCheckTime:this.lastCheckTime,nextCheckTime:this.nextCheckTime,currentVersion:G1(),updateAvailable:this.updateAvailable,latestVersion:this.latestVersion,releaseChannel:XT(G1()),startedAt:this.startedAt}}scheduleNextCheck(){if(!this.enabled)return;let _=(this.config.checkIntervalMinutes||60)*60*1000;if(this.nextCheckTime=new Date(Date.now()+_),this.checkInterval)clearInterval(this.checkInterval);this.checkInterval=setInterval(async()=>{try{await this.performUpdateCheck(),this.scheduleNextCheck()}catch(T){this.logger.error("Error in scheduled update check",T)}},_),this.logger.debug("Next update check scheduled",{nextCheckTime:this.nextCheckTime,intervalMinutes:this.config.checkIntervalMinutes})}async performUpdateCheck(){this.lastCheckTime=new Date;try{this.logger.debug("Performing update check",{packageName:this.config.packageName,currentVersion:G1()});let{updateAvailable:_,latestVersion:T,currentVersion:A,releaseChannel:E}=await BW(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 qW(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 Sh,readdirSync as yh,existsSync as vh}from"fs";import{stat as xW}from"fs/promises";import{join as gT,basename as hh}from"path";import{homedir as wW}from"os";import*as o_ from"path";import*as T9 from"os";var M4=v();class IW{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 PW=new IW;var Q1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6},xh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,wh="worktrees",F_=v();class jW{claudeProjectsDir;cccDir;constructor(){this.claudeProjectsDir=o_.join(T9.homedir(),".claude","projects"),this.cccDir=o_.join(T9.homedir(),".ccc")}async getWorktreePathsForProject(_){let T=await import("fs"),A=o_.basename(_),E=o_.join(this.cccDir,`${A}-${wh}`);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
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((
|
|
2619
|
-
`),L=null,J=0,X=0;for(let R of E){if(!R.trim())continue;try{let q=JSON.parse(R);X++;let f=null;if(q.type==="assistant"){if(q.message?.usage)f=q.message.usage;else if(q.usage)f=q.usage}if(q.type==="result"&&q.usage)f=q.usage;if(f&&(f.input_tokens!==void 0||f.output_tokens!==void 0))L=f,J++}catch{continue}}if(F_.debug("[SessionManager] Context calculation stats:",{sessionFile:o_.basename(_),totalMessages:X,messagesWithUsage:J,hasUsage:!!L,mostRecentUsage:L?{input:L.input_tokens,output:L.output_tokens,cacheCreate:L.cache_creation_input_tokens,cacheRead:L.cache_read_input_tokens}:null}),!L)return F_.warn("[SessionManager] No usage data found in session file:",_),this.getEmptyContextBreakdown();let H=L.input_tokens||0,Z=L.output_tokens||0,Y=L.cache_creation_input_tokens||0,K=L.cache_read_input_tokens||0,G=H+Y+K,$=N1.SYSTEM_PROMPT,U=N1.TOOLS_TOTAL,V=0,N=N1.AUTOCOMPACT_BUFFER,z=Math.max(0,G-$-U-V),Q=G+N,F=N1.CONTEXT_LIMIT_STANDARD;return F_.info("[SessionManager] Context breakdown calculated:",{total:Q,apiTokens:G,inputTokens:H,cacheCreation:Y,cacheRead:K,percentage:Math.round(Q/F*100),breakdown:{systemPrompt:$,tools:U,mcpServers:V,messages:z,autocompactBuffer:N,remaining:Math.max(0,F-Q)}}),{total:Q,inputTokens:H,outputTokens:Z,cacheCreation:Y,cacheRead:K,systemPrompt:$,tools:U,mcpServers:V,messages:z,autocompactBuffer:N,contextLimit:F,remaining:Math.max(0,F-Q),percentage:Math.round(Q/F*100),lastUpdated:Date.now()}}catch(T){return F_.error("[SessionManager] Error calculating context breakdown:",T),this.getEmptyContextBreakdown()}}getEmptyContextBreakdown(){let _=N1.SYSTEM_PROMPT+N1.TOOLS_TOTAL+N1.AUTOCOMPACT_BUFFER;return{total:_,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:N1.SYSTEM_PROMPT,tools:N1.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:N1.AUTOCOMPACT_BUFFER,contextLimit:N1.CONTEXT_LIMIT_STANDARD,remaining:N1.CONTEXT_LIMIT_STANDARD-_,percentage:Math.round(_/N1.CONTEXT_LIMIT_STANDARD*100),lastUpdated:Date.now()}}}var bT=new qW;var X_=v(),yh="worktrees";class _9{watches=new Map;registeredProjects=[];mqttClient;claudeProjectsDir;cccDir;constructor(_){this.mqttClient=_,this.claudeProjectsDir=gT(PW(),".claude","projects"),this.cccDir=gT(PW(),".ccc")}getWorktreePathsForProject(_){let T=Sh(_),A=gT(this.cccDir,`${T}-${yh}`);if(!wh(A))return[];try{let E=xh(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 IW(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 IW(T)}catch{return X_.debug(`[SessionWatcher] Sessions directory not found: ${T}`),null}return jh(T,{recursive:!0},async(L,J)=>{if(!J||!J.endsWith(".jsonl"))return;X_.debug(`[SessionWatcher] File ${L} detected in project ${_}: ${J}`),await this.handleSessionChange(_,T,A)})}async handleSessionChange(_,T,A=!0){try{let E=this.watches.get(_);if(!E){X_.warn(`[SessionWatcher] No watch found for project ${_}`);return}let L=await bT.getLatestSession(E.directoryPath);if(L)X_.debug(`[SessionWatcher] Session change for project ${_}: ${L.sessionId}`),this.publishSessionUpdate(_,L,A);else X_.debug(`[SessionWatcher] No sessions found for project ${_}`),this.publishSessionUpdate(_,null,A)}catch(E){X_.error(`[SessionWatcher] Error handling session change for project ${_}:`,E)}}publishSessionUpdate(_,T,A=!0){if(!this.mqttClient){X_.warn("[SessionWatcher] MQTT client not available");return}let E=`sessions/update/${_}`,L=JSON.stringify(T?{...T,pathExists:A}:{pathExists:A});this.mqttClient.publish(E,L).catch((J)=>{X_.error(`[SessionWatcher] Failed to publish to ${E}`,{error:J.message})}),X_.debug(`[SessionWatcher] Published update to ${E}: ${T?.sessionId||"null"}, pathExists: ${A}`)}stopProject(_){let T=this.watches.get(_);if(T){if(T.mainWatcher)T.mainWatcher.close();for(let E of T.worktreeWatchers)E.watcher.close();this.watches.delete(_);let A=(T.mainWatcher?1:0)+T.worktreeWatchers.length;X_.info(`[SessionWatcher] Stopped watching project ${_} (${A} watchers closed)`)}}stopAll(){X_.info(`[SessionWatcher] Stopping all watches (${this.watches.size} projects)`);for(let[_]of this.watches)this.stopProject(_)}async resumeAll(){if(this.registeredProjects.length===0){X_.debug("[SessionWatcher] No registered projects to resume");return}X_.info(`[SessionWatcher] Resuming watches for ${this.registeredProjects.length} projects`);for(let _ of this.registeredProjects)await this.watchProject(_.id,_.directory_path);X_.info(`[SessionWatcher] Resumed ${this.watches.size} watches`)}async notifySessionCreated(_,T){let A=null;for(let E of this.registeredProjects)if(E.directory_path===_){A=E.id;break}if(!A){X_.warn(`[SessionWatcher] notifySessionCreated - project not registered: ${_}`);return}X_.info(`[SessionWatcher] Session created notification for project ${A}`,{projectPath:_,workingDirectory:T}),await new Promise((E)=>setTimeout(E,500)),await this.fetchAndPublishLatestSession(A,_),await this.ensureWatcherForPath(A,T)}async ensureWatcherForPath(_,T){let A=this.watches.get(_);if(!A){X_.warn(`[SessionWatcher] Cannot ensure watcher - project not in watches: ${_}`);return}let E=gT(this.claudeProjectsDir,this.sanitizeProjectPath(T));if(T===A.directoryPath){if(A.mainWatcher){X_.debug(`[SessionWatcher] Main watcher already exists for project ${_}`);return}let J=await this.setupDirectoryWatcher(_,E,A.pathExists);if(J)A.mainWatcher=J,X_.info(`[SessionWatcher] Added main watcher for project ${_}: ${E}`)}else{if(A.worktreeWatchers.find((H)=>H.path===E)){X_.debug(`[SessionWatcher] Worktree watcher already exists: ${E}`);return}let X=await this.setupDirectoryWatcher(_,E,A.pathExists);if(X)A.worktreeWatchers.push({path:E,watcher:X}),X_.info(`[SessionWatcher] Added worktree watcher for project ${_}: ${E}`)}}}var G_=v();class F5{name="Sessions Service";running=!1;startedAt;mqttClient=null;watcher;claudeAgentService=null;constructor(){}setMQTTClient(_){this.mqttClient=_,this.watcher=new _9(_)}setClaudeAgentService(_){this.claudeAgentService=_}async notifySessionCreated(_,T){if(this.watcher)await this.watcher.notifySessionCreated(_,T);this.broadcastActiveSessionCounts()}notifySessionStopped(){this.broadcastActiveSessionCounts()}broadcastActiveSessionCounts(){if(!this.mqttClient||!this.claudeAgentService)return;let _=this.claudeAgentService.getActiveSessions(),T={activeSessions:_,timestamp:Date.now()};this.mqttClient.publish("sessions/active/broadcast",JSON.stringify(T)),G_.debug(`[Sessions] Broadcast ${_.length} active sessions to all clients`)}async start(){try{if(this.running=!0,this.startedAt=new Date,G_.info("[Sessions] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw G_.error("[Sessions] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.watcher)this.watcher.stopAll();G_.info("[Sessions] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("projects/register",(_,T)=>{this.handleProjectRegistration(_,T)}),this.mqttClient.subscribe("app/lifecycle",(_,T)=>{this.handleAppLifecycle(_,T)}),this.mqttClient.subscribe("sessions/list/request",(_,T)=>{this.handleSessionListRequest(_,T)}),this.mqttClient.subscribe("sessions/messages/request",(_,T)=>{this.handleSessionMessagesRequest(_,T)}),this.mqttClient.subscribe("sessions/latest/request",(_,T)=>{this.handleLatestSessionsRequest(_,T)}),this.mqttClient.subscribe("sessions/active/request",(_,T)=>{this.handleActiveSessionsRequest(_,T)}),G_.info("[Sessions] MQTT handlers registered for projects/register, app/lifecycle, sessions/list, sessions/messages, sessions/latest, sessions/active")}async handleProjectRegistration(_,T){try{let A=JSON.parse(T.toString()),E=A.projects;if(!Array.isArray(E)){G_.warn("[Sessions] Invalid projects payload:",A);return}if(G_.info(`[Sessions] Received registration for ${E.length} projects`),this.watcher)await this.watcher.registerProjects(E)}catch(A){G_.error("[Sessions] Error handling project registration:",A)}}async handleAppLifecycle(_,T){try{let E=JSON.parse(T.toString()).state;if(G_.info(`[Sessions] App lifecycle changed to: ${E}`),E==="background"||E==="terminated"){if(this.watcher)this.watcher.stopAll(),G_.info(`[Sessions] Stopped all watchers (app state: ${E})`)}else if(E==="active"){if(this.watcher)await this.watcher.resumeAll(),G_.info(`[Sessions] Resumed all watchers (app state: ${E})`)}}catch(A){G_.error("[Sessions] Error handling app lifecycle:",A)}}async handleSessionListRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPath:E,clientId:L,timestamp:J}=A;if(!E||!L){G_.warn("[Sessions] Invalid session list request:",A);return}G_.info(`[Sessions] Session list request from ${L} for ${E}`);let X=await bT.listSessions(E),H=this.claudeAgentService?.getActiveSessions()||[],Z=new Map(H.filter(($)=>$.projectPath===E).map(($)=>[$.sessionId,{status:$.status,worktreePath:$.worktreePath,worktreeBranch:$.worktreeBranch}])),K={sessions:X.sessions.map(($)=>{let U=Z.get($.sessionId);return{...$,status:U?.status,worktreePath:U?.worktreePath||$.worktreePath,worktreeBranch:U?.worktreeBranch||$.worktreeBranch}}),projectPath:X.projectPath,pathExists:X.pathExists,timestamp:Date.now()},G=`sessions/list/${L}/response`;await this.mqttClient?.publish(G,JSON.stringify(K)),G_.info(`[Sessions] Sent ${X.sessions.length} sessions to ${L}`)}catch(A){G_.error("[Sessions] Error handling session list request:",A)}}async handleSessionMessagesRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPath:E,sessionId:L,lastKnownUuid:J,limit:X=50,clientId:H,timestamp:Z}=A;if(!E||!L||!H){G_.warn("[Sessions] Invalid session messages request:",A);return}G_.info(`[Sessions] Messages request from ${H} for session ${L}${J?` (from ${J})`:""}`);let Y=await bT.getSessionMessages(E,L,J,X),K={...Y,timestamp:Date.now()},G=`sessions/messages/${H}/response`;await this.mqttClient?.publish(G,JSON.stringify(K)),G_.info(`[Sessions] Sent ${Y.messages.length} messages to ${H} (hasMore: ${Y.hasMore})`)}catch(A){G_.error("[Sessions] Error handling session messages request:",A)}}async handleLatestSessionsRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPaths:E,clientId:L,timestamp:J}=A;if(!Array.isArray(E)||!L){G_.warn("[Sessions] Invalid latest sessions request:",A);return}G_.info(`[Sessions] Latest sessions request from ${L} for ${E.length} projects`);let X=await bT.getLatestSessions(E),H={projects:X,timestamp:Date.now()},Z=`sessions/latest/${L}/response`;await this.mqttClient?.publish(Z,JSON.stringify(H)),G_.info(`[Sessions] Sent latest sessions for ${X.length} projects to ${L}`)}catch(A){G_.error("[Sessions] Error handling latest sessions request:",A)}}async handleActiveSessionsRequest(_,T){try{let A=JSON.parse(T.toString()),{clientId:E,timestamp:L}=A;if(!E){G_.warn("[Sessions] Invalid active sessions request:",A);return}G_.info(`[Sessions] Active sessions request from ${E}`);let J=this.claudeAgentService?.getActiveSessions()||[],X={activeSessions:J,timestamp:Date.now()},H=`sessions/active/${E}/response`;await this.mqttClient?.publish(H,JSON.stringify(X)),G_.info(`[Sessions] Sent ${J.length} active sessions to ${E}`)}catch(A){G_.error("[Sessions] Error handling active sessions request:",A)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt}}}import jW from"os";var T1=v(),vh="1.0.0";class C5{name="System Info Service";running=!1;startedAt;mqttClient=null;requestsHandled=0;messageHandler;versionCheckHandler;constructor(){}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,T1.info("[SystemInfo] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw T1.error("[SystemInfo] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){if(this.messageHandler)this.mqttClient.unsubscribe("system/os-info/request",this.messageHandler),T1.debug("[SystemInfo] Unsubscribed from system/os-info/request"),this.messageHandler=void 0;if(this.versionCheckHandler)this.mqttClient.unsubscribe("version/check/request",this.versionCheckHandler),T1.debug("[SystemInfo] Unsubscribed from version/check/request"),this.versionCheckHandler=void 0}T1.info("[SystemInfo] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(_,T)=>{this.handleSystemInfoRequest(_,T)},this.mqttClient.subscribe("system/os-info/request",this.messageHandler),T1.info("[SystemInfo] MQTT handler registered for system/os-info/request"),this.versionCheckHandler=(_,T)=>{this.handleVersionCheckRequest(_,T)},this.mqttClient.subscribe("version/check/request",this.versionCheckHandler),T1.info("[SystemInfo] MQTT handler registered for version/check/request")}async handleSystemInfoRequest(_,T){try{let A=JSON.parse(T.toString());T1.debug("[SystemInfo] Received system info request",{clientId:A.clientId});let E=jW.platform(),L=jW.homedir(),J;if(E==="win32")J=`${L}\\projects\\my-project`;else if(E==="darwin")J=`${L}/projects/my-project`;else J=`${L}/projects/my-project`;let X=`system/os-info/${A.clientId}/response`,H={platform:E,homedir:L,suggestedPath:J,timestamp:Date.now()};if(this.mqttClient)await this.mqttClient.publish(X,JSON.stringify(H),{qos:1}),this.requestsHandled++,T1.debug("[SystemInfo] Sent system info response",{clientId:A.clientId,platform:E,responseTopic:X});else T1.error("[SystemInfo] MQTT client not available for publishing")}catch(A){T1.error("[SystemInfo] Error handling system info request",{error:A instanceof Error?A.message:"Unknown error"})}}async handleVersionCheckRequest(_,T){try{let A=JSON.parse(T.toString());T1.debug("[SystemInfo] Received version check request",{clientId:A.clientId,appVersion:A.appVersion,platform:A.platform});let E=m0(),L=fT(E),J={backendVersion:E,latestBackendVersion:E,backendUpdateAvailable:!1,backendChannel:L==="beta"?"beta":"latest",minAppVersion:vh,currentAppVersion:A.appVersion,updateRequired:!1,updateAvailable:!1,timestamp:Date.now()},X=`version/check/${A.clientId}/response`;if(this.mqttClient)await this.mqttClient.publish(X,JSON.stringify(J),{qos:1}),this.requestsHandled++,T1.debug("[SystemInfo] Sent version check response",{clientId:A.clientId,backendVersion:E,responseTopic:X});else T1.error("[SystemInfo] MQTT client not available for publishing version response")}catch(A){T1.error("[SystemInfo] Error handling version check request",{error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}}var F0=v();class O5{name="Terminal Config Service";running=!1;startedAt;mqttClient=null;terminalServer;requestsHandled=0;messageHandler;constructor(_){this.terminalServer=_}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,F0.info("[TerminalConfig] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw F0.error("[TerminalConfig] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient&&this.messageHandler)this.mqttClient.unsubscribe("system/terminal-config/request",this.messageHandler),F0.debug("[TerminalConfig] Unsubscribed from system/terminal-config/request"),this.messageHandler=void 0;F0.info("[TerminalConfig] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(_,T)=>{this.handleTerminalConfigRequest(_,T)},this.mqttClient.subscribe("system/terminal-config/request",this.messageHandler),F0.info("[TerminalConfig] MQTT handler registered for system/terminal-config/request")}async handleTerminalConfigRequest(_,T){try{let A=JSON.parse(T.toString());F0.debug("[TerminalConfig] Received terminal config request",{clientId:A.clientId,projectPath:A.projectPath});let E=this.terminalServer.getStatus(),L;if(A.projectPath){let H=this.terminalServer.findSessionByProjectPath(A.projectPath);if(H)L=H,F0.debug("[TerminalConfig] Found existing session for project",{projectPath:A.projectPath,sessionId:H})}let J={enabled:E.running,path:"/terminal",port:E.port,username:E.credentials?.username||"",password:E.credentials?.password||"",timestamp:Date.now(),existingSessionId:L},X=`system/terminal-config/${A.clientId}/response`;if(this.mqttClient)await this.mqttClient.publish(X,JSON.stringify(J),{qos:1}),this.requestsHandled++,F0.debug("[TerminalConfig] Sent terminal config response",{clientId:A.clientId,enabled:J.enabled,port:J.port,responseTopic:X});else F0.error("[TerminalConfig] MQTT client not available for publishing")}catch(A){F0.error("[TerminalConfig] Error handling terminal config request",{error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}}import LN from"path";var o1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};var e=v();class T9{sessions=new Map;tempSessions=new Map;config;callbacks;resolvedClaudePath=null;constructor(_,T={}){this.config=_,this.callbacks=T}async resolveClaudePath(){if(this.resolvedClaudePath)return this.resolvedClaudePath;if(process.platform==="win32"&&process.env.APPDATA){let _=`${process.env.APPDATA}\\npm\\claude.cmd`;try{if(await Bun.file(_).exists())return this.resolvedClaudePath=_,e.info(`[ClaudeProcessManager] Using claude at ${_}`),_}catch(T){e.debug(`[ClaudeProcessManager] claude.cmd not found at ${_}`)}}try{if(await Bun.spawn(["claude","--version"],{stdout:"pipe",stderr:"pipe"}).exited===0)return this.resolvedClaudePath="claude",e.info("[ClaudeProcessManager] Found claude in PATH"),"claude"}catch(_){e.debug("[ClaudeProcessManager] claude not found in PATH")}return e.warn("[ClaudeProcessManager] Claude CLI not found. Please install: npm install -g @anthropic-ai/claude-code"),this.resolvedClaudePath="claude","claude"}async spawnSession(_,T,A,E,L,J,X,H,Z){if(e.info(`[ClaudeProcessManager] Spawning session for project ${A} in ${E}`,{resumeSessionId:J||"new session",permissionMode:X||"default",selectedModel:H||"sonnet"}),this.sessions.size+this.tempSessions.size>=this.config.maxConcurrentSessions)throw Error("Maximum concurrent sessions reached");let Y=this.config.claudeCodePath||await this.resolveClaudePath(),$=["-p","--output-format","stream-json","--input-format","stream-json","--permission-prompt-tool","stdio","--permission-mode",X||"default","--model",H||"sonnet","--verbose"];if(J)$.push("--resume",J),e.info(`[ClaudeProcessManager] Resuming session: ${J}`);e.info(`[ClaudeProcessManager] Spawning: ${Y} ${$.join(" ")}`,{cwd:E,claudePath:Y});try{if((await Bun.$`test -d ${E}`.quiet().nothrow()).exitCode!==0){if(e.info(`[ClaudeProcessManager] Directory does not exist, creating: ${E}`),(await Bun.$`mkdir -p ${E}`.quiet().nothrow()).exitCode!==0)throw Error(`Failed to create directory: ${E}`);e.info(`[ClaudeProcessManager] Directory created successfully: ${E}`)}}catch(N){throw e.error(`[ClaudeProcessManager] Failed to ensure directory exists: ${E}`,{error:N}),Error(`Cannot start session: failed to create directory ${E}`)}let U=Bun.spawn([Y,...$],{cwd:E,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:{...process.env,CI:"1",CLAUDE_HEADLESS:"1"}}),V={tempId:_,userId:T,projectId:A,directoryPath:E,process:U,status:"initializing",permissionMode:X||"default",createdAt:new Date,lastActivity:new Date,messageCount:0};return this.tempSessions.set(_,V),this.setupProcessHandlers(V,U),setTimeout(()=>{this.sendUserMessage(V,L,Z)},100),V}setupProcessHandlers(_,T){let{tempId:A}=_;this.readStdoutLines(T.stdout,_),this.readStderrLines(T.stderr,_),T.exited.then((E)=>{e.info("[ClaudeProcessManager] Claude process exited",{tempId:A,sessionId:_.sessionId,exitCode:E});let L=`exited with code ${E}`;this.handleSessionStopped(_,L)}).catch((E)=>{e.error("[ClaudeProcessManager] Claude process error:",{tempId:A,sessionId:_.sessionId,error:E.message}),this.handleSessionError(_,E.message)})}readStdoutLines(_,T){(async()=>{try{let A=_.pipeThrough(new TextDecoderStream).getReader(),E="";while(!0){let{done:L,value:J}=await A.read();if(L)break;E+=J;let X=E.split(`
|
|
2618
|
+
`),L=null,J=null;for(let H of E){if(!H.trim())continue;try{let Z=JSON.parse(H);if(Z.type==="summary"&&Z.summary)L=Z.summary;if(Z.isMeta)continue;if(!Z.message)continue;let Y=Z.type==="user"||Z.message?.role==="user",K=Array.isArray(Z.message?.content)&&Z.message.content.some(($)=>$.type==="tool_result");if(!J&&Y&&!K){let $=Z.message?.content,G=null;if(typeof $==="string")G=$;else if(Array.isArray($)){let V=$.find((N)=>N.type==="text");if(V?.text)G=V.text}let U=G?.trim();if(U&&U!=="Warmup"&&!U.startsWith("<command-name>")&&!U.startsWith("<local-command-stdout>"))J=U}}catch{}}return(L||J||"Untitled Session").substring(0,100)}catch(T){return F_.warn("[SessionManager] Error extracting title:",T),"Untitled Session"}}async getFileModTime(_){try{return(await import("fs")).statSync(_).mtime}catch{return null}}async extractSessionMetadata(_,T){try{let A=await this.extractTitle(_),E=await this.getFileModTime(_),L=E?E.toISOString():new Date().toISOString(),J=await this.countLines(_);return{sessionId:T,title:A,lastActivity:L,messageCount:J}}catch(A){return F_.warn(`[SessionManager] Error extracting metadata for session ${T}`,A),null}}async listSessionsFromDir(_,T){if(!(await import("fs")).existsSync(_))return[];try{let J=(await this.readDir(_)).filter((H)=>{if(!H.endsWith(".jsonl"))return!1;let Z=o_.basename(H,".jsonl");return xh.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 PW.parseSessionFile(L,A,E),Z=await this.extractTitle(L),Y=await this.calculateContextBreakdown(L),K={totalInputTokens:Y.inputTokens,totalOutputTokens:Y.outputTokens,totalCacheCreationTokens:Y.cacheCreation,totalCacheReadTokens:Y.cacheRead,totalTokens:Y.total};return{...H,sessionId:T,projectPath:_,title:Z,context:Y,totalUsage:K,timestamp:Date.now(),worktreePath:J,worktreeBranch:X}}catch(H){throw F_.error(`[SessionManager] Error getting session messages for ${T}`,H),H}}async calculateContextBreakdown(_){try{let E=(await Bun.file(_).text()).trim().split(`
|
|
2619
|
+
`),L=null,J=0,X=0;for(let R of E){if(!R.trim())continue;try{let q=JSON.parse(R);X++;let f=null;if(q.type==="assistant"){if(q.message?.usage)f=q.message.usage;else if(q.usage)f=q.usage}if(q.type==="result"&&q.usage)f=q.usage;if(f&&(f.input_tokens!==void 0||f.output_tokens!==void 0))L=f,J++}catch{continue}}if(F_.debug("[SessionManager] Context calculation stats:",{sessionFile:o_.basename(_),totalMessages:X,messagesWithUsage:J,hasUsage:!!L,mostRecentUsage:L?{input:L.input_tokens,output:L.output_tokens,cacheCreate:L.cache_creation_input_tokens,cacheRead:L.cache_read_input_tokens}:null}),!L)return F_.warn("[SessionManager] No usage data found in session file:",_),this.getEmptyContextBreakdown();let H=L.input_tokens||0,Z=L.output_tokens||0,Y=L.cache_creation_input_tokens||0,K=L.cache_read_input_tokens||0,$=H+Y+K,G=Q1.SYSTEM_PROMPT,U=Q1.TOOLS_TOTAL,V=0,N=Q1.AUTOCOMPACT_BUFFER,z=Math.max(0,$-G-U-V),Q=$+N,F=Q1.CONTEXT_LIMIT_STANDARD;return F_.info("[SessionManager] Context breakdown calculated:",{total:Q,apiTokens:$,inputTokens:H,cacheCreation:Y,cacheRead:K,percentage:Math.round(Q/F*100),breakdown:{systemPrompt:G,tools:U,mcpServers:V,messages:z,autocompactBuffer:N,remaining:Math.max(0,F-Q)}}),{total:Q,inputTokens:H,outputTokens:Z,cacheCreation:Y,cacheRead:K,systemPrompt:G,tools:U,mcpServers:V,messages:z,autocompactBuffer:N,contextLimit:F,remaining:Math.max(0,F-Q),percentage:Math.round(Q/F*100),lastUpdated:Date.now()}}catch(T){return F_.error("[SessionManager] Error calculating context breakdown:",T),this.getEmptyContextBreakdown()}}getEmptyContextBreakdown(){let _=Q1.SYSTEM_PROMPT+Q1.TOOLS_TOTAL+Q1.AUTOCOMPACT_BUFFER;return{total:_,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:Q1.SYSTEM_PROMPT,tools:Q1.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:Q1.AUTOCOMPACT_BUFFER,contextLimit:Q1.CONTEXT_LIMIT_STANDARD,remaining:Q1.CONTEXT_LIMIT_STANDARD-_,percentage:Math.round(_/Q1.CONTEXT_LIMIT_STANDARD*100),lastUpdated:Date.now()}}}var bT=new jW;var X_=v(),kh="worktrees";class A9{watches=new Map;registeredProjects=[];mqttClient;claudeProjectsDir;cccDir;constructor(_){this.mqttClient=_,this.claudeProjectsDir=gT(wW(),".claude","projects"),this.cccDir=gT(wW(),".ccc")}getWorktreePathsForProject(_){let T=hh(_),A=gT(this.cccDir,`${T}-${kh}`);if(!vh(A))return[];try{let E=yh(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 xW(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 xW(T)}catch{return X_.debug(`[SessionWatcher] Sessions directory not found: ${T}`),null}return Sh(T,{recursive:!0},async(L,J)=>{if(!J||!J.endsWith(".jsonl"))return;X_.debug(`[SessionWatcher] File ${L} detected in project ${_}: ${J}`),await this.handleSessionChange(_,T,A)})}async handleSessionChange(_,T,A=!0){try{let E=this.watches.get(_);if(!E){X_.warn(`[SessionWatcher] No watch found for project ${_}`);return}let L=await bT.getLatestSession(E.directoryPath);if(L)X_.debug(`[SessionWatcher] Session change for project ${_}: ${L.sessionId}`),this.publishSessionUpdate(_,L,A);else X_.debug(`[SessionWatcher] No sessions found for project ${_}`),this.publishSessionUpdate(_,null,A)}catch(E){X_.error(`[SessionWatcher] Error handling session change for project ${_}:`,E)}}publishSessionUpdate(_,T,A=!0){if(!this.mqttClient){X_.warn("[SessionWatcher] MQTT client not available");return}let E=`sessions/update/${_}`,L=JSON.stringify(T?{...T,pathExists:A}:{pathExists:A});this.mqttClient.publish(E,L).catch((J)=>{X_.error(`[SessionWatcher] Failed to publish to ${E}`,{error:J.message})}),X_.debug(`[SessionWatcher] Published update to ${E}: ${T?.sessionId||"null"}, pathExists: ${A}`)}stopProject(_){let T=this.watches.get(_);if(T){if(T.mainWatcher)T.mainWatcher.close();for(let E of T.worktreeWatchers)E.watcher.close();this.watches.delete(_);let A=(T.mainWatcher?1:0)+T.worktreeWatchers.length;X_.info(`[SessionWatcher] Stopped watching project ${_} (${A} watchers closed)`)}}stopAll(){X_.info(`[SessionWatcher] Stopping all watches (${this.watches.size} projects)`);for(let[_]of this.watches)this.stopProject(_)}async resumeAll(){if(this.registeredProjects.length===0){X_.debug("[SessionWatcher] No registered projects to resume");return}X_.info(`[SessionWatcher] Resuming watches for ${this.registeredProjects.length} projects`);for(let _ of this.registeredProjects)await this.watchProject(_.id,_.directory_path);X_.info(`[SessionWatcher] Resumed ${this.watches.size} watches`)}async notifySessionCreated(_,T){let A=null;for(let E of this.registeredProjects)if(E.directory_path===_){A=E.id;break}if(!A){X_.warn(`[SessionWatcher] notifySessionCreated - project not registered: ${_}`);return}X_.info(`[SessionWatcher] Session created notification for project ${A}`,{projectPath:_,workingDirectory:T}),await new Promise((E)=>setTimeout(E,500)),await this.fetchAndPublishLatestSession(A,_),await this.ensureWatcherForPath(A,T)}async ensureWatcherForPath(_,T){let A=this.watches.get(_);if(!A){X_.warn(`[SessionWatcher] Cannot ensure watcher - project not in watches: ${_}`);return}let E=gT(this.claudeProjectsDir,this.sanitizeProjectPath(T));if(T===A.directoryPath){if(A.mainWatcher){X_.debug(`[SessionWatcher] Main watcher already exists for project ${_}`);return}let J=await this.setupDirectoryWatcher(_,E,A.pathExists);if(J)A.mainWatcher=J,X_.info(`[SessionWatcher] Added main watcher for project ${_}: ${E}`)}else{if(A.worktreeWatchers.find((H)=>H.path===E)){X_.debug(`[SessionWatcher] Worktree watcher already exists: ${E}`);return}let X=await this.setupDirectoryWatcher(_,E,A.pathExists);if(X)A.worktreeWatchers.push({path:E,watcher:X}),X_.info(`[SessionWatcher] Added worktree watcher for project ${_}: ${E}`)}}}var $_=v();class F5{name="Sessions Service";running=!1;startedAt;mqttClient=null;watcher;claudeAgentService=null;constructor(){}setMQTTClient(_){this.mqttClient=_,this.watcher=new A9(_)}setClaudeAgentService(_){this.claudeAgentService=_}async notifySessionCreated(_,T){if(this.watcher)await this.watcher.notifySessionCreated(_,T);this.broadcastActiveSessionCounts()}notifySessionStopped(){this.broadcastActiveSessionCounts()}broadcastActiveSessionCounts(){if(!this.mqttClient||!this.claudeAgentService)return;let _=this.claudeAgentService.getActiveSessions(),T={activeSessions:_,timestamp:Date.now()};this.mqttClient.publish("sessions/active/broadcast",JSON.stringify(T)),$_.debug(`[Sessions] Broadcast ${_.length} active sessions to all clients`)}async start(){try{if(this.running=!0,this.startedAt=new Date,$_.info("[Sessions] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw $_.error("[Sessions] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.watcher)this.watcher.stopAll();$_.info("[Sessions] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("projects/register",(_,T)=>{this.handleProjectRegistration(_,T)}),this.mqttClient.subscribe("app/lifecycle",(_,T)=>{this.handleAppLifecycle(_,T)}),this.mqttClient.subscribe("sessions/list/request",(_,T)=>{this.handleSessionListRequest(_,T)}),this.mqttClient.subscribe("sessions/messages/request",(_,T)=>{this.handleSessionMessagesRequest(_,T)}),this.mqttClient.subscribe("sessions/latest/request",(_,T)=>{this.handleLatestSessionsRequest(_,T)}),this.mqttClient.subscribe("sessions/active/request",(_,T)=>{this.handleActiveSessionsRequest(_,T)}),$_.info("[Sessions] MQTT handlers registered for projects/register, app/lifecycle, sessions/list, sessions/messages, sessions/latest, sessions/active")}async handleProjectRegistration(_,T){try{let A=JSON.parse(T.toString()),E=A.projects;if(!Array.isArray(E)){$_.warn("[Sessions] Invalid projects payload:",A);return}if($_.info(`[Sessions] Received registration for ${E.length} projects`),this.watcher)await this.watcher.registerProjects(E)}catch(A){$_.error("[Sessions] Error handling project registration:",A)}}async handleAppLifecycle(_,T){try{let E=JSON.parse(T.toString()).state;if($_.info(`[Sessions] App lifecycle changed to: ${E}`),E==="background"||E==="terminated"){if(this.watcher)this.watcher.stopAll(),$_.info(`[Sessions] Stopped all watchers (app state: ${E})`)}else if(E==="active"){if(this.watcher)await this.watcher.resumeAll(),$_.info(`[Sessions] Resumed all watchers (app state: ${E})`)}}catch(A){$_.error("[Sessions] Error handling app lifecycle:",A)}}async handleSessionListRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPath:E,clientId:L,timestamp:J}=A;if(!E||!L){$_.warn("[Sessions] Invalid session list request:",A);return}$_.info(`[Sessions] Session list request from ${L} for ${E}`);let X=await bT.listSessions(E),H=this.claudeAgentService?.getActiveSessions()||[],Z=new Map(H.filter((G)=>G.projectPath===E).map((G)=>[G.sessionId,{status:G.status,worktreePath:G.worktreePath,worktreeBranch:G.worktreeBranch}])),K={sessions:X.sessions.map((G)=>{let U=Z.get(G.sessionId);return{...G,status:U?.status,worktreePath:U?.worktreePath||G.worktreePath,worktreeBranch:U?.worktreeBranch||G.worktreeBranch}}),projectPath:X.projectPath,pathExists:X.pathExists,timestamp:Date.now()},$=`sessions/list/${L}/response`;await this.mqttClient?.publish($,JSON.stringify(K)),$_.info(`[Sessions] Sent ${X.sessions.length} sessions to ${L}`)}catch(A){$_.error("[Sessions] Error handling session list request:",A)}}async handleSessionMessagesRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPath:E,sessionId:L,lastKnownUuid:J,limit:X=50,clientId:H,timestamp:Z}=A;if(!E||!L||!H){$_.warn("[Sessions] Invalid session messages request:",A);return}$_.info(`[Sessions] Messages request from ${H} for session ${L}${J?` (from ${J})`:""}`);let Y=await bT.getSessionMessages(E,L,J,X),K={...Y,timestamp:Date.now()},$=`sessions/messages/${H}/response`;await this.mqttClient?.publish($,JSON.stringify(K)),$_.info(`[Sessions] Sent ${Y.messages.length} messages to ${H} (hasMore: ${Y.hasMore})`)}catch(A){$_.error("[Sessions] Error handling session messages request:",A)}}async handleLatestSessionsRequest(_,T){try{let A=JSON.parse(T.toString()),{projectPaths:E,clientId:L,timestamp:J}=A;if(!Array.isArray(E)||!L){$_.warn("[Sessions] Invalid latest sessions request:",A);return}$_.info(`[Sessions] Latest sessions request from ${L} for ${E.length} projects`);let X=await bT.getLatestSessions(E),H={projects:X,timestamp:Date.now()},Z=`sessions/latest/${L}/response`;await this.mqttClient?.publish(Z,JSON.stringify(H)),$_.info(`[Sessions] Sent latest sessions for ${X.length} projects to ${L}`)}catch(A){$_.error("[Sessions] Error handling latest sessions request:",A)}}async handleActiveSessionsRequest(_,T){try{let A=JSON.parse(T.toString()),{clientId:E,timestamp:L}=A;if(!E){$_.warn("[Sessions] Invalid active sessions request:",A);return}$_.info(`[Sessions] Active sessions request from ${E}`);let J=this.claudeAgentService?.getActiveSessions()||[],X={activeSessions:J,timestamp:Date.now()},H=`sessions/active/${E}/response`;await this.mqttClient?.publish(H,JSON.stringify(X)),$_.info(`[Sessions] Sent ${J.length} active sessions to ${E}`)}catch(A){$_.error("[Sessions] Error handling active sessions request:",A)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt}}}import SW from"os";var T1=v(),fh="1.0.0";class C5{name="System Info Service";running=!1;startedAt;mqttClient=null;requestsHandled=0;messageHandler;versionCheckHandler;constructor(){}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,T1.info("[SystemInfo] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw T1.error("[SystemInfo] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){if(this.messageHandler)this.mqttClient.unsubscribe("system/os-info/request",this.messageHandler),T1.debug("[SystemInfo] Unsubscribed from system/os-info/request"),this.messageHandler=void 0;if(this.versionCheckHandler)this.mqttClient.unsubscribe("version/check/request",this.versionCheckHandler),T1.debug("[SystemInfo] Unsubscribed from version/check/request"),this.versionCheckHandler=void 0}T1.info("[SystemInfo] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(_,T)=>{this.handleSystemInfoRequest(_,T)},this.mqttClient.subscribe("system/os-info/request",this.messageHandler),T1.info("[SystemInfo] MQTT handler registered for system/os-info/request"),this.versionCheckHandler=(_,T)=>{this.handleVersionCheckRequest(_,T)},this.mqttClient.subscribe("version/check/request",this.versionCheckHandler),T1.info("[SystemInfo] MQTT handler registered for version/check/request")}async handleSystemInfoRequest(_,T){try{let A=JSON.parse(T.toString());T1.debug("[SystemInfo] Received system info request",{clientId:A.clientId});let E=SW.platform(),L=SW.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:fh,currentAppVersion:A.appVersion,updateRequired:!1,updateAvailable:!1,timestamp:Date.now()},X=`version/check/${A.clientId}/response`;if(this.mqttClient)await this.mqttClient.publish(X,JSON.stringify(J),{qos:1}),this.requestsHandled++,T1.debug("[SystemInfo] Sent version check response",{clientId:A.clientId,backendVersion:E,responseTopic:X});else T1.error("[SystemInfo] MQTT client not available for publishing version response")}catch(A){T1.error("[SystemInfo] Error handling version check request",{error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}}var C0=v();class O5{name="Terminal Config Service";running=!1;startedAt;mqttClient=null;terminalServer;requestsHandled=0;messageHandler;constructor(_){this.terminalServer=_}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,C0.info("[TerminalConfig] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw C0.error("[TerminalConfig] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient&&this.messageHandler)this.mqttClient.unsubscribe("system/terminal-config/request",this.messageHandler),C0.debug("[TerminalConfig] Unsubscribed from system/terminal-config/request"),this.messageHandler=void 0;C0.info("[TerminalConfig] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.messageHandler=(_,T)=>{this.handleTerminalConfigRequest(_,T)},this.mqttClient.subscribe("system/terminal-config/request",this.messageHandler),C0.info("[TerminalConfig] MQTT handler registered for system/terminal-config/request")}async handleTerminalConfigRequest(_,T){try{let A=JSON.parse(T.toString());C0.debug("[TerminalConfig] Received terminal config request",{clientId:A.clientId,projectPath:A.projectPath});let E=this.terminalServer.getStatus(),L;if(A.projectPath){let H=this.terminalServer.findSessionByProjectPath(A.projectPath);if(H)L=H,C0.debug("[TerminalConfig] Found existing session for project",{projectPath:A.projectPath,sessionId:H})}let J={enabled:E.running,path:"/terminal",port:E.port,username:E.credentials?.username||"",password:E.credentials?.password||"",timestamp:Date.now(),existingSessionId:L},X=`system/terminal-config/${A.clientId}/response`;if(this.mqttClient)await this.mqttClient.publish(X,JSON.stringify(J),{qos:1}),this.requestsHandled++,C0.debug("[TerminalConfig] Sent terminal config response",{clientId:A.clientId,enabled:J.enabled,port:J.port,responseTopic:X});else C0.error("[TerminalConfig] MQTT client not available for publishing")}catch(A){C0.error("[TerminalConfig] Error handling terminal config request",{error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}}import HN from"path";var r1={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};var e=v();class E9{sessions=new Map;tempSessions=new Map;config;callbacks;resolvedClaudePath=null;constructor(_,T={}){this.config=_,this.callbacks=T}async resolveClaudePath(){if(this.resolvedClaudePath)return this.resolvedClaudePath;if(process.platform==="win32"&&process.env.APPDATA){let _=`${process.env.APPDATA}\\npm\\claude.cmd`;try{if(await Bun.file(_).exists())return this.resolvedClaudePath=_,e.info(`[ClaudeProcessManager] Using claude at ${_}`),_}catch(T){e.debug(`[ClaudeProcessManager] claude.cmd not found at ${_}`)}}try{if(await Bun.spawn(["claude","--version"],{stdout:"pipe",stderr:"pipe"}).exited===0)return this.resolvedClaudePath="claude",e.info("[ClaudeProcessManager] Found claude in PATH"),"claude"}catch(_){e.debug("[ClaudeProcessManager] claude not found in PATH")}return e.warn("[ClaudeProcessManager] Claude CLI not found. Please install: npm install -g @anthropic-ai/claude-code"),this.resolvedClaudePath="claude","claude"}async spawnSession(_,T,A,E,L,J,X,H,Z){if(e.info(`[ClaudeProcessManager] Spawning session for project ${A} in ${E}`,{resumeSessionId:J||"new session",permissionMode:X||"default",selectedModel:H||"sonnet"}),this.sessions.size+this.tempSessions.size>=this.config.maxConcurrentSessions)throw Error("Maximum concurrent sessions reached");let Y=this.config.claudeCodePath||await this.resolveClaudePath(),G=["-p","--output-format","stream-json","--input-format","stream-json","--permission-prompt-tool","stdio","--permission-mode",X||"default","--model",H||"sonnet","--verbose"];if(J)G.push("--resume",J),e.info(`[ClaudeProcessManager] Resuming session: ${J}`);e.info(`[ClaudeProcessManager] Spawning: ${Y} ${G.join(" ")}`,{cwd:E,claudePath:Y});try{if((await Bun.$`test -d ${E}`.quiet().nothrow()).exitCode!==0){if(e.info(`[ClaudeProcessManager] Directory does not exist, creating: ${E}`),(await Bun.$`mkdir -p ${E}`.quiet().nothrow()).exitCode!==0)throw Error(`Failed to create directory: ${E}`);e.info(`[ClaudeProcessManager] Directory created successfully: ${E}`)}}catch(N){throw e.error(`[ClaudeProcessManager] Failed to ensure directory exists: ${E}`,{error:N}),Error(`Cannot start session: failed to create directory ${E}`)}let U=Bun.spawn([Y,...G],{cwd:E,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:{...process.env,CI:"1",CLAUDE_HEADLESS:"1"}}),V={tempId:_,userId:T,projectId:A,directoryPath:E,process:U,status:"initializing",permissionMode:X||"default",createdAt:new Date,lastActivity:new Date,messageCount:0};return this.tempSessions.set(_,V),this.setupProcessHandlers(V,U),setTimeout(()=>{this.sendUserMessage(V,L,Z)},100),V}setupProcessHandlers(_,T){let{tempId:A}=_;this.readStdoutLines(T.stdout,_),this.readStderrLines(T.stderr,_),T.exited.then((E)=>{e.info("[ClaudeProcessManager] Claude process exited",{tempId:A,sessionId:_.sessionId,exitCode:E});let L=`exited with code ${E}`;this.handleSessionStopped(_,L)}).catch((E)=>{e.error("[ClaudeProcessManager] Claude process error:",{tempId:A,sessionId:_.sessionId,error:E.message}),this.handleSessionError(_,E.message)})}readStdoutLines(_,T){(async()=>{try{let A=_.pipeThrough(new TextDecoderStream).getReader(),E="";while(!0){let{done:L,value:J}=await A.read();if(L)break;E+=J;let X=E.split(`
|
|
2620
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
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=
|
|
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
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_=v(),
|
|
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
|
|
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
|
|
2627
|
-
`))if(L.startsWith("worktree ")){if(E.path)A.push(E);E={path:L.substring(9),isMain:!1}}else if(L.startsWith("HEAD "))E.head=L.substring(5);else if(L.startsWith("branch ")){let J=L.substring(7);E.branch=J.replace("refs/heads/","")}else if(L==="bare")E.isMain=!0;else if(L===""){if(E.path){if(A.length===0&&!E.isMain)E.isMain=!0;A.push(E),E={}}}if(E.path){if(A.length===0)E.isMain=!0;A.push(E)}return A}catch(T){throw U_.error("[GitExecutor] Failed to list worktrees",{error:T,repoPath:_}),Error(`Failed to list worktrees: ${T instanceof Error?T.message:"Unknown error"}`)}}async function D5(_,T){try{let E=(await w8(_)).find((L)=>L.path.includes(T)||L.branch?.includes(T));if(E)return E.sessionId=T,E;return null}catch(A){return U_.error("[GitExecutor] Failed to find worktree by session ID",{error:A,repoPath:_,sessionId:T}),null}}async function
|
|
2628
|
-
`)){if(!Z.trim())continue;let Y=
|
|
2629
|
-
`);if(
|
|
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
|
|
2631
|
-
`),Z=H[0]||"",Y=H[1]||"",K=H[2]||""
|
|
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
|
|
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]||""
|
|
2624
|
+
`;A.process.stdin.write(J),e.info("[ClaudeProcessManager] Sent permission response:",{sessionId:_,request_id:T.request_id,behavior:T.behavior,hardDeny:T.hardDeny,hasMessage:!!T.message,fullResponse:J.trim()}),A.lastActivity=new Date,A.status="idle"}async respawnWithPermissionMode(_,T,A="proceed with implementation"){let E=this.sessions.get(_);if(!E)return e.warn(`[ClaudeProcessManager] Cannot respawn - session not found: ${_}`),null;let{tempId:L,userId:J,projectId:X,directoryPath:H,model:Z}=E;e.info("[ClaudeProcessManager] Respawning session with new permission mode:",{sessionId:_,newPermissionMode:T,continuationMessage:A}),E.respawning=!0;let Y=E.process;if(Y&&!Y.killed)Y.kill();this.sessions.delete(_);try{let K=await this.spawnSession(L,J,X,H,A,_,T,Z);return e.info("[ClaudeProcessManager] Session respawned successfully:",{sessionId:_,newPermissionMode:T,newTempId:K.tempId}),K}catch(K){return e.error("[ClaudeProcessManager] Failed to respawn session:",{sessionId:_,newPermissionMode:T,error:K instanceof Error?K.message:"Unknown error"}),null}}stopSession(_){let T=this.sessions.get(_)||this.tempSessions.get(_);if(!T){e.warn(`[ClaudeProcessManager] Session not found: ${_}`);return}e.info("[ClaudeProcessManager] Stopping session:",{tempId:T.tempId,sessionId:T.sessionId}),T.stopped=!0;let A=T.process;if(A&&!A.killed){try{A.stdin?.end?.()}catch{}A.kill("SIGKILL")}this.sessions.delete(T.sessionId),this.tempSessions.delete(T.tempId)}stopAll(){e.info(`[ClaudeProcessManager] Stopping all sessions (${this.sessions.size+this.tempSessions.size} total)`);for(let[_]of this.sessions)this.stopSession(_);for(let[_]of this.tempSessions)this.stopSession(_)}getSession(_){return this.sessions.get(_)||this.tempSessions.get(_)}getAllSessions(){return[...this.sessions.values(),...this.tempSessions.values()]}getSessionCount(){return this.sessions.size+this.tempSessions.size}cleanupInactiveSessions(){let _=Date.now(),T=this.config.sessionTimeoutMs;for(let A of this.getAllSessions()){let E=_-A.lastActivity.getTime();if(E>T)e.info("[ClaudeProcessManager] Cleaning up inactive session:",{sessionId:A.sessionId,tempId:A.tempId,inactiveMs:E}),this.stopSession(A.sessionId||A.tempId)}}}var{$:u}=globalThis.Bun;var U_=v(),bh=300000,hW=new Map,L9=null;function kW(_){if(!_)return!1;return Date.now()-_.timestamp<bh}function gh(_){let T=hW.get(_);if(kW(T))return T.data;return null}function yW(_,T){hW.set(_,{data:T,timestamp:Date.now()})}function mh(){if(kW(L9))return L9.data;return null}function vW(_){L9={data:_,timestamp:Date.now()}}function uh(){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 dh(){let _=uh();for(let T of _)try{if(await Bun.file(T).exists())return T}catch{}return null}async function fW(){try{if((await u`gh --version`.quiet()).exitCode===0)return await ch("gh")}catch{}let _=await dh();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 ch(_){try{let T=await u`${_} auth status`,A=T.stdout.toString(),E=T.stderr.toString();if(T.exitCode===0)return{authenticated:!0,installed:!0,inPath:!0,username:(A.match(/Logged in to .* as (\S+)/)||E.match(/Logged in to .* as (\S+)/))?.[1]};else return{authenticated:!1,installed:!0,inPath:!0,error:'GitHub CLI is installed but not authenticated. Run "gh auth login" in your terminal to authenticate.'}}catch(T){return{authenticated:!1,installed:!0,inPath:!0,error:'GitHub CLI is installed but authentication check failed. Try running "gh auth login" in your terminal.'}}}async function J9(){let _=mh();if(_)return _;try{let T=await u`gh api /user/orgs --jq '.[] | {login, id, description, avatar_url}'`.text();if(!T.trim())return vW([]),[];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 vW(A),A}catch(T){throw U_.error("[GitExecutor] Failed to fetch orgs",{error:T}),Error(`Failed to fetch organizations: ${T instanceof Error?T.message:"Unknown error"}`)}}async function R5(_,T=20){let A=`${_||"personal"}_${T}`,E=gh(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 yW(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 yW(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 bW(_,T,A=50){if(!_.trim()){await T([],"none",!0);return}let E=_.toLowerCase(),L=(J)=>{return J.filter((X)=>X.name.toLowerCase().includes(E)||X.fullName.toLowerCase().includes(E)||X.description?.toLowerCase().includes(E)).slice(0,A)};try{let[J,X]=await Promise.all([R5(void 0,100),J9()]),H=L(J);if(H.length>0)await T(H,"personal",X.length===0);if(X.length===0){if(H.length===0)await T([],"none",!0);return}let Z=await Promise.all(X.map(async(K)=>{try{let $=await R5(K.login,100);return{org:K.login,repos:L($),error:null}}catch($){return U_.warn("[GitExecutor] Failed to search org repos",{org:K.login,error:$}),{org:K.login,repos:[],error:$}}})),Y=[];for(let K of Z)Y.push(...K.repos);await T(Y,"organizations",!0)}catch(J){U_.error("[GitExecutor] Failed to search repos",{error:J,query:_}),await T([],"error",!0)}}async function gW(_,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 mW(_,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 uW(_,T,A){try{let E=await u`git -C ${_} worktree add ${T} -b ${A}`.quiet();if(E.exitCode!==0){let X=E.stderr.toString();throw Error(X||"Failed to create worktree")}let J=(await u`git -C ${T} rev-parse HEAD`.text()).trim();return{path:T,branch:A,head:J,isMain:!1,createdAt:new Date}}catch(E){throw U_.error("[GitExecutor] Failed to create worktree",{error:E,repoPath:_,worktreePath:T}),Error(`Failed to create worktree: ${E instanceof Error?E.message:"Unknown error"}`)}}async function w8(_){try{let T=await u`git -C ${_} worktree list --porcelain`.text(),A=[],E={};for(let L of T.split(`
|
|
2627
|
+
`))if(L.startsWith("worktree ")){if(E.path)A.push(E);E={path:L.substring(9),isMain:!1}}else if(L.startsWith("HEAD "))E.head=L.substring(5);else if(L.startsWith("branch ")){let J=L.substring(7);E.branch=J.replace("refs/heads/","")}else if(L==="bare")E.isMain=!0;else if(L===""){if(E.path){if(A.length===0&&!E.isMain)E.isMain=!0;A.push(E),E={}}}if(E.path){if(A.length===0)E.isMain=!0;A.push(E)}return A}catch(T){throw U_.error("[GitExecutor] Failed to list worktrees",{error:T,repoPath:_}),Error(`Failed to list worktrees: ${T instanceof Error?T.message:"Unknown error"}`)}}async function D5(_,T){try{let E=(await w8(_)).find((L)=>L.path.includes(T)||L.branch?.includes(T));if(E)return E.sessionId=T,E;return null}catch(A){return U_.error("[GitExecutor] Failed to find worktree by session ID",{error:A,repoPath:_,sessionId:T}),null}}async function X9(_){try{let A=(await u`git -C ${_} branch --show-current`.text()).trim()||"HEAD",E=0,L=0,J;try{if(J=(await u`git -C ${_} rev-parse --abbrev-ref @{upstream}`.text()).trim(),J){let K=(await u`git -C ${_} rev-list --left-right --count HEAD...@{upstream}`.text()).trim().split(/\s+/);E=parseInt(K[0]||"0",10)||0,L=parseInt(K[1]||"0",10)||0}}catch{}let X=await u`git -C ${_} status --porcelain=v2`.text(),H=[];for(let Z of X.split(`
|
|
2628
|
+
`)){if(!Z.trim())continue;let Y=ph(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 ph(_){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=lh(E,L,_.startsWith("2 "));return{path:H,status:Y,staged:E!=="."&&E!=="?",oldPath:Z||void 0}}return null}function lh(_,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 dW(_,T,A=!1){try{let E=["-C",_,"diff"];if(A)E.push("--staged");if(T)E.push("--",T);let L=await u`git ${E}`.text(),J=L.includes("Binary files")||L.includes("GIT binary patch");if(!L.trim()&&T){if((await u`git -C ${_} status --porcelain -- ${T}`.text()).trim().startsWith("??")){let Z=await import("fs"),K=(await import("path")).default.join(_,T);if(Z.existsSync(K)){let $=Z.statSync(K);if($.isDirectory())return{diff:"__DIRECTORY__",isBinary:!1};if($.isFile()){let G=Z.readFileSync(K,"utf-8"),U=G.split(`
|
|
2629
|
+
`);if(G.includes("\x00"))return{diff:`Binary file: ${T}`,isBinary:!0};return{diff:[`diff --git a/${T} b/${T}`,"new file mode 100644","--- /dev/null",`+++ b/${T}`,`@@ -0,0 +1,${U.length} @@`,...U.map((Q)=>`+${Q}`)].join(`
|
|
2630
|
+
`),isBinary:!1}}}}}return{diff:L,isBinary:J}}catch(E){throw U_.error("[GitExecutor] Failed to get diff",{error:E,path:_,file:T,staged:A}),Error(`Failed to get diff: ${E instanceof Error?E.message:"Unknown error"}`)}}async function cW(_,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 pW(_,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 lW(_,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 nW(_,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 iW(_,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 aW(_,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 oW(_,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 rW(_,T=50){try{let E=await u`git -C ${_} log -n ${T} --format=${"%H|%h|%s|%an|%aI"} --shortstat`.text();if(!E.trim())return{commits:[],totalCount:0};let L=[],J=E.trim().split(`
|
|
2633
|
+
`),X=0;while(X<J.length){let Z=J[X]?.trim();if(!Z){X++;continue}if(Z.includes("|")){let Y=Z.split("|"),K=Y[0]||"",$=Y[1]||"",G=Y[2]||"",U=Y[3]||"",V=Y[4]||"",N=0,z=0,Q=0,F=X+1;while(F<J.length&&!J[F]?.includes("|")){let R=J[F]?.trim();if(R){let q=R.match(/(\d+) files? changed/),f=R.match(/(\d+) insertions?\(\+\)/),h=R.match(/(\d+) deletions?\(-\)/);if(q?.[1])N=parseInt(q[1],10);if(f?.[1])z=parseInt(f[1],10);if(h?.[1])Q=parseInt(h[1],10);break}F++}L.push({hash:K,shortHash:$,message:G,author:U,timestamp:V,filesChanged:N,insertions:z,deletions:Q})}X++}let H=L.length;try{let Z=await u`git -C ${_} rev-list --count HEAD`.text();H=parseInt(Z.trim(),10)||L.length}catch{}return{commits:L,totalCount:H}}catch(A){throw U_.error("[GitExecutor] Failed to get commit history",{error:A,path:_}),Error(`Failed to get commit history: ${A instanceof Error?A.message:"Unknown error"}`)}}async function sW(_,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
|
-
`).trim(),K=L[Z]||""
|
|
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
2636
|
`)){if(!F.trim())continue;let R=F.split("\t");if(R.length<3)continue;let q=R[0]==="-"?0:parseInt(R[0]||"0",10),f=R[1]==="-"?0:parseInt(R[1]||"0",10),h=R.slice(2).join("\t");if(N+=q,z+=f,h.includes(" => ")){let[b,l]=h.split(" => ").map((c)=>c.trim().replace(/[{}]/g,""));V.push({path:l||"",oldPath:b||"",status:"renamed",insertions:q,deletions:f})}else V.push({path:h,status:"modified",insertions:q,deletions:f})}let Q=await u`git -C ${_} diff-tree --no-commit-id --name-status -r -M -C ${T}`.text();for(let F of Q.trim().split(`
|
|
2637
|
-
`)){if(!F.trim())continue;let R=F.split("\t");if(R.length<2)continue;let q=R[0]?.[0]||"M",f=R.length>2?R[2]:R[1],h=V.find((b)=>b.path===f||b.oldPath===R[1]);if(h)switch(q){case"A":h.status="added";break;case"D":h.status="deleted";break;case"R":h.status="renamed";break;case"C":h.status="copied";break;default:h.status="modified"}}return{hash:J,shortHash:X,message:H,body:Y,author:K,authorEmail:G,
|
|
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
|
|
2639
|
-
`).map((L)=>L.trim()).filter((L)=>L&&!L.includes("HEAD")&&!L.includes("->")).map((L)=>L.replace(/^origin\//,"")),E=await J9(_);return{branches:A,defaultBranch:E}}catch(T){return U_.error("[GitExecutor] Failed to get remote branches",{error:T,path:_}),{branches:[],defaultBranch:null}}}import*as r_ from"path";import*as D_ from"fs";import*as H9 from"os";var $_=v();function C4(_){return r_.normalize(_).toLowerCase()}var ch="worktrees",ph="sessions";function X9(){return r_.join(H9.homedir(),".ccc",ph)}function lh(){let _=new Date,T=_.getFullYear(),A=String(_.getMonth()+1).padStart(2,"0"),E=String(_.getDate()).padStart(2,"0"),L=String(_.getHours()).padStart(2,"0"),J=String(_.getMinutes()).padStart(2,"0");return`${T}${A}${E}-${L}${J}`}class O4{worktreeCache=new Map;saveSessionMapping(_,T){try{let A=X9();if(!D_.existsSync(A))D_.mkdirSync(A,{recursive:!0});let E=r_.join(A,_);D_.writeFileSync(E,T,"utf-8"),$_.debug("[WorktreeManager] Saved session mapping",{sessionId:_,worktreePath:T})}catch(A){$_.error("[WorktreeManager] Failed to save session mapping",{error:A,sessionId:_,worktreePath:T})}}loadSessionMapping(_){try{let T=r_.join(X9(),_);if(D_.existsSync(T)){let A=D_.readFileSync(T,"utf-8").trim();if(D_.existsSync(A))return A;else D_.unlinkSync(T),$_.debug("[WorktreeManager] Removed stale session mapping",{sessionId:_,worktreePath:A})}}catch(T){$_.error("[WorktreeManager] Failed to load session mapping",{error:T,sessionId:_})}return null}deleteSessionMapping(_){try{let T=r_.join(X9(),_);if(D_.existsSync(T))D_.unlinkSync(T),$_.debug("[WorktreeManager] Deleted session mapping",{sessionId:_})}catch(T){$_.error("[WorktreeManager] Failed to delete session mapping",{error:T,sessionId:_})}}getWorktreesBasePath(_){let T=r_.basename(_),A=r_.join(H9.homedir(),".ccc");return r_.join(A,`${T}-${ch}`)}getWorktreePath(_,T){let A=this.getWorktreesBasePath(_),E=T.replace(/[^a-zA-Z0-9_-]/g,"_");return r_.join(A,E)}generateBranchName(_){return`session/${_.replace(/[^a-zA-Z0-9_-]/g,"_")}`}async getOrCreateForSession(_,T){$_.debug("[WorktreeManager] getOrCreateForSession",{sessionId:_,repoPath:T});let A=this.worktreeCache.get(_);if(A)if(D_.existsSync(A.path))return $_.debug("[WorktreeManager] Returning cached worktree",{sessionId:_,path:A.path}),{worktree:A,isNew:!1};else this.worktreeCache.delete(_);let E=this.loadSessionMapping(_);if(E&&D_.existsSync(E)){let V=await C0(T);if(V){let N=await w8(V),z=C4(E),Q=N.find((F)=>C4(F.path)===z);if(Q)return Q.sessionId=_,this.worktreeCache.set(_,Q),$_.debug("[WorktreeManager] Found worktree from session mapping",{sessionId:_,path:E}),{worktree:Q,isNew:!1};else $_.warn("[WorktreeManager] Worktree path exists on disk but not found in git worktree list",{mappedWorktreePath:E})}}if(!await z4(T))throw Error(`Not a git repository: ${T}`);let J=await C0(T);if(!J)throw Error(`Could not determine repository root for: ${T}`);let X=await D5(J,_);if(X)return X.sessionId=_,this.worktreeCache.set(_,X),this.saveSessionMapping(_,X.path),$_.debug("[WorktreeManager] Found existing worktree (legacy)",{sessionId:_,path:X.path}),{worktree:X,isNew:!1};let H=this.getWorktreePath(J,_);if(D_.existsSync(H)){$_.warn("[WorktreeManager] Worktree path exists but not in git worktree list",{expectedPath:H});let V=await w8(J),N=C4(H),z=V.find((Q)=>C4(Q.path)===N);if(z)return z.sessionId=_,this.worktreeCache.set(_,z),{worktree:z,isNew:!1}}let Z=lh(),Y=this.getWorktreesBasePath(J),K=r_.join(Y,Z),G=`session/${Z}`,$=0;while(D_.existsSync(K)){$++;let V=`${Z}-${$}`;K=r_.join(Y,V),G=`session/${V}`}if(!D_.existsSync(Y))D_.mkdirSync(Y,{recursive:!0}),$_.debug("[WorktreeManager] Created worktrees base directory",{basePath:Y});let U=await bW(J,K,G);return U.sessionId=_,this.saveSessionMapping(_,K),this.worktreeCache.set(_,U),$_.info("[WorktreeManager] Created new worktree",{sessionId:_,worktreeName:r_.basename(K),path:U.path,branch:U.branch}),{worktree:U,isNew:!0}}async getWorktreeForSession(_,T){$_.debug("[WorktreeManager] getWorktreeForSession",{sessionId:_,repoPath:T});let A=this.worktreeCache.get(_);if(A)if(D_.existsSync(A.path))return A;else this.worktreeCache.delete(_);let E=await C0(T);if(!E)return null;let L=await D5(E,_);if(L)L.sessionId=_,this.worktreeCache.set(_,L);return L}async listWorktreesForRepo(_){$_.debug("[WorktreeManager] listWorktreesForRepo",{repoPath:_});let T=await C0(_);if(!T)throw Error(`Could not determine repository root for: ${_}`);let A=await w8(T);for(let E of A)if(!E.isMain)if(E.branch?.startsWith("session/"))E.sessionId=E.branch.substring(8);else{let L=this.getWorktreesBasePath(T);if(C4(E.path).startsWith(C4(L))){let J=r_.basename(E.path);E.sessionId=J}}for(let E of A)if(E.sessionId)this.worktreeCache.set(E.sessionId,E);return A}getActiveWorktreeCount(){return this.worktreeCache.size}clearCache(){this.worktreeCache.clear()}removeFromCache(_){this.worktreeCache.delete(_)}updateSessionId(_,T,A){try{this.deleteSessionMapping(T),this.saveSessionMapping(A,_);let E=this.worktreeCache.get(T);if(E)this.worktreeCache.delete(T),E.sessionId=A,this.worktreeCache.set(A,E);$_.info("[WorktreeManager] Updated session ID mapping",{worktreePath:_,oldSessionId:T,newSessionId:A})}catch(E){$_.error("[WorktreeManager] Failed to update session ID",{error:E,worktreePath:_,oldSessionId:T,newSessionId:A})}}async renameWorktreeForSession(_,T,A){$_.info("[WorktreeManager] Renaming worktree for session",{oldSessionId:_,newSessionId:T,repoPath:A});try{let E=await C0(A);if(!E)return $_.error("[WorktreeManager] Could not determine repo root for rename"),null;let L=this.worktreeCache.get(_);if(!L){if($_.warn("[WorktreeManager] No cached worktree found for old session ID",{oldSessionId:_}),!await D5(E,_))return $_.error("[WorktreeManager] Could not find worktree for old session ID"),null}let J=this.getWorktreePath(E,_),X=this.getWorktreePath(E,T),H=this.generateBranchName(_),Z=this.generateBranchName(T);if(!D_.existsSync(J))return $_.warn("[WorktreeManager] Old worktree path does not exist",{oldPath:J}),null;if(D_.existsSync(X)){$_.warn("[WorktreeManager] New worktree path already exists",{newPath:X});let K={path:X,branch:Z,head:L?.head||"",sessionId:T,isMain:!1};return this.worktreeCache.delete(_),this.worktreeCache.set(T,K),K}await pW(E,J,X),$_.debug("[WorktreeManager] Moved worktree",{from:J,to:X}),await cW(X,H,Z),$_.debug("[WorktreeManager] Renamed branch",{from:H,to:Z}),this.worktreeCache.delete(_);let Y={path:X,branch:Z,head:L?.head||"",sessionId:T,isMain:!1,createdAt:L?.createdAt};return this.worktreeCache.set(T,Y),$_.info("[WorktreeManager] Successfully renamed worktree",{oldSessionId:_,newSessionId:T,oldPath:J,newPath:X,oldBranch:H,newBranch:Z}),Y}catch(E){return $_.error("[WorktreeManager] Failed to rename worktree",{error:E,oldSessionId:_,newSessionId:T}),null}}}import*as Z9 from"path";import*as AN from"os";var x1=v(),B5=Z9.join(AN.homedir(),".ccc"),TN=Z9.join(B5,"pending-permissions.json");class EN{cache=null;async ensureDirectory(){try{let _=await import("fs");if(!_.existsSync(B5))_.mkdirSync(B5,{recursive:!0}),x1.debug("[PendingPermissions] Created .ccc directory:",B5)}catch(_){throw x1.error("[PendingPermissions] Error ensuring directory:",_),_}}async load(){if(this.cache)return this.cache;try{let _=Bun.file(TN);if(await _.exists()){let T=await _.text();return this.cache=JSON.parse(T),x1.debug("[PendingPermissions] Loaded permissions:",{count:this.cache?.permissions?.length||0}),this.cache}}catch(_){x1.warn("[PendingPermissions] Error loading, starting fresh:",_)}return this.cache={permissions:[],lastUpdated:new Date().toISOString()},this.cache}async save(_){try{await this.ensureDirectory(),_.lastUpdated=new Date().toISOString(),await Bun.write(TN,JSON.stringify(_,null,2)),this.cache=_,x1.debug("[PendingPermissions] Saved permissions:",{count:_.permissions.length})}catch(T){throw x1.error("[PendingPermissions] Error saving:",T),T}}async addPermission(_){let T=await this.load(),A=T.permissions.findIndex((E)=>E.requestId===_.requestId);if(A>=0)T.permissions[A]=_,x1.debug("[PendingPermissions] Updated existing permission:",{requestId:_.requestId,sessionId:_.sessionId});else T.permissions.push(_),x1.info("[PendingPermissions] Added new pending permission:",{requestId:_.requestId,sessionId:_.sessionId,action:_.action});await this.save(T)}async removePermission(_){let T=await this.load(),A=T.permissions.length;if(T.permissions=T.permissions.filter((E)=>E.requestId!==_),T.permissions.length<A)return await this.save(T),x1.info("[PendingPermissions] Removed permission:",{requestId:_}),!0;return!1}async removePermissionsForSession(_){let T=await this.load(),A=T.permissions.length;T.permissions=T.permissions.filter((L)=>L.sessionId!==_);let E=A-T.permissions.length;if(E>0)await this.save(T),x1.info("[PendingPermissions] Removed permissions for session:",{sessionId:_,removedCount:E});return E}async getPermissionsForSession(_){return(await this.load()).permissions.filter((A)=>A.sessionId===_)}async getPermissionsForProject(_){return(await this.load()).permissions.filter((A)=>A.projectPath===_)}async getAllPermissions(){return(await this.load()).permissions}async getPermission(_){return(await this.load()).permissions.find((A)=>A.requestId===_)}async clearAll(){this.cache={permissions:[],lastUpdated:new Date().toISOString()},await this.save(this.cache),x1.info("[PendingPermissions] Cleared all pending permissions")}clearCache(){this.cache=null,x1.debug("[PendingPermissions] Cleared cache")}}var LT=new EN;var m=v();class q5{name="Claude Agent Service";running=!1;startedAt;mqttClient=null;sessionsService=null;processManager;worktreeManager;config;totalSessionsCreated=0;totalMessagesProcessed=0;pendingPermissions=new Map;cleanupInterval;constructor(_){this.config=_,this.worktreeManager=new O4,this.processManager=new T9(_,{onSessionInitialized:this.handleSessionInitialized.bind(this),onTitleGenerated:this.handleTitleGenerated.bind(this),onAssistantMessage:this.handleAssistantMessage.bind(this),onPermissionRequest:this.handlePermissionRequest.bind(this),onSessionError:this.handleSessionError.bind(this),onSessionStopped:this.handleSessionStopped.bind(this),onProcessingStarted:this.handleProcessingStarted.bind(this),onProcessingComplete:this.handleProcessingComplete.bind(this),onContextUpdate:this.handleContextUpdate.bind(this)})}async determineWorkingDirectory(_,T,A){try{if(!await z4(T))return m.debug("[ClaudeAgent] Not a git repo, using project path",{projectId:_,directoryPath:T}),{path:T,isWorktree:!1};let L=await C0(T);if(!L)return m.warn("[ClaudeAgent] Could not determine repo root, using project path",{directoryPath:T}),{path:T,isWorktree:!1};m.info("[ClaudeAgent] Git repo detected, creating worktree",{projectId:_,sessionId:A,repoRoot:L});let{worktree:J,isNew:X}=await this.worktreeManager.getOrCreateForSession(A,L);return m.info("[ClaudeAgent] Worktree ready",{sessionId:A,worktreePath:J.path,branch:J.branch,isNew:X}),{path:J.path,isWorktree:!0,branch:J.branch}}catch(E){return m.error("[ClaudeAgent] Worktree creation failed, falling back to project path",{projectId:_,sessionId:A,error:E instanceof Error?E.message:"Unknown error"}),{path:T,isWorktree:!1}}}setMQTTClient(_){this.mqttClient=_}setSessionsService(_){this.sessionsService=_}async start(){try{if(this.running=!0,this.startedAt=new Date,m.info("[ClaudeAgent] Service started"),this.mqttClient)this.registerMQTTHandlers();else m.warn("[ClaudeAgent] MQTT client not set - handlers will not be registered");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions()},300000),m.info("[ClaudeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions,sessionTimeoutMs:this.config.sessionTimeoutMs})}catch(_){throw m.error("[ClaudeAgent] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval);this.processManager.stopAll(),m.info("[ClaudeAgent] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("claude/+/session/start",(_,T)=>{let A=this.extractUserIdFromTopic(_);this.handleSessionStart(A,_,T)}),this.mqttClient.subscribe("claude/+/input/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromInputTopic(_);this.handleUserInput(A,E,_,T)}),this.mqttClient.subscribe("claude/+/permission/response/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromPermissionTopic(_);this.handlePermissionResponse(A,E,_,T)}),this.mqttClient.subscribe("claude/+/session/stop/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromStopTopic(_);this.handleSessionStop(A,E)}),this.mqttClient.subscribe("permissions/pending/request",(_,T)=>{this.handlePendingPermissionsRequest(_,T)}),m.info("[ClaudeAgent] MQTT handlers registered")}async handleSessionStart(_,T,A){try{let E=JSON.parse(A.toString());m.info("[ClaudeAgent] Session start request:",{userId:_,tempId:E.tempId,projectId:E.projectId,directoryPath:E.directoryPath,permissionMode:E.permissionMode,selectedModel:E.selectedModel,hasAttachments:!!E.attachments,attachmentCount:E.attachments?.length||0});let{path:L,isWorktree:J,branch:X}=await this.determineWorkingDirectory(E.projectId,E.directoryPath,E.tempId),H=await this.processManager.spawnSession(E.tempId,_,E.projectId,L,E.initialMessage||"",void 0,E.permissionMode,E.selectedModel,E.attachments);if(J)H.directoryPath=E.directoryPath,H.worktreePath=L,H.worktreeBranch=X;this.totalSessionsCreated++,m.info("[ClaudeAgent] Session spawned successfully:",{userId:_,tempId:E.tempId,projectId:E.projectId,workingPath:L,isWorktree:J})}catch(E){m.error("[ClaudeAgent] Error starting session:",{userId:_,error:E instanceof Error?E.message:"Unknown error"}),this.publishStatus(_,"temp_error",{type:"error",error:E instanceof Error?E.message:"Failed to start session",timestamp:Date.now()})}}async handleUserInput(_,T,A,E){try{let L=JSON.parse(E.toString());if(!L.message&&(!L.attachments||L.attachments.length===0)){m.warn("[ClaudeAgent] Received request without message or attachments:",{userId:_,sessionId:L.sessionId,hasAttachments:!!L.attachments});return}m.info("[ClaudeAgent] User input:",{userId:_,sessionId:L.sessionId,messageLength:L.message?.length||0,permissionMode:L.permissionMode,selectedModel:L.selectedModel,hasAttachments:!!L.attachments,attachmentCount:L.attachments?.length||0,allSessions:this.processManager.getAllSessions().map((Z)=>({tempId:Z.tempId,sessionId:Z.sessionId,status:Z.status}))});let J=this.processManager.getSession(L.sessionId);if(!J){m.warn("[ClaudeAgent] Session not found, creating new session:",{userId:_,requestedSessionId:L.sessionId,projectId:L.projectId,availableSessions:this.processManager.getAllSessions().map((Y)=>Y.sessionId||Y.tempId)});let Z=L.sessionId&&!L.sessionId.startsWith("temp_")&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(L.sessionId);try{let{path:Y,isWorktree:K,branch:G}=await this.determineWorkingDirectory(L.projectId,L.directoryPath,L.sessionId);if(J=await this.processManager.spawnSession(L.sessionId,_,L.projectId,Y,L.message||"",Z?L.sessionId:void 0,L.permissionMode,L.selectedModel,L.attachments),K)J.directoryPath=L.directoryPath,J.worktreePath=Y,J.worktreeBranch=G;this.totalSessionsCreated++,m.info(`[ClaudeAgent] Session ${Z?"resumed":"created"} successfully:`,{userId:_,sessionId:L.sessionId,isResume:Z,workingPath:Y,isWorktree:K}),this.totalMessagesProcessed++;return}catch(Y){m.error("[ClaudeAgent] Failed to create session:",{userId:_,sessionId:L.sessionId,error:Y instanceof Error?Y.message:"Unknown error"}),this.publishStatus(_,L.sessionId,{type:"error",error:"Failed to create session",timestamp:Date.now()});return}}let X=J.permissionMode||"default",H=L.permissionMode||"default";if(H!==X&&J.sessionId)if(m.info("[ClaudeAgent] Permission mode changed, respawning session:",{userId:_,sessionId:J.sessionId,currentMode:X,requestedMode:H}),await this.processManager.respawnWithPermissionMode(J.sessionId,H,L.message||"proceed with implementation")){this.publishStatus(_,J.sessionId,{type:"session_restarted",permissionMode:H,timestamp:Date.now()}),this.totalMessagesProcessed++;return}else m.error("[ClaudeAgent] Failed to respawn session with new permission mode");this.processManager.sendUserMessage(J,L.message||"",L.attachments),this.totalMessagesProcessed++}catch(L){m.error("[ClaudeAgent] Error handling user input:",{userId:_,sessionId:T,error:L instanceof Error?L.message:"Unknown error"})}}async handlePermissionResponse(_,T,A,E){try{let L=JSON.parse(E.toString());m.info("[ClaudeAgent] Permission response:",{userId:_,sessionId:T,requestId:L.requestId,approved:L.approved,hasAnswers:!!L.answers,addToAllowedTools:L.addToAllowedTools,toolPattern:L.toolPattern,permissionMode:L.permissionMode,hardDeny:L.hardDeny,hasDenyMessage:!!L.denyMessage});let J=this.pendingPermissions.get(L.requestId);if(!J)m.warn(`[ClaudeAgent] No pending permission found for request_id: ${L.requestId}`);if(L.approved&&L.addToAllowedTools){let H=this.processManager.getSession(T);if(H){let Z=L.toolPattern||(J?this.generateToolPattern(J.action,J.params):null);if(Z)await this.addToAllowedTools(H.directoryPath,Z),m.info("[ClaudeAgent] Added tool pattern to settings.local.json:",{toolPattern:Z,projectPath:H.directoryPath})}}let X=this.processManager.getSession(T);if(L.permissionMode&&X?.sessionId){if(m.info("[ClaudeAgent] Permission mode change requested, will respawn session:",{sessionId:X.sessionId,newPermissionMode:L.permissionMode}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:J?.params,message:"Permission mode is changing. Stopping current execution for session respawn."}),await new Promise((Z)=>setTimeout(Z,200)),await this.processManager.respawnWithPermissionMode(X.sessionId,L.permissionMode,"proceed with implementation"))this.publishStatus(X.userId,X.sessionId,{type:"session_restarted",permissionMode:L.permissionMode,timestamp:Date.now()});else this.publishStatus(X.userId,X.sessionId,{type:"error",error:"Failed to respawn session with new permission mode",timestamp:Date.now()});if(J)this.pendingPermissions.delete(L.requestId);LT.removePermission(L.requestId).catch((Z)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",Z)});return}if(L.approved&&L.answers&&Object.keys(L.answers).length>0){let H={...J?.params,answers:L.answers};m.info("[ClaudeAgent] Sending AskUserQuestion response:",{requestId:L.requestId,answerCount:Object.keys(L.answers).length}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:H})}else if(L.approved)this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:J?J.params:void 0});else{let H=L.denyMessage||"Permission denied by user",Z=L.hardDeny!==!1;if(m.info("[ClaudeAgent] Sending deny response:",{requestId:L.requestId,hardDeny:Z,hasDenyMessage:!!L.denyMessage}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"deny",message:H,hardDeny:Z}),Z)m.info("[ClaudeAgent] Hard deny - stopping session:",{sessionId:T}),setTimeout(()=>{this.processManager.stopSession(T),this.publishStatus(_,T,{type:"session_stopped",reason:"permission_denied",message:H,timestamp:Date.now()})},100)}if(J)this.pendingPermissions.delete(L.requestId);LT.removePermission(L.requestId).catch((H)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",H)})}catch(L){m.error("[ClaudeAgent] Error handling permission response:",{userId:_,sessionId:T,error:L instanceof Error?L.message:"Unknown error"})}}handleSessionStop(_,T){m.info("[ClaudeAgent] Session stop request:",{userId:_,sessionId:T}),this.processManager.stopSession(T)}async handlePendingPermissionsRequest(_,T){try{let A=JSON.parse(T.toString()),{clientId:E,sessionId:L,projectPath:J}=A;if(!E){m.warn("[ClaudeAgent] Pending permissions request missing clientId");return}m.info("[ClaudeAgent] Pending permissions request:",{clientId:E,sessionId:L,projectPath:J});let X;if(L)X=await LT.getPermissionsForSession(L);else if(J)X=await LT.getPermissionsForProject(J);else X=await LT.getAllPermissions();let H=this.processManager.getAllSessions(),Z=new Set(H.filter(($)=>$.status==="waiting_permission"&&$.sessionId).map(($)=>$.sessionId)),Y=X.filter(($)=>Z.has($.sessionId)),K=`permissions/pending/${E}/response`,G={permissions:Y,timestamp:Date.now()};await this.mqttClient?.publish(K,JSON.stringify(G)),m.info("[ClaudeAgent] Sent pending permissions response:",{clientId:E,count:Y.length,totalStored:X.length})}catch(A){m.error("[ClaudeAgent] Error handling pending permissions request:",A)}}handleSessionInitialized(_,T){if(m.info("[ClaudeAgent] Session initialized callback:",{tempId:_.tempId,sessionId:_.sessionId,model:_.model}),_.worktreePath&&_.tempId&&_.sessionId)this.worktreeManager.updateSessionId(_.worktreePath,_.tempId,_.sessionId);if(this.publishStatus(_.userId,_.sessionId,{type:"session_started",sessionId:_.sessionId,tempId:_.tempId,model:_.model,worktreePath:_.worktreePath,worktreeBranch:_.worktreeBranch,timestamp:Date.now()}),this.sessionsService){let A=_.worktreePath||_.directoryPath;this.sessionsService.notifySessionCreated(_.directoryPath,A).catch((E)=>{m.warn("[ClaudeAgent] Failed to notify sessions service about new session",{error:E})})}}handleTitleGenerated(_,T){m.info("[ClaudeAgent] Title generated callback:",{sessionId:_.sessionId,title:T}),this.publishStatus(_.userId,_.sessionId,{type:"title_generated",title:T,timestamp:Date.now()})}handleAssistantMessage(_,T){if(this.totalMessagesProcessed++,_.sessionId)this.publishOutput(_.userId,_.sessionId,T)}handlePermissionRequest(_,T){if(m.info("[ClaudeAgent] Permission request callback:",{sessionId:_.sessionId,requestId:T.request_id,action:T.action}),_.sessionId)this.publishPermissionRequest(_,T)}handleSessionError(_,T){m.error("[ClaudeAgent] Session error callback:",{sessionId:_.sessionId,tempId:_.tempId,error:T}),this.publishStatus(_.userId,_.sessionId||_.tempId,{type:"error",error:T,timestamp:Date.now()})}handleSessionStopped(_,T){if(m.info("[ClaudeAgent] Session stopped callback:",{sessionId:_.sessionId,tempId:_.tempId,reason:T}),this.publishStatus(_.userId,_.sessionId||_.tempId,{type:"session_stopped",reason:T,timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifySessionStopped()}handleProcessingStarted(_){if(m.info("[ClaudeAgent] Processing started:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_processing",sessionId:_.sessionId,timestamp:Date.now()})}handleProcessingComplete(_){if(m.info("[ClaudeAgent] Processing complete:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_idle",sessionId:_.sessionId,timestamp:Date.now()})}handleContextUpdate(_,T){if(m.info(`[ClaudeAgent] Context update for session ${_.sessionId}:`,{total:T.total,percentage:T.percentage,inputTokens:T.inputTokens,cacheCreation:T.cacheCreation,cacheRead:T.cacheRead,breakdown:{systemPrompt:T.systemPrompt,tools:T.tools,messages:T.messages,remaining:T.remaining}}),_.sessionId)this.publishContextUpdate(_.userId,_.sessionId,T);else m.warn("[ClaudeAgent] Cannot publish context update - no sessionId yet")}publishStatus(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish status - MQTT client not available");return}let E=`claude/${_}/status/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish status to ${E}`,{error:J.message})})}publishOutput(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish output - MQTT client not available");return}let E=`claude/${_}/output/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish output to ${E}`,{error:J.message})})}publishContextUpdate(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish context update - MQTT client not available");return}let E=`claude/${_}/context/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish context to ${E}`,{error:J.message})})}publishPermissionRequest(_,T){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish permission request - MQTT client not available");return}let{userId:A,sessionId:E}=_;m.info("[ClaudeAgent] Raw permission request structure:",{fullRequest:JSON.stringify(T)});let L=T,J=L.request||{},X=J.tool_name||L.tool_name||L.action||"unknown_tool",H=J.input||L.tool_input||L.params||{},Z=J.permission_suggestions||[],Y=J.decision_reason||"",K=J.blocked_path||"";this.pendingPermissions.set(L.request_id,{requestId:L.request_id,action:X,params:H}),LT.addPermission({requestId:L.request_id,sessionId:E,projectPath:_.directoryPath,action:X,params:H,permissionSuggestions:Z.length>0?Z:void 0,decisionReason:Y||void 0,blockedPath:K||void 0,createdAt:new Date().toISOString()}).catch((V)=>{m.error("[ClaudeAgent] Failed to persist pending permission:",V)});let G={request_id:L.request_id,action:X,params:H,permission_suggestions:Z,decision_reason:Y,blocked_path:K},$=`claude/${A}/permission/request/${E}`,U=JSON.stringify(G);m.info("[ClaudeAgent] Publishing transformed permission request:",{topic:$,request_id:G.request_id,action:G.action}),this.mqttClient.publish($,U).catch((V)=>{m.error(`[ClaudeAgent] Failed to publish permission request to ${$}`,{error:V.message})})}extractUserIdFromTopic(_){return _.split("/")[1]||""}extractIdsFromInputTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[3]||""}}extractIdsFromPermissionTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[4]||""}}extractIdsFromStopTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[4]||""}}generateToolPattern(_,T){switch(_){case"Bash":case"bash":case"execute_command":return`Bash(${T.command})`;case"Read":case"read":case"read_file":return`Read(${T.file_path})`;case"Write":case"write":case"write_file":return`Write(${T.file_path})`;case"Edit":case"edit":return`Edit(${T.file_path})`;default:return _}}async addToAllowedTools(_,T){try{let A=LN.join(_,".claude"),E=LN.join(A,"settings.local.json"),L=Bun.file(A);if(!await Bun.$`test -d ${A}`.quiet().nothrow())await Bun.$`mkdir -p ${A}`.quiet();let J={},X=Bun.file(E);if(await X.exists())try{let H=await X.text();J=JSON.parse(H)}catch{J={}}if(J.permissions=J.permissions||{},J.permissions.allow=J.permissions.allow||[],!J.permissions.allow.includes(T))J.permissions.allow.push(T);await Bun.write(E,JSON.stringify(J,null,2)),m.info("[ClaudeAgent] Updated settings.local.json with allowed tool:",{settingsPath:E,toolPattern:T,totalAllowed:J.permissions.allow.length})}catch(A){m.error("[ClaudeAgent] Failed to update settings.local.json:",{projectPath:_,toolPattern:T,error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.processManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessions(){return this.processManager.getAllSessions().filter((_)=>_.sessionId).map((_)=>({sessionId:_.sessionId,projectPath:_.directoryPath,status:_.status,worktreePath:_.worktreePath,worktreeBranch:_.worktreeBranch}))}}import*as Y_ from"fs/promises";import*as y_ from"path";var u0=v();class I5{validatePath(_,T){try{let A=y_.resolve(_),E=y_.resolve(A,T);if(!(E===A||E.startsWith(A+y_.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};return{valid:!0,fullPath:E}}catch(A){return{valid:!1,fullPath:"",error:`Path validation error: ${A instanceof Error?A.message:"Unknown error"}`}}}async listDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{entries:[],error:A.error};try{if(!(await Y_.stat(A.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let L=await Y_.readdir(A.fullPath,{withFileTypes:!0}),J=await Promise.all(L.map(async(X)=>{let H=y_.join(A.fullPath,X.name);try{let Z=await Y_.stat(H);return{name:X.name,type:X.isDirectory()?"directory":"file",size:X.isFile()?Z.size:void 0,modified:Z.mtime.toISOString()}}catch{return{name:X.name,type:X.isDirectory()?"directory":"file"}}}));return J.sort((X,H)=>{if(X.type!==H.type)return X.type==="directory"?-1:1;return X.name.localeCompare(H.name,void 0,{sensitivity:"base"})}),{entries:J}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] listDirectory error",{error:L,path:A.fullPath}),{entries:[],error:`Failed to list directory: ${L}`}}}async readFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{content:"",size:0,error:A.error};try{let E=await Y_.stat(A.fullPath);if(!E.isFile())return{content:"",size:0,error:"Path is not a file"};return{content:await Y_.readFile(A.fullPath,"utf-8"),size:E.size}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] readFile error",{error:L,path:A.fullPath}),{content:"",size:0,error:`Failed to read file: ${L}`}}}async writeFile(_,T,A){let E=this.validatePath(_,T);if(!E.valid)return{success:!1,error:E.error};try{let L=y_.dirname(E.fullPath);return await Y_.mkdir(L,{recursive:!0}),await Y_.writeFile(E.fullPath,A,"utf-8"),{success:!0}}catch(L){let J=L instanceof Error?L.message:"Unknown error";return u0.error("[FileManager] writeFile error",{error:J,path:E.fullPath}),{success:!1,error:`Failed to write file: ${J}`}}}async createFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{try{return await Y_.access(A.fullPath),{success:!1,error:"File already exists"}}catch{}let E=y_.basename(T);if(!this.isValidFilename(E))return{success:!1,error:"Invalid filename"};let L=y_.dirname(A.fullPath);return await Y_.mkdir(L,{recursive:!0}),await Y_.writeFile(A.fullPath,"","utf-8"),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] createFile error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to create file: ${L}`}}}async createDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{let E=y_.basename(T);if(!this.isValidFilename(E))return{success:!1,error:"Invalid directory name"};try{if((await Y_.stat(A.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await Y_.mkdir(A.fullPath,{recursive:!0}),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] createDirectory error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to create directory: ${L}`}}}async deleteFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{if(!(await Y_.stat(A.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await Y_.unlink(A.fullPath),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] deleteFile error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to delete file: ${L}`}}}async deleteDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};if(A.fullPath===y_.resolve(_))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await Y_.stat(A.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await Y_.rm(A.fullPath,{recursive:!0,force:!0}),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] deleteDirectory error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to delete directory: ${L}`}}}async pathExists(_,T){let A=this.validatePath(_,T);if(!A.valid)return!1;try{return await Y_.access(A.fullPath),!0}catch{return!1}}async getStats(_,T){let A=this.validatePath(_,T);if(!A.valid)return null;try{let E=await Y_.stat(A.fullPath);return{isFile:E.isFile(),isDirectory:E.isDirectory(),size:E.size,modified:E.mtime.toISOString()}}catch{return null}}async readFileBinary(_,T){let A=this.validatePath(_,T);if(!A.valid)return{content:Buffer.alloc(0),size:0,mimeType:"",error:A.error};try{let E=await Y_.stat(A.fullPath);if(!E.isFile())return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Path is not a file"};let L=52428800;if(E.size>L)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"File exceeds maximum size of 50MB"};let J=await Y_.readFile(A.fullPath),X=this.getMimeType(y_.basename(T));return{content:J,size:E.size,mimeType:X}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] readFileBinary error",{error:L,path:A.fullPath}),{content:Buffer.alloc(0),size:0,mimeType:"",error:`Failed to read file: ${L}`}}}async writeFileBinary(_,T,A){let E=this.validatePath(_,T);if(!E.valid)return{success:!1,error:E.error};try{let L=y_.basename(T);if(!this.isValidFilename(L))return{success:!1,error:"Invalid filename"};let J=y_.dirname(E.fullPath);return await Y_.mkdir(J,{recursive:!0}),await Y_.writeFile(E.fullPath,A),{success:!0}}catch(L){let J=L instanceof Error?L.message:"Unknown error";return u0.error("[FileManager] writeFileBinary error",{error:J,path:E.fullPath}),{success:!1,error:`Failed to write file: ${J}`}}}getMimeType(_){let T=y_.extname(_).toLowerCase();return{".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".tiff":"image/tiff",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".txt":"text/plain",".json":"application/json",".xml":"application/xml",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".tsx":"application/typescript",".jsx":"application/javascript",".md":"text/markdown",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".7z":"application/x-7z-compressed",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".m4a":"audio/mp4",".flac":"audio/flac",".aac":"audio/aac",".mp4":"video/mp4",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".webm":"video/webm",".wmv":"video/x-ms-wmv",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".apk":"application/vnd.android.package-archive",".ipa":"application/octet-stream",".exe":"application/x-msdownload",".dmg":"application/x-apple-diskimage",".deb":"application/x-deb",".rpm":"application/x-rpm"}[T]||"application/octet-stream"}isValidFilename(_){if(!_||_.length===0)return!1;if(_.includes("/")||_.includes("\\"))return!1;let T=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],A=(_.split(".")[0]||"").toUpperCase();if(T.includes(A))return!1;if(/[<>:"|?*\x00-\x1f]/.test(_))return!1;if(_==="."||_==="..")return!1;return!0}}import*as Y9 from"path";var A1=v(),R4=51200,JN=50;class P5{name="File Browser Service";running=!1;startedAt;mqttClient=null;fileManager;requestsHandled=0;messageHandlers=new Map;fileSaveOperations=new Map;binaryUploadOperations=new Map;constructor(){this.fileManager=new I5}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,A1.info("[FileBrowser] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw A1.error("[FileBrowser] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){for(let[_,T]of this.messageHandlers)this.mqttClient.unsubscribe(_,T);this.messageHandlers.clear()}this.fileSaveOperations.clear(),this.binaryUploadOperations.clear(),A1.info("[FileBrowser] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("files/list/request",(_,T)=>{this.handleDirectoryListRequest(T)}),this.registerHandler("files/content/request",(_,T)=>{this.handleFileContentRequest(T)}),this.registerHandler("files/save/request",(_,T)=>{this.handleFileSaveRequest(T)}),this.registerHandler("files/create/request",(_,T)=>{this.handleFileCreateRequest(T)}),this.registerHandler("files/delete/request",(_,T)=>{this.handleFileDeleteRequest(T)}),this.registerHandler("files/upload/request",(_,T)=>{this.handleBinaryUploadRequest(T)}),this.registerHandler("files/download/request",(_,T)=>{this.handleBinaryDownloadRequest(T)}),A1.info("[FileBrowser] MQTT handlers registered")}registerHandler(_,T){if(!this.mqttClient)return;this.messageHandlers.set(_,T),this.mqttClient.subscribe(_,T)}async handleDirectoryListRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.listDirectory(T.projectPath,T.relativePath),E={path:T.relativePath,entries:A.entries,timestamp:Date.now(),error:A.error};await this.publishResponse(`files/list/${T.clientId}/response`,E),this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling directory list request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileContentRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.readFile(T.projectPath,T.relativePath),E=`files/content/${T.clientId}/response`;if(A.error){let J={path:T.relativePath,chunk:{chunkIndex:0,totalChunks:1,content:""},totalSize:0,timestamp:Date.now(),error:A.error};await this.publishResponse(E,J);return}let L=Math.max(1,Math.ceil(A.content.length/R4));for(let J=0;J<L;J++){let X=J*R4,H=Math.min(X+R4,A.content.length),Z=A.content.slice(X,H),Y={path:T.relativePath,chunk:{chunkIndex:J,totalChunks:L,content:Z},totalSize:A.size,timestamp:Date.now()};if(await this.publishResponse(E,Y),J<L-1)await this.delay(JN)}this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file content request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileSaveRequest(_){try{let T=JSON.parse(_.toString()),A=`${T.clientId}:${T.relativePath}`;if(T.chunk.chunkIndex===0)this.fileSaveOperations.set(A,{chunks:new Map,totalChunks:T.chunk.totalChunks,totalSize:T.totalSize});let E=this.fileSaveOperations.get(A);if(!E){await this.sendSaveResponse(T,!1,"Save operation not initialized");return}if(E.chunks.set(T.chunk.chunkIndex,T.chunk.content),await this.sendSaveResponse(T,!0),E.chunks.size===E.totalChunks){let L=[];for(let H=0;H<E.totalChunks;H++){let Z=E.chunks.get(H);if(Z!==void 0)L.push(Z)}let J=L.join(""),X=await this.fileManager.writeFile(T.projectPath,T.relativePath,J);if(this.fileSaveOperations.delete(A),!X.error)this.requestsHandled++}}catch(T){A1.error("[FileBrowser] Error handling file save request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileCreateRequest(_){try{let T=JSON.parse(_.toString()),A;if(T.type==="directory")A=await this.fileManager.createDirectory(T.projectPath,T.relativePath);else A=await this.fileManager.createFile(T.projectPath,T.relativePath);let E={path:T.relativePath,success:A.success,type:T.type,timestamp:Date.now(),error:A.error};if(await this.publishResponse(`files/create/${T.clientId}/response`,E),A.success)this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file create request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileDeleteRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.getStats(T.projectPath,T.relativePath),E;if(!A)E={success:!1,error:"Path does not exist"};else if(A.isDirectory)E=await this.fileManager.deleteDirectory(T.projectPath,T.relativePath);else E=await this.fileManager.deleteFile(T.projectPath,T.relativePath);let L={path:T.relativePath,success:E.success,timestamp:Date.now(),error:E.error};if(await this.publishResponse(`files/delete/${T.clientId}/response`,L),E.success)this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file delete request",{error:T instanceof Error?T.message:"Unknown error"})}}async sendSaveResponse(_,T,A){let E={path:_.relativePath,success:T,chunkIndex:_.chunk.chunkIndex,totalChunks:_.chunk.totalChunks,timestamp:Date.now(),error:A};await this.publishResponse(`files/save/${_.clientId}/response`,E)}async publishResponse(_,T){if(!this.mqttClient){A1.error("[FileBrowser] MQTT client not available");return}await this.mqttClient.publish(_,JSON.stringify(T),{qos:1})}delay(_){return new Promise((T)=>setTimeout(T,_))}async handleBinaryUploadRequest(_){try{let T=JSON.parse(_.toString()),A=`${T.clientId}:${T.relativePath}`;if(T.chunk.chunkIndex===0){if(T.totalSize>52428800){await this.sendBinaryUploadResponse(T,!1,"File exceeds 50MB limit",0);return}this.binaryUploadOperations.set(A,{chunks:new Map,totalChunks:T.chunk.totalChunks,totalSize:T.totalSize,filename:T.filename,mimeType:T.mimeType,receivedBytes:0})}let E=this.binaryUploadOperations.get(A);if(!E){await this.sendBinaryUploadResponse(T,!1,"Upload operation not initialized",0);return}let L=Buffer.from(T.chunk.data,"base64");if(E.chunks.set(T.chunk.chunkIndex,L),E.receivedBytes+=L.length,await this.sendBinaryUploadResponse(T,!0,void 0,E.receivedBytes),E.chunks.size===E.totalChunks){let J=[];for(let Z=0;Z<E.totalChunks;Z++){let Y=E.chunks.get(Z);if(Y)J.push(Y)}let X=Buffer.concat(J),H=await this.fileManager.writeFileBinary(T.projectPath,T.relativePath,X);if(this.binaryUploadOperations.delete(A),H.error)A1.error("[FileBrowser] Binary upload write failed",{error:H.error});else this.requestsHandled++,A1.info("[FileBrowser] Binary upload completed",{path:T.relativePath,size:X.length})}}catch(T){A1.error("[FileBrowser] Error handling binary upload",{error:T instanceof Error?T.message:"Unknown error"})}}async sendBinaryUploadResponse(_,T,A,E){let L={path:_.relativePath,success:T,chunkIndex:_.chunk.chunkIndex,totalChunks:_.chunk.totalChunks,bytesReceived:E||0,timestamp:Date.now(),error:A};await this.publishResponse(`files/upload/${_.clientId}/response`,L)}async handleBinaryDownloadRequest(_){try{let T=JSON.parse(_.toString()),A=`files/download/${T.clientId}/response`,E=await this.fileManager.readFileBinary(T.projectPath,T.relativePath);if(E.error){let H={path:T.relativePath,filename:Y9.basename(T.relativePath),mimeType:"",chunk:{chunkIndex:0,totalChunks:1,data:""},totalSize:0,timestamp:Date.now(),error:E.error};await this.publishResponse(A,H);return}let L=E.content.toString("base64"),J=Math.max(1,Math.ceil(L.length/R4)),X=Y9.basename(T.relativePath);for(let H=0;H<J;H++){let Z=H*R4,Y=Math.min(Z+R4,L.length),K=L.slice(Z,Y),G={path:T.relativePath,filename:X,mimeType:E.mimeType,chunk:{chunkIndex:H,totalChunks:J,data:K},totalSize:E.size,timestamp:Date.now()};if(await this.publishResponse(A,G),H<J-1)await this.delay(JN)}this.requestsHandled++,A1.info("[FileBrowser] Binary download completed",{path:T.relativePath,size:E.size,chunks:J})}catch(T){A1.error("[FileBrowser] Error handling binary download",{error:T instanceof Error?T.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,pendingSaveOperations:this.fileSaveOperations.size}}}var g=v();class j5{name="Git Service";running=!1;startedAt;mqttClient=null;worktreeManager;requestsHandled=0;messageHandlers=new Map;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){this.worktreeManager=new O4}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,this.ghAuthResult=await vW(),!this.ghAuthResult.authenticated)g.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else g.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username});if(this.mqttClient)this.registerMQTTHandlers();g.info("[GitService] Service started")}catch(_){throw g.error("[GitService] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){for(let[_,T]of this.messageHandlers)this.mqttClient.unsubscribe(_,T),g.debug(`[GitService] Unsubscribed from ${_}`);this.messageHandlers.clear()}this.worktreeManager.clearCache(),g.info("[GitService] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("git/orgs/request",(_,T)=>{this.handleOrgsRequest(T)}),this.registerHandler("git/repos/request",(_,T)=>{this.handleReposRequest(T)}),this.registerHandler("git/repos/search/request",(_,T)=>{this.handleSearchReposRequest(T)}),this.registerHandler("git/branches/request",(_,T)=>{this.handleBranchesRequest(T)}),this.registerHandler("git/clone/request",(_,T)=>{this.handleCloneRequest(T)}),this.registerHandler("git/is-repo/request",(_,T)=>{this.handleIsRepoRequest(T)}),this.registerHandler("git/worktree/get-or-create/request",(_,T)=>{this.handleWorktreeGetOrCreateRequest(T)}),this.registerHandler("git/worktree/get/request",(_,T)=>{this.handleWorktreeGetRequest(T)}),this.registerHandler("git/worktree/list/request",(_,T)=>{this.handleWorktreeListRequest(T)}),this.registerHandler("git/status/request",(_,T)=>{this.handleStatusRequest(T)}),this.registerHandler("git/diff/request",(_,T)=>{this.handleDiffRequest(T)}),this.registerHandler("git/changes/all/request",(_,T)=>{this.handleChangesAllRequest(T)}),this.registerHandler("git/stage/request",(_,T)=>{this.handleStageRequest(T)}),this.registerHandler("git/unstage/request",(_,T)=>{this.handleUnstageRequest(T)}),this.registerHandler("git/commit/request",(_,T)=>{this.handleCommitRequest(T)}),this.registerHandler("git/unpushed/request",(_,T)=>{this.handleUnpushedCommitsRequest(T)}),this.registerHandler("git/push/request",(_,T)=>{this.handlePushRequest(T)}),this.registerHandler("git/history/request",(_,T)=>{this.handleHistoryRequest(T)}),this.registerHandler("git/commit-details/request",(_,T)=>{this.handleCommitDetailsRequest(T)}),this.registerHandler("git/commit-file-diff/request",(_,T)=>{this.handleCommitFileDiffRequest(T)}),this.registerHandler("git/sync/request",(_,T)=>{this.handleSyncRequest(T)}),this.registerHandler("git/create-pr/request",(_,T)=>{this.handleCreatePRRequest(T)}),this.registerHandler("git/default-branch/request",(_,T)=>{this.handleDefaultBranchRequest(T)}),this.registerHandler("git/existing-pr/request",(_,T)=>{this.handleExistingPRRequest(T)}),this.registerHandler("git/remote-branches/request",(_,T)=>{this.handleRemoteBranchesRequest(T)}),g.info("[GitService] MQTT handlers registered")}registerHandler(_,T){if(!this.mqttClient)return;this.messageHandlers.set(_,T),this.mqttClient.subscribe(_,T),g.debug(`[GitService] Subscribed to ${_}`)}async publishResponse(_,T){if(!this.mqttClient){g.error("[GitService] MQTT client not available");return}await this.mqttClient.publish(_,JSON.stringify(T),{qos:1})}async handleOrgsRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Orgs request",{clientId:T.clientId}),!this.ghAuthResult.authenticated){let L={orgs:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/orgs/${T.clientId}/response`,L);return}let E={orgs:await E9(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling orgs request",{error:T})}}async handleReposRequest(_){try{let T=JSON.parse(_.toString()),A=T.requestId||T.clientId;if(g.debug("[GitService] Repos request",{clientId:T.clientId,requestId:T.requestId,org:T.org,limit:T.limit}),!this.ghAuthResult.authenticated){let J={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,J);return}let L={repos:await R5(T.org,T.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling repos request",{error:T})}}async handleSearchReposRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Search repos request",{clientId:T.clientId,query:T.query,limit:T.limit}),!this.ghAuthResult.authenticated){let A={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/search/${T.clientId}/response`,A);return}await hW(T.query,async(A,E,L)=>{let J={repos:A,timestamp:Date.now(),source:E,isComplete:L};await this.publishResponse(`git/repos/search/${T.clientId}/response`,J),g.debug("[GitService] Sent search results",{source:E,count:A.length,isComplete:L})},T.limit||50),this.requestsHandled++}catch(T){g.error("[GitService] Error handling search repos request",{error:T})}}async handleBranchesRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Branches request",{clientId:T.clientId,owner:T.owner,repo:T.repo}),!this.ghAuthResult.authenticated){let L={branches:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/branches/${T.clientId}/response`,L);return}let A=await kW(T.owner,T.repo),E={branches:A.branches,defaultBranch:A.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/branches/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling branches request",{error:T})}}async handleCloneRequest(_){try{let T=JSON.parse(_.toString());if(g.info("[GitService] Clone request",{clientId:T.clientId,repoUrl:T.repoUrl,targetPath:T.targetPath,branch:T.branch}),!this.ghAuthResult.authenticated){let L={success:!1,error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/clone/${T.clientId}/response`,L);return}let A=await fW(T.repoUrl,T.targetPath,T.branch),E=A.success?{success:!0,path:A.path,defaultBranch:A.defaultBranch,timestamp:Date.now()}:{success:!1,error:A.error||"Clone failed",timestamp:Date.now()};await this.publishResponse(`git/clone/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling clone request",{error:T})}}async handleIsRepoRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Is-repo request",{clientId:T.clientId,path:T.path});let A=await z4(T.path),E;if(A){let[L,J,X]=await Promise.all([C0(T.path),F4(T.path),lW(T.path)]);E={isGitRepo:!0,repoRoot:L||void 0,defaultBranch:J||void 0,remoteUrl:X||void 0,timestamp:Date.now()}}else E={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling is-repo request",{error:T});let A=JSON.parse(_.toString()),E={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${A.clientId}/response`,E)}}async handleWorktreeGetOrCreateRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree get-or-create request",{clientId:T.clientId,repoPath:T.repoPath,sessionId:T.sessionId});let{worktree:A,isNew:E}=await this.worktreeManager.getOrCreateForSession(T.sessionId,T.repoPath),L={success:!0,worktreePath:A.path,branch:A.branch,isNew:E,timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${T.clientId}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree get-or-create request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${A.clientId}/response`,E)}}async handleWorktreeGetRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree get request",{clientId:T.clientId,repoPath:T.repoPath,sessionId:T.sessionId});let A=await this.worktreeManager.getWorktreeForSession(T.sessionId,T.repoPath),E=A?{exists:!0,worktreePath:A.path,branch:A.branch,timestamp:Date.now()}:{exists:!1,timestamp:Date.now()};await this.publishResponse(`git/worktree/get/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree get request",{error:T})}}async handleWorktreeListRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree list request",{clientId:T.clientId,repoPath:T.repoPath});let E={worktrees:await this.worktreeManager.listWorktreesForRepo(T.repoPath),timestamp:Date.now()};await this.publishResponse(`git/worktree/list/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree list request",{error:T})}}async handleStatusRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Status request",{clientId:T.clientId,path:T.path});let E={success:!0,status:await L9(T.path),timestamp:Date.now()};await this.publishResponse(`git/status/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling status request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/status/${A.clientId}/response`,E)}}async handleDiffRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Diff request",{clientId:T.clientId,path:T.path,file:T.file,staged:T.staged});let A=await gW(T.path,T.file,T.staged),E={success:!0,diff:A.diff,isBinary:A.isBinary,timestamp:Date.now()};await this.publishResponse(`git/diff/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling diff request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/diff/${A.clientId}/response`,E)}}async handleChangesAllRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Changes all request",{clientId:T.clientId,repoPath:T.repoPath});let A=await this.worktreeManager.listWorktreesForRepo(T.repoPath),E={repoPath:T.repoPath,worktrees:[],totalChanges:0};for(let J of A)try{let X=await L9(J.path);E.worktrees.push({worktreePath:J.path,branch:J.branch,sessionId:J.sessionId,changes:X.files,totalCount:X.files.length}),E.totalChanges+=X.files.length}catch(X){g.warn("[GitService] Failed to get status for worktree",{path:J.path,error:X})}let L={success:!0,changes:E,timestamp:Date.now()};await this.publishResponse(`git/changes/all/${T.clientId}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling changes all request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/changes/all/${A.clientId}/response`,E)}}async handleStageRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Stage request",{clientId:T.clientId,path:T.path,files:T.files}),await mW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){g.error("[GitService] Error handling stage request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/stage/${A.clientId}/response`,E)}}async handleUnstageRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Unstage request",{clientId:T.clientId,path:T.path,files:T.files}),await uW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){g.error("[GitService] Error handling unstage request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unstage/${A.clientId}/response`,E)}}async handleCommitRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Commit request",{clientId:T.clientId,path:T.path,signoff:T.signoff});let E={success:!0,commit:await dW(T.path,T.message,T.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit/${A.clientId}/response`,E)}}async handleUnpushedCommitsRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Unpushed commits request",{clientId:T.clientId,path:T.path});let A=await V4(T.path),E={success:!0,commits:A.commits,upstream:A.upstream,ahead:A.ahead,timestamp:Date.now()};await this.publishResponse(`git/unpushed/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling unpushed commits request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unpushed/${A.clientId}/response`,E)}}async handlePushRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Push request",{clientId:T.clientId,path:T.path,force:T.force});let A=await nW(T.path,T.force),E={success:!0,commitsPushed:A.commitsPushed,remote:A.remote,branch:A.branch,timestamp:Date.now()};await this.publishResponse(`git/push/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling push request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/push/${A.clientId}/response`,E)}}async handleHistoryRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] History request",{clientId:T.clientId,path:T.path,limit:T.limit});let A=await iW(T.path,T.limit||50),E={success:!0,commits:A.commits,totalCount:A.totalCount,timestamp:Date.now()};await this.publishResponse(`git/history/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling history request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/history/${A.clientId}/response`,E)}}async handleCommitDetailsRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Commit details request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash});let E={success:!0,commit:await aW(T.path,T.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit details request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-details/${A.clientId}/response`,E)}}async handleCommitFileDiffRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Commit file diff request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash,filePath:T.filePath});let A=await rW(T.path,T.commitHash,T.filePath),E={success:!0,diff:A.diff,isBinary:A.isBinary,timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit file diff request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${A.clientId}/response`,E)}}async handleSyncRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Sync request",{clientId:T.clientId,path:T.path});let A=await oW(T.path),E=A.success?{success:!0,action:A.action,commitsPulled:A.commitsPulled,commitsPushed:A.commitsPushed,timestamp:Date.now()}:{success:!1,action:A.action,commitsPulled:A.commitsPulled,commitsPushed:A.commitsPushed,error:A.error||"Sync failed",conflictedFiles:A.conflictedFiles,timestamp:Date.now()};await this.publishResponse(`git/sync/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling sync request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/sync/${A.clientId}/response`,E)}}async handleCreatePRRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Create PR request",{clientId:T.clientId,path:T.path,title:T.title,baseBranch:T.baseBranch,draft:T.draft});let A=await sW(T.path,T.title,T.body,T.baseBranch,T.draft),E=A.success?{success:!0,prNumber:A.prNumber,prUrl:A.prUrl,timestamp:Date.now()}:{success:!1,error:A.error||"Failed to create pull request",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling create PR request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${A.clientId}/response`,E)}}async handleDefaultBranchRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Default branch request",{clientId:T.clientId,path:T.path});let A=await J9(T.path),E=A?{success:!0,defaultBranch:A,timestamp:Date.now()}:{success:!1,error:"Could not determine default branch",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling default branch request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${A.clientId}/response`,E)}}async handleExistingPRRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Existing PR request",{clientId:T.clientId,path:T.path});let A=await tW(T.path),E={exists:A.exists,prNumber:A.prNumber,prUrl:A.prUrl,title:A.title,state:A.state,draft:A.draft,error:A.error,timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling existing PR request",{error:T});let A=JSON.parse(_.toString()),E={exists:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${A.clientId}/response`,E)}}async handleRemoteBranchesRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Remote branches request",{clientId:T.clientId,path:T.path});let A=await eW(T.path),E={success:!0,branches:A.branches,defaultBranch:A.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling remote branches request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${A.clientId}/response`,E)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,activeWorktrees:this.worktreeManager.getActiveWorktreeCount(),ghAuthenticated:this.ghAuthResult.authenticated,ghInstalled:this.ghAuthResult.installed,ghInPath:this.ghAuthResult.inPath,ghError:this.ghAuthResult.error,ghUsername:this.ghAuthResult.username}}}import*as UN from"path";import*as x5 from"path";import*as ZN from"os";var d_=v(),S8=x5.join(ZN.homedir(),".ccc"),XN=x5.join(S8,"device-tokens.json"),HN=x5.join(S8,"notification-preferences.json");class YN{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if((await Bun.$`test -d ${S8}`.quiet().nothrow()).exitCode!==0)await Bun.$`mkdir -p ${S8}`.quiet(),d_.debug("[NotificationStorage] Created .ccc directory:",S8)}catch(_){throw d_.error("[NotificationStorage] Error ensuring directory:",_),_}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let _=Bun.file(XN);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(XN,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(HN);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(HN,JSON.stringify(_,null,2)),this.preferencesCache=_,d_.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(_.preferences).length})}catch(T){throw d_.error("[NotificationStorage] Error saving preferences:",T),T}}getDefaultPreferences(_){return{deviceId:_,allMessages:!0,needsAttention:!0,updatedAt:new Date().toISOString()}}async getPreferences(_){let T=await this.loadPreferences();if(!T.preferences[_])T.preferences[_]=this.getDefaultPreferences(_),await this.savePreferences(T),d_.info("[NotificationStorage] Created default preferences for device:",{deviceId:_});return T.preferences[_]}async updatePreferences(_,T){let A=await this.loadPreferences(),E=await this.getPreferences(_);return A.preferences[_]={...E,...T,deviceId:_,updatedAt:new Date().toISOString()},await this.savePreferences(A),d_.info("[NotificationStorage] Updated preferences:",{deviceId:_,updates:T}),A.preferences[_]}async isNotificationEnabled(_,T){return(await this.getPreferences(_))[T]}clearCache(){this.tokensCache=null,this.preferencesCache=null,d_.debug("[NotificationStorage] Cleared cache")}}var w1=new YN;import KN from"expo-server-sdk";var G1=v();class GN{expo;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;constructor(){this.expo=new KN}isValidToken(_){return KN.isExpoPushToken(_)}async sendNotification(_,T){if(!this.isValidToken(_))return G1.warn("[ExpoPushClient] Invalid Expo push token:",{token:_.substring(0,20)+"..."}),null;let A={to:_,title:T.title,body:T.body,data:T.data,sound:T.sound||"default",channelId:T.channelId||"default",priority:T.priority||"high",badge:T.badge};try{let L=(await this.expo.sendPushNotificationsAsync([A]))[0];if(this.notificationsSent++,this.lastNotificationAt=new Date,L.id){let J=L;this.pendingTickets.set(J.id,{ticketId:J.id,token:_,createdAt:new Date})}if(L.status==="error"){let J=L;await this.handleTicketError(J,_)}return G1.debug("[ExpoPushClient] Sent notification:",{token:_.substring(0,20)+"...",status:L.status}),L}catch(E){return G1.error("[ExpoPushClient] Error sending notification:",E),null}}async sendBatchNotifications(_,T){let A=_.filter((X)=>{let H=this.isValidToken(X);if(!H)G1.warn("[ExpoPushClient] Skipping invalid token:",{token:X.substring(0,20)+"..."});return H});if(A.length===0)return G1.warn("[ExpoPushClient] No valid tokens to send to"),[];let E=A.map((X)=>({to:X,title:T.title,body:T.body,data:T.data,sound:T.sound||"default",channelId:T.channelId||"default",priority:T.priority||"high",badge:T.badge})),L=this.expo.chunkPushNotifications(E),J=[];for(let X of L)try{let H=await this.expo.sendPushNotificationsAsync(X);J.push(...H);for(let Z=0;Z<H.length;Z++){let Y=H[Z],K=A[J.length-H.length+Z];if(Y.id){let G=Y;this.pendingTickets.set(G.id,{ticketId:G.id,token:K,createdAt:new Date})}if(Y.status==="error")await this.handleTicketError(Y,K)}this.notificationsSent+=H.length,this.lastNotificationAt=new Date}catch(H){G1.error("[ExpoPushClient] Error sending batch chunk:",H)}return G1.info("[ExpoPushClient] Sent batch notifications:",{total:A.length,successful:J.filter((X)=>X.status==="ok").length,failed:J.filter((X)=>X.status==="error").length}),J}async handleTicketError(_,T){if(G1.warn("[ExpoPushClient] Ticket error:",{message:_.message,details:_.details}),_.details?.error==="DeviceNotRegistered"){G1.info("[ExpoPushClient] Removing invalid token:",{token:T.substring(0,20)+"..."});let E=(await w1.getAllTokens()).find((L)=>L.expoPushToken===T);if(E)await w1.unregisterToken(E.deviceId)}}async checkReceipts(){let _=new Date;_.setMinutes(_.getMinutes()-15);let T=[];for(let[L,J]of this.pendingTickets.entries())if(J.createdAt<_)T.push(L);if(T.length===0)return;G1.debug("[ExpoPushClient] Checking receipts:",{count:T.length});let A=this.expo.chunkPushNotificationReceiptIds(T);for(let L of A)try{let J=await this.expo.getPushNotificationReceiptsAsync(L);for(let[X,H]of Object.entries(J)){let Z=this.pendingTickets.get(X);if(H.status==="ok")G1.debug("[ExpoPushClient] Receipt OK:",{ticketId:X});else if(H.status==="error"){let Y=H;if(G1.warn("[ExpoPushClient] Receipt error:",{ticketId:X,message:Y.message,details:Y.details}),Y.details?.error==="DeviceNotRegistered"&&Z){let G=(await w1.getAllTokens()).find(($)=>$.expoPushToken===Z.token);if(G)G1.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:G.deviceId}),await w1.unregisterToken(G.deviceId)}}this.pendingTickets.delete(X)}}catch(J){G1.error("[ExpoPushClient] Error checking receipts:",J)}let E=new Date;E.setHours(E.getHours()-24);for(let[L,J]of this.pendingTickets.entries())if(J.createdAt<E)this.pendingTickets.delete(L)}getStats(){return{notificationsSent:this.notificationsSent,lastNotificationAt:this.lastNotificationAt,pendingReceipts:this.pendingTickets.size}}}var y8=new GN;var Q_=v(),$N=200,nh=900000;class w5{name="Notification Service";running=!1;startedAt;mqttClient=null;claudeAgentService=null;receiptCheckInterval;constructor(){}setMQTTClient(_){this.mqttClient=_}setClaudeAgentService(_){this.claudeAgentService=_}async start(){try{if(this.running=!0,this.startedAt=new Date,Q_.info("[Notification] Service started"),this.mqttClient)this.registerMQTTHandlers();else Q_.warn("[Notification] MQTT client not set - handlers will not be registered");this.receiptCheckInterval=setInterval(()=>{y8.checkReceipts().catch((_)=>{Q_.error("[Notification] Error checking receipts:",_)})},nh),Q_.info("[Notification] Ready to send notifications")}catch(_){throw Q_.error("[Notification] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.receiptCheckInterval)clearInterval(this.receiptCheckInterval);Q_.info("[Notification] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("notifications/register/request",this.handleRegisterToken.bind(this)),this.mqttClient.subscribe("notifications/preferences/get/request",this.handleGetPreferences.bind(this)),this.mqttClient.subscribe("notifications/preferences/update/request",this.handleUpdatePreferences.bind(this)),this.mqttClient.subscribe("claude/+/output/+",this.handleClaudeOutput.bind(this)),this.mqttClient.subscribe("claude/+/permission/request/+",this.handlePermissionRequest.bind(this)),Q_.info("[Notification] MQTT handlers registered")}async handleRegisterToken(_,T){try{let A=JSON.parse(T.toString());Q_.info("[Notification] Register token request:",{deviceId:A.deviceId,platform:A.platform,hasExpoPushToken:!!A.expoPushToken,hasFcmToken:!!A.fcmToken}),await w1.registerToken(A.deviceId,A.fcmToken,A.expoPushToken,A.platform,A.deviceInfo);let E={requestId:A.requestId,success:!0};await this.mqttClient?.publish("notifications/register/response",JSON.stringify(E)),Q_.info("[Notification] Token registered successfully:",{deviceId:A.deviceId})}catch(A){Q_.error("[Notification] Error registering token:",A);try{let E=T.toString(),J={requestId:JSON.parse(E).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/register/response",JSON.stringify(J))}catch{}}}async handleGetPreferences(_,T){try{let A=JSON.parse(T.toString());Q_.debug("[Notification] Get preferences request:",{deviceId:A.deviceId});let E=await w1.getPreferences(A.deviceId),L={requestId:A.requestId,success:!0,preferences:E};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(L)),Q_.debug("[Notification] Sent preferences:",{deviceId:A.deviceId})}catch(A){Q_.error("[Notification] Error getting preferences:",A);try{let L={requestId:JSON.parse(T.toString()).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(L))}catch{}}}async handleUpdatePreferences(_,T){try{let A=JSON.parse(T.toString());Q_.info("[Notification] Update preferences request:",{deviceId:A.deviceId,preferences:A.preferences});let E=await w1.updatePreferences(A.deviceId,A.preferences),L={requestId:A.requestId,success:!0,preferences:E};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(L)),Q_.info("[Notification] Preferences updated:",{deviceId:A.deviceId})}catch(A){Q_.error("[Notification] Error updating preferences:",A);try{let L={requestId:JSON.parse(T.toString()).requestId,success:!1,error:A instanceof Error?A.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(L))}catch{}}}async handleClaudeOutput(_,T){try{let A=_.split("/"),E=A[1],L=A[3],J=JSON.parse(T.toString());if(J.type!=="assistant")return;let X=this.getSessionInfo(L);if(!X){Q_.debug("[Notification] Session not found for notification:",{sessionId:L});return}let H=this.buildNotificationTitle(X),Z=this.extractMessageBody(J);if(!Z)return;let Y={type:"message",projectId:X.projectPath,sessionId:L};await this.sendToDevicesWithPreference("allMessages",{title:H,body:Z,data:Y,priority:"high",channelId:"messages"}),Q_.debug("[Notification] Sent message notification:",{sessionId:L,title:H})}catch(A){Q_.error("[Notification] Error handling Claude output:",A)}}async handlePermissionRequest(_,T){try{let A=_.split("/"),E=A[1],L=A[4],J=JSON.parse(T.toString()),X=this.getSessionInfo(L);if(!X){Q_.debug("[Notification] Session not found for permission notification:",{sessionId:L});return}let H=this.buildNotificationTitle(X),Z=this.buildPermissionBody(J),Y={type:"permission",projectId:X.projectPath,sessionId:L,requestId:J.request_id,action:J.action};await this.sendToDevicesWithPreference("needsAttention",{title:H,body:Z,data:Y,priority:"high",channelId:"default"}),Q_.info("[Notification] Sent permission notification:",{sessionId:L,action:J.action})}catch(A){Q_.error("[Notification] Error handling permission request:",A)}}getSessionInfo(_){if(!this.claudeAgentService)return null;let A=this.claudeAgentService.getActiveSessions().find((E)=>E.sessionId===_);if(!A)return null;return{sessionId:A.sessionId,projectPath:A.projectPath,worktreeBranch:A.worktreeBranch}}buildNotificationTitle(_){let T=UN.basename(_.projectPath);if(_.worktreeBranch){let A=_.worktreeBranch.replace("session/","");return`${T} (${A})`}return T}extractMessageBody(_){let T="",A=_.message;if(A?.content&&Array.isArray(A.content))T=A.content.filter((L)=>L.type==="text").map((L)=>L.text).filter(Boolean).join(`
|
|
2637
|
+
`)){if(!F.trim())continue;let R=F.split("\t");if(R.length<2)continue;let q=R[0]?.[0]||"M",f=R.length>2?R[2]:R[1],h=V.find((b)=>b.path===f||b.oldPath===R[1]);if(h)switch(q){case"A":h.status="added";break;case"D":h.status="deleted";break;case"R":h.status="renamed";break;case"C":h.status="copied";break;default:h.status="modified"}}return{hash:J,shortHash:X,message:H,body:Y,author:K,authorEmail:$,timestamp:G,files:V,totalInsertions:N,totalDeletions:z}}catch(A){throw U_.error("[GitExecutor] Failed to get commit details",{error:A,path:_,commitHash:T}),Error(`Failed to get commit details: ${A instanceof Error?A.message:"Unknown error"}`)}}async function tW(_){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 eW(_,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 _N(_,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 TN(_){try{if(!await F4(_))return{exists:!1,error:"Not on a branch"};let A=await u`gh pr view --json number,url,title,state,isDraft`.cwd(_).quiet();if(A.exitCode!==0){let L=A.stderr.toString();if(L.includes("no pull requests found")||L.includes("Could not resolve"))return{exists:!1};return{exists:!1,error:L}}let E=JSON.parse(A.stdout.toString());return{exists:!0,prNumber:E.number,prUrl:E.url,title:E.title,state:E.state.toLowerCase(),draft:E.isDraft}}catch(T){U_.error("[GitExecutor] Failed to check for existing PR",{error:T,path:_});let A=T instanceof Error?T.message:String(T);if(A.includes("no pull requests found")||A.includes("Could not resolve"))return{exists:!1};return{exists:!1,error:`Failed to check for existing PR: ${A}`}}}async function H9(_){try{let A=(await u`gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name'`.cwd(_).text()).trim();if(A)return A;let E=await u`git -C ${_} branch -r`.text();if(E.includes("origin/main"))return"main";if(E.includes("origin/master"))return"master";return null}catch(T){return U_.error("[GitExecutor] Failed to get default branch",{error:T,path:_}),null}}async function AN(_){try{await u`git -C ${_} fetch --prune`.quiet();let A=(await u`git -C ${_} branch -r`.text()).split(`
|
|
2639
|
+
`).map((L)=>L.trim()).filter((L)=>L&&!L.includes("HEAD")&&!L.includes("->")).map((L)=>L.replace(/^origin\//,"")),E=await H9(_);return{branches:A,defaultBranch:E}}catch(T){return U_.error("[GitExecutor] Failed to get remote branches",{error:T,path:_}),{branches:[],defaultBranch:null}}}import*as r_ from"path";import*as D_ from"fs";import*as Y9 from"os";var G_=v();function C4(_){return r_.normalize(_).toLowerCase()}var nh="worktrees",ih="sessions";function Z9(){return r_.join(Y9.homedir(),".ccc",ih)}function ah(){let _=new Date,T=_.getFullYear(),A=String(_.getMonth()+1).padStart(2,"0"),E=String(_.getDate()).padStart(2,"0"),L=String(_.getHours()).padStart(2,"0"),J=String(_.getMinutes()).padStart(2,"0");return`${T}${A}${E}-${L}${J}`}class O4{worktreeCache=new Map;saveSessionMapping(_,T){try{let A=Z9();if(!D_.existsSync(A))D_.mkdirSync(A,{recursive:!0});let E=r_.join(A,_);D_.writeFileSync(E,T,"utf-8"),G_.debug("[WorktreeManager] Saved session mapping",{sessionId:_,worktreePath:T})}catch(A){G_.error("[WorktreeManager] Failed to save session mapping",{error:A,sessionId:_,worktreePath:T})}}loadSessionMapping(_){try{let T=r_.join(Z9(),_);if(D_.existsSync(T)){let A=D_.readFileSync(T,"utf-8").trim();if(D_.existsSync(A))return A;else D_.unlinkSync(T),G_.debug("[WorktreeManager] Removed stale session mapping",{sessionId:_,worktreePath:A})}}catch(T){G_.error("[WorktreeManager] Failed to load session mapping",{error:T,sessionId:_})}return null}deleteSessionMapping(_){try{let T=r_.join(Z9(),_);if(D_.existsSync(T))D_.unlinkSync(T),G_.debug("[WorktreeManager] Deleted session mapping",{sessionId:_})}catch(T){G_.error("[WorktreeManager] Failed to delete session mapping",{error:T,sessionId:_})}}getWorktreesBasePath(_){let T=r_.basename(_),A=r_.join(Y9.homedir(),".ccc");return r_.join(A,`${T}-${nh}`)}getWorktreePath(_,T){let A=this.getWorktreesBasePath(_),E=T.replace(/[^a-zA-Z0-9_-]/g,"_");return r_.join(A,E)}generateBranchName(_){return`session/${_.replace(/[^a-zA-Z0-9_-]/g,"_")}`}async getOrCreateForSession(_,T){G_.debug("[WorktreeManager] getOrCreateForSession",{sessionId:_,repoPath:T});let A=this.worktreeCache.get(_);if(A)if(D_.existsSync(A.path))return G_.debug("[WorktreeManager] Returning cached worktree",{sessionId:_,path:A.path}),{worktree:A,isNew:!1};else this.worktreeCache.delete(_);let E=this.loadSessionMapping(_);if(E&&D_.existsSync(E)){let V=await O0(T);if(V){let N=await w8(V),z=C4(E),Q=N.find((F)=>C4(F.path)===z);if(Q)return Q.sessionId=_,this.worktreeCache.set(_,Q),G_.debug("[WorktreeManager] Found worktree from session mapping",{sessionId:_,path:E}),{worktree:Q,isNew:!1};else G_.warn("[WorktreeManager] Worktree path exists on disk but not found in git worktree list",{mappedWorktreePath:E})}}if(!await z4(T))throw Error(`Not a git repository: ${T}`);let J=await O0(T);if(!J)throw Error(`Could not determine repository root for: ${T}`);let X=await D5(J,_);if(X)return X.sessionId=_,this.worktreeCache.set(_,X),this.saveSessionMapping(_,X.path),G_.debug("[WorktreeManager] Found existing worktree (legacy)",{sessionId:_,path:X.path}),{worktree:X,isNew:!1};let H=this.getWorktreePath(J,_);if(D_.existsSync(H)){G_.warn("[WorktreeManager] Worktree path exists but not in git worktree list",{expectedPath:H});let V=await w8(J),N=C4(H),z=V.find((Q)=>C4(Q.path)===N);if(z)return z.sessionId=_,this.worktreeCache.set(_,z),{worktree:z,isNew:!1}}let Z=ah(),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 uW(J,K,$);return U.sessionId=_,this.saveSessionMapping(_,K),this.worktreeCache.set(_,U),G_.info("[WorktreeManager] Created new worktree",{sessionId:_,worktreeName:r_.basename(K),path:U.path,branch:U.branch}),{worktree:U,isNew:!0}}async getWorktreeForSession(_,T){G_.debug("[WorktreeManager] getWorktreeForSession",{sessionId:_,repoPath:T});let A=this.worktreeCache.get(_);if(A)if(D_.existsSync(A.path))return A;else this.worktreeCache.delete(_);let E=await O0(T);if(!E)return null;let L=await D5(E,_);if(L)L.sessionId=_,this.worktreeCache.set(_,L);return L}async listWorktreesForRepo(_){G_.debug("[WorktreeManager] listWorktreesForRepo",{repoPath:_});let T=await O0(_);if(!T)throw Error(`Could not determine repository root for: ${_}`);let A=await w8(T);for(let E of A)if(!E.isMain)if(E.branch?.startsWith("session/"))E.sessionId=E.branch.substring(8);else{let L=this.getWorktreesBasePath(T);if(C4(E.path).startsWith(C4(L))){let J=r_.basename(E.path);E.sessionId=J}}for(let E of A)if(E.sessionId)this.worktreeCache.set(E.sessionId,E);return A}getActiveWorktreeCount(){return this.worktreeCache.size}clearCache(){this.worktreeCache.clear()}removeFromCache(_){this.worktreeCache.delete(_)}updateSessionId(_,T,A){try{this.deleteSessionMapping(T),this.saveSessionMapping(A,_);let E=this.worktreeCache.get(T);if(E)this.worktreeCache.delete(T),E.sessionId=A,this.worktreeCache.set(A,E);G_.info("[WorktreeManager] Updated session ID mapping",{worktreePath:_,oldSessionId:T,newSessionId:A})}catch(E){G_.error("[WorktreeManager] Failed to update session ID",{error:E,worktreePath:_,oldSessionId:T,newSessionId:A})}}async renameWorktreeForSession(_,T,A){G_.info("[WorktreeManager] Renaming worktree for session",{oldSessionId:_,newSessionId:T,repoPath:A});try{let E=await O0(A);if(!E)return G_.error("[WorktreeManager] Could not determine repo root for rename"),null;let L=this.worktreeCache.get(_);if(!L){if(G_.warn("[WorktreeManager] No cached worktree found for old session ID",{oldSessionId:_}),!await D5(E,_))return G_.error("[WorktreeManager] Could not find worktree for old session ID"),null}let J=this.getWorktreePath(E,_),X=this.getWorktreePath(E,T),H=this.generateBranchName(_),Z=this.generateBranchName(T);if(!D_.existsSync(J))return G_.warn("[WorktreeManager] Old worktree path does not exist",{oldPath:J}),null;if(D_.existsSync(X)){G_.warn("[WorktreeManager] New worktree path already exists",{newPath:X});let K={path:X,branch:Z,head:L?.head||"",sessionId:T,isMain:!1};return this.worktreeCache.delete(_),this.worktreeCache.set(T,K),K}await iW(E,J,X),G_.debug("[WorktreeManager] Moved worktree",{from:J,to:X}),await nW(X,H,Z),G_.debug("[WorktreeManager] Renamed branch",{from:H,to:Z}),this.worktreeCache.delete(_);let Y={path:X,branch:Z,head:L?.head||"",sessionId:T,isMain:!1,createdAt:L?.createdAt};return this.worktreeCache.set(T,Y),G_.info("[WorktreeManager] Successfully renamed worktree",{oldSessionId:_,newSessionId:T,oldPath:J,newPath:X,oldBranch:H,newBranch:Z}),Y}catch(E){return G_.error("[WorktreeManager] Failed to rename worktree",{error:E,oldSessionId:_,newSessionId:T}),null}}}import*as K9 from"path";import*as JN from"os";var w1=v(),B5=K9.join(JN.homedir(),".ccc"),LN=K9.join(B5,"pending-permissions.json");class XN{cache=null;async ensureDirectory(){try{let _=await import("fs");if(!_.existsSync(B5))_.mkdirSync(B5,{recursive:!0}),w1.debug("[PendingPermissions] Created .ccc directory:",B5)}catch(_){throw w1.error("[PendingPermissions] Error ensuring directory:",_),_}}async load(){if(this.cache)return this.cache;try{let _=Bun.file(LN);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(LN,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 XN;var m=v();class q5{name="Claude Agent Service";running=!1;startedAt;mqttClient=null;sessionsService=null;processManager;worktreeManager;config;totalSessionsCreated=0;totalMessagesProcessed=0;pendingPermissions=new Map;cleanupInterval;constructor(_){this.config=_,this.worktreeManager=new O4,this.processManager=new E9(_,{onSessionInitialized:this.handleSessionInitialized.bind(this),onTitleGenerated:this.handleTitleGenerated.bind(this),onAssistantMessage:this.handleAssistantMessage.bind(this),onPermissionRequest:this.handlePermissionRequest.bind(this),onSessionError:this.handleSessionError.bind(this),onSessionStopped:this.handleSessionStopped.bind(this),onProcessingStarted:this.handleProcessingStarted.bind(this),onProcessingComplete:this.handleProcessingComplete.bind(this),onContextUpdate:this.handleContextUpdate.bind(this)})}async determineWorkingDirectory(_,T,A){try{if(!await z4(T))return m.debug("[ClaudeAgent] Not a git repo, using project path",{projectId:_,directoryPath:T}),{path:T,isWorktree:!1};let L=await O0(T);if(!L)return m.warn("[ClaudeAgent] Could not determine repo root, using project path",{directoryPath:T}),{path:T,isWorktree:!1};m.info("[ClaudeAgent] Git repo detected, creating worktree",{projectId:_,sessionId:A,repoRoot:L});let{worktree:J,isNew:X}=await this.worktreeManager.getOrCreateForSession(A,L);return m.info("[ClaudeAgent] Worktree ready",{sessionId:A,worktreePath:J.path,branch:J.branch,isNew:X}),{path:J.path,isWorktree:!0,branch:J.branch}}catch(E){return m.error("[ClaudeAgent] Worktree creation failed, falling back to project path",{projectId:_,sessionId:A,error:E instanceof Error?E.message:"Unknown error"}),{path:T,isWorktree:!1}}}setMQTTClient(_){this.mqttClient=_}setSessionsService(_){this.sessionsService=_}async start(){try{if(this.running=!0,this.startedAt=new Date,m.info("[ClaudeAgent] Service started"),this.mqttClient)this.registerMQTTHandlers();else m.warn("[ClaudeAgent] MQTT client not set - handlers will not be registered");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions()},300000),m.info("[ClaudeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions,sessionTimeoutMs:this.config.sessionTimeoutMs})}catch(_){throw m.error("[ClaudeAgent] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval);this.processManager.stopAll(),m.info("[ClaudeAgent] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("claude/+/session/start",(_,T)=>{let A=this.extractUserIdFromTopic(_);this.handleSessionStart(A,_,T)}),this.mqttClient.subscribe("claude/+/input/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromInputTopic(_);this.handleUserInput(A,E,_,T)}),this.mqttClient.subscribe("claude/+/permission/response/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromPermissionTopic(_);this.handlePermissionResponse(A,E,_,T)}),this.mqttClient.subscribe("claude/+/session/stop/+",(_,T)=>{let{userId:A,sessionId:E}=this.extractIdsFromStopTopic(_);this.handleSessionStop(A,E)}),this.mqttClient.subscribe("permissions/pending/request",(_,T)=>{this.handlePendingPermissionsRequest(_,T)}),m.info("[ClaudeAgent] MQTT handlers registered")}async handleSessionStart(_,T,A){try{let E=JSON.parse(A.toString());m.info("[ClaudeAgent] Session start request:",{userId:_,tempId:E.tempId,projectId:E.projectId,directoryPath:E.directoryPath,permissionMode:E.permissionMode,selectedModel:E.selectedModel,hasAttachments:!!E.attachments,attachmentCount:E.attachments?.length||0});let{path:L,isWorktree:J,branch:X}=await this.determineWorkingDirectory(E.projectId,E.directoryPath,E.tempId),H=await this.processManager.spawnSession(E.tempId,_,E.projectId,L,E.initialMessage||"",void 0,E.permissionMode,E.selectedModel,E.attachments);if(J)H.directoryPath=E.directoryPath,H.worktreePath=L,H.worktreeBranch=X;this.totalSessionsCreated++,m.info("[ClaudeAgent] Session spawned successfully:",{userId:_,tempId:E.tempId,projectId:E.projectId,workingPath:L,isWorktree:J})}catch(E){m.error("[ClaudeAgent] Error starting session:",{userId:_,error:E instanceof Error?E.message:"Unknown error"}),this.publishStatus(_,"temp_error",{type:"error",error:E instanceof Error?E.message:"Failed to start session",timestamp:Date.now()})}}async handleUserInput(_,T,A,E){try{let L=JSON.parse(E.toString());if(!L.message&&(!L.attachments||L.attachments.length===0)){m.warn("[ClaudeAgent] Received request without message or attachments:",{userId:_,sessionId:L.sessionId,hasAttachments:!!L.attachments});return}m.info("[ClaudeAgent] User input:",{userId:_,sessionId:L.sessionId,messageLength:L.message?.length||0,permissionMode:L.permissionMode,selectedModel:L.selectedModel,hasAttachments:!!L.attachments,attachmentCount:L.attachments?.length||0,allSessions:this.processManager.getAllSessions().map((Z)=>({tempId:Z.tempId,sessionId:Z.sessionId,status:Z.status}))});let J=this.processManager.getSession(L.sessionId);if(!J){m.warn("[ClaudeAgent] Session not found, creating new session:",{userId:_,requestedSessionId:L.sessionId,projectId:L.projectId,availableSessions:this.processManager.getAllSessions().map((Y)=>Y.sessionId||Y.tempId)});let Z=L.sessionId&&!L.sessionId.startsWith("temp_")&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(L.sessionId);try{let{path:Y,isWorktree:K,branch:$}=await this.determineWorkingDirectory(L.projectId,L.directoryPath,L.sessionId);if(J=await this.processManager.spawnSession(L.sessionId,_,L.projectId,Y,L.message||"",Z?L.sessionId:void 0,L.permissionMode,L.selectedModel,L.attachments),K)J.directoryPath=L.directoryPath,J.worktreePath=Y,J.worktreeBranch=$;this.totalSessionsCreated++,m.info(`[ClaudeAgent] Session ${Z?"resumed":"created"} successfully:`,{userId:_,sessionId:L.sessionId,isResume:Z,workingPath:Y,isWorktree:K}),this.totalMessagesProcessed++;return}catch(Y){m.error("[ClaudeAgent] Failed to create session:",{userId:_,sessionId:L.sessionId,error:Y instanceof Error?Y.message:"Unknown error"}),this.publishStatus(_,L.sessionId,{type:"error",error:"Failed to create session",timestamp:Date.now()});return}}let X=J.permissionMode||"default",H=L.permissionMode||"default";if(H!==X&&J.sessionId)if(m.info("[ClaudeAgent] Permission mode changed, respawning session:",{userId:_,sessionId:J.sessionId,currentMode:X,requestedMode:H}),await this.processManager.respawnWithPermissionMode(J.sessionId,H,L.message||"proceed with implementation")){this.publishStatus(_,J.sessionId,{type:"session_restarted",permissionMode:H,timestamp:Date.now()}),this.totalMessagesProcessed++;return}else m.error("[ClaudeAgent] Failed to respawn session with new permission mode");this.processManager.sendUserMessage(J,L.message||"",L.attachments),this.totalMessagesProcessed++}catch(L){m.error("[ClaudeAgent] Error handling user input:",{userId:_,sessionId:T,error:L instanceof Error?L.message:"Unknown error"})}}async handlePermissionResponse(_,T,A,E){try{let L=JSON.parse(E.toString());m.info("[ClaudeAgent] Permission response:",{userId:_,sessionId:T,requestId:L.requestId,approved:L.approved,hasAnswers:!!L.answers,addToAllowedTools:L.addToAllowedTools,toolPattern:L.toolPattern,permissionMode:L.permissionMode,hardDeny:L.hardDeny,hasDenyMessage:!!L.denyMessage});let J=this.pendingPermissions.get(L.requestId);if(!J)m.warn(`[ClaudeAgent] No pending permission found for request_id: ${L.requestId}`);if(L.approved&&L.addToAllowedTools){let H=this.processManager.getSession(T);if(H){let Z=L.toolPattern||(J?this.generateToolPattern(J.action,J.params):null);if(Z)await this.addToAllowedTools(H.directoryPath,Z),m.info("[ClaudeAgent] Added tool pattern to settings.local.json:",{toolPattern:Z,projectPath:H.directoryPath})}}let X=this.processManager.getSession(T);if(L.permissionMode&&X?.sessionId){if(m.info("[ClaudeAgent] Permission mode change requested, will respawn session:",{sessionId:X.sessionId,newPermissionMode:L.permissionMode}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:J?.params,message:"Permission mode is changing. Stopping current execution for session respawn."}),await new Promise((Z)=>setTimeout(Z,200)),await this.processManager.respawnWithPermissionMode(X.sessionId,L.permissionMode,"proceed with implementation"))this.publishStatus(X.userId,X.sessionId,{type:"session_restarted",permissionMode:L.permissionMode,timestamp:Date.now()});else this.publishStatus(X.userId,X.sessionId,{type:"error",error:"Failed to respawn session with new permission mode",timestamp:Date.now()});if(J)this.pendingPermissions.delete(L.requestId);LT.removePermission(L.requestId).catch((Z)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",Z)});return}if(L.approved&&L.answers&&Object.keys(L.answers).length>0){let H={...J?.params,answers:L.answers};m.info("[ClaudeAgent] Sending AskUserQuestion response:",{requestId:L.requestId,answerCount:Object.keys(L.answers).length}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:H})}else if(L.approved)this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"allow",updatedInput:J?J.params:void 0});else{let H=L.denyMessage||"Permission denied by user",Z=L.hardDeny!==!1;if(m.info("[ClaudeAgent] Sending deny response:",{requestId:L.requestId,hardDeny:Z,hasDenyMessage:!!L.denyMessage}),this.processManager.sendPermissionResponse(T,{request_id:L.requestId,behavior:"deny",message:H,hardDeny:Z}),Z)m.info("[ClaudeAgent] Hard deny - stopping session:",{sessionId:T}),setTimeout(()=>{this.processManager.stopSession(T),this.publishStatus(_,T,{type:"session_stopped",reason:"permission_denied",message:H,timestamp:Date.now()})},100)}if(J)this.pendingPermissions.delete(L.requestId);LT.removePermission(L.requestId).catch((H)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",H)})}catch(L){m.error("[ClaudeAgent] Error handling permission response:",{userId:_,sessionId:T,error:L instanceof Error?L.message:"Unknown error"})}}handleSessionStop(_,T){m.info("[ClaudeAgent] Session stop request:",{userId:_,sessionId:T}),this.processManager.stopSession(T)}async handlePendingPermissionsRequest(_,T){try{let A=JSON.parse(T.toString()),{clientId:E,sessionId:L,projectPath:J}=A;if(!E){m.warn("[ClaudeAgent] Pending permissions request missing clientId");return}m.info("[ClaudeAgent] Pending permissions request:",{clientId:E,sessionId:L,projectPath:J});let X;if(L)X=await LT.getPermissionsForSession(L);else if(J)X=await LT.getPermissionsForProject(J);else X=await LT.getAllPermissions();let H=this.processManager.getAllSessions(),Z=new Set(H.filter((G)=>G.status==="waiting_permission"&&G.sessionId).map((G)=>G.sessionId)),Y=X.filter((G)=>Z.has(G.sessionId)),K=`permissions/pending/${E}/response`,$={permissions:Y,timestamp:Date.now()};await this.mqttClient?.publish(K,JSON.stringify($)),m.info("[ClaudeAgent] Sent pending permissions response:",{clientId:E,count:Y.length,totalStored:X.length})}catch(A){m.error("[ClaudeAgent] Error handling pending permissions request:",A)}}handleSessionInitialized(_,T){if(m.info("[ClaudeAgent] Session initialized callback:",{tempId:_.tempId,sessionId:_.sessionId,model:_.model}),_.worktreePath&&_.tempId&&_.sessionId)this.worktreeManager.updateSessionId(_.worktreePath,_.tempId,_.sessionId);if(this.publishStatus(_.userId,_.sessionId,{type:"session_started",sessionId:_.sessionId,tempId:_.tempId,model:_.model,worktreePath:_.worktreePath,worktreeBranch:_.worktreeBranch,timestamp:Date.now()}),this.sessionsService){let A=_.worktreePath||_.directoryPath;this.sessionsService.notifySessionCreated(_.directoryPath,A).catch((E)=>{m.warn("[ClaudeAgent] Failed to notify sessions service about new session",{error:E})})}}handleTitleGenerated(_,T){m.info("[ClaudeAgent] Title generated callback:",{sessionId:_.sessionId,title:T}),this.publishStatus(_.userId,_.sessionId,{type:"title_generated",title:T,timestamp:Date.now()})}handleAssistantMessage(_,T){if(this.totalMessagesProcessed++,_.sessionId)this.publishOutput(_.userId,_.sessionId,T)}handlePermissionRequest(_,T){if(m.info("[ClaudeAgent] Permission request callback:",{sessionId:_.sessionId,requestId:T.request_id,action:T.action}),_.sessionId)this.publishPermissionRequest(_,T)}handleSessionError(_,T){m.error("[ClaudeAgent] Session error callback:",{sessionId:_.sessionId,tempId:_.tempId,error:T}),this.publishStatus(_.userId,_.sessionId||_.tempId,{type:"error",error:T,timestamp:Date.now()})}handleSessionStopped(_,T){if(m.info("[ClaudeAgent] Session stopped callback:",{sessionId:_.sessionId,tempId:_.tempId,reason:T}),this.publishStatus(_.userId,_.sessionId||_.tempId,{type:"session_stopped",reason:T,timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifySessionStopped()}handleProcessingStarted(_){if(m.info("[ClaudeAgent] Processing started:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_processing",sessionId:_.sessionId,timestamp:Date.now()})}handleProcessingComplete(_){if(m.info("[ClaudeAgent] Processing complete:",{sessionId:_.sessionId,tempId:_.tempId}),_.sessionId)this.publishStatus(_.userId,_.sessionId,{type:"session_idle",sessionId:_.sessionId,timestamp:Date.now()})}handleContextUpdate(_,T){if(m.info(`[ClaudeAgent] Context update for session ${_.sessionId}:`,{total:T.total,percentage:T.percentage,inputTokens:T.inputTokens,cacheCreation:T.cacheCreation,cacheRead:T.cacheRead,breakdown:{systemPrompt:T.systemPrompt,tools:T.tools,messages:T.messages,remaining:T.remaining}}),_.sessionId)this.publishContextUpdate(_.userId,_.sessionId,T);else m.warn("[ClaudeAgent] Cannot publish context update - no sessionId yet")}publishStatus(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish status - MQTT client not available");return}let E=`claude/${_}/status/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish status to ${E}`,{error:J.message})})}publishOutput(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish output - MQTT client not available");return}let E=`claude/${_}/output/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish output to ${E}`,{error:J.message})})}publishContextUpdate(_,T,A){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish context update - MQTT client not available");return}let E=`claude/${_}/context/${T}`,L=JSON.stringify(A);this.mqttClient.publish(E,L).catch((J)=>{m.error(`[ClaudeAgent] Failed to publish context to ${E}`,{error:J.message})})}publishPermissionRequest(_,T){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish permission request - MQTT client not available");return}let{userId:A,sessionId:E}=_;m.info("[ClaudeAgent] Raw permission request structure:",{fullRequest:JSON.stringify(T)});let L=T,J=L.request||{},X=J.tool_name||L.tool_name||L.action||"unknown_tool",H=J.input||L.tool_input||L.params||{},Z=J.permission_suggestions||[],Y=J.decision_reason||"",K=J.blocked_path||"";this.pendingPermissions.set(L.request_id,{requestId:L.request_id,action:X,params:H}),LT.addPermission({requestId:L.request_id,sessionId:E,projectPath:_.directoryPath,action:X,params:H,permissionSuggestions:Z.length>0?Z:void 0,decisionReason:Y||void 0,blockedPath:K||void 0,createdAt:new Date().toISOString()}).catch((V)=>{m.error("[ClaudeAgent] Failed to persist pending permission:",V)});let $={request_id:L.request_id,action:X,params:H,permission_suggestions:Z,decision_reason:Y,blocked_path:K},G=`claude/${A}/permission/request/${E}`,U=JSON.stringify($);m.info("[ClaudeAgent] Publishing transformed permission request:",{topic:G,request_id:$.request_id,action:$.action}),this.mqttClient.publish(G,U).catch((V)=>{m.error(`[ClaudeAgent] Failed to publish permission request to ${G}`,{error:V.message})})}extractUserIdFromTopic(_){return _.split("/")[1]||""}extractIdsFromInputTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[3]||""}}extractIdsFromPermissionTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[4]||""}}extractIdsFromStopTopic(_){let T=_.split("/");return{userId:T[1]||"",sessionId:T[4]||""}}generateToolPattern(_,T){switch(_){case"Bash":case"bash":case"execute_command":return`Bash(${T.command})`;case"Read":case"read":case"read_file":return`Read(${T.file_path})`;case"Write":case"write":case"write_file":return`Write(${T.file_path})`;case"Edit":case"edit":return`Edit(${T.file_path})`;default:return _}}async addToAllowedTools(_,T){try{let A=HN.join(_,".claude"),E=HN.join(A,"settings.local.json"),L=Bun.file(A);if(!await Bun.$`test -d ${A}`.quiet().nothrow())await Bun.$`mkdir -p ${A}`.quiet();let J={},X=Bun.file(E);if(await X.exists())try{let H=await X.text();J=JSON.parse(H)}catch{J={}}if(J.permissions=J.permissions||{},J.permissions.allow=J.permissions.allow||[],!J.permissions.allow.includes(T))J.permissions.allow.push(T);await Bun.write(E,JSON.stringify(J,null,2)),m.info("[ClaudeAgent] Updated settings.local.json with allowed tool:",{settingsPath:E,toolPattern:T,totalAllowed:J.permissions.allow.length})}catch(A){m.error("[ClaudeAgent] Failed to update settings.local.json:",{projectPath:_,toolPattern:T,error:A instanceof Error?A.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.processManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessions(){return this.processManager.getAllSessions().filter((_)=>_.sessionId).map((_)=>({sessionId:_.sessionId,projectPath:_.directoryPath,status:_.status,worktreePath:_.worktreePath,worktreeBranch:_.worktreeBranch}))}}import*as Y_ from"fs/promises";import*as v_ from"path";var u0=v();class I5{validatePath(_,T){try{let A=v_.resolve(_),E=v_.resolve(A,T);if(!(E===A||E.startsWith(A+v_.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};return{valid:!0,fullPath:E}}catch(A){return{valid:!1,fullPath:"",error:`Path validation error: ${A instanceof Error?A.message:"Unknown error"}`}}}async listDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{entries:[],error:A.error};try{if(!(await Y_.stat(A.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let L=await Y_.readdir(A.fullPath,{withFileTypes:!0}),J=await Promise.all(L.map(async(X)=>{let H=v_.join(A.fullPath,X.name);try{let Z=await Y_.stat(H);return{name:X.name,type:X.isDirectory()?"directory":"file",size:X.isFile()?Z.size:void 0,modified:Z.mtime.toISOString()}}catch{return{name:X.name,type:X.isDirectory()?"directory":"file"}}}));return J.sort((X,H)=>{if(X.type!==H.type)return X.type==="directory"?-1:1;return X.name.localeCompare(H.name,void 0,{sensitivity:"base"})}),{entries:J}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] listDirectory error",{error:L,path:A.fullPath}),{entries:[],error:`Failed to list directory: ${L}`}}}async readFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{content:"",size:0,error:A.error};try{let E=await Y_.stat(A.fullPath);if(!E.isFile())return{content:"",size:0,error:"Path is not a file"};return{content:await Y_.readFile(A.fullPath,"utf-8"),size:E.size}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] readFile error",{error:L,path:A.fullPath}),{content:"",size:0,error:`Failed to read file: ${L}`}}}async writeFile(_,T,A){let E=this.validatePath(_,T);if(!E.valid)return{success:!1,error:E.error};try{let L=v_.dirname(E.fullPath);return await Y_.mkdir(L,{recursive:!0}),await Y_.writeFile(E.fullPath,A,"utf-8"),{success:!0}}catch(L){let J=L instanceof Error?L.message:"Unknown error";return u0.error("[FileManager] writeFile error",{error:J,path:E.fullPath}),{success:!1,error:`Failed to write file: ${J}`}}}async createFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{try{return await Y_.access(A.fullPath),{success:!1,error:"File already exists"}}catch{}let E=v_.basename(T);if(!this.isValidFilename(E))return{success:!1,error:"Invalid filename"};let L=v_.dirname(A.fullPath);return await Y_.mkdir(L,{recursive:!0}),await Y_.writeFile(A.fullPath,"","utf-8"),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] createFile error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to create file: ${L}`}}}async createDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{let E=v_.basename(T);if(!this.isValidFilename(E))return{success:!1,error:"Invalid directory name"};try{if((await Y_.stat(A.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await Y_.mkdir(A.fullPath,{recursive:!0}),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] createDirectory error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to create directory: ${L}`}}}async deleteFile(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};try{if(!(await Y_.stat(A.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await Y_.unlink(A.fullPath),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] deleteFile error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to delete file: ${L}`}}}async deleteDirectory(_,T){let A=this.validatePath(_,T);if(!A.valid)return{success:!1,error:A.error};if(A.fullPath===v_.resolve(_))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await Y_.stat(A.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await Y_.rm(A.fullPath,{recursive:!0,force:!0}),{success:!0}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] deleteDirectory error",{error:L,path:A.fullPath}),{success:!1,error:`Failed to delete directory: ${L}`}}}async pathExists(_,T){let A=this.validatePath(_,T);if(!A.valid)return!1;try{return await Y_.access(A.fullPath),!0}catch{return!1}}async getStats(_,T){let A=this.validatePath(_,T);if(!A.valid)return null;try{let E=await Y_.stat(A.fullPath);return{isFile:E.isFile(),isDirectory:E.isDirectory(),size:E.size,modified:E.mtime.toISOString()}}catch{return null}}async readFileBinary(_,T){let A=this.validatePath(_,T);if(!A.valid)return{content:Buffer.alloc(0),size:0,mimeType:"",error:A.error};try{let E=await Y_.stat(A.fullPath);if(!E.isFile())return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Path is not a file"};let L=52428800;if(E.size>L)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"File exceeds maximum size of 50MB"};let J=await Y_.readFile(A.fullPath),X=this.getMimeType(v_.basename(T));return{content:J,size:E.size,mimeType:X}}catch(E){let L=E instanceof Error?E.message:"Unknown error";return u0.error("[FileManager] readFileBinary error",{error:L,path:A.fullPath}),{content:Buffer.alloc(0),size:0,mimeType:"",error:`Failed to read file: ${L}`}}}async writeFileBinary(_,T,A){let E=this.validatePath(_,T);if(!E.valid)return{success:!1,error:E.error};try{let L=v_.basename(T);if(!this.isValidFilename(L))return{success:!1,error:"Invalid filename"};let J=v_.dirname(E.fullPath);return await Y_.mkdir(J,{recursive:!0}),await Y_.writeFile(E.fullPath,A),{success:!0}}catch(L){let J=L instanceof Error?L.message:"Unknown error";return u0.error("[FileManager] writeFileBinary error",{error:J,path:E.fullPath}),{success:!1,error:`Failed to write file: ${J}`}}}getMimeType(_){let T=v_.extname(_).toLowerCase();return{".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".tiff":"image/tiff",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".txt":"text/plain",".json":"application/json",".xml":"application/xml",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".tsx":"application/typescript",".jsx":"application/javascript",".md":"text/markdown",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".7z":"application/x-7z-compressed",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".m4a":"audio/mp4",".flac":"audio/flac",".aac":"audio/aac",".mp4":"video/mp4",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".webm":"video/webm",".wmv":"video/x-ms-wmv",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".apk":"application/vnd.android.package-archive",".ipa":"application/octet-stream",".exe":"application/x-msdownload",".dmg":"application/x-apple-diskimage",".deb":"application/x-deb",".rpm":"application/x-rpm"}[T]||"application/octet-stream"}isValidFilename(_){if(!_||_.length===0)return!1;if(_.includes("/")||_.includes("\\"))return!1;let T=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],A=(_.split(".")[0]||"").toUpperCase();if(T.includes(A))return!1;if(/[<>:"|?*\x00-\x1f]/.test(_))return!1;if(_==="."||_==="..")return!1;return!0}}import*as $9 from"path";var A1=v(),R4=51200,ZN=50;class P5{name="File Browser Service";running=!1;startedAt;mqttClient=null;fileManager;requestsHandled=0;messageHandlers=new Map;fileSaveOperations=new Map;binaryUploadOperations=new Map;constructor(){this.fileManager=new I5}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,A1.info("[FileBrowser] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(_){throw A1.error("[FileBrowser] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){for(let[_,T]of this.messageHandlers)this.mqttClient.unsubscribe(_,T);this.messageHandlers.clear()}this.fileSaveOperations.clear(),this.binaryUploadOperations.clear(),A1.info("[FileBrowser] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("files/list/request",(_,T)=>{this.handleDirectoryListRequest(T)}),this.registerHandler("files/content/request",(_,T)=>{this.handleFileContentRequest(T)}),this.registerHandler("files/save/request",(_,T)=>{this.handleFileSaveRequest(T)}),this.registerHandler("files/create/request",(_,T)=>{this.handleFileCreateRequest(T)}),this.registerHandler("files/delete/request",(_,T)=>{this.handleFileDeleteRequest(T)}),this.registerHandler("files/upload/request",(_,T)=>{this.handleBinaryUploadRequest(T)}),this.registerHandler("files/download/request",(_,T)=>{this.handleBinaryDownloadRequest(T)}),A1.info("[FileBrowser] MQTT handlers registered")}registerHandler(_,T){if(!this.mqttClient)return;this.messageHandlers.set(_,T),this.mqttClient.subscribe(_,T)}async handleDirectoryListRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.listDirectory(T.projectPath,T.relativePath),E={path:T.relativePath,entries:A.entries,timestamp:Date.now(),error:A.error};await this.publishResponse(`files/list/${T.clientId}/response`,E),this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling directory list request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileContentRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.readFile(T.projectPath,T.relativePath),E=`files/content/${T.clientId}/response`;if(A.error){let J={path:T.relativePath,chunk:{chunkIndex:0,totalChunks:1,content:""},totalSize:0,timestamp:Date.now(),error:A.error};await this.publishResponse(E,J);return}let L=Math.max(1,Math.ceil(A.content.length/R4));for(let J=0;J<L;J++){let X=J*R4,H=Math.min(X+R4,A.content.length),Z=A.content.slice(X,H),Y={path:T.relativePath,chunk:{chunkIndex:J,totalChunks:L,content:Z},totalSize:A.size,timestamp:Date.now()};if(await this.publishResponse(E,Y),J<L-1)await this.delay(ZN)}this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file content request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileSaveRequest(_){try{let T=JSON.parse(_.toString()),A=`${T.clientId}:${T.relativePath}`;if(T.chunk.chunkIndex===0)this.fileSaveOperations.set(A,{chunks:new Map,totalChunks:T.chunk.totalChunks,totalSize:T.totalSize});let E=this.fileSaveOperations.get(A);if(!E){await this.sendSaveResponse(T,!1,"Save operation not initialized");return}if(E.chunks.set(T.chunk.chunkIndex,T.chunk.content),await this.sendSaveResponse(T,!0),E.chunks.size===E.totalChunks){let L=[];for(let H=0;H<E.totalChunks;H++){let Z=E.chunks.get(H);if(Z!==void 0)L.push(Z)}let J=L.join(""),X=await this.fileManager.writeFile(T.projectPath,T.relativePath,J);if(this.fileSaveOperations.delete(A),!X.error)this.requestsHandled++}}catch(T){A1.error("[FileBrowser] Error handling file save request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileCreateRequest(_){try{let T=JSON.parse(_.toString()),A;if(T.type==="directory")A=await this.fileManager.createDirectory(T.projectPath,T.relativePath);else A=await this.fileManager.createFile(T.projectPath,T.relativePath);let E={path:T.relativePath,success:A.success,type:T.type,timestamp:Date.now(),error:A.error};if(await this.publishResponse(`files/create/${T.clientId}/response`,E),A.success)this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file create request",{error:T instanceof Error?T.message:"Unknown error"})}}async handleFileDeleteRequest(_){try{let T=JSON.parse(_.toString()),A=await this.fileManager.getStats(T.projectPath,T.relativePath),E;if(!A)E={success:!1,error:"Path does not exist"};else if(A.isDirectory)E=await this.fileManager.deleteDirectory(T.projectPath,T.relativePath);else E=await this.fileManager.deleteFile(T.projectPath,T.relativePath);let L={path:T.relativePath,success:E.success,timestamp:Date.now(),error:E.error};if(await this.publishResponse(`files/delete/${T.clientId}/response`,L),E.success)this.requestsHandled++}catch(T){A1.error("[FileBrowser] Error handling file delete request",{error:T instanceof Error?T.message:"Unknown error"})}}async sendSaveResponse(_,T,A){let E={path:_.relativePath,success:T,chunkIndex:_.chunk.chunkIndex,totalChunks:_.chunk.totalChunks,timestamp:Date.now(),error:A};await this.publishResponse(`files/save/${_.clientId}/response`,E)}async publishResponse(_,T){if(!this.mqttClient){A1.error("[FileBrowser] MQTT client not available");return}await this.mqttClient.publish(_,JSON.stringify(T),{qos:1})}delay(_){return new Promise((T)=>setTimeout(T,_))}async handleBinaryUploadRequest(_){try{let T=JSON.parse(_.toString()),A=`${T.clientId}:${T.relativePath}`;if(T.chunk.chunkIndex===0){if(T.totalSize>52428800){await this.sendBinaryUploadResponse(T,!1,"File exceeds 50MB limit",0);return}this.binaryUploadOperations.set(A,{chunks:new Map,totalChunks:T.chunk.totalChunks,totalSize:T.totalSize,filename:T.filename,mimeType:T.mimeType,receivedBytes:0})}let E=this.binaryUploadOperations.get(A);if(!E){await this.sendBinaryUploadResponse(T,!1,"Upload operation not initialized",0);return}let L=Buffer.from(T.chunk.data,"base64");if(E.chunks.set(T.chunk.chunkIndex,L),E.receivedBytes+=L.length,await this.sendBinaryUploadResponse(T,!0,void 0,E.receivedBytes),E.chunks.size===E.totalChunks){let J=[];for(let Z=0;Z<E.totalChunks;Z++){let Y=E.chunks.get(Z);if(Y)J.push(Y)}let X=Buffer.concat(J),H=await this.fileManager.writeFileBinary(T.projectPath,T.relativePath,X);if(this.binaryUploadOperations.delete(A),H.error)A1.error("[FileBrowser] Binary upload write failed",{error:H.error});else this.requestsHandled++,A1.info("[FileBrowser] Binary upload completed",{path:T.relativePath,size:X.length})}}catch(T){A1.error("[FileBrowser] Error handling binary upload",{error:T instanceof Error?T.message:"Unknown error"})}}async sendBinaryUploadResponse(_,T,A,E){let L={path:_.relativePath,success:T,chunkIndex:_.chunk.chunkIndex,totalChunks:_.chunk.totalChunks,bytesReceived:E||0,timestamp:Date.now(),error:A};await this.publishResponse(`files/upload/${_.clientId}/response`,L)}async handleBinaryDownloadRequest(_){try{let T=JSON.parse(_.toString()),A=`files/download/${T.clientId}/response`,E=await this.fileManager.readFileBinary(T.projectPath,T.relativePath);if(E.error){let H={path:T.relativePath,filename:$9.basename(T.relativePath),mimeType:"",chunk:{chunkIndex:0,totalChunks:1,data:""},totalSize:0,timestamp:Date.now(),error:E.error};await this.publishResponse(A,H);return}let L=E.content.toString("base64"),J=Math.max(1,Math.ceil(L.length/R4)),X=$9.basename(T.relativePath);for(let H=0;H<J;H++){let Z=H*R4,Y=Math.min(Z+R4,L.length),K=L.slice(Z,Y),$={path:T.relativePath,filename:X,mimeType:E.mimeType,chunk:{chunkIndex:H,totalChunks:J,data:K},totalSize:E.size,timestamp:Date.now()};if(await this.publishResponse(A,$),H<J-1)await this.delay(ZN)}this.requestsHandled++,A1.info("[FileBrowser] Binary download completed",{path:T.relativePath,size:E.size,chunks:J})}catch(T){A1.error("[FileBrowser] Error handling binary download",{error:T instanceof Error?T.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,pendingSaveOperations:this.fileSaveOperations.size}}}var g=v();class j5{name="Git Service";running=!1;startedAt;mqttClient=null;worktreeManager;requestsHandled=0;messageHandlers=new Map;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){this.worktreeManager=new O4}setMQTTClient(_){this.mqttClient=_}async start(){try{if(this.running=!0,this.startedAt=new Date,this.ghAuthResult=await fW(),!this.ghAuthResult.authenticated)g.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else g.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username});if(this.mqttClient)this.registerMQTTHandlers();g.info("[GitService] Service started")}catch(_){throw g.error("[GitService] Failed to start",_),this.running=!1,_}}async stop(){if(this.running=!1,this.mqttClient){for(let[_,T]of this.messageHandlers)this.mqttClient.unsubscribe(_,T),g.debug(`[GitService] Unsubscribed from ${_}`);this.messageHandlers.clear()}this.worktreeManager.clearCache(),g.info("[GitService] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("git/orgs/request",(_,T)=>{this.handleOrgsRequest(T)}),this.registerHandler("git/repos/request",(_,T)=>{this.handleReposRequest(T)}),this.registerHandler("git/repos/search/request",(_,T)=>{this.handleSearchReposRequest(T)}),this.registerHandler("git/branches/request",(_,T)=>{this.handleBranchesRequest(T)}),this.registerHandler("git/clone/request",(_,T)=>{this.handleCloneRequest(T)}),this.registerHandler("git/is-repo/request",(_,T)=>{this.handleIsRepoRequest(T)}),this.registerHandler("git/worktree/get-or-create/request",(_,T)=>{this.handleWorktreeGetOrCreateRequest(T)}),this.registerHandler("git/worktree/get/request",(_,T)=>{this.handleWorktreeGetRequest(T)}),this.registerHandler("git/worktree/list/request",(_,T)=>{this.handleWorktreeListRequest(T)}),this.registerHandler("git/status/request",(_,T)=>{this.handleStatusRequest(T)}),this.registerHandler("git/diff/request",(_,T)=>{this.handleDiffRequest(T)}),this.registerHandler("git/changes/all/request",(_,T)=>{this.handleChangesAllRequest(T)}),this.registerHandler("git/stage/request",(_,T)=>{this.handleStageRequest(T)}),this.registerHandler("git/unstage/request",(_,T)=>{this.handleUnstageRequest(T)}),this.registerHandler("git/commit/request",(_,T)=>{this.handleCommitRequest(T)}),this.registerHandler("git/unpushed/request",(_,T)=>{this.handleUnpushedCommitsRequest(T)}),this.registerHandler("git/push/request",(_,T)=>{this.handlePushRequest(T)}),this.registerHandler("git/history/request",(_,T)=>{this.handleHistoryRequest(T)}),this.registerHandler("git/commit-details/request",(_,T)=>{this.handleCommitDetailsRequest(T)}),this.registerHandler("git/commit-file-diff/request",(_,T)=>{this.handleCommitFileDiffRequest(T)}),this.registerHandler("git/sync/request",(_,T)=>{this.handleSyncRequest(T)}),this.registerHandler("git/create-pr/request",(_,T)=>{this.handleCreatePRRequest(T)}),this.registerHandler("git/default-branch/request",(_,T)=>{this.handleDefaultBranchRequest(T)}),this.registerHandler("git/existing-pr/request",(_,T)=>{this.handleExistingPRRequest(T)}),this.registerHandler("git/remote-branches/request",(_,T)=>{this.handleRemoteBranchesRequest(T)}),g.info("[GitService] MQTT handlers registered")}registerHandler(_,T){if(!this.mqttClient)return;this.messageHandlers.set(_,T),this.mqttClient.subscribe(_,T),g.debug(`[GitService] Subscribed to ${_}`)}async publishResponse(_,T){if(!this.mqttClient){g.error("[GitService] MQTT client not available");return}await this.mqttClient.publish(_,JSON.stringify(T),{qos:1})}async handleOrgsRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Orgs request",{clientId:T.clientId}),!this.ghAuthResult.authenticated){let L={orgs:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/orgs/${T.clientId}/response`,L);return}let E={orgs:await J9(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling orgs request",{error:T})}}async handleReposRequest(_){try{let T=JSON.parse(_.toString()),A=T.requestId||T.clientId;if(g.debug("[GitService] Repos request",{clientId:T.clientId,requestId:T.requestId,org:T.org,limit:T.limit}),!this.ghAuthResult.authenticated){let J={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,J);return}let L={repos:await R5(T.org,T.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${A}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling repos request",{error:T})}}async handleSearchReposRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Search repos request",{clientId:T.clientId,query:T.query,limit:T.limit}),!this.ghAuthResult.authenticated){let A={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/search/${T.clientId}/response`,A);return}await bW(T.query,async(A,E,L)=>{let J={repos:A,timestamp:Date.now(),source:E,isComplete:L};await this.publishResponse(`git/repos/search/${T.clientId}/response`,J),g.debug("[GitService] Sent search results",{source:E,count:A.length,isComplete:L})},T.limit||50),this.requestsHandled++}catch(T){g.error("[GitService] Error handling search repos request",{error:T})}}async handleBranchesRequest(_){try{let T=JSON.parse(_.toString());if(g.debug("[GitService] Branches request",{clientId:T.clientId,owner:T.owner,repo:T.repo}),!this.ghAuthResult.authenticated){let L={branches:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/branches/${T.clientId}/response`,L);return}let A=await gW(T.owner,T.repo),E={branches:A.branches,defaultBranch:A.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/branches/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling branches request",{error:T})}}async handleCloneRequest(_){try{let T=JSON.parse(_.toString());if(g.info("[GitService] Clone request",{clientId:T.clientId,repoUrl:T.repoUrl,targetPath:T.targetPath,branch:T.branch}),!this.ghAuthResult.authenticated){let L={success:!1,error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/clone/${T.clientId}/response`,L);return}let A=await mW(T.repoUrl,T.targetPath,T.branch),E=A.success?{success:!0,path:A.path,defaultBranch:A.defaultBranch,timestamp:Date.now()}:{success:!1,error:A.error||"Clone failed",timestamp:Date.now()};await this.publishResponse(`git/clone/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling clone request",{error:T})}}async handleIsRepoRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Is-repo request",{clientId:T.clientId,path:T.path});let A=await z4(T.path),E;if(A){let[L,J,X]=await Promise.all([O0(T.path),F4(T.path),aW(T.path)]);E={isGitRepo:!0,repoRoot:L||void 0,defaultBranch:J||void 0,remoteUrl:X||void 0,timestamp:Date.now()}}else E={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling is-repo request",{error:T});let A=JSON.parse(_.toString()),E={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${A.clientId}/response`,E)}}async handleWorktreeGetOrCreateRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree get-or-create request",{clientId:T.clientId,repoPath:T.repoPath,sessionId:T.sessionId});let{worktree:A,isNew:E}=await this.worktreeManager.getOrCreateForSession(T.sessionId,T.repoPath),L={success:!0,worktreePath:A.path,branch:A.branch,isNew:E,timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${T.clientId}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree get-or-create request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${A.clientId}/response`,E)}}async handleWorktreeGetRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree get request",{clientId:T.clientId,repoPath:T.repoPath,sessionId:T.sessionId});let A=await this.worktreeManager.getWorktreeForSession(T.sessionId,T.repoPath),E=A?{exists:!0,worktreePath:A.path,branch:A.branch,timestamp:Date.now()}:{exists:!1,timestamp:Date.now()};await this.publishResponse(`git/worktree/get/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree get request",{error:T})}}async handleWorktreeListRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Worktree list request",{clientId:T.clientId,repoPath:T.repoPath});let E={worktrees:await this.worktreeManager.listWorktreesForRepo(T.repoPath),timestamp:Date.now()};await this.publishResponse(`git/worktree/list/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling worktree list request",{error:T})}}async handleStatusRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Status request",{clientId:T.clientId,path:T.path});let E={success:!0,status:await X9(T.path),timestamp:Date.now()};await this.publishResponse(`git/status/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling status request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/status/${A.clientId}/response`,E)}}async handleDiffRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Diff request",{clientId:T.clientId,path:T.path,file:T.file,staged:T.staged});let A=await dW(T.path,T.file,T.staged),E={success:!0,diff:A.diff,isBinary:A.isBinary,timestamp:Date.now()};await this.publishResponse(`git/diff/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling diff request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/diff/${A.clientId}/response`,E)}}async handleChangesAllRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Changes all request",{clientId:T.clientId,repoPath:T.repoPath});let A=await this.worktreeManager.listWorktreesForRepo(T.repoPath),E={repoPath:T.repoPath,worktrees:[],totalChanges:0};for(let J of A)try{let X=await X9(J.path);E.worktrees.push({worktreePath:J.path,branch:J.branch,sessionId:J.sessionId,changes:X.files,totalCount:X.files.length}),E.totalChanges+=X.files.length}catch(X){g.warn("[GitService] Failed to get status for worktree",{path:J.path,error:X})}let L={success:!0,changes:E,timestamp:Date.now()};await this.publishResponse(`git/changes/all/${T.clientId}/response`,L),this.requestsHandled++}catch(T){g.error("[GitService] Error handling changes all request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/changes/all/${A.clientId}/response`,E)}}async handleStageRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Stage request",{clientId:T.clientId,path:T.path,files:T.files}),await cW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){g.error("[GitService] Error handling stage request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/stage/${A.clientId}/response`,E)}}async handleUnstageRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Unstage request",{clientId:T.clientId,path:T.path,files:T.files}),await pW(T.path,T.files);let A={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${T.clientId}/response`,A),this.requestsHandled++}catch(T){g.error("[GitService] Error handling unstage request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unstage/${A.clientId}/response`,E)}}async handleCommitRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Commit request",{clientId:T.clientId,path:T.path,signoff:T.signoff});let E={success:!0,commit:await lW(T.path,T.message,T.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit/${A.clientId}/response`,E)}}async handleUnpushedCommitsRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Unpushed commits request",{clientId:T.clientId,path:T.path});let A=await V4(T.path),E={success:!0,commits:A.commits,upstream:A.upstream,ahead:A.ahead,timestamp:Date.now()};await this.publishResponse(`git/unpushed/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling unpushed commits request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unpushed/${A.clientId}/response`,E)}}async handlePushRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Push request",{clientId:T.clientId,path:T.path,force:T.force});let A=await oW(T.path,T.force),E={success:!0,commitsPushed:A.commitsPushed,remote:A.remote,branch:A.branch,timestamp:Date.now()};await this.publishResponse(`git/push/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling push request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/push/${A.clientId}/response`,E)}}async handleHistoryRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] History request",{clientId:T.clientId,path:T.path,limit:T.limit});let A=await rW(T.path,T.limit||50),E={success:!0,commits:A.commits,totalCount:A.totalCount,timestamp:Date.now()};await this.publishResponse(`git/history/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling history request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/history/${A.clientId}/response`,E)}}async handleCommitDetailsRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Commit details request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash});let E={success:!0,commit:await sW(T.path,T.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit details request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-details/${A.clientId}/response`,E)}}async handleCommitFileDiffRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Commit file diff request",{clientId:T.clientId,path:T.path,commitHash:T.commitHash,filePath:T.filePath});let A=await eW(T.path,T.commitHash,T.filePath),E={success:!0,diff:A.diff,isBinary:A.isBinary,timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling commit file diff request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${A.clientId}/response`,E)}}async handleSyncRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Sync request",{clientId:T.clientId,path:T.path});let A=await tW(T.path),E=A.success?{success:!0,action:A.action,commitsPulled:A.commitsPulled,commitsPushed:A.commitsPushed,timestamp:Date.now()}:{success:!1,action:A.action,commitsPulled:A.commitsPulled,commitsPushed:A.commitsPushed,error:A.error||"Sync failed",conflictedFiles:A.conflictedFiles,timestamp:Date.now()};await this.publishResponse(`git/sync/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling sync request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/sync/${A.clientId}/response`,E)}}async handleCreatePRRequest(_){try{let T=JSON.parse(_.toString());g.info("[GitService] Create PR request",{clientId:T.clientId,path:T.path,title:T.title,baseBranch:T.baseBranch,draft:T.draft});let A=await _N(T.path,T.title,T.body,T.baseBranch,T.draft),E=A.success?{success:!0,prNumber:A.prNumber,prUrl:A.prUrl,timestamp:Date.now()}:{success:!1,error:A.error||"Failed to create pull request",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling create PR request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${A.clientId}/response`,E)}}async handleDefaultBranchRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Default branch request",{clientId:T.clientId,path:T.path});let A=await H9(T.path),E=A?{success:!0,defaultBranch:A,timestamp:Date.now()}:{success:!1,error:"Could not determine default branch",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling default branch request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${A.clientId}/response`,E)}}async handleExistingPRRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Existing PR request",{clientId:T.clientId,path:T.path});let A=await TN(T.path),E={exists:A.exists,prNumber:A.prNumber,prUrl:A.prUrl,title:A.title,state:A.state,draft:A.draft,error:A.error,timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling existing PR request",{error:T});let A=JSON.parse(_.toString()),E={exists:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${A.clientId}/response`,E)}}async handleRemoteBranchesRequest(_){try{let T=JSON.parse(_.toString());g.debug("[GitService] Remote branches request",{clientId:T.clientId,path:T.path});let A=await AN(T.path),E={success:!0,branches:A.branches,defaultBranch:A.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${T.clientId}/response`,E),this.requestsHandled++}catch(T){g.error("[GitService] Error handling remote branches request",{error:T});let A=JSON.parse(_.toString()),E={success:!1,error:T instanceof Error?T.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${A.clientId}/response`,E)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,activeWorktrees:this.worktreeManager.getActiveWorktreeCount(),ghAuthenticated:this.ghAuthResult.authenticated,ghInstalled:this.ghAuthResult.installed,ghInPath:this.ghAuthResult.inPath,ghError:this.ghAuthResult.error,ghUsername:this.ghAuthResult.username}}}import*as QN from"path";import*as x5 from"path";import*as $N from"os";var d_=v(),S8=x5.join($N.homedir(),".ccc"),YN=x5.join(S8,"device-tokens.json"),KN=x5.join(S8,"notification-preferences.json");class GN{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if((await Bun.$`test -d ${S8}`.quiet().nothrow()).exitCode!==0)await Bun.$`mkdir -p ${S8}`.quiet(),d_.debug("[NotificationStorage] Created .ccc directory:",S8)}catch(_){throw d_.error("[NotificationStorage] Error ensuring directory:",_),_}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let _=Bun.file(YN);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(YN,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(KN);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(KN,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 GN;var G9=null;async function UN(){if(!G9)G9=await import("expo-server-sdk");return G9}var $1=v();class WN{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;async getExpo(){if(!this.expo){let _=await UN();this.expo=new _.default}return this.expo}async isValidToken(_){return(await UN()).default.isExpoPushToken(_)}async sendNotification(_,T){if(!await this.isValidToken(_))return $1.warn("[ExpoPushClient] Invalid Expo push token:",{token:_.substring(0,20)+"..."}),null;let A={to:_,title:T.title,body:T.body,data:T.data,sound:T.sound||"default",channelId:T.channelId||"default",priority:T.priority||"high",badge:T.badge};try{let J=(await(await this.getExpo()).sendPushNotificationsAsync([A]))[0];if(this.notificationsSent++,this.lastNotificationAt=new Date,J.id){let X=J;this.pendingTickets.set(X.id,{ticketId:X.id,token:_,createdAt:new Date})}if(J.status==="error"){let X=J;await this.handleTicketError(X,_)}return $1.debug("[ExpoPushClient] Sent notification:",{token:_.substring(0,20)+"...",status:J.status}),J}catch(E){return $1.error("[ExpoPushClient] Error sending notification:",E),null}}async sendBatchNotifications(_,T){let A=[];for(let H of _)if(!await this.isValidToken(H))$1.warn("[ExpoPushClient] Skipping invalid token:",{token:H.substring(0,20)+"..."});else A.push(H);if(A.length===0)return $1.warn("[ExpoPushClient] No valid tokens to send to"),[];let E=A.map((H)=>({to:H,title:T.title,body:T.body,data:T.data,sound:T.sound||"default",channelId:T.channelId||"default",priority:T.priority||"high",badge:T.badge})),L=await this.getExpo(),J=L.chunkPushNotifications(E),X=[];for(let H of J)try{let Z=await L.sendPushNotificationsAsync(H);X.push(...Z);for(let Y=0;Y<Z.length;Y++){let K=Z[Y],$=A[X.length-Z.length+Y];if(K.id){let G=K;this.pendingTickets.set(G.id,{ticketId:G.id,token:$,createdAt:new Date})}if(K.status==="error")await this.handleTicketError(K,$)}this.notificationsSent+=Z.length,this.lastNotificationAt=new Date}catch(Z){$1.error("[ExpoPushClient] Error sending batch chunk:",Z)}return $1.info("[ExpoPushClient] Sent batch notifications:",{total:A.length,successful:X.filter((H)=>H.status==="ok").length,failed:X.filter((H)=>H.status==="error").length}),X}async handleTicketError(_,T){if($1.warn("[ExpoPushClient] Ticket error:",{message:_.message,details:_.details}),_.details?.error==="DeviceNotRegistered"){$1.info("[ExpoPushClient] Removing invalid token:",{token:T.substring(0,20)+"..."});let E=(await S1.getAllTokens()).find((L)=>L.expoPushToken===T);if(E)await S1.unregisterToken(E.deviceId)}}async checkReceipts(){let _=new Date;_.setMinutes(_.getMinutes()-15);let T=[];for(let[J,X]of this.pendingTickets.entries())if(X.createdAt<_)T.push(J);if(T.length===0)return;$1.debug("[ExpoPushClient] Checking receipts:",{count:T.length});let A=await this.getExpo(),E=A.chunkPushNotificationReceiptIds(T);for(let J of E)try{let X=await A.getPushNotificationReceiptsAsync(J);for(let[H,Z]of Object.entries(X)){let Y=this.pendingTickets.get(H);if(Z.status==="ok")$1.debug("[ExpoPushClient] Receipt OK:",{ticketId:H});else if(Z.status==="error"){let K=Z;if($1.warn("[ExpoPushClient] Receipt error:",{ticketId:H,message:K.message,details:K.details}),K.details?.error==="DeviceNotRegistered"&&Y){let G=(await S1.getAllTokens()).find((U)=>U.expoPushToken===Y.token);if(G)$1.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:G.deviceId}),await S1.unregisterToken(G.deviceId)}}this.pendingTickets.delete(H)}}catch(X){$1.error("[ExpoPushClient] Error checking receipts:",X)}let L=new Date;L.setHours(L.getHours()-24);for(let[J,X]of this.pendingTickets.entries())if(X.createdAt<L)this.pendingTickets.delete(J)}getStats(){return{notificationsSent:this.notificationsSent,lastNotificationAt:this.lastNotificationAt,pendingReceipts:this.pendingTickets.size}}}var y8=new WN;var Q_=v(),NN=200,oh=900000;class w5{name="Notification Service";running=!1;startedAt;mqttClient=null;claudeAgentService=null;receiptCheckInterval;constructor(){}setMQTTClient(_){this.mqttClient=_}setClaudeAgentService(_){this.claudeAgentService=_}async start(){try{if(this.running=!0,this.startedAt=new Date,Q_.info("[Notification] Service started"),this.mqttClient)this.registerMQTTHandlers();else Q_.warn("[Notification] MQTT client not set - handlers will not be registered");this.receiptCheckInterval=setInterval(()=>{y8.checkReceipts().catch((_)=>{Q_.error("[Notification] Error checking receipts:",_)})},oh),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=QN.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
|
|
2641
|
+
`)}if(!T.trim())return null;if(T.length>NN)T=T.substring(0,NN)+"...";return T}buildPermissionBody(_){let T=_.action||"Unknown tool",A=_.params||{},E="";switch(T.toLowerCase()){case"bash":case"execute_command":E=A.command||"";break;case"read":case"read_file":E=A.file_path||"";break;case"write":case"write_file":E=A.file_path||"";break;case"edit":E=A.file_path||"";break;case"webfetch":E=A.url||"";break;case"websearch":E=A.query||"";break;default:E=A.file_path||A.command||A.path||""}if(E.length>100)E=E.substring(0,100)+"...";if(E)return`Permission requested: ${T}: ${E}`;return`Permission requested: ${T}`}async sendToDevicesWithPreference(_,T){try{let A=await S1.getAllTokens();if(A.length===0){Q_.debug("[Notification] No registered devices");return}let E=[];for(let L of A){if(!L.expoPushToken)continue;if((await S1.getPreferences(L.deviceId))[_])E.push(L.expoPushToken)}if(E.length===0){Q_.debug("[Notification] No devices with preference enabled:",{preferenceType:_});return}await y8.sendBatchNotifications(E,T),Q_.debug("[Notification] Sent to devices:",{count:E.length,preferenceType:_})}catch(A){Q_.error("[Notification] Error sending to devices:",A)}}getStatus(){let _=y8.getStats();return{name:this.name,running:this.running,startedAt:this.startedAt,registeredDevices:0,notificationsSent:_.notificationsSent,lastNotificationAt:_.lastNotificationAt}}}class U9{services=[];startedServices=[];logger=v();addService(_){this.services.push(_)}addOptionalService(_,T){if(T)this.services.push(_)}getServiceByName(_){return this.services.find((T)=>T.name===_)}async startAll(){for(let _ of this.services)try{this.logger.debug(`Starting ${_.name}...`),await _.start(),this.startedServices.push(_)}catch(T){throw this.logger.error(`Failed to start ${_.name}`,T),await this.stopAll(),T}this.logger.info("All services started successfully")}async stopAll(){for(let _=this.startedServices.length-1;_>=0;_--){let T=this.startedServices[_];try{this.logger.debug(`Stopping ${T?.name}...`),await T?.stop()}catch(A){this.logger.error(`Failed to stop ${T?.name}`,A)}}this.startedServices=[],this.logger.info("All services stopped")}getStatus(){return this.services.map((_)=>_.getStatus())}printStatus(){let _=this.getStatus();this.logger.info("=== Backend Status ===");for(let T of _){let A=T.running?"\u2713":"\u2717";if(this.logger.info(`${A} ${T.name}`),"port"in T&&T.port)this.logger.info(` Port: ${T.port}`);if("routes"in T&&T.routes)this.logger.info(` Routes: ${T.routes.map((E)=>`${E.path}->${E.target}`).join(", ")}`);if(T.startedAt)this.logger.info(` Started: ${T.startedAt.toISOString()}`);if(T.error)this.logger.info(` Error: ${T.error}`)}this.logger.info("=====================")}}import MN from"os";function VN(){let _=MN.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 zN(){let _=MN.hostname().toLowerCase();if(_.endsWith(".local"))_=_.slice(0,-6);return _=_.replace(/\./g,"-"),_||"ccc-server"}var FN=process.argv.slice(2);if(FN.includes("--version")||FN.includes("-v"))console.log(`ccc v${G1()}`),process.exit(0);function rh(_){let T=v();try{if(process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",(A)=>{let E=A.toString().toLowerCase();if(E==="q")_.display();if(E==="\x03")process.emit("SIGINT")}),T.debug('Keypress listener enabled (press "q" to redisplay QR codes)')}catch(A){T.warn("Could not setup keypress listener",A)}}async function sh(){try{D9();let _=V9();F9(_.debug);let T=v();T.info("Backend v2 starting...");let A=z9(_);if(_.debug)T.debug("Configuration",A);let E=new mA(A.mqtt),L=new K5({host:"localhost",port:A.mqtt.port,username:A.mqtt.auth?.username,password:A.mqtt.auth?.password}),J=new $5(A.terminal),X=new U5(A.router),H=new z5(A.autoUpdate),Z=new F5,Y=new C5,K=new O5(J),$=new q5(A.claudeAgent),G=new P5,U=new j5,V=new w5,N=new U9;if(N.addService(E),N.addService(L),N.addService(J),N.addService(X),N.addService(H),N.addService(Z),N.addService(Y),N.addService(K),N.addService($),N.addService(G),N.addService(U),N.addService(V),A.ngrok){let c=new W5(A.ngrok);N.addOptionalService(c,!0)}Z.setMQTTClient(L),Z.setClaudeAgentService($),Y.setMQTTClient(L),K.setMQTTClient(L),$.setMQTTClient(L),$.setSessionsService(Z),G.setMQTTClient(L),U.setMQTTClient(L),V.setMQTTClient(L),V.setClaudeAgentService($),await N.startAll();let z=N.getServiceByName("CCC Ngrok Service"),Q,F=VN(),R=F?`${F}:${A.router.port}`:void 0;if(z&&z.getStatus().active)Q=z.getUrl()||void 0;let q=zN(),f={...A.qrcode,profileName:q,ipBasedUrl:R,ngrokUrl:Q},h=new V5(f);N.addService(h),await h.start(),N.printStatus(),T.info("Backend v2 is ready"),rh(h);let b=!1,l=async(c)=>{if(b){T.warn("Shutdown already in progress, ignoring signal");return}b=!0,T.info(`Received ${c}, shutting down...`);try{await N.stopAll(),process.exit(0)}catch(W_){T.error("Error during shutdown",W_),process.exit(1)}};process.once("SIGINT",()=>l("SIGINT")),process.once("SIGTERM",()=>l("SIGTERM")),process.on("uncaughtException",(c)=>{if(c&&c.code==="ERR_SOCKET_CLOSED"){T.debug("Ignoring socket closed error (expected during PTY cleanup)");return}T.error("Uncaught exception",c)}),process.on("unhandledRejection",(c)=>{T.error("Unhandled rejection",c)})}catch(_){v().error("Fatal error",_),process.exit(1)}}sh();
|