iosignal 1.4.2 → 1.5.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.md +247 -240
- package/auth_file.json +13 -13
- package/auth_file.mjs +23 -23
- package/dist/iosignal.cjs +1 -1
- package/dist/iosignal.esm.js.map +1 -1
- package/dist/iosignal.min.js.map +1 -1
- package/index.js +19 -19
- package/indexWebBrowser.js +13 -13
- package/package.json +59 -60
- package/rollup.config.js +69 -69
- package/src/api/RedisAPI.js +68 -68
- package/src/api/api_constant.js +7 -7
- package/src/api/api_reply.js +34 -34
- package/src/api/api_sudo.js +96 -96
- package/src/auth/Auth_Env.js +78 -78
- package/src/auth/Auth_File.js +75 -75
- package/src/auth/Auth_Redis.js +50 -50
- package/src/auth/BohoAuth.js +168 -168
- package/src/client/CongPacket.js +150 -150
- package/src/client/IOCongSocket.js +88 -88
- package/src/client/IOCore.js +851 -851
- package/src/client/IOWS.js +81 -81
- package/src/client/IOWebSocket.js +95 -95
- package/src/common/constants.js +159 -159
- package/src/common/payload.js +82 -82
- package/src/common/quotaTable.js +68 -68
- package/src/common/util.js +61 -61
- package/src/server/FileLogger.js +30 -30
- package/src/server/Manager.js +449 -449
- package/src/server/Metric.js +154 -154
- package/src/server/Server.js +166 -148
- package/src/server/ServerRemote.js +227 -227
- package/src/server/ServerRemoteCore.js +467 -467
- package/src/server/serverOption.js +56 -55
- package/test-browser/favicon.ico +0 -0
- package/test-browser/index.html +92 -92
- package/test-browser/server.js +11 -11
- package/test-client-nodejs/client.cjs +17 -17
- package/test-client-nodejs/client.mjs +17 -17
- package/test-client-nodejs/client_api_reply.mjs +15 -15
- package/test-client-nodejs/stateChange.mjs +19 -19
- package/test-server/server-Auth_Env.js +19 -19
- package/test-server/server-Auth_File.js +12 -12
- package/test-server/server-api_reply.js +6 -6
- package/test-server/server-api_sudo.js +7 -7
- package/test-server/server-commonjs.cjs +8 -8
- package/test-server/server-esm.mjs +19 -19
- package/test-server/simple-server.mjs +11 -11
- package/test-signal-payloadType/signalPack.js +34 -34
- package/test-signal-payloadType/signaling.js +60 -60
package/dist/iosignal.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("crypto"),t=require("stream"),r=require("net"),s=require("zlib"),i=require("fs"),n=require("path"),o=require("os"),a=require("buffer"),h=require("events"),c=require("https"),l=require("http"),f=require("tls"),u=require("url"),d=require("process");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function g(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var _=p(e),y=p(t),m=p(r),b=p(s),E=p(i),w=p(n),v=p(o),S=p(a),k=p(h),A=p(c),T=p(l),L=p(f),x=p(u);function B(e){var t={exports:{}};return e(t,t.exports),t.exports}function C(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.')}for(var I=function(e){var t=H(e),r=t[0],s=t[1];return 3*(r+s)/4-s},O=function(e){var t,r,s=H(e),i=s[0],n=s[1],o=new M(function(e,t,r){return 3*(t+r)/4-r}(0,i,n)),a=0,h=n>0?i-4:i;for(r=0;r<h;r+=4)t=U[e.charCodeAt(r)]<<18|U[e.charCodeAt(r+1)]<<12|U[e.charCodeAt(r+2)]<<6|U[e.charCodeAt(r+3)],o[a++]=t>>16&255,o[a++]=t>>8&255,o[a++]=255&t;2===n&&(t=U[e.charCodeAt(r)]<<2|U[e.charCodeAt(r+1)]>>4,o[a++]=255&t);1===n&&(t=U[e.charCodeAt(r)]<<10|U[e.charCodeAt(r+1)]<<4|U[e.charCodeAt(r+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t);return o},R=function(e){for(var t,r=e.length,s=r%3,i=[],n=16383,o=0,a=r-s;o<a;o+=n)i.push($(e,o,o+n>a?a:o+n));1===s?(t=e[r-1],i.push(N[t>>2]+N[t<<4&63]+"==")):2===s&&(t=(e[r-2]<<8)+e[r-1],i.push(N[t>>10]+N[t>>4&63]+N[t<<2&63]+"="));return i.join("")},N=[],U=[],M="undefined"!=typeof Uint8Array?Uint8Array:Array,P="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",D=0;D<64;++D)N[D]=P[D],U[P.charCodeAt(D)]=D;function H(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function $(e,t,r){for(var s,i,n=[],o=t;o<r;o+=3)s=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),n.push(N[(i=s)>>18&63]+N[i>>12&63]+N[i>>6&63]+N[63&i]);return n.join("")}U["-".charCodeAt(0)]=62,U["_".charCodeAt(0)]=63;var F={byteLength:I,toByteArray:O,fromByteArray:R},j=function(e,t,r,s,i){var n,o,a=8*i-s-1,h=(1<<a)-1,c=h>>1,l=-7,f=r?i-1:0,u=r?-1:1,d=e[t+f];for(f+=u,n=d&(1<<-l)-1,d>>=-l,l+=a;l>0;n=256*n+e[t+f],f+=u,l-=8);for(o=n&(1<<-l)-1,n>>=-l,l+=s;l>0;o=256*o+e[t+f],f+=u,l-=8);if(0===n)n=1-c;else{if(n===h)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,s),n-=c}return(d?-1:1)*o*Math.pow(2,n-s)},z=function(e,t,r,s,i,n){var o,a,h,c=8*n-i-1,l=(1<<c)-1,f=l>>1,u=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=s?0:n-1,p=s?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(h=Math.pow(2,-o))<1&&(o--,h*=2),(t+=o+f>=1?u/h:u*Math.pow(2,1-f))*h>=2&&(o++,h/=2),o+f>=l?(a=0,o=l):o+f>=1?(a=(t*h-1)*Math.pow(2,i),o+=f):(a=t*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;e[r+d]=255&a,d+=p,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;e[r+d]=255&o,d+=p,o/=256,c-=8);e[r+d-p]|=128*g},W=B((function(e,t){const r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=n,t.SlowBuffer=function(e){+e!=e&&(e=0);return n.alloc(+e)},t.INSPECT_MAX_BYTES=50;const s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,n.prototype),t}function n(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return h(e)}return o(e,t,r)}function o(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!n.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|u(e,t);let s=i(r);const o=s.write(e,t);o!==r&&(s=s.slice(0,o));return s}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Q(e,Uint8Array)){const t=new Uint8Array(e);return l(t.buffer,t.byteOffset,t.byteLength)}return c(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Q(e,ArrayBuffer)||e&&Q(e.buffer,ArrayBuffer))return l(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(Q(e,SharedArrayBuffer)||e&&Q(e.buffer,SharedArrayBuffer)))return l(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const s=e.valueOf&&e.valueOf();if(null!=s&&s!==e)return n.from(s,t,r);const o=function(e){if(n.isBuffer(e)){const t=0|f(e.length),r=i(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||K(e.length)?i(0):c(e);if("Buffer"===e.type&&Array.isArray(e.data))return c(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return n.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function a(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function h(e){return a(e),i(e<0?0:0|f(e))}function c(e){const t=e.length<0?0:0|f(e.length),r=i(t);for(let s=0;s<t;s+=1)r[s]=255&e[s];return r}function l(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let s;return s=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(s,n.prototype),s}function f(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function u(e,t){if(n.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,s=arguments.length>2&&!0===arguments[2];if(!s&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return q(e).length;default:if(i)return s?-1:V(e).length;t=(""+t).toLowerCase(),i=!0}}function d(e,t,r){let s=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return L(this,t,r);case"utf8":case"utf-8":return S(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return T(this,t,r);case"base64":return v(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,t,r);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),s=!0}}function p(e,t,r){const s=e[t];e[t]=e[r],e[r]=s}function g(e,t,r,s,i){if(0===e.length)return-1;if("string"==typeof r?(s=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),K(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=n.from(t,s)),n.isBuffer(t))return 0===t.length?-1:_(e,t,r,s,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):_(e,[t],r,s,i);throw new TypeError("val must be string, number or Buffer")}function _(e,t,r,s,i){let n,o=1,a=e.length,h=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return-1;o=2,a/=2,h/=2,r/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){let s=-1;for(n=r;n<a;n++)if(c(e,n)===c(t,-1===s?0:n-s)){if(-1===s&&(s=n),n-s+1===h)return s*o}else-1!==s&&(n-=n-s),s=-1}else for(r+h>a&&(r=a-h),n=r;n>=0;n--){let r=!0;for(let s=0;s<h;s++)if(c(e,n+s)!==c(t,s)){r=!1;break}if(r)return n}return-1}function y(e,t,r,s){r=Number(r)||0;const i=e.length-r;s?(s=Number(s))>i&&(s=i):s=i;const n=t.length;let o;for(s>n/2&&(s=n/2),o=0;o<s;++o){const s=parseInt(t.substr(2*o,2),16);if(K(s))return o;e[r+o]=s}return o}function m(e,t,r,s){return Y(V(t,e.length-r),e,r,s)}function b(e,t,r,s){return Y(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,s)}function E(e,t,r,s){return Y(q(t),e,r,s)}function w(e,t,r,s){return Y(function(e,t){let r,s,i;const n=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)r=e.charCodeAt(o),s=r>>8,i=r%256,n.push(i),n.push(s);return n}(t,e.length-r),e,r,s)}function v(e,t,r){return 0===t&&r===e.length?F.fromByteArray(e):F.fromByteArray(e.slice(t,r))}function S(e,t,r){r=Math.min(e.length,r);const s=[];let i=t;for(;i<r;){const t=e[i];let n=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=r){let r,s,a,h;switch(o){case 1:t<128&&(n=t);break;case 2:r=e[i+1],128==(192&r)&&(h=(31&t)<<6|63&r,h>127&&(n=h));break;case 3:r=e[i+1],s=e[i+2],128==(192&r)&&128==(192&s)&&(h=(15&t)<<12|(63&r)<<6|63&s,h>2047&&(h<55296||h>57343)&&(n=h));break;case 4:r=e[i+1],s=e[i+2],a=e[i+3],128==(192&r)&&128==(192&s)&&128==(192&a)&&(h=(15&t)<<18|(63&r)<<12|(63&s)<<6|63&a,h>65535&&h<1114112&&(n=h))}}null===n?(n=65533,o=1):n>65535&&(n-=65536,s.push(n>>>10&1023|55296),n=56320|1023&n),s.push(n),i+=o}return function(e){const t=e.length;if(t<=k)return String.fromCharCode.apply(String,e);let r="",s=0;for(;s<t;)r+=String.fromCharCode.apply(String,e.slice(s,s+=k));return r}(s)}t.kMaxLength=s,n.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),n.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(n.prototype,"parent",{enumerable:!0,get:function(){if(n.isBuffer(this))return this.buffer}}),Object.defineProperty(n.prototype,"offset",{enumerable:!0,get:function(){if(n.isBuffer(this))return this.byteOffset}}),n.poolSize=8192,n.from=function(e,t,r){return o(e,t,r)},Object.setPrototypeOf(n.prototype,Uint8Array.prototype),Object.setPrototypeOf(n,Uint8Array),n.alloc=function(e,t,r){return function(e,t,r){return a(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},n.allocUnsafe=function(e){return h(e)},n.allocUnsafeSlow=function(e){return h(e)},n.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==n.prototype},n.compare=function(e,t){if(Q(e,Uint8Array)&&(e=n.from(e,e.offset,e.byteLength)),Q(t,Uint8Array)&&(t=n.from(t,t.offset,t.byteLength)),!n.isBuffer(e)||!n.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,s=t.length;for(let i=0,n=Math.min(r,s);i<n;++i)if(e[i]!==t[i]){r=e[i],s=t[i];break}return r<s?-1:s<r?1:0},n.isEncoding=function(e){switch(String(e).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}},n.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return n.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const s=n.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(Q(t,Uint8Array))i+t.length>s.length?(n.isBuffer(t)||(t=n.from(t)),t.copy(s,i)):Uint8Array.prototype.set.call(s,t,i);else{if(!n.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(s,i)}i+=t.length}return s},n.byteLength=u,n.prototype._isBuffer=!0,n.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},n.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},n.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},n.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?S(this,0,e):d.apply(this,arguments)},n.prototype.toLocaleString=n.prototype.toString,n.prototype.equals=function(e){if(!n.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===n.compare(this,e)},n.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+">"},r&&(n.prototype[r]=n.prototype.inspect),n.prototype.compare=function(e,t,r,s,i){if(Q(e,Uint8Array)&&(e=n.from(e,e.offset,e.byteLength)),!n.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===s&&(s=0),void 0===i&&(i=this.length),t<0||r>e.length||s<0||i>this.length)throw new RangeError("out of range index");if(s>=i&&t>=r)return 0;if(s>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let o=(i>>>=0)-(s>>>=0),a=(r>>>=0)-(t>>>=0);const h=Math.min(o,a),c=this.slice(s,i),l=e.slice(t,r);for(let e=0;e<h;++e)if(c[e]!==l[e]){o=c[e],a=l[e];break}return o<a?-1:a<o?1:0},n.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},n.prototype.indexOf=function(e,t,r){return g(this,e,t,r,!0)},n.prototype.lastIndexOf=function(e,t,r){return g(this,e,t,r,!1)},n.prototype.write=function(e,t,r,s){if(void 0===t)s="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)s=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===s&&(s="utf8")):(s=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");let n=!1;for(;;)switch(s){case"hex":return y(this,e,t,r);case"utf8":case"utf-8":return m(this,e,t,r);case"ascii":case"latin1":case"binary":return b(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),n=!0}},n.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const k=4096;function A(e,t,r){let s="";r=Math.min(e.length,r);for(let i=t;i<r;++i)s+=String.fromCharCode(127&e[i]);return s}function T(e,t,r){let s="";r=Math.min(e.length,r);for(let i=t;i<r;++i)s+=String.fromCharCode(e[i]);return s}function L(e,t,r){const s=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>s)&&(r=s);let i="";for(let s=t;s<r;++s)i+=J[e[s]];return i}function x(e,t,r){const s=e.slice(t,r);let i="";for(let e=0;e<s.length-1;e+=2)i+=String.fromCharCode(s[e]+256*s[e+1]);return i}function B(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function C(e,t,r,s,i,o){if(!n.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(r+s>e.length)throw new RangeError("Index out of range")}function I(e,t,r,s,i){H(t,s,i,e,r,7);let n=Number(t&BigInt(4294967295));e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,r}function O(e,t,r,s,i){H(t,s,i,e,r,7);let n=Number(t&BigInt(4294967295));e[r+7]=n,n>>=8,e[r+6]=n,n>>=8,e[r+5]=n,n>>=8,e[r+4]=n;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=o,o>>=8,e[r+2]=o,o>>=8,e[r+1]=o,o>>=8,e[r]=o,r+8}function R(e,t,r,s,i,n){if(r+s>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function N(e,t,r,s,i){return t=+t,r>>>=0,i||R(e,0,r,4),z(e,t,r,s,23,4),r+4}function U(e,t,r,s,i){return t=+t,r>>>=0,i||R(e,0,r,8),z(e,t,r,s,52,8),r+8}n.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const s=this.subarray(e,t);return Object.setPrototypeOf(s,n.prototype),s},n.prototype.readUintLE=n.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||B(e,t,this.length);let s=this[e],i=1,n=0;for(;++n<t&&(i*=256);)s+=this[e+n]*i;return s},n.prototype.readUintBE=n.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||B(e,t,this.length);let s=this[e+--t],i=1;for(;t>0&&(i*=256);)s+=this[e+--t]*i;return s},n.prototype.readUint8=n.prototype.readUInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),this[e]},n.prototype.readUint16LE=n.prototype.readUInt16LE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]|this[e+1]<<8},n.prototype.readUint16BE=n.prototype.readUInt16BE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]<<8|this[e+1]},n.prototype.readUint32LE=n.prototype.readUInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},n.prototype.readUint32BE=n.prototype.readUInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},n.prototype.readBigUInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const s=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(s)+(BigInt(i)<<BigInt(32))})),n.prototype.readBigUInt64BE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const s=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(s)<<BigInt(32))+BigInt(i)})),n.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||B(e,t,this.length);let s=this[e],i=1,n=0;for(;++n<t&&(i*=256);)s+=this[e+n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},n.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||B(e,t,this.length);let s=t,i=1,n=this[e+--s];for(;s>0&&(i*=256);)n+=this[e+--s]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},n.prototype.readInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},n.prototype.readInt16LE=function(e,t){e>>>=0,t||B(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},n.prototype.readInt16BE=function(e,t){e>>>=0,t||B(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},n.prototype.readInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},n.prototype.readInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},n.prototype.readBigInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const s=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(s)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),n.prototype.readBigInt64BE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const s=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(s)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),n.prototype.readFloatLE=function(e,t){return e>>>=0,t||B(e,4,this.length),j(this,e,!0,23,4)},n.prototype.readFloatBE=function(e,t){return e>>>=0,t||B(e,4,this.length),j(this,e,!1,23,4)},n.prototype.readDoubleLE=function(e,t){return e>>>=0,t||B(e,8,this.length),j(this,e,!0,52,8)},n.prototype.readDoubleBE=function(e,t){return e>>>=0,t||B(e,8,this.length),j(this,e,!1,52,8)},n.prototype.writeUintLE=n.prototype.writeUIntLE=function(e,t,r,s){if(e=+e,t>>>=0,r>>>=0,!s){C(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,n=0;for(this[t]=255&e;++n<r&&(i*=256);)this[t+n]=e/i&255;return t+r},n.prototype.writeUintBE=n.prototype.writeUIntBE=function(e,t,r,s){if(e=+e,t>>>=0,r>>>=0,!s){C(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,n=1;for(this[t+i]=255&e;--i>=0&&(n*=256);)this[t+i]=e/n&255;return t+r},n.prototype.writeUint8=n.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,255,0),this[t]=255&e,t+1},n.prototype.writeUint16LE=n.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},n.prototype.writeUint16BE=n.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},n.prototype.writeUint32LE=n.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},n.prototype.writeUint32BE=n.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},n.prototype.writeBigUInt64LE=X((function(e,t=0){return I(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),n.prototype.writeBigUInt64BE=X((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),n.prototype.writeIntLE=function(e,t,r,s){if(e=+e,t>>>=0,!s){const s=Math.pow(2,8*r-1);C(this,e,t,r,s-1,-s)}let i=0,n=1,o=0;for(this[t]=255&e;++i<r&&(n*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/n>>0)-o&255;return t+r},n.prototype.writeIntBE=function(e,t,r,s){if(e=+e,t>>>=0,!s){const s=Math.pow(2,8*r-1);C(this,e,t,r,s-1,-s)}let i=r-1,n=1,o=0;for(this[t+i]=255&e;--i>=0&&(n*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/n>>0)-o&255;return t+r},n.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},n.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},n.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},n.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},n.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},n.prototype.writeBigInt64LE=X((function(e,t=0){return I(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),n.prototype.writeBigInt64BE=X((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),n.prototype.writeFloatLE=function(e,t,r){return N(this,e,t,!0,r)},n.prototype.writeFloatBE=function(e,t,r){return N(this,e,t,!1,r)},n.prototype.writeDoubleLE=function(e,t,r){return U(this,e,t,!0,r)},n.prototype.writeDoubleBE=function(e,t,r){return U(this,e,t,!1,r)},n.prototype.copy=function(e,t,r,s){if(!n.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s<r&&(s=r),s===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t<s-r&&(s=e.length-t+r);const i=s-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,s):Uint8Array.prototype.set.call(e,this.subarray(r,s),t),i},n.prototype.fill=function(e,t,r,s){if("string"==typeof e){if("string"==typeof t?(s=t,t=0,r=this.length):"string"==typeof r&&(s=r,r=this.length),void 0!==s&&"string"!=typeof s)throw new TypeError("encoding must be a string");if("string"==typeof s&&!n.isEncoding(s))throw new TypeError("Unknown encoding: "+s);if(1===e.length){const t=e.charCodeAt(0);("utf8"===s&&t<128||"latin1"===s)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{const o=n.isBuffer(e)?e:n.from(e,s),a=o.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%a]}return this};const M={};function P(e,t,r){M[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function D(e){let t="",r=e.length;const s="-"===e[0]?1:0;for(;r>=s+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function H(e,t,r,s,i,n){if(e>r||e<t){const s="bigint"==typeof t?"n":"";let i;throw i=n>3?0===t||t===BigInt(0)?`>= 0${s} and < 2${s} ** ${8*(n+1)}${s}`:`>= -(2${s} ** ${8*(n+1)-1}${s}) and < 2 ** ${8*(n+1)-1}${s}`:`>= ${t}${s} and <= ${r}${s}`,new M.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){$(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||W(t,e.length-(r+1))}(s,i,n)}function $(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function W(e,t,r){if(Math.floor(e)!==e)throw $(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}P("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),P("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),P("ERR_OUT_OF_RANGE",(function(e,t,r){let s=`The value of "${e}" 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"),s+=` It must be ${t}. Received ${i}`,s}),RangeError);const G=/[^+/0-9A-Za-z-_]/g;function V(e,t){let r;t=t||1/0;const s=e.length;let i=null;const n=[];for(let o=0;o<s;++o){if(r=e.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(o+1===s){(t-=3)>-1&&n.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&n.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function q(e){return F.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,r,s){let i;for(i=0;i<s&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function K(e){return e!=e}const J=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const s=16*r;for(let i=0;i<16;++i)t[s+i]=e[r]+e[i]}return t}();function X(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}));
|
|
2
|
-
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */const G=new TextEncoder,V=new TextDecoder,q=Y;function Y(e,t=0){let r;if(void 0===e||"string"!=typeof e||"number"!=typeof t)throw TypeError("invlaid init variablie type name. ");return(e=e.toUpperCase()).includes("8")?(r=W.Buffer.alloc(1),e.includes("I")?r.writeInt8(t):r.writeUint8(t)):e.includes("16")?(r=W.Buffer.alloc(2),e.includes("I")?e.includes("L")?r.writeInt16LE(t):r.writeInt16BE(t):e.includes("L")?r.writeUint16LE(t):r.writeUint16BE(t)):e.includes("32")?(r=W.Buffer.alloc(4),e.includes("I")?e.includes("L")?r.writeInt32LE(t):r.writeInt32BE(t):e.includes("L")?r.writeUint32LE(t):r.writeUint32BE(t)):e.includes("F")?(r=W.Buffer.alloc(4),e.includes("L")?r.writeFloatLE(t):r.writeFloatBE(t)):e.includes("N")?r=W.Buffer.from(String(t)):console.log(`invalid type: ${e} or initvalue: ${t}`),r}const Q=K;function K(e,t,r){let s,i="B";if("number"==typeof t)"number"==typeof r?(s=W.Buffer.alloc(t),0!==r&&s.fill(r),i="B"):(s=W.Buffer.from(String(t)),i="N");else if("string"==typeof t&&"number"==typeof r)i=t.toUpperCase(),s=Y(t,r);else if("string"==typeof t&&void 0===r)s=W.Buffer.from(t),i="S";else if(t instanceof Uint8Array&&void 0===r)s=t instanceof W.Buffer?t:W.Buffer.from(t);else if(t instanceof ArrayBuffer&&void 0===r)s=W.Buffer.from(t);else if(ArrayBuffer.isView(t))s=W.Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if("object"==typeof t&&void 0===r)s=W.Buffer.from(JSON.stringify(t)),i="O";else{if("boolean"!=typeof t||void 0!==r)throw TypeError("invalid meta buffer type");{const e=t?1:0;s=W.Buffer.from([e]),i="!"}}return"string"==typeof e&&e.includes("#")&&(e=""),[e,i,s]}const J=X;function X(...e){let t=0;return e.map((e=>{const r=t++;return"number"==typeof e?Q(r,"N",e):Q(r,e)}))}function Z(e){if((e=e.toUpperCase()).includes("8"))return e.includes("I")?"int8":"uint8";if(e.includes("16"))return e.includes("I")?e.includes("L")?"int16_le":"int16_be":e.includes("L")?"uint16_le":"uint16_be";if(e.includes("32"))return e.includes("I")?e.includes("L")?"int32_le":"int32_be":e.includes("L")?"uint32_le":"uint32_be";if(e.includes("F"))return e.includes("L")?"float_le":"float_be";if("B"===e)return"buffer";if("S"===e)return"string";if("N"===e)return"number";if("O"===e)return"object";if("!"===e)return"boolean";throw TypeError("invalid data type")}function ee(e,t,r,s){try{const i=Z(e);if("int8"==i)return t.readInt8(r);if("uint8"===i)return t.readUint8(r);if("int16_le"===i)return t.readInt16LE(r);if("int16_be"===i)return t.readInt16BE(r);if("uint16_le"===i)return t.readUint16LE(r);if("uint16_be"===i)return t.readUint16BE(r);if("int32_le"===i)return t.readInt32LE(r);if("int32_be"===i)return t.readInt32BE(r);if("uint32_le"===i)return t.readUint32LE(r);if("uint32_be"===i)return t.readUint32BE(r);if("float_le"===i)return t.readFloatLE(r);if("float_be"===i)return t.readFloatBE(r);if("buffer"===i)return t.subarray(r,r+s);if("string"===i){const e=t.subarray(r,r+s);return V.decode(e)}if("number"===i){const e=t.subarray(r,r+s);return Number(V.decode(e))}if("object"===i){const e=t.subarray(r,r+s);return JSON.parse(V.decode(e))}if("boolean"===i){return 1===t.readInt8(r)}return}catch(e){}}function te(...e){const t=function(e){let t=[];return e.filter((e=>{if(!Array.isArray(e[0]))return e;t=t.concat(e)})).concat(t)}(e);let r=0;const s=[];let i,n,o=0;if(t.forEach((e=>{const[t,i,n]=e;r+=n.byteLength,("number"==typeof t||t.length>0)&&s.push([t,i,o,n.byteLength]),o=r})),s.length>0){let e=JSON.stringify(s);i=G.encode(e),n=i.byteLength,r=r+n+2}const a=W.Buffer.alloc(r);if(o=0,t.forEach((e=>{const t=e[2];a.set(t,o),o+=t.byteLength})),s.length>0){a.set(i,o);const e=q("16",n);return a.set(e,o+n),a}return a}function re(e,t){const r=t||me(e);if(!r)return;const s=W.Buffer.from(e),i={};let n=0;if(r.forEach((e=>{const[t,r,o,a]=e;let h=ee(r,s,o,a);null!=h&&(i[t]=h,a&&(n+=a))})),t&&s.byteLength!==n){let e=s.byteLength-n,t=ee("b",s,n,e);if(null==t)return;i.$OTHERS=t}let o=0,a=[];for(;i[o];)a.push(i[o++]);return a.length>0&&(i.args=a,i.$=i.args),i}const se=ie;function ie(e,t=!1){if(void 0===e)throw TypeError("Invalid data type: Undefined");if("string"==typeof e)return G.encode(e);if("number"==typeof e)return Uint8Array.from([e]);if(e instanceof ArrayBuffer){if(t)return new Uint8Array(e);{const t=new Uint8Array(e),r=new Uint8Array(e.byteLength);return r.set(t),r}}if(ArrayBuffer.isView(e)){if(t)return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);{const t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=new Uint8Array(e.byteLength);return r.set(t),r}}return G.encode(JSON.stringify(e))}const ne=oe;function oe(e,t=!1){const r=ie(e,t);return t?W.Buffer.from(r.buffer,r.byteOffset,r.byteLength):W.Buffer.from(r)}const ae=he;function he(...e){const t=e.map((e=>oe(e)));return W.Buffer.concat(t)}const ce=le;function le(...e){try{let t=0,r=0;const s=e.map((e=>ie(e)));s.forEach((e=>{t+=e.byteLength}));const i=new Uint8Array(t);return s.forEach((e=>{i.set(e,r),r+=e.byteLength})),i}catch(e){console.log(e)}}function fe(e,t){if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function ue(e){return 0===_e(e)?e.byteLength:e.byteLength-_e(e)-pe}function de(e,t){try{const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=r.byteLength-t-2,i=r.subarray(s,r.byteLength-2),n=V.decode(i),o=JSON.parse(n);if(!Array.isArray(o)||!Array.isArray(o[0]))return;let a=o[0];if(!a)return;if(a.length<3)return;const[h,c,l]=a;if("string"!=typeof c||"number"!=typeof l)return;return o}catch(e){}}const pe=2;function ge(e){if(e instanceof ArrayBuffer&&(e=W.Buffer.from(e)),e instanceof Uint8Array){if(e.byteLength<=pe)return 0;return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(e.byteLength-pe)}return 0}function _e(e){if(e instanceof ArrayBuffer&&(e=W.Buffer.from(e)),e instanceof Uint8Array){const t=e.byteLength;if(t<=pe)return 0;const r=ge(e);if(0===r||r>t)return 0;return de(e,r)?r:0}return 0}function ye(e){const t=ue(e);return e.subarray(0,t)}function me(e,t=!1){e instanceof ArrayBuffer&&(e=W.Buffer.from(e));const r=ge(e);if(0===r)return;let s=de(e,r);return s?t?(s.forEach((e=>{null==e[3]&&(e[1].includes("8")?e[3]=1:e[1].includes("16")?e[3]=2:e[1].includes("32")||e[1].includes("F")?e[3]=4:e[1].includes("!")&&(e[3]=1)),e[4]=Z(e[1])})),s):s:void 0}function be(...e){return ye(te(...e))}function Ee(...e){return me(te(...e))}var we=Object.freeze({__proto__:null,Buffer:W.Buffer,NB:q,numberBuffer:Y,MB:Q,metaBuffer:K,MBA:J,metaBufferArguments:X,parseTypeName:Z,readTypedBuffer:ee,pack:te,unpack:re,U8:se,parseUint8Array:ie,B8:ne,parseBuffer:oe,B8pack:ae,parseBufferThenConcat:he,U8pack:ce,parseUint8ThenConcat:le,hex:function(e){return Array.prototype.map.call(new Uint8Array(e),(e=>("00"+e.toString(16)).slice(-2))).join("")},equal:fe,getBufferSize:ue,parseMetaInfo:de,TAIL_LEN:pe,readTail:ge,getMetaSize:_e,getBuffer:ye,getMeta:me,rawPack:be,meta:Ee,metaDetail:function(...e){return me(te(...e),!0)},getMetaDetail:function(e){return me(e,!0)}}),ve=B((function(e){var t=Object.prototype.hasOwnProperty,r="~";function s(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,s,n,o){if("function"!=typeof s)throw new TypeError("The listener must be a function");var a=new i(s,n||e,o),h=r?r+t:t;return e._events[h]?e._events[h].fn?e._events[h]=[e._events[h],a]:e._events[h].push(a):(e._events[h]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function a(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,s,i=[];if(0===this._eventsCount)return i;for(s in e=this._events)t.call(e,s)&&i.push(r?s.slice(1):s);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var i=0,n=s.length,o=new Array(n);i<n;i++)o[i]=s[i].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,s=this._events[t];return s?s.fn?1:s.length:0},a.prototype.emit=function(e,t,s,i,n,o){var a=r?r+e:e;if(!this._events[a])return!1;var h,c,l=this._events[a],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,s),!0;case 4:return l.fn.call(l.context,t,s,i),!0;case 5:return l.fn.call(l.context,t,s,i,n),!0;case 6:return l.fn.call(l.context,t,s,i,n,o),!0}for(c=1,h=new Array(f-1);c<f;c++)h[c-1]=arguments[c];l.fn.apply(l.context,h)}else{var u,d=l.length;for(c=0;c<d;c++)switch(l[c].once&&this.removeListener(e,l[c].fn,void 0,!0),f){case 1:l[c].fn.call(l[c].context);break;case 2:l[c].fn.call(l[c].context,t);break;case 3:l[c].fn.call(l[c].context,t,s);break;case 4:l[c].fn.call(l[c].context,t,s,i);break;default:if(!h)for(u=1,h=new Array(f-1);u<f;u++)h[u-1]=arguments[u];l[c].fn.apply(l[c].context,h)}}return!0},a.prototype.on=function(e,t,r){return n(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return n(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,s,i){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return o(this,n),this;var a=this._events[n];if(a.fn)a.fn!==t||i&&!a.once||s&&a.context!==s||o(this,n);else{for(var h=0,c=[],l=a.length;h<l;h++)(a[h].fn!==t||i&&!a[h].once||s&&a[h].context!==s)&&c.push(a[h]);c.length?this._events[n]=1===c.length?c[0]:c:o(this,n)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}));const Se=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 ke(e,t,r,s,i){let n,o,a,h,c,l,f,u,d,p,g,_,y;for(;i>=64;){for(n=t[0],o=t[1],a=t[2],h=t[3],c=t[4],l=t[5],f=t[6],u=t[7],p=0;p<16;p++)g=s+4*p,e[p]=(255&r[g])<<24|(255&r[g+1])<<16|(255&r[g+2])<<8|255&r[g+3];for(p=16;p<64;p++)d=e[p-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,d=e[p-15],y=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,e[p]=(_+e[p-7]|0)+(y+e[p-16]|0);for(p=0;p<64;p++)_=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&l^~c&f)|0)+(u+(Se[p]+e[p]|0)|0)|0,y=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&o^n&a^o&a)|0,u=f,f=l,l=c,c=h+_|0,h=a,a=o,o=n,n=_+y|0;t[0]+=n,t[1]+=o,t[2]+=a,t[3]+=h,t[4]+=c,t[5]+=l,t[6]+=f,t[7]+=u,s+=64,i-=64}return s}const Ae=function(){function e(){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 e.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},e.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},e.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");let r=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[r++],t--;64===this.bufferLength&&(ke(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(r=ke(this.temp,this.state,e,r,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[r++],t--;return this},e.prototype.finish=function(e){if(!this.finished){const e=this.bytesHashed,r=this.bufferLength,s=e/536870912|0,i=e<<3,n=e%64<56?64:128;this.buffer[r]=128;for(var t=r+1;t<n-8;t++)this.buffer[t]=0;this.buffer[n-8]=s>>>24&255,this.buffer[n-7]=s>>>16&255,this.buffer[n-6]=s>>>8&255,this.buffer[n-5]=s>>>0&255,this.buffer[n-4]=i>>>24&255,this.buffer[n-3]=i>>>16&255,this.buffer[n-2]=i>>>8&255,this.buffer[n-1]=i>>>0&255,ke(this.temp,this.state,this.buffer,0,n),this.finished=!0}for(t=0;t<8;t++)e[4*t+0]=this.state[t]>>>24&255,e[4*t+1]=this.state[t]>>>16&255,e[4*t+2]=this.state[t]>>>8&255,e[4*t+3]=this.state[t]>>>0&255;return this},e.prototype.digest=function(){const e=new Uint8Array(this.digestLength);return this.finish(e),e},e.prototype._saveState=function(e){for(let t=0;t<this.state.length;t++)e[t]=this.state[t]},e.prototype._restoreState=function(e,t){for(let t=0;t<this.state.length;t++)this.state[t]=e[t];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},e}(),Te=function(){function e(e){this.inner=new Ae,this.outer=new Ae,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;const t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new Ae).update(e).finish(t).clean();else for(var r=0;r<e.length;r++)t[r]=e[r];for(r=0;r<t.length;r++)t[r]^=54;this.inner.update(t);for(r=0;r<t.length;r++)t[r]^=106;this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(r=0;r<t.length;r++)t[r]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(let e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){const e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function Le(e){const t=(new Ae).update(e),r=t.digest();return t.clean(),r}const xe={hash:function(e){return Le(se(e))},hex:function(e){return ne(Le(se(e))).toString("hex")},base64:function(e){return ne(Le(se(e))).toString("base64")}};xe.hmac=function(e,t){return function(e,t){const r=new Te(e).update(t),s=r.digest();return r.clean(),s}(se(e),se(t))};const Be=Q;let Ce={AUTH_REQ:176,AUTH_NONCE:177,AUTH_HMAC:178,AUTH_ACK:179,AUTH_FAIL:180,AUTH_EXT:181,ENC_PACK:182,ENC_E2E:183,ENC_488:184};for(let e in Ce)Ce[Ce[e]]=e;const Ie={AUTH_REQ:Ee(Be("header","8",0),Be("reserved","8",0)),AUTH_NONCE:Ee(Be("header","8",0),Be("unixTime","32L",0),Be("milTime","32L",0),Be("nonce",W.Buffer.alloc(4))),AUTH_HMAC:Ee(Be("header","8",0),Be("id8",W.Buffer.alloc(8)),Be("nonce",W.Buffer.alloc(4)),Be("hmac32",W.Buffer.alloc(32))),AUTH_ACK:Ee(Be("header","8",0),Be("hmac32",W.Buffer.alloc(32))),ENC_PACK:Ee(Be("type","8",0),Be("len","32L",0),Be("salt12",W.Buffer.alloc(12)),Be("hmac",8,0)),ENC_488:Ee(Be("type","8",0),Be("len","32L",0),Be("otpSrc8",W.Buffer.alloc(8)),Be("hmac8",W.Buffer.alloc(8)))};function Oe(e){let t=e[e.length-1];return t[2]+t[3]}const Re={AUTH_REQ:Oe(Ie.AUTH_REQ),AUTH_NONCE:Oe(Ie.AUTH_NONCE),AUTH_HMAC:Oe(Ie.AUTH_HMAC),AUTH_ACK:Oe(Ie.AUTH_ACK),ENC_PACK:Oe(Ie.ENC_PACK),ENC_488:Oe(Ie.ENC_488)};let Ne=!1;try{Ne="[object process]"===Object.prototype.toString.call(global.process)}catch(e){}function Ue(t){return Ne?e.webcrypto.getRandomValues(W.Buffer.alloc(t)):self.crypto.getRandomValues(W.Buffer.alloc(t))}class Me{constructor(){this._id8=W.Buffer.alloc(8),this._otpSrc44=W.Buffer.alloc(44),this._otp36=W.Buffer.alloc(36),this._hmac=W.Buffer.alloc(32),this.auth_salt12=W.Buffer.alloc(12),this.localNonce=W.Buffer.alloc(4),this.remoteNonce=W.Buffer.alloc(4),this.isAuthorized=!1}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}set_hash_id8(e){ne(xe.hash(e)).copy(this._id8,0,0,8)}set_id8(e){let t=ne(e);this._id8.fill(0),t.copy(this._id8,0,0,8)}set_key(e){ne(xe.hash(e)).copy(this._otpSrc44,0,0,32)}set_id_key(e){let t=e.indexOf(".");if(-1==t)return;let r=e.substring(0,t),s=e.substring(t+1);this.set_id8(r),this.set_key(s)}copy_id8(e){e.copy(this._id8,0,0,8)}copy_key(e){e.copy(this._otpSrc44,0,0,32)}sha256_n(e,t){let r=xe.hash(e);for(let e=0;e<t;e++)r=xe.hash(r);return r}set_clock_rand(){let e=Date.now(),t=parseInt(e/1e3);e%=4294967295;W.Buffer.concat([q("32L",t),q("32L",e),Ue(4)]).copy(this._otpSrc44,32)}set_clock_nonce(e){let t=Date.now(),r=parseInt(t/1e3);t%=4294967295;W.Buffer.concat([q("32L",r),q("32L",t),e]).copy(this._otpSrc44,32)}set_salt12(e){e.copy(this._otpSrc44,32)}resetOTP(){ne(xe.hash(this._otpSrc44)).copy(this._otp36,0,0,32)}getIndexOTP(e){return this._otp36.writeUInt32LE(e,32),xe.hash(this._otp36)}generateHMAC(e){let t=W.Buffer.concat([this._otpSrc44,e]);this._hmac=ne(xe.hash(t))}getHMAC8(e){let t=W.Buffer.concat([this._otpSrc44,e]);return this._hmac=ne(xe.hash(t)),this._hmac.subarray(0,8)}xotp(e,t=0,r=!1){let s=(e=ne(e,r)).byteLength,i=t,n=0,o=0;for(;s>0;){o=s<32?s:32;let t=this.getIndexOTP(++i);for(let r=0;r<o;r++)e[n++]^=t[r];s-=32}return e}auth_req(){return te(Q("#type","8",Ce.AUTH_REQ),Q("#reserved","8",0))}auth_nonce(){let e=Date.now(),t=Math.floor(e/1e3),r=e%1e3;return this.localNonce=Ue(4),this.auth_salt12=W.Buffer.concat([q("32L",t),q("32L",r),this.localNonce]),W.Buffer.concat([q("8",Ce.AUTH_NONCE),this.auth_salt12])}auth_hmac(e){let t=re(e,Ie.AUTH_NONCE);if(t){let e=W.Buffer.concat([q("32L",t.unixTime),q("32L",t.milTime),t.nonce]);return this.set_salt12(e),this.localNonce=Ue(4),this.generateHMAC(this.localNonce),this.remoteNonce=t.nonce,te(Q("#header","8",Ce.AUTH_HMAC),Q("#id8",this._id8),Q("#nonce",this.localNonce),Q("#hmac32",this._hmac))}return!1}check_auth_hmac(e){let t;if(e instanceof Uint8Array){if(t=re(e,Ie.AUTH_HMAC),!t)return}else t=e;this.set_salt12(this.auth_salt12),this.generateHMAC(t.nonce);let r=this._hmac;if(fe(t.hmac32,r)){this.remoteNonce=t.nonce;let e=W.Buffer.concat([this.localNonce,this.remoteNonce,this.localNonce]);this.set_salt12(e),this.generateHMAC(t.nonce);let r=this._hmac,s=be(Q("header","8",Ce.AUTH_ACK),Q("hmac32",r));return this.isAuthorized=!0,s}return!1}check_auth_ack_hmac(e){let t=re(e,Ie.AUTH_ACK);if(t){let e=W.Buffer.concat([this.remoteNonce,this.localNonce,this.remoteNonce]);if(this.set_salt12(e),this.generateHMAC(this.localNonce),fe(this._hmac,t.hmac32))return this.isAuthorized=!0,!0}}encrypt_488(e){if(!this.isAuthorized)return;e=ne(e),this.set_clock_nonce(this.remoteNonce),this.resetOTP();let t=this.getHMAC8(e),r=this.xotp(e);return te(Q("#type","8",Ce.ENC_488),Q("#len","32L",e.byteLength),Q("#otpSrc8",this._otpSrc44.subarray(32,40)),Q("#hmac8",t),Q("#xdata",r))}decrypt_488(e){let t=re(e=ne(e),Ie.ENC_488);if(t){let e=W.Buffer.concat([t.otpSrc8,this.localNonce]);this.set_salt12(e),this.resetOTP();let r=t.$OTHERS.subarray(0,t.len),s=this.xotp(r);if(fe(this.getHMAC8(s),t.hmac8))return s}}encryptPack(e){e=ne(e),this.set_clock_rand(),this.resetOTP();let t=this.getHMAC8(e),r=this.xotp(e);return te(Q("#type","8",Ce.ENC_PACK),Q("#len","32L",e.byteLength),Q("#salt12",this._otpSrc44.subarray(32)),Q("#hmac8",t),Q("#xdata",r))}decryptPack(e){if(e[0]!==Ce.ENC_PACK)return;if(e.readUint32LE(1)==e.byteLength-Re.ENC_PACK)try{let t=re(e,Ie.ENC_PACK);if(!t)return;this.set_salt12(t.salt12),this.resetOTP();let r=t.$OTHERS,s=this.xotp(r),i=this.getHMAC8(s);if(fe(t.hmac,i))return t.data=s,t}catch(e){}}encrypt_e2e(e,t){let r=W.Buffer.alloc(32);r.set(this._otpSrc44.subarray(0,32)),this.set_key(t);let s=this.encryptPack(e);return this._otpSrc44.set(r),s}decrypt_e2e(e,t){let r=W.Buffer.alloc(32);r.set(this._otpSrc44.subarray(0,32)),this.set_key(t);let s=this.decryptPack(e);return this._otpSrc44.set(r),s}}const Pe={OPENING:0,OPEN:1,CLOSING:2,CLOSED:3,SERVER_READY:4,AUTH_FAIL:5,AUTH_READY:6,READY:7,REDIRECTING:8};for(let e in Pe)Pe[Pe[e]]=e;const De={INIT:0,SENT_SERVER_READY:1,RECV_AUTH_REQ:2,SENT_SERVER_NONCE:3,RECV_AUTH_HMAC:4,AUTH_FAIL:5,AUTH_READY:6,CID_READY:7};for(let e in De)De[De[e]]=e;let He={NO:0,YES:1,AUTO:2};for(let e in He)He[He[e]]=e;const $e={TAG_LEN1:255,TAG_LEN2:65535,CONNECTION_CHECKER_PERIOD:3e3,PROMISE_TIMEOUT:5e3,DID:8,CID:12};let Fe={EMPTY:0,TEXT:1,BINARY:2,OBJECT:3,MJSON:4,MBA:5};for(let e in Fe)Fe[Fe[e]]=e;let je={SERVER_READY:192,CID_REQ:193,CID_RES:194,QUOTA_LEVEL:195,SERVER_CLEAR_AUTH:196,SERVER_REDIRECT:197,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_CODE:220,RESPONSE_MBP:221,REQUEST:222,RESPONSE:223,FLOW_MODE:240,WAIT:241,RESUME:242,TIME_OUT:253,OVER_SIZE:254,OVER_FLOW:255};for(let e in je)je[je[e]]=e;let ze={0:{signalSize:1500,publishCounter:10,trafficRate:1e4},1:{signalSize:255,publishCounter:10,trafficRate:1e5},2:{signalSize:65535,publishCounter:10,trafficRate:1048576},3:{signalSize:1048576,publishCounter:10,trafficRate:20971520},10:{signalSize:1500,publishCounter:5,trafficRate:20971520},11:{signalSize:65535,publishCounter:10,trafficRate:20971520},12:{signalSize:1048576,publishCounter:100,trafficRate:20971520},200:{signalSize:20971520,publishCounter:1e4,trafficRate:104857600},255:{signalSize:20971520,publishCounter:1e4,trafficRate:104857600}};const We=new TextEncoder;function Ge(e,...t){if("string"!=typeof e)throw TypeError("tag should be string.");let r,s=We.encode(e),i=function(e){let t,r;if(0==e.length)t=Fe.EMPTY,r=null;else if(1==e.length)if("string"==typeof e[0]||"number"==typeof e[0])t=Fe.TEXT,r=We.encode(e[0]+"."),r[r.byteLength-1]=0;else if(ArrayBuffer.isView(e[0])||e[0]instanceof ArrayBuffer)t=Fe.BINARY,r=ne(e[0]);else{if("object"!=typeof e[0])throw new Error("unknown payload arguments");t=Fe.OBJECT,r=We.encode(JSON.stringify(e[0]))}else{let s=!1;e.forEach((e=>{(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)&&(s=!0)})),s?t=Fe.MBA:(t=Fe.MJSON,r=We.encode(JSON.stringify(e)))}return{type:t,buffer:r}}(t);if(i.type==Fe.EMPTY)r=te(Q("#MsgType","8",je.SIGNAL),Q("#tagLen","8",s.byteLength),Q("#tag",s),Q("#payloadType","8",i.type));else if(i.type==Fe.MBA){let e=te(J(...t));r=te(Q("#MsgType","8",je.SIGNAL),Q("#tagLen","8",s.byteLength),Q("#tag",s),Q("#payloadType","8",i.type),Q("#mbaBuffer",e))}else r=te(Q("#MsgType","8",je.SIGNAL),Q("#tagLen","8",s.byteLength),Q("#tag",s),Q("#payloadType","8",i.type),Q("#payload",i.buffer));return r}const Ve=new TextEncoder,qe=new TextDecoder;class Ye extends ve{constructor(e){super(),this.cid="",this.ip="",this.socket=null,this.url=e,this.state=Pe.CLOSED,this.stateName=this.getStateName(),this.txCounter=0,this.rxCounter=0,this.txBytes=0,this.rxBytes=0,this.lastTxRxTime=Date.now(),this.connectionCheckerPeriod=$e.CONNECTION_CHECKER_PERIOD,this.connectionCheckerIntervalID=null,this.boho=new Me,this.TLS=!1,this.encMode=He.AUTO,this.useAuth=!1,this.nick="",this.channels=new Set,this.promiseMap=new Map,this.promiseTimeOut=$e.PROMISE_TIMEOUT,this.mid=0,this.level=3,this.quota=ze[this.level],this.serverSet={},this.linkMap=new Map,this.on("open",this.onOpen.bind(this)),this.on("close",this.onClose.bind(this)),this.on("socket_data",this.onData.bind(this))}redirect(e){this.close(),this.stateChange("redirecting"),this.createConnection(e)}open(e){if(e||this.url){if(e)if(this.url){if(e!==this.url&&(this.url=e,this.socket))return void this.close()}else this.url=e;this.createConnection(this.url),this.connectionCheckerIntervalID||(this.connectionCheckerIntervalID=setInterval(this.keepAlive.bind(this),this.connectionCheckerPeriod))}}onOpen(){this.url.includes("wss://")?this.TLS=!0:this.TLS=!1,this.stateChange("open")}onClose(){this.boho.isAuthorized=!1,this.cid="",this.stateChange("closed")}login(e,t){if(!e&&!t)return void console.log("no id and key.");if(console.log("manual login: ",e),!t&&e.includes("."))this.boho.set_id_key(e);else{if(!e||!t)return void console.log("no id or key.");this.boho.set_id8(e),this.boho.set_key(t)}this.useAuth=!0;let r=this.boho.auth_req();this.send(r)}auth(e,t){if(e||t){if(!t&&e.includes("."))this.boho.set_id_key(e);else{if(!e||!t)return void console.log("no id or key.");this.boho.set_id8(e),this.boho.set_key(t)}this.useAuth=!0}else console.log("no id and key.")}onData(e){let t,r=e[0];if(r===Ce.ENC_488)t=this.boho.decrypt_488(e),t&&(r=t[0],e=t);else if(r===Ce.ENC_E2E)try{if(t=this.boho.decrypt_488(e),!t)return;r=t[0],e.set(t,Re.ENC_488),e=e.subarray(Re.ENC_488)}catch(e){return}let s=je[r];switch(s||(s=Ce[r]),r){case je.OVER_SIZE:console.log("## server sent: over_size event."),this.emit("over_size","over_size");break;case je.PING:this.pong();break;case je.PONG:break;case je.IAM_RES:try{let t=qe.decode(e.subarray(1)),r=JSON.parse(t);r.ip&&(this.ip=r.ip),console.log("<IAM_RES>",JSON.stringify(r))}catch(e){}break;case je.CID_RES:let r=qe.decode(e.subarray(1));this.cid=r,this.stateChange("ready","cid_ready"),this.subscribe_memory_channels();break;case je.QUOTA_LEVEL:let s=e[1];this.level=s,this.quota=ze[s],console.log("## QUOTA:",s,JSON.stringify(this.quota));break;case je.SERVER_CLEAR_AUTH:this.useAuth=!1,this.boho.clearAuth(),this.stop();break;case je.SERVER_REDIRECT:let i,n,o;7==e.byteLength?(i=function(e){if(6!=e.byteLength)return;return e[0].toString()+"."+e[1].toString()+"."+e[2].toString()+"."+e[3].toString()+":"+((e[4]<<8)+e[5]).toString()}(e.subarray(1)),o="cong://"):(i=qe.decode(e.subarray(1)),o=""),n=o+i,this.redirect(n);break;case je.SERVER_READY:this.stateChange("server_ready","server_ready"),this.useAuth?this.send(this.boho.auth_req()):this.send(W.Buffer.from([je.CID_REQ]));break;case je.SERVER_SIGNAL:try{let t=qe.decode(e.subarray(1)),r=JSON.parse(t);r.event&&r.data&&(this.serverSet=r.data,this.emit(r.event,r.data))}catch(e){}break;case je.SET:try{let t=re(e);t&&this.emit(t.topic,...t.args)}catch(e){}break;case je.SIGNAL_E2E:case je.SIGNAL:try{let t=e.readUint8(1),r=e.subarray(2,2+t),s=qe.decode(r),i=e.readUint8(2+t),n=e.subarray(3+t);switch(i){case Fe.EMPTY:0===s.indexOf("@")?this.emit("@",null,s):this.emit(s,null,s);break;case Fe.TEXT:let e=n.subarray(0,n.byteLength-1),t=qe.decode(e);0===s.indexOf("@")&&this.emit("@",t,s),"@"!==s&&this.emit(s,t,s);break;case Fe.BINARY:0===s.indexOf("@")&&this.emit("@",n,s),"@"!==s&&this.emit(s,n,s);break;case Fe.OBJECT:let r=qe.decode(n),i=JSON.parse(r);0===s.indexOf("@")&&this.emit("@",i,s),"@"!==s&&this.emit(s,i,s);break;case Fe.MJSON:let o=qe.decode(n),a=JSON.parse(o);0===s.indexOf("@")&&this.emit("@",...a,s),"@"!==s&&this.emit(s,...a,s);break;case Fe.MBA:let h=re(n);0===s.indexOf("@")&&this.emit("@",...h.args,s),"@"!==s&&this.emit(s,...h.args,s)}}catch(e){}break;case je.RESPONSE_MBP:this.testPromise(e);break;case Ce.AUTH_NONCE:let a=this.boho.auth_hmac(e);a?this.send(a):this.stateChange("auth_fail","Invalid local auth_hmac.");break;case Ce.AUTH_FAIL:this.stateChange("auth_fail","server reject auth.");break;case Ce.AUTH_ACK:this.boho.check_auth_ack_hmac(e)?(this.stateChange("auth_ready","server sent auth_ack"),this.send(W.Buffer.from([je.CID_REQ]))):this.stateChange("auth_fail","invalid server_hmac");break;default:try{t=qe.decode(e),this.emit("text_message",t)}catch(e){}}}iam(e){e?this.send_enc_mode(te(Q("#MsgType","8",je.IAM),Q("#",e))):this.send_enc_mode(te(Q("#MsgType","8",je.IAM)))}ping(){this.send(W.Buffer.from([je.PING]))}pong(){this.send(W.Buffer.from([je.PONG]))}echo(e){e?(console.log("echo args:",e),this.send_enc_mode(te(Q("#MsgType","8",je.ECHO),Q("#msg",e)))):this.send(W.Buffer.from([je.ECHO]))}bin(...e){this.send(ce(...e))}send(e){if(e.byteLength>this.quota.signalSize)return this.emit("over_size"),console.log("## QUOTA LIMIT OVER!! \nsignal message.byteLength: ",e.byteLength),void console.log("## your maximum signalSize(bytes) is:",this.quota.signalSize);this.socket_send(e)}getEncryptionMode(){return!(this.encMode!==He.YES&&(this.encMode!==He.AUTO||this.TLS||!this.boho.isAuthorized))}send_enc_mode(e,t){if(void 0===t&&(t=this.getEncryptionMode()),e[0]==je.SIGNAL_E2E&&t){let t=e[1],r=this.boho.encrypt_488(e.subarray(0,3+t));r[0]=Ce.ENC_E2E,this.send(W.Buffer.concat([r,e.subarray(3+t)]))}else if(t){let t=this.boho.encrypt_488(e);this.send(t)}else this.send(e)}setMsgPromise(e){return new Promise(((t,r)=>{this.promiseMap.set(e,[t,r]),setTimeout((t=>{this.promiseMap.has(e)&&(r("timeout"),this.promiseMap.delete(e))}),this.promiseTimeOut)}))}testPromise(e){let t=re(e);if(t)if(this.promiseMap.has(t.mid)){let[e,r]=this.promiseMap.get(t.mid);this.promiseMap.delete(t.mid),t.status<128?(t.ok=!0,e(t)):(t.ok=!1,r(t))}else console.log("no promise id")}publish(...e){this.signal(...e)}signal(e,...t){if("string"!=typeof e)throw TypeError("tag should be string.");let r=Ge(e,...t);this.send_enc_mode(r)}decrypt_e2e(e,t){return this.boho.decrypt_e2e(e,t)}signal_e2e(e,t,r){if("string"!=typeof e)throw TypeError("tag should be string.");let s=Ve.encode(e),i=ne(t),n=this.boho.encrypt_e2e(i,r),o=te(Q("#MsgType","8",je.SIGNAL_E2E),Q("#tagLen","8",s.byteLength),Q("#tag",s),Q("#payloadType","8",Fe.BINARY),Q("#payload",n));this.send_enc_mode(o)}set(e,...t){return e&&0!=t.length?this.req("store","set",e,...t):Promise.reject(new Error("set need storeName and value)"))}async get(e){if(!e)return Promise.reject(new Error("store get need storeName)"));let t=await this.req("store","get",e),{$:r}=re(t.body);return r}req(e,t,...r){if(!e||!t)return Promise.reject(new Error("request need target and topic)"));let s;return s=r.length>0?te(Q("#MsgType","8",je.REQUEST),Q("mid","16",++this.mid),Q("target",e),Q("topic",t),J(...r)):te(Q("#MsgType","8",je.REQUEST),Q("mid","16",++this.mid),Q("target",e),Q("topic",t)),this.send_enc_mode(s),this.setMsgPromise(this.mid)}subscribe(e){if("string"!=typeof e)throw TypeError("tag should be string.");if(this.state!==Pe.READY)return;e.split(",").forEach((e=>{this.channels.add(e)}));let t=Ve.encode(e);if(t.byteLength>$e.TAG_LEN1)throw TypeError("please use tag string bytelength below:"+$e.TAG_LEN1);this.send_enc_mode(W.Buffer.concat([q("8",je.SUBSCRIBE),q("8",t.byteLength),t]))}subscribe_promise(e){if("string"!=typeof e)throw TypeError("tag should be string.");if(this.state!==Pe.READY)return Promise.reject("subscribe_promise:: connection is not ready");let t=Ve.encode(e);if(t.byteLength>$e.TAG_LEN2)throw TypeError("please use tag string bytelength: "+$e.TAG_LEN2);return this.send_enc_mode(W.Buffer.concat([q("8",je.SUBSCRIBE_REQ),q("16",++this.mid),q("16",t.byteLength),t])),this.setMsgPromise(this.mid)}subscribe_memory_channels(){if(0==this.channels.size)return;let e=Array.from(this.channels).join(",");this.subscribe_promise(e).then((e=>{})).catch((e=>{console.log(">> SUBSCRIBE FAIL:",e)}))}unsubscribe(e=""){if("string"!=typeof e)throw TypeError("tag should be string.");if(""==e)this.channels.clear();else{e.split(",").forEach((e=>{this.channels.delete(e)}))}let t=Ve.encode(e);if(t.byteLength>$e.TAG_LEN1)throw TypeError("please use tag string bytelength below:"+$e.TAG_LEN1);this.send_enc_mode(W.Buffer.concat([q("8",je.UNSUBSCRIBE),q("8",t.byteLength),t]))}listen(e,t){if("string"!=typeof e)throw TypeError("tag should be string.");if(e.length>255||0==e.length)throw TypeError("tag string length range: 1~255");if("function"!=typeof t)throw TypeError("handler is not a function.");0!==e.indexOf("@")&&this.channels.add(e),this.on(e,t)}link(e,t,r){if("string"!=typeof e)throw TypeError("to(local link target) is not a string.");if("string"!=typeof t)throw TypeError("tag is not a string.");if(t.length>255||0==t.length)throw TypeError("tag string length range: 1~255");if("function"!=typeof r)throw TypeError("handler is not a function.");let s;0!==t.indexOf("@")&&this.channels.add(t),s=this.linkMap.has(e)?this.linkMap.get(e):new Set,s.add(t),this.linkMap.set(e,s),this.on(t,r),this.subscribe(t)}unlink(e,t){if("string"!=typeof e)throw TypeError("to(local link target) is not a string.");if("string"!=typeof t)throw TypeError("tag is not a string.");if(t.length>255||0==t.length)throw TypeError("tag string length range: 1~255");if(!this.linkMap.has(e))return;let r=this.linkMap.get(e),s=Array.from(r);for(let i=0;i<s.length;i++)if(s[i]==t){this.unsubscribe(t),this.removeAllListeners(t),r.delete(t),this.linkMap.set(e,r);break}}unlinkAll(e){if("string"!=typeof e)throw TypeError("to(local link target) is not a string.");if(!this.linkMap.has(e))return;let t=this.linkMap.get(e),r=Array.from(t);for(let e=0;e<r.length;e++)this.unsubscribe(r[e]),this.removeAllListeners(r[e]),t.delete(r[e]);this.linkMap.delete(e)}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 Pe[this.state].toLowerCase()}getSecurity(){return{useAuth:this.useAuth,isTLS:this.TLS,isAuthorized:this.boho.isAuthorized,encMode:this.encMode,usingEncryption:this.getEncryptionMode()}}stateChange(e,t){let r=e.toLowerCase();this.state=Pe[e.toUpperCase()],t&&this.emit(r,t),this.stateName!==r&&(this.stateName=r,this.emit("change",r))}}const Qe=1,Ke=2,Je=3,Xe=4;function Ze(e){if(e.byteLength<256)return te(Q("#type","8",Qe),Q("#payloadLen1","8",e.byteLength),Q("#payload",e));if(e.byteLength<65536)return te(Q("#type","8",Ke),Q("#payloadLen2","16L",e.byteLength),Q("#payload",e));if(e.byteLength<2**24){let t=Buffer.alloc(4);t.writeUint32LE(e.byteLength);let r=t.subarray(0,3);return te(Q("#type","8",Je),Q("#payloadLen3",r),Q("#payload",e))}return te(Q("#type","8",Xe),Q("#payloadLen4","32L",e.byteLength),Q("#payload",e))}class et extends t.Transform{constructor(e){super(e),this.buffer=Buffer.alloc(0),this.frames=[],this.rxi=0,this.rxi_zero=0}_transform(e,t,r){this.addData(e),this.frames.length>0&&(this.frames.forEach((e=>{this.push(e)})),this.frames=[]),r()}addData(e){let t=e.byteLength,r=0;for(;t--;)this.rxi++,0==e[r++]&&this.rxi_zero++;this.buffer.byteLength>0?this.buffer=Buffer.concat([this.buffer,e]):this.buffer=e,this.parse()}parse(){let e,t,r=this.buffer[0];if(r==Qe){if(e=2,this.buffer.byteLength<e)return;t=this.buffer.readUint8(1)}else if(r==Ke){if(e=3,this.buffer.byteLength<e)return;t=this.buffer.readUint16LE(1)}else if(r==Je){if(e=4,this.buffer.byteLength<e)return;t=this.buffer.readUint16LE(1)+65536*this.buffer.readUint8(3)}else if(r==Xe){if(e=5,this.buffer.byteLength<e)return;t=this.buffer.readUint32LE(1)}else this.emit("wrong",this.buffer),this.buffer=Buffer.alloc(0);if(t==this.buffer.byteLength-e)return this.frames.push(this.buffer.subarray(e)),void(this.buffer=Buffer.alloc(0));t<this.buffer.byteLength-e&&(this.frames.push(this.buffer.subarray(e,e+t)),this.buffer=this.buffer.subarray(e+t),this.parse())}}var tt={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}},rt="function"==typeof __webpack_require__?__non_webpack_require__:C,st=process.config&&process.config.variables||{},it=!!process.env.PREBUILDS_ONLY,nt=process.versions.modules,ot=!(!process.versions||!process.versions.electron)||!!process.env.ELECTRON_RUN_AS_NODE||"undefined"!=typeof window&&window.process&&"renderer"===window.process.type?"electron":process.versions&&process.versions.nw?"node-webkit":"node",at=process.env.npm_config_arch||v.default.arch(),ht=process.env.npm_config_platform||v.default.platform(),ct=process.env.LIBC||(function(e){return"linux"===e&&E.default.existsSync("/etc/alpine-release")}(ht)?"musl":"glibc"),lt=process.env.ARM_VERSION||("arm64"===at?"8":st.arm_version)||"",ft=(process.versions.uv||"").split(".")[0],ut=dt;function dt(e){return rt(dt.resolve(e))}function pt(e){try{return E.default.readdirSync(e)}catch(e){return[]}}function gt(e,t){var r=pt(e).filter(t);return r[0]&&w.default.join(e,r[0])}function _t(e){return/\.node$/.test(e)}function yt(e){var t=e.split("-");if(2===t.length){var r=t[0],s=t[1].split("+");if(r&&s.length&&s.every(Boolean))return{name:e,platform:r,architectures:s}}}function mt(e,t){return function(r){return null!=r&&(r.platform===e&&r.architectures.includes(t))}}function bt(e,t){return e.architectures.length-t.architectures.length}function Et(e){var t=e.split("."),r={file:e,specificity:0};if("node"===t.pop()){for(var s=0;s<t.length;s++){var i=t[s];if("node"===i||"electron"===i||"node-webkit"===i)r.runtime=i;else if("napi"===i)r.napi=!0;else if("abi"===i.slice(0,3))r.abi=i.slice(3);else if("uv"===i.slice(0,2))r.uv=i.slice(2);else if("armv"===i.slice(0,4))r.armv=i.slice(4);else{if("glibc"!==i&&"musl"!==i)continue;r.libc=i}r.specificity++}return r}}function wt(e,t){return function(r){return null!=r&&(!(r.runtime!==e&&!function(e){return"node"===e.runtime&&e.napi}(r))&&(!(r.abi!==t&&!r.napi)&&((!r.uv||r.uv===ft)&&((!r.armv||r.armv===lt)&&(!r.libc||r.libc===ct)))))}}function vt(e){return function(t,r){return t.runtime!==r.runtime?t.runtime===e?-1:1:t.abi!==r.abi?t.abi?-1:1:t.specificity!==r.specificity?t.specificity>r.specificity?-1:1:0}}dt.resolve=dt.path=function(e){e=w.default.resolve(e||".");try{var t=rt(w.default.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[t+"_PREBUILD"]&&(e=process.env[t+"_PREBUILD"])}catch(e){}if(!it){var r=gt(w.default.join(e,"build/Release"),_t);if(r)return r;var s=gt(w.default.join(e,"build/Debug"),_t);if(s)return s}var i=a(e);if(i)return i;var n=a(w.default.dirname(process.execPath));if(n)return n;var o=["platform="+ht,"arch="+at,"runtime="+ot,"abi="+nt,"uv="+ft,lt?"armv="+lt:"","libc="+ct,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"","function"==typeof __webpack_require__?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+o+"\n loaded from: "+e+"\n");function a(e){var t=pt(w.default.join(e,"prebuilds")).map(yt).filter(mt(ht,at)).sort(bt)[0];if(t){var r=w.default.join(e,"prebuilds",t.name),s=pt(r).map(Et).filter(wt(ot,nt)).sort(vt(ot))[0];return s?w.default.join(r,s.file):void 0}}},dt.parseTags=Et,dt.matchTags=wt,dt.compareTags=vt,dt.parseTuple=yt,dt.matchTuple=mt,dt.compareTuples=bt;var St=B((function(e){const t="function"==typeof __webpack_require__?__non_webpack_require__:C;"function"==typeof t.addon?e.exports=t.addon.bind(t):e.exports=ut}));var kt={mask:(e,t,r,s,i)=>{for(var n=0;n<i;n++)r[s+n]=e[n]^t[3&n]},unmask:(e,t)=>{const r=e.length;for(var s=0;s<r;s++)e[s]^=t[3&s]}},At=B((function(e){try{e.exports=St(__dirname)}catch(t){e.exports=kt}})),Tt=B((function(e){const{EMPTY_BUFFER:t}=tt,r=Buffer[Symbol.species];function s(e,t,r,s,i){for(let n=0;n<i;n++)r[s+n]=e[n]^t[3&n]}function i(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(e.exports={concat:function(e,s){if(0===e.length)return t;if(1===e.length)return e[0];const i=Buffer.allocUnsafe(s);let n=0;for(let t=0;t<e.length;t++){const r=e[t];i.set(r,n),n+=r.length}return n<s?new r(i.buffer,i.byteOffset,n):i},mask:s,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let s;return t instanceof ArrayBuffer?s=new r(t):ArrayBuffer.isView(t)?s=new r(t.buffer,t.byteOffset,t.byteLength):(s=Buffer.from(t),e.readOnly=!1),s},unmask:i},!process.env.WS_NO_BUFFER_UTIL)try{const t=At;e.exports.mask=function(e,r,i,n,o){o<48?s(e,r,i,n,o):t.mask(e,r,i,n,o)},e.exports.unmask=function(e,r){e.length<32?i(e,r):t.unmask(e,r)}}catch(e){}}));const Lt=Symbol("kDone"),xt=Symbol("kRun");var Bt=class{constructor(e){this[Lt]=()=>{this.pending--,this[xt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xt]()}[xt](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Lt])}}};const{kStatusCode:Ct}=tt,It=Buffer[Symbol.species],Ot=Buffer.from([0,0,255,255]),Rt=Symbol("permessage-deflate"),Nt=Symbol("total-length"),Ut=Symbol("callback"),Mt=Symbol("buffers"),Pt=Symbol("error");let Dt;var Ht=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Dt){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Dt=new Bt(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[Ut];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){Dt.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){Dt.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?b.default.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=b.default.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Rt]=this,this._inflate[Nt]=0,this._inflate[Mt]=[],this._inflate.on("error",jt),this._inflate.on("data",Ft)}this._inflate[Ut]=r,this._inflate.write(e),t&&this._inflate.write(Ot),this._inflate.flush((()=>{const e=this._inflate[Pt];if(e)return this._inflate.close(),this._inflate=null,void r(e);const i=Tt.concat(this._inflate[Mt],this._inflate[Nt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Nt]=0,this._inflate[Mt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,i)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?b.default.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=b.default.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Nt]=0,this._deflate[Mt]=[],this._deflate.on("data",$t)}this._deflate[Ut]=r,this._deflate.write(e),this._deflate.flush(b.default.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Tt.concat(this._deflate[Mt],this._deflate[Nt]);t&&(e=new It(e.buffer,e.byteOffset,e.length-4)),this._deflate[Ut]=null,this._deflate[Nt]=0,this._deflate[Mt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function $t(e){this[Mt].push(e),this[Nt]+=e.length}function Ft(e){this[Nt]+=e.length,this[Rt]._maxPayload<1||this[Nt]<=this[Rt]._maxPayload?this[Mt].push(e):(this[Pt]=new RangeError("Max payload size exceeded"),this[Pt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pt][Ct]=1009,this.removeListener("data",Ft),this.reset())}function jt(e){this[Rt]._inflate=null,e[Ct]=1007,this[Ut](e)}var zt=function(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0},Wt=B((function(e){try{e.exports=St(__dirname)}catch(t){e.exports=zt}})),Gt=B((function(e){const{isUtf8:t}=S.default;function r(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(e.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:r,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},t)e.exports.isValidUTF8=function(e){return e.length<24?r(e):t(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const t=Wt;e.exports.isValidUTF8=function(e){return e.length<32?r(e):t(e)}}catch(e){}}));const{Writable:Vt}=y.default,{BINARY_TYPES:qt,EMPTY_BUFFER:Yt,kStatusCode:Qt,kWebSocket:Kt}=tt,{concat:Jt,toArrayBuffer:Xt,unmask:Zt}=Tt,{isValidStatusCode:er,isValidUTF8:tr}=Gt,rr=Buffer[Symbol.species],sr=Promise.resolve(),ir="function"==typeof queueMicrotask?queueMicrotask:function(e){sr.then(e).catch(ar)};var nr=class extends Vt{constructor(e={}){super(),this._allowSynchronousEvents=!!e.allowSynchronousEvents,this._binaryType=e.binaryType||qt[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Kt]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new rr(t.buffer,t.byteOffset+e,t.length-e),new rr(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new rr(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(0!=(48&t[0])){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=64==(64&t[0]);if(!r||this._extensions[Ht.extensionName]){if(this._fin=128==(128&t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=Yt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&Zt(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[Ht.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let s;s="nodebuffer"===this._binaryType?Jt(r,t):"arraybuffer"===this._binaryType?Xt(Jt(r,t)):r,5===this._state||this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=0):(this._state=6,ir((()=>{this.emit("message",s,!0),this._state=0,this.startLoop(e)})))}else{const s=Jt(r,t);if(!this._skipUTF8Validation&&!tr(s)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=0):(this._state=6,ir((()=>{this.emit("message",s,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,ir((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,Yt),this.end();else{const r=e.readUInt16BE(0);if(!er(r)){const e=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const s=new rr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!tr(s)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=0}}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;const n=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(n,this.createError),n.code=i,n[Qt]=s,n}};function or(e){throw e}function ar(e){process.nextTick(or,e)}const{randomFillSync:hr}=_.default,{EMPTY_BUFFER:cr}=tt,{isValidStatusCode:lr}=Gt,{mask:fr,toBuffer:ur}=Tt,dr=Symbol("kByteLength"),pr=Buffer.alloc(4);class gr{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,s,i=!1,n=2,o=!1;t.mask&&(r=t.maskBuffer||pr,t.generateMask?t.generateMask(r):hr(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),n=6),"string"==typeof e?s=t.mask&&!o||void 0===t[dr]?(e=Buffer.from(e)).length:t[dr]:(s=e.length,i=t.mask&&t.readOnly&&!o);let a=s;s>=65536?(n+=8,a=127):s>125&&(n+=2,a=126);const h=Buffer.allocUnsafe(i?s+n:n);return h[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(h[0]|=64),h[1]=a,126===a?h.writeUInt16BE(s,2):127===a&&(h[2]=h[3]=0,h.writeUIntBE(s,4,6)),t.mask?(h[1]|=128,h[n-4]=r[0],h[n-3]=r[1],h[n-2]=r[2],h[n-1]=r[3],o?[h,e]:i?(fr(e,r,h,n,s),[h]):(fr(e,r,e,0,s),[h,e])):[h,e]}close(e,t,r,s){let i;if(void 0===e)i=cr;else{if("number"!=typeof e||!lr(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+r),i.writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0)}const n={[dr]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,i,!1,n,s]):this.sendFrame(gr.frame(i,n),s)}ping(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=ur(e)).length,i=ur.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const n={[dr]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,n,r]):this.sendFrame(gr.frame(e,n),r)}pong(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=ur(e)).length,i=ur.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const n={[dr]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,n,r]):this.sendFrame(gr.frame(e,n),r)}send(e,t,r){const s=this._extensions[Ht.extensionName];let i,n,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(i=Buffer.byteLength(e),n=!1):(i=(e=ur(e)).length,n=ur.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=s._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),s){const s={[dr]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:n,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,s,r]):this.dispatch(e,this._compress,s,r)}else this.sendFrame(gr.frame(e,{[dr]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:n,rsv1:!1}),r)}dispatch(e,t,r,s){if(!t)return void this.sendFrame(gr.frame(e,r),s);const i=this._extensions[Ht.extensionName];this._bufferedBytes+=r[dr],this._deflating=!0,i.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof s&&s(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],s=r[r.length-1];"function"==typeof s&&s(e)}}else this._bufferedBytes-=r[dr],this._deflating=!1,r.readOnly=!1,this.sendFrame(gr.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][dr],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][dr],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var _r=gr;const{kForOnEventAttribute:yr,kListener:mr}=tt,br=Symbol("kCode"),Er=Symbol("kData"),wr=Symbol("kError"),vr=Symbol("kMessage"),Sr=Symbol("kReason"),kr=Symbol("kTarget"),Ar=Symbol("kType"),Tr=Symbol("kWasClean");class Lr{constructor(e){this[kr]=null,this[Ar]=e}get target(){return this[kr]}get type(){return this[Ar]}}Object.defineProperty(Lr.prototype,"target",{enumerable:!0}),Object.defineProperty(Lr.prototype,"type",{enumerable:!0});class xr extends Lr{constructor(e,t={}){super(e),this[br]=void 0===t.code?0:t.code,this[Sr]=void 0===t.reason?"":t.reason,this[Tr]=void 0!==t.wasClean&&t.wasClean}get code(){return this[br]}get reason(){return this[Sr]}get wasClean(){return this[Tr]}}Object.defineProperty(xr.prototype,"code",{enumerable:!0}),Object.defineProperty(xr.prototype,"reason",{enumerable:!0}),Object.defineProperty(xr.prototype,"wasClean",{enumerable:!0});class Br extends Lr{constructor(e,t={}){super(e),this[wr]=void 0===t.error?null:t.error,this[vr]=void 0===t.message?"":t.message}get error(){return this[wr]}get message(){return this[vr]}}Object.defineProperty(Br.prototype,"error",{enumerable:!0}),Object.defineProperty(Br.prototype,"message",{enumerable:!0});class Cr extends Lr{constructor(e,t={}){super(e),this[Er]=void 0===t.data?null:t.data}get data(){return this[Er]}}Object.defineProperty(Cr.prototype,"data",{enumerable:!0});const Ir={addEventListener(e,t,r={}){for(const s of this.listeners(e))if(!r[yr]&&s[mr]===t&&!s[yr])return;let s;if("message"===e)s=function(e,r){const s=new Cr("message",{data:r?e:e.toString()});s[kr]=this,Rr(t,this,s)};else if("close"===e)s=function(e,r){const s=new xr("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[kr]=this,Rr(t,this,s)};else if("error"===e)s=function(e){const r=new Br("error",{error:e,message:e.message});r[kr]=this,Rr(t,this,r)};else{if("open"!==e)return;s=function(){const e=new Lr("open");e[kr]=this,Rr(t,this,e)}}s[yr]=!!r[yr],s[mr]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[mr]===t&&!r[yr]){this.removeListener(e,r);break}}};var Or={CloseEvent:xr,ErrorEvent:Br,Event:Lr,EventTarget:Ir,MessageEvent:Cr};function Rr(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:Nr}=Gt;function Ur(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var Mr={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,s,i=Object.create(null),n=!1,o=!1,a=!1,h=-1,c=-1,l=-1,f=0;for(;f<e.length;f++)if(c=e.charCodeAt(f),void 0===r)if(-1===l&&1===Nr[c])-1===h&&(h=f);else if(0===f||32!==c&&9!==c){if(59!==c&&44!==c)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===h)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f);const s=e.slice(h,l);44===c?(Ur(t,s,i),i=Object.create(null)):r=s,h=l=-1}}else-1===l&&-1!==h&&(l=f);else if(void 0===s)if(-1===l&&1===Nr[c])-1===h&&(h=f);else if(32===c||9===c)-1===l&&-1!==h&&(l=f);else if(59===c||44===c){if(-1===h)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f),Ur(i,e.slice(h,l),!0),44===c&&(Ur(t,r,i),i=Object.create(null),r=void 0),h=l=-1}else{if(61!==c||-1===h||-1!==l)throw new SyntaxError(`Unexpected character at index ${f}`);s=e.slice(h,f),h=l=-1}else if(o){if(1!==Nr[c])throw new SyntaxError(`Unexpected character at index ${f}`);-1===h?h=f:n||(n=!0),o=!1}else if(a)if(1===Nr[c])-1===h&&(h=f);else if(34===c&&-1!==h)a=!1,l=f;else{if(92!==c)throw new SyntaxError(`Unexpected character at index ${f}`);o=!0}else if(34===c&&61===e.charCodeAt(f-1))a=!0;else if(-1===l&&1===Nr[c])-1===h&&(h=f);else if(-1===h||32!==c&&9!==c){if(59!==c&&44!==c)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===h)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f);let o=e.slice(h,l);n&&(o=o.replace(/\\/g,""),n=!1),Ur(i,s,o),44===c&&(Ur(t,r,i),i=Object.create(null),r=void 0),s=void 0,h=l=-1}}else-1===l&&(l=f);if(-1===h||a||32===c||9===c)throw new SyntaxError("Unexpected end of input");-1===l&&(l=f);const u=e.slice(h,l);return void 0===r?Ur(t,u,i):(void 0===s?Ur(i,u,!0):Ur(i,s,n?u.replace(/\\/g,""):u),Ur(t,r,i)),t}};const{randomBytes:Pr,createHash:Dr}=_.default,{URL:Hr}=x.default,{BINARY_TYPES:$r,EMPTY_BUFFER:Fr,GUID:jr,kForOnEventAttribute:zr,kListener:Wr,kStatusCode:Gr,kWebSocket:Vr,NOOP:qr}=tt,{EventTarget:{addEventListener:Yr,removeEventListener:Qr}}=Or,{format:Kr,parse:Jr}=Mr,{toBuffer:Xr}=Tt,Zr=Symbol("kAborted"),es=[8,13],ts=["CONNECTING","OPEN","CLOSING","CLOSED"],rs=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class ss extends k.default{constructor(e,t,r){super(),this._binaryType=$r[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Fr,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=ss.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),ns(this,e,t,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){$r.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const s=new nr({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new _r(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[Vr]=this,e[Vr]=this,s.on("conclude",fs),s.on("drain",us),s.on("error",ds),s.on("message",gs),s.on("ping",_s),s.on("pong",ys),e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",bs),e.on("data",Es),e.on("end",ws),e.on("error",vs),this._readyState=ss.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=ss.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Ht.extensionName]&&this._extensions[Ht.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=ss.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==ss.CLOSED)if(this.readyState!==ss.CONNECTING)this.readyState!==ss.CLOSING?(this._readyState=ss.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";cs(this,this._req,e)}}pause(){this.readyState!==ss.CONNECTING&&this.readyState!==ss.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===ss.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===ss.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||Fr,t,r)):ls(this,e,r)}pong(e,t,r){if(this.readyState===ss.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===ss.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||Fr,t,r)):ls(this,e,r)}resume(){this.readyState!==ss.CONNECTING&&this.readyState!==ss.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===ss.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==ss.OPEN)return void ls(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Ht.extensionName]||(s.compress=!1),this._sender.send(e||Fr,s,r)}terminate(){if(this.readyState!==ss.CLOSED)if(this.readyState!==ss.CONNECTING)this._socket&&(this._readyState=ss.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";cs(this,this._req,e)}}}Object.defineProperty(ss,"CONNECTING",{enumerable:!0,value:ts.indexOf("CONNECTING")}),Object.defineProperty(ss.prototype,"CONNECTING",{enumerable:!0,value:ts.indexOf("CONNECTING")}),Object.defineProperty(ss,"OPEN",{enumerable:!0,value:ts.indexOf("OPEN")}),Object.defineProperty(ss.prototype,"OPEN",{enumerable:!0,value:ts.indexOf("OPEN")}),Object.defineProperty(ss,"CLOSING",{enumerable:!0,value:ts.indexOf("CLOSING")}),Object.defineProperty(ss.prototype,"CLOSING",{enumerable:!0,value:ts.indexOf("CLOSING")}),Object.defineProperty(ss,"CLOSED",{enumerable:!0,value:ts.indexOf("CLOSED")}),Object.defineProperty(ss.prototype,"CLOSED",{enumerable:!0,value:ts.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(ss.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(ss.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[zr])return t[Wr];return null},set(t){for(const t of this.listeners(e))if(t[zr]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[zr]:!0})}})})),ss.prototype.addEventListener=Yr,ss.prototype.removeEventListener=Qr;var is=ss;function ns(e,t,r,s){const i={allowSynchronousEvents:!1,autoPong:!0,protocolVersion:es[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!es.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${es.join(", ")})`);let n;if(t instanceof Hr)n=t;else try{n=new Hr(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===n.protocol?n.protocol="ws:":"https:"===n.protocol&&(n.protocol="wss:"),e._url=n.href;const o="wss:"===n.protocol,a="ws+unix:"===n.protocol;let h;if("ws:"===n.protocol||o||a?a&&!n.pathname?h="The URL's pathname is empty":n.hash&&(h="The URL contains a fragment identifier"):h='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',h){const t=new SyntaxError(h);if(0===e._redirects)throw t;return void os(e,t)}const c=o?443:80,l=Pr(16).toString("base64"),f=o?A.default.request:T.default.request,u=new Set;let d,p;if(i.createConnection=o?hs:as,i.defaultPort=i.defaultPort||c,i.port=n.port||c,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(d=new Ht(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Kr({[Ht.extensionName]:d.offer()})),r.length){for(const e of r){if("string"!=typeof e||!rs.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:n.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&n.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=f(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(i);i.timeout&&p.on("timeout",(()=>{cs(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Zr]||(p=e._req=null,os(e,t))})),p.on("response",(n=>{const o=n.headers.location,a=n.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void cs(e,p,"Maximum redirects exceeded");let n;p.abort();try{n=new Hr(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void os(e,r)}ns(e,n,r,s)}else e.emit("unexpected-response",p,n)||cs(e,p,`Unexpected server response: ${n.statusCode}`)})),p.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==ss.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void cs(e,r,"Invalid Upgrade header");const n=Dr("sha1").update(l+jr).digest("base64");if(t.headers["sec-websocket-accept"]!==n)return void cs(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?u.size?u.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":u.size&&(a="Server sent no subprotocol"),a)return void cs(e,r,a);o&&(e._protocol=o);const h=t.headers["sec-websocket-extensions"];if(void 0!==h){if(!d){return void cs(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Jr(h)}catch(t){return void cs(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==Ht.extensionName){return void cs(e,r,"Server indicated an extension that was not requested")}try{d.accept(t[Ht.extensionName])}catch(t){return void cs(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Ht.extensionName]=d}e.setSocket(r,s,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(p,e):p.end()}function os(e,t){e._readyState=ss.CLOSING,e.emit("error",t),e.emitClose()}function as(e){return e.path=e.socketPath,m.default.connect(e)}function hs(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=m.default.isIP(e.host)?"":e.host),L.default.connect(e)}function cs(e,t,r){e._readyState=ss.CLOSING;const s=new Error(r);Error.captureStackTrace(s,cs),t.setHeader?(t[Zr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(os,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function ls(e,t,r){if(t){const r=Xr(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${ts[e.readyState]})`);process.nextTick(r,t)}}function fs(e,t){const r=this[Vr];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[Vr]&&(r._socket.removeListener("data",Es),process.nextTick(ms,r._socket),1005===e?r.close():r.close(e,t))}function us(){const e=this[Vr];e.isPaused||e._socket.resume()}function ds(e){const t=this[Vr];void 0!==t._socket[Vr]&&(t._socket.removeListener("data",Es),process.nextTick(ms,t._socket),t.close(e[Gr])),t.emit("error",e)}function ps(){this[Vr].emitClose()}function gs(e,t){this[Vr].emit("message",e,t)}function _s(e){const t=this[Vr];t._autoPong&&t.pong(e,!this._isServer,qr),t.emit("ping",e)}function ys(e){this[Vr].emit("pong",e)}function ms(e){e.resume()}function bs(){const e=this[Vr];let t;this.removeListener("close",bs),this.removeListener("data",Es),this.removeListener("end",ws),e._readyState=ss.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Vr]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",ps),e._receiver.on("finish",ps))}function Es(e){this[Vr]._receiver.write(e)||this.pause()}function ws(){const e=this[Vr];e._readyState=ss.CLOSING,e._receiver.end(),this.end()}function vs(){const e=this[Vr];this.removeListener("error",vs),this.on("error",qr),e&&(e._readyState=ss.CLOSING,this.destroy())}const{tokenChars:Ss}=Gt;var ks={parse:function(e){const t=new Set;let r=-1,s=-1,i=0;for(;i<e.length;i++){const n=e.charCodeAt(i);if(-1===s&&1===Ss[n])-1===r&&(r=i);else if(0===i||32!==n&&9!==n){if(44!==n)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${i}`);-1===s&&(s=i);const n=e.slice(r,s);if(t.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=s=-1}}else-1===s&&-1!==r&&(s=i)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const n=e.slice(r,i);if(t.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return t.add(n),t}};const{createHash:As}=_.default,{GUID:Ts,kWebSocket:Ls}=tt,xs=/^[+/0-9A-Za-z]{22}==$/;class Bs extends k.default{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!1,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:is,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=T.default.createServer(((e,t)=>{const r=T.default.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,s)=>{this.handleUpgrade(t,r,s,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(Is,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Is,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Is(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",Os);const i=e.headers["sec-websocket-key"],n=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Ns(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void Ns(this,e,t,400,"Invalid Upgrade header")}if(!i||!xs.test(i)){return void Ns(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==n&&13!==n){return void Ns(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Rs(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=ks.parse(o)}catch(r){return void Ns(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const h=e.headers["sec-websocket-extensions"],c={};if(this.options.perMessageDeflate&&void 0!==h){const r=new Ht(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Mr.parse(h);e[Ht.extensionName]&&(r.accept(e[Ht.extensionName]),c[Ht.extensionName]=r)}catch(r){return void Ns(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===n?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((n,o,h,l)=>{if(!n)return Rs(t,o||401,h,l);this.completeUpgrade(c,i,a,e,t,r,s)}));if(!this.options.verifyClient(o))return Rs(t,401)}this.completeUpgrade(c,i,a,e,t,r,s)}completeUpgrade(e,t,r,s,i,n,o){if(!i.readable||!i.writable)return i.destroy();if(i[Ls])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Rs(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${As("sha1").update(t+Ts).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),h._protocol=e)}if(e[Ht.extensionName]){const t=e[Ht.extensionName].params,r=Mr.format({[Ht.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),h._extensions=e}this.emit("headers",a,s),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",Os),h.setSocket(i,n,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",(()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Is,this)}))),o(h,s)}}var Cs=Bs;function Is(e){e._state=2,e.emit("close")}function Os(){this.destroy()}function Rs(e,t,r,s){r=r||T.default.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${T.default.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Ns(e,t,r,s,i){if(e.listenerCount("wsClientError")){const s=new Error(i);Error.captureStackTrace(s,Ns),e.emit("wsClientError",s,r,t)}else Rs(r,s,i)}let Us={clientTracking:!1,port:0,congPort:0,timeout:5e4,showMessage:"none",showMetric:0,showChannel:0,monitorPeriod:5e3,fileLogger:{connection:{use:!1,path:"connection.log"},auth:{use:!1,path:"auth.log"},attack:{use:!1,path:"attack.log"}},useQuota:{signalSize:!1,publishCounter:!1,trafficRate:!1,disconnect:!1},defaultQuotaIndex:3,adminLevel:255,debug:{slow:!1,delay:500,showAuthInfo:!1},retain:{isAvailable:!0,limitSize:1e5,limitCounter:1e3},auth:{delay_auth_fail:1e3},memberOnly:!1};const Ms=new TextDecoder,Ps=Q;class Ds{constructor(e,t){this.socket=e,e.isAlive=!0,e.txCounter=0,e.rxCounter=0,e.openTime=Date.now(),this.boho=new Me,this.encMode=He.AUTO,this.channels=new Set,this.retain_signal=new Map,this.ssid=Ds.ssid++,this.manager=t,this.cid,this.did,this.uid,this.nick="",this.lastEchoMessage="N",this.privateNode=!1,this.HOME_CHANNEL="",this.level=Us.defaultQuotaIndex,this.quota=ze[this.level],this.isAdmin=!1,this.state,this.stateLog=[],this.setState(De.INIT)}static ssid=1;setState(e){this.state=e,Us.debug.showAuthInfo&&(this.stateLog.push(e),console.log(this.stateLog.join(">")))}getState(){return this.state}getStateName(){return De[this.state].toLowerCase()}showMessageLog(e,t){let r=this.boho.isAuthorized?`did: ${this.did} ${this.cid}@`:`${this.cid}@`;if(t){let t=je[e[0]];t||(t=Ce[e[0]]),t=" ["+t+"]",e.byteLength>40?console.log(r+t+" LEN:",e.length):console.log(r+t,e)}else console.log(r+" [TEXT] %s",e)}rxQuotaChecker(e){let t=e.byteLength;return this.manager.rxBytes+=t,!(Us.useQuota.signalSize&&t>this.quota.signalSize)||(console.log("## quota: size over"),this.send(Buffer.from([je.OVER_SIZE])),Us.useQuota.disconnect&&this.close(),!1)}onTimeDelayMessage(e,t=!0){setTimeout((()=>{this.onSocketMessage(e,t)}),Us.debug.delay)}onSocketMessage(t,r=!0){if(this.receiveMonitor(),!this.rxQuotaChecker(t))return;let s,i;if("message"===Us.showMessage&&this.showMessageLog(t,r),r){if(s=t[0],s===Ce.ENC_488){try{i=this.boho.decrypt_488(t)}catch(e){return void console.log("-- E488 DEC_FAIL",e)}if(!i)return;s=i[0],t=i}else if(s===Ce.ENC_E2E){try{i=this.boho.decrypt_488(t)}catch(e){return void console.log("-- E2E DEC_FAIL",e)}if(!i)return;s=i[0],t.set(i,Re.ENC_488),t=t.subarray(Re.ENC_488)}switch(s){case je.PING:this.pong();break;case je.PONG:break;case je.CID_REQ:this.state<De.SENT_SERVER_READY&&this.close(),this.cid||(this.cid="?"+e.webcrypto.getRandomValues(Buffer.alloc(3)).toString("base64url"),this.manager.cid2remote.set(this.cid,this)),this.send_enc_mode(te(Ps("#cid_ack","8",je.CID_RES),Ps("#cid",this.cid))),this.setState(De.CID_READY);break;case je.ECHO:try{let e=Ms.decode(t.subarray(1));this.lastEchoMessage=e}catch(e){}this.send(t,r);break;case je.IAM:if(t.byteLength>1){let e=t.subarray(1);this.nick=Ms.decode(e),console.log("iam nick reset",this.nick)}this.iamResponse();break;case je.SIGNAL_E2E:case je.SIGNAL:if(t.byteLength>=3){let e=t.readUInt8(1);if(t.byteLength>=e+2){let r=t.subarray(2,2+e);r=Ms.decode(r),this.manager.sender(r,this,t)}}break;case je.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=Ms.decode(r);let s=r.split(",");this.manager.unsubscribe(s,this)}}break;case je.SUBSCRIBE:if(t.byteLength>=3){let e=t.readUInt8(1);if(t.byteLength==e+2){let r=t.subarray(2,2+e);r=Ms.decode(r);let s=r.split(",");this.manager.subscribe(s,this)}}break;case je.SUBSCRIBE_REQ:if(t.byteLength>=6){let e=t.readUInt16BE(1),r=t.readUInt16BE(3);if(t.byteLength==r+5){let s=t.subarray(5,5+r);s=Ms.decode(s);let i=s.split(",");this.manager.subscribe(i,this),this.response(e,0)}else this.response(e,255)}break;case je.REQUEST:try{let e=re(t);if(e){if(!e.target||!e.topic)return;this.manager.server.apiNames.has(e.target)?this.manager.server.emit(e.target,this,e):console.log("UnKnown API req: ",e.target)}}catch(e){console.log("request catch error",e)}break;case je.CLOSE:if(t.byteLength>1){let e=Ms.decode(t.subarray(1));console.log(">> CLOSE reason:",e),this.close()}break;case Ce.AUTH_REQ:if(!this.manager.authManager)return;this.state<De.SENT_SERVER_READY&&this.close(),this.setState(De.RECV_AUTH_REQ);let s=this.boho.auth_nonce();this.send(s),this.setState(De.SENT_SERVER_NONCE);break;case Ce.AUTH_HMAC:if(!this.manager.authManager)return;return this.state<De.SENT_SERVER_NONCE&&this.close(),this.setState(De.RECV_AUTH_HMAC),void this.manager.authManager.verify_auth_hmac(t,this).then((e=>{e&&this.manager.deligateSignal(remote,"@$name",e.name)})).catch((e=>{}))}}else try{let e=Ms.decode(t);this.manager.server.emit("text_message",e,this)}catch(e){}}response(e,t,r){r?this.send_enc_mode(te(Ps("#type","8",je.RESPONSE_MBP),Ps("status","8",t),Ps("mid","16",e),Ps("body",r))):this.send_enc_mode(te(Ps("#type","8",je.RESPONSE_MBP),Ps("status","8",t),Ps("mid","16",e)))}send_enc_mode(e,t=!1){if((this.encMode===He.YES||this.encMode===He.AUTO&&!this.TLS&&this.boho.isAuthorized)&&(t=!0),t&&e[0]==je.SIGNAL_E2E){let t=e[1],r=this.boho.encrypt_488(e.subarray(0,3+t));r[0]=Ce.ENC_E2E;let s=Buffer.concat([r,e.subarray(3+t)]);this.send(s)}else if(t){let t=this.boho.encrypt_488(e);t?this.send(t):console.log("encryption FAIL: NO DATA TRANSIT")}else this.send(e)}iamResponse(e=""){if(""==e){let t=[];for(let e of this.channels.keys())t.push(e);e={ssid:this.ssid,uid:this.uid,cid:this.cid,did:this.did,nick:this.nick,ip:this.ip,tag:t}}let t=te(Ps("#MsgType","8",je.IAM_RES),Ps("#info",e));this.send_enc_mode(t)}}const Hs=new TextDecoder;class $s extends Ds{constructor(e,t,r){super(e,r),this.socketType=e.socketType,"websocket"===this.socketType?(this.TLS="https"===t.headers["x-forwarded-proto"],this.ip=this.getRemoteIP(t)):(this.TLS=!1,this.ip=this.getRemoteIP(e.remoteAddress)),!function(e){if(0===e.indexOf("0.0.0.0"))return!0;if(0===e.indexOf("127.0.0.1"))return!0;if(0===e.indexOf("192.168."))return!0;if(0===e.indexOf("10."))return!0;if(0===e.indexOf("172.")){if(0===e.indexOf("172.16."))return!0;if(0===e.indexOf("172.17."))return!0;if(0===e.indexOf("172.18."))return!0;if(0===e.indexOf("172.19."))return!0;if(0===e.indexOf("172.20."))return!0;if(0===e.indexOf("172.21."))return!0;if(0===e.indexOf("172.22."))return!0;if(0===e.indexOf("172.23."))return!0;if(0===e.indexOf("172.24."))return!0;if(0===e.indexOf("172.25."))return!0;if(0===e.indexOf("172.26."))return!0;if(0===e.indexOf("172.27."))return!0;if(0===e.indexOf("172.28."))return!0;if(0===e.indexOf("172.29."))return!0;if(0===e.indexOf("172.30."))return!0;if(0===e.indexOf("172.31."))return!0}return!1}(this.ip)?this.HOME_CHANNEL="IP:"+function(e){let t=e.split(".");return Buffer.from(t).toString("hex")}(this.ip):(this.HOME_CHANNEL="PRIVATE:",this.privateNode=!0),"websocket"===this.socketType?(Us.debug.slow?e.on("message",this.onTimeDelayMessage.bind(this)):e.on("message",this.onSocketMessage.bind(this)),e.on("pong",this.receiveMonitor.bind(this)),e.on("ping",this.receiveMonitor.bind(this)),e.on("error",(e=>{console.log("Websocket error",e,e.code)})),e.onclose=e=>{this.manager.removeRemote(this)}):(this.congRx=new et,e.on("data",(e=>{this.congRx.write(e)})),this.congRx.on("wrong",this.onWrongCongPacketMessage.bind(this)),Us.debug.slow?this.congRx.on("data",this.onTimeDelayMessage.bind(this)):this.congRx.on("data",this.onSocketMessage.bind(this)),e.on("error",(e=>{console.log("TCP Socket error",e)})),e.on("close",(e=>{this.manager.removeRemote(this)})))}onWrongCongPacketMessage(e){if(this.cid)console.log("wrong congpack from user:",Date(),this.ip,this.ssid,this.cid);else{let t="";try{t=Hs.decode(e)}catch(r){t+="Len: "+e.byteLength}if(this.manager.attackLogger){let e=`> ${this.ssid} ${this.ip} ${t}`;this.manager.attackLogger.log(e)}this.close(!0)}}permissionChecker(){this.socket.bytesWritten||this.socket._socket,this.socket.bytesRead||this.socket._socket}receiveMonitor(){this.socket.rxCounter++,this.socket.isAlive=!0}isConnectionHTTPS(e){return e.headers["x-forwarded-proto"]}getRemoteIP(e){let t;return e&&e.headers?(t=e.headers["x-forwarded-for"],null==t&&(t=e.socket.remoteAddress)):t=e,t?(0==t.indexOf("::ffff:")&&(t=t.substring(7)),"::1"==t&&(t="127.0.0.1")):t="0.0.0.0",t}ping(){"websocket"===this.socketType?(this.socket.ping(),this.socket.txCounter++):this.send(Buffer.from([je.PING]))}pong(){"websocket"===this.socketType?(this.socket.pong(),this.socket.txCounter++):this.send(Buffer.from([je.PONG]))}getTraffic(){this.socket.bytesWritten||this.socket._socket,this.socket.bytesRead||this.socket._socket,this.socket.txCounter,this.socket.rxCounter}close(e=!1){this.getTraffic(),"websocket"===this.socketType?e?this.socket.terminate():this.socket.close():e?this.socket.destroy():this.socket.end()}send(e,t){this.manager.txBytes+=e.byteLength,this.socket.txCounter++,"websocket"===this.socketType?1===this.socket.readyState?null!=t?this.socket.send(e,{binary:t}):this.socket.send(e):this.close(!0):"open"==this.socket.readyState?this.socket.write(Ze(e)):this.close(!0)}}const Fs=new Intl.DateTimeFormat("ko-KR",{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1,timeZone:"Asia/Seoul"});class js{constructor(e){this.file=E.default.openSync(e,"a+"),console.log("new logFile",e,this.file)}log(e){let t=Fs.format(new Date)+" "+e+"\n";E.default.write(this.file,t,(e=>{if(e)throw e}))}}class zs{constructor(e){this.manager=e,this.metricsPack={remotes:[0],channels:[0],txBytes:[0],rxBytes:[0],unixTime:[Math.floor(Date.now()/1e3)],period:0},this.tickId=setInterval((e=>{this.metricsPack.remotes.push(this.manager.remotes.size),this.metricsPack.remotes.length>10&&this.metricsPack.remotes.shift(),this.metricsPack.channels.push(this.manager.channel_map.size),this.metricsPack.channels.length>10&&this.metricsPack.channels.shift(),this.metricsPack.txBytes.push(this.manager.txBytes),this.metricsPack.txBytes.length>10&&this.metricsPack.txBytes.shift(),this.metricsPack.rxBytes.push(this.manager.rxBytes),this.metricsPack.rxBytes.length>10&&this.metricsPack.rxBytes.shift(),this.metricsPack.unixTime=Math.floor(Date.now()/1e3),this.metricsPack.period=1e4,this.manager.txBytes=0,this.manager.rxBytes=0}),1e4)}oneline(e){let t=[{...d.memoryUsage()}];e&&console.table(t,["rss","heapTotal","heapUsed","external","arrayBuffers"]);let r=[{lastSSID:this.manager.lastSSID,remotes:this.manager.remotes.size,channels:this.manager.channel_map.size,txBytes:this.manager.txBytes,rxBytes:this.manager.rxBytes}];return e&&console.table(r,["lastSSID","remotes","channels","txBytes","rxBytes"]),r[0]}getRemotes(e){let t=Array.from(this.manager.remotes.values()).map((e=>"#"+e.ssid+":"+e.cid+"("+e.state+")"));return e&&console.table(t),t}getCIdList(e){let t=Array.from(this.manager.cid2remote.keys());return e&&console.table(t),t}getChannelList(e){let t=Array.from(this.manager.channel_map.keys());return e&&console.table(t),t}getSubscribers(e){let t=[];if(this.manager.channel_map.has(e)){this.manager.channel_map.get(e).forEach((e=>{t.push(e.cid)}))}return t}getRemoteByCId(e,t=1){if(!this.manager.cid2remote.has(e))return{result:"nop"};{let r=this.manager.cid2remote.get(e);if(1==t)return{ip:r.ip,id:r.cid,ssid:r.ssid,cid:r.cid,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==t)return{ip:r.ip,uptime:Math.trunc((Date.now()-r.socket.openTime)/1e3),nick:r.nick,ssid:r.ssid,echo:r.lastEchoMessage};if(3==t)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:He[r.encMode]};if(4==t){let e=Array.from(r.channels.keys()),t=Array.from(r.memory.keys()),s=Array.from(r.retain_signal.keys());return{ip:r.ip,uptime:Math.trunc((Date.now()-r.socket.openTime)/1e3),channels:e,set:t,retain:s}}}}}const Ws=new TextEncoder,Gs=new TextDecoder;class Vs{constructor(e,t){this.server=e,this.txBytes=0,this.rxBytes=0,this.authManager=t,this.connectionLogger,Us.fileLogger.connection.use&&(this.connectionLogger=new js(Us.fileLogger.connection.path),console.log("Manager: begin file logger [connection]")),this.attackLogger,Us.fileLogger.attack.use&&(this.attackLogger=new js(Us.fileLogger.attack.path),console.log("Manager: begin file logger.[attack]")),this.remotes=new Set,this.channel_map=new Map,this.CHANNEL_PREFIX="CH:",this.CID_PREFIX="CID:",this.cid2remote=new Map,this.retain_messages=new Map,this.metric=new zs(this),this.lastSSID=0,this.pingIntervalID=setInterval((e=>{this.remotes.forEach((function(e){let t=e.socket;!1===t.isAlive&&(console.log("## timeout. cid:",e.cid),e.close()),t.txCounter++,t.isAlive=!1,"websocket"===e.socketType?t.ping():e.ping()}))}),Us.timeout),Us.showMetric&&(this.monitIntervalID=setInterval((e=>{this.monitor()}),Us.monitorPeriod))}addRemote(e,t){e.isAlive=!0;let r=new $s(e,t,this);this.remotes.add(r),r.send(Buffer.from([je.SERVER_READY])),r.setState(De.SENT_SERVER_READY),this.lastSSID=r.ssid;let s=`+ IP:${r.ip} #${r.ssid} ${"websocket"===e.socketType?"WS":"CS"} `;this.connectionLogger&&this.connectionLogger.log(s)}removeRemote(e){let t=`- IP:${e.ip} #${e.ssid} cid:${e.cid} ${"websocket"===e?.socket.socketType?"WS":"CS"} `;this.connectionLogger&&this.connectionLogger.log(t),this.deligateSignal(e,"@state","close"),this.deligateSignal(e,"@$state","close");for(let t of e.channels.keys())if(this.channel_map.has(t)){const r=this.channel_map.get(t);r.delete(e),0==r.size&&this.channel_map.delete(t)}if(e.boho.isAuthorized);else for(let t of e.retain_signal.keys())t=this.CID_PREFIX+e.cid+"@"+t,this.channel_map.has(t)&&this.channel_map.delete(t);if(e.uid&&this.server.apiNames.has("account")){let t={topic:"detachUserRemote",args:["caller:manager.removeRemote"]};this.server.emit("account",e,t)}this.remotes.delete(e),this.cid2remote.delete(e.cid),e=null}serverSignal(e){let t=te(Q("#MsgType","8",je.SERVER_SIGNAL),Q("#signalObject",e));this.remotes.forEach((e=>{e.send_enc_mode(t)}))}getSignalTag(e){let t=e.readUint8(1),r=e.subarray(2,2+t);return Gs.decode(r)}getNewSignalTagMessage(e,t){let r=e[0],s=e.readUint8(1),i=Ws.encode(t),n=i.byteLength,o=e.subarray(2+s);return Buffer.concat([Buffer.from([r,n]),i,o])}deligateSignal(e,t,...r){let s=Ge(t,...r);this.sender(t,e,s)}adminSignal(e,t){return this.cid2remote.has(e)?void this.cid2remote.get(e).send_enc_mode(t):"no cid"}serverSignalTo(e,...t){let r=e.split("@")[0],s=Ge("@"+e.split("@")[1],...t);if(r&&this.cid2remote.has(r)){let e=this.cid2remote.get(r);return console.log("target",e.state,e.cid),void e.send_enc_mode(s)}return"no cid"}sender(e,t,r){if(Us.memberOnly&&!t.boho.isAuthorized)return t.send(Buffer.from([je.SERVER_CLEAR_AUTH])),t.close(),["err","not autrized"];if(0==e.indexOf("$"))return["err","prefix $ is reserved for userSet tag."];let s=e.indexOf("@");if(0===s)e=t.cid+e,r=this.getNewSignalTagMessage(r,e);else if(s>0){let t=e.split("@")[0];if(this.cid2remote.has(t)){let s="@"+e.split("@")[1];return r=this.getNewSignalTagMessage(r,s),this.cid2remote.get(t).send_enc_mode(r),["ok",1]}return["err","Invalid cid"]}if((e=0===e.indexOf("#")?t.HOME_CHANNEL+e:e.includes("@")?this.CID_PREFIX+e:this.CHANNEL_PREFIX+e).includes("$")&&Us.retain.isAvailable&&Us.retain.limitCounter>this.retain_messages.size&&Us.retain.limitSize>r.byteLength)if(e.includes("@")){let s=e.split("@")[1];t.retain_signal.set(s,r)}else this.retain_messages.set(e,r);let i=0;if(this.channel_map.has(e)){let s=this.channel_map.get(e);if(s.size>=1){let e;e=Us.useQuota.publishCounter?Math.min(t.quota.publishCounter,s.size):s.size;let n=s.values();for(;i<e;){let e=n.next().value;if(!e)break;e!==t&&(e.send_enc_mode(r),i++)}return Us.useQuota.publishCounter,["ok",i]}}return["err","No subscriber."]}subscribe(e,t){return e.forEach((e=>{if(e=0===e.indexOf("#")?t.HOME_CHANNEL+e:e.includes("@")?this.CID_PREFIX+e:this.CHANNEL_PREFIX+e,this.channel_map.has(e)?this.channel_map.get(e).add(t):this.channel_map.set(e,new Set([t])),t.channels.add(e),e.includes("$")&&Us.retain.isAvailable){let r;if(e.includes("@")){let t=e.split("@")[0];t=t.split(this.CID_PREFIX)[1];let s=e.split("@")[1];if(!this.cid2remote.has(t))return;r=this.cid2remote.get(t).retain_signal.get(s)}else this.retain_messages.has(e)&&(r=this.retain_messages.get(e));r&&t.send_enc_mode(r)}})),t.channels.size}unsubscribe(e,t){1==e.length&&""==e[0]?(t.channels.forEach((e=>{if(this.channel_map.has(e)){let r=this.channel_map.get(e);r.delete(t),0==r.size&&this.channel_map.delete(e)}})),t.channels.clear()):e.forEach((e=>{if(e=0===e.indexOf("#")?t.HOME_CHANNEL+e:e.includes("@")?this.CID_PREFIX+e:this.CHANNEL_PREFIX+e,this.channel_map.has(e)){let r=this.channel_map.get(e);r.delete(t),0==r.size&&this.channel_map.delete(e)}t.channels.delete(e)}))}monitor(){process.stdout.isTTY&&(process.stdout.cursorTo(0,0),process.stdout.clearScreenDown()),Us.showChannel>0&&this.metric.channels(Us.showChannel);let e=parseInt(Us.showMetric);switch(console.log("monitor metric type:",e),e){case 1:this.metric.oneline(!0);break;case 2:this.metric.getRemotes(!0);break;case 3:this.metric.getChannelList(!0)}}closeRemoteByCId(e){return this.cid2remote.has(e)?(this.cid2remote.get(e).close(),1):0}}const qs=0,Ys=255;class Qs extends k.default{constructor(e,t){if(super(),this.apiNames=new Set,e.timeout){let t=parseInt(e.timeout);t&&t>=1e3&&(Us.timeout=t)}if(e.monitorPeriod){let t=parseInt(e.monitorPeriod);t&&t>=1e3&&(Us.monitorPeriod=t)}e.showMessage&&(Us.showMessage=e.showMessage),e.showMetric&&(Us.showMetric=e.showMetric),e.timeout&&(Us.timeout=e.timeout),e.port&&(Us.port=parseInt(e.port)),e.congPort&&(Us.congPort=parseInt(e.congPort)),this.manager=new Vs(this,t),Us.port&&this.startWSServer(Us.port),Us.congPort&&this.startCongServer(Us.congPort)}startWSServer(e){console.log("opening WebSocket Server:",e),this.wss=new Cs({port:e}),this.wss.on("error",(e=>{console.error("### ws server error:",e.message),"EADDRINUSE"==e.code&&process.exit()})),this.wss.on("close",(e=>{console.log("### WS server closed.",e)})),this.wss.on("connection",((e,t)=>{e.socketType="websocket",this.manager.addRemote(e,t)}))}startCongServer(e){console.log("opening CongSocket Server:",e),this.congServer=m.default.createServer((e=>{this.manager.addRemote(e)})).on("error",(e=>{console.log("### cong server error:",e.message),"EADDRINUSE"==e.code&&process.exit()})).listen(e,(()=>{}))}api(e,t){if(this.apiNames.add(e),!t.checkPermission||"function"!=typeof t.checkPermission)throw new Error("wrong api interface. no checkPermission function.");if("function"==typeof t.request&&Array.isArray(t.commands))console.log(`API TYPE1. A Class with one request function. target: ${e} list: ${t.commands}`),this.on(e,((e,r)=>{t.checkPermission(e,r)?t.request(e,r):e.response(r.mid,Ys,"NO_PERMISSION.")}));else{let r=[];Object.keys(t).forEach((e=>{"function"==typeof t[e]&&r.push(e),console.log("api list",typeof t[e],e)})),console.log(`API TYPE2. Multiple function list. target: ${e} list:${r}`),this.on(e,((r,s)=>{let i;if(t.checkPermission(r,s)){if(t[s.topic])return console.log(`API TYPE2. request target: ${e} has topic:${s.topic}`),void t[s.topic](r,s);i=`target: ${s.target} has not topic name: ${s.topic}`}else i="NO_PERMISSION.";r.response(s.mid,Ys,i)}))}return this}}const Ks=new TextDecoder;class Js{constructor(){this.authLogger,Us.fileLogger.auth.use&&(this.authLogger=new js(Us.fileLogger.auth.path),console.log("Auth: begin file logger.[auth]"))}send_auth_fail(e,t){if(this.authLogger){let r=`FAIL #${e.ssid} reason:${t} `;this.authLogger.log(r)}console.log("## AUTH_FAIL reason:",t),e.setState(De.AUTH_FAIL),setTimeout((t=>{e.send(Buffer.from([Ce.AUTH_FAIL]))}),Us.auth.delay_auth_fail)}async verify_auth_hmac(e,t){try{let r=re(e,Ie.AUTH_HMAC);if(!r)return void this.send_auth_fail(t,"unpack auth_pack fail");let s="";s=r.id8.includes(0)?Ks.decode(r.id8.subarray(0,r.id8.indexOf(0))):Ks.decode(r.id8);let i,n=await this.getAuth(s);if(Us.debug.showAuthInfo,!n)return void this.send_auth_fail(t,"NO ID:"+s);t.boho.copy_id8(r.id8);const o=44;n.key.length==o?(i=Buffer.from(n.key,"base64"),t.boho.copy_key(i)):t.boho.set_key(n.key);let a=t.boho.check_auth_hmac(r);if(!a)return void this.send_auth_fail(t,"hmac dismatched");if(t.manager.cid2remote.has(n.cid)){let e=t.manager.cid2remote.get(n.cid);return e==t?void console.log("## trying RELOGIN with SAME ID. ignored."):(console.log("### clear_auth and close old connection:",e.cid),e.send(Buffer.from([je.SERVER_CLEAR_AUTH])),e.close(),void t.close())}t.cid&&t.manager.cid2remote.delete(t.cid),t.did=s,t.cid=n.cid,t.nick=n.cid;let h=Us.defaultQuotaIndex;n.level&&(h=n.level),h=parseInt(h);let c=ze[h];if(!c){let e="no index quotaTable for auth.level: "+h;return console.log("##AUTH:DATA ERROR##",e),void this.send_auth_fail(t,e)}if(t.level=h,t.quota=c,t.level===Us.adminLevel&&(console.log("## LOGIN ADMIN CID:",t.cid),t.isAdmin=!0),t.send(Buffer.from([je.QUOTA_LEVEL,h])),t.manager.cid2remote.set(t.cid,t),t.send(a),t.setState(De.AUTH_READY),this.authLogger){let e=`OK #${t.ssid} cid: ${t.cid} did:${t.did}`;t.isAdmin&&(e="#ADMIN# "+e),this.authLogger.log(e)}return n}catch(e){this.send_auth_fail(t,"caught: unknown error"+e)}}}const Xs="device:";var Zs=Object.freeze({__proto__:null,checkPermission:function(e){return e.level>=0},echo:async function(e,t){t.args?e.response(t.mid,qs,t.args):e.response(t.mid,Ys,"no message to echo")},date:async function(e,t){let r=(new Date).toUTCString();e.response(t.mid,qs,r)},unixtime:async function(e,t){let r=Math.floor(Date.now()/1e3);e.response(t.mid,qs,r)}});var ei=Object.freeze({__proto__:null,commands:["cid","remotes","clients","channels","subscribers","remote","client","close","addauth","getauth","delauth","getauthidlist","getdevicelist","adddevice","getdevice","deldevice"],checkPermission:function(e){return e.level>=255},request:async function(e,t){let r,s=0;try{let i=t.topic;if(i=i.toLowerCase(),"cid"==i)r=e.manager.metric.getCIdList();else if("remotes"==i||"clients"==i)r=e.manager.metric.getRemotes();else if("channels"==i)r=e.manager.metric.getChannelList();else if("subscribers"==i){let s=t.$[0];s&&(r=e.manager.metric.getSubscribers(s))}else if("remote"==i||"client"==i){let s=t.$[0],i=t.$[1];s&&(r=e.manager.metric.getRemoteByCId(s,i))}else if("close"==i)t.$[0]&&(r=e.manager.closeRemoteByCId(t.$[0]));else if("addauth"==i||"adddevice"==i){if(e.manager.authManager&&4==t.$.length&&e.manager.authManager.addAuth){let s=t.$[0],i=t.$[1],n=t.$[2],o=t.$[3];r=await e.manager.authManager.addAuth(s,i,n,o)}}else if("delauth"==i||"deldevice"==i){if(e.manager.authManager&&1==t.$.length&&e.manager.authManager.delAuth){let s=t.$[0];r=await e.manager.authManager.delAuth(s)}}else if("getauth"==i||"getdevice"==i){if(e.manager.authManager&&1==t.$.length&&e.manager.authManager.getAuth){let s=t.$[0];r=await e.manager.authManager.getAuth(s)}}else"getauthidlist"==i||"getdevicelist"==i?e.manager.authManager&&e.manager.authManager.getAuthIdList&&(r=await e.manager.authManager.getAuthIdList()):(s=Ys,r="api sudo: no such a cmd: "+i);e.response(t.mid,s,r)}catch(r){e.response(t.mid,Ys,r.message)}}});const ti=["GET","SET","HGETALL","HGET","HSET","SADD","SISMEMBER","SMEMBERS","EXISTS","SREM","DEL","KEYS","SAVE"];exports.API_TYPE={REQUEST_RESPONSE:"requet_response",ONE_WAY:"one_way"},exports.Auth_Env=class extends Js{constructor(e){let t;super(),e?t=e.split(","):process.env.BOHO_AUTH?(e=process.env.BOHO_AUTH,t=process.env.BOHO_AUTH.split(",")):(console.log("Auth_Env: None of process.env.BOHO_AUTH or authInfo"),process.exit()),this.AUTH=new Map,t.length>=1?t.forEach((e=>{let t=e.split(".")[0],r=e.split(".")[1],s=e.split(".")[2];if(s=parseInt(s),t&&r&&"number"==typeof s){let e=t;this.addAuth(t,r,e,s)}else console.log("Wrong process.env.BOHO_AUTH authentication value.",id,r,s),process.exit()})):(console.log("Wrong process.env.BOHO_AUTH authentication value."),process.exit())}async getAuth(e){return this.AUTH.get(e)}async getAuthIdList(){return Array.from(this.AUTH.keys())}addAuth(e,t,r,s=0){let i=Buffer.from(xe.hash(t)).toString("base64");this.AUTH.set(e,{key:i,cid:r,level:s})}},exports.Auth_File=class extends Js{constructor(e){super(),this.AUTH=new Map;let t=w.default.parse(e);this.path=w.default.resolve(e),console.log("auth from file path:",this.path);let r=t.ext;".js"==r.toLowerCase()||".mjs"==r.toLowerCase()?(console.log("#JS path:",this.path),this.loadAuthInfoFile_JS(this.path)):".json"==r.toLowerCase()?(console.log("#JSON path:",this.path),this.loadAuthInfoFile_JSON(this.path)):console.log("no authinfofile path.")}async getAuth(e){return this.AUTH.get(e)}async getAuthIdList(){return Array.from(this.AUTH.keys())}loadAuthInfoFile_JS(e){var t;(t=e,Promise.resolve().then((function(){return g(require(t))}))).then((e=>{console.log(e.authInfo),e.authInfo.forEach((e=>{this.addAuth(...e)})),console.log("total AUTH INFO size: ",this.AUTH.size)})).catch((e=>{console.log(e)}))}loadAuthInfoFile_JSON(e){let t=i.readFileSync(e);t=(new TextDecoder).decode(t),JSON.parse(t).forEach((e=>{this.addAuth(...e)})),console.log("total AUTH INFO size: ",this.AUTH.size)}addAuth(e,t,r,s=0){let i=Buffer.from(xe.hash(t)).toString("base64");this.AUTH.set(e,{key:i,cid:r,level:s})}},exports.Auth_Redis=class extends Js{constructor(e){if(super(),!e)throw new Error("AuthRedis constructor: no redisClient");this.redis=e}async getAuth(e){let t=await this.redis.hGetAll(Xs+e);if(t.key)return t}async getAuthIdList(){let e=await this.redis.keys(Xs+"*");if(e=e.map((e=>e.split(":")[1])),e)return e}async addAuth(e,t,r="",s=0){let i=Buffer.from(xe.hash(t)).toString("base64");return this.redis.hSet(Xs+e,{key:i,cid:r,level:s})}async delAuth(e){return this.redis.del(Xs+e)}async save(e){return this.redis.save()}},exports.Boho=Me,exports.BohoAuth=Js,exports.BohoMsg=Ce,exports.Buffer=W.Buffer,exports.CLIENT_STATE=De,exports.CongRx=et,exports.ENC_MODE=He,exports.FileLogger=js,exports.IO=class extends Ye{constructor(e){super(e),e&&this.open()}close(){this.socket&&(this.socket.onclose=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.close(),this.socket=null),this.emit("close")}stop(){this.close(),clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null}keepAlive(){this.socket&&3!==this.socket?.readyState||this.open()}createConnection(e){this.socket=new is(e),this.stateChange("opening"),this.socket.onopen=()=>{this.socket.on("message",this.onWebSocketMessage.bind(this)),this.emit("open")},this.socket.onerror=e=>{this.emit("error",e)},this.socket.onclose=()=>{this.emit("close")}}onWebSocketMessage(e){this.rxCounter++,this.lastTxRxTime=Date.now(),this.rxBytes+=e.byteLength,this.emit("socket_data",e)}socket_send(e){1===this.socket?.readyState?(this.socket.send(e),this.txCounter++,this.txBytes+=e.byteLength,this.lastTxRxTime=Date.now()):console.log("")}},exports.IOCongSocket=class extends Ye{constructor(e){super(e),e&&this.open()}close(){this.socket?.end(),this.socket=null}stop(){this.close(),clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null}keepAlive(){let e=this.socket?.readyState;(!this.socket||"open"!==e&&"opening"!==e)&&this.open()}createConnection(e){let t=new URL(e);"cong:"!=t.protocol&&(t=new URL("cong://"+e)),this.socket=m.default.createConnection(t.port,t.hostname),this.stateChange("opening"),this.socket.on("connect",(()=>{this.congRx=new et,this.socket.pipe(this.congRx),this.congRx.on("data",this.onTCPSocketMessage.bind(this)),this.emit("open")})),this.socket.on("error",(e=>{this.emit("error",e)})),this.socket.on("close",(()=>{this.emit("close")}))}onTCPSocketMessage(e){this.rxCounter++,this.rxBytes+=e.byteLength,this.lastTxRxTime=Date.now(),this.emit("socket_data",e)}socket_send(e){if("open"===this.socket?.readyState){let t=Ze(e);this.socket.write(t),this.txCounter++,this.txBytes+=t.byteLength,this.lastTxRxTime=Date.now()}else console.log(".")}},exports.IOMsg=je,exports.MBP=we,exports.Meta=Ie,exports.MetaSize=Re,exports.PAYLOAD_TYPE=Fe,exports.RAND=Ue,exports.RedisAPI=class{constructor(e,t){if(!e)throw new Error("RedisAPI constructor: no redisClient");this.redisClient=e,this.minLevel=t||200,this.commands=ti}checkPermission(e,t){return console.log("checkPermission",e.level,"vs",this.minLevel),e.level>=this.minLevel}async request(e,t){let r,s=qs;try{let i=t.topic;i=i.toUpperCase(),ti.includes(i)?(console.log("RedisAPI call:",i,t.args),r=t.args.length>0?await this.redisClient[i](...t.args):await this.redisClient[i]()):s=Ys,e.response(t.mid,s,r)}catch(r){e.response(t.mid,Ys,r.message)}}},exports.SIZE_LIMIT=$e,exports.STATES=Pe,exports.STATUS={OK:0,ERROR:255},exports.Server=Qs,exports.api_reply=Zs,exports.api_sudo=ei,exports.pack=Ze,exports.serverOption=Us,exports.sha256=xe;
|
|
2
|
+
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */const G=new TextEncoder,V=new TextDecoder,q=Y;function Y(e,t=0){let r;if(void 0===e||"string"!=typeof e||"number"!=typeof t)throw TypeError("invlaid init variablie type name. ");return(e=e.toUpperCase()).includes("8")?(r=W.Buffer.alloc(1),e.includes("I")?r.writeInt8(t):r.writeUint8(t)):e.includes("16")?(r=W.Buffer.alloc(2),e.includes("I")?e.includes("L")?r.writeInt16LE(t):r.writeInt16BE(t):e.includes("L")?r.writeUint16LE(t):r.writeUint16BE(t)):e.includes("32")?(r=W.Buffer.alloc(4),e.includes("I")?e.includes("L")?r.writeInt32LE(t):r.writeInt32BE(t):e.includes("L")?r.writeUint32LE(t):r.writeUint32BE(t)):e.includes("F")?(r=W.Buffer.alloc(4),e.includes("L")?r.writeFloatLE(t):r.writeFloatBE(t)):e.includes("N")?r=W.Buffer.from(String(t)):console.log(`invalid type: ${e} or initvalue: ${t}`),r}const Q=K;function K(e,t,r){let s,i="B";if("number"==typeof t)"number"==typeof r?(s=W.Buffer.alloc(t),0!==r&&s.fill(r),i="B"):(s=W.Buffer.from(String(t)),i="N");else if("string"==typeof t&&"number"==typeof r)i=t.toUpperCase(),s=Y(t,r);else if("string"==typeof t&&void 0===r)s=W.Buffer.from(t),i="S";else if(t instanceof Uint8Array&&void 0===r)s=t instanceof W.Buffer?t:W.Buffer.from(t);else if(t instanceof ArrayBuffer&&void 0===r)s=W.Buffer.from(t);else if(ArrayBuffer.isView(t))s=W.Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if("object"==typeof t&&void 0===r)s=W.Buffer.from(JSON.stringify(t)),i="O";else{if("boolean"!=typeof t||void 0!==r)throw TypeError("invalid meta buffer type");{const e=t?1:0;s=W.Buffer.from([e]),i="!"}}return"string"==typeof e&&e.includes("#")&&(e=""),[e,i,s]}const J=X;function X(...e){let t=0;return e.map((e=>{const r=t++;return"number"==typeof e?Q(r,"N",e):Q(r,e)}))}function Z(e){if((e=e.toUpperCase()).includes("8"))return e.includes("I")?"int8":"uint8";if(e.includes("16"))return e.includes("I")?e.includes("L")?"int16_le":"int16_be":e.includes("L")?"uint16_le":"uint16_be";if(e.includes("32"))return e.includes("I")?e.includes("L")?"int32_le":"int32_be":e.includes("L")?"uint32_le":"uint32_be";if(e.includes("F"))return e.includes("L")?"float_le":"float_be";if("B"===e)return"buffer";if("S"===e)return"string";if("N"===e)return"number";if("O"===e)return"object";if("!"===e)return"boolean";throw TypeError("invalid data type")}function ee(e,t,r,s){try{const i=Z(e);if("int8"==i)return t.readInt8(r);if("uint8"===i)return t.readUint8(r);if("int16_le"===i)return t.readInt16LE(r);if("int16_be"===i)return t.readInt16BE(r);if("uint16_le"===i)return t.readUint16LE(r);if("uint16_be"===i)return t.readUint16BE(r);if("int32_le"===i)return t.readInt32LE(r);if("int32_be"===i)return t.readInt32BE(r);if("uint32_le"===i)return t.readUint32LE(r);if("uint32_be"===i)return t.readUint32BE(r);if("float_le"===i)return t.readFloatLE(r);if("float_be"===i)return t.readFloatBE(r);if("buffer"===i)return t.subarray(r,r+s);if("string"===i){const e=t.subarray(r,r+s);return V.decode(e)}if("number"===i){const e=t.subarray(r,r+s);return Number(V.decode(e))}if("object"===i){const e=t.subarray(r,r+s);return JSON.parse(V.decode(e))}if("boolean"===i){return 1===t.readInt8(r)}return}catch(e){}}function te(...e){const t=function(e){let t=[];return e.filter((e=>{if(!Array.isArray(e[0]))return e;t=t.concat(e)})).concat(t)}(e);let r=0;const s=[];let i,n,o=0;if(t.forEach((e=>{const[t,i,n]=e;r+=n.byteLength,("number"==typeof t||t.length>0)&&s.push([t,i,o,n.byteLength]),o=r})),s.length>0){let e=JSON.stringify(s);i=G.encode(e),n=i.byteLength,r=r+n+2}const a=W.Buffer.alloc(r);if(o=0,t.forEach((e=>{const t=e[2];a.set(t,o),o+=t.byteLength})),s.length>0){a.set(i,o);const e=q("16",n);return a.set(e,o+n),a}return a}function re(e,t){const r=t||me(e);if(!r)return;const s=W.Buffer.from(e),i={};let n=0;if(r.forEach((e=>{const[t,r,o,a]=e;let h=ee(r,s,o,a);null!=h&&(i[t]=h,a&&(n+=a))})),t&&s.byteLength!==n){let e=s.byteLength-n,t=ee("b",s,n,e);if(null==t)return;i.$OTHERS=t}let o=0,a=[];for(;i[o];)a.push(i[o++]);return a.length>0&&(i.args=a,i.$=i.args),i}const se=ie;function ie(e,t=!1){if(void 0===e)throw TypeError("Invalid data type: Undefined");if("string"==typeof e)return G.encode(e);if("number"==typeof e)return Uint8Array.from([e]);if(e instanceof ArrayBuffer){if(t)return new Uint8Array(e);{const t=new Uint8Array(e),r=new Uint8Array(e.byteLength);return r.set(t),r}}if(ArrayBuffer.isView(e)){if(t)return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);{const t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=new Uint8Array(e.byteLength);return r.set(t),r}}return G.encode(JSON.stringify(e))}const ne=oe;function oe(e,t=!1){const r=ie(e,t);return t?W.Buffer.from(r.buffer,r.byteOffset,r.byteLength):W.Buffer.from(r)}const ae=he;function he(...e){const t=e.map((e=>oe(e)));return W.Buffer.concat(t)}const ce=le;function le(...e){try{let t=0,r=0;const s=e.map((e=>ie(e)));s.forEach((e=>{t+=e.byteLength}));const i=new Uint8Array(t);return s.forEach((e=>{i.set(e,r),r+=e.byteLength})),i}catch(e){console.log(e)}}function fe(e,t){if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function ue(e){return 0===_e(e)?e.byteLength:e.byteLength-_e(e)-pe}function de(e,t){try{const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=r.byteLength-t-2,i=r.subarray(s,r.byteLength-2),n=V.decode(i),o=JSON.parse(n);if(!Array.isArray(o)||!Array.isArray(o[0]))return;let a=o[0];if(!a)return;if(a.length<3)return;const[h,c,l]=a;if("string"!=typeof c||"number"!=typeof l)return;return o}catch(e){}}const pe=2;function ge(e){if(e instanceof ArrayBuffer&&(e=W.Buffer.from(e)),e instanceof Uint8Array){if(e.byteLength<=pe)return 0;return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(e.byteLength-pe)}return 0}function _e(e){if(e instanceof ArrayBuffer&&(e=W.Buffer.from(e)),e instanceof Uint8Array){const t=e.byteLength;if(t<=pe)return 0;const r=ge(e);if(0===r||r>t)return 0;return de(e,r)?r:0}return 0}function ye(e){const t=ue(e);return e.subarray(0,t)}function me(e,t=!1){e instanceof ArrayBuffer&&(e=W.Buffer.from(e));const r=ge(e);if(0===r)return;let s=de(e,r);return s?t?(s.forEach((e=>{null==e[3]&&(e[1].includes("8")?e[3]=1:e[1].includes("16")?e[3]=2:e[1].includes("32")||e[1].includes("F")?e[3]=4:e[1].includes("!")&&(e[3]=1)),e[4]=Z(e[1])})),s):s:void 0}function be(...e){return ye(te(...e))}function Ee(...e){return me(te(...e))}var we=Object.freeze({__proto__:null,Buffer:W.Buffer,NB:q,numberBuffer:Y,MB:Q,metaBuffer:K,MBA:J,metaBufferArguments:X,parseTypeName:Z,readTypedBuffer:ee,pack:te,unpack:re,U8:se,parseUint8Array:ie,B8:ne,parseBuffer:oe,B8pack:ae,parseBufferThenConcat:he,U8pack:ce,parseUint8ThenConcat:le,hex:function(e){return Array.prototype.map.call(new Uint8Array(e),(e=>("00"+e.toString(16)).slice(-2))).join("")},equal:fe,getBufferSize:ue,parseMetaInfo:de,TAIL_LEN:pe,readTail:ge,getMetaSize:_e,getBuffer:ye,getMeta:me,rawPack:be,meta:Ee,metaDetail:function(...e){return me(te(...e),!0)},getMetaDetail:function(e){return me(e,!0)}}),ve=B((function(e){var t=Object.prototype.hasOwnProperty,r="~";function s(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,s,n,o){if("function"!=typeof s)throw new TypeError("The listener must be a function");var a=new i(s,n||e,o),h=r?r+t:t;return e._events[h]?e._events[h].fn?e._events[h]=[e._events[h],a]:e._events[h].push(a):(e._events[h]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function a(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,s,i=[];if(0===this._eventsCount)return i;for(s in e=this._events)t.call(e,s)&&i.push(r?s.slice(1):s);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var i=0,n=s.length,o=new Array(n);i<n;i++)o[i]=s[i].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,s=this._events[t];return s?s.fn?1:s.length:0},a.prototype.emit=function(e,t,s,i,n,o){var a=r?r+e:e;if(!this._events[a])return!1;var h,c,l=this._events[a],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,s),!0;case 4:return l.fn.call(l.context,t,s,i),!0;case 5:return l.fn.call(l.context,t,s,i,n),!0;case 6:return l.fn.call(l.context,t,s,i,n,o),!0}for(c=1,h=new Array(f-1);c<f;c++)h[c-1]=arguments[c];l.fn.apply(l.context,h)}else{var u,d=l.length;for(c=0;c<d;c++)switch(l[c].once&&this.removeListener(e,l[c].fn,void 0,!0),f){case 1:l[c].fn.call(l[c].context);break;case 2:l[c].fn.call(l[c].context,t);break;case 3:l[c].fn.call(l[c].context,t,s);break;case 4:l[c].fn.call(l[c].context,t,s,i);break;default:if(!h)for(u=1,h=new Array(f-1);u<f;u++)h[u-1]=arguments[u];l[c].fn.apply(l[c].context,h)}}return!0},a.prototype.on=function(e,t,r){return n(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return n(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,s,i){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return o(this,n),this;var a=this._events[n];if(a.fn)a.fn!==t||i&&!a.once||s&&a.context!==s||o(this,n);else{for(var h=0,c=[],l=a.length;h<l;h++)(a[h].fn!==t||i&&!a[h].once||s&&a[h].context!==s)&&c.push(a[h]);c.length?this._events[n]=1===c.length?c[0]:c:o(this,n)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}));const Se=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 ke(e,t,r,s,i){let n,o,a,h,c,l,f,u,d,p,g,_,y;for(;i>=64;){for(n=t[0],o=t[1],a=t[2],h=t[3],c=t[4],l=t[5],f=t[6],u=t[7],p=0;p<16;p++)g=s+4*p,e[p]=(255&r[g])<<24|(255&r[g+1])<<16|(255&r[g+2])<<8|255&r[g+3];for(p=16;p<64;p++)d=e[p-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,d=e[p-15],y=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,e[p]=(_+e[p-7]|0)+(y+e[p-16]|0);for(p=0;p<64;p++)_=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&l^~c&f)|0)+(u+(Se[p]+e[p]|0)|0)|0,y=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&o^n&a^o&a)|0,u=f,f=l,l=c,c=h+_|0,h=a,a=o,o=n,n=_+y|0;t[0]+=n,t[1]+=o,t[2]+=a,t[3]+=h,t[4]+=c,t[5]+=l,t[6]+=f,t[7]+=u,s+=64,i-=64}return s}const Ae=function(){function e(){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 e.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},e.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},e.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");let r=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[r++],t--;64===this.bufferLength&&(ke(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(r=ke(this.temp,this.state,e,r,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[r++],t--;return this},e.prototype.finish=function(e){if(!this.finished){const e=this.bytesHashed,r=this.bufferLength,s=e/536870912|0,i=e<<3,n=e%64<56?64:128;this.buffer[r]=128;for(var t=r+1;t<n-8;t++)this.buffer[t]=0;this.buffer[n-8]=s>>>24&255,this.buffer[n-7]=s>>>16&255,this.buffer[n-6]=s>>>8&255,this.buffer[n-5]=s>>>0&255,this.buffer[n-4]=i>>>24&255,this.buffer[n-3]=i>>>16&255,this.buffer[n-2]=i>>>8&255,this.buffer[n-1]=i>>>0&255,ke(this.temp,this.state,this.buffer,0,n),this.finished=!0}for(t=0;t<8;t++)e[4*t+0]=this.state[t]>>>24&255,e[4*t+1]=this.state[t]>>>16&255,e[4*t+2]=this.state[t]>>>8&255,e[4*t+3]=this.state[t]>>>0&255;return this},e.prototype.digest=function(){const e=new Uint8Array(this.digestLength);return this.finish(e),e},e.prototype._saveState=function(e){for(let t=0;t<this.state.length;t++)e[t]=this.state[t]},e.prototype._restoreState=function(e,t){for(let t=0;t<this.state.length;t++)this.state[t]=e[t];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},e}(),Te=function(){function e(e){this.inner=new Ae,this.outer=new Ae,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;const t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new Ae).update(e).finish(t).clean();else for(var r=0;r<e.length;r++)t[r]=e[r];for(r=0;r<t.length;r++)t[r]^=54;this.inner.update(t);for(r=0;r<t.length;r++)t[r]^=106;this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(r=0;r<t.length;r++)t[r]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(let e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){const e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function Le(e){const t=(new Ae).update(e),r=t.digest();return t.clean(),r}const xe={hash:function(e){return Le(se(e))},hex:function(e){return ne(Le(se(e))).toString("hex")},base64:function(e){return ne(Le(se(e))).toString("base64")}};xe.hmac=function(e,t){return function(e,t){const r=new Te(e).update(t),s=r.digest();return r.clean(),s}(se(e),se(t))};const Be=Q;let Ce={AUTH_REQ:176,AUTH_NONCE:177,AUTH_HMAC:178,AUTH_ACK:179,AUTH_FAIL:180,AUTH_EXT:181,ENC_PACK:182,ENC_E2E:183,ENC_488:184};for(let e in Ce)Ce[Ce[e]]=e;const Ie={AUTH_REQ:Ee(Be("header","8",0),Be("reserved","8",0)),AUTH_NONCE:Ee(Be("header","8",0),Be("unixTime","32L",0),Be("milTime","32L",0),Be("nonce",W.Buffer.alloc(4))),AUTH_HMAC:Ee(Be("header","8",0),Be("id8",W.Buffer.alloc(8)),Be("nonce",W.Buffer.alloc(4)),Be("hmac32",W.Buffer.alloc(32))),AUTH_ACK:Ee(Be("header","8",0),Be("hmac32",W.Buffer.alloc(32))),ENC_PACK:Ee(Be("type","8",0),Be("len","32L",0),Be("salt12",W.Buffer.alloc(12)),Be("hmac",8,0)),ENC_488:Ee(Be("type","8",0),Be("len","32L",0),Be("otpSrc8",W.Buffer.alloc(8)),Be("hmac8",W.Buffer.alloc(8)))};function Oe(e){let t=e[e.length-1];return t[2]+t[3]}const Re={AUTH_REQ:Oe(Ie.AUTH_REQ),AUTH_NONCE:Oe(Ie.AUTH_NONCE),AUTH_HMAC:Oe(Ie.AUTH_HMAC),AUTH_ACK:Oe(Ie.AUTH_ACK),ENC_PACK:Oe(Ie.ENC_PACK),ENC_488:Oe(Ie.ENC_488)};let Ne=!1;try{Ne="[object process]"===Object.prototype.toString.call(global.process)}catch(e){}function Ue(t){return Ne?e.webcrypto.getRandomValues(W.Buffer.alloc(t)):self.crypto.getRandomValues(W.Buffer.alloc(t))}class Me{constructor(){this._id8=W.Buffer.alloc(8),this._otpSrc44=W.Buffer.alloc(44),this._otp36=W.Buffer.alloc(36),this._hmac=W.Buffer.alloc(32),this.auth_salt12=W.Buffer.alloc(12),this.localNonce=W.Buffer.alloc(4),this.remoteNonce=W.Buffer.alloc(4),this.isAuthorized=!1}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}set_hash_id8(e){ne(xe.hash(e)).copy(this._id8,0,0,8)}set_id8(e){let t=ne(e);this._id8.fill(0),t.copy(this._id8,0,0,8)}set_key(e){ne(xe.hash(e)).copy(this._otpSrc44,0,0,32)}set_id_key(e){let t=e.indexOf(".");if(-1==t)return;let r=e.substring(0,t),s=e.substring(t+1);this.set_id8(r),this.set_key(s)}copy_id8(e){e.copy(this._id8,0,0,8)}copy_key(e){e.copy(this._otpSrc44,0,0,32)}sha256_n(e,t){let r=xe.hash(e);for(let e=0;e<t;e++)r=xe.hash(r);return r}set_clock_rand(){let e=Date.now(),t=parseInt(e/1e3);e%=4294967295;W.Buffer.concat([q("32L",t),q("32L",e),Ue(4)]).copy(this._otpSrc44,32)}set_clock_nonce(e){let t=Date.now(),r=parseInt(t/1e3);t%=4294967295;W.Buffer.concat([q("32L",r),q("32L",t),e]).copy(this._otpSrc44,32)}set_salt12(e){e.copy(this._otpSrc44,32)}resetOTP(){ne(xe.hash(this._otpSrc44)).copy(this._otp36,0,0,32)}getIndexOTP(e){return this._otp36.writeUInt32LE(e,32),xe.hash(this._otp36)}generateHMAC(e){let t=W.Buffer.concat([this._otpSrc44,e]);this._hmac=ne(xe.hash(t))}getHMAC8(e){let t=W.Buffer.concat([this._otpSrc44,e]);return this._hmac=ne(xe.hash(t)),this._hmac.subarray(0,8)}xotp(e,t=0,r=!1){let s=(e=ne(e,r)).byteLength,i=t,n=0,o=0;for(;s>0;){o=s<32?s:32;let t=this.getIndexOTP(++i);for(let r=0;r<o;r++)e[n++]^=t[r];s-=32}return e}auth_req(){return te(Q("#type","8",Ce.AUTH_REQ),Q("#reserved","8",0))}auth_nonce(){let e=Date.now(),t=Math.floor(e/1e3),r=e%1e3;return this.localNonce=Ue(4),this.auth_salt12=W.Buffer.concat([q("32L",t),q("32L",r),this.localNonce]),W.Buffer.concat([q("8",Ce.AUTH_NONCE),this.auth_salt12])}auth_hmac(e){let t=re(e,Ie.AUTH_NONCE);if(t){let e=W.Buffer.concat([q("32L",t.unixTime),q("32L",t.milTime),t.nonce]);return this.set_salt12(e),this.localNonce=Ue(4),this.generateHMAC(this.localNonce),this.remoteNonce=t.nonce,te(Q("#header","8",Ce.AUTH_HMAC),Q("#id8",this._id8),Q("#nonce",this.localNonce),Q("#hmac32",this._hmac))}return!1}check_auth_hmac(e){let t;if(e instanceof Uint8Array){if(t=re(e,Ie.AUTH_HMAC),!t)return}else t=e;this.set_salt12(this.auth_salt12),this.generateHMAC(t.nonce);let r=this._hmac;if(fe(t.hmac32,r)){this.remoteNonce=t.nonce;let e=W.Buffer.concat([this.localNonce,this.remoteNonce,this.localNonce]);this.set_salt12(e),this.generateHMAC(t.nonce);let r=this._hmac,s=be(Q("header","8",Ce.AUTH_ACK),Q("hmac32",r));return this.isAuthorized=!0,s}return!1}check_auth_ack_hmac(e){let t=re(e,Ie.AUTH_ACK);if(t){let e=W.Buffer.concat([this.remoteNonce,this.localNonce,this.remoteNonce]);if(this.set_salt12(e),this.generateHMAC(this.localNonce),fe(this._hmac,t.hmac32))return this.isAuthorized=!0,!0}}encrypt_488(e){if(!this.isAuthorized)return;e=ne(e),this.set_clock_nonce(this.remoteNonce),this.resetOTP();let t=this.getHMAC8(e),r=this.xotp(e);return te(Q("#type","8",Ce.ENC_488),Q("#len","32L",e.byteLength),Q("#otpSrc8",this._otpSrc44.subarray(32,40)),Q("#hmac8",t),Q("#xdata",r))}decrypt_488(e){let t=re(e=ne(e),Ie.ENC_488);if(t){let e=W.Buffer.concat([t.otpSrc8,this.localNonce]);this.set_salt12(e),this.resetOTP();let r=t.$OTHERS.subarray(0,t.len),s=this.xotp(r);if(fe(this.getHMAC8(s),t.hmac8))return s}}encryptPack(e){e=ne(e),this.set_clock_rand(),this.resetOTP();let t=this.getHMAC8(e),r=this.xotp(e);return te(Q("#type","8",Ce.ENC_PACK),Q("#len","32L",e.byteLength),Q("#salt12",this._otpSrc44.subarray(32)),Q("#hmac8",t),Q("#xdata",r))}decryptPack(e){if(e[0]!==Ce.ENC_PACK)return;if(e.readUint32LE(1)==e.byteLength-Re.ENC_PACK)try{let t=re(e,Ie.ENC_PACK);if(!t)return;this.set_salt12(t.salt12),this.resetOTP();let r=t.$OTHERS,s=this.xotp(r),i=this.getHMAC8(s);if(fe(t.hmac,i))return t.data=s,t}catch(e){}}encrypt_e2e(e,t){let r=W.Buffer.alloc(32);r.set(this._otpSrc44.subarray(0,32)),this.set_key(t);let s=this.encryptPack(e);return this._otpSrc44.set(r),s}decrypt_e2e(e,t){let r=W.Buffer.alloc(32);r.set(this._otpSrc44.subarray(0,32)),this.set_key(t);let s=this.decryptPack(e);return this._otpSrc44.set(r),s}}const Pe={OPENING:0,OPEN:1,CLOSING:2,CLOSED:3,SERVER_READY:4,AUTH_FAIL:5,AUTH_READY:6,READY:7,REDIRECTING:8};for(let e in Pe)Pe[Pe[e]]=e;const De={INIT:0,SENT_SERVER_READY:1,RECV_AUTH_REQ:2,SENT_SERVER_NONCE:3,RECV_AUTH_HMAC:4,AUTH_FAIL:5,AUTH_READY:6,CID_READY:7};for(let e in De)De[De[e]]=e;let He={NO:0,YES:1,AUTO:2};for(let e in He)He[He[e]]=e;const $e={TAG_LEN1:255,TAG_LEN2:65535,CONNECTION_CHECKER_PERIOD:3e3,PROMISE_TIMEOUT:5e3,DID:8,CID:12};let Fe={EMPTY:0,TEXT:1,BINARY:2,OBJECT:3,MJSON:4,MBA:5};for(let e in Fe)Fe[Fe[e]]=e;let je={SERVER_READY:192,CID_REQ:193,CID_RES:194,QUOTA_LEVEL:195,SERVER_CLEAR_AUTH:196,SERVER_REDIRECT:197,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_CODE:220,RESPONSE_MBP:221,REQUEST:222,RESPONSE:223,FLOW_MODE:240,WAIT:241,RESUME:242,TIME_OUT:253,OVER_SIZE:254,OVER_FLOW:255};for(let e in je)je[je[e]]=e;let ze={0:{signalSize:1500,publishCounter:10,trafficRate:1e4},1:{signalSize:255,publishCounter:10,trafficRate:1e5},2:{signalSize:65535,publishCounter:10,trafficRate:1048576},3:{signalSize:1048576,publishCounter:10,trafficRate:20971520},10:{signalSize:1500,publishCounter:5,trafficRate:20971520},11:{signalSize:65535,publishCounter:10,trafficRate:20971520},12:{signalSize:1048576,publishCounter:100,trafficRate:20971520},200:{signalSize:20971520,publishCounter:1e4,trafficRate:104857600},255:{signalSize:20971520,publishCounter:1e4,trafficRate:104857600}};const We=new TextEncoder;function Ge(e,...t){if("string"!=typeof e)throw TypeError("tag should be string.");let r,s=We.encode(e),i=function(e){let t,r;if(0==e.length)t=Fe.EMPTY,r=null;else if(1==e.length)if("string"==typeof e[0]||"number"==typeof e[0])t=Fe.TEXT,r=We.encode(e[0]+"."),r[r.byteLength-1]=0;else if(ArrayBuffer.isView(e[0])||e[0]instanceof ArrayBuffer)t=Fe.BINARY,r=ne(e[0]);else{if("object"!=typeof e[0])throw new Error("unknown payload arguments");t=Fe.OBJECT,r=We.encode(JSON.stringify(e[0]))}else{let s=!1;e.forEach((e=>{(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)&&(s=!0)})),s?t=Fe.MBA:(t=Fe.MJSON,r=We.encode(JSON.stringify(e)))}return{type:t,buffer:r}}(t);if(i.type==Fe.EMPTY)r=te(Q("#MsgType","8",je.SIGNAL),Q("#tagLen","8",s.byteLength),Q("#tag",s),Q("#payloadType","8",i.type));else if(i.type==Fe.MBA){let e=te(J(...t));r=te(Q("#MsgType","8",je.SIGNAL),Q("#tagLen","8",s.byteLength),Q("#tag",s),Q("#payloadType","8",i.type),Q("#mbaBuffer",e))}else r=te(Q("#MsgType","8",je.SIGNAL),Q("#tagLen","8",s.byteLength),Q("#tag",s),Q("#payloadType","8",i.type),Q("#payload",i.buffer));return r}const Ve=new TextEncoder,qe=new TextDecoder;class Ye extends ve{constructor(e){super(),this.cid="",this.ip="",this.socket=null,this.url=e,this.state=Pe.CLOSED,this.stateName=this.getStateName(),this.txCounter=0,this.rxCounter=0,this.txBytes=0,this.rxBytes=0,this.lastTxRxTime=Date.now(),this.connectionCheckerPeriod=$e.CONNECTION_CHECKER_PERIOD,this.connectionCheckerIntervalID=null,this.boho=new Me,this.TLS=!1,this.encMode=He.AUTO,this.useAuth=!1,this.nick="",this.channels=new Set,this.promiseMap=new Map,this.promiseTimeOut=$e.PROMISE_TIMEOUT,this.mid=0,this.level=3,this.quota=ze[this.level],this.serverSet={},this.linkMap=new Map,this.on("open",this.onOpen.bind(this)),this.on("close",this.onClose.bind(this)),this.on("socket_data",this.onData.bind(this))}redirect(e){this.close(),this.stateChange("redirecting"),this.createConnection(e)}open(e){if(e||this.url){if(e)if(this.url){if(e!==this.url&&(this.url=e,this.socket))return void this.close()}else this.url=e;this.createConnection(this.url),this.connectionCheckerIntervalID||(this.connectionCheckerIntervalID=setInterval(this.keepAlive.bind(this),this.connectionCheckerPeriod))}}onOpen(){this.url.includes("wss://")?this.TLS=!0:this.TLS=!1,this.stateChange("open")}onClose(){this.boho.isAuthorized=!1,this.cid="",this.stateChange("closed")}login(e,t){if(!e&&!t)return void console.log("no id and key.");if(console.log("manual login: ",e),!t&&e.includes("."))this.boho.set_id_key(e);else{if(!e||!t)return void console.log("no id or key.");this.boho.set_id8(e),this.boho.set_key(t)}this.useAuth=!0;let r=this.boho.auth_req();this.send(r)}auth(e,t){if(e||t){if(!t&&e.includes("."))this.boho.set_id_key(e);else{if(!e||!t)return void console.log("no id or key.");this.boho.set_id8(e),this.boho.set_key(t)}this.useAuth=!0}else console.log("no id and key.")}onData(e){let t,r=e[0];if(r===Ce.ENC_488)t=this.boho.decrypt_488(e),t&&(r=t[0],e=t);else if(r===Ce.ENC_E2E)try{if(t=this.boho.decrypt_488(e),!t)return;r=t[0],e.set(t,Re.ENC_488),e=e.subarray(Re.ENC_488)}catch(e){return}let s=je[r];switch(s||(s=Ce[r]),r){case je.OVER_SIZE:console.log("## server sent: over_size event."),this.emit("over_size","over_size");break;case je.PING:this.pong();break;case je.PONG:break;case je.IAM_RES:try{let t=qe.decode(e.subarray(1)),r=JSON.parse(t);r.ip&&(this.ip=r.ip),console.log("<IAM_RES>",JSON.stringify(r))}catch(e){}break;case je.CID_RES:let r=qe.decode(e.subarray(1));this.cid=r,this.stateChange("ready","cid_ready"),this.subscribe_memory_channels();break;case je.QUOTA_LEVEL:let s=e[1];this.level=s,this.quota=ze[s],console.log("## QUOTA:",s,JSON.stringify(this.quota));break;case je.SERVER_CLEAR_AUTH:this.useAuth=!1,this.boho.clearAuth(),this.stop();break;case je.SERVER_REDIRECT:let i,n,o;7==e.byteLength?(i=function(e){if(6!=e.byteLength)return;return e[0].toString()+"."+e[1].toString()+"."+e[2].toString()+"."+e[3].toString()+":"+((e[4]<<8)+e[5]).toString()}(e.subarray(1)),o="cong://"):(i=qe.decode(e.subarray(1)),o=""),n=o+i,this.redirect(n);break;case je.SERVER_READY:this.stateChange("server_ready","server_ready"),this.useAuth?this.send(this.boho.auth_req()):this.send(W.Buffer.from([je.CID_REQ]));break;case je.SERVER_SIGNAL:try{let t=qe.decode(e.subarray(1)),r=JSON.parse(t);r.event&&r.data&&(this.serverSet=r.data,this.emit(r.event,r.data))}catch(e){}break;case je.SET:try{let t=re(e);t&&this.emit(t.topic,...t.args)}catch(e){}break;case je.SIGNAL_E2E:case je.SIGNAL:try{let t=e.readUint8(1),r=e.subarray(2,2+t),s=qe.decode(r),i=e.readUint8(2+t),n=e.subarray(3+t);switch(i){case Fe.EMPTY:0===s.indexOf("@")?this.emit("@",null,s):this.emit(s,null,s);break;case Fe.TEXT:let e=n.subarray(0,n.byteLength-1),t=qe.decode(e);0===s.indexOf("@")&&this.emit("@",t,s),"@"!==s&&this.emit(s,t,s);break;case Fe.BINARY:0===s.indexOf("@")&&this.emit("@",n,s),"@"!==s&&this.emit(s,n,s);break;case Fe.OBJECT:let r=qe.decode(n),i=JSON.parse(r);0===s.indexOf("@")&&this.emit("@",i,s),"@"!==s&&this.emit(s,i,s);break;case Fe.MJSON:let o=qe.decode(n),a=JSON.parse(o);0===s.indexOf("@")&&this.emit("@",...a,s),"@"!==s&&this.emit(s,...a,s);break;case Fe.MBA:let h=re(n);0===s.indexOf("@")&&this.emit("@",...h.args,s),"@"!==s&&this.emit(s,...h.args,s)}}catch(e){}break;case je.RESPONSE_MBP:this.testPromise(e);break;case Ce.AUTH_NONCE:let a=this.boho.auth_hmac(e);a?this.send(a):this.stateChange("auth_fail","Invalid local auth_hmac.");break;case Ce.AUTH_FAIL:this.stateChange("auth_fail","server reject auth.");break;case Ce.AUTH_ACK:this.boho.check_auth_ack_hmac(e)?(this.stateChange("auth_ready","server sent auth_ack"),this.send(W.Buffer.from([je.CID_REQ]))):this.stateChange("auth_fail","invalid server_hmac");break;default:try{t=qe.decode(e),this.emit("text_message",t)}catch(e){}}}iam(e){e?this.send_enc_mode(te(Q("#MsgType","8",je.IAM),Q("#",e))):this.send_enc_mode(te(Q("#MsgType","8",je.IAM)))}ping(){this.send(W.Buffer.from([je.PING]))}pong(){this.send(W.Buffer.from([je.PONG]))}echo(e){e?(console.log("echo args:",e),this.send_enc_mode(te(Q("#MsgType","8",je.ECHO),Q("#msg",e)))):this.send(W.Buffer.from([je.ECHO]))}bin(...e){this.send(ce(...e))}send(e){if(e.byteLength>this.quota.signalSize)return this.emit("over_size"),console.log("## QUOTA LIMIT OVER!! \nsignal message.byteLength: ",e.byteLength),void console.log("## your maximum signalSize(bytes) is:",this.quota.signalSize);this.socket_send(e)}getEncryptionMode(){return!(this.encMode!==He.YES&&(this.encMode!==He.AUTO||this.TLS||!this.boho.isAuthorized))}send_enc_mode(e,t){if(void 0===t&&(t=this.getEncryptionMode()),e[0]==je.SIGNAL_E2E&&t){let t=e[1],r=this.boho.encrypt_488(e.subarray(0,3+t));r[0]=Ce.ENC_E2E,this.send(W.Buffer.concat([r,e.subarray(3+t)]))}else if(t){let t=this.boho.encrypt_488(e);this.send(t)}else this.send(e)}setMsgPromise(e){return new Promise(((t,r)=>{this.promiseMap.set(e,[t,r]),setTimeout((t=>{this.promiseMap.has(e)&&(r("timeout"),this.promiseMap.delete(e))}),this.promiseTimeOut)}))}testPromise(e){let t=re(e);if(t)if(this.promiseMap.has(t.mid)){let[e,r]=this.promiseMap.get(t.mid);this.promiseMap.delete(t.mid),t.status<128?(t.ok=!0,e(t)):(t.ok=!1,r(t))}else console.log("no promise id")}publish(...e){this.signal(...e)}signal(e,...t){if("string"!=typeof e)throw TypeError("tag should be string.");let r=Ge(e,...t);this.send_enc_mode(r)}decrypt_e2e(e,t){return this.boho.decrypt_e2e(e,t)}signal_e2e(e,t,r){if("string"!=typeof e)throw TypeError("tag should be string.");let s=Ve.encode(e),i=ne(t),n=this.boho.encrypt_e2e(i,r),o=te(Q("#MsgType","8",je.SIGNAL_E2E),Q("#tagLen","8",s.byteLength),Q("#tag",s),Q("#payloadType","8",Fe.BINARY),Q("#payload",n));this.send_enc_mode(o)}set(e,...t){return e&&0!=t.length?this.req("store","set",e,...t):Promise.reject(new Error("set need storeName and value)"))}async get(e){if(!e)return Promise.reject(new Error("store get need storeName)"));let t=await this.req("store","get",e),{$:r}=re(t.body);return r}req(e,t,...r){if(!e||!t)return Promise.reject(new Error("request need target and topic)"));let s;return s=r.length>0?te(Q("#MsgType","8",je.REQUEST),Q("mid","16",++this.mid),Q("target",e),Q("topic",t),J(...r)):te(Q("#MsgType","8",je.REQUEST),Q("mid","16",++this.mid),Q("target",e),Q("topic",t)),this.send_enc_mode(s),this.setMsgPromise(this.mid)}subscribe(e){if("string"!=typeof e)throw TypeError("tag should be string.");if(this.state!==Pe.READY)return;e.split(",").forEach((e=>{this.channels.add(e)}));let t=Ve.encode(e);if(t.byteLength>$e.TAG_LEN1)throw TypeError("please use tag string bytelength below:"+$e.TAG_LEN1);this.send_enc_mode(W.Buffer.concat([q("8",je.SUBSCRIBE),q("8",t.byteLength),t]))}subscribe_promise(e){if("string"!=typeof e)throw TypeError("tag should be string.");if(this.state!==Pe.READY)return Promise.reject("subscribe_promise:: connection is not ready");let t=Ve.encode(e);if(t.byteLength>$e.TAG_LEN2)throw TypeError("please use tag string bytelength: "+$e.TAG_LEN2);return this.send_enc_mode(W.Buffer.concat([q("8",je.SUBSCRIBE_REQ),q("16",++this.mid),q("16",t.byteLength),t])),this.setMsgPromise(this.mid)}subscribe_memory_channels(){if(0==this.channels.size)return;let e=Array.from(this.channels).join(",");this.subscribe_promise(e).then((e=>{})).catch((e=>{console.log(">> SUBSCRIBE FAIL:",e)}))}unsubscribe(e=""){if("string"!=typeof e)throw TypeError("tag should be string.");if(""==e)this.channels.clear();else{e.split(",").forEach((e=>{this.channels.delete(e)}))}let t=Ve.encode(e);if(t.byteLength>$e.TAG_LEN1)throw TypeError("please use tag string bytelength below:"+$e.TAG_LEN1);this.send_enc_mode(W.Buffer.concat([q("8",je.UNSUBSCRIBE),q("8",t.byteLength),t]))}listen(e,t){if("string"!=typeof e)throw TypeError("tag should be string.");if(e.length>255||0==e.length)throw TypeError("tag string length range: 1~255");if("function"!=typeof t)throw TypeError("handler is not a function.");0!==e.indexOf("@")&&this.channels.add(e),this.on(e,t)}link(e,t,r){if("string"!=typeof e)throw TypeError("to(local link target) is not a string.");if("string"!=typeof t)throw TypeError("tag is not a string.");if(t.length>255||0==t.length)throw TypeError("tag string length range: 1~255");if("function"!=typeof r)throw TypeError("handler is not a function.");let s;0!==t.indexOf("@")&&this.channels.add(t),s=this.linkMap.has(e)?this.linkMap.get(e):new Set,s.add(t),this.linkMap.set(e,s),this.on(t,r),this.subscribe(t)}unlink(e,t){if("string"!=typeof e)throw TypeError("to(local link target) is not a string.");if("string"!=typeof t)throw TypeError("tag is not a string.");if(t.length>255||0==t.length)throw TypeError("tag string length range: 1~255");if(!this.linkMap.has(e))return;let r=this.linkMap.get(e),s=Array.from(r);for(let i=0;i<s.length;i++)if(s[i]==t){this.unsubscribe(t),this.removeAllListeners(t),r.delete(t),this.linkMap.set(e,r);break}}unlinkAll(e){if("string"!=typeof e)throw TypeError("to(local link target) is not a string.");if(!this.linkMap.has(e))return;let t=this.linkMap.get(e),r=Array.from(t);for(let e=0;e<r.length;e++)this.unsubscribe(r[e]),this.removeAllListeners(r[e]),t.delete(r[e]);this.linkMap.delete(e)}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 Pe[this.state].toLowerCase()}getSecurity(){return{useAuth:this.useAuth,isTLS:this.TLS,isAuthorized:this.boho.isAuthorized,encMode:this.encMode,usingEncryption:this.getEncryptionMode()}}stateChange(e,t){let r=e.toLowerCase();this.state=Pe[e.toUpperCase()],t&&this.emit(r,t),this.stateName!==r&&(this.stateName=r,this.emit("change",r))}}const Qe=1,Ke=2,Je=3,Xe=4;function Ze(e){if(e.byteLength<256)return te(Q("#type","8",Qe),Q("#payloadLen1","8",e.byteLength),Q("#payload",e));if(e.byteLength<65536)return te(Q("#type","8",Ke),Q("#payloadLen2","16L",e.byteLength),Q("#payload",e));if(e.byteLength<2**24){let t=Buffer.alloc(4);t.writeUint32LE(e.byteLength);let r=t.subarray(0,3);return te(Q("#type","8",Je),Q("#payloadLen3",r),Q("#payload",e))}return te(Q("#type","8",Xe),Q("#payloadLen4","32L",e.byteLength),Q("#payload",e))}class et extends t.Transform{constructor(e){super(e),this.buffer=Buffer.alloc(0),this.frames=[],this.rxi=0,this.rxi_zero=0}_transform(e,t,r){this.addData(e),this.frames.length>0&&(this.frames.forEach((e=>{this.push(e)})),this.frames=[]),r()}addData(e){let t=e.byteLength,r=0;for(;t--;)this.rxi++,0==e[r++]&&this.rxi_zero++;this.buffer.byteLength>0?this.buffer=Buffer.concat([this.buffer,e]):this.buffer=e,this.parse()}parse(){let e,t,r=this.buffer[0];if(r==Qe){if(e=2,this.buffer.byteLength<e)return;t=this.buffer.readUint8(1)}else if(r==Ke){if(e=3,this.buffer.byteLength<e)return;t=this.buffer.readUint16LE(1)}else if(r==Je){if(e=4,this.buffer.byteLength<e)return;t=this.buffer.readUint16LE(1)+65536*this.buffer.readUint8(3)}else if(r==Xe){if(e=5,this.buffer.byteLength<e)return;t=this.buffer.readUint32LE(1)}else this.emit("wrong",this.buffer),this.buffer=Buffer.alloc(0);if(t==this.buffer.byteLength-e)return this.frames.push(this.buffer.subarray(e)),void(this.buffer=Buffer.alloc(0));t<this.buffer.byteLength-e&&(this.frames.push(this.buffer.subarray(e,e+t)),this.buffer=this.buffer.subarray(e+t),this.parse())}}var tt={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}},rt="function"==typeof __webpack_require__?__non_webpack_require__:C,st=process.config&&process.config.variables||{},it=!!process.env.PREBUILDS_ONLY,nt=process.versions.modules,ot=!(!process.versions||!process.versions.electron)||!!process.env.ELECTRON_RUN_AS_NODE||"undefined"!=typeof window&&window.process&&"renderer"===window.process.type?"electron":process.versions&&process.versions.nw?"node-webkit":"node",at=process.env.npm_config_arch||v.default.arch(),ht=process.env.npm_config_platform||v.default.platform(),ct=process.env.LIBC||(function(e){return"linux"===e&&E.default.existsSync("/etc/alpine-release")}(ht)?"musl":"glibc"),lt=process.env.ARM_VERSION||("arm64"===at?"8":st.arm_version)||"",ft=(process.versions.uv||"").split(".")[0],ut=dt;function dt(e){return rt(dt.resolve(e))}function pt(e){try{return E.default.readdirSync(e)}catch(e){return[]}}function gt(e,t){var r=pt(e).filter(t);return r[0]&&w.default.join(e,r[0])}function _t(e){return/\.node$/.test(e)}function yt(e){var t=e.split("-");if(2===t.length){var r=t[0],s=t[1].split("+");if(r&&s.length&&s.every(Boolean))return{name:e,platform:r,architectures:s}}}function mt(e,t){return function(r){return null!=r&&(r.platform===e&&r.architectures.includes(t))}}function bt(e,t){return e.architectures.length-t.architectures.length}function Et(e){var t=e.split("."),r={file:e,specificity:0};if("node"===t.pop()){for(var s=0;s<t.length;s++){var i=t[s];if("node"===i||"electron"===i||"node-webkit"===i)r.runtime=i;else if("napi"===i)r.napi=!0;else if("abi"===i.slice(0,3))r.abi=i.slice(3);else if("uv"===i.slice(0,2))r.uv=i.slice(2);else if("armv"===i.slice(0,4))r.armv=i.slice(4);else{if("glibc"!==i&&"musl"!==i)continue;r.libc=i}r.specificity++}return r}}function wt(e,t){return function(r){return null!=r&&(!(r.runtime!==e&&!function(e){return"node"===e.runtime&&e.napi}(r))&&(!(r.abi!==t&&!r.napi)&&((!r.uv||r.uv===ft)&&((!r.armv||r.armv===lt)&&(!r.libc||r.libc===ct)))))}}function vt(e){return function(t,r){return t.runtime!==r.runtime?t.runtime===e?-1:1:t.abi!==r.abi?t.abi?-1:1:t.specificity!==r.specificity?t.specificity>r.specificity?-1:1:0}}dt.resolve=dt.path=function(e){e=w.default.resolve(e||".");try{var t=rt(w.default.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[t+"_PREBUILD"]&&(e=process.env[t+"_PREBUILD"])}catch(e){}if(!it){var r=gt(w.default.join(e,"build/Release"),_t);if(r)return r;var s=gt(w.default.join(e,"build/Debug"),_t);if(s)return s}var i=a(e);if(i)return i;var n=a(w.default.dirname(process.execPath));if(n)return n;var o=["platform="+ht,"arch="+at,"runtime="+ot,"abi="+nt,"uv="+ft,lt?"armv="+lt:"","libc="+ct,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"","function"==typeof __webpack_require__?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+o+"\n loaded from: "+e+"\n");function a(e){var t=pt(w.default.join(e,"prebuilds")).map(yt).filter(mt(ht,at)).sort(bt)[0];if(t){var r=w.default.join(e,"prebuilds",t.name),s=pt(r).map(Et).filter(wt(ot,nt)).sort(vt(ot))[0];return s?w.default.join(r,s.file):void 0}}},dt.parseTags=Et,dt.matchTags=wt,dt.compareTags=vt,dt.parseTuple=yt,dt.matchTuple=mt,dt.compareTuples=bt;var St=B((function(e){const t="function"==typeof __webpack_require__?__non_webpack_require__:C;"function"==typeof t.addon?e.exports=t.addon.bind(t):e.exports=ut}));var kt={mask:(e,t,r,s,i)=>{for(var n=0;n<i;n++)r[s+n]=e[n]^t[3&n]},unmask:(e,t)=>{const r=e.length;for(var s=0;s<r;s++)e[s]^=t[3&s]}},At=B((function(e){try{e.exports=St(__dirname)}catch(t){e.exports=kt}})),Tt=B((function(e){const{EMPTY_BUFFER:t}=tt,r=Buffer[Symbol.species];function s(e,t,r,s,i){for(let n=0;n<i;n++)r[s+n]=e[n]^t[3&n]}function i(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(e.exports={concat:function(e,s){if(0===e.length)return t;if(1===e.length)return e[0];const i=Buffer.allocUnsafe(s);let n=0;for(let t=0;t<e.length;t++){const r=e[t];i.set(r,n),n+=r.length}return n<s?new r(i.buffer,i.byteOffset,n):i},mask:s,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let s;return t instanceof ArrayBuffer?s=new r(t):ArrayBuffer.isView(t)?s=new r(t.buffer,t.byteOffset,t.byteLength):(s=Buffer.from(t),e.readOnly=!1),s},unmask:i},!process.env.WS_NO_BUFFER_UTIL)try{const t=At;e.exports.mask=function(e,r,i,n,o){o<48?s(e,r,i,n,o):t.mask(e,r,i,n,o)},e.exports.unmask=function(e,r){e.length<32?i(e,r):t.unmask(e,r)}}catch(e){}}));const Lt=Symbol("kDone"),xt=Symbol("kRun");var Bt=class{constructor(e){this[Lt]=()=>{this.pending--,this[xt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xt]()}[xt](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Lt])}}};const{kStatusCode:Ct}=tt,It=Buffer[Symbol.species],Ot=Buffer.from([0,0,255,255]),Rt=Symbol("permessage-deflate"),Nt=Symbol("total-length"),Ut=Symbol("callback"),Mt=Symbol("buffers"),Pt=Symbol("error");let Dt;var Ht=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Dt){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Dt=new Bt(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[Ut];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){Dt.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){Dt.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?b.default.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=b.default.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Rt]=this,this._inflate[Nt]=0,this._inflate[Mt]=[],this._inflate.on("error",jt),this._inflate.on("data",Ft)}this._inflate[Ut]=r,this._inflate.write(e),t&&this._inflate.write(Ot),this._inflate.flush((()=>{const e=this._inflate[Pt];if(e)return this._inflate.close(),this._inflate=null,void r(e);const i=Tt.concat(this._inflate[Mt],this._inflate[Nt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Nt]=0,this._inflate[Mt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,i)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?b.default.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=b.default.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Nt]=0,this._deflate[Mt]=[],this._deflate.on("data",$t)}this._deflate[Ut]=r,this._deflate.write(e),this._deflate.flush(b.default.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Tt.concat(this._deflate[Mt],this._deflate[Nt]);t&&(e=new It(e.buffer,e.byteOffset,e.length-4)),this._deflate[Ut]=null,this._deflate[Nt]=0,this._deflate[Mt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function $t(e){this[Mt].push(e),this[Nt]+=e.length}function Ft(e){this[Nt]+=e.length,this[Rt]._maxPayload<1||this[Nt]<=this[Rt]._maxPayload?this[Mt].push(e):(this[Pt]=new RangeError("Max payload size exceeded"),this[Pt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pt][Ct]=1009,this.removeListener("data",Ft),this.reset())}function jt(e){this[Rt]._inflate=null,e[Ct]=1007,this[Ut](e)}var zt=function(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0},Wt=B((function(e){try{e.exports=St(__dirname)}catch(t){e.exports=zt}})),Gt=B((function(e){const{isUtf8:t}=S.default;function r(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(e.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:r,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},t)e.exports.isValidUTF8=function(e){return e.length<24?r(e):t(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const t=Wt;e.exports.isValidUTF8=function(e){return e.length<32?r(e):t(e)}}catch(e){}}));const{Writable:Vt}=y.default,{BINARY_TYPES:qt,EMPTY_BUFFER:Yt,kStatusCode:Qt,kWebSocket:Kt}=tt,{concat:Jt,toArrayBuffer:Xt,unmask:Zt}=Tt,{isValidStatusCode:er,isValidUTF8:tr}=Gt,rr=Buffer[Symbol.species];var sr=class extends Vt{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||qt[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Kt]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new rr(t.buffer,t.byteOffset+e,t.length-e),new rr(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new rr(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(0!=(48&t[0])){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=64==(64&t[0]);if(!r||this._extensions[Ht.extensionName]){if(this._fin=128==(128&t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=Yt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&Zt(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[Ht.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let s;s="nodebuffer"===this._binaryType?Jt(r,t):"arraybuffer"===this._binaryType?Xt(Jt(r,t)):r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",s,!0),this._state=0,this.startLoop(e)})))}else{const s=Jt(r,t);if(!this._skipUTF8Validation&&!tr(s)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",s,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,Yt),this.end();else{const r=e.readUInt16BE(0);if(!er(r)){const e=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const s=new rr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!tr(s)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=0}}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;const n=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(n,this.createError),n.code=i,n[Qt]=s,n}};const{randomFillSync:ir}=_.default,{EMPTY_BUFFER:nr}=tt,{isValidStatusCode:or}=Gt,{mask:ar,toBuffer:hr}=Tt,cr=Symbol("kByteLength"),lr=Buffer.alloc(4),fr=8192;let ur,dr=fr;class pr{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,s,i=!1,n=2,o=!1;t.mask&&(r=t.maskBuffer||lr,t.generateMask?t.generateMask(r):(dr===fr&&(void 0===ur&&(ur=Buffer.alloc(fr)),ir(ur,0,fr),dr=0),r[0]=ur[dr++],r[1]=ur[dr++],r[2]=ur[dr++],r[3]=ur[dr++]),o=0==(r[0]|r[1]|r[2]|r[3]),n=6),"string"==typeof e?s=t.mask&&!o||void 0===t[cr]?(e=Buffer.from(e)).length:t[cr]:(s=e.length,i=t.mask&&t.readOnly&&!o);let a=s;s>=65536?(n+=8,a=127):s>125&&(n+=2,a=126);const h=Buffer.allocUnsafe(i?s+n:n);return h[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(h[0]|=64),h[1]=a,126===a?h.writeUInt16BE(s,2):127===a&&(h[2]=h[3]=0,h.writeUIntBE(s,4,6)),t.mask?(h[1]|=128,h[n-4]=r[0],h[n-3]=r[1],h[n-2]=r[2],h[n-1]=r[3],o?[h,e]:i?(ar(e,r,h,n,s),[h]):(ar(e,r,e,0,s),[h,e])):[h,e]}close(e,t,r,s){let i;if(void 0===e)i=nr;else{if("number"!=typeof e||!or(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+r),i.writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0)}const n={[cr]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,i,!1,n,s]):this.sendFrame(pr.frame(i,n),s)}ping(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=hr(e)).length,i=hr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const n={[cr]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,n,r]):this.sendFrame(pr.frame(e,n),r)}pong(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=hr(e)).length,i=hr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const n={[cr]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,n,r]):this.sendFrame(pr.frame(e,n),r)}send(e,t,r){const s=this._extensions[Ht.extensionName];let i,n,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(i=Buffer.byteLength(e),n=!1):(i=(e=hr(e)).length,n=hr.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=s._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),s){const s={[cr]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:n,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,s,r]):this.dispatch(e,this._compress,s,r)}else this.sendFrame(pr.frame(e,{[cr]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:n,rsv1:!1}),r)}dispatch(e,t,r,s){if(!t)return void this.sendFrame(pr.frame(e,r),s);const i=this._extensions[Ht.extensionName];this._bufferedBytes+=r[cr],this._deflating=!0,i.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof s&&s(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],s=r[r.length-1];"function"==typeof s&&s(e)}}else this._bufferedBytes-=r[cr],this._deflating=!1,r.readOnly=!1,this.sendFrame(pr.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][cr],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][cr],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var gr=pr;const{kForOnEventAttribute:_r,kListener:yr}=tt,mr=Symbol("kCode"),br=Symbol("kData"),Er=Symbol("kError"),wr=Symbol("kMessage"),vr=Symbol("kReason"),Sr=Symbol("kTarget"),kr=Symbol("kType"),Ar=Symbol("kWasClean");class Tr{constructor(e){this[Sr]=null,this[kr]=e}get target(){return this[Sr]}get type(){return this[kr]}}Object.defineProperty(Tr.prototype,"target",{enumerable:!0}),Object.defineProperty(Tr.prototype,"type",{enumerable:!0});class Lr extends Tr{constructor(e,t={}){super(e),this[mr]=void 0===t.code?0:t.code,this[vr]=void 0===t.reason?"":t.reason,this[Ar]=void 0!==t.wasClean&&t.wasClean}get code(){return this[mr]}get reason(){return this[vr]}get wasClean(){return this[Ar]}}Object.defineProperty(Lr.prototype,"code",{enumerable:!0}),Object.defineProperty(Lr.prototype,"reason",{enumerable:!0}),Object.defineProperty(Lr.prototype,"wasClean",{enumerable:!0});class xr extends Tr{constructor(e,t={}){super(e),this[Er]=void 0===t.error?null:t.error,this[wr]=void 0===t.message?"":t.message}get error(){return this[Er]}get message(){return this[wr]}}Object.defineProperty(xr.prototype,"error",{enumerable:!0}),Object.defineProperty(xr.prototype,"message",{enumerable:!0});class Br extends Tr{constructor(e,t={}){super(e),this[br]=void 0===t.data?null:t.data}get data(){return this[br]}}Object.defineProperty(Br.prototype,"data",{enumerable:!0});const Cr={addEventListener(e,t,r={}){for(const s of this.listeners(e))if(!r[_r]&&s[yr]===t&&!s[_r])return;let s;if("message"===e)s=function(e,r){const s=new Br("message",{data:r?e:e.toString()});s[Sr]=this,Or(t,this,s)};else if("close"===e)s=function(e,r){const s=new Lr("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Sr]=this,Or(t,this,s)};else if("error"===e)s=function(e){const r=new xr("error",{error:e,message:e.message});r[Sr]=this,Or(t,this,r)};else{if("open"!==e)return;s=function(){const e=new Tr("open");e[Sr]=this,Or(t,this,e)}}s[_r]=!!r[_r],s[yr]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[yr]===t&&!r[_r]){this.removeListener(e,r);break}}};var Ir={CloseEvent:Lr,ErrorEvent:xr,Event:Tr,EventTarget:Cr,MessageEvent:Br};function Or(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:Rr}=Gt;function Nr(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var Ur={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,s,i=Object.create(null),n=!1,o=!1,a=!1,h=-1,c=-1,l=-1,f=0;for(;f<e.length;f++)if(c=e.charCodeAt(f),void 0===r)if(-1===l&&1===Rr[c])-1===h&&(h=f);else if(0===f||32!==c&&9!==c){if(59!==c&&44!==c)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===h)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f);const s=e.slice(h,l);44===c?(Nr(t,s,i),i=Object.create(null)):r=s,h=l=-1}}else-1===l&&-1!==h&&(l=f);else if(void 0===s)if(-1===l&&1===Rr[c])-1===h&&(h=f);else if(32===c||9===c)-1===l&&-1!==h&&(l=f);else if(59===c||44===c){if(-1===h)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f),Nr(i,e.slice(h,l),!0),44===c&&(Nr(t,r,i),i=Object.create(null),r=void 0),h=l=-1}else{if(61!==c||-1===h||-1!==l)throw new SyntaxError(`Unexpected character at index ${f}`);s=e.slice(h,f),h=l=-1}else if(o){if(1!==Rr[c])throw new SyntaxError(`Unexpected character at index ${f}`);-1===h?h=f:n||(n=!0),o=!1}else if(a)if(1===Rr[c])-1===h&&(h=f);else if(34===c&&-1!==h)a=!1,l=f;else{if(92!==c)throw new SyntaxError(`Unexpected character at index ${f}`);o=!0}else if(34===c&&61===e.charCodeAt(f-1))a=!0;else if(-1===l&&1===Rr[c])-1===h&&(h=f);else if(-1===h||32!==c&&9!==c){if(59!==c&&44!==c)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===h)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f);let o=e.slice(h,l);n&&(o=o.replace(/\\/g,""),n=!1),Nr(i,s,o),44===c&&(Nr(t,r,i),i=Object.create(null),r=void 0),s=void 0,h=l=-1}}else-1===l&&(l=f);if(-1===h||a||32===c||9===c)throw new SyntaxError("Unexpected end of input");-1===l&&(l=f);const u=e.slice(h,l);return void 0===r?Nr(t,u,i):(void 0===s?Nr(i,u,!0):Nr(i,s,n?u.replace(/\\/g,""):u),Nr(t,r,i)),t}};const{randomBytes:Mr,createHash:Pr}=_.default,{URL:Dr}=x.default,{BINARY_TYPES:Hr,EMPTY_BUFFER:$r,GUID:Fr,kForOnEventAttribute:jr,kListener:zr,kStatusCode:Wr,kWebSocket:Gr,NOOP:Vr}=tt,{EventTarget:{addEventListener:qr,removeEventListener:Yr}}=Ir,{format:Qr,parse:Kr}=Ur,{toBuffer:Jr}=Tt,Xr=Symbol("kAborted"),Zr=[8,13],es=["CONNECTING","OPEN","CLOSING","CLOSED"],ts=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class rs extends k.default{constructor(e,t,r){super(),this._binaryType=Hr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=$r,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=rs.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),is(this,e,t,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Hr.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const s=new sr({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new gr(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[Gr]=this,e[Gr]=this,s.on("conclude",ls),s.on("drain",fs),s.on("error",us),s.on("message",ps),s.on("ping",gs),s.on("pong",_s),e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ms),e.on("data",bs),e.on("end",Es),e.on("error",ws),this._readyState=rs.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=rs.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Ht.extensionName]&&this._extensions[Ht.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=rs.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==rs.CLOSED)if(this.readyState!==rs.CONNECTING)this.readyState!==rs.CLOSING?(this._readyState=rs.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";hs(this,this._req,e)}}pause(){this.readyState!==rs.CONNECTING&&this.readyState!==rs.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===rs.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===rs.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||$r,t,r)):cs(this,e,r)}pong(e,t,r){if(this.readyState===rs.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===rs.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||$r,t,r)):cs(this,e,r)}resume(){this.readyState!==rs.CONNECTING&&this.readyState!==rs.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===rs.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==rs.OPEN)return void cs(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Ht.extensionName]||(s.compress=!1),this._sender.send(e||$r,s,r)}terminate(){if(this.readyState!==rs.CLOSED)if(this.readyState!==rs.CONNECTING)this._socket&&(this._readyState=rs.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";hs(this,this._req,e)}}}Object.defineProperty(rs,"CONNECTING",{enumerable:!0,value:es.indexOf("CONNECTING")}),Object.defineProperty(rs.prototype,"CONNECTING",{enumerable:!0,value:es.indexOf("CONNECTING")}),Object.defineProperty(rs,"OPEN",{enumerable:!0,value:es.indexOf("OPEN")}),Object.defineProperty(rs.prototype,"OPEN",{enumerable:!0,value:es.indexOf("OPEN")}),Object.defineProperty(rs,"CLOSING",{enumerable:!0,value:es.indexOf("CLOSING")}),Object.defineProperty(rs.prototype,"CLOSING",{enumerable:!0,value:es.indexOf("CLOSING")}),Object.defineProperty(rs,"CLOSED",{enumerable:!0,value:es.indexOf("CLOSED")}),Object.defineProperty(rs.prototype,"CLOSED",{enumerable:!0,value:es.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(rs.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(rs.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[jr])return t[zr];return null},set(t){for(const t of this.listeners(e))if(t[jr]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[jr]:!0})}})})),rs.prototype.addEventListener=qr,rs.prototype.removeEventListener=Yr;var ss=rs;function is(e,t,r,s){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!Zr.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Zr.join(", ")})`);let n;if(t instanceof Dr)n=t;else try{n=new Dr(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===n.protocol?n.protocol="ws:":"https:"===n.protocol&&(n.protocol="wss:"),e._url=n.href;const o="wss:"===n.protocol,a="ws+unix:"===n.protocol;let h;if("ws:"===n.protocol||o||a?a&&!n.pathname?h="The URL's pathname is empty":n.hash&&(h="The URL contains a fragment identifier"):h='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',h){const t=new SyntaxError(h);if(0===e._redirects)throw t;return void ns(e,t)}const c=o?443:80,l=Mr(16).toString("base64"),f=o?A.default.request:T.default.request,u=new Set;let d,p;if(i.createConnection=i.createConnection||(o?as:os),i.defaultPort=i.defaultPort||c,i.port=n.port||c,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(d=new Ht(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Qr({[Ht.extensionName]:d.offer()})),r.length){for(const e of r){if("string"!=typeof e||!ts.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:n.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&n.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=f(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(i);i.timeout&&p.on("timeout",(()=>{hs(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Xr]||(p=e._req=null,ns(e,t))})),p.on("response",(n=>{const o=n.headers.location,a=n.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void hs(e,p,"Maximum redirects exceeded");let n;p.abort();try{n=new Dr(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void ns(e,r)}is(e,n,r,s)}else e.emit("unexpected-response",p,n)||hs(e,p,`Unexpected server response: ${n.statusCode}`)})),p.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==rs.CONNECTING)return;p=e._req=null;const n=t.headers.upgrade;if(void 0===n||"websocket"!==n.toLowerCase())return void hs(e,r,"Invalid Upgrade header");const o=Pr("sha1").update(l+Fr).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void hs(e,r,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let h;if(void 0!==a?u.size?u.has(a)||(h="Server sent an invalid subprotocol"):h="Server sent a subprotocol but none was requested":u.size&&(h="Server sent no subprotocol"),h)return void hs(e,r,h);a&&(e._protocol=a);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!d){return void hs(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Kr(c)}catch(t){return void hs(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==Ht.extensionName){return void hs(e,r,"Server indicated an extension that was not requested")}try{d.accept(t[Ht.extensionName])}catch(t){return void hs(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Ht.extensionName]=d}e.setSocket(r,s,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(p,e):p.end()}function ns(e,t){e._readyState=rs.CLOSING,e.emit("error",t),e.emitClose()}function os(e){return e.path=e.socketPath,m.default.connect(e)}function as(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=m.default.isIP(e.host)?"":e.host),L.default.connect(e)}function hs(e,t,r){e._readyState=rs.CLOSING;const s=new Error(r);Error.captureStackTrace(s,hs),t.setHeader?(t[Xr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ns,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function cs(e,t,r){if(t){const r=Jr(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${es[e.readyState]})`);process.nextTick(r,t)}}function ls(e,t){const r=this[Gr];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[Gr]&&(r._socket.removeListener("data",bs),process.nextTick(ys,r._socket),1005===e?r.close():r.close(e,t))}function fs(){const e=this[Gr];e.isPaused||e._socket.resume()}function us(e){const t=this[Gr];void 0!==t._socket[Gr]&&(t._socket.removeListener("data",bs),process.nextTick(ys,t._socket),t.close(e[Wr])),t.emit("error",e)}function ds(){this[Gr].emitClose()}function ps(e,t){this[Gr].emit("message",e,t)}function gs(e){const t=this[Gr];t._autoPong&&t.pong(e,!this._isServer,Vr),t.emit("ping",e)}function _s(e){this[Gr].emit("pong",e)}function ys(e){e.resume()}function ms(){const e=this[Gr];let t;this.removeListener("close",ms),this.removeListener("data",bs),this.removeListener("end",Es),e._readyState=rs.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Gr]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",ds),e._receiver.on("finish",ds))}function bs(e){this[Gr]._receiver.write(e)||this.pause()}function Es(){const e=this[Gr];e._readyState=rs.CLOSING,e._receiver.end(),this.end()}function ws(){const e=this[Gr];this.removeListener("error",ws),this.on("error",Vr),e&&(e._readyState=rs.CLOSING,this.destroy())}const{tokenChars:vs}=Gt;var Ss={parse:function(e){const t=new Set;let r=-1,s=-1,i=0;for(;i<e.length;i++){const n=e.charCodeAt(i);if(-1===s&&1===vs[n])-1===r&&(r=i);else if(0===i||32!==n&&9!==n){if(44!==n)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${i}`);-1===s&&(s=i);const n=e.slice(r,s);if(t.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=s=-1}}else-1===s&&-1!==r&&(s=i)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const n=e.slice(r,i);if(t.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return t.add(n),t}};const{createHash:ks}=_.default,{GUID:As,kWebSocket:Ts}=tt,Ls=/^[+/0-9A-Za-z]{22}==$/;class xs extends k.default{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ss,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=T.default.createServer(((e,t)=>{const r=T.default.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,s)=>{this.handleUpgrade(t,r,s,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(Cs,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Cs,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Cs(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",Is);const i=e.headers["sec-websocket-key"],n=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Rs(this,e,t,405,"Invalid HTTP method")}if(void 0===n||"websocket"!==n.toLowerCase()){return void Rs(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!Ls.test(i)){return void Rs(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Rs(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Os(t,400);const a=e.headers["sec-websocket-protocol"];let h=new Set;if(void 0!==a)try{h=Ss.parse(a)}catch(r){return void Rs(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const r=new Ht(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Ur.parse(c);e[Ht.extensionName]&&(r.accept(e[Ht.extensionName]),l[Ht.extensionName]=r)}catch(r){return void Rs(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const n={origin:e.headers[""+(8===o?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(n,((n,o,a,c)=>{if(!n)return Os(t,o||401,a,c);this.completeUpgrade(l,i,h,e,t,r,s)}));if(!this.options.verifyClient(n))return Os(t,401)}this.completeUpgrade(l,i,h,e,t,r,s)}completeUpgrade(e,t,r,s,i,n,o){if(!i.readable||!i.writable)return i.destroy();if(i[Ts])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Os(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ks("sha1").update(t+As).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),h._protocol=e)}if(e[Ht.extensionName]){const t=e[Ht.extensionName].params,r=Ur.format({[Ht.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),h._extensions=e}this.emit("headers",a,s),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",Is),h.setSocket(i,n,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",(()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Cs,this)}))),o(h,s)}}var Bs=xs;function Cs(e){e._state=2,e.emit("close")}function Is(){this.destroy()}function Os(e,t,r,s){r=r||T.default.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${T.default.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Rs(e,t,r,s,i){if(e.listenerCount("wsClientError")){const s=new Error(i);Error.captureStackTrace(s,Rs),e.emit("wsClientError",s,r,t)}else Os(r,s,i)}let Ns={clientTracking:!1,port:0,httpServer:null,congPort:0,timeout:5e4,showMessage:"none",showMetric:0,showChannel:0,monitorPeriod:5e3,fileLogger:{connection:{use:!1,path:"connection.log"},auth:{use:!1,path:"auth.log"},attack:{use:!1,path:"attack.log"}},useQuota:{signalSize:!1,publishCounter:!1,trafficRate:!1,disconnect:!1},defaultQuotaIndex:3,adminLevel:255,debug:{slow:!1,delay:500,showAuthInfo:!1},retain:{isAvailable:!0,limitSize:1e5,limitCounter:1e3},auth:{delay_auth_fail:1e3},memberOnly:!1};const Us=new TextDecoder,Ms=Q;class Ps{constructor(e,t){this.socket=e,e.isAlive=!0,e.txCounter=0,e.rxCounter=0,e.openTime=Date.now(),this.boho=new Me,this.encMode=He.AUTO,this.channels=new Set,this.retain_signal=new Map,this.ssid=Ps.ssid++,this.manager=t,this.cid,this.did,this.uid,this.nick="",this.lastEchoMessage="N",this.privateNode=!1,this.HOME_CHANNEL="",this.level=Ns.defaultQuotaIndex,this.quota=ze[this.level],this.isAdmin=!1,this.state,this.stateLog=[],this.setState(De.INIT)}static ssid=1;setState(e){this.state=e,Ns.debug.showAuthInfo&&(this.stateLog.push(e),console.log(this.stateLog.join(">")))}getState(){return this.state}getStateName(){return De[this.state].toLowerCase()}showMessageLog(e,t){let r=this.boho.isAuthorized?`did: ${this.did} ${this.cid}@`:`${this.cid}@`;if(t){let t=je[e[0]];t||(t=Ce[e[0]]),t=" ["+t+"]",e.byteLength>40?console.log(r+t+" LEN:",e.length):console.log(r+t,e)}else console.log(r+" [TEXT] %s",e)}rxQuotaChecker(e){let t=e.byteLength;return this.manager.rxBytes+=t,!(Ns.useQuota.signalSize&&t>this.quota.signalSize)||(console.log("## quota: size over"),this.send(Buffer.from([je.OVER_SIZE])),Ns.useQuota.disconnect&&this.close(),!1)}onTimeDelayMessage(e,t=!0){setTimeout((()=>{this.onSocketMessage(e,t)}),Ns.debug.delay)}onSocketMessage(t,r=!0){if(this.receiveMonitor(),!this.rxQuotaChecker(t))return;let s,i;if("message"===Ns.showMessage&&this.showMessageLog(t,r),r){if(s=t[0],s===Ce.ENC_488){try{i=this.boho.decrypt_488(t)}catch(e){return void console.log("-- E488 DEC_FAIL",e)}if(!i)return;s=i[0],t=i}else if(s===Ce.ENC_E2E){try{i=this.boho.decrypt_488(t)}catch(e){return void console.log("-- E2E DEC_FAIL",e)}if(!i)return;s=i[0],t.set(i,Re.ENC_488),t=t.subarray(Re.ENC_488)}switch(s){case je.PING:this.pong();break;case je.PONG:break;case je.CID_REQ:this.state<De.SENT_SERVER_READY&&this.close(),this.cid||(this.cid="?"+e.webcrypto.getRandomValues(Buffer.alloc(3)).toString("base64url"),this.manager.cid2remote.set(this.cid,this)),this.send_enc_mode(te(Ms("#cid_ack","8",je.CID_RES),Ms("#cid",this.cid))),this.setState(De.CID_READY);break;case je.ECHO:try{let e=Us.decode(t.subarray(1));this.lastEchoMessage=e}catch(e){}this.send(t,r);break;case je.IAM:if(t.byteLength>1){let e=t.subarray(1);this.nick=Us.decode(e),console.log("iam nick reset",this.nick)}this.iamResponse();break;case je.SIGNAL_E2E:case je.SIGNAL:if(t.byteLength>=3){let e=t.readUInt8(1);if(t.byteLength>=e+2){let r=t.subarray(2,2+e);r=Us.decode(r),this.manager.sender(r,this,t)}}break;case je.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=Us.decode(r);let s=r.split(",");this.manager.unsubscribe(s,this)}}break;case je.SUBSCRIBE:if(t.byteLength>=3){let e=t.readUInt8(1);if(t.byteLength==e+2){let r=t.subarray(2,2+e);r=Us.decode(r);let s=r.split(",");this.manager.subscribe(s,this)}}break;case je.SUBSCRIBE_REQ:if(t.byteLength>=6){let e=t.readUInt16BE(1),r=t.readUInt16BE(3);if(t.byteLength==r+5){let s=t.subarray(5,5+r);s=Us.decode(s);let i=s.split(",");this.manager.subscribe(i,this),this.response(e,0)}else this.response(e,255)}break;case je.REQUEST:try{let e=re(t);if(e){if(!e.target||!e.topic)return;this.manager.server.apiNames.has(e.target)?this.manager.server.emit(e.target,this,e):console.log("UnKnown API req: ",e.target)}}catch(e){console.log("request catch error",e)}break;case je.CLOSE:if(t.byteLength>1){let e=Us.decode(t.subarray(1));console.log(">> CLOSE reason:",e),this.close()}break;case Ce.AUTH_REQ:if(!this.manager.authManager)return;this.state<De.SENT_SERVER_READY&&this.close(),this.setState(De.RECV_AUTH_REQ);let s=this.boho.auth_nonce();this.send(s),this.setState(De.SENT_SERVER_NONCE);break;case Ce.AUTH_HMAC:if(!this.manager.authManager)return;return this.state<De.SENT_SERVER_NONCE&&this.close(),this.setState(De.RECV_AUTH_HMAC),void this.manager.authManager.verify_auth_hmac(t,this).then((e=>{e&&this.manager.deligateSignal(remote,"@$name",e.name)})).catch((e=>{}))}}else try{let e=Us.decode(t);this.manager.server.emit("text_message",e,this)}catch(e){}}response(e,t,r){r?this.send_enc_mode(te(Ms("#type","8",je.RESPONSE_MBP),Ms("status","8",t),Ms("mid","16",e),Ms("body",r))):this.send_enc_mode(te(Ms("#type","8",je.RESPONSE_MBP),Ms("status","8",t),Ms("mid","16",e)))}send_enc_mode(e,t=!1){if((this.encMode===He.YES||this.encMode===He.AUTO&&!this.TLS&&this.boho.isAuthorized)&&(t=!0),t&&e[0]==je.SIGNAL_E2E){let t=e[1],r=this.boho.encrypt_488(e.subarray(0,3+t));r[0]=Ce.ENC_E2E;let s=Buffer.concat([r,e.subarray(3+t)]);this.send(s)}else if(t){let t=this.boho.encrypt_488(e);t?this.send(t):console.log("encryption FAIL: NO DATA TRANSIT")}else this.send(e)}iamResponse(e=""){if(""==e){let t=[];for(let e of this.channels.keys())t.push(e);e={ssid:this.ssid,uid:this.uid,cid:this.cid,did:this.did,nick:this.nick,ip:this.ip,tag:t}}let t=te(Ms("#MsgType","8",je.IAM_RES),Ms("#info",e));this.send_enc_mode(t)}}const Ds=new TextDecoder;class Hs extends Ps{constructor(e,t,r){super(e,r),this.socketType=e.socketType,"websocket"===this.socketType?(this.TLS="https"===t.headers["x-forwarded-proto"],this.ip=this.getRemoteIP(t)):(this.TLS=!1,this.ip=this.getRemoteIP(e.remoteAddress)),!function(e){if(0===e.indexOf("0.0.0.0"))return!0;if(0===e.indexOf("127.0.0.1"))return!0;if(0===e.indexOf("192.168."))return!0;if(0===e.indexOf("10."))return!0;if(0===e.indexOf("172.")){if(0===e.indexOf("172.16."))return!0;if(0===e.indexOf("172.17."))return!0;if(0===e.indexOf("172.18."))return!0;if(0===e.indexOf("172.19."))return!0;if(0===e.indexOf("172.20."))return!0;if(0===e.indexOf("172.21."))return!0;if(0===e.indexOf("172.22."))return!0;if(0===e.indexOf("172.23."))return!0;if(0===e.indexOf("172.24."))return!0;if(0===e.indexOf("172.25."))return!0;if(0===e.indexOf("172.26."))return!0;if(0===e.indexOf("172.27."))return!0;if(0===e.indexOf("172.28."))return!0;if(0===e.indexOf("172.29."))return!0;if(0===e.indexOf("172.30."))return!0;if(0===e.indexOf("172.31."))return!0}return!1}(this.ip)?this.HOME_CHANNEL="IP:"+function(e){let t=e.split(".");return Buffer.from(t).toString("hex")}(this.ip):(this.HOME_CHANNEL="PRIVATE:",this.privateNode=!0),"websocket"===this.socketType?(Ns.debug.slow?e.on("message",this.onTimeDelayMessage.bind(this)):e.on("message",this.onSocketMessage.bind(this)),e.on("pong",this.receiveMonitor.bind(this)),e.on("ping",this.receiveMonitor.bind(this)),e.on("error",(e=>{console.log("Websocket error",e,e.code)})),e.onclose=e=>{this.manager.removeRemote(this)}):(this.congRx=new et,e.on("data",(e=>{this.congRx.write(e)})),this.congRx.on("wrong",this.onWrongCongPacketMessage.bind(this)),Ns.debug.slow?this.congRx.on("data",this.onTimeDelayMessage.bind(this)):this.congRx.on("data",this.onSocketMessage.bind(this)),e.on("error",(e=>{console.log("TCP Socket error",e)})),e.on("close",(e=>{this.manager.removeRemote(this)})))}onWrongCongPacketMessage(e){if(this.cid)console.log("wrong congpack from user:",Date(),this.ip,this.ssid,this.cid);else{let t="";try{t=Ds.decode(e)}catch(r){t+="Len: "+e.byteLength}if(this.manager.attackLogger){let e=`> ${this.ssid} ${this.ip} ${t}`;this.manager.attackLogger.log(e)}this.close(!0)}}permissionChecker(){this.socket.bytesWritten||this.socket._socket,this.socket.bytesRead||this.socket._socket}receiveMonitor(){this.socket.rxCounter++,this.socket.isAlive=!0}isConnectionHTTPS(e){return e.headers["x-forwarded-proto"]}getRemoteIP(e){let t;return e&&e.headers?(t=e.headers["x-forwarded-for"],null==t&&(t=e.socket.remoteAddress)):t=e,t?(0==t.indexOf("::ffff:")&&(t=t.substring(7)),"::1"==t&&(t="127.0.0.1")):t="0.0.0.0",t}ping(){"websocket"===this.socketType?(this.socket.ping(),this.socket.txCounter++):this.send(Buffer.from([je.PING]))}pong(){"websocket"===this.socketType?(this.socket.pong(),this.socket.txCounter++):this.send(Buffer.from([je.PONG]))}getTraffic(){this.socket.bytesWritten||this.socket._socket,this.socket.bytesRead||this.socket._socket,this.socket.txCounter,this.socket.rxCounter}close(e=!1){this.getTraffic(),"websocket"===this.socketType?e?this.socket.terminate():this.socket.close():e?this.socket.destroy():this.socket.end()}send(e,t){this.manager.txBytes+=e.byteLength,this.socket.txCounter++,"websocket"===this.socketType?1===this.socket.readyState?null!=t?this.socket.send(e,{binary:t}):this.socket.send(e):this.close(!0):"open"==this.socket.readyState?this.socket.write(Ze(e)):this.close(!0)}}const $s=new Intl.DateTimeFormat("ko-KR",{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1,timeZone:"Asia/Seoul"});class Fs{constructor(e){this.file=E.default.openSync(e,"a+"),console.log("new logFile",e,this.file)}log(e){let t=$s.format(new Date)+" "+e+"\n";E.default.write(this.file,t,(e=>{if(e)throw e}))}}class js{constructor(e){this.manager=e,this.metricsPack={remotes:[0],channels:[0],txBytes:[0],rxBytes:[0],unixTime:[Math.floor(Date.now()/1e3)],period:0},this.tickId=setInterval((e=>{this.metricsPack.remotes.push(this.manager.remotes.size),this.metricsPack.remotes.length>10&&this.metricsPack.remotes.shift(),this.metricsPack.channels.push(this.manager.channel_map.size),this.metricsPack.channels.length>10&&this.metricsPack.channels.shift(),this.metricsPack.txBytes.push(this.manager.txBytes),this.metricsPack.txBytes.length>10&&this.metricsPack.txBytes.shift(),this.metricsPack.rxBytes.push(this.manager.rxBytes),this.metricsPack.rxBytes.length>10&&this.metricsPack.rxBytes.shift(),this.metricsPack.unixTime=Math.floor(Date.now()/1e3),this.metricsPack.period=1e4,this.manager.txBytes=0,this.manager.rxBytes=0}),1e4)}oneline(e){let t=[{...d.memoryUsage()}];e&&console.table(t,["rss","heapTotal","heapUsed","external","arrayBuffers"]);let r=[{lastSSID:this.manager.lastSSID,remotes:this.manager.remotes.size,channels:this.manager.channel_map.size,txBytes:this.manager.txBytes,rxBytes:this.manager.rxBytes}];return e&&console.table(r,["lastSSID","remotes","channels","txBytes","rxBytes"]),r[0]}getRemotes(e){let t=Array.from(this.manager.remotes.values()).map((e=>"#"+e.ssid+":"+e.cid+"("+e.state+")"));return e&&console.table(t),t}getCIdList(e){let t=Array.from(this.manager.cid2remote.keys());return e&&console.table(t),t}getChannelList(e){let t=Array.from(this.manager.channel_map.keys());return e&&console.table(t),t}getSubscribers(e){let t=[];if(this.manager.channel_map.has(e)){this.manager.channel_map.get(e).forEach((e=>{t.push(e.cid)}))}return t}getRemoteByCId(e,t=1){if(!this.manager.cid2remote.has(e))return{result:"nop"};{let r=this.manager.cid2remote.get(e);if(1==t)return{ip:r.ip,id:r.cid,ssid:r.ssid,cid:r.cid,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==t)return{ip:r.ip,uptime:Math.trunc((Date.now()-r.socket.openTime)/1e3),nick:r.nick,ssid:r.ssid,echo:r.lastEchoMessage};if(3==t)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:He[r.encMode]};if(4==t){let e=Array.from(r.channels.keys()),t=Array.from(r.memory.keys()),s=Array.from(r.retain_signal.keys());return{ip:r.ip,uptime:Math.trunc((Date.now()-r.socket.openTime)/1e3),channels:e,set:t,retain:s}}}}}const zs=new TextEncoder,Ws=new TextDecoder;class Gs{constructor(e,t){this.server=e,this.txBytes=0,this.rxBytes=0,this.authManager=t,this.connectionLogger,Ns.fileLogger.connection.use&&(this.connectionLogger=new Fs(Ns.fileLogger.connection.path),console.log("Manager: begin file logger [connection]")),this.attackLogger,Ns.fileLogger.attack.use&&(this.attackLogger=new Fs(Ns.fileLogger.attack.path),console.log("Manager: begin file logger.[attack]")),this.remotes=new Set,this.channel_map=new Map,this.CHANNEL_PREFIX="CH:",this.CID_PREFIX="CID:",this.cid2remote=new Map,this.retain_messages=new Map,this.metric=new js(this),this.lastSSID=0,this.pingIntervalID=setInterval((e=>{this.remotes.forEach((function(e){let t=e.socket;!1===t.isAlive&&(console.log("## timeout. cid:",e.cid),e.close()),t.txCounter++,t.isAlive=!1,"websocket"===e.socketType?t.ping():e.ping()}))}),Ns.timeout),Ns.showMetric&&(this.monitIntervalID=setInterval((e=>{this.monitor()}),Ns.monitorPeriod))}addRemote(e,t){e.isAlive=!0;let r=new Hs(e,t,this);this.remotes.add(r),r.send(Buffer.from([je.SERVER_READY])),r.setState(De.SENT_SERVER_READY),this.lastSSID=r.ssid;let s=`+ IP:${r.ip} #${r.ssid} ${"websocket"===e.socketType?"WS":"CS"} `;this.connectionLogger&&this.connectionLogger.log(s)}removeRemote(e){let t=`- IP:${e.ip} #${e.ssid} cid:${e.cid} ${"websocket"===e?.socket.socketType?"WS":"CS"} `;this.connectionLogger&&this.connectionLogger.log(t),this.deligateSignal(e,"@state","close"),this.deligateSignal(e,"@$state","close");for(let t of e.channels.keys())if(this.channel_map.has(t)){const r=this.channel_map.get(t);r.delete(e),0==r.size&&this.channel_map.delete(t)}if(e.boho.isAuthorized);else for(let t of e.retain_signal.keys())t=this.CID_PREFIX+e.cid+"@"+t,this.channel_map.has(t)&&this.channel_map.delete(t);if(e.uid&&this.server.apiNames.has("account")){let t={topic:"detachUserRemote",args:["caller:manager.removeRemote"]};this.server.emit("account",e,t)}this.remotes.delete(e),this.cid2remote.delete(e.cid),e=null}serverSignal(e){let t=te(Q("#MsgType","8",je.SERVER_SIGNAL),Q("#signalObject",e));this.remotes.forEach((e=>{e.send_enc_mode(t)}))}getSignalTag(e){let t=e.readUint8(1),r=e.subarray(2,2+t);return Ws.decode(r)}getNewSignalTagMessage(e,t){let r=e[0],s=e.readUint8(1),i=zs.encode(t),n=i.byteLength,o=e.subarray(2+s);return Buffer.concat([Buffer.from([r,n]),i,o])}deligateSignal(e,t,...r){let s=Ge(t,...r);this.sender(t,e,s)}adminSignal(e,t){return this.cid2remote.has(e)?void this.cid2remote.get(e).send_enc_mode(t):"no cid"}serverSignalTo(e,...t){let r=e.split("@")[0],s=Ge("@"+e.split("@")[1],...t);if(r&&this.cid2remote.has(r)){let e=this.cid2remote.get(r);return console.log("target",e.state,e.cid),void e.send_enc_mode(s)}return"no cid"}sender(e,t,r){if(Ns.memberOnly&&!t.boho.isAuthorized)return t.send(Buffer.from([je.SERVER_CLEAR_AUTH])),t.close(),["err","not autrized"];if(0==e.indexOf("$"))return["err","prefix $ is reserved for userSet tag."];let s=e.indexOf("@");if(0===s)e=t.cid+e,r=this.getNewSignalTagMessage(r,e);else if(s>0){let t=e.split("@")[0];if(this.cid2remote.has(t)){let s="@"+e.split("@")[1];return r=this.getNewSignalTagMessage(r,s),this.cid2remote.get(t).send_enc_mode(r),["ok",1]}return["err","Invalid cid"]}if((e=0===e.indexOf("#")?t.HOME_CHANNEL+e:e.includes("@")?this.CID_PREFIX+e:this.CHANNEL_PREFIX+e).includes("$")&&Ns.retain.isAvailable&&Ns.retain.limitCounter>this.retain_messages.size&&Ns.retain.limitSize>r.byteLength)if(e.includes("@")){let s=e.split("@")[1];t.retain_signal.set(s,r)}else this.retain_messages.set(e,r);let i=0;if(this.channel_map.has(e)){let s=this.channel_map.get(e);if(s.size>=1){let e;e=Ns.useQuota.publishCounter?Math.min(t.quota.publishCounter,s.size):s.size;let n=s.values();for(;i<e;){let e=n.next().value;if(!e)break;e!==t&&(e.send_enc_mode(r),i++)}return Ns.useQuota.publishCounter,["ok",i]}}return["err","No subscriber."]}subscribe(e,t){return e.forEach((e=>{if(e=0===e.indexOf("#")?t.HOME_CHANNEL+e:e.includes("@")?this.CID_PREFIX+e:this.CHANNEL_PREFIX+e,this.channel_map.has(e)?this.channel_map.get(e).add(t):this.channel_map.set(e,new Set([t])),t.channels.add(e),e.includes("$")&&Ns.retain.isAvailable){let r;if(e.includes("@")){let t=e.split("@")[0];t=t.split(this.CID_PREFIX)[1];let s=e.split("@")[1];if(!this.cid2remote.has(t))return;r=this.cid2remote.get(t).retain_signal.get(s)}else this.retain_messages.has(e)&&(r=this.retain_messages.get(e));r&&t.send_enc_mode(r)}})),t.channels.size}unsubscribe(e,t){1==e.length&&""==e[0]?(t.channels.forEach((e=>{if(this.channel_map.has(e)){let r=this.channel_map.get(e);r.delete(t),0==r.size&&this.channel_map.delete(e)}})),t.channels.clear()):e.forEach((e=>{if(e=0===e.indexOf("#")?t.HOME_CHANNEL+e:e.includes("@")?this.CID_PREFIX+e:this.CHANNEL_PREFIX+e,this.channel_map.has(e)){let r=this.channel_map.get(e);r.delete(t),0==r.size&&this.channel_map.delete(e)}t.channels.delete(e)}))}monitor(){process.stdout.isTTY&&(process.stdout.cursorTo(0,0),process.stdout.clearScreenDown()),Ns.showChannel>0&&this.metric.channels(Ns.showChannel);let e=parseInt(Ns.showMetric);switch(console.log("monitor metric type:",e),e){case 1:this.metric.oneline(!0);break;case 2:this.metric.getRemotes(!0);break;case 3:this.metric.getChannelList(!0)}}closeRemoteByCId(e){return this.cid2remote.has(e)?(this.cid2remote.get(e).close(),1):0}}const Vs=0,qs=255;class Ys extends k.default{constructor(e,t){if(super(),this.apiNames=new Set,this.wss={},e.timeout){let t=parseInt(e.timeout);t&&t>=1e3&&(Ns.timeout=t)}if(e.monitorPeriod){let t=parseInt(e.monitorPeriod);t&&t>=1e3&&(Ns.monitorPeriod=t)}e.showMessage&&(Ns.showMessage=e.showMessage),e.showMetric&&(Ns.showMetric=e.showMetric),e.timeout&&(Ns.timeout=e.timeout),e.port&&(Ns.port=parseInt(e.port)),e.httpServer&&(Ns.httpServer=e.httpServer),e.congPort&&(Ns.congPort=parseInt(e.congPort)),this.manager=new Gs(this,t),(Ns.port||Ns.httpServer)&&this.startWSServer(Ns),Ns.congPort&&this.startCongServer(Ns.congPort)}startWSServer(e){if(e.port)console.log("opening WebSocket Server port:",e.port),this.wss=new Bs({port:e.port});else{if(!e.httpServer)throw new TypeError('One and only one of the "port", "httpServer"must be specified');console.log("opening WebSocket Server external httpServer:"),this.wss=new Bs({server:e.httpServer})}this.wss.on("error",(e=>{console.error("### ws server error:",e.message),"EADDRINUSE"==e.code&&process.exit()})),this.wss.on("close",(e=>{console.log("### WS server closed.",e)})),this.wss.on("connection",((e,t)=>{e.socketType="websocket",this.manager.addRemote(e,t)}))}startCongServer(e){console.log("opening CongSocket Server:",e),this.congServer=m.default.createServer((e=>{this.manager.addRemote(e)})).on("error",(e=>{console.log("### cong server error:",e.message),"EADDRINUSE"==e.code&&process.exit()})).listen(e,(()=>{}))}api(e,t){if(this.apiNames.add(e),!t.checkPermission||"function"!=typeof t.checkPermission)throw new Error("wrong api interface. no checkPermission function.");if("function"==typeof t.request&&Array.isArray(t.commands))console.log(`API TYPE1. A Class with one request function. target: ${e} list: ${t.commands}`),this.on(e,((e,r)=>{t.checkPermission(e,r)?t.request(e,r):e.response(r.mid,qs,"NO_PERMISSION.")}));else{let r=[];Object.keys(t).forEach((e=>{"function"==typeof t[e]&&r.push(e),console.log("api list",typeof t[e],e)})),console.log(`API TYPE2. Multiple function list. target: ${e} list:${r}`),this.on(e,((r,s)=>{let i;if(t.checkPermission(r,s)){if(t[s.topic])return console.log(`API TYPE2. request target: ${e} has topic:${s.topic}`),void t[s.topic](r,s);i=`target: ${s.target} has not topic name: ${s.topic}`}else i="NO_PERMISSION.";r.response(s.mid,qs,i)}))}return this}}const Qs=new TextDecoder;class Ks{constructor(){this.authLogger,Ns.fileLogger.auth.use&&(this.authLogger=new Fs(Ns.fileLogger.auth.path),console.log("Auth: begin file logger.[auth]"))}send_auth_fail(e,t){if(this.authLogger){let r=`FAIL #${e.ssid} reason:${t} `;this.authLogger.log(r)}console.log("## AUTH_FAIL reason:",t),e.setState(De.AUTH_FAIL),setTimeout((t=>{e.send(Buffer.from([Ce.AUTH_FAIL]))}),Ns.auth.delay_auth_fail)}async verify_auth_hmac(e,t){try{let r=re(e,Ie.AUTH_HMAC);if(!r)return void this.send_auth_fail(t,"unpack auth_pack fail");let s="";s=r.id8.includes(0)?Qs.decode(r.id8.subarray(0,r.id8.indexOf(0))):Qs.decode(r.id8);let i,n=await this.getAuth(s);if(Ns.debug.showAuthInfo,!n)return void this.send_auth_fail(t,"NO ID:"+s);t.boho.copy_id8(r.id8);const o=44;n.key.length==o?(i=Buffer.from(n.key,"base64"),t.boho.copy_key(i)):t.boho.set_key(n.key);let a=t.boho.check_auth_hmac(r);if(!a)return void this.send_auth_fail(t,"hmac dismatched");if(t.manager.cid2remote.has(n.cid)){let e=t.manager.cid2remote.get(n.cid);return e==t?void console.log("## trying RELOGIN with SAME ID. ignored."):(console.log("### clear_auth and close old connection:",e.cid),e.send(Buffer.from([je.SERVER_CLEAR_AUTH])),e.close(),void t.close())}t.cid&&t.manager.cid2remote.delete(t.cid),t.did=s,t.cid=n.cid,t.nick=n.cid;let h=Ns.defaultQuotaIndex;n.level&&(h=n.level),h=parseInt(h);let c=ze[h];if(!c){let e="no index quotaTable for auth.level: "+h;return console.log("##AUTH:DATA ERROR##",e),void this.send_auth_fail(t,e)}if(t.level=h,t.quota=c,t.level===Ns.adminLevel&&(console.log("## LOGIN ADMIN CID:",t.cid),t.isAdmin=!0),t.send(Buffer.from([je.QUOTA_LEVEL,h])),t.manager.cid2remote.set(t.cid,t),t.send(a),t.setState(De.AUTH_READY),this.authLogger){let e=`OK #${t.ssid} cid: ${t.cid} did:${t.did}`;t.isAdmin&&(e="#ADMIN# "+e),this.authLogger.log(e)}return n}catch(e){this.send_auth_fail(t,"caught: unknown error"+e)}}}const Js="device:";var Xs=Object.freeze({__proto__:null,checkPermission:function(e){return e.level>=0},echo:async function(e,t){t.args?e.response(t.mid,Vs,t.args):e.response(t.mid,qs,"no message to echo")},date:async function(e,t){let r=(new Date).toUTCString();e.response(t.mid,Vs,r)},unixtime:async function(e,t){let r=Math.floor(Date.now()/1e3);e.response(t.mid,Vs,r)}});var Zs=Object.freeze({__proto__:null,commands:["cid","remotes","clients","channels","subscribers","remote","client","close","addauth","getauth","delauth","getauthidlist","getdevicelist","adddevice","getdevice","deldevice"],checkPermission:function(e){return e.level>=255},request:async function(e,t){let r,s=0;try{let i=t.topic;if(i=i.toLowerCase(),"cid"==i)r=e.manager.metric.getCIdList();else if("remotes"==i||"clients"==i)r=e.manager.metric.getRemotes();else if("channels"==i)r=e.manager.metric.getChannelList();else if("subscribers"==i){let s=t.$[0];s&&(r=e.manager.metric.getSubscribers(s))}else if("remote"==i||"client"==i){let s=t.$[0],i=t.$[1];s&&(r=e.manager.metric.getRemoteByCId(s,i))}else if("close"==i)t.$[0]&&(r=e.manager.closeRemoteByCId(t.$[0]));else if("addauth"==i||"adddevice"==i){if(e.manager.authManager&&4==t.$.length&&e.manager.authManager.addAuth){let s=t.$[0],i=t.$[1],n=t.$[2],o=t.$[3];r=await e.manager.authManager.addAuth(s,i,n,o)}}else if("delauth"==i||"deldevice"==i){if(e.manager.authManager&&1==t.$.length&&e.manager.authManager.delAuth){let s=t.$[0];r=await e.manager.authManager.delAuth(s)}}else if("getauth"==i||"getdevice"==i){if(e.manager.authManager&&1==t.$.length&&e.manager.authManager.getAuth){let s=t.$[0];r=await e.manager.authManager.getAuth(s)}}else"getauthidlist"==i||"getdevicelist"==i?e.manager.authManager&&e.manager.authManager.getAuthIdList&&(r=await e.manager.authManager.getAuthIdList()):(s=qs,r="api sudo: no such a cmd: "+i);e.response(t.mid,s,r)}catch(r){e.response(t.mid,qs,r.message)}}});const ei=["GET","SET","HGETALL","HGET","HSET","SADD","SISMEMBER","SMEMBERS","EXISTS","SREM","DEL","KEYS","SAVE"];exports.API_TYPE={REQUEST_RESPONSE:"requet_response",ONE_WAY:"one_way"},exports.Auth_Env=class extends Ks{constructor(e){let t;super(),e?t=e.split(","):process.env.BOHO_AUTH?(e=process.env.BOHO_AUTH,t=process.env.BOHO_AUTH.split(",")):(console.log("Auth_Env: None of process.env.BOHO_AUTH or authInfo"),process.exit()),this.AUTH=new Map,t.length>=1?t.forEach((e=>{let t=e.split(".")[0],r=e.split(".")[1],s=e.split(".")[2];if(s=parseInt(s),t&&r&&"number"==typeof s){let e=t;this.addAuth(t,r,e,s)}else console.log("Wrong process.env.BOHO_AUTH authentication value.",id,r,s),process.exit()})):(console.log("Wrong process.env.BOHO_AUTH authentication value."),process.exit())}async getAuth(e){return this.AUTH.get(e)}async getAuthIdList(){return Array.from(this.AUTH.keys())}addAuth(e,t,r,s=0){let i=Buffer.from(xe.hash(t)).toString("base64");this.AUTH.set(e,{key:i,cid:r,level:s})}},exports.Auth_File=class extends Ks{constructor(e){super(),this.AUTH=new Map;let t=w.default.parse(e);this.path=w.default.resolve(e),console.log("auth from file path:",this.path);let r=t.ext;".js"==r.toLowerCase()||".mjs"==r.toLowerCase()?(console.log("#JS path:",this.path),this.loadAuthInfoFile_JS(this.path)):".json"==r.toLowerCase()?(console.log("#JSON path:",this.path),this.loadAuthInfoFile_JSON(this.path)):console.log("no authinfofile path.")}async getAuth(e){return this.AUTH.get(e)}async getAuthIdList(){return Array.from(this.AUTH.keys())}loadAuthInfoFile_JS(e){var t;(t=e,Promise.resolve().then((function(){return g(require(t))}))).then((e=>{console.log(e.authInfo),e.authInfo.forEach((e=>{this.addAuth(...e)})),console.log("total AUTH INFO size: ",this.AUTH.size)})).catch((e=>{console.log(e)}))}loadAuthInfoFile_JSON(e){let t=i.readFileSync(e);t=(new TextDecoder).decode(t),JSON.parse(t).forEach((e=>{this.addAuth(...e)})),console.log("total AUTH INFO size: ",this.AUTH.size)}addAuth(e,t,r,s=0){let i=Buffer.from(xe.hash(t)).toString("base64");this.AUTH.set(e,{key:i,cid:r,level:s})}},exports.Auth_Redis=class extends Ks{constructor(e){if(super(),!e)throw new Error("AuthRedis constructor: no redisClient");this.redis=e}async getAuth(e){let t=await this.redis.hGetAll(Js+e);if(t.key)return t}async getAuthIdList(){let e=await this.redis.keys(Js+"*");if(e=e.map((e=>e.split(":")[1])),e)return e}async addAuth(e,t,r="",s=0){let i=Buffer.from(xe.hash(t)).toString("base64");return this.redis.hSet(Js+e,{key:i,cid:r,level:s})}async delAuth(e){return this.redis.del(Js+e)}async save(e){return this.redis.save()}},exports.Boho=Me,exports.BohoAuth=Ks,exports.BohoMsg=Ce,exports.Buffer=W.Buffer,exports.CLIENT_STATE=De,exports.CongRx=et,exports.ENC_MODE=He,exports.FileLogger=Fs,exports.IO=class extends Ye{constructor(e){super(e),e&&this.open()}close(){this.socket&&(this.socket.onclose=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.close(),this.socket=null),this.emit("close")}stop(){this.close(),clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null}keepAlive(){this.socket&&3!==this.socket?.readyState||this.open()}createConnection(e){this.socket=new ss(e),this.stateChange("opening"),this.socket.onopen=()=>{this.socket.on("message",this.onWebSocketMessage.bind(this)),this.emit("open")},this.socket.onerror=e=>{this.emit("error",e)},this.socket.onclose=()=>{this.emit("close")}}onWebSocketMessage(e){this.rxCounter++,this.lastTxRxTime=Date.now(),this.rxBytes+=e.byteLength,this.emit("socket_data",e)}socket_send(e){1===this.socket?.readyState?(this.socket.send(e),this.txCounter++,this.txBytes+=e.byteLength,this.lastTxRxTime=Date.now()):console.log("")}},exports.IOCongSocket=class extends Ye{constructor(e){super(e),e&&this.open()}close(){this.socket?.end(),this.socket=null}stop(){this.close(),clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null}keepAlive(){let e=this.socket?.readyState;(!this.socket||"open"!==e&&"opening"!==e)&&this.open()}createConnection(e){let t=new URL(e);"cong:"!=t.protocol&&(t=new URL("cong://"+e)),this.socket=m.default.createConnection(t.port,t.hostname),this.stateChange("opening"),this.socket.on("connect",(()=>{this.congRx=new et,this.socket.pipe(this.congRx),this.congRx.on("data",this.onTCPSocketMessage.bind(this)),this.emit("open")})),this.socket.on("error",(e=>{this.emit("error",e)})),this.socket.on("close",(()=>{this.emit("close")}))}onTCPSocketMessage(e){this.rxCounter++,this.rxBytes+=e.byteLength,this.lastTxRxTime=Date.now(),this.emit("socket_data",e)}socket_send(e){if("open"===this.socket?.readyState){let t=Ze(e);this.socket.write(t),this.txCounter++,this.txBytes+=t.byteLength,this.lastTxRxTime=Date.now()}else console.log(".")}},exports.IOMsg=je,exports.MBP=we,exports.Meta=Ie,exports.MetaSize=Re,exports.PAYLOAD_TYPE=Fe,exports.RAND=Ue,exports.RedisAPI=class{constructor(e,t){if(!e)throw new Error("RedisAPI constructor: no redisClient");this.redisClient=e,this.minLevel=t||200,this.commands=ei}checkPermission(e,t){return console.log("checkPermission",e.level,"vs",this.minLevel),e.level>=this.minLevel}async request(e,t){let r,s=Vs;try{let i=t.topic;i=i.toUpperCase(),ei.includes(i)?(console.log("RedisAPI call:",i,t.args),r=t.args.length>0?await this.redisClient[i](...t.args):await this.redisClient[i]()):s=qs,e.response(t.mid,s,r)}catch(r){e.response(t.mid,qs,r.message)}}},exports.SIZE_LIMIT=$e,exports.STATES=Pe,exports.STATUS={OK:0,ERROR:255},exports.Server=Ys,exports.api_reply=Xs,exports.api_sudo=Zs,exports.pack=Ze,exports.serverOption=Ns,exports.sha256=xe;
|