rtsp2web 2.1.0 → 2.2.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.
@@ -1,9 +1,9 @@
1
1
  /*!
2
- * rtsp2web v2.1.0
2
+ * rtsp2web v2.2.0
3
3
  * (c) 2020-2022 NeverYu
4
4
  * Released under the ISC License.
5
5
  */
6
6
  "use strict";var e=require("events"),t=require("https"),r=require("http"),s=require("net"),i=require("tls"),n=require("crypto"),o=require("stream"),a=require("url"),c=require("zlib");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=h(e),f=h(t),d=h(r),u=h(s),_=h(i),p=h(n),m=h(o),y=h(a),g=h(c);function v(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function b(e,t){for(var r=0;r<t.length;r++){var s=t[r];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function S(e,t,r){return t&&b(e.prototype,t),r&&b(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function w(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function k(e){return k=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},k(e)}function x(e,t){return x=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},x(e,t)}function E(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function O(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return E(e)}function C(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,s=k(e);if(t){var i=k(this).constructor;r=Reflect.construct(s,arguments,i)}else r=s.apply(this,arguments);return O(this,r)}}function T(e){return function(e){if(Array.isArray(e))return L(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||N(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function N(e,t){if(e){if("string"==typeof e)return L(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?L(e,t):void 0}}function L(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,s=new Array(t);r<t;r++)s[r]=e[r];return s}function P(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=N(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var s=0,i=function(){};return{s:i,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,o=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,n=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw n}}}}var R="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},B={exports:{}};
7
7
  /*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */
8
- !function(e,t){!function(r){var s=t,i=e&&e.exports==s&&e,n="object"==typeof R&&R;n.global!==n&&n.window!==n||(r=n);var o=function(e){this.message=e};(o.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new o(e)},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=/[\t\n\f\r ]/g,l={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,s,i,n=e.length%3,o="",h=-1,l=e.length-n;++h<l;)t=e.charCodeAt(h)<<16,r=e.charCodeAt(++h)<<8,s=e.charCodeAt(++h),o+=c.charAt((i=t+r+s)>>18&63)+c.charAt(i>>12&63)+c.charAt(i>>6&63)+c.charAt(63&i);return 2==n?(t=e.charCodeAt(h)<<8,r=e.charCodeAt(++h),o+=c.charAt((i=t+r)>>10)+c.charAt(i>>4&63)+c.charAt(i<<2&63)+"="):1==n&&(i=e.charCodeAt(h),o+=c.charAt(i>>2)+c.charAt(i<<4&63)+"=="),o},decode:function(e){var t=(e=String(e).replace(h,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,s,i=0,n="",o=-1;++o<t;)s=c.indexOf(e.charAt(o)),r=i%4?64*r+s:s,i++%4&&(n+=String.fromCharCode(255&r>>(-2*i&6)));return n},version:"1.0.0"};if(s&&!s.nodeType)if(i)i.exports=l;else for(var f in l)l.hasOwnProperty(f)&&(s[f]=l[f]);else r.base64=l}(R)}(B,B.exports);var A={exports:{}},U={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:()=>{}};const{EMPTY_BUFFER:I}=U;function M(e,t){if(0===e.length)return I;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const i=e[t];r.set(i,s),s+=i.length}return s<t?r.slice(0,s):r}function W(e,t,r,s,i){for(let n=0;n<i;n++)r[s+n]=e[n]^t[3&n]}function D(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}function F(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function j(e){if(j.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=Buffer.from(e):ArrayBuffer.isView(e)?t=Buffer.from(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),j.readOnly=!1),t}try{const e=require("bufferutil");A.exports={concat:M,mask(t,r,s,i,n){n<48?W(t,r,s,i,n):e.mask(t,r,s,i,n)},toArrayBuffer:F,toBuffer:j,unmask(t,r){t.length<32?D(t,r):e.unmask(t,r)}}}catch(e){A.exports={concat:M,mask:W,toArrayBuffer:F,toBuffer:j,unmask:D}}const $=Symbol("kDone"),G=Symbol("kRun");var V=class{constructor(e){this[$]=()=>{this.pending--,this[G]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[G]()}[G](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[$])}}};const q=g.default,z=A.exports,H=V,{kStatusCode:Y}=U,X=Buffer.from([0,0,255,255]),Z=Symbol("permessage-deflate"),K=Symbol("total-length"),J=Symbol("callback"),Q=Symbol("buffers"),ee=Symbol("error");let te;var re=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,!te){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;te=new H(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[J];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){te.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){te.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]?q.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=q.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Z]=this,this._inflate[K]=0,this._inflate[Q]=[],this._inflate.on("error",ne),this._inflate.on("data",ie)}this._inflate[J]=r,this._inflate.write(e),t&&this._inflate.write(X),this._inflate.flush((()=>{const e=this._inflate[ee];if(e)return this._inflate.close(),this._inflate=null,void r(e);const i=z.concat(this._inflate[Q],this._inflate[K]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[K]=0,this._inflate[Q]=[],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]?q.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=q.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[K]=0,this._deflate[Q]=[],this._deflate.on("data",se)}this._deflate[J]=r,this._deflate.write(e),this._deflate.flush(q.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=z.concat(this._deflate[Q],this._deflate[K]);t&&(e=e.slice(0,e.length-4)),this._deflate[J]=null,this._deflate[K]=0,this._deflate[Q]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function se(e){this[Q].push(e),this[K]+=e.length}function ie(e){this[K]+=e.length,this[Z]._maxPayload<1||this[K]<=this[Z]._maxPayload?this[Q].push(e):(this[ee]=new RangeError("Max payload size exceeded"),this[ee].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ee][Y]=1009,this.removeListener("data",ie),this.reset())}function ne(e){this[Z]._inflate=null,e[Y]=1007,this[J](e)}var oe={exports:{}};const ae=[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];function ce(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999}function he(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}try{const e=require("utf-8-validate");oe.exports={isValidStatusCode:ce,isValidUTF8:t=>t.length<150?he(t):e(t),tokenChars:ae}}catch(e){oe.exports={isValidStatusCode:ce,isValidUTF8:he,tokenChars:ae}}const{Writable:le}=m.default,fe=re,{BINARY_TYPES:de,EMPTY_BUFFER:ue,kStatusCode:_e,kWebSocket:pe}=U,{concat:me,toArrayBuffer:ye,unmask:ge}=A.exports,{isValidStatusCode:ve,isValidUTF8:be}=oe.exports;var Se=class extends le{constructor(e={}){super(),this._binaryType=e.binaryType||de[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[pe]=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._state=0,this._loop=!1}_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]=t.slice(e),t.slice(0,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]=r.slice(e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,we(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[fe.extensionName])return this._loop=!1,we(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,we(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,we(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 this._loop=!1,we(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,we(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,we(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,we(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125)return this._loop=!1,we(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&e[1]),this._isServer){if(!this._masked)return this._loop=!1,we(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,we(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,we(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,we(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");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=ue;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])&&ge(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[fe.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)return t(we(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const s=this.dataMessage();if(s)return t(s);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?me(t,e):"arraybuffer"===this._binaryType?ye(me(t,e)):t,this.emit("message",r,!0)}else{const r=me(t,e);if(!this._skipUTF8Validation&&!be(r))return this._loop=!1,we(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",r,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,ue),this.end();else{if(1===e.length)return we(RangeError,"invalid payload length 1",!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");{const t=e.readUInt16BE(0);if(!ve(t))return we(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=e.slice(2);if(!this._skipUTF8Validation&&!be(r))return we(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,r),this.end()}}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function we(e,t,r,s,i){const n=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(n,we),n.code=i,n[_e]=s,n}const{randomFillSync:ke}=p.default,xe=re,{EMPTY_BUFFER:Ee}=U,{isValidStatusCode:Oe}=oe.exports,{mask:Ce,toBuffer:Te}=A.exports,Ne=Symbol("kByteLength"),Le=Buffer.alloc(4);class Pe{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||Le,t.generateMask?t.generateMask(r):ke(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[Ne]?(e=Buffer.from(e)).length:t[Ne]:(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 c=Buffer.allocUnsafe(i?s+n:n);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(s,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(s,4,6)),t.mask?(c[1]|=128,c[n-4]=r[0],c[n-3]=r[1],c[n-2]=r[2],c[n-1]=r[3],o?[c,e]:i?(Ce(e,r,c,n,s),[c]):(Ce(e,r,e,0,s),[c,e])):[c,e]}close(e,t,r,s){let i;if(void 0===e)i=Ee;else{if("number"!=typeof e||!Oe(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={[Ne]: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(Pe.frame(i,n),s)}ping(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Te(e)).length,i=Te.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const n={[Ne]: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(Pe.frame(e,n),r)}pong(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Te(e)).length,i=Te.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const n={[Ne]: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(Pe.frame(e,n),r)}send(e,t,r){const s=this._extensions[xe.extensionName];let i,n,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(i=Buffer.byteLength(e),n=!1):(i=(e=Te(e)).length,n=Te.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={[Ne]: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(Pe.frame(e,{[Ne]: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(Pe.frame(e,r),s);const i=this._extensions[xe.extensionName];this._bufferedBytes+=r[Ne],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[Ne],this._deflating=!1,r.readOnly=!1,this.sendFrame(Pe.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ne],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ne],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 Re=Pe;const{kForOnEventAttribute:Be,kListener:Ae}=U,Ue=Symbol("kCode"),Ie=Symbol("kData"),Me=Symbol("kError"),We=Symbol("kMessage"),De=Symbol("kReason"),Fe=Symbol("kTarget"),je=Symbol("kType"),$e=Symbol("kWasClean");class Ge{constructor(e){this[Fe]=null,this[je]=e}get target(){return this[Fe]}get type(){return this[je]}}Object.defineProperty(Ge.prototype,"target",{enumerable:!0}),Object.defineProperty(Ge.prototype,"type",{enumerable:!0});class Ve extends Ge{constructor(e,t={}){super(e),this[Ue]=void 0===t.code?0:t.code,this[De]=void 0===t.reason?"":t.reason,this[$e]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ue]}get reason(){return this[De]}get wasClean(){return this[$e]}}Object.defineProperty(Ve.prototype,"code",{enumerable:!0}),Object.defineProperty(Ve.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ve.prototype,"wasClean",{enumerable:!0});class qe extends Ge{constructor(e,t={}){super(e),this[Me]=void 0===t.error?null:t.error,this[We]=void 0===t.message?"":t.message}get error(){return this[Me]}get message(){return this[We]}}Object.defineProperty(qe.prototype,"error",{enumerable:!0}),Object.defineProperty(qe.prototype,"message",{enumerable:!0});class ze extends Ge{constructor(e,t={}){super(e),this[Ie]=void 0===t.data?null:t.data}get data(){return this[Ie]}}Object.defineProperty(ze.prototype,"data",{enumerable:!0});const He={addEventListener(e,t,r={}){let s;if("message"===e)s=function(e,r){const s=new ze("message",{data:r?e:e.toString()});s[Fe]=this,t.call(this,s)};else if("close"===e)s=function(e,r){const s=new Ve("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Fe]=this,t.call(this,s)};else if("error"===e)s=function(e){const r=new qe("error",{error:e,message:e.message});r[Fe]=this,t.call(this,r)};else{if("open"!==e)return;s=function(){const e=new Ge("open");e[Fe]=this,t.call(this,e)}}s[Be]=!!r[Be],s[Ae]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[Ae]===t&&!r[Be]){this.removeListener(e,r);break}}};var Ye={CloseEvent:Ve,ErrorEvent:qe,Event:Ge,EventTarget:He,MessageEvent:ze};const{tokenChars:Xe}=oe.exports;function Ze(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var Ke={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,c=-1,h=-1,l=-1,f=0;for(;f<e.length;f++)if(h=e.charCodeAt(f),void 0===r)if(-1===l&&1===Xe[h])-1===c&&(c=f);else if(0===f||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f);const s=e.slice(c,l);44===h?(Ze(t,s,i),i=Object.create(null)):r=s,c=l=-1}}else-1===l&&-1!==c&&(l=f);else if(void 0===s)if(-1===l&&1===Xe[h])-1===c&&(c=f);else if(32===h||9===h)-1===l&&-1!==c&&(l=f);else if(59===h||44===h){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f),Ze(i,e.slice(c,l),!0),44===h&&(Ze(t,r,i),i=Object.create(null),r=void 0),c=l=-1}else{if(61!==h||-1===c||-1!==l)throw new SyntaxError(`Unexpected character at index ${f}`);s=e.slice(c,f),c=l=-1}else if(o){if(1!==Xe[h])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:n||(n=!0),o=!1}else if(a)if(1===Xe[h])-1===c&&(c=f);else if(34===h&&-1!==c)a=!1,l=f;else{if(92!==h)throw new SyntaxError(`Unexpected character at index ${f}`);o=!0}else if(34===h&&61===e.charCodeAt(f-1))a=!0;else if(-1===l&&1===Xe[h])-1===c&&(c=f);else if(-1===c||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f);let o=e.slice(c,l);n&&(o=o.replace(/\\/g,""),n=!1),Ze(i,s,o),44===h&&(Ze(t,r,i),i=Object.create(null),r=void 0),s=void 0,c=l=-1}}else-1===l&&(l=f);if(-1===c||a||32===h||9===h)throw new SyntaxError("Unexpected end of input");-1===l&&(l=f);const d=e.slice(c,l);return void 0===r?Ze(t,d,i):(void 0===s?Ze(i,d,!0):Ze(i,s,n?d.replace(/\\/g,""):d),Ze(t,r,i)),t}};const Je=l.default,Qe=f.default,et=d.default,tt=u.default,rt=_.default,{randomBytes:st,createHash:it}=p.default,{URL:nt}=y.default,ot=re,at=Se,ct=Re,{BINARY_TYPES:ht,EMPTY_BUFFER:lt,GUID:ft,kForOnEventAttribute:dt,kListener:ut,kStatusCode:_t,kWebSocket:pt,NOOP:mt}=U,{EventTarget:{addEventListener:yt,removeEventListener:gt}}=Ye,{format:vt,parse:bt}=Ke,{toBuffer:St}=A.exports,wt=["CONNECTING","OPEN","CLOSING","CLOSED"],kt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,xt=[8,13];class Et extends Je{constructor(e,t,r){super(),this._binaryType=ht[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=lt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=Et.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]),Ct(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){ht.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 at({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new ct(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[pt]=this,e[pt]=this,s.on("conclude",Bt),s.on("drain",At),s.on("error",Ut),s.on("message",Mt),s.on("ping",Wt),s.on("pong",Dt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",jt),e.on("data",$t),e.on("end",Gt),e.on("error",Vt),this._readyState=Et.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Et.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[ot.extensionName]&&this._extensions[ot.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Et.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Et.CLOSED){if(this.readyState===Et.CONNECTING){const e="WebSocket was closed before the connection was established";return Pt(this,this._req,e)}this.readyState!==Et.CLOSING?(this._readyState=Et.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()}}pause(){this.readyState!==Et.CONNECTING&&this.readyState!==Et.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===Et.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===Et.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||lt,t,r)):Rt(this,e,r)}pong(e,t,r){if(this.readyState===Et.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===Et.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||lt,t,r)):Rt(this,e,r)}resume(){this.readyState!==Et.CONNECTING&&this.readyState!==Et.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===Et.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!==Et.OPEN)return void Rt(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ot.extensionName]||(s.compress=!1),this._sender.send(e||lt,s,r)}terminate(){if(this.readyState!==Et.CLOSED){if(this.readyState===Et.CONNECTING){const e="WebSocket was closed before the connection was established";return Pt(this,this._req,e)}this._socket&&(this._readyState=Et.CLOSING,this._socket.destroy())}}}Object.defineProperty(Et,"CONNECTING",{enumerable:!0,value:wt.indexOf("CONNECTING")}),Object.defineProperty(Et.prototype,"CONNECTING",{enumerable:!0,value:wt.indexOf("CONNECTING")}),Object.defineProperty(Et,"OPEN",{enumerable:!0,value:wt.indexOf("OPEN")}),Object.defineProperty(Et.prototype,"OPEN",{enumerable:!0,value:wt.indexOf("OPEN")}),Object.defineProperty(Et,"CLOSING",{enumerable:!0,value:wt.indexOf("CLOSING")}),Object.defineProperty(Et.prototype,"CLOSING",{enumerable:!0,value:wt.indexOf("CLOSING")}),Object.defineProperty(Et,"CLOSED",{enumerable:!0,value:wt.indexOf("CLOSED")}),Object.defineProperty(Et.prototype,"CLOSED",{enumerable:!0,value:wt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Et.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Et.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[dt])return t[ut];return null},set(t){for(const t of this.listeners(e))if(t[dt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[dt]:!0})}})})),Et.prototype.addEventListener=yt,Et.prototype.removeEventListener=gt;var Ot=Et;function Ct(e,t,r,s){const i={protocolVersion:xt[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:void 0,host:void 0,path:void 0,port:void 0};if(!xt.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${xt.join(", ")})`);let n;if(t instanceof nt)n=t,e._url=t.href;else{try{n=new nt(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const o="wss:"===n.protocol,a="ws+unix:"===n.protocol;let c;if("ws:"===n.protocol||o||a?a&&!n.pathname?c="The URL's pathname is empty":n.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void Tt(e,t)}const h=o?443:80,l=st(16).toString("base64"),f=o?Qe.get:et.get,d=new Set;let u;if(i.createConnection=o?Lt:Nt,i.defaultPort=i.defaultPort||h,i.port=n.port||h,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket",...i.headers},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(u=new ot(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=vt({[ot.extensionName]:u.offer()})),r.length){for(const e of r){if("string"!=typeof e||!kt.test(e)||d.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.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._originalHost=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 n.host!==e._originalHost&&(delete i.headers.authorization,delete i.headers.cookie,delete i.headers.host,i.auth=void 0);i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64"))}let _=e._req=f(i);i.timeout&&_.on("timeout",(()=>{Pt(e,_,"Opening handshake has timed out")})),_.on("error",(t=>{null===_||_.aborted||(_=e._req=null,Tt(e,t))})),_.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 Pt(e,_,"Maximum redirects exceeded");let n;_.abort();try{n=new nt(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Tt(e,r)}Ct(e,n,r,s)}else e.emit("unexpected-response",_,n)||Pt(e,_,`Unexpected server response: ${n.statusCode}`)})),_.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==Et.CONNECTING)return;_=e._req=null;const n=it("sha1").update(l+ft).digest("base64");if(t.headers["sec-websocket-accept"]!==n)return void Pt(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?d.size?d.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":d.size&&(a="Server sent no subprotocol"),a)return void Pt(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!u){return void Pt(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=bt(c)}catch(t){return void Pt(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==ot.extensionName){return void Pt(e,r,"Server indicated an extension that was not requested")}try{u.accept(t[ot.extensionName])}catch(t){return void Pt(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[ot.extensionName]=u}e.setSocket(r,s,{generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}))}function Tt(e,t){e._readyState=Et.CLOSING,e.emit("error",t),e.emitClose()}function Nt(e){return e.path=e.socketPath,tt.connect(e)}function Lt(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=tt.isIP(e.host)?"":e.host),rt.connect(e)}function Pt(e,t,r){e._readyState=Et.CLOSING;const s=new Error(r);Error.captureStackTrace(s,Pt),t.setHeader?(t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),t.once("abort",e.emitClose.bind(e)),e.emit("error",s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Rt(e,t,r){if(t){const r=St(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){r(new Error(`WebSocket is not open: readyState ${e.readyState} (${wt[e.readyState]})`))}}function Bt(e,t){const r=this[pt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[pt]&&(r._socket.removeListener("data",$t),process.nextTick(Ft,r._socket),1005===e?r.close():r.close(e,t))}function At(){const e=this[pt];e.isPaused||e._socket.resume()}function Ut(e){const t=this[pt];void 0!==t._socket[pt]&&(t._socket.removeListener("data",$t),process.nextTick(Ft,t._socket),t.close(e[_t])),t.emit("error",e)}function It(){this[pt].emitClose()}function Mt(e,t){this[pt].emit("message",e,t)}function Wt(e){const t=this[pt];t.pong(e,!t._isServer,mt),t.emit("ping",e)}function Dt(e){this[pt].emit("pong",e)}function Ft(e){e.resume()}function jt(){const e=this[pt];let t;this.removeListener("close",jt),this.removeListener("data",$t),this.removeListener("end",Gt),e._readyState=Et.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[pt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",It),e._receiver.on("finish",It))}function $t(e){this[pt]._receiver.write(e)||this.pause()}function Gt(){const e=this[pt];e._readyState=Et.CLOSING,e._receiver.end(),this.end()}function Vt(){const e=this[pt];this.removeListener("error",Vt),this.on("error",mt),e&&(e._readyState=Et.CLOSING,this.destroy())}const{Duplex:qt}=m.default;function zt(e){e.emit("close")}function Ht(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Yt(e){this.removeListener("error",Yt),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var Xt=function(e,t){let r=!0;const s=new qt({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const i=!r&&s._readableState.objectMode?t.toString():t;s.push(i)||e.pause()})),e.once("error",(function(e){s.destroyed||(r=!1,s.destroy(e))})),e.once("close",(function(){s.destroyed||s.push(null)})),s._destroy=function(t,i){if(e.readyState===e.CLOSED)return i(t),void process.nextTick(zt,s);let n=!1;e.once("error",(function(e){n=!0,i(e)})),e.once("close",(function(){n||i(t),process.nextTick(zt,s)})),r&&e.terminate()},s._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){s._final(t)}))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,r,i){e.readyState!==e.CONNECTING?e.send(t,i):e.once("open",(function(){s._write(t,r,i)}))},s.on("end",Ht),s.on("error",Yt),s};const{tokenChars:Zt}=oe.exports;var Kt={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===Zt[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 Jt=l.default,Qt=d.default,{createHash:er}=p.default,tr=Ke,rr=re,sr=Kt,ir=Ot,{GUID:nr,kWebSocket:or}=U,ar=/^[+/0-9A-Za-z]{22}==$/;var cr=class extends Jt{constructor(e,t){if(super(),null==(e={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:ir,...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=Qt.createServer(((e,t)=>{const r=Qt.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(hr,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(hr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{hr(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",lr);const i=void 0!==e.headers["sec-websocket-key"]&&e.headers["sec-websocket-key"],n=+e.headers["sec-websocket-version"];if("GET"!==e.method||"websocket"!==e.headers.upgrade.toLowerCase()||!i||!ar.test(i)||8!==n&&13!==n||!this.shouldHandle(e))return fr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=sr.parse(o)}catch(e){return fr(t,400)}const c=e.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&void 0!==c){const e=new rr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const t=tr.parse(c);t[rr.extensionName]&&(e.accept(t[rr.extensionName]),h[rr.extensionName]=e)}catch(e){return fr(t,400)}}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,c,l)=>{if(!n)return fr(t,o||401,c,l);this.completeUpgrade(h,i,a,e,t,r,s)}));if(!this.options.verifyClient(o))return fr(t,401)}this.completeUpgrade(h,i,a,e,t,r,s)}completeUpgrade(e,t,r,s,i,n,o){if(!i.readable||!i.writable)return i.destroy();if(i[or])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return fr(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${er("sha1").update(t+nr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[rr.extensionName]){const t=e[rr.extensionName].params,r=tr.format({[rr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,s),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",lr),c.setSocket(i,n,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(hr,this)}))),o(c,s)}};function hr(e){e._state=2,e.emit("close")}function lr(){this.destroy()}function fr(e,t,r,s){e.writable&&(r=r||Qt.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.write(`HTTP/1.1 ${t} ${Qt.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)),e.removeListener("error",lr),e.destroy()}const dr=Ot;dr.createWebSocketStream=Xt,dr.Server=cr,dr.Receiver=Se,dr.Sender=Re,dr.WebSocket=dr,dr.WebSocketServer=dr.Server;var ur=dr,_r=require("child_process"),pr=require("events"),mr=require("url"),yr=ur.Server,gr=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&x(e,t)}(r,pr.EventEmitter);var t=C(r);function r(e){var s;return v(this,r),w(E(s=t.call(this)),"exitCode",void 0),w(E(s),"additionalFlags",[]),w(E(s),"stream",null),w(E(s),"inputStreamStarted",!1),s.options=e,s.ffmpegPath=e.ffmpegPath||"ffmpeg",s.url=e.url,s.ffmpegOptions=e.ffmpegOptions,s.initMpeg2Muxer(),s}return S(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(this.ffmpegOptions)for(var t in this.ffmpegOptions)this.additionalFlags.push(t),""!==String(this.ffmpegOptions[t])&&this.additionalFlags.push(String(this.ffmpegOptions[t]));this.spawnOptions=["-rtsp_transport","tcp","-thread_queue_size","512","-i",this.url,"-f","mpegts","-codec:v","mpeg1video"].concat(T(this.additionalFlags),["-"]),this.stream=_r.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数")})),this.stream.on("close",(function(t,r){return console.log("ffmpeg关闭,code:",t),e.emit("exitWithError")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(t){return e.emit("mpeg2data",t)})),this.stream.stderr.on("data",(function(t){return e.emit("ffmpegStderr",t)})),this.stream.on("exit",(function(t,r){if(1===t)return console.error("RTSP stream exited with error"),e.exitCode=1,e.emit("exitWithError")}))}}]),r}(),vr=function(){function e(t,r){v(this,e),w(this,"freeTime",0),w(this,"isStreamWrap",!1),w(this,"clients",[]),w(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),this.config=t,this.client=r}return S(e,[{key:"createStream",value:function(){var e=this;this.isStreamWrap||(this.isStreamWrap=!0,this.mpeg2Muxer.instance=new gr({ffmpegOptions:{"-stats":"","-r":20,"-s":"1920x1080","-b:v":"2000k"},url:this.config.url,ffmpegPath:"ffmpeg"}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})))}},{key:"stopStreamWrap",value:function(){this.mpeg2Muxer.stream.kill(),this.mpeg2Muxer.stream=null}},{key:"broadcast",value:function(e){var t,r=P(this.clients);try{for(r.s();!(t=r.n()).done;){var s=t.value;s.isSegment&&s.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"sendData",value:function(e){e.send(this.mpeg1Muxer.data),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);t>-1&&this.clients.splice(t,1)}}]),e}(),br=function(){function e(t){var r=this;v(this,e),w(this,"channels",[]),setInterval((function(){return r.checkFree()}),1e4),this.wss=new yr({port:t&&t.port||9999}),this.wss.on("connection",(function(e,t){var s=mr.parse(t.url,!0);if(s.query.url){var i=B.exports.decode(s.query.url.toString());r.registeClient(e,{url:i})}console.log("一个新的client(ws句柄)连接成功")}))}return S(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=P(this.channels);try{for(r.s();!(t=r.n()).done;){var s=t.value;if(s.config.url===e)return s}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new vr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=P(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=10,r.freeTime>=60&&this.destroyedChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyedChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.stopStreamWrap())}}]),e}();w(br,"version","2.1.0"),module.exports=br;
8
+ !function(e,t){!function(r){var s=t,i=e&&e.exports==s&&e,n="object"==typeof R&&R;n.global!==n&&n.window!==n||(r=n);var o=function(e){this.message=e};(o.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new o(e)},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=/[\t\n\f\r ]/g,l={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,s,i,n=e.length%3,o="",h=-1,l=e.length-n;++h<l;)t=e.charCodeAt(h)<<16,r=e.charCodeAt(++h)<<8,s=e.charCodeAt(++h),o+=c.charAt((i=t+r+s)>>18&63)+c.charAt(i>>12&63)+c.charAt(i>>6&63)+c.charAt(63&i);return 2==n?(t=e.charCodeAt(h)<<8,r=e.charCodeAt(++h),o+=c.charAt((i=t+r)>>10)+c.charAt(i>>4&63)+c.charAt(i<<2&63)+"="):1==n&&(i=e.charCodeAt(h),o+=c.charAt(i>>2)+c.charAt(i<<4&63)+"=="),o},decode:function(e){var t=(e=String(e).replace(h,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,s,i=0,n="",o=-1;++o<t;)s=c.indexOf(e.charAt(o)),r=i%4?64*r+s:s,i++%4&&(n+=String.fromCharCode(255&r>>(-2*i&6)));return n},version:"1.0.0"};if(s&&!s.nodeType)if(i)i.exports=l;else for(var f in l)l.hasOwnProperty(f)&&(s[f]=l[f]);else r.base64=l}(R)}(B,B.exports);var A={exports:{}},U={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:()=>{}};const{EMPTY_BUFFER:I}=U;function M(e,t){if(0===e.length)return I;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const i=e[t];r.set(i,s),s+=i.length}return s<t?r.slice(0,s):r}function W(e,t,r,s,i){for(let n=0;n<i;n++)r[s+n]=e[n]^t[3&n]}function D(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}function F(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function j(e){if(j.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=Buffer.from(e):ArrayBuffer.isView(e)?t=Buffer.from(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),j.readOnly=!1),t}try{const e=require("bufferutil");A.exports={concat:M,mask(t,r,s,i,n){n<48?W(t,r,s,i,n):e.mask(t,r,s,i,n)},toArrayBuffer:F,toBuffer:j,unmask(t,r){t.length<32?D(t,r):e.unmask(t,r)}}}catch(e){A.exports={concat:M,mask:W,toArrayBuffer:F,toBuffer:j,unmask:D}}const $=Symbol("kDone"),G=Symbol("kRun");var V=class{constructor(e){this[$]=()=>{this.pending--,this[G]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[G]()}[G](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[$])}}};const q=g.default,z=A.exports,H=V,{kStatusCode:Y}=U,X=Buffer.from([0,0,255,255]),Z=Symbol("permessage-deflate"),K=Symbol("total-length"),J=Symbol("callback"),Q=Symbol("buffers"),ee=Symbol("error");let te;var re=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,!te){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;te=new H(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[J];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){te.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){te.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]?q.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=q.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Z]=this,this._inflate[K]=0,this._inflate[Q]=[],this._inflate.on("error",ne),this._inflate.on("data",ie)}this._inflate[J]=r,this._inflate.write(e),t&&this._inflate.write(X),this._inflate.flush((()=>{const e=this._inflate[ee];if(e)return this._inflate.close(),this._inflate=null,void r(e);const i=z.concat(this._inflate[Q],this._inflate[K]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[K]=0,this._inflate[Q]=[],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]?q.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=q.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[K]=0,this._deflate[Q]=[],this._deflate.on("data",se)}this._deflate[J]=r,this._deflate.write(e),this._deflate.flush(q.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=z.concat(this._deflate[Q],this._deflate[K]);t&&(e=e.slice(0,e.length-4)),this._deflate[J]=null,this._deflate[K]=0,this._deflate[Q]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function se(e){this[Q].push(e),this[K]+=e.length}function ie(e){this[K]+=e.length,this[Z]._maxPayload<1||this[K]<=this[Z]._maxPayload?this[Q].push(e):(this[ee]=new RangeError("Max payload size exceeded"),this[ee].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ee][Y]=1009,this.removeListener("data",ie),this.reset())}function ne(e){this[Z]._inflate=null,e[Y]=1007,this[J](e)}var oe={exports:{}};const ae=[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];function ce(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999}function he(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}try{const e=require("utf-8-validate");oe.exports={isValidStatusCode:ce,isValidUTF8:t=>t.length<150?he(t):e(t),tokenChars:ae}}catch(e){oe.exports={isValidStatusCode:ce,isValidUTF8:he,tokenChars:ae}}const{Writable:le}=m.default,fe=re,{BINARY_TYPES:de,EMPTY_BUFFER:ue,kStatusCode:_e,kWebSocket:pe}=U,{concat:me,toArrayBuffer:ye,unmask:ge}=A.exports,{isValidStatusCode:ve,isValidUTF8:be}=oe.exports;var Se=class extends le{constructor(e={}){super(),this._binaryType=e.binaryType||de[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[pe]=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._state=0,this._loop=!1}_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]=t.slice(e),t.slice(0,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]=r.slice(e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,we(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[fe.extensionName])return this._loop=!1,we(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,we(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,we(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 this._loop=!1,we(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,we(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,we(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,we(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125)return this._loop=!1,we(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&e[1]),this._isServer){if(!this._masked)return this._loop=!1,we(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,we(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,we(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,we(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");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=ue;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])&&ge(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[fe.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)return t(we(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const s=this.dataMessage();if(s)return t(s);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?me(t,e):"arraybuffer"===this._binaryType?ye(me(t,e)):t,this.emit("message",r,!0)}else{const r=me(t,e);if(!this._skipUTF8Validation&&!be(r))return this._loop=!1,we(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",r,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,ue),this.end();else{if(1===e.length)return we(RangeError,"invalid payload length 1",!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");{const t=e.readUInt16BE(0);if(!ve(t))return we(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=e.slice(2);if(!this._skipUTF8Validation&&!be(r))return we(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,r),this.end()}}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function we(e,t,r,s,i){const n=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(n,we),n.code=i,n[_e]=s,n}const{randomFillSync:ke}=p.default,xe=re,{EMPTY_BUFFER:Ee}=U,{isValidStatusCode:Oe}=oe.exports,{mask:Ce,toBuffer:Te}=A.exports,Ne=Symbol("kByteLength"),Le=Buffer.alloc(4);class Pe{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||Le,t.generateMask?t.generateMask(r):ke(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[Ne]?(e=Buffer.from(e)).length:t[Ne]:(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 c=Buffer.allocUnsafe(i?s+n:n);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(s,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(s,4,6)),t.mask?(c[1]|=128,c[n-4]=r[0],c[n-3]=r[1],c[n-2]=r[2],c[n-1]=r[3],o?[c,e]:i?(Ce(e,r,c,n,s),[c]):(Ce(e,r,e,0,s),[c,e])):[c,e]}close(e,t,r,s){let i;if(void 0===e)i=Ee;else{if("number"!=typeof e||!Oe(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={[Ne]: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(Pe.frame(i,n),s)}ping(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Te(e)).length,i=Te.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const n={[Ne]: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(Pe.frame(e,n),r)}pong(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Te(e)).length,i=Te.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const n={[Ne]: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(Pe.frame(e,n),r)}send(e,t,r){const s=this._extensions[xe.extensionName];let i,n,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(i=Buffer.byteLength(e),n=!1):(i=(e=Te(e)).length,n=Te.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={[Ne]: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(Pe.frame(e,{[Ne]: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(Pe.frame(e,r),s);const i=this._extensions[xe.extensionName];this._bufferedBytes+=r[Ne],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[Ne],this._deflating=!1,r.readOnly=!1,this.sendFrame(Pe.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ne],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ne],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 Re=Pe;const{kForOnEventAttribute:Be,kListener:Ae}=U,Ue=Symbol("kCode"),Ie=Symbol("kData"),Me=Symbol("kError"),We=Symbol("kMessage"),De=Symbol("kReason"),Fe=Symbol("kTarget"),je=Symbol("kType"),$e=Symbol("kWasClean");class Ge{constructor(e){this[Fe]=null,this[je]=e}get target(){return this[Fe]}get type(){return this[je]}}Object.defineProperty(Ge.prototype,"target",{enumerable:!0}),Object.defineProperty(Ge.prototype,"type",{enumerable:!0});class Ve extends Ge{constructor(e,t={}){super(e),this[Ue]=void 0===t.code?0:t.code,this[De]=void 0===t.reason?"":t.reason,this[$e]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ue]}get reason(){return this[De]}get wasClean(){return this[$e]}}Object.defineProperty(Ve.prototype,"code",{enumerable:!0}),Object.defineProperty(Ve.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ve.prototype,"wasClean",{enumerable:!0});class qe extends Ge{constructor(e,t={}){super(e),this[Me]=void 0===t.error?null:t.error,this[We]=void 0===t.message?"":t.message}get error(){return this[Me]}get message(){return this[We]}}Object.defineProperty(qe.prototype,"error",{enumerable:!0}),Object.defineProperty(qe.prototype,"message",{enumerable:!0});class ze extends Ge{constructor(e,t={}){super(e),this[Ie]=void 0===t.data?null:t.data}get data(){return this[Ie]}}Object.defineProperty(ze.prototype,"data",{enumerable:!0});const He={addEventListener(e,t,r={}){let s;if("message"===e)s=function(e,r){const s=new ze("message",{data:r?e:e.toString()});s[Fe]=this,t.call(this,s)};else if("close"===e)s=function(e,r){const s=new Ve("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Fe]=this,t.call(this,s)};else if("error"===e)s=function(e){const r=new qe("error",{error:e,message:e.message});r[Fe]=this,t.call(this,r)};else{if("open"!==e)return;s=function(){const e=new Ge("open");e[Fe]=this,t.call(this,e)}}s[Be]=!!r[Be],s[Ae]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[Ae]===t&&!r[Be]){this.removeListener(e,r);break}}};var Ye={CloseEvent:Ve,ErrorEvent:qe,Event:Ge,EventTarget:He,MessageEvent:ze};const{tokenChars:Xe}=oe.exports;function Ze(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var Ke={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,c=-1,h=-1,l=-1,f=0;for(;f<e.length;f++)if(h=e.charCodeAt(f),void 0===r)if(-1===l&&1===Xe[h])-1===c&&(c=f);else if(0===f||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f);const s=e.slice(c,l);44===h?(Ze(t,s,i),i=Object.create(null)):r=s,c=l=-1}}else-1===l&&-1!==c&&(l=f);else if(void 0===s)if(-1===l&&1===Xe[h])-1===c&&(c=f);else if(32===h||9===h)-1===l&&-1!==c&&(l=f);else if(59===h||44===h){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f),Ze(i,e.slice(c,l),!0),44===h&&(Ze(t,r,i),i=Object.create(null),r=void 0),c=l=-1}else{if(61!==h||-1===c||-1!==l)throw new SyntaxError(`Unexpected character at index ${f}`);s=e.slice(c,f),c=l=-1}else if(o){if(1!==Xe[h])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:n||(n=!0),o=!1}else if(a)if(1===Xe[h])-1===c&&(c=f);else if(34===h&&-1!==c)a=!1,l=f;else{if(92!==h)throw new SyntaxError(`Unexpected character at index ${f}`);o=!0}else if(34===h&&61===e.charCodeAt(f-1))a=!0;else if(-1===l&&1===Xe[h])-1===c&&(c=f);else if(-1===c||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===l&&(l=f);let o=e.slice(c,l);n&&(o=o.replace(/\\/g,""),n=!1),Ze(i,s,o),44===h&&(Ze(t,r,i),i=Object.create(null),r=void 0),s=void 0,c=l=-1}}else-1===l&&(l=f);if(-1===c||a||32===h||9===h)throw new SyntaxError("Unexpected end of input");-1===l&&(l=f);const d=e.slice(c,l);return void 0===r?Ze(t,d,i):(void 0===s?Ze(i,d,!0):Ze(i,s,n?d.replace(/\\/g,""):d),Ze(t,r,i)),t}};const Je=l.default,Qe=f.default,et=d.default,tt=u.default,rt=_.default,{randomBytes:st,createHash:it}=p.default,{URL:nt}=y.default,ot=re,at=Se,ct=Re,{BINARY_TYPES:ht,EMPTY_BUFFER:lt,GUID:ft,kForOnEventAttribute:dt,kListener:ut,kStatusCode:_t,kWebSocket:pt,NOOP:mt}=U,{EventTarget:{addEventListener:yt,removeEventListener:gt}}=Ye,{format:vt,parse:bt}=Ke,{toBuffer:St}=A.exports,wt=["CONNECTING","OPEN","CLOSING","CLOSED"],kt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,xt=[8,13];class Et extends Je{constructor(e,t,r){super(),this._binaryType=ht[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=lt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=Et.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]),Ct(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){ht.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 at({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new ct(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[pt]=this,e[pt]=this,s.on("conclude",Bt),s.on("drain",At),s.on("error",Ut),s.on("message",Mt),s.on("ping",Wt),s.on("pong",Dt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",jt),e.on("data",$t),e.on("end",Gt),e.on("error",Vt),this._readyState=Et.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Et.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[ot.extensionName]&&this._extensions[ot.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Et.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Et.CLOSED){if(this.readyState===Et.CONNECTING){const e="WebSocket was closed before the connection was established";return Pt(this,this._req,e)}this.readyState!==Et.CLOSING?(this._readyState=Et.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()}}pause(){this.readyState!==Et.CONNECTING&&this.readyState!==Et.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===Et.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===Et.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||lt,t,r)):Rt(this,e,r)}pong(e,t,r){if(this.readyState===Et.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===Et.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||lt,t,r)):Rt(this,e,r)}resume(){this.readyState!==Et.CONNECTING&&this.readyState!==Et.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===Et.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!==Et.OPEN)return void Rt(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ot.extensionName]||(s.compress=!1),this._sender.send(e||lt,s,r)}terminate(){if(this.readyState!==Et.CLOSED){if(this.readyState===Et.CONNECTING){const e="WebSocket was closed before the connection was established";return Pt(this,this._req,e)}this._socket&&(this._readyState=Et.CLOSING,this._socket.destroy())}}}Object.defineProperty(Et,"CONNECTING",{enumerable:!0,value:wt.indexOf("CONNECTING")}),Object.defineProperty(Et.prototype,"CONNECTING",{enumerable:!0,value:wt.indexOf("CONNECTING")}),Object.defineProperty(Et,"OPEN",{enumerable:!0,value:wt.indexOf("OPEN")}),Object.defineProperty(Et.prototype,"OPEN",{enumerable:!0,value:wt.indexOf("OPEN")}),Object.defineProperty(Et,"CLOSING",{enumerable:!0,value:wt.indexOf("CLOSING")}),Object.defineProperty(Et.prototype,"CLOSING",{enumerable:!0,value:wt.indexOf("CLOSING")}),Object.defineProperty(Et,"CLOSED",{enumerable:!0,value:wt.indexOf("CLOSED")}),Object.defineProperty(Et.prototype,"CLOSED",{enumerable:!0,value:wt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Et.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Et.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[dt])return t[ut];return null},set(t){for(const t of this.listeners(e))if(t[dt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[dt]:!0})}})})),Et.prototype.addEventListener=yt,Et.prototype.removeEventListener=gt;var Ot=Et;function Ct(e,t,r,s){const i={protocolVersion:xt[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:void 0,host:void 0,path:void 0,port:void 0};if(!xt.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${xt.join(", ")})`);let n;if(t instanceof nt)n=t,e._url=t.href;else{try{n=new nt(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const o="wss:"===n.protocol,a="ws+unix:"===n.protocol;let c;if("ws:"===n.protocol||o||a?a&&!n.pathname?c="The URL's pathname is empty":n.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void Tt(e,t)}const h=o?443:80,l=st(16).toString("base64"),f=o?Qe.get:et.get,d=new Set;let u;if(i.createConnection=o?Lt:Nt,i.defaultPort=i.defaultPort||h,i.port=n.port||h,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket",...i.headers},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(u=new ot(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=vt({[ot.extensionName]:u.offer()})),r.length){for(const e of r){if("string"!=typeof e||!kt.test(e)||d.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.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._originalHost=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 n.host!==e._originalHost&&(delete i.headers.authorization,delete i.headers.cookie,delete i.headers.host,i.auth=void 0);i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64"))}let _=e._req=f(i);i.timeout&&_.on("timeout",(()=>{Pt(e,_,"Opening handshake has timed out")})),_.on("error",(t=>{null===_||_.aborted||(_=e._req=null,Tt(e,t))})),_.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 Pt(e,_,"Maximum redirects exceeded");let n;_.abort();try{n=new nt(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Tt(e,r)}Ct(e,n,r,s)}else e.emit("unexpected-response",_,n)||Pt(e,_,`Unexpected server response: ${n.statusCode}`)})),_.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==Et.CONNECTING)return;_=e._req=null;const n=it("sha1").update(l+ft).digest("base64");if(t.headers["sec-websocket-accept"]!==n)return void Pt(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?d.size?d.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":d.size&&(a="Server sent no subprotocol"),a)return void Pt(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!u){return void Pt(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=bt(c)}catch(t){return void Pt(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==ot.extensionName){return void Pt(e,r,"Server indicated an extension that was not requested")}try{u.accept(t[ot.extensionName])}catch(t){return void Pt(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[ot.extensionName]=u}e.setSocket(r,s,{generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}))}function Tt(e,t){e._readyState=Et.CLOSING,e.emit("error",t),e.emitClose()}function Nt(e){return e.path=e.socketPath,tt.connect(e)}function Lt(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=tt.isIP(e.host)?"":e.host),rt.connect(e)}function Pt(e,t,r){e._readyState=Et.CLOSING;const s=new Error(r);Error.captureStackTrace(s,Pt),t.setHeader?(t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),t.once("abort",e.emitClose.bind(e)),e.emit("error",s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Rt(e,t,r){if(t){const r=St(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){r(new Error(`WebSocket is not open: readyState ${e.readyState} (${wt[e.readyState]})`))}}function Bt(e,t){const r=this[pt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[pt]&&(r._socket.removeListener("data",$t),process.nextTick(Ft,r._socket),1005===e?r.close():r.close(e,t))}function At(){const e=this[pt];e.isPaused||e._socket.resume()}function Ut(e){const t=this[pt];void 0!==t._socket[pt]&&(t._socket.removeListener("data",$t),process.nextTick(Ft,t._socket),t.close(e[_t])),t.emit("error",e)}function It(){this[pt].emitClose()}function Mt(e,t){this[pt].emit("message",e,t)}function Wt(e){const t=this[pt];t.pong(e,!t._isServer,mt),t.emit("ping",e)}function Dt(e){this[pt].emit("pong",e)}function Ft(e){e.resume()}function jt(){const e=this[pt];let t;this.removeListener("close",jt),this.removeListener("data",$t),this.removeListener("end",Gt),e._readyState=Et.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[pt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",It),e._receiver.on("finish",It))}function $t(e){this[pt]._receiver.write(e)||this.pause()}function Gt(){const e=this[pt];e._readyState=Et.CLOSING,e._receiver.end(),this.end()}function Vt(){const e=this[pt];this.removeListener("error",Vt),this.on("error",mt),e&&(e._readyState=Et.CLOSING,this.destroy())}const{Duplex:qt}=m.default;function zt(e){e.emit("close")}function Ht(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Yt(e){this.removeListener("error",Yt),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var Xt=function(e,t){let r=!0;const s=new qt({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const i=!r&&s._readableState.objectMode?t.toString():t;s.push(i)||e.pause()})),e.once("error",(function(e){s.destroyed||(r=!1,s.destroy(e))})),e.once("close",(function(){s.destroyed||s.push(null)})),s._destroy=function(t,i){if(e.readyState===e.CLOSED)return i(t),void process.nextTick(zt,s);let n=!1;e.once("error",(function(e){n=!0,i(e)})),e.once("close",(function(){n||i(t),process.nextTick(zt,s)})),r&&e.terminate()},s._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){s._final(t)}))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,r,i){e.readyState!==e.CONNECTING?e.send(t,i):e.once("open",(function(){s._write(t,r,i)}))},s.on("end",Ht),s.on("error",Yt),s};const{tokenChars:Zt}=oe.exports;var Kt={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===Zt[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 Jt=l.default,Qt=d.default,{createHash:er}=p.default,tr=Ke,rr=re,sr=Kt,ir=Ot,{GUID:nr,kWebSocket:or}=U,ar=/^[+/0-9A-Za-z]{22}==$/;var cr=class extends Jt{constructor(e,t){if(super(),null==(e={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:ir,...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=Qt.createServer(((e,t)=>{const r=Qt.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(hr,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(hr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{hr(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",lr);const i=void 0!==e.headers["sec-websocket-key"]&&e.headers["sec-websocket-key"],n=+e.headers["sec-websocket-version"];if("GET"!==e.method||"websocket"!==e.headers.upgrade.toLowerCase()||!i||!ar.test(i)||8!==n&&13!==n||!this.shouldHandle(e))return fr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=sr.parse(o)}catch(e){return fr(t,400)}const c=e.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&void 0!==c){const e=new rr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const t=tr.parse(c);t[rr.extensionName]&&(e.accept(t[rr.extensionName]),h[rr.extensionName]=e)}catch(e){return fr(t,400)}}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,c,l)=>{if(!n)return fr(t,o||401,c,l);this.completeUpgrade(h,i,a,e,t,r,s)}));if(!this.options.verifyClient(o))return fr(t,401)}this.completeUpgrade(h,i,a,e,t,r,s)}completeUpgrade(e,t,r,s,i,n,o){if(!i.readable||!i.writable)return i.destroy();if(i[or])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return fr(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${er("sha1").update(t+nr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[rr.extensionName]){const t=e[rr.extensionName].params,r=tr.format({[rr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,s),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",lr),c.setSocket(i,n,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(hr,this)}))),o(c,s)}};function hr(e){e._state=2,e.emit("close")}function lr(){this.destroy()}function fr(e,t,r,s){e.writable&&(r=r||Qt.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.write(`HTTP/1.1 ${t} ${Qt.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)),e.removeListener("error",lr),e.destroy()}const dr=Ot;dr.createWebSocketStream=Xt,dr.Server=cr,dr.Receiver=Se,dr.Sender=Re,dr.WebSocket=dr,dr.WebSocketServer=dr.Server;var ur=dr,_r=require("child_process"),pr=require("events"),mr=require("url"),yr=ur.Server,gr=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&x(e,t)}(r,pr.EventEmitter);var t=C(r);function r(e){var s;return v(this,r),w(E(s=t.call(this)),"exitCode",void 0),w(E(s),"additionalFlags",[]),w(E(s),"stream",null),w(E(s),"inputStreamStarted",!1),s.options=e,s.ffmpegPath=e.ffmpegPath||"ffmpeg",s.url=e.url,s.ffmpegOptions=e.ffmpegOptions,s.initMpeg2Muxer(),s}return S(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(this.ffmpegOptions)for(var t in this.ffmpegOptions)this.additionalFlags.push(t),""!==String(this.ffmpegOptions[t])&&this.additionalFlags.push(String(this.ffmpegOptions[t]));this.spawnOptions=["-rtsp_transport","tcp","-thread_queue_size","512","-i",this.url,"-f","mpegts","-codec:v","mpeg1video"].concat(T(this.additionalFlags),["-"]),this.stream=_r.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数")})),this.stream.on("close",(function(t,r){return console.log("ffmpeg关闭,code:",t),e.emit("exitWithError")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(t){return e.emit("mpeg2data",t)})),this.stream.stderr.on("data",(function(t){return e.emit("ffmpegStderr",t)})),this.stream.on("exit",(function(t,r){if(1===t)return console.error("RTSP stream exited with error"),e.exitCode=1,e.emit("exitWithError")}))}}]),r}(),vr=function(){function e(t,r){v(this,e),w(this,"freeTime",0),w(this,"isStreamWrap",!1),w(this,"clients",[]),w(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),this.config=t,this.client=r}return S(e,[{key:"createStream",value:function(){var e=this;this.isStreamWrap||(this.isStreamWrap=!0,this.mpeg2Muxer.instance=new gr({ffmpegOptions:{"-stats":"","-r":20,"-s":"1920x1080","-b:v":"2000k"},url:this.config.url,ffmpegPath:"ffmpeg"}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})))}},{key:"stopStreamWrap",value:function(){this.mpeg2Muxer.stream.kill(),this.mpeg2Muxer.stream=null}},{key:"broadcast",value:function(e){var t,r=P(this.clients);try{for(r.s();!(t=r.n()).done;){var s=t.value;s.isSegment&&s.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"sendData",value:function(e){e.send(this.mpeg1Muxer.data),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);t>-1&&this.clients.splice(t,1)}}]),e}(),br=function(){function e(t){var r=this;v(this,e),w(this,"channels",[]),t&&t.videoSize&&t.videoSize.includes("x")&&(t.videoSize,function(e){throw new TypeError('"'+e+'" is read-only')}("videoSize")),setInterval((function(){return r.checkFree()}),1e4),this.wss=new yr({port:t&&t.port||9999}),this.wss.on("connection",(function(e,t){var s=mr.parse(t.url,!0);if(s.query.url){var i=B.exports.decode(s.query.url.toString());r.registeClient(e,{url:i})}console.log("一个新的client(ws句柄)连接成功")}))}return S(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=P(this.channels);try{for(r.s();!(t=r.n()).done;){var s=t.value;if(s.config.url===e)return s}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new vr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=P(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=10,r.freeTime>=60&&this.destroyedChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyedChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.stopStreamWrap())}}]),e}();w(br,"version","2.2.0"),module.exports=br;
9
9
  //# sourceMappingURL=rtsp2web.min.js.map