iosignal 9.21.0 → 9.22.0
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/README.ko.md +6 -0
- package/README.md +8 -0
- package/dist/browser/esm/broker.js +24 -0
- package/dist/browser/esm/broker.js.map +1 -0
- package/dist/browser/esm/io.d.ts +14 -0
- package/dist/browser/esm/io.js +1 -1
- package/dist/browser/esm/io.js.map +1 -1
- package/dist/browser/iife/io.js +1 -1
- package/dist/browser/iife/io.js.map +1 -1
- package/dist/node/iosignal.cjs +138 -96
- package/dist/node/iosignal.d.cts +1 -1
- package/dist/node/iosignal.d.ts +1 -1
- package/dist/node/iosignal.js +138 -96
- package/dist/types/client/browser/IOWebSocket.d.ts +14 -0
- package/package.json +4 -1
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function e(e,r,n,i,s){let o,a,h,u,c,f,l,p,d,g,y,m,b;for(;s>=64;){for(o=r[0],a=r[1],h=r[2],u=r[3],c=r[4],f=r[5],l=r[6],p=r[7],g=0;g<16;g++)y=i+4*g,e[g]=(255&n[y])<<24|(255&n[y+1])<<16|(255&n[y+2])<<8|255&n[y+3];for(g=16;g<64;g++)d=e[g-2],m=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,d=e[g-15],b=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,e[g]=(m+e[g-7]|0)+(b+e[g-16]|0);for(g=0;g<64;g++)m=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&l)|0)+(p+(t[g]+e[g]|0)|0)|0,b=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&a^o&h^a&h)|0,p=l,l=f,f=c,c=u+m|0,u=h,h=a,a=o,o=m+b|0;r[0]+=o,r[1]+=a,r[2]+=h,r[3]+=u,r[4]+=c,r[5]+=f,r[6]+=l,r[7]+=p,i+=64,s-=64}return i}const r=function(){function t(){this.digestLength=32,this.blockSize=64,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var t=0;t<this.buffer.length;t++)this.buffer[t]=0;for(t=0;t<this.temp.length;t++)this.temp[t]=0;this.reset()},t.prototype.update=function(t,r){if(void 0===r&&(r=t.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");let n=0;if(this.bytesHashed+=r,this.bufferLength>0){for(;this.bufferLength<64&&r>0;)this.buffer[this.bufferLength++]=t[n++],r--;64===this.bufferLength&&(e(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(r>=64&&(n=e(this.temp,this.state,t,n,r),r%=64);r>0;)this.buffer[this.bufferLength++]=t[n++],r--;return this},t.prototype.finish=function(t){if(!this.finished){const t=this.bytesHashed,n=this.bufferLength,i=t/536870912|0,s=t<<3,o=t%64<56?64:128;this.buffer[n]=128;for(var r=n+1;r<o-8;r++)this.buffer[r]=0;this.buffer[o-8]=i>>>24&255,this.buffer[o-7]=i>>>16&255,this.buffer[o-6]=i>>>8&255,this.buffer[o-5]=i>>>0&255,this.buffer[o-4]=s>>>24&255,this.buffer[o-3]=s>>>16&255,this.buffer[o-2]=s>>>8&255,this.buffer[o-1]=s>>>0&255,e(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(r=0;r<8;r++)t[4*r+0]=this.state[r]>>>24&255,t[4*r+1]=this.state[r]>>>16&255,t[4*r+2]=this.state[r]>>>8&255,t[4*r+3]=this.state[r]>>>0&255;return this},t.prototype.digest=function(){const t=new Uint8Array(this.digestLength);return this.finish(t),t},t.prototype._saveState=function(t){for(let e=0;e<this.state.length;e++)t[e]=this.state[e]},t.prototype._restoreState=function(t,e){for(let e=0;e<this.state.length;e++)this.state[e]=t[e];this.bytesHashed=e,this.finished=!1,this.bufferLength=0},t}(),n=function(){function t(t){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;const e=new Uint8Array(this.blockSize);if(t.length>this.blockSize)(new r).update(t).finish(e).clean();else for(var n=0;n<t.length;n++)e[n]=t[n];for(n=0;n<e.length;n++)e[n]^=54;for(this.inner.update(e),n=0;n<e.length;n++)e[n]^=106;for(this.outer.update(e),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),n=0;n<e.length;n++)e[n]=0}return t.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},t.prototype.clean=function(){for(let t=0;t<this.istate.length;t++)this.ostate[t]=this.istate[t]=0;this.inner.clean(),this.outer.clean()},t.prototype.update=function(t){return this.inner.update(t),this},t.prototype.finish=function(t){return this.outer.finished?this.outer.finish(t):(this.inner.finish(t),this.outer.update(t,this.digestLength).finish(t)),this},t.prototype.digest=function(){const t=new Uint8Array(this.digestLength);return this.finish(t),t},t}();function i(t){const e=(new r).update(t),n=e.digest();return e.clean(),n}var s,o,a,h={},u={},c={};
|
|
2
|
+
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
3
|
+
/*!
|
|
4
|
+
* The buffer module from node.js, for the browser.
|
|
5
|
+
*
|
|
6
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
7
|
+
* @license MIT
|
|
8
|
+
*/
|
|
9
|
+
var f=(a||(a=1,function(t){const e=function(){if(s)return u;s=1,u.byteLength=function(t){var e=o(t),r=e[0],n=e[1];return 3*(r+n)/4-n},u.toByteArray=function(t){var n,i,s=o(t),a=s[0],h=s[1],u=new r(function(t,e,r){return 3*(e+r)/4-r}(0,a,h)),c=0,f=h>0?a-4:a;for(i=0;i<f;i+=4)n=e[t.charCodeAt(i)]<<18|e[t.charCodeAt(i+1)]<<12|e[t.charCodeAt(i+2)]<<6|e[t.charCodeAt(i+3)],u[c++]=n>>16&255,u[c++]=n>>8&255,u[c++]=255&n;return 2===h&&(n=e[t.charCodeAt(i)]<<2|e[t.charCodeAt(i+1)]>>4,u[c++]=255&n),1===h&&(n=e[t.charCodeAt(i)]<<10|e[t.charCodeAt(i+1)]<<4|e[t.charCodeAt(i+2)]>>2,u[c++]=n>>8&255,u[c++]=255&n),u},u.fromByteArray=function(e){for(var r,n=e.length,i=n%3,s=[],o=16383,a=0,u=n-i;a<u;a+=o)s.push(h(e,a,a+o>u?u:a+o));return 1===i?(r=e[n-1],s.push(t[r>>2]+t[r<<4&63]+"==")):2===i&&(r=(e[n-2]<<8)+e[n-1],s.push(t[r>>10]+t[r>>4&63]+t[r<<2&63]+"=")),s.join("")};for(var t=[],e=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)t[i]=n[i],e[n.charCodeAt(i)]=i;function o(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function a(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[63&e]}function h(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(255&t[s+2]),i.push(a(n));return i.join("")}return e["-".charCodeAt(0)]=62,e["_".charCodeAt(0)]=63,u}(),r=(o||(o=1,c.read=function(t,e,r,n,i){var s,o,a=8*i-n-1,h=(1<<a)-1,u=h>>1,c=-7,f=r?i-1:0,l=r?-1:1,p=t[e+f];for(f+=l,s=p&(1<<-c)-1,p>>=-c,c+=a;c>0;s=256*s+t[e+f],f+=l,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=n;c>0;o=256*o+t[e+f],f+=l,c-=8);if(0===s)s=1-u;else{if(s===h)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),s-=u}return(p?-1:1)*o*Math.pow(2,s-n)},c.write=function(t,e,r,n,i,s){var o,a,h,u=8*s-i-1,c=(1<<u)-1,f=c>>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),(e+=o+f>=1?l/h:l*Math.pow(2,1-f))*h>=2&&(o++,h/=2),o+f>=c?(a=0,o=c):o+f>=1?(a=(e*h-1)*Math.pow(2,i),o+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&a,p+=d,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}),c),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=h,t.SlowBuffer=function(t){return+t!=t&&(t=0),h.alloc(+t)},t.INSPECT_MAX_BYTES=50;const i=2147483647;function a(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,h.prototype),e}function h(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return p(t)}return f(t,e,r)}function f(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!h.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|m(t,e);let n=a(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(J(t,Uint8Array)){const e=new Uint8Array(t);return g(e.buffer,e.byteOffset,e.byteLength)}return d(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(J(t,ArrayBuffer)||t&&J(t.buffer,ArrayBuffer))return g(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(J(t,SharedArrayBuffer)||t&&J(t.buffer,SharedArrayBuffer)))return g(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return h.from(n,e,r);const i=function(t){if(h.isBuffer(t)){const e=0|y(t.length),r=a(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||X(t.length)?a(0):d(t):"Buffer"===t.type&&Array.isArray(t.data)?d(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return h.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function l(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function p(t){return l(t),a(t<0?0:0|y(t))}function d(t){const e=t.length<0?0:0|y(t.length),r=a(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function g(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,h.prototype),n}function y(t){if(t>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function m(t,e){if(h.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||J(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return K(t).length;default:if(i)return n?-1:Q(t).length;e=(""+e).toLowerCase(),i=!0}}function b(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return M(this,e,r);case"utf8":case"utf-8":return T(this,e,r);case"ascii":return C(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return I(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function w(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function E(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),X(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=h.from(e,n)),h.isBuffer(e))return 0===e.length?-1:_(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):_(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function _(t,e,r,n,i){let s,o=1,a=t.length,h=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,a/=2,h/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){let n=-1;for(s=r;s<a;s++)if(u(t,s)===u(e,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===h)return n*o}else-1!==n&&(s-=s-n),n=-1}else for(r+h>a&&(r=a-h),s=r;s>=0;s--){let r=!0;for(let n=0;n<h;n++)if(u(t,s+n)!==u(e,n)){r=!1;break}if(r)return s}return-1}function B(t,e,r,n){r=Number(r)||0;const i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;const s=e.length;let o;for(n>s/2&&(n=s/2),o=0;o<n;++o){const n=parseInt(e.substr(2*o,2),16);if(X(n))return o;t[r+o]=n}return o}function A(t,e,r,n){return Y(Q(e,t.length-r),t,r,n)}function v(t,e,r,n){return Y(function(t){const e=[];for(let r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function S(t,e,r,n){return Y(K(e),t,r,n)}function L(t,e,r,n){return Y(function(t,e){let r,n,i;const s=[];for(let o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}(e,t.length-r),t,r,n)}function I(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function T(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i<r;){const e=t[i];let s=null,o=e>239?4:e>223?3:e>191?2:1;if(i+o<=r){let r,n,a,h;switch(o){case 1:e<128&&(s=e);break;case 2:r=t[i+1],128==(192&r)&&(h=(31&e)<<6|63&r,h>127&&(s=h));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(h=(15&e)<<12|(63&r)<<6|63&n,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:r=t[i+1],n=t[i+2],a=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(h=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&a,h>65535&&h<1114112&&(s=h))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(t){const e=t.length;if(e<=k)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=k));return r}(n)}t.kMaxLength=i,h.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),h.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.buffer}}),Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.byteOffset}}),h.poolSize=8192,h.from=function(t,e,r){return f(t,e,r)},Object.setPrototypeOf(h.prototype,Uint8Array.prototype),Object.setPrototypeOf(h,Uint8Array),h.alloc=function(t,e,r){return function(t,e,r){return l(t),t<=0?a(t):void 0!==e?"string"==typeof r?a(t).fill(e,r):a(t).fill(e):a(t)}(t,e,r)},h.allocUnsafe=function(t){return p(t)},h.allocUnsafeSlow=function(t){return p(t)},h.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==h.prototype},h.compare=function(t,e){if(J(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),J(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),!h.isBuffer(t)||!h.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let r=t.length,n=e.length;for(let i=0,s=Math.min(r,n);i<s;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},h.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}},h.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return h.alloc(0);let r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;const n=h.allocUnsafe(e);let i=0;for(r=0;r<t.length;++r){let e=t[r];if(J(e,Uint8Array))i+e.length>n.length?(h.isBuffer(e)||(e=h.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!h.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},h.byteLength=m,h.prototype._isBuffer=!0,h.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)w(this,e,e+1);return this},h.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)w(this,e,e+3),w(this,e+1,e+2);return this},h.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)w(this,e,e+7),w(this,e+1,e+6),w(this,e+2,e+5),w(this,e+3,e+4);return this},h.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?T(this,0,t):b.apply(this,arguments)},h.prototype.toLocaleString=h.prototype.toString,h.prototype.equals=function(t){if(!h.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===h.compare(this,t)},h.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(h.prototype[n]=h.prototype.inspect),h.prototype.compare=function(t,e,r,n,i){if(J(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(e>>>=0);const a=Math.min(s,o),u=this.slice(n,i),c=t.slice(e,r);for(let t=0;t<a;++t)if(u[t]!==c[t]){s=u[t],o=c[t];break}return s<o?-1:o<s?1:0},h.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},h.prototype.indexOf=function(t,e,r){return E(this,t,e,r,!0)},h.prototype.lastIndexOf=function(t,e,r){return E(this,t,e,r,!1)},h.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return B(this,t,e,r);case"utf8":case"utf-8":return A(this,t,e,r);case"ascii":case"latin1":case"binary":return v(this,t,e,r);case"base64":return S(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const k=4096;function C(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function R(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function M(t,e,r){const n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=e;n<r;++n)i+=Z[t[n]];return i}function U(t,e,r){const n=t.slice(e,r);let i="";for(let t=0;t<n.length-1;t+=2)i+=String.fromCharCode(n[t]+256*n[t+1]);return i}function O(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function x(t,e,r,n,i,s){if(!h.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function N(t,e,r,n,i){G(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,r}function P(t,e,r,n,i){G(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s>>=8,t[r+6]=s,s>>=8,t[r+5]=s,s>>=8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o>>=8,t[r+2]=o,o>>=8,t[r+1]=o,o>>=8,t[r]=o,r+8}function $(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function D(t,e,n,i,s){return e=+e,n>>>=0,s||$(t,0,n,4),r.write(t,e,n,i,23,4),n+4}function F(t,e,n,i,s){return e=+e,n>>>=0,s||$(t,0,n,8),r.write(t,e,n,i,52,8),n+8}h.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);const n=this.subarray(t,e);return Object.setPrototypeOf(n,h.prototype),n},h.prototype.readUintLE=h.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t],i=1,s=0;for(;++s<e&&(i*=256);)n+=this[t+s]*i;return n},h.prototype.readUintBE=h.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},h.prototype.readUint8=h.prototype.readUInt8=function(t,e){return t>>>=0,e||O(t,1,this.length),this[t]},h.prototype.readUint16LE=h.prototype.readUInt16LE=function(t,e){return t>>>=0,e||O(t,2,this.length),this[t]|this[t+1]<<8},h.prototype.readUint16BE=h.prototype.readUInt16BE=function(t,e){return t>>>=0,e||O(t,2,this.length),this[t]<<8|this[t+1]},h.prototype.readUint32LE=h.prototype.readUInt32LE=function(t,e){return t>>>=0,e||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},h.prototype.readUint32BE=h.prototype.readUInt32BE=function(t,e){return t>>>=0,e||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},h.prototype.readBigUInt64LE=tt(function(t){q(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||V(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),h.prototype.readBigUInt64BE=tt(function(t){q(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||V(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),h.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t],i=1,s=0;for(;++s<e&&(i*=256);)n+=this[t+s]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n},h.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||O(t,e,this.length);let n=e,i=1,s=this[t+--n];for(;n>0&&(i*=256);)s+=this[t+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*e)),s},h.prototype.readInt8=function(t,e){return t>>>=0,e||O(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},h.prototype.readInt16LE=function(t,e){t>>>=0,e||O(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},h.prototype.readInt16BE=function(t,e){t>>>=0,e||O(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},h.prototype.readInt32LE=function(t,e){return t>>>=0,e||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},h.prototype.readInt32BE=function(t,e){return t>>>=0,e||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},h.prototype.readBigInt64LE=tt(function(t){q(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||V(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)}),h.prototype.readBigInt64BE=tt(function(t){q(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||V(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+r)}),h.prototype.readFloatLE=function(t,e){return t>>>=0,e||O(t,4,this.length),r.read(this,t,!0,23,4)},h.prototype.readFloatBE=function(t,e){return t>>>=0,e||O(t,4,this.length),r.read(this,t,!1,23,4)},h.prototype.readDoubleLE=function(t,e){return t>>>=0,e||O(t,8,this.length),r.read(this,t,!0,52,8)},h.prototype.readDoubleBE=function(t,e){return t>>>=0,e||O(t,8,this.length),r.read(this,t,!1,52,8)},h.prototype.writeUintLE=h.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||x(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,s=0;for(this[e]=255&t;++s<r&&(i*=256);)this[e+s]=t/i&255;return e+r},h.prototype.writeUintBE=h.prototype.writeUIntBE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||x(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,s=1;for(this[e+i]=255&t;--i>=0&&(s*=256);)this[e+i]=t/s&255;return e+r},h.prototype.writeUint8=h.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,1,255,0),this[e]=255&t,e+1},h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},h.prototype.writeBigUInt64LE=tt(function(t,e=0){return N(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),h.prototype.writeBigUInt64BE=tt(function(t,e=0){return P(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),h.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);x(this,t,e,r,n-1,-n)}let i=0,s=1,o=0;for(this[e]=255&t;++i<r&&(s*=256);)t<0&&0===o&&0!==this[e+i-1]&&(o=1),this[e+i]=(t/s|0)-o&255;return e+r},h.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);x(this,t,e,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===o&&0!==this[e+i+1]&&(o=1),this[e+i]=(t/s|0)-o&255;return e+r},h.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},h.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},h.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},h.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},h.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||x(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},h.prototype.writeBigInt64LE=tt(function(t,e=0){return N(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),h.prototype.writeBigInt64BE=tt(function(t,e=0){return P(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),h.prototype.writeFloatLE=function(t,e,r){return D(this,t,e,!0,r)},h.prototype.writeFloatBE=function(t,e,r){return D(this,t,e,!1,r)},h.prototype.writeDoubleLE=function(t,e,r){return F(this,t,e,!0,r)},h.prototype.writeDoubleBE=function(t,e,r){return F(this,t,e,!1,r)},h.prototype.copy=function(t,e,r,n){if(!h.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);const i=n-r;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,r,n):Uint8Array.prototype.set.call(t,this.subarray(r,n),e),i},h.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!h.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){const e=t.charCodeAt(0);("utf8"===n&&e<128||"latin1"===n)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;let i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{const s=h.isBuffer(t)?t:h.from(t,n),o=s.length;if(0===o)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<r-e;++i)this[i+e]=s[i%o]}return this};const j={};function z(t,e,r){j[t]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function H(t){let e="",r=t.length;const n="-"===t[0]?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function G(t,e,r,n,i,s){if(t>r||t<e){const r="bigint"==typeof e?"n":"";let n;throw n=0===e||e===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(s+1)}${r}`:`>= -(2${r} ** ${8*(s+1)-1}${r}) and < 2 ** ${8*(s+1)-1}${r}`,new j.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,r){q(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||V(e,t.length-(r+1))}(n,i,s)}function q(t,e){if("number"!=typeof t)throw new j.ERR_INVALID_ARG_TYPE(e,"number",t)}function V(t,e,r){if(Math.floor(t)!==t)throw q(t,r),new j.ERR_OUT_OF_RANGE("offset","an integer",t);if(e<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${e}`,t)}z("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),z("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),z("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function Q(t,e){let r;e=e||1/0;const n=t.length;let i=null;const s=[];for(let o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function K(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Y(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function J(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function X(t){return t!=t}const Z=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function tt(t){return"undefined"==typeof BigInt?et:t}function et(){throw new Error("BigInt not supported")}}(h)),h);const l=new TextEncoder,p=new TextDecoder,d=g;function g(t,e=0){let r;if(void 0===t||"string"!=typeof t||"number"!=typeof e)throw TypeError("invlaid init variablie type name. ");if((t=t.toUpperCase()).includes("8"))r=f.Buffer.alloc(1),t.includes("I")?r.writeInt8(e):r.writeUint8(e);else if(t.includes("16"))r=f.Buffer.alloc(2),t.includes("I")?t.includes("L")?r.writeInt16LE(e):r.writeInt16BE(e):t.includes("L")?r.writeUint16LE(e):r.writeUint16BE(e);else if(t.includes("32"))r=f.Buffer.alloc(4),t.includes("I")?t.includes("L")?r.writeInt32LE(e):r.writeInt32BE(e):t.includes("L")?r.writeUint32LE(e):r.writeUint32BE(e);else if(t.includes("F"))r=f.Buffer.alloc(4),t.includes("L")?r.writeFloatLE(e):r.writeFloatBE(e);else{if(!t.includes("N"))throw TypeError(`invalid number type: ${t}`);r=f.Buffer.from(String(e))}return r}const y=m;function m(t,e,r){let n,i="B";if("number"==typeof e)"number"==typeof r?(n=f.Buffer.alloc(e),0!==r&&n.fill(r),i="B"):(n=f.Buffer.from(String(e)),i="N");else if("string"==typeof e&&"number"==typeof r)i=e.toUpperCase(),n=g(e,r);else if("string"==typeof e&&void 0===r)n=f.Buffer.from(e),i="S";else if(e instanceof Uint8Array&&void 0===r)n=e instanceof f.Buffer?e:f.Buffer.from(e);else if(e instanceof ArrayBuffer&&void 0===r)n=f.Buffer.from(e);else if(ArrayBuffer.isView(e))n=f.Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if("object"==typeof e&&void 0===r)n=f.Buffer.from(JSON.stringify(e)),i="O";else{if("boolean"!=typeof e||void 0!==r)throw TypeError("invalid meta buffer type");{const t=e?1:0;n=f.Buffer.from([t]),i="!"}}return"string"==typeof t&&t.includes("#")&&(t=""),[t,i,n]}const b=w;function w(...t){let e=0;return t.map(t=>{const r=e++;return"number"==typeof t?y(r,"N",t):y(r,t)})}function E(t){if((t=t.toUpperCase()).includes("8"))return t.includes("I")?"int8":"uint8";if(t.includes("16"))return t.includes("I")?t.includes("L")?"int16_le":"int16_be":t.includes("L")?"uint16_le":"uint16_be";if(t.includes("32"))return t.includes("I")?t.includes("L")?"int32_le":"int32_be":t.includes("L")?"uint32_le":"uint32_be";if(t.includes("F"))return t.includes("L")?"float_le":"float_be";if("B"===t)return"buffer";if("S"===t)return"string";if("N"===t)return"number";if("O"===t)return"object";if("!"===t)return"boolean";throw TypeError("invalid data type")}function _(t,e){const r=E(t),n=/^(u?int)8$/.test(r)||"boolean"===r?1:/^(u?int)16_/.test(r)?2:/^(u?int)32_|^float_/.test(r)?4:void 0;if(void 0===e&&(e=n),!Number.isSafeInteger(e)||e<0||void 0!==n&&e!==n)throw TypeError("invalid field length");return e}function B(t,e){if(!Array.isArray(t))return!1;try{for(const r of t){if(!Array.isArray(r)||r.length<3||r.length>5)return!1;const[t,n,i,s]=r;if("string"!=typeof t&&!(Number.isSafeInteger(t)&&t>=0))return!1;const o=_(n,s);if(!Number.isSafeInteger(i)||i<0||i>e||o>e-i)return!1}return!0}catch{return!1}}function A(t,e,r,n){try{if(n=_(t,n),!Number.isSafeInteger(r)||r<0||r>e.byteLength||n>e.byteLength-r)return;const i=E(t);if("int8"==i)return e.readInt8(r);if("uint8"===i)return e.readUint8(r);if("int16_le"===i)return e.readInt16LE(r);if("int16_be"===i)return e.readInt16BE(r);if("uint16_le"===i)return e.readUint16LE(r);if("uint16_be"===i)return e.readUint16BE(r);if("int32_le"===i)return e.readInt32LE(r);if("int32_be"===i)return e.readInt32BE(r);if("uint32_le"===i)return e.readUint32LE(r);if("uint32_be"===i)return e.readUint32BE(r);if("float_le"===i)return e.readFloatLE(r);if("float_be"===i)return e.readFloatBE(r);if("buffer"===i)return e.subarray(r,r+n);if("string"===i){const t=e.subarray(r,r+n);return p.decode(t)}if("number"===i){const t=e.subarray(r,r+n);return Number(p.decode(t))}if("object"===i){const t=e.subarray(r,r+n);return JSON.parse(p.decode(t))}return"boolean"===i?1===e.readInt8(r):void 0}catch(t){}}function v(...t){const e=function(t){let e=[];return t.filter(t=>{if(!Array.isArray(t[0]))return t;e=e.concat(t)}).concat(e)}(t);let r=0;const n=[];let i,s,o=0;if(e.forEach(t=>{const[e,i,s]=t;r+=s.byteLength,("number"==typeof e||e.length>0)&&n.push([e,i,o,s.byteLength]),o=r}),n.length>0){let t=JSON.stringify(n);i=l.encode(t),s=i.byteLength,r=r+s+2}const a=f.Buffer.alloc(r);if(o=0,e.forEach(t=>{const e=t[2];a.set(e,o),o+=e.byteLength}),n.length>0){a.set(i,o);const t=d("16",s);return a.set(t,o+s),a}return a}const S=L;function L(t,e=!1){if(void 0===t)throw TypeError("Invalid data type: Undefined");if("string"==typeof t)return l.encode(t);if("number"==typeof t)return Uint8Array.from([t]);if(t instanceof ArrayBuffer){if(e)return new Uint8Array(t);{const e=new Uint8Array(t),r=new Uint8Array(t.byteLength);return r.set(e),r}}if(ArrayBuffer.isView(t)){if(e)return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);{const e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=new Uint8Array(t.byteLength);return r.set(e),r}}return l.encode(JSON.stringify(t))}const I=T;function T(t,e=!1){const r=L(t,e);return e?f.Buffer.from(r.buffer,r.byteOffset,r.byteLength):f.Buffer.from(r)}const k=C;function C(...t){const e=t.map(t=>T(t));return f.Buffer.concat(e)}const R=M;function M(...t){try{let e=0,r=0;const n=t.map(t=>L(t));n.forEach(t=>{e+=t.byteLength});const i=new Uint8Array(e);return n.forEach(t=>{i.set(t,r),r+=t.byteLength}),i}catch(t){console.log(t)}}function U(t){return 0===P(t)?t.byteLength:t.byteLength-P(t)-x}function O(t,e=N(t)){try{if(t instanceof ArrayBuffer&&(t=f.Buffer.from(t)),!(t instanceof Uint8Array))return;if(!Number.isSafeInteger(e)||e<=0||e>t.byteLength-x)return;const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),n=r.byteLength-e-x,i=JSON.parse(p.decode(r.subarray(n,r.byteLength-x)));if(!B(i,n)||0===i.length)return;return i}catch{return}}const x=2;function N(t){return t instanceof ArrayBuffer&&(t=f.Buffer.from(t)),t instanceof Uint8Array?t.byteLength<=x?0:new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(t.byteLength-x):0}function P(t){if(t instanceof ArrayBuffer&&(t=f.Buffer.from(t)),t instanceof Uint8Array){const e=t.byteLength;if(e<=x)return 0;const r=N(t);return 0===r||r>e?0:O(t,r)?r:0}return 0}function $(t){const e=U(t);return t.subarray(0,e)}function D(t,e=!1){t instanceof ArrayBuffer&&(t=f.Buffer.from(t));const r=N(t);if(0===r)return;let n=O(t,r);return n?e?(n.forEach(t=>{null==t[3]&&(t[1].includes("8")?t[3]=1:t[1].includes("16")?t[3]=2:t[1].includes("32")||t[1].includes("F")?t[3]=4:t[1].includes("!")&&(t[3]=1)),t[4]=E(t[1])}),n):n:void 0}var F=Object.freeze({__proto__:null,B8:I,B8pack:k,Buffer:f.Buffer,MB:y,MBA:b,NB:d,TAIL_LEN:x,U8:S,U8pack:R,equal:function(t,e){if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},getBuffer:$,getBufferSize:U,getMeta:D,getMetaDetail:function(t){return D(t,!0)},getMetaSize:P,hex:function(t){return Array.prototype.map.call(new Uint8Array(t),t=>("00"+t.toString(16)).slice(-2)).join("")},meta:function(...t){return D(v(...t))},metaBuffer:m,metaBufferArguments:w,metaDetail:function(...t){return D(v(...t),!0)},numberBuffer:g,pack:v,parseBuffer:T,parseBufferThenConcat:C,parseMetaInfo:O,parseTypeName:E,parseUint8Array:L,parseUint8ThenConcat:M,rawPack:function(...t){return $(v(...t))},readTail:N,readTypedBuffer:A,unpack:function(t,e){if(!(t instanceof Uint8Array||t instanceof ArrayBuffer))return;const r=void 0!==e,n=r?e:D(t);if(!B(n,r?t.byteLength:t.byteLength-N(t)-x))return;const i=f.Buffer.from(t),s={};let o=0;for(const[t,e,r,a]of n){const n=_(e,a),h=A(e,i,r,n);if(void 0===h)return;Object.defineProperty(s,t,{value:h,enumerable:!0,writable:!0,configurable:!0}),o=Math.max(o,r+n)}r&&o<i.byteLength&&(s.$OTHERS=i.subarray(o));let a=0,h=[];for(;Object.prototype.hasOwnProperty.call(s,a);)h.push(s[a++]);return h.length>0&&(s.args=h,s.$=s.args),s}});const j={hash:function(t){return i(F.U8(t))},hex:function(t){return F.B8(i(F.U8(t))).toString("hex")},base64:function(t){return F.B8(i(F.U8(t))).toString("base64")},hmac:function(t,e){return function(t,e){const r=new n(t).update(e),i=r.digest();return r.clean(),i}(F.U8(t),F.U8(e))}};var z,H,G,q={},V={},W={};
|
|
10
|
+
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */function Q(){return H||(H=1,W.read=function(t,e,r,n,i){var s,o,a=8*i-n-1,h=(1<<a)-1,u=h>>1,c=-7,f=r?i-1:0,l=r?-1:1,p=t[e+f];for(f+=l,s=p&(1<<-c)-1,p>>=-c,c+=a;c>0;s=256*s+t[e+f],f+=l,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=n;c>0;o=256*o+t[e+f],f+=l,c-=8);if(0===s)s=1-u;else{if(s===h)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),s-=u}return(p?-1:1)*o*Math.pow(2,s-n)},W.write=function(t,e,r,n,i,s){var o,a,h,u=8*s-i-1,c=(1<<u)-1,f=c>>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),(e+=o+f>=1?l/h:l*Math.pow(2,1-f))*h>=2&&(o++,h/=2),o+f>=c?(a=0,o=c):o+f>=1?(a=(e*h-1)*Math.pow(2,i),o+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&a,p+=d,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}),W}
|
|
11
|
+
/*!
|
|
12
|
+
* The buffer module from node.js, for the browser.
|
|
13
|
+
*
|
|
14
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
15
|
+
* @license MIT
|
|
16
|
+
*/var K=(G||(G=1,function(t){const e=function(){if(z)return V;z=1,V.byteLength=function(t){var e=s(t),r=e[0],n=e[1];return 3*(r+n)/4-n},V.toByteArray=function(t){var n,i,o=s(t),a=o[0],h=o[1],u=new r(function(t,e,r){return 3*(e+r)/4-r}(0,a,h)),c=0,f=h>0?a-4:a;for(i=0;i<f;i+=4)n=e[t.charCodeAt(i)]<<18|e[t.charCodeAt(i+1)]<<12|e[t.charCodeAt(i+2)]<<6|e[t.charCodeAt(i+3)],u[c++]=n>>16&255,u[c++]=n>>8&255,u[c++]=255&n;return 2===h&&(n=e[t.charCodeAt(i)]<<2|e[t.charCodeAt(i+1)]>>4,u[c++]=255&n),1===h&&(n=e[t.charCodeAt(i)]<<10|e[t.charCodeAt(i+1)]<<4|e[t.charCodeAt(i+2)]>>2,u[c++]=n>>8&255,u[c++]=255&n),u},V.fromByteArray=function(e){for(var r,n=e.length,i=n%3,s=[],o=16383,h=0,u=n-i;h<u;h+=o)s.push(a(e,h,h+o>u?u:h+o));return 1===i?(r=e[n-1],s.push(t[r>>2]+t[r<<4&63]+"==")):2===i&&(r=(e[n-2]<<8)+e[n-1],s.push(t[r>>10]+t[r>>4&63]+t[r<<2&63]+"=")),s.join("")};for(var t=[],e=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)t[i]=n[i],e[n.charCodeAt(i)]=i;function s(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function o(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[63&e]}function a(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(255&t[s+2]),i.push(o(n));return i.join("")}return e["-".charCodeAt(0)]=62,e["_".charCodeAt(0)]=63,V}(),r=Q(),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=o,t.SlowBuffer=function(t){return+t!=t&&(t=0),o.alloc(+t)},t.INSPECT_MAX_BYTES=50;const i=2147483647;function s(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,o.prototype),e}function o(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return u(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!o.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|p(t,e);let n=s(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(Y(t,Uint8Array)){const e=new Uint8Array(t);return f(e.buffer,e.byteOffset,e.byteLength)}return c(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Y(t,ArrayBuffer)||t&&Y(t.buffer,ArrayBuffer))return f(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(Y(t,SharedArrayBuffer)||t&&Y(t.buffer,SharedArrayBuffer)))return f(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return o.from(n,e,r);const i=function(t){if(o.isBuffer(t)){const e=0|l(t.length),r=s(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||J(t.length)?s(0):c(t):"Buffer"===t.type&&Array.isArray(t.data)?c(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return o.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function u(t){return h(t),s(t<0?0:0|l(t))}function c(t){const e=t.length<0?0:0|l(t.length),r=s(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function f(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,o.prototype),n}function l(t){if(t>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function p(t,e){if(o.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Y(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return W(t).length;default:if(i)return n?-1:q(t).length;e=(""+e).toLowerCase(),i=!0}}function d(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return v(this,e,r);case"ascii":return L(this,e,r);case"latin1":case"binary":return I(this,e,r);case"base64":return A(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function g(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function y(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),J(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=o.from(e,n)),o.isBuffer(e))return 0===e.length?-1:m(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):m(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function m(t,e,r,n,i){let s,o=1,a=t.length,h=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,a/=2,h/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){let n=-1;for(s=r;s<a;s++)if(u(t,s)===u(e,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===h)return n*o}else-1!==n&&(s-=s-n),n=-1}else for(r+h>a&&(r=a-h),s=r;s>=0;s--){let r=!0;for(let n=0;n<h;n++)if(u(t,s+n)!==u(e,n)){r=!1;break}if(r)return s}return-1}function b(t,e,r,n){r=Number(r)||0;const i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;const s=e.length;let o;for(n>s/2&&(n=s/2),o=0;o<n;++o){const n=parseInt(e.substr(2*o,2),16);if(J(n))return o;t[r+o]=n}return o}function w(t,e,r,n){return K(q(e,t.length-r),t,r,n)}function E(t,e,r,n){return K(function(t){const e=[];for(let r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function _(t,e,r,n){return K(W(e),t,r,n)}function B(t,e,r,n){return K(function(t,e){let r,n,i;const s=[];for(let o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}(e,t.length-r),t,r,n)}function A(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function v(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i<r;){const e=t[i];let s=null,o=e>239?4:e>223?3:e>191?2:1;if(i+o<=r){let r,n,a,h;switch(o){case 1:e<128&&(s=e);break;case 2:r=t[i+1],128==(192&r)&&(h=(31&e)<<6|63&r,h>127&&(s=h));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(h=(15&e)<<12|(63&r)<<6|63&n,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:r=t[i+1],n=t[i+2],a=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(h=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&a,h>65535&&h<1114112&&(s=h))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(t){const e=t.length;if(e<=S)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=S));return r}(n)}t.kMaxLength=i,o.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(t,e,r){return a(t,e,r)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(t,e,r){return function(t,e,r){return h(t),t<=0?s(t):void 0!==e?"string"==typeof r?s(t).fill(e,r):s(t).fill(e):s(t)}(t,e,r)},o.allocUnsafe=function(t){return u(t)},o.allocUnsafeSlow=function(t){return u(t)},o.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==o.prototype},o.compare=function(t,e){if(Y(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),Y(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let r=t.length,n=e.length;for(let i=0,s=Math.min(r,n);i<s;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},o.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}},o.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);let r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;const n=o.allocUnsafe(e);let i=0;for(r=0;r<t.length;++r){let e=t[r];if(Y(e,Uint8Array))i+e.length>n.length?(o.isBuffer(e)||(e=o.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!o.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},o.byteLength=p,o.prototype._isBuffer=!0,o.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)g(this,e,e+1);return this},o.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},o.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},o.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?v(this,0,t):d.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===o.compare(this,t)},o.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(t,e,r,n,i){if(Y(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let s=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(e>>>=0);const h=Math.min(s,a),u=this.slice(n,i),c=t.slice(e,r);for(let t=0;t<h;++t)if(u[t]!==c[t]){s=u[t],a=c[t];break}return s<a?-1:a<s?1:0},o.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},o.prototype.indexOf=function(t,e,r){return y(this,t,e,r,!0)},o.prototype.lastIndexOf=function(t,e,r){return y(this,t,e,r,!1)},o.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return b(this,t,e,r);case"utf8":case"utf-8":return w(this,t,e,r);case"ascii":case"latin1":case"binary":return E(this,t,e,r);case"base64":return _(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const S=4096;function L(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function I(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function T(t,e,r){const n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=e;n<r;++n)i+=X[t[n]];return i}function k(t,e,r){const n=t.slice(e,r);let i="";for(let t=0;t<n.length-1;t+=2)i+=String.fromCharCode(n[t]+256*n[t+1]);return i}function C(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function R(t,e,r,n,i,s){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function M(t,e,r,n,i){F(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,r}function U(t,e,r,n,i){F(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s>>=8,t[r+6]=s,s>>=8,t[r+5]=s,s>>=8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o>>=8,t[r+2]=o,o>>=8,t[r+1]=o,o>>=8,t[r]=o,r+8}function O(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function x(t,e,n,i,s){return e=+e,n>>>=0,s||O(t,0,n,4),r.write(t,e,n,i,23,4),n+4}function N(t,e,n,i,s){return e=+e,n>>>=0,s||O(t,0,n,8),r.write(t,e,n,i,52,8),n+8}o.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);const n=this.subarray(t,e);return Object.setPrototypeOf(n,o.prototype),n},o.prototype.readUintLE=o.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);let n=this[t],i=1,s=0;for(;++s<e&&(i*=256);)n+=this[t+s]*i;return n},o.prototype.readUintBE=o.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},o.prototype.readUint8=o.prototype.readUInt8=function(t,e){return t>>>=0,e||C(t,1,this.length),this[t]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(t,e){return t>>>=0,e||C(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(t,e){return t>>>=0,e||C(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(t,e){return t>>>=0,e||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(t,e){return t>>>=0,e||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readBigUInt64LE=Z(function(t){j(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||H(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),o.prototype.readBigUInt64BE=Z(function(t){j(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||H(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),o.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);let n=this[t],i=1,s=0;for(;++s<e&&(i*=256);)n+=this[t+s]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n},o.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);let n=e,i=1,s=this[t+--n];for(;n>0&&(i*=256);)s+=this[t+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*e)),s},o.prototype.readInt8=function(t,e){return t>>>=0,e||C(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){t>>>=0,e||C(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(t,e){t>>>=0,e||C(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(t,e){return t>>>=0,e||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return t>>>=0,e||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readBigInt64LE=Z(function(t){j(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||H(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)}),o.prototype.readBigInt64BE=Z(function(t){j(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||H(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+r)}),o.prototype.readFloatLE=function(t,e){return t>>>=0,e||C(t,4,this.length),r.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return t>>>=0,e||C(t,4,this.length),r.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return t>>>=0,e||C(t,8,this.length),r.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return t>>>=0,e||C(t,8,this.length),r.read(this,t,!1,52,8)},o.prototype.writeUintLE=o.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||R(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,s=0;for(this[e]=255&t;++s<r&&(i*=256);)this[e+s]=t/i&255;return e+r},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||R(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,s=1;for(this[e+i]=255&t;--i>=0&&(s*=256);)this[e+i]=t/s&255;return e+r},o.prototype.writeUint8=o.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,1,255,0),this[e]=255&t,e+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeBigUInt64LE=Z(function(t,e=0){return M(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Z(function(t,e=0){return U(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);R(this,t,e,r,n-1,-n)}let i=0,s=1,o=0;for(this[e]=255&t;++i<r&&(s*=256);)t<0&&0===o&&0!==this[e+i-1]&&(o=1),this[e+i]=(t/s|0)-o&255;return e+r},o.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);R(this,t,e,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===o&&0!==this[e+i+1]&&(o=1),this[e+i]=(t/s|0)-o&255;return e+r},o.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},o.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeBigInt64LE=Z(function(t,e=0){return M(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Z(function(t,e=0){return U(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeFloatLE=function(t,e,r){return x(this,t,e,!0,r)},o.prototype.writeFloatBE=function(t,e,r){return x(this,t,e,!1,r)},o.prototype.writeDoubleLE=function(t,e,r){return N(this,t,e,!0,r)},o.prototype.writeDoubleBE=function(t,e,r){return N(this,t,e,!1,r)},o.prototype.copy=function(t,e,r,n){if(!o.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);const i=n-r;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,r,n):Uint8Array.prototype.set.call(t,this.subarray(r,n),e),i},o.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){const e=t.charCodeAt(0);("utf8"===n&&e<128||"latin1"===n)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;let i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{const s=o.isBuffer(t)?t:o.from(t,n),a=s.length;if(0===a)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<r-e;++i)this[i+e]=s[i%a]}return this};const P={};function $(t,e,r){P[t]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function D(t){let e="",r=t.length;const n="-"===t[0]?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function F(t,e,r,n,i,s){if(t>r||t<e){const r="bigint"==typeof e?"n":"";let n;throw n=0===e||e===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(s+1)}${r}`:`>= -(2${r} ** ${8*(s+1)-1}${r}) and < 2 ** ${8*(s+1)-1}${r}`,new P.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,r){j(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||H(e,t.length-(r+1))}(n,i,s)}function j(t,e){if("number"!=typeof t)throw new P.ERR_INVALID_ARG_TYPE(e,"number",t)}function H(t,e,r){if(Math.floor(t)!==t)throw j(t,r),new P.ERR_OUT_OF_RANGE("offset","an integer",t);if(e<0)throw new P.ERR_BUFFER_OUT_OF_BOUNDS;throw new P.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${e}`,t)}$("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),$("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function q(t,e){let r;e=e||1/0;const n=t.length;let i=null;const s=[];for(let o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function W(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function K(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Y(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function J(t){return t!=t}const X=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Z(t){return"undefined"==typeof BigInt?tt:t}function tt(){throw new Error("BigInt not supported")}}(q)),q);let Y={SERVER_TIME_NONCE:176,AUTH_REQ:177,AUTH_RES:178,AUTH_FAIL:179,ENC_PACK:182,ENC_E2E:183,ENC_488:184};for(let t in Y)Y[Y[t]]=t;const J={SERVER_TIME_NONCE:F.meta(F.MB("header","8",0),F.MB("unixTime","32L",0),F.MB("milTime","16L",0),F.MB("counter","16L",0),F.MB("nonce",K.Buffer.alloc(4))),AUTH_REQ:F.meta(F.MB("header","8",0),F.MB("id8",K.Buffer.alloc(8)),F.MB("nonce",K.Buffer.alloc(4)),F.MB("hmac32",K.Buffer.alloc(32))),AUTH_RES:F.meta(F.MB("header","8",0),F.MB("hmac32",K.Buffer.alloc(32))),ENC_PACK:F.meta(F.MB("type","8",0),F.MB("len","32L",0),F.MB("salt12",K.Buffer.alloc(12)),F.MB("hmac",8,0)),ENC_488:F.meta(F.MB("type","8",0),F.MB("len","32L",0),F.MB("otpSrc8",K.Buffer.alloc(8)),F.MB("hmac8",K.Buffer.alloc(8)))};function X(t){let e=t[t.length-1];return e[2]+e[3]}const Z={SERVER_TIME_NONCE:X(J.SERVER_TIME_NONCE),AUTH_REQ:X(J.AUTH_REQ),AUTH_RES:X(J.AUTH_RES),ENC_PACK:X(J.ENC_PACK),ENC_488:X(J.ENC_488)};function tt(t,e){if(!(t instanceof Uint8Array&&e instanceof Uint8Array&&t.length===e.length))return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return 0===r}function et(t,e,r,n,i=!1){if(!(t instanceof Uint8Array))return;const s=K.Buffer.from(t);return s.length<r||s[0]!==e||(i?s.readUInt32LE(1)!==s.length-r:s.length!==r)?void 0:F.unpack(s,n)}function rt(t){return globalThis.crypto.getRandomValues(K.Buffer.alloc(t))}class nt{constructor(){this._id8=K.Buffer.alloc(8),this._otpSrc44=K.Buffer.alloc(44),this._otp36=K.Buffer.alloc(36),this._hmac=K.Buffer.alloc(32),this.auth_salt12=K.Buffer.alloc(12),this.localNonce=K.Buffer.alloc(4),this.remoteNonce=K.Buffer.alloc(4),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}clearAuth(){this._id8.fill(0),this._otpSrc44.fill(0),this._otp36.fill(0),this._hmac.fill(0),this.auth_salt12.fill(0),this.localNonce.fill(0),this.remoteNonce.fill(0),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}set_hash_id8(t){F.B8(j.hash(t)).copy(this._id8,0,0,8)}set_id8(t){let e=F.B8(t);this._id8.fill(0),e.copy(this._id8,0,0,8)}set_key(t){const e=F.B8(t);if(!e||0===e.length)throw new TypeError("Key must not be empty");this.copy_key(F.B8(j.hash(e)))}set_id_key(t){let e=t.indexOf(".");if(-1==e)return;let r=t.substring(0,e),n=t.substring(e+1);this.set_id8(r),this.set_key(n)}copy_id8(t){t.copy(this._id8,0,0,8)}copy_key(t){if(!(t instanceof Uint8Array)||32!==t.length)throw new TypeError("copy_key requires exactly 32 bytes");this._otpSrc44.set(t,0),this._hasKey=!0}sha256_n(t,e){let r=j.hash(t);for(let t=0;t<e;t++)r=j.hash(r);return r}set_clock_rand(){this.set_clock_nonce(rt(4))}set_clock_nonce(t){if(!(t instanceof Uint8Array)||4!==t.length)throw new TypeError("Nonce must be 4 bytes");let e=Math.max(Date.now(),this._lastSendTime);if(this.counter=this.counter+1&65535,0===this.counter&&e===this._lastSendTime&&e++,!Number.isSafeInteger(e)||e<0||Math.floor(e/1e3)>4294967295)throw new RangeError("Clock is outside the protocol range");this._lastSendTime=e,K.Buffer.concat([F.NB("32L",Math.floor(e/1e3)),F.NB("16L",e%1e3),F.NB("16L",this.counter),K.Buffer.from(t)]).copy(this._otpSrc44,32)}_requireKey(){if(!this._hasKey)throw new Error("Set a key before encryption or authentication")}set_salt12(t,e){if(12!=t.byteLength)throw TypeError("set_salt12: Invalid salt12 byteLength.");t.copy(this._otpSrc44,32)}resetOTP(){this._requireKey(),F.B8(j.hash(this._otpSrc44)).copy(this._otp36,0,0,32)}getIndexOTP(t){return this._otp36.writeUInt32LE(t,32),j.hash(this._otp36)}generateHMAC(t){this._requireKey();let e=K.Buffer.concat([this._otpSrc44,t]);this._hmac=F.B8(j.hash(e))}getHMAC8(t){this._requireKey();let e=K.Buffer.concat([this._otpSrc44,t]);return this._hmac=F.B8(j.hash(e)),this._hmac.subarray(0,8)}xotp(t,e=0,r=!1){let n=(t=F.B8(t,r)).byteLength,i=e,s=0,o=0;for(;n>0;){o=n<32?n:32;let e=this.getIndexOTP(++i);for(let r=0;r<o;r++)t[s++]^=e[r];n-=32}return t}server_time_nonce(){const t=Date.now(),e=Math.floor(t/1e3),r=t%1e3;return this.localNonce=rt(4),this.auth_salt12=K.Buffer.concat([F.NB("32L",e),F.NB("16L",r),rt(2),this.localNonce]),K.Buffer.concat([F.NB("8",Y.SERVER_TIME_NONCE),this.auth_salt12])}auth_req(t){if(!this._hasKey)return!1;let e=et(t,Y.SERVER_TIME_NONCE,Z.SERVER_TIME_NONCE,J.SERVER_TIME_NONCE);if(e&&e.milTime>=1e3)return!1;if(e){let t=K.Buffer.concat([F.NB("32L",e.unixTime),F.NB("16L",e.milTime),F.NB("16L",e.counter),e.nonce]);return this.set_salt12(t,"auth_req"),this.localNonce=rt(4),this.generateHMAC(this.localNonce),this.remoteNonce=e.nonce,F.pack(F.MB("#header","8",Y.AUTH_REQ),F.MB("#id8",this._id8),F.MB("#nonce",this.localNonce),F.MB("#hmac32",this._hmac))}return!1}verify_auth_req(t){if(!this._hasKey)return!1;let e;if(t instanceof Uint8Array?e=et(t,Y.AUTH_REQ,Z.AUTH_REQ,J.AUTH_REQ):t&&"object"==typeof t&&(e=t),!e||e.header!==Y.AUTH_REQ||!(e.id8 instanceof Uint8Array)||8!==e.id8.length||!(e.nonce instanceof Uint8Array)||4!==e.nonce.length||!(e.hmac32 instanceof Uint8Array)||32!==e.hmac32.length||e.$OTHERS&&0!==e.$OTHERS.length)return!1;this.set_salt12(this.auth_salt12,"verify_auth_req 1/2"),this.generateHMAC(e.nonce);let r=this._hmac;if(tt(e.hmac32,r)){this.remoteNonce=K.Buffer.from(e.nonce);let t=K.Buffer.concat([this.localNonce,this.remoteNonce,this.localNonce]);this.set_salt12(t,"verify_auth_req 2/2"),this.generateHMAC(e.nonce);let r=this._hmac,n=F.rawPack(F.MB("header","8",Y.AUTH_RES),F.MB("hmac32",r));return this.isAuthorized=!0,n}return!1}verify_auth_res(t){if(!this._hasKey)return!1;let e=et(t,Y.AUTH_RES,Z.AUTH_RES,J.AUTH_RES);if(e){let t=K.Buffer.concat([this.remoteNonce,this.localNonce,this.remoteNonce]);if(this.set_salt12(t,"verify_auth_res"),this.generateHMAC(this.localNonce),tt(this._hmac,e.hmac32))return this.isAuthorized=!0,!0}}encrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;t=F.B8(t),this.set_clock_nonce(this.remoteNonce),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return F.pack(F.MB("#type","8",Y.ENC_488),F.MB("#len","32L",t.byteLength),F.MB("#otpSrc8",this._otpSrc44.subarray(32,40)),F.MB("#hmac8",e),F.MB("#xdata",r))}decrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;let e=t;if(t instanceof Uint8Array&&t[0]===Y.ENC_E2E){if(t.length<Z.ENC_488)return;const r=K.Buffer.from(t),n=r.readUInt32LE(1);if(n>r.length-Z.ENC_488)return;e=K.Buffer.from(r.subarray(0,Z.ENC_488+n)),e[0]=Y.ENC_488}const r=et(e,Y.ENC_488,Z.ENC_488,J.ENC_488,!0);if(!(r&&(n=r.otpSrc8,n.readUInt16LE(4)<1e3)))return;var n;this.set_salt12(K.Buffer.concat([r.otpSrc8,this.localNonce]),"decrypt_488"),this.resetOTP();const i=this.xotp(r.$OTHERS??K.Buffer.alloc(0));return tt(this.getHMAC8(i),r.hmac8)?i:void 0}encryptPack(t){this._requireKey(),t=F.B8(t),this.set_clock_rand(),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return F.pack(F.MB("#type","8",Y.ENC_PACK),F.MB("#len","32L",t.byteLength),F.MB("#salt12",this._otpSrc44.subarray(32)),F.MB("#hmac8",e),F.MB("#xdata",r))}decryptPack(t){if(!this._hasKey)return;const e=et(t,Y.ENC_PACK,Z.ENC_PACK,J.ENC_PACK,!0);if(!e)return;this.set_salt12(e.salt12,"decryptPack"),this.resetOTP();const r=this.xotp(e.$OTHERS??K.Buffer.alloc(0));return tt(e.hmac,this.getHMAC8(r))?(e.data=r,e):void 0}encrypt_e2e(t,e){return this._withKey(e,()=>this.encryptPack(t))}decrypt_e2e(t,e){return this._withKey(e,()=>this.decryptPack(t))}_withKey(t,e){const r=F.B8(t);if(!r||0===r.length)throw new TypeError("Key must not be empty");const n=[K.Buffer.from(this._otpSrc44),K.Buffer.from(this._otp36),K.Buffer.from(this._hmac)],i=this._hasKey;try{return this._otpSrc44.set(j.hash(r),0),this._hasKey=!0,e()}finally{this._otpSrc44.set(n[0]),this._otp36.set(n[1]),this._hmac.set(n[2]),this._hasKey=i;for(const t of n)t.fill(0)}}}nt.RAND=rt,nt.BohoMsg=Y,nt.Meta=J,nt.MetaSize=Z,nt.sha256=j,nt.MBP=F,nt.Buffer=K.Buffer,void 0===globalThis.Buffer&&(globalThis.Buffer=nt.Buffer);const it=/^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;function st(t){return"string"==typeof t&&it.test(t)}function ot(t){if("string"!=typeof t||!t.includes(":"))return!1;let e=(t=t.split("%")[0]).slice(t.lastIndexOf(":")+1);if(e.includes(".")){if(!st(e))return!1;t=t.slice(0,t.lastIndexOf(":")+1)+"0:0"}if((t.match(/::/g)||[]).length>1)return!1;const r=t.split("::"),n=r.flatMap(t=>t?t.split(":"):[]);return!!n.every(t=>/^[0-9a-fA-F]{1,4}$/.test(t))&&(2===r.length?n.length<8:8===n.length)}function at(t){return st(t)?4:ot(t)?6:0}var ht={isIP:at,isIPv4:st,isIPv6:ot,createServer:function(){throw new Error("net.createServer is not available in the browser (do not pass `congPort`)")}};var ut={createServer:function(){throw new Error("http.createServer is not available in the browser (do not pass `dashboard`)")}};function ct(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ft,lt={exports:{}};var pt=(ft||(ft=1,function(t){var e=Object.prototype.hasOwnProperty,r="~";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function s(t,e,n,s,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new i(n,s||t,o),h=r?r+e:e;return t._events[h]?t._events[h].fn?t._events[h]=[t._events[h],a]:t._events[h].push(a):(t._events[h]=a,t._eventsCount++),t}function o(t,e){0===--t._eventsCount?t._events=new n:delete t._events[e]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var t,n,i=[];if(0===this._eventsCount)return i;for(n in t=this._events)e.call(t,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},a.prototype.listeners=function(t){var e=r?r+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o},a.prototype.listenerCount=function(t){var e=r?r+t:t,n=this._events[e];return n?n.fn?1:n.length:0},a.prototype.emit=function(t,e,n,i,s,o){var a=r?r+t:t;if(!this._events[a])return!1;var h,u,c=this._events[a],f=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),f){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,i),!0;case 5:return c.fn.call(c.context,e,n,i,s),!0;case 6:return c.fn.call(c.context,e,n,i,s,o),!0}for(u=1,h=new Array(f-1);u<f;u++)h[u-1]=arguments[u];c.fn.apply(c.context,h)}else{var l,p=c.length;for(u=0;u<p;u++)switch(c[u].once&&this.removeListener(t,c[u].fn,void 0,!0),f){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,e);break;case 3:c[u].fn.call(c[u].context,e,n);break;case 4:c[u].fn.call(c[u].context,e,n,i);break;default:if(!h)for(l=1,h=new Array(f-1);l<f;l++)h[l-1]=arguments[l];c[u].fn.apply(c[u].context,h)}}return!0},a.prototype.on=function(t,e,r){return s(this,t,e,r,!1)},a.prototype.once=function(t,e,r){return s(this,t,e,r,!0)},a.prototype.removeListener=function(t,e,n,i){var s=r?r+t:t;if(!this._events[s])return this;if(!e)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==e||i&&!a.once||n&&a.context!==n||o(this,s);else{for(var h=0,u=[],c=a.length;h<c;h++)(a[h].fn!==e||i&&!a[h].once||n&&a[h].context!==n)&&u.push(a[h]);u.length?this._events[s]=1===u.length?u[0]:u:o(this,s)}return this},a.prototype.removeAllListeners=function(t){var e;return t?(e=r?r+t:t,this._events[e]&&o(this,e)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,t.exports=a}(lt)),lt.exports),dt=ct(pt);const gt="local:",yt=Symbol.for("iosignal-local.servers");function mt(){return globalThis[yt]??=new Map}function bt(t){return"iosignal-local:"+t}const wt=new Set;"function"==typeof addEventListener&&"undefined"!=typeof window&&addEventListener("pagehide",()=>{for(const t of[...wt])t.close(1001,"page closed")});class Et{constructor(t){this.kind=t,this.onframe=null,this.closed=!1,wt.add(this)}receive(t){!this.closed&&t&&"string"==typeof t.t&&this.onframe?.(t)}close(t=1e3,e=""){this.closed||(this.post({t:"close",code:t,reason:e}),this.dispose())}dispose(){this.closed=!0,wt.delete(this)}}class _t extends Et{constructor(t){super("MessageChannel"),this.port=t,t.onmessage=t=>this.receive(t.data)}post(t){if(this.closed)return;const e=t.d instanceof ArrayBuffer?[t.d]:[];this.port.postMessage(t,e)}dispose(){this.closed||(super.dispose(),this.port.onmessage=null,setTimeout(()=>this.port.close(),0))}}class Bt extends Et{constructor(t,e){super("BroadcastChannel"),this.side=e,this.channel=new BroadcastChannel(t),this.channel.onmessage=t=>{t.data?.from!==this.side&&this.receive(t.data)}}post(t){this.closed||this.channel.postMessage({...t,from:this.side})}dispose(){this.closed||(super.dispose(),this.channel.onmessage=null,this.channel.close())}}function At(t){return new Promise((e,r)=>{const n=setTimeout(()=>{t.onframe=null,t.dispose(),r(new Error("no server answered"))},1500);t.onframe=r=>{"open"===r.t&&(clearTimeout(n),t.onframe=null,e(t))}})}function vt(t){const e=new Error(`listen EADDRINUSE: ${gt}//${t}`);return e.code="EADDRINUSE",e.syscall="listen",e}class St extends dt{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;constructor(t,e,r){super(),this.link=t,this.wss=e,this.transport=r.transport,this.readyState=1,this.bufferedAmount=0,this.bytesWritten=0,this.bytesRead=0,this.onclose=null,t.onframe=t=>this.frame(t)}frame(t){switch(t.t){case"data":{if(1!==this.readyState)return;const e="string"!=typeof t.d,r=e?Buffer.from(t.d):Buffer.from(t.d,"utf8");this.bytesRead+=r.byteLength,this.wss.around("rx",this,r,e,()=>this.emit("message",r,e));break}case"ping":this.link.post({t:"pong"}),this.emit("ping");break;case"pong":this.emit("pong");break;case"close":this.link.dispose(),this.finish(t.code??1005,t.reason??"")}}send(t,e,r){if("function"==typeof e&&(r=e,e=void 0),1!==this.readyState)return;let n;if("string"==typeof t||!1===e?.binary)n="string"==typeof t?t:(new TextDecoder).decode(t);else{const e=t instanceof ArrayBuffer?new Uint8Array(t):t,r=new Uint8Array(e.byteLength);r.set(e),n=r.buffer,this.bytesWritten+=r.byteLength}this.wss.emit("local:tx",this,t),this.link.post({t:"data",d:n}),r?.()}ping(){1===this.readyState&&this.link.post({t:"ping"})}pong(){1===this.readyState&&this.link.post({t:"pong"})}close(t=1e3,e=""){this.readyState>=2||(this.readyState=2,this.link.close(t,e),setTimeout(()=>this.finish(t,e),0))}terminate(){3!==this.readyState&&(this.readyState=2,this.link.close(1006,""),setTimeout(()=>this.finish(1006,""),0))}finish(t,e){3!==this.readyState&&(this.readyState=3,this.wss.clients.delete(this),this.wss.around("close",this,t,e,()=>{this.emit("close",t,e),this.onclose?.({code:t,reason:e,target:this})}))}}class Lt extends dt{constructor(t={}){if(super(),t.server)throw new Error("WebSocketServer({ server }) is not available in the browser: use { port }");this.options=t,this.clients=new Set,this.stopListening=null,this.closed=!1;const e=0===t.port?1+Math.floor(65534*Math.random()):t.port;this._port=e,this.address_=String(e)+(t.path?"/"+String(t.path).replace(/^\/+|\/+$/g,""):""),async function(t,e){const r=mt();if(r.has(t))throw vt(t);let n=null;if(globalThis.navigator?.locks&&(n=await new Promise((e,r)=>{globalThis.navigator.locks.request(bt(t),{ifAvailable:!0},n=>{if(n)return new Promise(t=>e(t));r(vt(t))}).catch(r)})),r.has(t))throw n?.(),vt(t);const i=(t,r)=>{t.post({t:"open"}),e(t,r)};r.set(t,{accept:i});let s=null;return"function"==typeof BroadcastChannel&&(s=new BroadcastChannel(bt(t)),s.onmessage=e=>{const{t:r,id:n,ip:s}=e.data??{};if("connect"!==r||"string"!=typeof n||n.length>64)return;const o="string"==typeof s&&s.length<=64?s:void 0;i(new Bt(`${bt(t)}:${n}`,"s"),{transport:"BroadcastChannel",ip:o})}),function(){r.get(t)?.accept===i&&r.delete(t),s&&(s.onmessage=null,s.close()),n?.()}}(this.address_,(t,e)=>this.accept(t,e)).then(t=>{this.closed?t():(this.stopListening=t,this.emit("listening"))}).catch(t=>this.emit("error",t))}get url(){return"local://"+this.address_}address(){return{port:this._port,address:this.url,family:"local"}}accept(t,e){const r=new St(t,this,e);this.clients.add(r);const n={headers:{origin:globalThis.location?.origin??""},socket:{remoteAddress:e.ip??"127.0.0.1"},url:"/"+(this.options.path??"")};this.around("connection",r,n,e,()=>this.emit("connection",r,n))}around(t,e,r,n,i){this.emit("local:"+t,e,r,n);try{i()}finally{this.emit("local:"+t+":end",e)}}close(t){this.closed=!0,this.stopListening?.(),this.stopListening=null;for(const t of[...this.clients])t.terminate();setTimeout(()=>{this.emit("close"),t?.()},0)}}var It,Tt,kt,Ct={},Rt={},Mt={};
|
|
17
|
+
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */function Ut(){return Tt||(Tt=1,Mt.read=function(t,e,r,n,i){var s,o,a=8*i-n-1,h=(1<<a)-1,u=h>>1,c=-7,f=r?i-1:0,l=r?-1:1,p=t[e+f];for(f+=l,s=p&(1<<-c)-1,p>>=-c,c+=a;c>0;s=256*s+t[e+f],f+=l,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=n;c>0;o=256*o+t[e+f],f+=l,c-=8);if(0===s)s=1-u;else{if(s===h)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),s-=u}return(p?-1:1)*o*Math.pow(2,s-n)},Mt.write=function(t,e,r,n,i,s){var o,a,h,u=8*s-i-1,c=(1<<u)-1,f=c>>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),(e+=o+f>=1?l/h:l*Math.pow(2,1-f))*h>=2&&(o++,h/=2),o+f>=c?(a=0,o=c):o+f>=1?(a=(e*h-1)*Math.pow(2,i),o+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&a,p+=d,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}),Mt}
|
|
18
|
+
/*!
|
|
19
|
+
* The buffer module from node.js, for the browser.
|
|
20
|
+
*
|
|
21
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
22
|
+
* @license MIT
|
|
23
|
+
*/var Ot=(kt||(kt=1,function(t){const e=function(){if(It)return Rt;It=1,Rt.byteLength=function(t){var e=s(t),r=e[0],n=e[1];return 3*(r+n)/4-n},Rt.toByteArray=function(t){var n,i,o=s(t),a=o[0],h=o[1],u=new r(function(t,e,r){return 3*(e+r)/4-r}(0,a,h)),c=0,f=h>0?a-4:a;for(i=0;i<f;i+=4)n=e[t.charCodeAt(i)]<<18|e[t.charCodeAt(i+1)]<<12|e[t.charCodeAt(i+2)]<<6|e[t.charCodeAt(i+3)],u[c++]=n>>16&255,u[c++]=n>>8&255,u[c++]=255&n;return 2===h&&(n=e[t.charCodeAt(i)]<<2|e[t.charCodeAt(i+1)]>>4,u[c++]=255&n),1===h&&(n=e[t.charCodeAt(i)]<<10|e[t.charCodeAt(i+1)]<<4|e[t.charCodeAt(i+2)]>>2,u[c++]=n>>8&255,u[c++]=255&n),u},Rt.fromByteArray=function(e){for(var r,n=e.length,i=n%3,s=[],o=16383,h=0,u=n-i;h<u;h+=o)s.push(a(e,h,h+o>u?u:h+o));return 1===i?(r=e[n-1],s.push(t[r>>2]+t[r<<4&63]+"==")):2===i&&(r=(e[n-2]<<8)+e[n-1],s.push(t[r>>10]+t[r>>4&63]+t[r<<2&63]+"=")),s.join("")};for(var t=[],e=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)t[i]=n[i],e[n.charCodeAt(i)]=i;function s(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function o(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[63&e]}function a(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(255&t[s+2]),i.push(o(n));return i.join("")}return e["-".charCodeAt(0)]=62,e["_".charCodeAt(0)]=63,Rt}(),r=Ut(),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=o,t.SlowBuffer=function(t){return+t!=t&&(t=0),o.alloc(+t)},t.INSPECT_MAX_BYTES=50;const i=2147483647;function s(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,o.prototype),e}function o(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return u(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!o.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|p(t,e);let n=s(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(W(t,Uint8Array)){const e=new Uint8Array(t);return f(e.buffer,e.byteOffset,e.byteLength)}return c(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(W(t,ArrayBuffer)||t&&W(t.buffer,ArrayBuffer))return f(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(W(t,SharedArrayBuffer)||t&&W(t.buffer,SharedArrayBuffer)))return f(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return o.from(n,e,r);const i=function(t){if(o.isBuffer(t)){const e=0|l(t.length),r=s(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||Q(t.length)?s(0):c(t):"Buffer"===t.type&&Array.isArray(t.data)?c(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return o.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function u(t){return h(t),s(t<0?0:0|l(t))}function c(t){const e=t.length<0?0:0|l(t.length),r=s(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function f(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,o.prototype),n}function l(t){if(t>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function p(t,e){if(o.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||W(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return q(t).length;default:if(i)return n?-1:G(t).length;e=(""+e).toLowerCase(),i=!0}}function d(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return v(this,e,r);case"ascii":return L(this,e,r);case"latin1":case"binary":return I(this,e,r);case"base64":return A(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function g(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function y(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=o.from(e,n)),o.isBuffer(e))return 0===e.length?-1:m(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):m(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function m(t,e,r,n,i){let s,o=1,a=t.length,h=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,a/=2,h/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){let n=-1;for(s=r;s<a;s++)if(u(t,s)===u(e,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===h)return n*o}else-1!==n&&(s-=s-n),n=-1}else for(r+h>a&&(r=a-h),s=r;s>=0;s--){let r=!0;for(let n=0;n<h;n++)if(u(t,s+n)!==u(e,n)){r=!1;break}if(r)return s}return-1}function b(t,e,r,n){r=Number(r)||0;const i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;const s=e.length;let o;for(n>s/2&&(n=s/2),o=0;o<n;++o){const n=parseInt(e.substr(2*o,2),16);if(Q(n))return o;t[r+o]=n}return o}function w(t,e,r,n){return V(G(e,t.length-r),t,r,n)}function E(t,e,r,n){return V(function(t){const e=[];for(let r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function _(t,e,r,n){return V(q(e),t,r,n)}function B(t,e,r,n){return V(function(t,e){let r,n,i;const s=[];for(let o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}(e,t.length-r),t,r,n)}function A(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function v(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i<r;){const e=t[i];let s=null,o=e>239?4:e>223?3:e>191?2:1;if(i+o<=r){let r,n,a,h;switch(o){case 1:e<128&&(s=e);break;case 2:r=t[i+1],128==(192&r)&&(h=(31&e)<<6|63&r,h>127&&(s=h));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(h=(15&e)<<12|(63&r)<<6|63&n,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:r=t[i+1],n=t[i+2],a=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(h=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&a,h>65535&&h<1114112&&(s=h))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(t){const e=t.length;if(e<=S)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=S));return r}(n)}t.kMaxLength=i,o.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(t,e,r){return a(t,e,r)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(t,e,r){return function(t,e,r){return h(t),t<=0?s(t):void 0!==e?"string"==typeof r?s(t).fill(e,r):s(t).fill(e):s(t)}(t,e,r)},o.allocUnsafe=function(t){return u(t)},o.allocUnsafeSlow=function(t){return u(t)},o.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==o.prototype},o.compare=function(t,e){if(W(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),W(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let r=t.length,n=e.length;for(let i=0,s=Math.min(r,n);i<s;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},o.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}},o.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);let r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;const n=o.allocUnsafe(e);let i=0;for(r=0;r<t.length;++r){let e=t[r];if(W(e,Uint8Array))i+e.length>n.length?(o.isBuffer(e)||(e=o.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!o.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},o.byteLength=p,o.prototype._isBuffer=!0,o.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)g(this,e,e+1);return this},o.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},o.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},o.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?v(this,0,t):d.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===o.compare(this,t)},o.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(t,e,r,n,i){if(W(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let s=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(e>>>=0);const h=Math.min(s,a),u=this.slice(n,i),c=t.slice(e,r);for(let t=0;t<h;++t)if(u[t]!==c[t]){s=u[t],a=c[t];break}return s<a?-1:a<s?1:0},o.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},o.prototype.indexOf=function(t,e,r){return y(this,t,e,r,!0)},o.prototype.lastIndexOf=function(t,e,r){return y(this,t,e,r,!1)},o.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return b(this,t,e,r);case"utf8":case"utf-8":return w(this,t,e,r);case"ascii":case"latin1":case"binary":return E(this,t,e,r);case"base64":return _(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const S=4096;function L(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function I(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function T(t,e,r){const n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=e;n<r;++n)i+=K[t[n]];return i}function k(t,e,r){const n=t.slice(e,r);let i="";for(let t=0;t<n.length-1;t+=2)i+=String.fromCharCode(n[t]+256*n[t+1]);return i}function C(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function R(t,e,r,n,i,s){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function M(t,e,r,n,i){F(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,r}function U(t,e,r,n,i){F(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s>>=8,t[r+6]=s,s>>=8,t[r+5]=s,s>>=8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o>>=8,t[r+2]=o,o>>=8,t[r+1]=o,o>>=8,t[r]=o,r+8}function O(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function x(t,e,n,i,s){return e=+e,n>>>=0,s||O(t,0,n,4),r.write(t,e,n,i,23,4),n+4}function N(t,e,n,i,s){return e=+e,n>>>=0,s||O(t,0,n,8),r.write(t,e,n,i,52,8),n+8}o.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);const n=this.subarray(t,e);return Object.setPrototypeOf(n,o.prototype),n},o.prototype.readUintLE=o.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);let n=this[t],i=1,s=0;for(;++s<e&&(i*=256);)n+=this[t+s]*i;return n},o.prototype.readUintBE=o.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},o.prototype.readUint8=o.prototype.readUInt8=function(t,e){return t>>>=0,e||C(t,1,this.length),this[t]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(t,e){return t>>>=0,e||C(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(t,e){return t>>>=0,e||C(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(t,e){return t>>>=0,e||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(t,e){return t>>>=0,e||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readBigUInt64LE=Y(function(t){j(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||z(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),o.prototype.readBigUInt64BE=Y(function(t){j(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||z(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),o.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);let n=this[t],i=1,s=0;for(;++s<e&&(i*=256);)n+=this[t+s]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n},o.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);let n=e,i=1,s=this[t+--n];for(;n>0&&(i*=256);)s+=this[t+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*e)),s},o.prototype.readInt8=function(t,e){return t>>>=0,e||C(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){t>>>=0,e||C(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(t,e){t>>>=0,e||C(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(t,e){return t>>>=0,e||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return t>>>=0,e||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readBigInt64LE=Y(function(t){j(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||z(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)}),o.prototype.readBigInt64BE=Y(function(t){j(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||z(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+r)}),o.prototype.readFloatLE=function(t,e){return t>>>=0,e||C(t,4,this.length),r.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return t>>>=0,e||C(t,4,this.length),r.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return t>>>=0,e||C(t,8,this.length),r.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return t>>>=0,e||C(t,8,this.length),r.read(this,t,!1,52,8)},o.prototype.writeUintLE=o.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||R(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,s=0;for(this[e]=255&t;++s<r&&(i*=256);)this[e+s]=t/i&255;return e+r},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||R(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,s=1;for(this[e+i]=255&t;--i>=0&&(s*=256);)this[e+i]=t/s&255;return e+r},o.prototype.writeUint8=o.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,1,255,0),this[e]=255&t,e+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeBigUInt64LE=Y(function(t,e=0){return M(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Y(function(t,e=0){return U(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);R(this,t,e,r,n-1,-n)}let i=0,s=1,o=0;for(this[e]=255&t;++i<r&&(s*=256);)t<0&&0===o&&0!==this[e+i-1]&&(o=1),this[e+i]=(t/s|0)-o&255;return e+r},o.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);R(this,t,e,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===o&&0!==this[e+i+1]&&(o=1),this[e+i]=(t/s|0)-o&255;return e+r},o.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},o.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeBigInt64LE=Y(function(t,e=0){return M(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Y(function(t,e=0){return U(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeFloatLE=function(t,e,r){return x(this,t,e,!0,r)},o.prototype.writeFloatBE=function(t,e,r){return x(this,t,e,!1,r)},o.prototype.writeDoubleLE=function(t,e,r){return N(this,t,e,!0,r)},o.prototype.writeDoubleBE=function(t,e,r){return N(this,t,e,!1,r)},o.prototype.copy=function(t,e,r,n){if(!o.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);const i=n-r;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,r,n):Uint8Array.prototype.set.call(t,this.subarray(r,n),e),i},o.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){const e=t.charCodeAt(0);("utf8"===n&&e<128||"latin1"===n)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;let i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{const s=o.isBuffer(t)?t:o.from(t,n),a=s.length;if(0===a)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<r-e;++i)this[i+e]=s[i%a]}return this};const P={};function $(t,e,r){P[t]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function D(t){let e="",r=t.length;const n="-"===t[0]?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function F(t,e,r,n,i,s){if(t>r||t<e){const r="bigint"==typeof e?"n":"";let n;throw n=0===e||e===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(s+1)}${r}`:`>= -(2${r} ** ${8*(s+1)-1}${r}) and < 2 ** ${8*(s+1)-1}${r}`,new P.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,r){j(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||z(e,t.length-(r+1))}(n,i,s)}function j(t,e){if("number"!=typeof t)throw new P.ERR_INVALID_ARG_TYPE(e,"number",t)}function z(t,e,r){if(Math.floor(t)!==t)throw j(t,r),new P.ERR_OUT_OF_RANGE("offset","an integer",t);if(e<0)throw new P.ERR_BUFFER_OUT_OF_BOUNDS;throw new P.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${e}`,t)}$("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),$("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function G(t,e){let r;e=e||1/0;const n=t.length;let i=null;const s=[];for(let o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function q(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function V(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function W(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function Q(t){return t!=t}const K=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Y(t){return"undefined"==typeof BigInt?J:t}function J(){throw new Error("BigInt not supported")}}(Ct)),Ct);const xt=new TextEncoder,Nt=new TextDecoder,Pt=$t;function $t(t,e=0){let r;if(void 0===t||"string"!=typeof t||"number"!=typeof e)throw TypeError("invlaid init variablie type name. ");if((t=t.toUpperCase()).includes("8"))r=Ot.Buffer.alloc(1),t.includes("I")?r.writeInt8(e):r.writeUint8(e);else if(t.includes("16"))r=Ot.Buffer.alloc(2),t.includes("I")?t.includes("L")?r.writeInt16LE(e):r.writeInt16BE(e):t.includes("L")?r.writeUint16LE(e):r.writeUint16BE(e);else if(t.includes("32"))r=Ot.Buffer.alloc(4),t.includes("I")?t.includes("L")?r.writeInt32LE(e):r.writeInt32BE(e):t.includes("L")?r.writeUint32LE(e):r.writeUint32BE(e);else if(t.includes("F"))r=Ot.Buffer.alloc(4),t.includes("L")?r.writeFloatLE(e):r.writeFloatBE(e);else{if(!t.includes("N"))throw TypeError(`invalid number type: ${t}`);r=Ot.Buffer.from(String(e))}return r}const Dt=Ft;function Ft(t,e,r){let n,i="B";if("number"==typeof e)"number"==typeof r?(n=Ot.Buffer.alloc(e),0!==r&&n.fill(r),i="B"):(n=Ot.Buffer.from(String(e)),i="N");else if("string"==typeof e&&"number"==typeof r)i=e.toUpperCase(),n=$t(e,r);else if("string"==typeof e&&void 0===r)n=Ot.Buffer.from(e),i="S";else if(e instanceof Uint8Array&&void 0===r)n=e instanceof Ot.Buffer?e:Ot.Buffer.from(e);else if(e instanceof ArrayBuffer&&void 0===r)n=Ot.Buffer.from(e);else if(ArrayBuffer.isView(e))n=Ot.Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if("object"==typeof e&&void 0===r)n=Ot.Buffer.from(JSON.stringify(e)),i="O";else{if("boolean"!=typeof e||void 0!==r)throw TypeError("invalid meta buffer type");{const t=e?1:0;n=Ot.Buffer.from([t]),i="!"}}return"string"==typeof t&&t.includes("#")&&(t=""),[t,i,n]}const jt=zt;function zt(...t){let e=0;return t.map(t=>{const r=e++;return"number"==typeof t?Dt(r,"N",t):Dt(r,t)})}function Ht(t){if((t=t.toUpperCase()).includes("8"))return t.includes("I")?"int8":"uint8";if(t.includes("16"))return t.includes("I")?t.includes("L")?"int16_le":"int16_be":t.includes("L")?"uint16_le":"uint16_be";if(t.includes("32"))return t.includes("I")?t.includes("L")?"int32_le":"int32_be":t.includes("L")?"uint32_le":"uint32_be";if(t.includes("F"))return t.includes("L")?"float_le":"float_be";if("B"===t)return"buffer";if("S"===t)return"string";if("N"===t)return"number";if("O"===t)return"object";if("!"===t)return"boolean";throw TypeError("invalid data type")}function Gt(t,e){const r=Ht(t),n=/^(u?int)8$/.test(r)||"boolean"===r?1:/^(u?int)16_/.test(r)?2:/^(u?int)32_|^float_/.test(r)?4:void 0;if(void 0===e&&(e=n),!Number.isSafeInteger(e)||e<0||void 0!==n&&e!==n)throw TypeError("invalid field length");return e}function qt(t,e){if(!Array.isArray(t))return!1;try{for(const r of t){if(!Array.isArray(r)||r.length<3||r.length>5)return!1;const[t,n,i,s]=r;if("string"!=typeof t&&!(Number.isSafeInteger(t)&&t>=0))return!1;const o=Gt(n,s);if(!Number.isSafeInteger(i)||i<0||i>e||o>e-i)return!1}return!0}catch{return!1}}function Vt(t,e,r,n){try{if(n=Gt(t,n),!Number.isSafeInteger(r)||r<0||r>e.byteLength||n>e.byteLength-r)return;const i=Ht(t);if("int8"==i)return e.readInt8(r);if("uint8"===i)return e.readUint8(r);if("int16_le"===i)return e.readInt16LE(r);if("int16_be"===i)return e.readInt16BE(r);if("uint16_le"===i)return e.readUint16LE(r);if("uint16_be"===i)return e.readUint16BE(r);if("int32_le"===i)return e.readInt32LE(r);if("int32_be"===i)return e.readInt32BE(r);if("uint32_le"===i)return e.readUint32LE(r);if("uint32_be"===i)return e.readUint32BE(r);if("float_le"===i)return e.readFloatLE(r);if("float_be"===i)return e.readFloatBE(r);if("buffer"===i)return e.subarray(r,r+n);if("string"===i){const t=e.subarray(r,r+n);return Nt.decode(t)}if("number"===i){const t=e.subarray(r,r+n);return Number(Nt.decode(t))}if("object"===i){const t=e.subarray(r,r+n);return JSON.parse(Nt.decode(t))}return"boolean"===i?1===e.readInt8(r):void 0}catch(t){}}function Wt(...t){const e=function(t){let e=[];return t.filter(t=>{if(!Array.isArray(t[0]))return t;e=e.concat(t)}).concat(e)}(t);let r=0;const n=[];let i,s,o=0;if(e.forEach(t=>{const[e,i,s]=t;r+=s.byteLength,("number"==typeof e||e.length>0)&&n.push([e,i,o,s.byteLength]),o=r}),n.length>0){let t=JSON.stringify(n);i=xt.encode(t),s=i.byteLength,r=r+s+2}const a=Ot.Buffer.alloc(r);if(o=0,e.forEach(t=>{const e=t[2];a.set(e,o),o+=e.byteLength}),n.length>0){a.set(i,o);const t=Pt("16",s);return a.set(t,o+s),a}return a}const Qt=Kt;function Kt(t,e=!1){if(void 0===t)throw TypeError("Invalid data type: Undefined");if("string"==typeof t)return xt.encode(t);if("number"==typeof t)return Uint8Array.from([t]);if(t instanceof ArrayBuffer){if(e)return new Uint8Array(t);{const e=new Uint8Array(t),r=new Uint8Array(t.byteLength);return r.set(e),r}}if(ArrayBuffer.isView(t)){if(e)return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);{const e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=new Uint8Array(t.byteLength);return r.set(e),r}}return xt.encode(JSON.stringify(t))}const Yt=Jt;function Jt(t,e=!1){const r=Kt(t,e);return e?Ot.Buffer.from(r.buffer,r.byteOffset,r.byteLength):Ot.Buffer.from(r)}const Xt=Zt;function Zt(...t){const e=t.map(t=>Jt(t));return Ot.Buffer.concat(e)}const te=ee;function ee(...t){try{let e=0,r=0;const n=t.map(t=>Kt(t));n.forEach(t=>{e+=t.byteLength});const i=new Uint8Array(e);return n.forEach(t=>{i.set(t,r),r+=t.byteLength}),i}catch(t){console.log(t)}}function re(t){return 0===oe(t)?t.byteLength:t.byteLength-oe(t)-ie}function ne(t,e=se(t)){try{if(t instanceof ArrayBuffer&&(t=Ot.Buffer.from(t)),!(t instanceof Uint8Array))return;if(!Number.isSafeInteger(e)||e<=0||e>t.byteLength-ie)return;const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),n=r.byteLength-e-ie,i=JSON.parse(Nt.decode(r.subarray(n,r.byteLength-ie)));if(!qt(i,n)||0===i.length)return;return i}catch{return}}const ie=2;function se(t){return t instanceof ArrayBuffer&&(t=Ot.Buffer.from(t)),t instanceof Uint8Array?t.byteLength<=ie?0:new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(t.byteLength-ie):0}function oe(t){if(t instanceof ArrayBuffer&&(t=Ot.Buffer.from(t)),t instanceof Uint8Array){const e=t.byteLength;if(e<=ie)return 0;const r=se(t);return 0===r||r>e?0:ne(t,r)?r:0}return 0}function ae(t){const e=re(t);return t.subarray(0,e)}function he(t,e=!1){t instanceof ArrayBuffer&&(t=Ot.Buffer.from(t));const r=se(t);if(0===r)return;let n=ne(t,r);return n?e?(n.forEach(t=>{null==t[3]&&(t[1].includes("8")?t[3]=1:t[1].includes("16")?t[3]=2:t[1].includes("32")||t[1].includes("F")?t[3]=4:t[1].includes("!")&&(t[3]=1)),t[4]=Ht(t[1])}),n):n:void 0}var ue=Object.freeze({__proto__:null,B8:Yt,B8pack:Xt,Buffer:Ot.Buffer,MB:Dt,MBA:jt,NB:Pt,TAIL_LEN:ie,U8:Qt,U8pack:te,equal:function(t,e){if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},getBuffer:ae,getBufferSize:re,getMeta:he,getMetaDetail:function(t){return he(t,!0)},getMetaSize:oe,hex:function(t){return Array.prototype.map.call(new Uint8Array(t),t=>("00"+t.toString(16)).slice(-2)).join("")},meta:function(...t){return he(Wt(...t))},metaBuffer:Ft,metaBufferArguments:zt,metaDetail:function(...t){return he(Wt(...t),!0)},numberBuffer:$t,pack:Wt,parseBuffer:Jt,parseBufferThenConcat:Zt,parseMetaInfo:ne,parseTypeName:Ht,parseUint8Array:Kt,parseUint8ThenConcat:ee,rawPack:function(...t){return ae(Wt(...t))},readTail:se,readTypedBuffer:Vt,unpack:function(t,e){if(!(t instanceof Uint8Array||t instanceof ArrayBuffer))return;const r=void 0!==e,n=r?e:he(t);if(!qt(n,r?t.byteLength:t.byteLength-se(t)-ie))return;const i=Ot.Buffer.from(t),s={};let o=0;for(const[t,e,r,a]of n){const n=Gt(e,a),h=Vt(e,i,r,n);if(void 0===h)return;Object.defineProperty(s,t,{value:h,enumerable:!0,writable:!0,configurable:!0}),o=Math.max(o,r+n)}r&&o<i.byteLength&&(s.$OTHERS=i.subarray(o));let a=0,h=[];for(;Object.prototype.hasOwnProperty.call(s,a);)h.push(s[a++]);return h.length>0&&(s.args=h,s.$=s.args),s}});const ce=globalThis.performance,fe=1,le=2,pe=3,de=4;function ge(t,e,r){let n=e.byteLength,i=0;for(;n--;)t.rxi++,0==e[i++]&&t.rxi_zero++;if(t.skipBytes>0){if(e.byteLength<=t.skipBytes)return void(t.skipBytes-=e.byteLength);e=e.subarray(t.skipBytes),t.skipBytes=0}t.buffer.byteLength>0?t.buffer=Buffer.concat([t.buffer,e]):t.buffer=e,function(t,e){for(;t.buffer.byteLength>0;){const r=t.buffer[0];let n,i;if(r===fe){if(n=2,t.buffer.byteLength<n)return;i=t.buffer.readUint8(1)}else if(r===le){if(n=3,t.buffer.byteLength<n)return;i=t.buffer.readUint16LE(1)}else if(r===pe){if(n=4,t.buffer.byteLength<n)return;i=t.buffer.readUint16LE(1)+65536*t.buffer.readUint8(3)}else{if(r!==de)return e("wrong",t.buffer),void(t.buffer=Buffer.alloc(0));if(n=5,t.buffer.byteLength<n)return;i=t.buffer.readUint32LE(1)}if(i>t.maxFrameSize){e("oversize",i);const r=t.buffer.byteLength-n;if(r<i)return t.skipBytes=i-r,void(t.buffer=Buffer.alloc(0));t.buffer=t.buffer.subarray(n+i);continue}const s=n+i;if(t.buffer.byteLength<s)return;if(t.frames.push(t.buffer.subarray(n,s)),t.buffer.byteLength===s)return void(t.buffer=Buffer.alloc(0));t.buffer=t.buffer.subarray(s)}}(t,r)}class ye{constructor({maxFrameSize:t=1/0,onFrame:e=null,onWrong:r=null,onOversize:n=null}={}){this.buffer=Buffer.alloc(0),this.frames=[],this.rxi=0,this.rxi_zero=0,this.maxFrameSize=t,this.skipBytes=0,this.onFrame=e,this.onWrong=r,this.onOversize=n}write(t){ge(this,t,(t,e)=>{"wrong"===t?this.onWrong?.(e):this.onOversize?.(e)});const e=this.frames;this.frames=[];for(const t of e)this.onFrame?.(t)}clear(){this.onFrame=this.onWrong=this.onOversize=null,this.buffer=Buffer.alloc(0),this.frames=[]}}const me={heartbeatInterval:5e4,heartbeatGrace:5e3,maxPayload:33554432,trustProxy:"private",maxBufferedBytes:67108864,membersOnly:!1,logMessages:!1,logStats:0,security:{maxClockSkewMs:6e4,authChallengeMaxAgeMs:6e4,maxReplayEntries:65536,requireEncryption:!1},quotas:{anonymous:{maxMessageBytes:262144,fanout:1e3,msgPerSec:100,bytesPerSec:2097152,maxConnections:null,maxSubscriptions:1e3},basic:{maxMessageBytes:1048576,fanout:1e3,msgPerSec:200,bytesPerSec:4194304,maxConnections:20,maxSubscriptions:2e3},pro:{maxMessageBytes:4194304,fanout:1e4,msgPerSec:1e3,bytesPerSec:16777216,maxConnections:200,maxSubscriptions:1e4},unlimited:{maxMessageBytes:null,fanout:null,msgPerSec:null,bytesPerSec:null,maxConnections:null,maxSubscriptions:null}},anonymousQuota:"anonymous",retain:{enabled:!0,limitSize:1e5,limitCounter:1e3,tagsPerOwner:32,bytesPerOwner:1048576,anonymousGraceMs:36e5,bytesPerConnection:1048576,bytesTotal:268435456},fileLogger:{connection:{use:!1,path:"connection.log"},auth:{use:!1,path:"auth.log"},attack:{use:!1,path:"attack.log"}},auth:{failDelay:600,maxFailuresPerConnection:5,maxFailuresPerAddress:30,failureWindowMs:6e4,duplicateLogin:"keepNew"},debug:{slow:!1,delay:500,showAuthInfo:!1}},be={CONNECTING:0,OPEN:1,SERVER_READY:10,AUTH_REQ:11,AUTH_RES:12,AUTH_FAIL:13,AUTH_CLEAR:14,CID_REQ:17,CID_RES:18,READY:19,CLOSING:2,CLOSED:3,STOP:4,REDIRECTING:5};for(let t in be)be[be[t]]=t;let we={NO:0,YES:1,AUTO:2};for(let t in we)we[we[t]]=t;const Ee={TAG_LEN1:255,TAG_LEN2:65535,CONNECTION_CHECKER_PERIOD:3e3,CLIENT_PING_PERIOD:4e4,PONG_TIMEOUT:15e3,RECONNECT_JITTER:1e3,RECONNECT_BASE:3e3,RECONNECT_MAX:3e4,SERVER_HELLO_TIMEOUT:15e3,PROMISE_TIMEOUT:5e3,DID:8,CID:12};let _e={EMPTY:0,TEXT:1,BINARY:2,OBJECT:3,MJSON:4,MBA:5};for(let t in _e)_e[_e[t]]=t;let Be={SERVER_READY:192,CID_REQ:193,CID_RES:194,AUTH_CLEAR:196,SERVER_REDIRECT:197,QUOTA:198,LOOP:203,ECHO:204,PING:205,PONG:206,CLOSE:207,SIGNAL:208,SIGNAL_REQ:209,SIGNAL_E2E:210,SUBSCRIBE:211,SUBSCRIBE_REQ:212,UNSUBSCRIBE:213,SERVER_SIGNAL:214,IAM:217,IAM_RES:218,SET:219,RESPONSE_MBP:221,CALL:222,FLOW_MODE:240,WAIT:241,RESUME:242,TIME_OUT:253,OVER_SIZE:254,OVER_FLOW:255};for(let t in Be)Be[Be[t]]=t;var Ae=Object.freeze({__proto__:null,ENC_MODE:we,IOMsg:Be,PAYLOAD_TYPE:_e,SIZE_LIMIT:Ee,STATE:be,STATUS:{OK:0,ERROR:255}});const ve=new TextDecoder,Se=new Set([Be.SIGNAL,Be.SIGNAL_E2E,Be.SUBSCRIBE,Be.SUBSCRIBE_REQ,Be.UNSUBSCRIBE,Be.CALL,Be.IAM]);ue.NB;const Le=ue.MB,Ie={[Be.AUTH_CLEAR]:"AUTH_CLEAR",[Be.SERVER_REDIRECT]:"SERVER_REDIRECT",253:"CONG_UNKNOWN_TYPE",254:"CONG_OVER_SIZE",255:"CONG_OVER_FLOW"};class Te{constructor(t,e){this.socket=t,t.isAlive=!0,t.txCounter=0,t.rxCounter=0,t.openTime=Date.now(),this.boho=new nt,this.security=e.server.security,this._challengeIssuedAt=null,this._challengeUsed=!1,this.authFailures=0,this._replayBuckets=new Map,this._replayEntries=0,this._replayExpiredBefore=0,this.securityFailure=null,this.closeReason=null,this.encMode=we.AUTO,this.channels=new Set,this.retain_signal=new Map,this.retainBytes=0,this.ssid=Te.ssid++,this.manager=e,this.cid="",this.did="",this.uid="",this.nick="",this.site="",this.privateNode=!1,this.HOME_CHANNEL="",this.role="anonymous",this.accountUid=null,this.ownerUid=null,this.rxPolicy=null,this.quotaName=e.anonymousQuota,this.quota=e.quotas[this.quotaName],this._rateAt=null,this._msgTokens=0,this._byteTokens=0,this.peerRxLimit=null,this.peerRxLimitSkipped=0,this.state,this.stateLog=[],this.setState(be.OPEN)}static ssid=1;get isAdmin(){return"admin"===this.role&&!0===this.boho.isAuthorized}setState(t){const e=this.state;this.state=t,e!==t&&this.manager.server?.emit("remote:state",this,e),me.debug.showAuthInfo&&(this.stateLog.push(t+":"+be[t]),t==be.AUTH_RES?console.log("[auth success]",this.cid,this.stateLog.join(">")):t==be.AUTH_FAIL&&console.log("[auth_fail]",this.stateLog.join(">")))}getState(){return this.state}getStateName(){return be[this.state].toLowerCase()}logMessage(t,e,r=!1){if(t===Be.PING||t===Be.PONG)return;let n="";try{if([Be.SIGNAL,Be.SIGNAL_E2E,Be.SUBSCRIBE,Be.UNSUBSCRIBE].includes(t))n=ve.decode(e.subarray(2,2+e[1]));else if(t===Be.SUBSCRIBE_REQ&&e.byteLength>=5)n=ve.decode(e.subarray(5,5+e.readUInt16BE(3)));else if(t===Be.CALL){const t=ue.unpack(e);t&&(n=`${t.target}.${t.topic}`)}}catch{}const i=void 0===t?"TEXT":Be[t]??nt.BohoMsg[t]??"0x"+t.toString(16),s="websocket"===this.socketType?"WS":"CS";console.log(`[rx] #${this.ssid} ${this.cid||"-"} ${s} ${i}${r?"(enc)":""}${n?" "+n:""} ${e.byteLength}B`)}setQuota(t,e){if(this.quotaName=t,this.quota=this.manager.quotas[t],this.refreshRxFrameLimit?.(),e){const t=Buffer.alloc(5);t[0]=Be.QUOTA,t.writeUInt32LE(this.quota.maxMessageBytes??0,1),this.send(t)}}takeRateTokens(t){const{msgPerSec:e,bytesPerSec:r}=this.quota;if(null===e&&null===r)return!0;const n=ce.now();if(null===this._rateAt)this._msgTokens=e??0,this._byteTokens=r??0;else{const t=(n-this._rateAt)/1e3;null!==e&&(this._msgTokens=Math.min(e,this._msgTokens+t*e)),null!==r&&(this._byteTokens=Math.min(r,this._byteTokens+t*r))}return this._rateAt=n,!(null!==e&&this._msgTokens<1)&&(!(null!==r&&this._byteTokens<Math.min(t,r))&&(null!==e&&(this._msgTokens-=1),null!==r&&(this._byteTokens-=t),!0))}rxQuotaChecker(t){let e=t.byteLength;this.manager.counters.rxBytes+=e,this.manager.counters.rxMessages++;const r=this.quota.maxMessageBytes;return null!==r&&e>r?(this.manager.counters.oversizeRejected++,this.send(Buffer.from([Be.OVER_SIZE])),!1):!!this.takeRateTokens(e)||(this.manager.counters.rateLimited++,!1)}issueAuthChallenge(){const t=this.boho.server_time_nonce();return this._challengeIssuedAt=ce.now(),t}securityMismatch(t){return this._closing||this.state===be.CLOSED||(this.securityFailure=t,this.boho.clearAuth(),this.role="anonymous",this._replayBuckets.clear(),this._replayEntries=0,this.close(!0),this.manager.attackLogger?.log(`SECURITY #${this.ssid} reason:${t}`),this.manager.server.emit("security:mismatch",this,t)),!1}checkAuthChallenge(){return!this._closing&&this.state!==be.CLOSED&&(this._challengeUsed?this.securityMismatch("AUTH_CHALLENGE_REUSED"):!(null===this._challengeIssuedAt||ce.now()-this._challengeIssuedAt>this.security.authChallengeMaxAgeMs)||this.securityMismatch("AUTH_CHALLENGE_EXPIRED"))}acceptEncryptedClock(t,e){const r=t.readUInt32LE(5),n=t.readUInt16LE(9),i=t.readUInt16LE(11),s=1e3*r+n,o=e-this.security.maxClockSkewMs;if(n>=1e3||Math.abs(e-s)>this.security.maxClockSkewMs||s<this._replayExpiredBefore)return this.securityMismatch("TIME_MISMATCH");this._replayExpiredBefore=Math.max(this._replayExpiredBefore,o);for(const[t,e]of this._replayBuckets)1e3*(t+1)<=this._replayExpiredBefore&&(this._replayEntries-=e.size,this._replayBuckets.delete(t));let a=this._replayBuckets.get(r);const h=65536*n+i;return a?.has(h)?this.securityMismatch("REPLAY_DETECTED"):this._replayEntries>=this.security.maxReplayEntries?this.securityMismatch("REPLAY_CAPACITY_EXCEEDED"):(a||this._replayBuckets.set(r,a=new Set),a.add(h),this._replayEntries++,!0)}decryptSessionPacket(t,e){let r;try{r=this.boho.decrypt_488(t)}catch{return void this.securityMismatch("INVALID_ENCRYPTED_PACKET")}if(r)return this.acceptEncryptedClock(t,e)?r:void 0;this.securityMismatch("INVALID_ENCRYPTED_PACKET")}onTimeDelayMessage(t,e=!0){const r=Date.now();setTimeout(()=>{this.onSocketMessage(t,e,r)},me.debug.delay)}onSocketMessage(t,e=!0,r=Date.now()){if(this._closing||this.state===be.CLOSED)return;if(this.receiveMonitor(),!this.rxQuotaChecker(t))return;const n=this.manager.server?.logMessages;let i,s,o=!1;if(e){if(i=t[0],i===nt.BohoMsg.ENC_488){if(s=this.decryptSessionPacket(t,r),!s)return;i=s[0],t=s,o=!0}else if(i===nt.BohoMsg.ENC_E2E){if(s=this.decryptSessionPacket(t,r),!s)return;i=s[0],t.set(s,nt.MetaSize.ENC_488),t=t.subarray(nt.MetaSize.ENC_488),o=!0}if(!o&&this.security.requireEncryption&&this.boho.isAuthorized&&!this.TLS&&Se.has(i))return void this.securityMismatch("PLAINTEXT_AFTER_LOGIN");switch(n&&this.logMessage(i,t,o),i){case Be.PING:this.send(Buffer.from([Be.PONG]));break;case Be.PONG:break;case Be.CID_REQ:if(![be.SERVER_READY,be.AUTH_RES,be.AUTH_FAIL,be.CID_RES].includes(this.state))return console.log("CID_REQ before SERVER_READY"),void this.close();if(t.byteLength>=5){const e=(t[1]|t[2]<<8|t[3]<<16)+16777216*t[4];e>0&&(this.peerRxLimit=e)}if(!this.cid){const t=this.manager.issueAnonymousCid();if(!t)return console.log("anonymous CID space exhausted"),void this.close();this.cid=t,this.manager.cid2remote.set(this.cid,this),this.setQuota(this.quotaName,!0)}this.send_enc_mode(ue.pack(Le("#cid_ack","8",Be.CID_RES),Le("#cid",this.cid))),this.setState(be.CID_RES);break;case Be.ECHO:t.byteLength<30&&this.send(t,e);break;case Be.IAM:t.byteLength>1&&t.byteLength<30&&(this.nick=ve.decode(t.subarray(1))),this.iamResponse();break;case Be.SIGNAL_E2E:case Be.SIGNAL:if(t.byteLength>=3){let e=t.readUInt8(1);if(t.byteLength>=e+2){let r=t.subarray(2,2+e);r=ve.decode(r),this.manager.sender(r,this,t)}}break;case Be.UNSUBSCRIBE:if(2==t.byteLength)this.manager.unsubscribe([""],this);else if(t.byteLength>=3){let e=t.readUInt8(1);if(t.byteLength==e+2){let r=t.subarray(2,2+e);r=ve.decode(r);let n=r.split(",");this.manager.unsubscribe(n,this)}}break;case Be.SUBSCRIBE:if(t.byteLength>=3){let e=t.readUInt8(1);if(t.byteLength==e+2){let r=t.subarray(2,2+e);r=ve.decode(r);let n=r.split(",");this.manager.subscribe(n,this)}}break;case Be.SUBSCRIBE_REQ:if(t.byteLength>=6){let e=t.readUInt16BE(1),r=t.readUInt16BE(3);if(t.byteLength==r+5){let n=t.subarray(5,5+r);n=ve.decode(n);let i=n.split(",");const s=this.subscriptionsRejected??0;if(!1===this.manager.subscribe(i,this))return;this.response(e,(this.subscriptionsRejected??0)>s?255:0)}else this.response(e,255)}break;case Be.CALL:try{let e=ue.unpack(t);if(e){if(!e.target||!e.topic)return;this.manager.server.serviceNames.has(e.target)&&this.manager.server.emit(e.target,this,e)}}catch(t){console.log("request catch error",t)}break;case Be.CLOSE:this.closeReason=function(t){if(t.byteLength<2)return"none";if(2===t.byteLength){const e="0x"+t[1].toString(16).padStart(2,"0");return Ie[t[1]]?`${Ie[t[1]]}(${e})`:e}return ve.decode(t.subarray(1))}(t),console.log(`>> CLOSE #${this.ssid} cid:${this.cid} reason: ${this.closeReason}`),this.close();break;case nt.BohoMsg.AUTH_REQ:if(!this.manager.authManager)return void this.send(Buffer.from([nt.BohoMsg.AUTH_FAIL]));if(this.state===be.AUTH_REQ)return void this.securityMismatch("AUTH_IN_PROGRESS");if(![be.SERVER_READY,be.AUTH_RES,be.AUTH_FAIL,be.CID_RES].includes(this.state))return console.log("protocol error. must called auth_req after server_ready"),void this.close();if(!this.checkAuthChallenge())return;return this.setState(be.AUTH_REQ),void this.manager.authManager.verify_auth_req(t,this).then(t=>{t?.name&&this.manager.deligateSignal(this,"@$name",t.name)}).catch(t=>{console.log("authInfo return fail.",t)})}}else{n&&this.logMessage(void 0,t);try{let e=ve.decode(t);this.manager.server.emit("text_message",e,this)}catch(t){}}}response(t,e,r){r?this.send_enc_mode(ue.pack(Le("#type","8",Be.RESPONSE_MBP),Le("status","8",e),Le("mid","16",t),Le("body",r))):this.send_enc_mode(ue.pack(Le("#type","8",Be.RESPONSE_MBP),Le("status","8",e),Le("mid","16",t)))}send_enc_mode(t,e=!1){if((this.encMode===we.YES||this.encMode===we.AUTO&&!this.TLS&&this.boho.isAuthorized)&&(e=!0),e&&t[0]==Be.SIGNAL_E2E){let e=t[1],r=this.boho.encrypt_488(t.subarray(0,3+e));r[0]=nt.BohoMsg.ENC_E2E;let n=Buffer.concat([r,t.subarray(3+e)]);this.send(n)}else if(e){let e=this.boho.encrypt_488(t);e&&this.send(e)}else this.send(t)}iamResponse(t=""){if(""==t){let e=[];for(let t of this.channels.keys())e.push(t);t={ssid:this.ssid,cid:this.cid,did:this.did,uid:this.uid,role:this.role,quota:this.quotaName,nick:this.nick,ip:this.ip,tag:e}}let e=ue.pack(Le("#MsgType","8",Be.IAM_RES),Le("#info",t));this.send_enc_mode(e)}}function ke(t){if(!ot(t))return null;const e=(t=t.split("%")[0]).lastIndexOf(":")+1,r=t.slice(e);if(st(r)){const[n,i,s,o]=r.split(".").map(Number);t=t.slice(0,e)+(n<<8|i).toString(16)+":"+(s<<8|o).toString(16)}const n=t=>t?t.split(":").map(t=>parseInt(t,16)):[],[i,s]=t.split("::"),o=n(i),a=n(s),h=[...o,...new Array(8-o.length-a.length).fill(0),...a],u=Buffer.alloc(16);return h.forEach((t,e)=>u.writeUInt16BE(t,2*e)),u}function Ce(t){const[e,r]=t.split(".").map(Number);return 0===e||127===e||10===e||172===e&&r>=16&&r<=31||192===e&&168===r}function Re(t){if(st(t))return Ce(t);const e=ke(t);return!!e&&(!!(e.subarray(0,15).every(t=>0===t)&&e[15]<=1)||(e.subarray(0,10).every(t=>0===t)&&255===e[10]&&255===e[11]?Ce(e.subarray(12).join(".")):252==(254&e[0])||254===e[0]&&128==(192&e[1])))}const Me=new TextDecoder;function Ue(t,e){if(!e||"string"!=typeof t)return;const r=t.split(",").map(t=>t.trim()).filter(Boolean);return r[Math.max(0,r.length-e)]}function Oe(t){if("string"==typeof t)return t.startsWith("::ffff:")&&st(t.slice(7))&&(t=t.slice(7)),"::1"===t&&(t="127.0.0.1"),at(t)?t:void 0}function xe(t,e=me.trustProxy){return"private"===e?t&&Re(t)?1:0:!0===e?1:Number.isSafeInteger(e)&&e>0?e:0}class Ne extends Te{constructor(t,e,r){if(super(t,r),this.txQueuePeakBytes=0,this.txWriteFalseCount=0,this.txBlockedSince=null,this.txDrainMaxMs=0,this.socketType=t.socketType,"websocket"===this.socketType){const{ip:t,TLS:r}=function(t,e=me.trustProxy){const r=Oe(t.socket?.remoteAddress),n=xe(r,e);return{ip:Oe(Ue(t.headers["x-forwarded-for"],n))??r??"0.0.0.0",TLS:"https"===Ue(t.headers["x-forwarded-proto"],n)}}(e,this.manager.server?.trustProxy);this.ip=t,this.TLS=r,this.site=function(t){const e=t?.headers?.origin;if("string"!=typeof e||!e||"null"===e||e.length>512)return"";try{return new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"").slice(0,253)}catch{return""}}(e)}else this.TLS=!1,this.ip=Oe(t.remoteAddress)??"0.0.0.0";var n;Re(this.ip)?(this.HOME_CHANNEL="PRIVATE:",this.privateNode=!0):ot(this.ip)?this.HOME_CHANNEL="IP6:"+(n=this.ip,ke(n)?.subarray(0,8).toString("hex")??null):this.HOME_CHANNEL="IP:"+function(t){let e=t.split(".");return Buffer.from(e).toString("hex")}(this.ip),"websocket"===this.socketType?(me.debug.slow?t.on("message",this.onTimeDelayMessage.bind(this)):t.on("message",this.onSocketMessage.bind(this)),t.on("pong",this.receiveMonitor.bind(this)),t.on("ping",this.receiveMonitor.bind(this)),t.on("error",t=>{console.log("Websocket error",t,t.code)}),t.onclose=e=>{t.removeAllListeners(),this.manager.removeRemote(this)}):(t.on("drain",()=>{null!==this.txBlockedSince&&(this.txDrainMaxMs=Math.max(this.txDrainMaxMs,ce.now()-this.txBlockedSince),this.txBlockedSince=null)}),this.congRx=new ye({maxFrameSize:this.rxFrameLimit(),onFrame:(me.debug.slow?this.onTimeDelayMessage:this.onSocketMessage).bind(this),onWrong:this.onWrongCongPacketMessage.bind(this),onOversize:this.onOversizeCongPacket.bind(this)}),t.on("data",t=>{this.congRx.write(t)}),t.on("error",t=>{console.log("TCP Socket error",t)}),t.on("close",e=>{t.removeAllListeners(),this.congRx.clear(),this.manager.removeRemote(this)}))}onWrongCongPacketMessage(t){if(this.cid);else{let e="";try{e=Me.decode(t)}catch(r){e+="Len: "+t.byteLength}if(this.manager.attackLogger){let t=`> ${this.ssid} ${this.ip} ${e}`;this.manager.attackLogger.log(t)}this.close(!0)}}rxFrameLimit(){const t=this.manager.server?.maxPayload??me.maxPayload,e=this.quota?.maxMessageBytes??null;return null===e?t:Math.min(t,e)}refreshRxFrameLimit(){this.congRx&&(this.congRx.maxFrameSize=this.rxFrameLimit())}onOversizeCongPacket(t){if(!this._closing){if(!this.cid)return this.manager.attackLogger?.log(`> ${this.ssid} ${this.ip} OVERSIZE ${t}`),void this.close(!0);this.manager.counters.oversizeRejected++,this.send(Buffer.from([Be.OVER_SIZE]))}}receiveMonitor(){this.socket.rxCounter++,!1===this.socket.isAlive&&this.manager.heartbeatPending.delete(this),this.socket.isAlive=!0}trustedProxyHops(t){return xe(t,this.manager.server?.trustProxy)}ping(){"websocket"===this.socketType?(this.socket.ping(),this.socket.txCounter++):this.send(Buffer.from([Be.PING]))}pong(){"websocket"===this.socketType?(this.socket.pong(),this.socket.txCounter++):this.send(Buffer.from([Be.PONG]))}getTraffic(){let t=this.socket.bytesWritten||this.socket._socket?.bytesWritten,e=this.socket.bytesRead||this.socket._socket?.bytesRead;return{tx:this.socket.txCounter,txb:t,rx:this.socket.rxCounter,rxb:e}}close(t=!1){this._closing=!0,"websocket"===this.socketType?t?this.socket.terminate():this.socket.close():t?this.socket.destroy():this.socket.end()}recordTxQueue(){const t=this.socket.bufferedAmount??this.socket.writableLength??0;t>this.txQueuePeakBytes&&(this.txQueuePeakBytes=t);t>(this.manager.server?.maxBufferedBytes??me.maxBufferedBytes)&&(console.log(`slow peer #${this.ssid} cid:${this.cid} has ${t} unsent bytes: closing`),this.close(!0))}send(t,e){if(!this._closing){if(null!==this.peerRxLimit&&t.byteLength>this.peerRxLimit)return this.peerRxLimitSkipped++,void this.manager.counters.peerRxLimitSkipped++;if(this.manager.counters.txBytes+=t.byteLength,this.manager.counters.txMessages++,this.socket.txCounter++,"websocket"===this.socketType)1===this.socket.readyState?(null!=e?this.socket.send(t,{binary:e}):this.socket.send(t),this.recordTxQueue()):(console.log("server(ws)Remote.send() called. not open state. current readyState:",this.socket.readyState),this.close(!0));else if("open"==this.socket.readyState){const e=this.socket.write(function(t){if(null==t.byteLength&&(t=Buffer.from(t)),t.byteLength<256)return ue.pack(ue.MB("#type","8",fe),ue.MB("#payloadLen1","8",t.byteLength),ue.MB("#payload",t));if(t.byteLength<65536)return ue.pack(ue.MB("#type","8",le),ue.MB("#payloadLen2","16L",t.byteLength),ue.MB("#payload",t));if(t.byteLength<2**24){let e=Buffer.alloc(4);e.writeUint32LE(t.byteLength);let r=e.subarray(0,3);return ue.pack(ue.MB("#type","8",pe),ue.MB("#payloadLen3",r),ue.MB("#payload",t))}return ue.pack(ue.MB("#type","8",de),ue.MB("#payloadLen4","32L",t.byteLength),ue.MB("#payload",t))}(t));this.recordTxQueue(),e||(this.txWriteFalseCount++,null===this.txBlockedSince&&(this.txBlockedSince=ce.now()))}else console.log("server(cong)Remote.send() called. not open state. current readyState:",this.socket.readyState),this.close(!0)}}}const Pe=new TextEncoder;function $e(t,...e){if("string"!=typeof t)throw TypeError("tag should be string.");let r=Pe.encode(t);if(r.byteLength>Ee.TAG_LEN1)throw TypeError("tag UTF-8 byte length exceeds 255");let n,i=function(t){let e,r;if(0==t.length)e=_e.EMPTY,r=null;else if(1==t.length)if("string"==typeof t[0]||"number"==typeof t[0])e=_e.TEXT,r=Pe.encode(t[0]+"."),r[r.byteLength-1]=0;else if(ArrayBuffer.isView(t[0])||t[0]instanceof ArrayBuffer)e=_e.BINARY,r=ue.B8(t[0]);else{if("object"!=typeof t[0])throw new Error("unknown payload arguments");e=_e.OBJECT,r=Pe.encode(JSON.stringify(t[0]))}else{let n=!1;t.forEach(t=>{(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)&&(n=!0)}),n?e=_e.MBA:(e=_e.MJSON,r=Pe.encode(JSON.stringify(t)))}return{type:e,buffer:r}}(e);if(i.type==_e.EMPTY)n=ue.pack(ue.MB("#MsgType","8",Be.SIGNAL),ue.MB("#tagLen","8",r.byteLength),ue.MB("#tag",r),ue.MB("#payloadType","8",i.type));else if(i.type==_e.MBA){let t=ue.pack(ue.MBA(...e));n=ue.pack(ue.MB("#MsgType","8",Be.SIGNAL),ue.MB("#tagLen","8",r.byteLength),ue.MB("#tag",r),ue.MB("#payloadType","8",i.type),ue.MB("#mbaBuffer",t))}else n=ue.pack(ue.MB("#MsgType","8",Be.SIGNAL),ue.MB("#tagLen","8",r.byteLength),ue.MB("#tag",r),ue.MB("#payloadType","8",i.type),ue.MB("#payload",i.buffer));return n}const De=new TextDecoder;function Fe(t,e){switch(t){case _e.EMPTY:return[];case _e.TEXT:{const t=0===e[e.byteLength-1]?e.byteLength-1:e.byteLength;return[De.decode(e.subarray(0,t))]}case _e.BINARY:return[e];case _e.OBJECT:return[JSON.parse(De.decode(e))];case _e.MJSON:{const t=JSON.parse(De.decode(e));if(!Array.isArray(t))throw new TypeError("MJSON payload is not an array");return t}case _e.MBA:{const t=ue.unpack(e);if(!t)throw new TypeError("malformed MBA payload");return t.args}default:return null}}const je=t=>()=>{throw new Error(`fs.${t} is not available in the browser`)};var ze={openSync:je("openSync"),write:je("write"),readFileSync:je("readFileSync"),readFile:async()=>je("readFile")()};const He=new Intl.DateTimeFormat("ko-KR",{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1,timeZone:"Asia/Seoul"});class Ge{constructor(t){this.file=ze.openSync(t,"a+"),console.log("new FileLogger logFile: ",t,this.file)}log(t){let e=He.format(new Date)+" "+t+"\n";ze.write(this.file,e,t=>{if(t)throw t})}}const qe=1048576;function Ve(t){return t>=qe?(t/qe).toFixed(1)+"MB":t>=1024?(t/1024).toFixed(1)+"KB":Math.round(t)+"B"}class We{constructor(t){this.manager=t,this.previous=null}close(){this.previous=null}snapshot(){const t=this.manager;let e=0,r=0;for(const n of t.remotes)n.boho.isAuthorized&&e++,"websocket"===n.socketType&&r++;const n=t.remotes.size,i=function(){const t=globalThis.performance?.memory,e=t?.usedJSHeapSize??0;return{rss:t?.totalJSHeapSize??0,heapUsed:e,heapTotal:t?.totalJSHeapSize??0,external:0,arrayBuffers:0}}();return{at:Date.now(),connections:{total:n,authenticated:e,anonymous:n-e,websocket:r,tcp:n-r},channels:t.channel_map.size,retained:{channel:t.retain_messages.size,bytes:t.retainBytes},counters:{...t.counters},memory:{rss:i.rss,heapUsed:i.heapUsed}}}summaryLine(t=ce.now()){const e=this.snapshot(),r=this.previous,n=n=>r?1e3*(e.counters[n]-r.counters[n])/Math.max(1,t-r.time):0;this.previous={time:t,counters:e.counters};const i=e.connections;return`[iosignal] conn ${i.total} (auth ${i.authenticated}, anon ${i.anonymous}, ws ${i.websocket}, tcp ${i.tcp}) ch ${e.channels} retained ${e.retained.channel}/${Ve(e.retained.bytes)} | rx ${n("rxMessages").toFixed(1)}/s ${Ve(n("rxBytes"))}/s tx ${n("txMessages").toFixed(1)}/s ${Ve(n("txBytes"))}/s pub ${n("publishes").toFixed(1)}/s | rss ${Ve(e.memory.rss)} heap ${Ve(e.memory.heapUsed)}`}oneline(){return{lastSSID:this.manager.lastSSID,remotes:this.manager.remotes.size,channels:this.manager.channel_map.size,txBytes:this.manager.counters.txBytes,rxBytes:this.manager.counters.rxBytes}}getRemotes(){return Array.from(this.manager.remotes,t=>"#"+t.ssid+":"+t.cid+"("+t.getStateName()+")")}getCIdList(){return Array.from(this.manager.cid2remote.keys())}getChannelList(){return Array.from(this.manager.channel_map.keys())}getSubscribers(t){let e=[];if(this.manager.channel_map.has(t)){this.manager.channel_map.get(t).forEach(t=>{e.push(t.cid)})}return e}getRemoteByCId(t,e=1){if(!this.manager.cid2remote.has(t))return{result:"nop"};{let r=this.manager.cid2remote.get(t);if(1==e)return{ip:r.ip,id:r.cid,ssid:r.ssid,cid:r.cid,uid:r.uid,uptime:Math.trunc((Date.now()-r.socket.openTime)/1e3),tx:r.socket.txCounter,rx:r.socket.rxCounter,txBytes:r.socket.bytesWritten||r.socket._socket?.bytesWritten,rxBytes:r.socket.bytesRead||r.socket._socket?.bytesRead};if(2==e)return{ip:r.ip,uptime:Math.trunc((Date.now()-r.socket.openTime)/1e3),nick:r.nick,ssid:r.ssid};if(3==e)return{ip:r.ip,uptime:Math.trunc((Date.now()-r.socket.openTime)/1e3),nick:r.nick,ssid:r.ssid,isSecure:r.TLS,isAuth:r.boho.isAuthorized,encMode:we[r.encMode]};if(4==e)return{ip:r.ip,uptime:Math.trunc((Date.now()-r.socket.openTime)/1e3),channels:Array.from(r.channels.keys()),retain:Array.from(r.retain_signal.keys())}}}}const Qe=Object.freeze(["open","allowlist","denylist"]),Ke=["cids","uids"];function Ye(t,e){if(null==e)return[];if(!Array.isArray(e))throw new TypeError(`${t} must be an array`);if(e.length>200)throw new RangeError(`${t} has more than 200 entries`);for(const r of e)if("string"!=typeof r||!r||r.length>64)throw new TypeError(`${t} entries must be non-empty strings of at most 64 characters`);return[...new Set(e)]}function Je(t,e){if(null==e)return{cids:[],uids:[]};if("object"!=typeof e||Array.isArray(e))throw new TypeError(`${t} must be an object`);for(const r of Object.keys(e))if(!Ke.includes(r))throw new TypeError(`unknown ${t}.${r}`);return{cids:Ye(`${t}.cids`,e.cids),uids:Ye(`${t}.uids`,e.uids)}}function Xe(t){if(null==t||""===t)return null;let e=t;if("string"==typeof t)try{e=JSON.parse(t)}catch{throw new TypeError("delivery policy is not valid JSON")}if(!e||"object"!=typeof e||Array.isArray(e))throw new TypeError("delivery policy must be an object");for(const t of Object.keys(e))if(!["v","mode","anonymous","publish","allow","deny","updatedAt"].includes(t))throw new TypeError(`unknown delivery policy field ${t}`);if(void 0!==e.v&&1!==e.v)throw new TypeError("delivery policy version must be 1");const r=e.mode??"open";if(!Qe.includes(r))throw new TypeError(`delivery policy mode must be one of: ${Qe.join(", ")}`);const n=e.anonymous??("allowlist"===r?"deny":"allow");if("allow"!==n&&"deny"!==n)throw new TypeError("delivery policy anonymous must be 'allow' or 'deny'");const i=e.publish??"all";if("all"!==i&&"policy"!==i)throw new TypeError("delivery policy publish must be 'all' or 'policy'");const s={v:1,mode:r,anonymous:n,publish:i,allow:Je("allow",e.allow),deny:Je("deny",e.deny)};if(void 0!==e.updatedAt){if(!Number.isSafeInteger(e.updatedAt)||e.updatedAt<0)throw new TypeError("delivery policy updatedAt must be a time in ms");s.updatedAt=e.updatedAt}return s}function Ze(t,e){if("string"!=typeof e||!e)return null;let r;try{r=Xe(t)}catch(t){console.warn(`[iosignal] unreadable delivery policy of uid ${e}, owner only:`,t.message),r={mode:"allowlist",anonymous:"deny",publish:"policy",allow:{cids:[],uids:[]},deny:{cids:[],uids:[]}}}return r&&"open"!==r.mode?Object.freeze({owner:e,mode:r.mode,defaultAllow:"denylist"===r.mode,anonymousAllow:"allow"===r.anonymous,filterPublish:"policy"===r.publish,allowCids:new Set(r.allow.cids),denyCids:new Set(r.deny.cids),allowUids:new Set(r.allow.uids),denyUids:new Set(r.deny.uids)}):null}function tr(t,e){const r=t.rxPolicy;if(!r)return!0;if(e===t)return!0;const n=!0===e.boho?.isAuthorized,i="string"==typeof e.uid&&e.uid?e.uid:null;if(i===r.owner)return!0;if(n&&"admin"===e.role)return!0;if(n){if(r.denyCids.has(e.cid))return!1;if(r.allowCids.has(e.cid))return!0}if(i){if(r.denyUids.has(i))return!1;if(r.allowUids.has(i))return!0}return n||i?r.defaultAllow:r.anonymousAllow}const er=new TextEncoder,rr=/^[A-Za-z0-9_.-]{1,64}$/;function nr(t,e){if("string"!=typeof t||0===t.length)throw new TypeError("host tag must be a non-empty string");const r=t.endsWith("*"),n=r?t.slice(0,-1):t;if(n.includes("*"))throw new TypeError(`host tag ${t}: '*' is allowed only at the end`);if(n.includes(","))throw new TypeError(`host tag ${t}: ',' separates tags`);if(er.encode(n).byteLength>Ee.TAG_LEN1)throw new TypeError(`host tag ${t} exceeds 255 UTF-8 bytes`);const i=n.startsWith("@");if(i){if(!e)throw new TypeError(`host tag ${t}: inbound tags are channel tags (no '@')`);if(-1!==n.indexOf("@",1))throw new TypeError(`host tag ${t}: a unicast topic has one '@'`);if(1===n.length)throw new TypeError(`host tag ${t}: empty topic`)}else{if(n.includes("@"))throw new TypeError(`host tag ${t}: channel tags have no '@'`);if(n.startsWith("#"))throw new TypeError(`host tag ${t}: home channel tags ('#...') cannot be hosted`);if(n.startsWith("$"))throw new TypeError(`host tag ${t}: '$' prefix is reserved`);if(0===n.length)throw new TypeError(`host tag ${t}: empty tag`)}return{pattern:t,text:n,prefix:r,unicast:i}}function ir(t,e){return!(!t.prefix||!e.text.startsWith(t.text))||(!(!e.prefix||!t.text.startsWith(e.text))||t.text===e.text)}class sr{constructor(){this.exact=new Map,this.prefixes=[],this.hosts=new Map}get size(){return this.hosts.size}add(t,e){if(this.hosts.has(t.name))throw new Error(`host ${t.name} already exists`);const r=[...this.exact.values(),...this.prefixes];e.forEach((n,i)=>{for(const s of[...r,...e.slice(0,i)])if(ir(n,s))throw new Error(`host tag ${n.pattern} overlaps ${s.pattern}`+(s.host===t?"":` of host ${s.host.name}`))});for(const t of e)t.prefix?this.prefixes.push(t):this.exact.set(t.text,t);this.hosts.set(t.name,t)}remove(t){if(this.hosts.get(t.name)===t){this.hosts.delete(t.name);for(const[e,r]of this.exact)r.host===t&&this.exact.delete(e);this.prefixes=this.prefixes.filter(e=>e.host!==t)}}match(t){const e=this.exact.get(t);if(e)return e;for(const e of this.prefixes)if(t.startsWith(e.text))return e}remoteClosed(t,e){if(e&&t.cid)for(const e of this.hosts.values())e._remoteClosed(t)}}class or extends dt{constructor(t,e,r={}){if(super(),"string"!=typeof e||!rr.test(e))throw new TypeError("host name: 1-64 characters of A-Z a-z 0-9 _ . -");if(null===r||"object"!=typeof r)throw new TypeError("host options must be an object");for(const t of Object.keys(r))if(!["inbound","own","fanout","retain"].includes(t))throw new TypeError(`unknown host option: ${t}`);const n=t=>{const e=r[t]??[];if(!Array.isArray(e))throw new TypeError(`host option ${t} must be an array of tags`);return e},i=this,s=n("inbound").map(t=>({...nr(t,!1),kind:"inbound",host:i})),o=n("own").map(t=>({...nr(t,!0),kind:"own",host:i}));if(0===s.length)throw new TypeError("host needs at least one inbound tag");const a=r.fanout??null;if(null!==a&&!(Number.isSafeInteger(a)&&a>0))throw new RangeError("host fanout must be null or a positive integer");const h=r.retain??{};for(const t of["tags","bytes"])if(void 0!==h[t]&&!(Number.isSafeInteger(h[t])&&h[t]>0))throw new RangeError(`host retain.${t} must be a positive integer`);this.name=e,this.manager=t,this.fanout=a,this.retainTags=h.tags??null,this.retainBytes=h.bytes??null,this.retainOwnerKey="host:"+e,this.ownChannels=o.filter(t=>!t.unicast),this.closed=!1,this._participants=new Map,this._activity=new Map,this.counters={inbound:0,rejected:0,denied:0,published:0,delivered:0,sent:0,joins:0,leaves:0,errors:0,handlerMs:0},this.handlerMaxMs=0,this.reported={},this._journal=[],this._journalSeq=0,this._loops=new Set,t.hosts.add(this,[...s,...o]);for(const e of[...t.retain_messages.keys()]){if(!e.startsWith(t.CHANNEL_PREFIX))continue;const r=t.hosts.match(e.slice(t.CHANNEL_PREFIX.length));r?.host===this&&t.dropChannelRetain(e)}}get participants(){return this._participants}forget(t){return this._activity.delete(t),this._participants.delete(t)}publish(t,...e){if(this._open(),"string"!=typeof t)throw new TypeError("tag should be string.");const r=this.manager.hosts.match(t);if(t.startsWith("@")||r?.host!==this||"own"!==r.kind)throw new Error(`host ${this.name} does not own channel tag ${t}`);const n=$e(t,...e),i=this.manager.hostPublish(this,this.manager.CHANNEL_PREFIX+t,n);return this.counters.published++,this.counters.delivered+=i,i}to(t,e,...r){if(this._open(),"string"!=typeof e||0===e.length||e.includes("@"))throw new TypeError("topic must be a non-empty string without @");const n=this.manager.cid2remote.get(t),i=$e("@"+e,...r);if(!n||n._closing)return!1;const s=n.peerRxLimitSkipped;return n.send_enc_mode(i),n.peerRxLimitSkipped===s&&(this.counters.sent++,!0)}report(t){if(null===t||"object"!=typeof t)throw new TypeError("report() takes an object");for(const[e,r]of Object.entries(t))if(null!=r){if(!["number","string","boolean"].includes(typeof r))throw new TypeError(`report value ${e} must be a number, string or boolean`);!(e in this.reported)&&Object.keys(this.reported).length>=20||(this.reported[String(e).slice(0,32)]="string"==typeof r?r.slice(0,64):r)}else delete this.reported[e];return this}loop(t,e){if(this._open(),!(Number.isFinite(t)&&t>=1))throw new RangeError("loop interval must be at least 1 ms");if("function"!=typeof e)throw new TypeError("loop needs a function");const r={intervalMs:t,ticks:0,gaps:[],steps:[],last:0},n=setInterval(()=>{const t=ce.now();r.last&&(r.gaps.push(t-r.last),r.gaps.length>200&&r.gaps.shift()),r.last=t;try{e(Date.now())}catch(t){this._failed(t)}r.steps.push(ce.now()-t),r.steps.length>200&&r.steps.shift(),r.ticks++},t),i={timer:n,stats:r};return this._loops.add(i),()=>{clearInterval(n),this._loops.delete(i)}}loopStats(){const t=(t,e)=>{if(!t.length)return 0;const r=[...t].sort((t,e)=>t-e);return r[Math.min(r.length-1,Math.floor(e/100*r.length))]};return[...this._loops].map(({stats:e})=>({intervalMs:e.intervalMs,ticks:e.ticks,gapP50:t(e.gaps,50),gapP99:t(e.gaps,99),gapMax:e.gaps.length?Math.max(...e.gaps):0,stepAvg:e.steps.length?e.steps.reduce((t,e)=>t+e,0)/e.steps.length:0,stepMax:e.steps.length?Math.max(...e.steps):0}))}activity(){return[...this._participants.values()].map(t=>({from:t,...this._activity.get(t.cid)??{inputs:0,firstAt:0,lastAt:0}}))}journal(t=0){return this._journal.filter(e=>e.seq>t)}_note(t,e){this._journal.push({seq:++this._journalSeq,at:Date.now(),kind:t,...e}),this._journal.length>200&&this._journal.shift()}_denied(t,e){this.counters.denied++,this._note("denied",{cid:t.cid,tag:e})}_failed(t){this.counters.errors++,this._note("error",{message:String(t?.message??t).slice(0,200)}),this.listenerCount("error")?this.emit("error",t):console.error(`host ${this.name} error:`,t)}close(){if(this.closed)return;this.closed=!0;for(const{timer:t}of this._loops)clearInterval(t);this._loops.clear(),this.manager.hosts.remove(this);const t=this.manager.retainOwners.get(this.retainOwnerKey);if(t)for(const e of[...t.tags])this.manager.dropChannelRetain(e);this._participants.clear(),this._activity.clear(),this.emit("close")}_open(){if(this.closed)throw new Error(`host ${this.name} is closed`)}static from(t){const e=!0===t.boho?.isAuthorized,r=t._hostFrom;return r&&r.cid===t.cid&&r.uid===t.uid&&r.role===t.role&&r.nick===t.nick&&r.authorized===e?r:t._hostFrom=Object.freeze({cid:t.cid,uid:t.uid||null,role:t.role,authorized:e,nick:t.nick||"",ssid:t.ssid})}_receive(t,e,r){if(r[0]!==Be.SIGNAL||!t.cid)return!1;const n=r[1];if(r.byteLength<n+3)return!1;let i;try{i=Fe(r[2+n],r.subarray(3+n))}catch{return!1}if(!i)return!1;const s=or.from(t),o=Date.now();let a=this._activity.get(s.cid);return a||(a={inputs:0,firstAt:o,lastAt:o},this._activity.set(s.cid,a),this.counters.joins++,this._note("join",{cid:s.cid,nick:s.nick,authorized:s.authorized})),a.inputs++,a.lastAt=o,this._participants.set(s.cid,s),this.counters.inbound++,this._emitSafely("message",s,e,...i),!0}_remoteClosed(t){this._participants.get(t.cid)&&(this._participants.delete(t.cid),this._activity.delete(t.cid),this.counters.leaves++,this._note("leave",{cid:t.cid,reason:t.closeReason??"close"}),this._emitSafely("leave",or.from(t),t.closeReason??"close"))}_emitSafely(t,...e){const r=ce.now();try{this.emit(t,...e)}catch(t){this._failed(t)}const n=ce.now()-r;this.counters.handlerMs+=n,n>this.handlerMaxMs&&(this.handlerMaxMs=n)}}const ar=new TextEncoder,hr=new TextDecoder;class ur{constructor(t,e){if(this.server=t,this.pingPeriod=t?.heartbeatInterval??me.heartbeatInterval,this.pingGrace=t?.heartbeatGrace??me.heartbeatGrace,!Number.isFinite(this.pingPeriod)||this.pingPeriod<=0||!Number.isFinite(this.pingGrace)||this.pingGrace<0)throw new RangeError("Invalid heartbeat period or grace");this.counters={rxMessages:0,rxBytes:0,txMessages:0,txBytes:0,publishes:0,deliveryAttempts:0,quotaExcluded:0,oversizeRejected:0,rateLimited:0,peerRxLimitSkipped:0,subscriptionsRejected:0,policyDenied:0,hostInbound:0,hostRejected:0,hostDenied:0},this.authManager=e,this.connectionLogger,me.fileLogger.connection.use&&(this.connectionLogger=new Ge(me.fileLogger.connection.path)),this.attackLogger,me.fileLogger.attack.use&&(this.attackLogger=new Ge(me.fileLogger.attack.path)),this.remotes=new Set,this.cid2remote=new Map,this.accountConnectionCounts=new Map,this.retain_messages=new Map,this.retain_owner=new Map,this.retainOwners=new Map,this.retainExpiry=new Map,this.retainBytes=0,this.channel_map=new Map,this.hosts=new sr,this.CHANNEL_PREFIX="CH:",this.CID_PREFIX="CID:",this.metrics=new We(this),this.lastSSID=0;const r=Math.min(50,Math.max(1,Math.floor(this.pingPeriod/1e3)));this.pingGroups=Array.from({length:r},()=>new Set),this.nextPingGroup=0,this.pingGroupCursor=0,this.heartbeatPending=new Map,this.pingTickMs=this.pingPeriod/r,this.heartbeatStopped=!1;const n=()=>{this.heartbeatStopped||(this.heartbeatTick(),this.heartbeatStopped||(this.pingIntervalID=setTimeout(n,this.pingTickMs)))};this.pingIntervalID=setTimeout(n,this.pingTickMs),t.logStats&&(this.statsIntervalID=setInterval(()=>console.log(this.metrics.summaryLine()),t.logStats))}get retainOptions(){return this.server?.retain??me.retain}get quotas(){return this.server?.quotas??me.quotas}get anonymousQuota(){return this.server?.anonymousQuota??me.anonymousQuota}accountConnections(t){return this.accountConnectionCounts.get(t)??0}addAccountConnection(t,e){t.accountUid=e,this.accountConnectionCounts.set(e,this.accountConnections(e)+1)}setDeliveryPolicy(t,e){const r=this.cid2remote.get(t);return!(!r?.boho.isAuthorized||!r.ownerUid)&&(Xe(e),r.rxPolicy=Ze(e,r.ownerUid),!0)}deliveryDenied(t,e,r){if(this.counters.policyDenied++,!this.server?.listenerCount?.("delivery:denied"))return;const n=!0===e.boho?.isAuthorized;this.server.emit("delivery:denied",{kind:r,cid:t.cid,did:t.did,owner:t.ownerUid,other:{cid:n?e.cid:null,uid:e.uid||null,ip:e.ip??null,authenticated:n},at:Date.now()})}removeAccountConnection(t){const e=t.accountUid;if(!e)return;t.accountUid=null;const r=this.accountConnections(e)-1;r>0?this.accountConnectionCounts.set(e,r):this.accountConnectionCounts.delete(e)}heartbeatTick(){const t=ce.now();this.retainExpiry.size&&this.expireChannelRetains(t);for(const[e,r]of this.heartbeatPending){if(r>t)break;this.heartbeatPending.delete(e),e._closing||!1!==e.socket.isAlive||e.close(!0)}const e=this.pingGroups[this.pingGroupCursor];this.pingGroupCursor=(this.pingGroupCursor+1)%this.pingGroups.length;for(const t of e)if(!t._closing&&!this.heartbeatPending.has(t)){t.socket.isAlive=!1,this.heartbeatPending.set(t,ce.now()+this.pingPeriod+this.pingGrace);try{t.ping()}catch{this.heartbeatPending.delete(t),t.close(!0)}}}addRemote(t,e){t.isAlive=!0;let r=new Ne(t,e,this);this.remotes.add(r),r.pingGroup=this.nextPingGroup,this.pingGroups[r.pingGroup].add(r),this.nextPingGroup=(this.nextPingGroup+1)%this.pingGroups.length,r.send(r.issueAuthChallenge()),r.send(Buffer.from([Be.SERVER_READY])),r.setState(be.SERVER_READY),this.lastSSID=r.ssid;let n=`+ IP:${r.ip} #${r.ssid} ${"websocket"===t.socketType?"WS":"CS"} `;this.connectionLogger&&this.connectionLogger.log(n)}removeRemote(t){t._closing=!0,this.removeAccountConnection(t),this.pingGroups[t.pingGroup]?.delete(t),this.heartbeatPending.delete(t),t.setState(be.CLOSED);let e=`- IP:${t.ip} #${t.ssid} cid:${t.cid} ${"websocket"===t?.socket.socketType?"WS":"CS"} `;this.connectionLogger&&this.connectionLogger.log(e);const r=this.cid2remote.get(t.cid),n=!t.cid||!r||r===t;n&&(this.deligateSignal(t,"@state","close"),this.deligateSignal(t,"@$state","close")),this.hosts.size&&this.hosts.remoteClosed(t,n);for(let e of t.channels.keys())if(this.channel_map.has(e)){const r=this.channel_map.get(e);r.delete(t),0==r.size&&this.channel_map.delete(e)}if(this.orphanChannelRetains(t),t.boho.isAuthorized);else for(let e of t.retain_signal.keys())e=this.CID_PREFIX+t.cid+"@"+e,this.channel_map.has(e)&&this.channel_map.delete(e);for(const e of t.retain_signal.values())this.retainBytes-=e.byteLength;t.retain_signal.clear(),t.retainBytes=0;for(const e of new Set(this.server.services?.values()??[]))if("function"==typeof e.onRemoteClose)try{e.onRemoteClose(t)}catch(t){console.error("service onRemoteClose error:",t)}this.remotes.delete(t),this.cid2remote.get(t.cid)===t&&this.cid2remote.delete(t.cid),t=null}serverSignal(t){let e=ue.pack(ue.MB("#MsgType","8",Be.SERVER_SIGNAL),ue.MB("#signalObject",t));this.remotes.forEach(t=>{t.send_enc_mode(e)})}getSignalTag(t){let e=t.readUint8(1),r=t.subarray(2,2+e);return hr.decode(r)}getNewSignalTagMessage(t,e){let r=t[0],n=t.readUint8(1),i=ar.encode(e),s=i.byteLength;if(s>Ee.TAG_LEN1)return null;let o=t.subarray(2+n);return Buffer.concat([Buffer.from([r,s]),i,o])}deligateSignal(t,e,...r){let n=$e(e,...r);this.sender(e,t,n)}adminSignal(t,e){return this.cid2remote.has(t)?void this.cid2remote.get(t).send_enc_mode(e):"no cid"}serverSignalTo(t,...e){let r=t.split("@")[0],n=t.split("@")[1];if(r&&this.cid2remote.has(r)){let t=$e("@"+n,...e);return void this.cid2remote.get(r).send_enc_mode(t)}return"no cid"}sender(t,e,r){if(ar.encode(t).byteLength>Ee.TAG_LEN1)return["err","Tag exceeds 255 UTF-8 bytes"];if((this.server?.membersOnly??me.membersOnly)&&!e.boho.isAuthorized)return e.send(Buffer.from([Be.AUTH_CLEAR])),e.close(),["err","unAuthorized"];if(0==t.indexOf("$"))return["err","prefix $ is reserved for userSet tag."];let n=t.indexOf("@");if(this.hosts.size&&0!==n){const i=this.hosts.match(n>0?t.slice(n):t);if("inbound"===i?.kind)return i.host._receive(e,t,r)?(this.counters.hostInbound++,["ok",1]):(this.counters.hostRejected++,i.host.counters.rejected++,["err","Not accepted by the host"]);if(i)return this.counters.hostDenied++,i.host._denied(e,t),this.server?.listenerCount?.("host:denied")&&this.server.emit("host:denied",e,t,i.host.name),["err","Tag is reserved by a host"]}const i=0===n&&e.rxPolicy?.filterPublish?e:null;if(0===n){if(t=e.cid+t,!(r=this.getNewSignalTagMessage(r,t)))return["err","CID-prefixed tag exceeds 255 UTF-8 bytes"]}else if(n>0){let n=t.split("@")[0];const i=this.cid2remote.get(n);if(i&&!tr(i,e))return this.deliveryDenied(i,e,"unicast"),["err","Invalid cid"];if(i){let e="@"+t.split("@")[1];return(r=this.getNewSignalTagMessage(r,e))?(i.send_enc_mode(r),["ok",1]):["err","Tag exceeds 255 UTF-8 bytes"]}return["err","Invalid cid"]}(t=0===t.indexOf("#")?e.HOME_CHANNEL+t:t.includes("@")?this.CID_PREFIX+t:this.CHANNEL_PREFIX+t).includes("$")&&this.retainOptions.enabled&&(t.includes("@")?this.storeCidRetain(t.split("@")[1],r,e):this.storeChannelRetain(t,r,e)),this.counters.publishes++;const s=this.deliver(t,r,e.quota.fanout,i);return null===s?["err","No subscriber."]:["ok",s]}deliver(t,e,r,n=null){const i=this.channel_map.get(t);if(!i||0===i.size)return null;const s=null===r?i.size:Math.min(r,i.size);this.counters.quotaExcluded+=i.size-s;let o=0;for(const t of i){if(o>=s)break;!n||tr(n,t)?(t.send_enc_mode(e),o++):this.deliveryDenied(n,t,"publish")}return this.counters.deliveryAttempts+=o,o}hostPublish(t,e,r){return e.includes("$")&&this.retainOptions.enabled&&this.storeChannelRetain(e,r,null,t),this.counters.publishes++,this.deliver(e,r,t.fanout)??0}retainFits(t,e,r,n){return this.retainOptions.limitSize>t.byteLength&&r+t.byteLength<=n&&this.retainBytes+t.byteLength-e<=this.retainOptions.bytesTotal}retainCopy(t){const e=Buffer.allocUnsafeSlow(t.byteLength);return e.set(t),this.retainBytes+=e.byteLength,e}storeCidRetain(t,e,r){const n=r.retain_signal,i=n.get(t),s=i?.byteLength??0;(i||n.size<this.retainOptions.limitCounter)&&this.retainFits(e,s,r.retainBytes-s,this.retainOptions.bytesPerConnection)?(n.set(t,this.retainCopy(e)),this.retainBytes-=s,r.retainBytes+=e.byteLength-s):i&&(n.delete(t),this.retainBytes-=s,r.retainBytes-=s)}retainOwner(t){let e=this.retainOwners.get(t);return e||this.retainOwners.set(t,e={key:t,bytes:0,tags:new Set}),e}storeChannelRetain(t,e,r,n=null){const i=this.retainOwner(n?n.retainOwnerKey:r.boho.isAuthorized?"cid:"+r.cid:"conn:"+r.ssid),s=n?.retainTags??this.retainOptions.tagsPerOwner,o=n?.retainBytes??this.retainOptions.bytesPerOwner,a=this.retain_messages.get(t),h=a?.byteLength??0,u=a||this.retain_messages.size<this.retainOptions.limitCounter&&i.tags.size<s,c=i.bytes-(this.retain_owner.get(t)===i?h:0);u&&this.retainFits(e,h,c,o)?(a&&this.releaseChannelRetain(t,h),this.retain_messages.set(t,this.retainCopy(e)),i.bytes+=e.byteLength,i.tags.add(t),this.retain_owner.set(t,i),this.retainOwners.set(i.key,i)):a&&this.dropChannelRetain(t),0===i.tags.size&&this.retainOwners.delete(i.key)}orphanChannelRetains(t){const e=this.retainOwners.get("conn:"+t.ssid);if(!e)return;const r=this.retainOptions.anonymousGraceMs;if(!(r>0)){for(const t of[...e.tags])this.dropChannelRetain(t);return}this.retainOwners.delete(e.key);const n=this.retainOwner("net:"+t.HOME_CHANNEL),i=ce.now()+r;for(const t of e.tags)n.tags.add(t),n.bytes+=this.retain_messages.get(t).byteLength,this.retain_owner.set(t,n),this.retainExpiry.set(t,i);for(;n.bytes>this.retainOptions.bytesPerOwner||n.tags.size>this.retainOptions.tagsPerOwner;){let t;for(const e of n.tags)(void 0===t||this.retainExpiry.get(e)<this.retainExpiry.get(t))&&(t=e);this.dropChannelRetain(t)}}expireChannelRetains(t=ce.now()){for(const[e,r]of this.retainExpiry)r<=t&&this.dropChannelRetain(e)}dropChannelRetain(t){const e=this.retain_messages.get(t);e&&(this.releaseChannelRetain(t,e.byteLength),this.retain_messages.delete(t))}releaseChannelRetain(t,e){const r=this.retain_owner.get(t);this.retain_owner.delete(t),this.retainExpiry.delete(t),this.retainBytes-=e,r&&(r.tags.delete(t),r.bytes-=e,0===r.tags.size&&this.retainOwners.delete(r.key))}subscribe(t,e){if((this.server?.membersOnly??me.membersOnly)&&!e.boho.isAuthorized)return e.send(Buffer.from([Be.AUTH_CLEAR])),e.close(),!1;const r=e.quota?.maxSubscriptions??null;return t.forEach(t=>{if(t=0===t.indexOf("#")?e.HOME_CHANNEL+t:t.includes("@")?this.CID_PREFIX+t:this.CHANNEL_PREFIX+t,null!==r&&e.channels.size>=r&&!e.channels.has(t))return this.counters.subscriptionsRejected++,void(e.subscriptionsRejected=(e.subscriptionsRejected??0)+1);if(this.channel_map.has(t)?this.channel_map.get(t).add(e):this.channel_map.set(t,new Set([e])),e.channels.add(t),t.includes("$")&&this.retainOptions.enabled){let r;if(t.includes("@")){let n=t.split("@")[0];n=n.split(this.CID_PREFIX)[1];let i=t.split("@")[1];const s=this.cid2remote.get(n);if(!s)return;if(s.rxPolicy?.filterPublish&&!tr(s,e))return void this.deliveryDenied(s,e,"publish");r=s.retain_signal.get(i)}else this.retain_messages.has(t)&&(r=this.retain_messages.get(t));r&&e.send_enc_mode(r)}}),e.channels.size}unsubscribe(t,e){1==t.length&&""==t[0]?(e.channels.forEach(t=>{if(this.channel_map.has(t)){let r=this.channel_map.get(t);r.delete(e),0==r.size&&this.channel_map.delete(t)}}),e.channels.clear()):t.forEach(t=>{if(t=0===t.indexOf("#")?e.HOME_CHANNEL+t:t.includes("@")?this.CID_PREFIX+t:this.CHANNEL_PREFIX+t,this.channel_map.has(t)){let r=this.channel_map.get(t);r.delete(e),0==r.size&&this.channel_map.delete(t)}e.channels.delete(t)})}anonymousCidRandom(t){return globalThis.crypto.getRandomValues(Buffer.alloc(t))}issueAnonymousCid(){for(const[t,e]of[[4,8],[8,8]])for(let r=0;r<e;r++){let e="?";for(const r of this.anonymousCidRandom(t))e+="0123456789abcdefghjkmnpqrstvwxyz"[31&r];if(!this.cid2remote.has(e))return e}return null}closeRemoteByCId(t){return this.cid2remote.has(t)?(this.cid2remote.get(t).close(),1):0}close(){this.metrics.close(),this.heartbeatStopped=!0,clearTimeout(this.pingIntervalID),this.heartbeatPending.clear();for(const t of this.pingGroups)t.clear();this.statsIntervalID&&clearInterval(this.statsIntervalID),this.remotes.forEach(t=>{t.close()}),this.remotes.clear(),this.cid2remote.clear(),this.retain_messages.clear(),this.retain_owner.clear(),this.retainOwners.clear(),this.retainExpiry.clear(),this.retainBytes=0,this.channel_map.clear()}}class cr{constructor(){throw new Error("dashboard is not available in the browser")}}const fr=255,lr=new TextDecoder,pr=["keepOld","keepNew"],dr=t=>"websocket"===t.socketType?"websocket":"congsocket";function gr(t){if(!pr.includes(t))throw new RangeError(`duplicateLogin must be one of: ${pr.join(", ")}`);return t}const yr=["anonymous","device","service","admin"];function mr(t,e){return t.quota||("device"===e?"basic":"unlimited")}class br{constructor(t,e={}){if(!t)throw new Error("BohoAuth must be initialized with a keyProvider.");this.keyProvider=t,this._duplicateLogin=null,void 0!==e.duplicateLogin&&(this.duplicateLogin=e.duplicateLogin),this.onAuthEvent=e.onAuthEvent??null,this.resolveQuota=e.resolveQuota??mr,this.addressFailures=new Map,this.authLogger,me.fileLogger.auth.use&&(this.authLogger=new Ge(me.fileLogger.auth.path),console.log("Auth: begin file logger.[auth]"))}get duplicateLogin(){return this._duplicateLogin??me.auth.duplicateLogin}set duplicateLogin(t){this._duplicateLogin=null===t?null:gr(t)}duplicateLoginFor(t){return t.manager?.server?.duplicateLogin??this.duplicateLogin}get keepOldConnection(){return"keepOld"===this.duplicateLogin}set keepOldConnection(t){this.duplicateLogin=t?"keepOld":"keepNew"}emitAuthEvent(t){if("function"==typeof this.onAuthEvent)try{Promise.resolve(this.onAuthEvent(t)).catch(t=>console.error("onAuthEvent error:",t))}catch(t){console.error("onAuthEvent error:",t)}}#t(t,e=Date.now()){if("string"!=typeof t||!t||Re(t))return null;let r=this.addressFailures.get(t);return r&&e-r.since>=me.auth.failureWindowMs&&(this.addressFailures.delete(t),r=void 0),r??{count:0,since:e,fresh:!0}}addressBlocked(t){const e=this.#t(t);return!!e&&e.count>=me.auth.maxFailuresPerAddress}#e(t){t.authFailures=(t.authFailures??0)+1;const e=this.#t(t.ip);if(e){if(e.fresh){if(delete e.fresh,this.addressFailures.size>=1e4){const t=Date.now();for(const[e,r]of this.addressFailures)t-r.since>=me.auth.failureWindowMs&&this.addressFailures.delete(e);this.addressFailures.size>=1e4&&this.addressFailures.clear()}this.addressFailures.set(t.ip,e)}e.count++}}send_auth_fail(t,e,r=!1){if(t._closing||t.state===be.CLOSED)return;t.boho.isAuthorized=!1,r&&this.#e(t);const n=r&&t.authFailures>=me.auth.maxFailuresPerConnection;if(this.authLogger){let r=`FAIL #${t.ssid} reason:${e} `;this.authLogger.log(r)}t.setState(be.AUTH_FAIL),setTimeout(e=>{t._closing||t.state!==be.AUTH_FAIL||(t.send(Buffer.from([nt.BohoMsg.AUTH_FAIL])),n&&t.close())},me.auth.failDelay)}close_unavailable(t,e){t._closing||t.state===be.CLOSED||(console.error("BohoAuth: login not checked, closing the connection:",e),this.authLogger&&this.authLogger.log(`UNAVAILABLE #${t.ssid} reason:${e} `),t.boho.isAuthorized=!1,t.close())}beforeAccept(t,e,r,n){return null}async#r(t,e,r,n){try{const i=await this.beforeAccept(t,e,r,n);return i instanceof Uint8Array&&i.byteLength>0?i:null}catch(t){return console.error("BohoAuth.beforeAccept error:",t),null}}async verify_auth_req(t,e){try{if(!e.checkAuthChallenge())return;if(!(t instanceof Uint8Array)||t.length!==nt.MetaSize.AUTH_REQ||t[0]!==nt.BohoMsg.AUTH_REQ)return void e.securityMismatch("INVALID_AUTH_PACKET");let r=ue.unpack(t,nt.Meta.AUTH_REQ);if(!r)return void this.send_auth_fail(e,"unpack auth_pack fail");let n,i,s="";if(s=r.id8.includes(0)?lr.decode(r.id8.subarray(0,r.id8.indexOf(0))):lr.decode(r.id8),this.addressBlocked(e.ip))return void this.close_unavailable(e,"too many wrong logins from "+e.ip);try{n=await this.keyProvider.getAuth(s)}catch(t){return void this.close_unavailable(e,"key provider: "+(t?.message??t))}if(!e.checkAuthChallenge())return;if(!n)return void this.send_auth_fail(e,"NO ID:"+s,!0);me.debug.showAuthInfo&&console.log("[debug]showAuthInfo",{id:s,cid:n.cid,uid:n.uid,role:n.role,quota:n.quota}),e.boho.copy_id8(r.id8);const o=44;n.key.length==o?(i=Buffer.from(n.key,"base64"),e.boho.copy_key(i)):e.boho.set_key(n.key);let a=e.boho.verify_auth_req(r);if(!a)return void this.send_auth_fail(e,"hmac dismatched",!0);e._challengeUsed=!0;const h=function(t){return null==t||""===t?"device":yr.includes(t)&&"anonymous"!==t?t:void 0}(n.role);if(void 0===h)return void this.send_auth_fail(e,"unknown auth.role: "+n.role);const u=await this.#r(e,n,h,s);if(e._closing)return;if(u)return e.boho.isAuthorized=!1,e.send(u),void e.close();let c;try{c=await this.resolveQuota(n,h)}catch(t){return void this.close_unavailable(e,"quota: "+(t?.message??t))}const f=Object.hasOwn(e.manager.quotas,c)?e.manager.quotas[c]:void 0;if(!f)return void this.send_auth_fail(e,"unknown quota: "+c);if(e._closing)return;const l=n.uid||null;if(l&&null!==f.maxConnections){const t=e.manager.cid2remote.get(n.cid),r=t&&t!==e&&t.accountUid===l&&"keepNew"===this.duplicateLoginFor(e)?1:0;if(e.manager.accountConnections(l)-r>=f.maxConnections)return void this.send_auth_fail(e,"too many connections")}if(e.manager.cid2remote.has(n.cid)&&e.manager.cid2remote.get(n.cid)!==e){let t=e.manager.cid2remote.get(n.cid);console.log("[WARN]DUPLICATE_LOGIN detected.",t.cid),t.ping();let r=ue.pack(ue.MB("#MsgType","8",Be.AUTH_CLEAR),ue.MB("#reason","duplicate login."));const i="keepOld"===this.duplicateLoginFor(e);if(i?(e.boho.isAuthorized=!1,"websocket"==e.socketType?this.send_auth_fail(e,"duplicate login"):(e.setState(be.AUTH_FAIL),e.close())):(t.send(r),t.close()),this.emitAuthEvent({type:i?"duplicate_rejected":"replaced",did:s,cid:n.cid,uid:n.uid||null,ip:e.ip,oldIp:t.ip,socketType:dr(e),oldSocketType:dr(t),reason:"duplicate login",at:Date.now()}),i)return}if(e.cid&&e.cid!==n.cid){const t=e.manager;for(const r of["@state","@$state"]){const n=e.cid+r;t.deliver(t.CID_PREFIX+n,$e(n,"close"),null)}for(const r of e.retain_signal.values())t.retainBytes-=r.byteLength;e.retain_signal.clear(),e.retainBytes=0,t.cid2remote.delete(e.cid)}if(e.did=s,e.cid=n.cid,n.uid&&(e.uid=n.uid),e.ownerUid=l,e.rxPolicy=Ze(n.rxPolicy,l),e.role=h,"admin"===h&&console.log("## LOGIN ADMIN CID:",e.cid),l&&e.manager.addAccountConnection(e,l),e.setQuota(c,!0),e.manager.cid2remote.set(e.cid,e),e.send(a),e.setState(be.AUTH_RES),this.authLogger){let t=`OK #${e.ssid} cid: ${e.cid} did:${e.did}`;e.isAdmin&&(t="#ADMIN# "+t),this.authLogger.log(t)}return n}catch(t){console.log("verify_auth_req error",t),this.send_auth_fail(e,"[BohoAuth]caught: unknown error:"+t)}}async getAuth(t){return this.keyProvider.getAuth(t)}async getAuthIdList(){if("function"==typeof this.keyProvider.getAuthIdList)return this.keyProvider.getAuthIdList()}async addAuth(t,e,r,n,i){if("function"==typeof this.keyProvider.addAuth)return this.keyProvider.addAuth(t,e,r,n,i)}async delAuth(t){if("function"==typeof this.keyProvider.delAuth)return this.keyProvider.delAuth(t)}async save(){if("function"==typeof this.keyProvider.save)return this.keyProvider.save()}}const wr=["idKey","sharedKey"],Er=t=>Buffer.from(nt.sha256.hash(t)).toString("base64");class _r{constructor(t){const{mode:e,key:r,role:n="device",quota:i}="string"==typeof t?{mode:t}:t??{};if(!wr.includes(e))throw new TypeError(`LocalKeyProvider mode must be one of: ${wr.join(", ")}`);if("sharedKey"===e&&("string"!=typeof r||0===r.length))throw new TypeError("LocalKeyProvider mode 'sharedKey' needs a non-empty key");if(void 0!==i&&("string"!=typeof i||!i))throw new TypeError("LocalKeyProvider quota must be a quotas profile name");if(!yr.includes(n)||"anonymous"===n)throw new RangeError(`LocalKeyProvider role must be one of: ${yr.slice(1).join(", ")}`);this.mode=e,this.role=n,this.quota=i,this.sharedKeyHash="sharedKey"===e?Er(r):null}async getAuth(t){if(t)return{key:this.sharedKeyHash??Er(t),cid:t,role:this.role,...this.quota&&{quota:this.quota}}}}const Br=[["showMessage","logMessages: true"],["showMetric","logStats: <interval ms> (for lists, the sudo service's remotes/channels commands)"],["monitorPeriod","logStats: <interval ms>"],["timeout","heartbeatInterval"],["pingTimeoutGrace","heartbeatGrace"],["retain.isAvailable","retain.enabled"],["useQuota","quotas: named quota profiles, always enforced (null: unlimited)"],["defaultQuotaIndex","anonymousQuota: a quotas profile name; logins use their account's quota"],["auth.delay_auth_fail","auth.failDelay","global"],["adminLevel","role: 'admin' in the account (key entry)","global"],["clientTracking","nothing: it was never used","global"],...["port","congPort","httpServer","wsPath"].map(t=>[t,`new Server({ ${t} })`,"global"])],Ar=(t,e)=>e.split(".").reduce((t,e)=>t?.[e],t);const vr=2147483647;function Sr(t,e,r,n=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(e)||e<r||e>n)throw new RangeError(`${t} must be an integer from ${r} to ${n}`);return e}const Lr=(t,e)=>Sr(t,e,1),Ir=(t,e)=>Sr(t,e,0),Tr=["maxMessageBytes","fanout","msgPerSec","bytesPerSec","maxConnections","maxSubscriptions"];function kr(t,e){if("boolean"!=typeof e)throw new TypeError(`${t} must be a boolean`);return e}function Cr(t,e,r){if(void 0!==e&&(null===e||"object"!=typeof e))throw new TypeError(`${t} must be an object`);for(const n of Object.keys(e??{}))if(!(n in r))throw new TypeError(`unknown option ${t}.${n}`);const n={...me[t],...e};for(const[e,i]of Object.entries(r))i(`${t}.${e}`,n[e]);return n}class Rr extends dt{constructor(t,e){if(super(),void 0!==t.localAuth&&null!==t.localAuth){if(e)throw new TypeError("localAuth cannot be combined with an authManager");e=new br(new _r(t.localAuth))}if(function(t){for(const[e,r,n]of Br){const i="global"===n?[["serverOption.",me]]:[["",t],["serverOption.",me]];for(const[t,n]of i)if(void 0!==Ar(n,e))throw new TypeError(`${t}${e} was removed in iosignal 9.0; use ${r}`)}}(t),this.security=Object.freeze(Cr("security",t.security,{maxClockSkewMs:Lr,authChallengeMaxAgeMs:Lr,maxReplayEntries:Lr,requireEncryption:kr})),this.retain=Cr("retain",t.retain,{enabled:kr,limitSize:Lr,limitCounter:Lr,tagsPerOwner:Lr,bytesPerOwner:Lr,anonymousGraceMs:Ir,bytesPerConnection:Lr,bytesTotal:Lr}),this.quotas=function(t){if(void 0!==t&&(null===t||"object"!=typeof t))throw new TypeError("quotas must be an object");const e={};for(const r of new Set([...Object.keys(me.quotas),...Object.keys(t??{})])){const n=t?.[r];if(void 0!==n&&(null===n||"object"!=typeof n))throw new TypeError(`quotas.${r} must be an object`);for(const t of Object.keys(n??{}))if(!Tr.includes(t))throw new TypeError(`unknown option quotas.${r}.${t}`);const i=me.quotas[r]??Object.fromEntries(Tr.map(t=>[t,null]));e[r]={...i,...n};for(const t of Tr)null!==e[r][t]&&Lr(`quotas.${r}.${t}`,e[r][t])}return e}(t.quotas),this.anonymousQuota=t.anonymousQuota??me.anonymousQuota,!Object.hasOwn(this.quotas,this.anonymousQuota))throw new RangeError(`anonymousQuota must be one of the quotas: ${Object.keys(this.quotas).join(", ")}`);var r;if(this.heartbeatInterval=Sr("heartbeatInterval",t.heartbeatInterval??me.heartbeatInterval,1,vr),this.heartbeatGrace=Sr("heartbeatGrace",t.heartbeatGrace??me.heartbeatGrace,0,vr),this.maxPayload=Lr("maxPayload",t.maxPayload??me.maxPayload),this.maxBufferedBytes=Lr("maxBufferedBytes",t.maxBufferedBytes??me.maxBufferedBytes),this.logMessages=kr("logMessages",t.logMessages??me.logMessages),this.logStats=0===(r=t.logStats??me.logStats)||!1===r?0:Sr("logStats",r,1e3,vr),this.trustProxy=t.trustProxy??me.trustProxy,!([!0,!1,"private"].includes(this.trustProxy)||Number.isSafeInteger(this.trustProxy)&&this.trustProxy>0))throw new RangeError("trustProxy must be true, false, 'private' or a positive integer");if(this.membersOnly=kr("membersOnly",t.membersOnly??me.membersOnly),this.serviceNames=new Set,this.services=new Map,this.hosts=new Set,this.wss=null,this.port=null,this.congPort=null,this.duplicateLogin=null,void 0!==t.duplicateLogin&&(this.duplicateLogin=gr(t.duplicateLogin),e&&!("duplicateLogin"in e)))throw new TypeError("duplicateLogin: the auth manager does not support this option");if((t.port||0==t.port)&&(this.port=parseInt(t.port)),t.httpServer&&(this.httpServer=t.httpServer),t.wsPath&&(this.wsPath=t.wsPath),(t.congPort||0==t.congPort)&&(this.congPort=parseInt(t.congPort)),this.manager=new ur(this,e),this.dashboard=null,t.dashboard)try{this.dashboard=new cr(this,t.dashboard)}catch(t){throw this.manager.close(),t}if(this.serverCountToListen=0,this.listeningServerCount=0,(this.port||0==this.port||this.httpServer)&&this.serverCountToListen++,(this.congPort||0==this.congPort)&&this.serverCountToListen++,0===this.serverCountToListen)throw new Error('Cannot create Server: At least one of "port", "httpServer", or "congPort" must be specified.');(this.port||0==this.port||this.httpServer)&&this.startWSServer(),(this.congPort||0==this.congPort)&&this.startCongServer()}startWSServer(){if((this.port||0==this.port)&&this.dashboard)this.ownHttp=ut.createServer((t,e)=>{this.dashboard.handle(t,e)||(e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not found"))}),this.ownHttp.on("error",t=>this.onListenerError("ws",t)),this.wss=new Lt({server:this.ownHttp,path:this.wsPath,maxPayload:this.maxPayload}),this.ownHttp.listen(this.port);else if(this.port||0==this.port)this.wss=new Lt({port:this.port,path:this.wsPath,maxPayload:this.maxPayload});else{if(!this.httpServer)throw new TypeError('One and only one of the "port", "httpServer"must be specified');this.wss=new Lt({server:this.httpServer,path:this.wsPath,maxPayload:this.maxPayload})}this.wss.once("listening",()=>{this.port=this.wss.address().port,this.listeningServerCount++,this.listeningServerCount===this.serverCountToListen&&this.emit("ready")}),this.wss.on("error",t=>this.onListenerError("ws",t)),this.wss.on("close",()=>{}),this.wss.on("connection",(t,e)=>{t.socketType="websocket",this.manager.addRemote(t,e)})}startCongServer(){this.congServer=ht.createServer(t=>{t.setNoDelay(!0),this.manager.addRemote(t)}).on("error",t=>this.onListenerError("cong",t)).on("close",()=>{}).listen(this.congPort,()=>{this.congPort=this.congServer.address().port,this.listeningServerCount++,this.listeningServerCount===this.serverCountToListen&&this.emit("ready")})}onListenerError(t,e){console.error(`### ${t} server error:`,e.message),"listen"===e.syscall&&this.emit("error",e)}stats(){return this.manager.metrics.snapshot()}host(t,e){const r=new or(this.manager,t,e);return r.once("close",()=>this.hosts.delete(r)),this.hosts.add(r),r}attach(t,e){if("string"!=typeof t)throw new Error("attach service name is not a string.");if(!e.checkPermission||"function"!=typeof e.checkPermission)throw new Error(`Service ${t} : no checkPermission or not a function.`);if(!e.commands||!Array.isArray(e.commands))throw new Error(`Service ${t} : no commands or !Array.`);const r=(e,r,n)=>{if(console.error(`Unhandled Service Error in service [${t}]:`,n),!e._closing)try{e.response(r.mid,fr,"INTERNAL_SERVER_ERROR")}catch(e){console.error(`Service error response failed [${t}]:`,e)}},n="function"==typeof e.call;return this.on(t,(t,i)=>{try{if(!e.checkPermission(t,i))return void t.response(i.mid,fr,"NO_PERMISSION.");if(!e.commands.includes(i.topic))return void t.response(i.mid,fr,"UNKNOWN_COMMAND");const s=n?e.call(t,i):e[i.topic](t,i);Promise.resolve(s).catch(e=>r(t,i,e))}catch(e){r(t,i,e)}}),this.serviceNames.add(t),this.services.set(t,e),this}close(t){console.log("closing iosignal server..."),this.dashboard&&this.dashboard.close();for(const t of[...this.hosts])t.close();this.manager&&this.manager.close(),this.serviceNames.forEach(t=>this.removeAllListeners(t)),this.serviceNames.clear();let e=0;if(this.wss&&e++,this.congServer&&e++,0===e)return void(t&&process.nextTick(t));let r=0;const n=()=>{r++,r===e&&(console.log("IOSignal server is closed."),t&&t())};this.wss&&this.wss.close(()=>{if(!this.ownHttp)return n();this.ownHttp.close(()=>n()),this.ownHttp.closeAllConnections?.()}),this.congServer&&this.congServer.close(t=>{n()})}}function Mr(t={},e){for(const e of["httpServer","congPort","dashboard"])if(void 0!==t[e])throw new TypeError(`${e} is not available in the browser`);const r=new Rr({port:7700,...t},e);return r.url=r.wss.url,new Promise((t,e)=>{const n=t=>{r.close(),e(t)};r.once("error",n),r.once("ready",()=>{r.off("error",n),t(r)})})}const Ur=new TextDecoder;function Or(t,e,{showPing:r=!1}={}){const n=t.wss,i=new WeakMap,s=[],o=e=>{const r=(e=>{let r=i.get(e);if(!r){for(const n of t.manager.remotes)if(n.socket===e){r=n;break}r&&i.set(e,r)}return r})(e);return{ssid:r?.ssid??null,cid:r?.cid||"",transport:e.transport}},a=t=>e({at:Date.now(),...t});let h=null;const u=()=>{const e=h;h=null;for(const{signal:r,to:n}of e.values()){const e=t.manager.hosts.size?t.manager.hosts.match(r.tag):null;a({type:"host",from:{host:e?.host.name??"server"},tag:r.tag,args:r.args,to:n})}},c={"local:connection":t=>s.push({kind:"connection",socket:t,out:[]}),"local:connection:end":()=>{const t=s.pop();a({type:"connect",from:o(t.socket),note:t.socket.transport})},"local:rx":(t,e,r)=>s.push({kind:"rx",socket:t,data:e,isBinary:r,out:[],from:o(t)}),"local:rx:end":()=>{const e=function(t,e,r,n){const{data:i,isBinary:s,from:o,out:a}=t;if(!s)return{type:"other",from:o,note:"text message "+Pr(Ur.decode(i))};const h=i[0];switch(h){case Be.PING:case Be.PONG:return r?{type:"other",from:o,note:Be[h]}:null;case Be.CID_REQ:{const t=a.find(t=>t.data[0]===Be.CID_RES),e=t?Ur.decode(t.data.subarray(1)):"";return{type:"cid",from:{...o,cid:e||o.cid},note:e?`CID ${e}`:"no CID"}}case Be.SIGNAL:case Be.SIGNAL_E2E:{const{tag:t,args:r}=Nr(i),s=$r(a,e);let h="";const u=n.manager.hosts.size&&0!==t.indexOf("@")?n.manager.hosts.match(t.includes("@")?t.slice(t.indexOf("@")):t):null;if("inbound"===u?.kind){const e=new Map;for(const t of s)e.has(t.signal.tag)||e.set(t.signal.tag,{type:"host",from:{host:u.host.name},tag:t.signal.tag,args:t.signal.args,to:[]}),e.get(t.signal.tag).to.push(t.to);return{type:"signal",from:o,tag:t,args:r,to:[],note:`→ host ${u.host.name}`,hostSent:[...e.values()]}}if(u)h=`denied: owned by host ${u.host.name}`;else if(0===s.length){h=t.indexOf("@")>0?"no such CID (or not allowed)":"no subscriber"}return t.includes("$")&&(h=(h?h+", ":"")+"retained"),{type:"signal",from:o,tag:t,args:r,to:s.map(t=>t.to),note:h}}case Be.SUBSCRIBE:case Be.SUBSCRIBE_REQ:case Be.UNSUBSCRIBE:{const t=h===Be.SUBSCRIBE_REQ?Ur.decode(i.subarray(5,5+i.readUInt16BE(3))):xr(i);if(h===Be.UNSUBSCRIBE)return{type:"unsubscribe",from:o,tag:t||"(all)"};const r=$r(a,e);return{type:"subscribe",from:o,tag:t,note:r.length?"retained: "+r.map(t=>`${t.signal.tag}=${t.signal.args}`).join("; "):""}}case Be.IAM:return{type:"other",from:o,note:"IAM"};case Be.CLOSE:return{type:"other",from:o,note:"CLOSE"};case Be.CALL:{const t=ue.unpack(i);return{type:"other",from:o,note:`CALL ${t?.target}.${t?.topic}`}}case nt.BohoMsg.AUTH_REQ:return{type:"auth",from:o,note:"login request"};case nt.BohoMsg.ENC_488:case nt.BohoMsg.ENC_E2E:return{type:"other",from:o,note:`encrypted message (${i.byteLength} bytes)`};default:return{type:"other",from:o,note:Be[h]??nt.BohoMsg[h]??`type 0x${h.toString(16)}`}}}(s.pop(),o,r,t);if(!e)return;const{hostSent:n,...i}=e;a(i);for(const t of n??[])a(t)},"local:close":(t,e,r)=>s.push({kind:"close",socket:t,code:e,reason:r,out:[],from:o(t)}),"local:close:end":()=>{const t=s.pop();a({type:"disconnect",from:t.from,note:`code ${t.code}${t.reason?" "+t.reason:""}`});for(const e of $r(t.out,o))a({type:"signal",from:{...t.from,server:!0},...e.signal,to:[e.to]})},"local:tx":(t,e)=>{const r=s.at(-1);r?r.out.push({socket:t,data:e}):((t,e)=>{if(e[0]!==Be.SIGNAL&&e[0]!==Be.SIGNAL_E2E)return;const r=Nr(e);h||(h=new Map,setTimeout(u,0));const n=r.tag.startsWith("@")?r.tag+" "+r.args:r.tag;h.has(n)||h.set(n,{signal:r,to:[]}),h.get(n).to.push({...o(t),tag:r.tag})})(t,e)}};for(const[t,e]of Object.entries(c))n.on(t,e);return()=>{for(const[t,e]of Object.entries(c))n.off(t,e)}}function xr(t){return Ur.decode(t.subarray(2,2+t[1]))}function Nr(t){const e=xr(t);if(t[0]===Be.SIGNAL_E2E)return{tag:e,args:"(end-to-end encrypted)"};const r=t[2+t[1]];let n;try{const e=Fe(r,t.subarray(3+t[1]));n=null===e?`(payload type ${r})`:e.map(t=>Pr(t)).join(", ")}catch{n="(malformed payload)"}return{tag:e,args:n}}function Pr(t,e=80){let r;if(t instanceof Uint8Array||t instanceof ArrayBuffer)return`<${t.byteLength} bytes>`;if("string"==typeof t)r=JSON.stringify(t);else try{r=JSON.stringify(t)}catch{r=String(t)}return r.length>e?r.slice(0,e-1)+"…":r}function $r(t,e){return t.filter(({data:t})=>t[0]===Be.SIGNAL||t[0]===Be.SIGNAL_E2E).map(({socket:t,data:r})=>{const n=Nr(r);return{signal:n,to:{...e(t),tag:n.tag}}})}const Dr=ue.Buffer,Fr=new TextEncoder,jr=new TextDecoder;function zr(t,e=!0){if("string"!=typeof t)throw TypeError("tag should be string.");const r=Fr.encode(t);if(!e&&0===r.byteLength||r.byteLength>Ee.TAG_LEN1)throw TypeError("tag UTF-8 byte length must be "+(e?"0":"1")+"~255");return r}function Hr(t){const e=zr(t);if(t.split(",").some(t=>t.startsWith("@")))throw TypeError("direct signal tags need no subscription; use on/listen/link and off/unlink");return e}function Gr(t,e){const r=Hr(e);t.send_enc_mode(Dr.concat([ue.NB("8",Be.SUBSCRIBE),ue.NB("8",r.byteLength),r]))}const qr=new Set(["open","close","closed","socket_data","change","error","message","connecting","closing","server_ready","auth_req","auth_res","auth_fail","auth_clear","cid_req","cid_res","ready","stop","redirecting","pong","echo","iam_res","over_size","text_message"]);class Vr extends dt{constructor(t){super(),this.cid="",this.ip="",this.socket=null,this.url=t,this.state=be.CLOSED,this.stateName=this.getStateName(),this._stateRevision=0,this.txCounter=0,this.rxCounter=0,this.txBytes=0,this.rxBytes=0,this.lastTxRxTime=Date.now(),this.lastRxTime=Date.now(),this._pingSentAt=0,this._reconnectAttempts=0,this._nextConnectAt=0,this.connectionCheckerPeriod=Ee.CONNECTION_CHECKER_PERIOD,this.connectionCheckerIntervalID=null,this.boho=new nt,this.serverTimeNonce=Dr.alloc(nt.MetaSize.SERVER_TIME_NONCE),this.TLS=!1,this.encMode=we.AUTO,this.useAuth=!1,this.nick="",this.channels=new Set,this.promiseMap=new Map,this.promiseTimeOut=Ee.PROMISE_TIMEOUT,this.mid=0,this.quota={maxMessageBytes:null},this.serverSet={},this.linkMap=new Map,this._linkHandlers=new Map,this._listenTags=new Set,this._readyDispatch=!1,this._manualSubscriptions=new Set,this.autoReconnect=!0,this._closed=!1,this.on("open",this.onOpen.bind(this)),this.on("close",this.onClose.bind(this)),this.on("socket_data",this.onData.bind(this))}close(){if(this.clearHelloTimer(),this._pingSentAt=0,!1===this.autoReconnect&&(clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null),this._closed)return;if(this._closed=!0,this.scheduleReconnect(),this.socket){if(0===this.socket.readyState){const t=this.socket;t.onopen=()=>{t&&t.close()},t.onmessage=null,t.onerror=null,t.onclose=null}else try{this.socket.close?.()}catch{}this.socket=null}const t=new Error("Connection closed");t.code="CONNECTION_CLOSED";for(const[,e,r]of this.promiseMap.values())clearTimeout(r),e(t);this.promiseMap.clear(),this._manualSubscriptions.clear(),this.cid="",this.boho&&(this.boho.isAuthorized=!1),this.state!==be.STOP&&this.stateChange("closed")&&this.emit("closed")}stop(){this.autoReconnect=!1,this.close(),this.cid="",this.stateChange("stop","stop")}destroy(){this.stop(),this.removeAllListeners(),this.channels.clear(),this.linkMap.clear(),this._linkHandlers.clear(),this._listenTags.clear(),this._manualSubscriptions.clear(),this.boho=null}keepAlive(){if(Date.now()>=this._nextConnectAt&&this.keepConnection(),!this.isLinkUp())return;const t=Date.now();if(this._pingSentAt&&t-this._pingSentAt>Ee.PONG_TIMEOUT)return this.emit("error",new Error("no reply from the server in "+Ee.PONG_TIMEOUT/1e3+" s; reconnecting")),void this.close();!this._pingSentAt&&t-this.lastRxTime>Ee.CLIENT_PING_PERIOD&&this.ping()}scheduleReconnect(){const t=this._reconnectAttempts++,e=0===t?Math.random()*Ee.RECONNECT_JITTER:Math.min(Ee.RECONNECT_MAX,Ee.RECONNECT_BASE*2**(t-1))*(.8+.4*Math.random());this._nextConnectAt=Date.now()+e}isLinkUp(){return!!this.socket&&!this._closed&&(this.state===be.OPEN||this.state>=be.SERVER_READY)}redirect(t){this.stateChange("redirecting","redirecting"),this.close(),this.createConnection(t),this.armHelloTimer()}armHelloTimer(){if(this.clearHelloTimer(),this._closed||!this.socket)return;const t=this.socket;this.helloTimerID=setTimeout(()=>{this.helloTimerID=null,this.socket===t&&(this.emit("error",new Error("no reply from the server in "+Ee.SERVER_HELLO_TIMEOUT/1e3+" s")),this.close())},Ee.SERVER_HELLO_TIMEOUT)}clearHelloTimer(){this.helloTimerID&&clearTimeout(this.helloTimerID),this.helloTimerID=null}open(t){this.socket&&this.close(),t&&(this.url=t),this.url?(this.createConnection(this.url),this._closed||(this.armHelloTimer(),this.connectionCheckerIntervalID||(this.connectionCheckerIntervalID=setInterval(this.keepAlive.bind(this),this.connectionCheckerPeriod)))):this.emit("error",new Error("URL is not set."))}onOpen(){this._closed=!1,this.lastRxTime=Date.now(),this._pingSentAt=0,this.url.includes("wss://")?this.TLS=!0:this.TLS=!1,this.stateChange("open")}onClose(){this.close()}login(t,e){if(this.serverTimeNonce){this.auth(t,e),this.useAuth=!0;let r=this.boho.auth_req(this.serverTimeNonce);if(!r)return this;this.send(r),this.stateChange("auth_req","auth_req")}return this}auth(t,e){if(null!==e&&""!==e||(e=void 0),"string"!=typeof t||!t||(void 0===e?!/^[^.]+\..+$/.test(t):"string"!=typeof e))return this.emit("error",new Error("auth failed. use auth('id', 'key') or auth('id.key').")),this;const r=void 0===e?t.slice(0,t.indexOf(".")):t;return Fr.encode(r).byteLength>Ee.DID&&this.emit("error",new Error(`auth: login ID '${r}' is longer than ${Ee.DID} bytes and is cut to them.`)),void 0===e?this.boho.set_id_key(t):(this.boho.set_id8(t),this.boho.set_key(e)),this.useAuth=!0,this}onData(t){this.lastRxTime=Date.now(),this._pingSentAt=0;let e,r=t[0];if(r===nt.BohoMsg.ENC_488){if(e=this.boho.decrypt_488(t),!e)return;r=e[0],t=e}else if(r===nt.BohoMsg.ENC_E2E)try{if(e=this.boho.decrypt_488(t),!e)return;r=e[0],t.set(e,nt.MetaSize.ENC_488),t=t.subarray(nt.MetaSize.ENC_488)}catch(t){return}let n=Be[r];switch(n||(n=nt.BohoMsg[r]),r){case Be.OVER_SIZE:console.log("## server sent: over_size event."),this.emit("over_size","over_size");break;case Be.PING:this.pong();break;case Be.PONG:this.emit("pong");break;case Be.ECHO:try{let e=jr.decode(t.subarray(1));this.emit("echo",e)}catch(t){this.emit("error",new Error("ECHO data error"))}break;case Be.IAM_RES:try{let e=jr.decode(t.subarray(1)),r=JSON.parse(e);r.ip&&(this.ip=r.ip),r.nick&&(this.nick=r.nick),r.did&&(this.did=r.did),r.uid&&(this.uid=r.uid),this.emit("iam_res",e)}catch(t){this.emit("error",new Error("IAM_RES data error"))}break;case Be.CID_RES:let r=jr.decode(t.subarray(1));if(this.cid=r,this._reconnectAttempts=0,!this.stateChange("ready"))break;this.subscribe_channels(),this._readyDispatch=!0;try{this.emit("ready","cid_ready")}finally{this._readyDispatch=!1}break;case Be.QUOTA:{if(t.byteLength<5)break;const e=(t[1]|t[2]<<8|t[3]<<16)+16777216*t[4];this.quota={maxMessageBytes:e||null};break}case Be.AUTH_CLEAR:this.useAuth=!1,this.boho.clearAuth(),this.stateChange("auth_clear","server request auth_clear."),this.stop();break;case Be.SERVER_REDIRECT:let n,i,s;7==t.byteLength?(n=function(t){if(6!=t.byteLength)return;return t[0].toString()+"."+t[1].toString()+"."+t[2].toString()+"."+t[3].toString()+":"+((t[4]<<8)+t[5]).toString()}(t.subarray(1)),s="cong://"):(n=jr.decode(t.subarray(1)),s=""),i=s+n,this.redirect(i);break;case nt.BohoMsg.SERVER_TIME_NONCE:if(this.clearHelloTimer(),t.copy(this.serverTimeNonce),!this.stateChange("server_ready","server_ready"))break;this.useAuth?(this.send(this.boho.auth_req(t)),this.stateChange("auth_req","auth_req")):this.send(Dr.from([Be.CID_REQ]));break;case Be.SERVER_SIGNAL:try{let e=jr.decode(t.subarray(1)),r=JSON.parse(e);"string"==typeof r.event&&r.event&&r.data&&!qr.has(r.event)&&(this.serverSet=r.data,this.emit(r.event,r.data))}catch(t){this.emit("error",new Error("SERVER_SIGNAL parsing error"))}break;case Be.SET:try{let e=ue.unpack(t);e&&"string"==typeof e.topic&&!qr.has(e.topic)&&this.emit(e.topic,...e.args??[])}catch(t){this.emit("error",new Error("SET parsing error"))}break;case Be.SIGNAL_E2E:case Be.SIGNAL:try{let e=t.readUint8(1),r=t.subarray(2,2+e),n=jr.decode(r);const i=Fe(t.readUint8(2+e),t.subarray(3+e));i&&(0===n.indexOf("@")?(this.emit("@",n,...i),"@"!==n&&this.emit(n,n,...i)):(qr.has(n)||this.emit(n,n,...i),this.emit("message",n,...i)))}catch(t){console.log("IOCore IOMsg.SIGNAL parser err",t)}break;case Be.RESPONSE_MBP:this.testPromise(t);break;case nt.BohoMsg.AUTH_FAIL:this.boho.isAuthorized=!1,this.stateChange("auth_fail","auth_fail from server.");break;case nt.BohoMsg.AUTH_RES:if(this.boho.verify_auth_res(t)){if(!this.stateChange("auth_res","server sent auth_res"))break;this.send(Dr.from([Be.CID_REQ]))}else this.boho.isAuthorized=!1,this.stateChange("auth_fail","verify_auth_res() invalid server_hmac");break;default:try{e=jr.decode(t),this.emit("text_message",e)}catch(t){}}}iam(t){t?this.send_enc_mode(ue.pack(ue.MB("#MsgType","8",Be.IAM),ue.MB("#",t))):this.send_enc_mode(ue.pack(ue.MB("#MsgType","8",Be.IAM)))}ping(){!this._pingSentAt&&this.isLinkUp()&&(this._pingSentAt=Date.now()),this.send(Dr.from([Be.PING]))}pong(){this.send(Dr.from([Be.PONG]))}echo(t){t?this.send_enc_mode(ue.pack(ue.MB("#MsgType","8",Be.ECHO),ue.MB("#msg",t))):this.send(Dr.from([Be.ECHO]))}bin(...t){this.send(ue.U8pack(...t))}send(t){const e=this.quota.maxMessageBytes;if(null!==e&&t.byteLength>e)return this.emit("over_size"),void console.log(`## quota: ${t.byteLength} bytes is over this connection's maxMessageBytes ${e}`);this.socket_send(t)}getEncryptionMode(){return!(this.encMode!==we.YES&&(this.encMode!==we.AUTO||this.TLS||!this.boho?.isAuthorized))}send_enc_mode(t,e){if(this.boho)if(void 0===e&&(e=this.getEncryptionMode()),t[0]==Be.SIGNAL_E2E&&e){let e=t[1],r=this.boho.encrypt_488(t.subarray(0,3+e));r[0]=nt.BohoMsg.ENC_E2E,this.send(Dr.concat([r,t.subarray(3+e)]))}else if(e){let e=this.boho.encrypt_488(t);this.send(e)}else this.send(t)}setMsgPromise(t){return new Promise((e,r)=>{const n=setTimeout(e=>{this.promiseMap.has(t)&&(r("timeout"),this.promiseMap.delete(t))},this.promiseTimeOut);this.promiseMap.set(t,[e,r,n])})}testPromise(t){let e=ue.unpack(t);if(e)if(this.promiseMap.has(e.mid)){let[t,r,n]=this.promiseMap.get(e.mid);clearTimeout(n),this.promiseMap.delete(e.mid),e.status<128?(e.ok=!0,t(e)):(e.ok=!1,r(e))}else console.log("no promise id")}publish(t,...e){this.signal(t,...e)}signal(t,...e){if("string"!=typeof t)throw TypeError("tag should be string.");t.startsWith("@")&&this.cid&&zr(this.cid+t);let r=$e(t,...e);this.send_enc_mode(r)}decrypt_e2e(t,e){return this.boho.decrypt_e2e(t,e)}signal_e2e(t,e,r){const n=zr(t);if(t.startsWith("@")&&this.cid&&zr(this.cid+t),!this.boho?.isAuthorized)return;let i=ue.B8(e),s=this.boho.encrypt_e2e(i,r),o=ue.pack(ue.MB("#MsgType","8",Be.SIGNAL_E2E),ue.MB("#tagLen","8",n.byteLength),ue.MB("#tag",n),ue.MB("#payloadType","8",_e.BINARY),ue.MB("#payload",s));this.send_enc_mode(o)}set(t,...e){return t&&0!=e.length?this.call("store","set",t,...e):Promise.reject(new Error("set need storeName and value)"))}async get(t){if(!t)return Promise.reject(new Error("store get need storeName)"));let e=await this.call("store","get",t),{$:r}=ue.unpack(e.body);return r}call(t,e,...r){if(!t||!e)return Promise.reject(new Error("request need target and topic)"));if(!this.boho){const t=new Error("Connection closed");return t.code="CONNECTION_CLOSED",Promise.reject(t)}let n;return this.mid=this.mid+1&65535,n=r.length>0?ue.pack(ue.MB("#MsgType","8",Be.CALL),ue.MB("mid","16",this.mid),ue.MB("target",t),ue.MB("topic",e),ue.MBA(...r)):ue.pack(ue.MB("#MsgType","8",Be.CALL),ue.MB("mid","16",this.mid),ue.MB("target",t),ue.MB("topic",e)),this.send_enc_mode(n),this.setMsgPromise(this.mid)}subscribe(t){if(Hr(t),this.boho){if(this.state!==be.READY)throw new Error(`subscribe('${t}') needs a ready connection (state: ${this.stateName}); call it from a ready handler, or use listen() or link()`);Gr(this,t);for(const e of t.split(","))this._manualSubscriptions.add(e)}}subscribe_channels(){if(this.state!==be.READY||0===this.channels.size)return;const t=Array.from(this.channels).join(",").split(","),e=t.map(t=>Hr(t).byteLength),r=[];let n=[],i=0;t.forEach((t,s)=>{n.length&&i+1+e[s]>Ee.TAG_LEN1&&(r.push(n.join(",")),n=[],i=0),i+=(n.length?1:0)+e[s],n.push(t)}),n.length&&r.push(n.join(",")),r.forEach(t=>Gr(this,t))}unsubscribe(t=""){const e=Hr(t);if(""==t)this.channels.clear(),this._listenTags.clear(),this._manualSubscriptions.clear();else{t.split(",").forEach(t=>{this.channels.delete(t),this._listenTags.delete(t),this._manualSubscriptions.delete(t)})}this.send_enc_mode(Dr.concat([ue.NB("8",Be.UNSUBSCRIBE),ue.NB("8",e.byteLength),e]))}listen(t,e){if("string"!=typeof t)throw TypeError("tag should be string.");if(zr(t,!1),"function"!=typeof e)throw TypeError("handler is not a function.");if(this._readyDispatch)throw new Error(`listen('${t}') inside a ready handler: call listen() in the setup code that runs before the connection is ready, or use on() and subscribe() in the ready handler`);0!==t.indexOf("@")&&(Hr(t),this.channels.add(t),this._listenTags.add(t)),this.on(t,e)}link(t,e,r){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if(zr(e,!1),"function"!=typeof r)throw TypeError("handler is not a function.");const n=e.startsWith("@");n||Hr(e);let i=this._linkHandlers.get(t);i||this._linkHandlers.set(t,i=new Map);let s=i.get(e);s||i.set(e,s=new Set);const o=(...t)=>r.apply(this,t);s.add(o);let a=this.linkMap.get(t);a||this.linkMap.set(t,a=new Set),a.add(e),this.on(e,o),n||(this.channels.add(e),this.state===be.READY&&Gr(this,e))}unlink(t,e){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");zr(e,!1);const r=this._linkHandlers.get(t),n=r?.get(e);if(!n)return;for(const t of n)this.removeListener(e,t);r.delete(e);if(this.linkMap.get(t).delete(e),0===r.size&&(this._linkHandlers.delete(t),this.linkMap.delete(t)),e.startsWith("@"))return;[...this._linkHandlers.values()].some(t=>t.has(e))||this._listenTags.has(e)||this.channels.delete(e);const i=new Set([...this.channels].flatMap(t=>t.split(","))),s=e.split(",").filter(t=>!i.has(t)&&!this._manualSubscriptions.has(t));s.length&&this.unsubscribe(s.join(","))}unlinkAll(t){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");const e=this._linkHandlers.get(t);if(e)for(const r of[...e.keys()])this.unlink(t,r)}getMetric(){return{tx:this.txCounter,rx:this.rxCounter,txb:this.txBytes,rxb:this.rxBytes,last:(Date.now()-this.lastTxRxTime)/1e3}}getState(){return this.state}getStateName(){return be[this.state].toLowerCase()}getSecurity(){return{useAuth:this.useAuth,isTLS:this.TLS,isAuthorized:this.boho?.isAuthorized??!1,encMode:this.encMode,usingEncryption:this.getEncryptionMode()}}stateChange(t,e){let r=t.toLowerCase();const n=be[t.toUpperCase()];if("number"!=typeof n)throw new TypeError("Unknown state: "+t);const i=this.state!==n;this.state=n,this.stateName=r,i&&this._stateRevision++;const s=this._stateRevision;return i&&this.emit("change",r),s===this._stateRevision&&(e&&this.emit(r,e),s===this._stateRevision)}}const Wr=nt.Buffer;class Qr extends Vr{static version="9.22.0";static binaryType="arraybuffer";static Boho=nt;static MBP=nt.MBP;static Buffer=nt.Buffer;static constants=Ae;static WebSocket=null;static instanceCount=0;static webSocketCount=0;constructor(t){super(t),Qr.instanceCount++,this.boundBrowserVisiblePing=this.browserVisiblePing.bind(this),document.addEventListener("visibilitychange",this.boundBrowserVisiblePing),t&&this.open()}browserVisiblePing(){"visible"===document.visibilityState&&this.ping()}stop(){super.stop()}destroy(){document.removeEventListener("visibilitychange",this.boundBrowserVisiblePing),super.destroy()}keepConnection(){this.autoReconnect&&(this.socket&&3!==this.socket.readyState||this.open())}createWebSocket(t){return new(this.constructor.WebSocket??WebSocket)(t)}createConnection(t){Qr.webSocketCount++;const e=this.socket=this.createWebSocket(t);this._closed=!1,this.socket.binaryType=Qr.binaryType,this.socket.onopen=()=>{this.socket===e&&("arraybuffer"==this.socket.binaryType?this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessage(t)}:this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessageBlob(t)},this.emit("open"))},this.socket.onerror=t=>{this.socket===e&&this.emit("error",t)},this.socket.onclose=()=>{this.socket===e&&this.emit("close")},this.stateChange("connecting","connecting")}onWebSocketMessage(t){this.rxCounter++,this.lastTxRxTime=Date.now();let e=Wr.from(t.data);this.rxBytes+=e.byteLength,this.emit("socket_data",e)}async onWebSocketMessageBlob(t){const e=this.socket;let r;if(this.rxCounter++,this.lastTxRxTime=Date.now(),t.data instanceof Blob){let e=await t.data.arrayBuffer();r=Wr.from(e)}else r=Wr.from(t.data);this.rxBytes+=r.byteLength,this.socket===e&&this.emit("socket_data",r)}socket_send(t){1===this.socket?.readyState&&(this.socket.send(t),this.txCounter++,this.txBytes+=t.byteLength,this.lastTxRxTime=Date.now())}}class Kr extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;constructor(t){super(),this.url=String(t),this.readyState=0,this.binaryType="blob",this.bufferedAmount=0,this.protocol="",this.extensions="",this.onopen=this.onmessage=this.onerror=this.onclose=null,this.link=null,function(t,{ip:e}={}){const r=mt().get(t);if(r){const{port1:t,port2:n}=new MessageChannel,i=new _t(t);return setTimeout(()=>r.accept(new _t(n),{transport:"MessageChannel",ip:e}),0),At(i)}if("function"!=typeof BroadcastChannel)return Promise.reject(new Error(`no server at ${gt}//${t}`));const n=globalThis.crypto.randomUUID(),i=new Bt(`${bt(t)}:${n}`,"c"),s=new BroadcastChannel(bt(t));return s.postMessage({t:"connect",id:n,ip:e}),s.close(),At(i)}(function(t){const e=String(t);if(!e.startsWith(gt+"//"))throw new TypeError(`not a ${gt}// URL: ${e}`);return e.slice(8).split("?")[0].replace(/\/+$/,"")}(this.url),function(t){const e=String(t).split("?")[1]??"",r=new URLSearchParams(e).get("ip");return r&&r.length<=64?{ip:r}:{}}(this.url)).then(t=>{0===this.readyState?(this.link=t,t.onframe=t=>this.frame(t),this.readyState=1,this.dispatch("open",new Event("open"))):t.close(1e3,"closed while connecting")},t=>{3!==this.readyState&&(this.dispatch("error",Object.assign(new Event("error"),{error:t})),this.finish(1006,t.message))})}get CONNECTING(){return 0}get OPEN(){return 1}get CLOSING(){return 2}get CLOSED(){return 3}frame(t){switch(t.t){case"data":{if(1!==this.readyState)return;let e=t.d;e instanceof ArrayBuffer&&"blob"===this.binaryType&&(e=new Blob([e])),this.dispatch("message",new MessageEvent("message",{data:e}));break}case"ping":this.link.post({t:"pong"});break;case"close":this.link.dispose(),this.finish(t.code??1005,t.reason??"")}}send(t){if(0===this.readyState)throw new DOMException("Still in CONNECTING state.","InvalidStateError");if(1!==this.readyState)return;let e;if("string"==typeof t)e=t;else{e=(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).slice().buffer}this.link.post({t:"data",d:e})}close(t=1e3,e=""){if(this.readyState>=2)return;const r=this.link;this.readyState=2,r&&r.close(t,e),setTimeout(()=>this.finish(t,e),0)}finish(t,e){3!==this.readyState&&(this.readyState=3,this.dispatch("close",Object.assign(new Event("close"),{code:t,reason:e,wasClean:1e3===t})))}dispatch(t,e){this[`on${t}`]?.(e),this.dispatchEvent(e)}}class Yr extends Qr{createWebSocket(t){return String(t).startsWith(gt)?new Kr(t):super.createWebSocket(t)}}export{Qr as IO,Yr as LocalIO,Kr as LocalWebSocket,Rr as Server,Or as attachMonitor,Mr as createBrowserBroker,Nr as readSignal,me as serverOption,Pr as summarize};
|
|
24
|
+
//# sourceMappingURL=broker.js.map
|