@rsbuild/core 0.6.8 → 0.6.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/compiled/commander/{typings/index.d.ts → index.d.ts} +26 -24
  2. package/compiled/commander/index.js +3528 -1
  3. package/compiled/commander/package.json +1 -1
  4. package/compiled/connect-history-api-fallback/index.js +186 -1
  5. package/compiled/dotenv/{lib/main.d.ts → index.d.ts} +16 -12
  6. package/compiled/dotenv/index.js +458 -1
  7. package/compiled/dotenv/package.json +1 -1
  8. package/compiled/dotenv-expand/{lib/main.d.ts → index.d.ts} +9 -7
  9. package/compiled/dotenv-expand/index.js +146 -1
  10. package/compiled/dotenv-expand/package.json +1 -1
  11. package/compiled/http-compression/index.js +185 -1
  12. package/compiled/launch-editor-middleware/index.js +843 -1
  13. package/compiled/on-finished/index.d.ts +2 -2
  14. package/compiled/on-finished/index.js +390 -3
  15. package/compiled/on-finished/package.json +1 -1
  16. package/compiled/open/index.d.ts +1 -153
  17. package/compiled/open/index.js +526 -1
  18. package/compiled/open/package.json +1 -1
  19. package/compiled/sirv/index.d.ts +1 -0
  20. package/compiled/sirv/index.js +798 -1
  21. package/compiled/sirv/package.json +1 -1
  22. package/compiled/webpack-dev-middleware/index.d.ts +1 -0
  23. package/compiled/webpack-dev-middleware/index.js +6696 -0
  24. package/compiled/webpack-dev-middleware/license +20 -0
  25. package/compiled/webpack-dev-middleware/package.json +1 -0
  26. package/compiled/webpack-dev-middleware/schema-utils.js +1 -0
  27. package/compiled/ws/index.d.ts +7 -15
  28. package/compiled/ws/index.js +4885 -1
  29. package/compiled/ws/package.json +1 -1
  30. package/dist/cli/commands.js +1 -1
  31. package/dist/cli/prepare.js +1 -1
  32. package/dist/client/format.d.ts +5 -0
  33. package/dist/client/{formatStats.js → format.js} +8 -43
  34. package/dist/client/{hmr/index.d.ts → hmr.d.ts} +4 -0
  35. package/dist/client/hmr.mjs +194 -431
  36. package/dist/client/overlay.mjs +205 -227
  37. package/dist/createContext.js +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/plugins/target.js +19 -16
  40. package/dist/provider/plugins/swc.js +1 -0
  41. package/dist/provider/shared.js +2 -2
  42. package/dist/server/devMiddleware.js +1 -1
  43. package/dist/server/devServer.js +6 -1
  44. package/dist/server/getDevMiddlewares.d.ts +3 -0
  45. package/dist/server/getDevMiddlewares.js +6 -8
  46. package/dist/server/helper.d.ts +4 -4
  47. package/dist/server/middlewares.d.ts +5 -2
  48. package/dist/server/middlewares.js +1 -7
  49. package/package.json +6 -5
  50. package/compiled/open/license +0 -9
  51. package/compiled/sirv/sirv.d.ts +0 -27
  52. package/dist/client/formatStats.d.ts +0 -12
  53. package/dist/client/hmr/url.d.ts +0 -6
@@ -1 +1,4885 @@
1
- (()=>{var __webpack_modules__={201:(e,t,s)=>{"use strict";const r=s(885);r.createWebSocketStream=s(334);r.Server=s(69);r.Receiver=s(997);r.Sender=s(345);r.WebSocket=r;r.WebSocketServer=r.Server;e.exports=r},64:(e,t,s)=>{"use strict";const{EMPTY_BUFFER:r}=s(547);const n=Buffer[Symbol.species];function concat(e,t){if(e.length===0)return r;if(e.length===1)return e[0];const s=Buffer.allocUnsafe(t);let i=0;for(let t=0;t<e.length;t++){const r=e[t];s.set(r,i);i+=r.length}if(i<t){return new n(s.buffer,s.byteOffset,i)}return s}function _mask(e,t,s,r,n){for(let i=0;i<n;i++){s[r+i]=e[i]^t[i&3]}}function _unmask(e,t){for(let s=0;s<e.length;s++){e[s]^=t[s&3]}}function toArrayBuffer(e){if(e.length===e.buffer.byteLength){return e.buffer}return e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function toBuffer(e){toBuffer.readOnly=true;if(Buffer.isBuffer(e))return e;let t;if(e instanceof ArrayBuffer){t=new n(e)}else if(ArrayBuffer.isView(e)){t=new n(e.buffer,e.byteOffset,e.byteLength)}else{t=Buffer.from(e);toBuffer.readOnly=false}return t}e.exports={concat:concat,mask:_mask,toArrayBuffer:toArrayBuffer,toBuffer:toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const t=s(471);e.exports.mask=function(e,s,r,n,i){if(i<48)_mask(e,s,r,n,i);else t.mask(e,s,r,n,i)};e.exports.unmask=function(e,s){if(e.length<32)_unmask(e,s);else t.unmask(e,s)}}catch(e){}}},547:e=>{"use strict";e.exports={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:()=>{}}},874:(e,t,s)=>{"use strict";const{kForOnEventAttribute:r,kListener:n}=s(547);const i=Symbol("kCode");const o=Symbol("kData");const a=Symbol("kError");const c=Symbol("kMessage");const l=Symbol("kReason");const f=Symbol("kTarget");const h=Symbol("kType");const d=Symbol("kWasClean");class Event{constructor(e){this[f]=null;this[h]=e}get target(){return this[f]}get type(){return this[h]}}Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});class CloseEvent extends Event{constructor(e,t={}){super(e);this[i]=t.code===undefined?0:t.code;this[l]=t.reason===undefined?"":t.reason;this[d]=t.wasClean===undefined?false:t.wasClean}get code(){return this[i]}get reason(){return this[l]}get wasClean(){return this[d]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});class ErrorEvent extends Event{constructor(e,t={}){super(e);this[a]=t.error===undefined?null:t.error;this[c]=t.message===undefined?"":t.message}get error(){return this[a]}get message(){return this[c]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});class MessageEvent extends Event{constructor(e,t={}){super(e);this[o]=t.data===undefined?null:t.data}get data(){return this[o]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});const u={addEventListener(e,t,s={}){for(const i of this.listeners(e)){if(!s[r]&&i[n]===t&&!i[r]){return}}let i;if(e==="message"){i=function onMessage(e,s){const r=new MessageEvent("message",{data:s?e:e.toString()});r[f]=this;callListener(t,this,r)}}else if(e==="close"){i=function onClose(e,s){const r=new CloseEvent("close",{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[f]=this;callListener(t,this,r)}}else if(e==="error"){i=function onError(e){const s=new ErrorEvent("error",{error:e,message:e.message});s[f]=this;callListener(t,this,s)}}else if(e==="open"){i=function onOpen(){const e=new Event("open");e[f]=this;callListener(t,this,e)}}else{return}i[r]=!!s[r];i[n]=t;if(s.once){this.once(e,i)}else{this.on(e,i)}},removeEventListener(e,t){for(const s of this.listeners(e)){if(s[n]===t&&!s[r]){this.removeListener(e,s);break}}}};e.exports={CloseEvent:CloseEvent,ErrorEvent:ErrorEvent,Event:Event,EventTarget:u,MessageEvent:MessageEvent};function callListener(e,t,s){if(typeof e==="object"&&e.handleEvent){e.handleEvent.call(e,s)}else{e.call(t,s)}}},321:(e,t,s)=>{"use strict";const{tokenChars:r}=s(903);function push(e,t,s){if(e[t]===undefined)e[t]=[s];else e[t].push(s)}function parse(e){const t=Object.create(null);let s=Object.create(null);let n=false;let i=false;let o=false;let a;let c;let l=-1;let f=-1;let h=-1;let d=0;for(;d<e.length;d++){f=e.charCodeAt(d);if(a===undefined){if(h===-1&&r[f]===1){if(l===-1)l=d}else if(d!==0&&(f===32||f===9)){if(h===-1&&l!==-1)h=d}else if(f===59||f===44){if(l===-1){throw new SyntaxError(`Unexpected character at index ${d}`)}if(h===-1)h=d;const r=e.slice(l,h);if(f===44){push(t,r,s);s=Object.create(null)}else{a=r}l=h=-1}else{throw new SyntaxError(`Unexpected character at index ${d}`)}}else if(c===undefined){if(h===-1&&r[f]===1){if(l===-1)l=d}else if(f===32||f===9){if(h===-1&&l!==-1)h=d}else if(f===59||f===44){if(l===-1){throw new SyntaxError(`Unexpected character at index ${d}`)}if(h===-1)h=d;push(s,e.slice(l,h),true);if(f===44){push(t,a,s);s=Object.create(null);a=undefined}l=h=-1}else if(f===61&&l!==-1&&h===-1){c=e.slice(l,d);l=h=-1}else{throw new SyntaxError(`Unexpected character at index ${d}`)}}else{if(i){if(r[f]!==1){throw new SyntaxError(`Unexpected character at index ${d}`)}if(l===-1)l=d;else if(!n)n=true;i=false}else if(o){if(r[f]===1){if(l===-1)l=d}else if(f===34&&l!==-1){o=false;h=d}else if(f===92){i=true}else{throw new SyntaxError(`Unexpected character at index ${d}`)}}else if(f===34&&e.charCodeAt(d-1)===61){o=true}else if(h===-1&&r[f]===1){if(l===-1)l=d}else if(l!==-1&&(f===32||f===9)){if(h===-1)h=d}else if(f===59||f===44){if(l===-1){throw new SyntaxError(`Unexpected character at index ${d}`)}if(h===-1)h=d;let r=e.slice(l,h);if(n){r=r.replace(/\\/g,"");n=false}push(s,c,r);if(f===44){push(t,a,s);s=Object.create(null);a=undefined}c=undefined;l=h=-1}else{throw new SyntaxError(`Unexpected character at index ${d}`)}}}if(l===-1||o||f===32||f===9){throw new SyntaxError("Unexpected end of input")}if(h===-1)h=d;const u=e.slice(l,h);if(a===undefined){push(t,u,s)}else{if(c===undefined){push(s,u,true)}else if(n){push(s,c,u.replace(/\\/g,""))}else{push(s,c,u)}push(t,a,s)}return t}function format(e){return Object.keys(e).map((t=>{let s=e[t];if(!Array.isArray(s))s=[s];return s.map((e=>[t].concat(Object.keys(e).map((t=>{let s=e[t];if(!Array.isArray(s))s=[s];return s.map((e=>e===true?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")}e.exports={format:format,parse:parse}},658:e=>{"use strict";const t=Symbol("kDone");const s=Symbol("kRun");class Limiter{constructor(e){this[t]=()=>{this.pending--;this[s]()};this.concurrency=e||Infinity;this.jobs=[];this.pending=0}add(e){this.jobs.push(e);this[s]()}[s](){if(this.pending===this.concurrency)return;if(this.jobs.length){const e=this.jobs.shift();this.pending++;e(this[t])}}}e.exports=Limiter},613:(e,t,s)=>{"use strict";const r=s(796);const n=s(64);const i=s(658);const{kStatusCode:o}=s(547);const a=Buffer[Symbol.species];const c=Buffer.from([0,0,255,255]);const l=Symbol("permessage-deflate");const f=Symbol("total-length");const h=Symbol("callback");const d=Symbol("buffers");const u=Symbol("error");let _;class PerMessageDeflate{constructor(e,t,s){this._maxPayload=s|0;this._options=e||{};this._threshold=this._options.threshold!==undefined?this._options.threshold:1024;this._isServer=!!t;this._deflate=null;this._inflate=null;this.params=null;if(!_){const e=this._options.concurrencyLimit!==undefined?this._options.concurrencyLimit:10;_=new i(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};if(this._options.serverNoContextTakeover){e.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){e.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){e.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){e.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){e.client_max_window_bits=true}return e}accept(e){e=this.normalizeParams(e);this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const e=this._deflate[h];this._deflate.close();this._deflate=null;if(e){e(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(e){const t=this._options;const s=e.find((e=>{if(t.serverNoContextTakeover===false&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===false||typeof t.serverMaxWindowBits==="number"&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==="number"&&!e.client_max_window_bits){return false}return true}));if(!s){throw new Error("None of the extension offers can be accepted")}if(t.serverNoContextTakeover){s.server_no_context_takeover=true}if(t.clientNoContextTakeover){s.client_no_context_takeover=true}if(typeof t.serverMaxWindowBits==="number"){s.server_max_window_bits=t.serverMaxWindowBits}if(typeof t.clientMaxWindowBits==="number"){s.client_max_window_bits=t.clientMaxWindowBits}else if(s.client_max_window_bits===true||t.clientMaxWindowBits===false){delete s.client_max_window_bits}return s}acceptAsClient(e){const t=e[0];if(this._options.clientNoContextTakeover===false&&t.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!t.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){t.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return t}normalizeParams(e){e.forEach((e=>{Object.keys(e).forEach((t=>{let s=e[t];if(s.length>1){throw new Error(`Parameter "${t}" must have only a single value`)}s=s[0];if(t==="client_max_window_bits"){if(s!==true){const e=+s;if(!Number.isInteger(e)||e<8||e>15){throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}s=e}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}}else if(t==="server_max_window_bits"){const e=+s;if(!Number.isInteger(e)||e<8||e>15){throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}s=e}else if(t==="client_no_context_takeover"||t==="server_no_context_takeover"){if(s!==true){throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}}else{throw new Error(`Unknown parameter "${t}"`)}e[t]=s}))}));return e}decompress(e,t,s){_.add((r=>{this._decompress(e,t,((e,t)=>{r();s(e,t)}))}))}compress(e,t,s){_.add((r=>{this._compress(e,t,((e,t)=>{r();s(e,t)}))}))}_decompress(e,t,s){const i=this._isServer?"client":"server";if(!this._inflate){const e=`${i}_max_window_bits`;const t=typeof this.params[e]!=="number"?r.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t});this._inflate[l]=this;this._inflate[f]=0;this._inflate[d]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[h]=s;this._inflate.write(e);if(t)this._inflate.write(c);this._inflate.flush((()=>{const e=this._inflate[u];if(e){this._inflate.close();this._inflate=null;s(e);return}const r=n.concat(this._inflate[d],this._inflate[f]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[f]=0;this._inflate[d]=[];if(t&&this.params[`${i}_no_context_takeover`]){this._inflate.reset()}}s(null,r)}))}_compress(e,t,s){const i=this._isServer?"server":"client";if(!this._deflate){const e=`${i}_max_window_bits`;const t=typeof this.params[e]!=="number"?r.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t});this._deflate[f]=0;this._deflate[d]=[];this._deflate.on("data",deflateOnData)}this._deflate[h]=s;this._deflate.write(e);this._deflate.flush(r.Z_SYNC_FLUSH,(()=>{if(!this._deflate){return}let e=n.concat(this._deflate[d],this._deflate[f]);if(t){e=new a(e.buffer,e.byteOffset,e.length-4)}this._deflate[h]=null;this._deflate[f]=0;this._deflate[d]=[];if(t&&this.params[`${i}_no_context_takeover`]){this._deflate.reset()}s(null,e)}))}}e.exports=PerMessageDeflate;function deflateOnData(e){this[d].push(e);this[f]+=e.length}function inflateOnData(e){this[f]+=e.length;if(this[l]._maxPayload<1||this[f]<=this[l]._maxPayload){this[d].push(e);return}this[u]=new RangeError("Max payload size exceeded");this[u].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[u][o]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(e){this[l]._inflate=null;e[o]=1007;this[h](e)}},997:(e,t,s)=>{"use strict";const{Writable:r}=s(781);const n=s(613);const{BINARY_TYPES:i,EMPTY_BUFFER:o,kStatusCode:a,kWebSocket:c}=s(547);const{concat:l,toArrayBuffer:f,unmask:h}=s(64);const{isValidStatusCode:d,isValidUTF8:u}=s(903);const _=Buffer[Symbol.species];const p=Promise.resolve();const m=typeof queueMicrotask==="function"?queueMicrotask:queueMicrotaskShim;const b=0;const k=1;const S=2;const y=3;const g=4;const E=5;const w=6;class Receiver extends r{constructor(e={}){super();this._allowSynchronousEvents=!!e.allowSynchronousEvents;this._binaryType=e.binaryType||i[0];this._extensions=e.extensions||{};this._isServer=!!e.isServer;this._maxPayload=e.maxPayload|0;this._skipUTF8Validation=!!e.skipUTF8Validation;this[c]=undefined;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=undefined;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._fragments=[];this._errored=false;this._loop=false;this._state=b}_write(e,t,s){if(this._opcode===8&&this._state==b)return s();this._bufferedBytes+=e.length;this._buffers.push(e);this.startLoop(s)}consume(e){this._bufferedBytes-=e;if(e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];this._buffers[0]=new _(t.buffer,t.byteOffset+e,t.length-e);return new _(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const s=this._buffers[0];const r=t.length-e;if(e>=s.length){t.set(this._buffers.shift(),r)}else{t.set(new Uint8Array(s.buffer,s.byteOffset,e),r);this._buffers[0]=new _(s.buffer,s.byteOffset+e,s.length-e)}e-=s.length}while(e>0);return t}startLoop(e){this._loop=true;do{switch(this._state){case b:this.getInfo(e);break;case k:this.getPayloadLength16(e);break;case S:this.getPayloadLength64(e);break;case y:this.getMask();break;case g:this.getData(e);break;case E:case w:this._loop=false;return}}while(this._loop);if(!this._errored)e()}getInfo(e){if(this._bufferedBytes<2){this._loop=false;return}const t=this.consume(2);if((t[0]&48)!==0){const t=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(t);return}const s=(t[0]&64)===64;if(s&&!this._extensions[n.extensionName]){const t=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(t);return}this._fin=(t[0]&128)===128;this._opcode=t[0]&15;this._payloadLength=t[1]&127;if(this._opcode===0){if(s){const t=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(t);return}if(!this._fragmented){const t=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const t=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");e(t);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const t=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");e(t);return}if(s){const t=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(t);return}}else{const t=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");e(t);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(t[1]&128)===128;if(this._isServer){if(!this._masked){const t=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");e(t);return}}else if(this._masked){const t=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");e(t);return}if(this._payloadLength===126)this._state=k;else if(this._payloadLength===127)this._state=S;else this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=false;return}const t=this.consume(8);const s=t.readUInt32BE(0);if(s>Math.pow(2,53-32)-1){const t=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(t);return}this._payloadLength=s*Math.pow(2,32)+t.readUInt32BE(4);this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const t=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}}if(this._masked)this._state=y;else this._state=g}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=g}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}t=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){h(t,this._mask)}}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=E;this.decompress(t,e);return}if(t.length){this._messageLength=this._totalPayloadLength;this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){const s=this._extensions[n.extensionName];s.decompress(e,this._fin,((e,s)=>{if(e)return t(e);if(s.length){this._messageLength+=s.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(e);return}this._fragments.push(s)}this.dataMessage(t);if(this._state===b)this.startLoop(t)}))}dataMessage(e){if(!this._fin){this._state=b;return}const t=this._messageLength;const s=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._fragments=[];if(this._opcode===2){let r;if(this._binaryType==="nodebuffer"){r=l(s,t)}else if(this._binaryType==="arraybuffer"){r=f(l(s,t))}else{r=s}if(this._state===E||this._allowSynchronousEvents){this.emit("message",r,true);this._state=b}else{this._state=w;m((()=>{this.emit("message",r,true);this._state=b;this.startLoop(e)}))}}else{const r=l(s,t);if(!this._skipUTF8Validation&&!u(r)){const t=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");e(t);return}if(this._state===E||this._allowSynchronousEvents){this.emit("message",r,false);this._state=b}else{this._state=w;m((()=>{this.emit("message",r,false);this._state=b;this.startLoop(e)}))}}}controlMessage(e,t){if(this._opcode===8){if(e.length===0){this._loop=false;this.emit("conclude",1005,o);this.end()}else{const s=e.readUInt16BE(0);if(!d(s)){const e=this.createError(RangeError,`invalid status code ${s}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");t(e);return}const r=new _(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!u(r)){const e=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");t(e);return}this._loop=false;this.emit("conclude",s,r);this.end()}this._state=b;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",e);this._state=b}else{this._state=w;m((()=>{this.emit(this._opcode===9?"ping":"pong",e);this._state=b;this.startLoop(t)}))}}createError(e,t,s,r,n){this._loop=false;this._errored=true;const i=new e(s?`Invalid WebSocket frame: ${t}`:t);Error.captureStackTrace(i,this.createError);i.code=n;i[a]=r;return i}}e.exports=Receiver;function queueMicrotaskShim(e){p.then(e).catch(throwErrorNextTick)}function throwError(e){throw e}function throwErrorNextTick(e){process.nextTick(throwError,e)}},345:(e,t,s)=>{"use strict";const{Duplex:r}=s(781);const{randomFillSync:n}=s(113);const i=s(613);const{EMPTY_BUFFER:o}=s(547);const{isValidStatusCode:a}=s(903);const{mask:c,toBuffer:l}=s(64);const f=Symbol("kByteLength");const h=Buffer.alloc(4);class Sender{constructor(e,t,s){this._extensions=t||{};if(s){this._generateMask=s;this._maskBuffer=Buffer.alloc(4)}this._socket=e;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._deflating=false;this._queue=[]}static frame(e,t){let s;let r=false;let i=2;let o=false;if(t.mask){s=t.maskBuffer||h;if(t.generateMask){t.generateMask(s)}else{n(s,0,4)}o=(s[0]|s[1]|s[2]|s[3])===0;i=6}let a;if(typeof e==="string"){if((!t.mask||o)&&t[f]!==undefined){a=t[f]}else{e=Buffer.from(e);a=e.length}}else{a=e.length;r=t.mask&&t.readOnly&&!o}let l=a;if(a>=65536){i+=8;l=127}else if(a>125){i+=2;l=126}const d=Buffer.allocUnsafe(r?a+i:i);d[0]=t.fin?t.opcode|128:t.opcode;if(t.rsv1)d[0]|=64;d[1]=l;if(l===126){d.writeUInt16BE(a,2)}else if(l===127){d[2]=d[3]=0;d.writeUIntBE(a,4,6)}if(!t.mask)return[d,e];d[1]|=128;d[i-4]=s[0];d[i-3]=s[1];d[i-2]=s[2];d[i-1]=s[3];if(o)return[d,e];if(r){c(e,s,d,i,a);return[d]}c(e,s,e,0,a);return[d,e]}close(e,t,s,r){let n;if(e===undefined){n=o}else if(typeof e!=="number"||!a(e)){throw new TypeError("First argument must be a valid error code number")}else if(t===undefined||!t.length){n=Buffer.allocUnsafe(2);n.writeUInt16BE(e,0)}else{const s=Buffer.byteLength(t);if(s>123){throw new RangeError("The message must not be greater than 123 bytes")}n=Buffer.allocUnsafe(2+s);n.writeUInt16BE(e,0);if(typeof t==="string"){n.write(t,2)}else{n.set(t,2)}}const i={[f]:n.length,fin:true,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,n,false,i,r])}else{this.sendFrame(Sender.frame(n,i),r)}}ping(e,t,s){let r;let n;if(typeof e==="string"){r=Buffer.byteLength(e);n=false}else{e=l(e);r=e.length;n=l.readOnly}if(r>125){throw new RangeError("The data size must not be greater than 125 bytes")}const i={[f]:r,fin:true,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,e,false,i,s])}else{this.sendFrame(Sender.frame(e,i),s)}}pong(e,t,s){let r;let n;if(typeof e==="string"){r=Buffer.byteLength(e);n=false}else{e=l(e);r=e.length;n=l.readOnly}if(r>125){throw new RangeError("The data size must not be greater than 125 bytes")}const i={[f]:r,fin:true,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,e,false,i,s])}else{this.sendFrame(Sender.frame(e,i),s)}}send(e,t,s){const r=this._extensions[i.extensionName];let n=t.binary?2:1;let o=t.compress;let a;let c;if(typeof e==="string"){a=Buffer.byteLength(e);c=false}else{e=l(e);a=e.length;c=l.readOnly}if(this._firstFragment){this._firstFragment=false;if(o&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]){o=a>=r._threshold}this._compress=o}else{o=false;n=0}if(t.fin)this._firstFragment=true;if(r){const r={[f]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:c,rsv1:o};if(this._deflating){this.enqueue([this.dispatch,e,this._compress,r,s])}else{this.dispatch(e,this._compress,r,s)}}else{this.sendFrame(Sender.frame(e,{[f]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:c,rsv1:false}),s)}}dispatch(e,t,s,r){if(!t){this.sendFrame(Sender.frame(e,s),r);return}const n=this._extensions[i.extensionName];this._bufferedBytes+=s[f];this._deflating=true;n.compress(e,s.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");if(typeof r==="function")r(e);for(let t=0;t<this._queue.length;t++){const s=this._queue[t];const r=s[s.length-1];if(typeof r==="function")r(e)}return}this._bufferedBytes-=s[f];this._deflating=false;s.readOnly=false;this.sendFrame(Sender.frame(t,s),r);this.dequeue()}))}dequeue(){while(!this._deflating&&this._queue.length){const e=this._queue.shift();this._bufferedBytes-=e[3][f];Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f];this._queue.push(e)}sendFrame(e,t){if(e.length===2){this._socket.cork();this._socket.write(e[0]);this._socket.write(e[1],t);this._socket.uncork()}else{this._socket.write(e[0],t)}}}e.exports=Sender},334:(e,t,s)=>{"use strict";const{Duplex:r}=s(781);function emitClose(e){e.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(e){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",e)}}function createWebSocketStream(e,t){let s=true;const n=new r({...t,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});e.on("message",(function message(t,s){const r=!s&&n._readableState.objectMode?t.toString():t;if(!n.push(r))e.pause()}));e.once("error",(function error(e){if(n.destroyed)return;s=false;n.destroy(e)}));e.once("close",(function close(){if(n.destroyed)return;n.push(null)}));n._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t);process.nextTick(emitClose,n);return}let i=false;e.once("error",(function error(e){i=true;r(e)}));e.once("close",(function close(){if(!i)r(t);process.nextTick(emitClose,n)}));if(s)e.terminate()};n._final=function(t){if(e.readyState===e.CONNECTING){e.once("open",(function open(){n._final(t)}));return}if(e._socket===null)return;if(e._socket._writableState.finished){t();if(n._readableState.endEmitted)n.destroy()}else{e._socket.once("finish",(function finish(){t()}));e.close()}};n._read=function(){if(e.isPaused)e.resume()};n._write=function(t,s,r){if(e.readyState===e.CONNECTING){e.once("open",(function open(){n._write(t,s,r)}));return}e.send(t,r)};n.on("end",duplexOnEnd);n.on("error",duplexOnError);return n}e.exports=createWebSocketStream},320:(e,t,s)=>{"use strict";const{tokenChars:r}=s(903);function parse(e){const t=new Set;let s=-1;let n=-1;let i=0;for(i;i<e.length;i++){const o=e.charCodeAt(i);if(n===-1&&r[o]===1){if(s===-1)s=i}else if(i!==0&&(o===32||o===9)){if(n===-1&&s!==-1)n=i}else if(o===44){if(s===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1)n=i;const r=e.slice(s,n);if(t.has(r)){throw new SyntaxError(`The "${r}" subprotocol is duplicated`)}t.add(r);s=n=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(s===-1||n!==-1){throw new SyntaxError("Unexpected end of input")}const o=e.slice(s,i);if(t.has(o)){throw new SyntaxError(`The "${o}" subprotocol is duplicated`)}t.add(o);return t}e.exports={parse:parse}},903:(e,t,s)=>{"use strict";const{isUtf8:r}=s(300);const n=[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 isValidStatusCode(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function _isValidUTF8(e){const t=e.length;let s=0;while(s<t){if((e[s]&128)===0){s++}else if((e[s]&224)===192){if(s+1===t||(e[s+1]&192)!==128||(e[s]&254)===192){return false}s+=2}else if((e[s]&240)===224){if(s+2>=t||(e[s+1]&192)!==128||(e[s+2]&192)!==128||e[s]===224&&(e[s+1]&224)===128||e[s]===237&&(e[s+1]&224)===160){return false}s+=3}else if((e[s]&248)===240){if(s+3>=t||(e[s+1]&192)!==128||(e[s+2]&192)!==128||(e[s+3]&192)!==128||e[s]===240&&(e[s+1]&240)===128||e[s]===244&&e[s+1]>143||e[s]>244){return false}s+=4}else{return false}}return true}e.exports={isValidStatusCode:isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars:n};if(r){e.exports.isValidUTF8=function(e){return e.length<24?_isValidUTF8(e):r(e)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const t=s(177);e.exports.isValidUTF8=function(e){return e.length<32?_isValidUTF8(e):t(e)}}catch(e){}}},69:(e,t,s)=>{"use strict";const r=s(361);const n=s(685);const{Duplex:i}=s(781);const{createHash:o}=s(113);const a=s(321);const c=s(613);const l=s(320);const f=s(885);const{GUID:h,kWebSocket:d}=s(547);const u=/^[+/0-9A-Za-z]{22}==$/;const _=0;const p=1;const m=2;class WebSocketServer extends r{constructor(e,t){super();e={allowSynchronousEvents:false,autoPong:true,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket:f,...e};if(e.port==null&&!e.server&&!e.noServer||e.port!=null&&(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(e.port!=null){this._server=n.createServer(((e,t)=>{const s=n.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"});t.end(s)}));this._server.listen(e.port,e.host,e.backlog,t)}else if(e.server){this._server=e.server}if(this._server){const e=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,r)=>{this.handleUpgrade(t,s,r,e)}})}if(e.perMessageDeflate===true)e.perMessageDeflate={};if(e.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=e;this._state=_}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(e){if(this._state===m){if(e){this.once("close",(()=>{e(new Error("The server is not running"))}))}process.nextTick(emitClose,this);return}if(e)this.once("close",e);if(this._state===p)return;this._state=p;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const e=this._server;this._removeListeners();this._removeListeners=this._server=null;e.close((()=>{emitClose(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");const s=t!==-1?e.url.slice(0,t):e.url;if(s!==this.options.path)return false}return true}handleUpgrade(e,t,s,r){t.on("error",socketOnError);const n=e.headers["sec-websocket-key"];const i=+e.headers["sec-websocket-version"];if(e.method!=="GET"){const s="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,e,t,405,s);return}if(e.headers.upgrade.toLowerCase()!=="websocket"){const s="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,e,t,400,s);return}if(!n||!u.test(n)){const s="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,e,t,400,s);return}if(i!==8&&i!==13){const s="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,e,t,400,s);return}if(!this.shouldHandle(e)){abortHandshake(t,400);return}const o=e.headers["sec-websocket-protocol"];let f=new Set;if(o!==undefined){try{f=l.parse(o)}catch(s){const r="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,e,t,400,r);return}}const h=e.headers["sec-websocket-extensions"];const d={};if(this.options.perMessageDeflate&&h!==undefined){const s=new c(this.options.perMessageDeflate,true,this.options.maxPayload);try{const e=a.parse(h);if(e[c.extensionName]){s.accept(e[c.extensionName]);d[c.extensionName]=s}}catch(s){const r="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,e,t,400,r);return}}if(this.options.verifyClient){const o={origin:e.headers[`${i===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(o,((i,o,a,c)=>{if(!i){return abortHandshake(t,o||401,a,c)}this.completeUpgrade(d,n,f,e,t,s,r)}));return}if(!this.options.verifyClient(o))return abortHandshake(t,401)}this.completeUpgrade(d,n,f,e,t,s,r)}completeUpgrade(e,t,s,r,n,i,l){if(!n.readable||!n.writable)return n.destroy();if(n[d]){throw new Error("server.handleUpgrade() was called more than once with the same "+"socket, possibly due to a misconfiguration")}if(this._state>_)return abortHandshake(n,503);const f=o("sha1").update(t+h).digest("base64");const u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${f}`];const p=new this.options.WebSocket(null,undefined,this.options);if(s.size){const e=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;if(e){u.push(`Sec-WebSocket-Protocol: ${e}`);p._protocol=e}}if(e[c.extensionName]){const t=e[c.extensionName].params;const s=a.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${s}`);p._extensions=e}this.emit("headers",u,r);n.write(u.concat("\r\n").join("\r\n"));n.removeListener("error",socketOnError);p.setSocket(n,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(p);p.on("close",(()=>{this.clients.delete(p);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}}))}l(p,r)}}e.exports=WebSocketServer;function addListeners(e,t){for(const s of Object.keys(t))e.on(s,t[s]);return function removeListeners(){for(const s of Object.keys(t)){e.removeListener(s,t[s])}}}function emitClose(e){e._state=m;e.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(e,t,s,r){s=s||n.STATUS_CODES[t];r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r};e.once("finish",e.destroy);e.end(`HTTP/1.1 ${t} ${n.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+s)}function abortHandshakeOrEmitwsClientError(e,t,s,r,n){if(e.listenerCount("wsClientError")){const r=new Error(n);Error.captureStackTrace(r,abortHandshakeOrEmitwsClientError);e.emit("wsClientError",r,s,t)}else{abortHandshake(s,r,n)}}},885:(e,t,s)=>{"use strict";const r=s(361);const n=s(687);const i=s(685);const o=s(808);const a=s(404);const{randomBytes:c,createHash:l}=s(113);const{Duplex:f,Readable:h}=s(781);const{URL:d}=s(310);const u=s(613);const _=s(997);const p=s(345);const{BINARY_TYPES:m,EMPTY_BUFFER:b,GUID:k,kForOnEventAttribute:S,kListener:y,kStatusCode:g,kWebSocket:E,NOOP:w}=s(547);const{EventTarget:{addEventListener:v,removeEventListener:x}}=s(874);const{format:O,parse:C}=s(321);const{toBuffer:T}=s(64);const L=30*1e3;const N=Symbol("kAborted");const P=[8,13];const W=["CONNECTING","OPEN","CLOSING","CLOSED"];const B=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends r{constructor(e,t,s){super();this._binaryType=m[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=b;this._closeTimer=null;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(e!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(t===undefined){t=[]}else if(!Array.isArray(t)){if(typeof t==="object"&&t!==null){s=t;t=[]}else{t=[t]}}initAsClient(this,e,t,s)}else{this._autoPong=s.autoPong;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(e){if(!m.includes(e))return;this._binaryType=e;if(this._receiver)this._receiver._binaryType=e}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}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,s){const r=new _({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation});this._sender=new p(e,this._extensions,s.generateMask);this._receiver=r;this._socket=e;r[E]=this;e[E]=this;r.on("conclude",receiverOnConclude);r.on("drain",receiverOnDrain);r.on("error",receiverOnError);r.on("message",receiverOnMessage);r.on("ping",receiverOnPing);r.on("pong",receiverOnPong);if(e.setTimeout)e.setTimeout(0);if(e.setNoDelay)e.setNoDelay();if(t.length>0)e.unshift(t);e.on("close",socketOnClose);e.on("data",socketOnData);e.on("end",socketOnEnd);e.on("error",socketOnError);this._readyState=WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[u.extensionName]){this._extensions[u.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";abortHandshake(this,this._req,e);return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=WebSocket.CLOSING;this._sender.close(e,t,!this._isServer,(e=>{if(e)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}}));this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),L)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(e,t,s){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof e==="function"){s=e;e=t=undefined}else if(typeof t==="function"){s=t;t=undefined}if(typeof e==="number")e=e.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,e,s);return}if(t===undefined)t=!this._isServer;this._sender.ping(e||b,t,s)}pong(e,t,s){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof e==="function"){s=e;e=t=undefined}else if(typeof t==="function"){s=t;t=undefined}if(typeof e==="number")e=e.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,e,s);return}if(t===undefined)t=!this._isServer;this._sender.pong(e||b,t,s)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(e,t,s){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof t==="function"){s=t;t={}}if(typeof e==="number")e=e.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,e,s);return}const r={binary:typeof e!=="string",mask:!this._isServer,compress:true,fin:true,...t};if(!this._extensions[u.extensionName]){r.compress=false}this._sender.send(e||b,r,s)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";abortHandshake(this,this._req,e);return}if(this._socket){this._readyState=WebSocket.CLOSING;this._socket.destroy()}}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:true,value:W.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:true,value:W.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:true,value:W.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:true,value:W.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:true,value:W.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:true,value:W.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:true,value:W.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:true,value:W.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(WebSocket.prototype,e,{enumerable:true})}));["open","error","close","message"].forEach((e=>{Object.defineProperty(WebSocket.prototype,`on${e}`,{enumerable:true,get(){for(const t of this.listeners(e)){if(t[S])return t[y]}return null},set(t){for(const t of this.listeners(e)){if(t[S]){this.removeListener(e,t);break}}if(typeof t!=="function")return;this.addEventListener(e,t,{[S]:true})}})}));WebSocket.prototype.addEventListener=v;WebSocket.prototype.removeEventListener=x;e.exports=WebSocket;function initAsClient(e,t,s,r){const o={allowSynchronousEvents:false,autoPong:true,protocolVersion:P[1],maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...r,createConnection:undefined,socketPath:undefined,hostname:undefined,protocol:undefined,timeout:undefined,method:"GET",host:undefined,path:undefined,port:undefined};e._autoPong=o.autoPong;if(!P.includes(o.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} `+`(supported versions: ${P.join(", ")})`)}let a;if(t instanceof d){a=t}else{try{a=new d(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}}if(a.protocol==="http:"){a.protocol="ws:"}else if(a.protocol==="https:"){a.protocol="wss:"}e._url=a.href;const f=a.protocol==="wss:";const h=a.protocol==="ws+unix:";let _;if(a.protocol!=="ws:"&&!f&&!h){_='The URL\'s protocol must be one of "ws:", "wss:", '+'"http:", "https", or "ws+unix:"'}else if(h&&!a.pathname){_="The URL's pathname is empty"}else if(a.hash){_="The URL contains a fragment identifier"}if(_){const t=new SyntaxError(_);if(e._redirects===0){throw t}else{emitErrorAndClose(e,t);return}}const p=f?443:80;const m=c(16).toString("base64");const b=f?n.request:i.request;const S=new Set;let y;o.createConnection=f?tlsConnect:netConnect;o.defaultPort=o.defaultPort||p;o.port=a.port||p;o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname;o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"};o.path=a.pathname+a.search;o.timeout=o.handshakeTimeout;if(o.perMessageDeflate){y=new u(o.perMessageDeflate!==true?o.perMessageDeflate:{},false,o.maxPayload);o.headers["Sec-WebSocket-Extensions"]=O({[u.extensionName]:y.offer()})}if(s.length){for(const e of s){if(typeof e!=="string"||!B.test(e)||S.has(e)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}S.add(e)}o.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(o.origin){if(o.protocolVersion<13){o.headers["Sec-WebSocket-Origin"]=o.origin}else{o.headers.Origin=o.origin}}if(a.username||a.password){o.auth=`${a.username}:${a.password}`}if(h){const e=o.path.split(":");o.socketPath=e[0];o.path=e[1]}let g;if(o.followRedirects){if(e._redirects===0){e._originalIpc=h;e._originalSecure=f;e._originalHostOrSocketPath=h?o.socketPath:a.host;const t=r&&r.headers;r={...r,headers:{}};if(t){for(const[e,s]of Object.entries(t)){r.headers[e.toLowerCase()]=s}}}else if(e.listenerCount("redirect")===0){const t=h?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:false:e._originalIpc?false:a.host===e._originalHostOrSocketPath;if(!t||e._originalSecure&&!f){delete o.headers.authorization;delete o.headers.cookie;if(!t)delete o.headers.host;o.auth=undefined}}if(o.auth&&!r.headers.authorization){r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")}g=e._req=b(o);if(e._redirects){e.emit("redirect",e.url,g)}}else{g=e._req=b(o)}if(o.timeout){g.on("timeout",(()=>{abortHandshake(e,g,"Opening handshake has timed out")}))}g.on("error",(t=>{if(g===null||g[N])return;g=e._req=null;emitErrorAndClose(e,t)}));g.on("response",(n=>{const i=n.headers.location;const a=n.statusCode;if(i&&o.followRedirects&&a>=300&&a<400){if(++e._redirects>o.maxRedirects){abortHandshake(e,g,"Maximum redirects exceeded");return}g.abort();let n;try{n=new d(i,t)}catch(t){const s=new SyntaxError(`Invalid URL: ${i}`);emitErrorAndClose(e,s);return}initAsClient(e,n,s,r)}else if(!e.emit("unexpected-response",g,n)){abortHandshake(e,g,`Unexpected server response: ${n.statusCode}`)}}));g.on("upgrade",((t,s,r)=>{e.emit("upgrade",t);if(e.readyState!==WebSocket.CONNECTING)return;g=e._req=null;if(t.headers.upgrade.toLowerCase()!=="websocket"){abortHandshake(e,s,"Invalid Upgrade header");return}const n=l("sha1").update(m+k).digest("base64");if(t.headers["sec-websocket-accept"]!==n){abortHandshake(e,s,"Invalid Sec-WebSocket-Accept header");return}const i=t.headers["sec-websocket-protocol"];let a;if(i!==undefined){if(!S.size){a="Server sent a subprotocol but none was requested"}else if(!S.has(i)){a="Server sent an invalid subprotocol"}}else if(S.size){a="Server sent no subprotocol"}if(a){abortHandshake(e,s,a);return}if(i)e._protocol=i;const c=t.headers["sec-websocket-extensions"];if(c!==undefined){if(!y){const t="Server sent a Sec-WebSocket-Extensions header but no extension "+"was requested";abortHandshake(e,s,t);return}let t;try{t=C(c)}catch(t){const r="Invalid Sec-WebSocket-Extensions header";abortHandshake(e,s,r);return}const r=Object.keys(t);if(r.length!==1||r[0]!==u.extensionName){const t="Server indicated an extension that was not requested";abortHandshake(e,s,t);return}try{y.accept(t[u.extensionName])}catch(t){const r="Invalid Sec-WebSocket-Extensions header";abortHandshake(e,s,r);return}e._extensions[u.extensionName]=y}e.setSocket(s,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}));if(o.finishRequest){o.finishRequest(g,e)}else{g.end()}}function emitErrorAndClose(e,t){e._readyState=WebSocket.CLOSING;e.emit("error",t);e.emitClose()}function netConnect(e){e.path=e.socketPath;return o.connect(e)}function tlsConnect(e){e.path=undefined;if(!e.servername&&e.servername!==""){e.servername=o.isIP(e.host)?"":e.host}return a.connect(e)}function abortHandshake(e,t,s){e._readyState=WebSocket.CLOSING;const r=new Error(s);Error.captureStackTrace(r,abortHandshake);if(t.setHeader){t[N]=true;t.abort();if(t.socket&&!t.socket.destroyed){t.socket.destroy()}process.nextTick(emitErrorAndClose,e,r)}else{t.destroy(r);t.once("error",e.emit.bind(e,"error"));t.once("close",e.emitClose.bind(e))}}function sendAfterClose(e,t,s){if(t){const s=T(t).length;if(e._socket)e._sender._bufferedBytes+=s;else e._bufferedAmount+=s}if(s){const t=new Error(`WebSocket is not open: readyState ${e.readyState} `+`(${W[e.readyState]})`);process.nextTick(s,t)}}function receiverOnConclude(e,t){const s=this[E];s._closeFrameReceived=true;s._closeMessage=t;s._closeCode=e;if(s._socket[E]===undefined)return;s._socket.removeListener("data",socketOnData);process.nextTick(resume,s._socket);if(e===1005)s.close();else s.close(e,t)}function receiverOnDrain(){const e=this[E];if(!e.isPaused)e._socket.resume()}function receiverOnError(e){const t=this[E];if(t._socket[E]!==undefined){t._socket.removeListener("data",socketOnData);process.nextTick(resume,t._socket);t.close(e[g])}t.emit("error",e)}function receiverOnFinish(){this[E].emitClose()}function receiverOnMessage(e,t){this[E].emit("message",e,t)}function receiverOnPing(e){const t=this[E];if(t._autoPong)t.pong(e,!this._isServer,w);t.emit("ping",e)}function receiverOnPong(e){this[E].emit("pong",e)}function resume(e){e.resume()}function socketOnClose(){const e=this[E];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);e._readyState=WebSocket.CLOSING;let t;if(!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null){e._receiver.write(t)}e._receiver.end();this[E]=undefined;clearTimeout(e._closeTimer);if(e._receiver._writableState.finished||e._receiver._writableState.errorEmitted){e.emitClose()}else{e._receiver.on("error",receiverOnFinish);e._receiver.on("finish",receiverOnFinish)}}function socketOnData(e){if(!this[E]._receiver.write(e)){this.pause()}}function socketOnEnd(){const e=this[E];e._readyState=WebSocket.CLOSING;e._receiver.end();this.end()}function socketOnError(){const e=this[E];this.removeListener("error",socketOnError);this.on("error",w);if(e){e._readyState=WebSocket.CLOSING;this.destroy()}}},471:module=>{module.exports=eval("require")("bufferutil")},177:module=>{module.exports=eval("require")("utf-8-validate")},300:e=>{"use strict";e.exports=require("buffer")},113:e=>{"use strict";e.exports=require("crypto")},361:e=>{"use strict";e.exports=require("events")},685:e=>{"use strict";e.exports=require("http")},687:e=>{"use strict";e.exports=require("https")},808:e=>{"use strict";e.exports=require("net")},781:e=>{"use strict";e.exports=require("stream")},404:e=>{"use strict";e.exports=require("tls")},310:e=>{"use strict";e.exports=require("url")},796:e=>{"use strict";e.exports=require("zlib")}};var __webpack_module_cache__={};function __nccwpck_require__(e){var t=__webpack_module_cache__[e];if(t!==undefined){return t.exports}var s=__webpack_module_cache__[e]={exports:{}};var r=true;try{__webpack_modules__[e](s,s.exports,__nccwpck_require__);r=false}finally{if(r)delete __webpack_module_cache__[e]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(201);module.exports=__webpack_exports__})();
1
+ /******/ (() => { // webpackBootstrap
2
+ /******/ var __webpack_modules__ = ({
3
+
4
+ /***/ 514:
5
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
6
+
7
+ "use strict";
8
+
9
+
10
+ const WebSocket = __nccwpck_require__(462);
11
+
12
+ WebSocket.createWebSocketStream = __nccwpck_require__(972);
13
+ WebSocket.Server = __nccwpck_require__(51);
14
+ WebSocket.Receiver = __nccwpck_require__(663);
15
+ WebSocket.Sender = __nccwpck_require__(19);
16
+
17
+ WebSocket.WebSocket = WebSocket;
18
+ WebSocket.WebSocketServer = WebSocket.Server;
19
+
20
+ module.exports = WebSocket;
21
+
22
+
23
+ /***/ }),
24
+
25
+ /***/ 820:
26
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
27
+
28
+ "use strict";
29
+
30
+
31
+ const { EMPTY_BUFFER } = __nccwpck_require__(862);
32
+
33
+ const FastBuffer = Buffer[Symbol.species];
34
+
35
+ /**
36
+ * Merges an array of buffers into a new buffer.
37
+ *
38
+ * @param {Buffer[]} list The array of buffers to concat
39
+ * @param {Number} totalLength The total length of buffers in the list
40
+ * @return {Buffer} The resulting buffer
41
+ * @public
42
+ */
43
+ function concat(list, totalLength) {
44
+ if (list.length === 0) return EMPTY_BUFFER;
45
+ if (list.length === 1) return list[0];
46
+
47
+ const target = Buffer.allocUnsafe(totalLength);
48
+ let offset = 0;
49
+
50
+ for (let i = 0; i < list.length; i++) {
51
+ const buf = list[i];
52
+ target.set(buf, offset);
53
+ offset += buf.length;
54
+ }
55
+
56
+ if (offset < totalLength) {
57
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
58
+ }
59
+
60
+ return target;
61
+ }
62
+
63
+ /**
64
+ * Masks a buffer using the given mask.
65
+ *
66
+ * @param {Buffer} source The buffer to mask
67
+ * @param {Buffer} mask The mask to use
68
+ * @param {Buffer} output The buffer where to store the result
69
+ * @param {Number} offset The offset at which to start writing
70
+ * @param {Number} length The number of bytes to mask.
71
+ * @public
72
+ */
73
+ function _mask(source, mask, output, offset, length) {
74
+ for (let i = 0; i < length; i++) {
75
+ output[offset + i] = source[i] ^ mask[i & 3];
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Unmasks a buffer using the given mask.
81
+ *
82
+ * @param {Buffer} buffer The buffer to unmask
83
+ * @param {Buffer} mask The mask to use
84
+ * @public
85
+ */
86
+ function _unmask(buffer, mask) {
87
+ for (let i = 0; i < buffer.length; i++) {
88
+ buffer[i] ^= mask[i & 3];
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Converts a buffer to an `ArrayBuffer`.
94
+ *
95
+ * @param {Buffer} buf The buffer to convert
96
+ * @return {ArrayBuffer} Converted buffer
97
+ * @public
98
+ */
99
+ function toArrayBuffer(buf) {
100
+ if (buf.length === buf.buffer.byteLength) {
101
+ return buf.buffer;
102
+ }
103
+
104
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
105
+ }
106
+
107
+ /**
108
+ * Converts `data` to a `Buffer`.
109
+ *
110
+ * @param {*} data The data to convert
111
+ * @return {Buffer} The buffer
112
+ * @throws {TypeError}
113
+ * @public
114
+ */
115
+ function toBuffer(data) {
116
+ toBuffer.readOnly = true;
117
+
118
+ if (Buffer.isBuffer(data)) return data;
119
+
120
+ let buf;
121
+
122
+ if (data instanceof ArrayBuffer) {
123
+ buf = new FastBuffer(data);
124
+ } else if (ArrayBuffer.isView(data)) {
125
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
126
+ } else {
127
+ buf = Buffer.from(data);
128
+ toBuffer.readOnly = false;
129
+ }
130
+
131
+ return buf;
132
+ }
133
+
134
+ module.exports = {
135
+ concat,
136
+ mask: _mask,
137
+ toArrayBuffer,
138
+ toBuffer,
139
+ unmask: _unmask
140
+ };
141
+
142
+ /* istanbul ignore else */
143
+ if (!process.env.WS_NO_BUFFER_UTIL) {
144
+ try {
145
+ const bufferUtil = __nccwpck_require__(471);
146
+
147
+ module.exports.mask = function (source, mask, output, offset, length) {
148
+ if (length < 48) _mask(source, mask, output, offset, length);
149
+ else bufferUtil.mask(source, mask, output, offset, length);
150
+ };
151
+
152
+ module.exports.unmask = function (buffer, mask) {
153
+ if (buffer.length < 32) _unmask(buffer, mask);
154
+ else bufferUtil.unmask(buffer, mask);
155
+ };
156
+ } catch (e) {
157
+ // Continue regardless of the error.
158
+ }
159
+ }
160
+
161
+
162
+ /***/ }),
163
+
164
+ /***/ 862:
165
+ /***/ ((module) => {
166
+
167
+ "use strict";
168
+
169
+
170
+ module.exports = {
171
+ BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
172
+ EMPTY_BUFFER: Buffer.alloc(0),
173
+ GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
174
+ kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
175
+ kListener: Symbol('kListener'),
176
+ kStatusCode: Symbol('status-code'),
177
+ kWebSocket: Symbol('websocket'),
178
+ NOOP: () => {}
179
+ };
180
+
181
+
182
+ /***/ }),
183
+
184
+ /***/ 360:
185
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
186
+
187
+ "use strict";
188
+
189
+
190
+ const { kForOnEventAttribute, kListener } = __nccwpck_require__(862);
191
+
192
+ const kCode = Symbol('kCode');
193
+ const kData = Symbol('kData');
194
+ const kError = Symbol('kError');
195
+ const kMessage = Symbol('kMessage');
196
+ const kReason = Symbol('kReason');
197
+ const kTarget = Symbol('kTarget');
198
+ const kType = Symbol('kType');
199
+ const kWasClean = Symbol('kWasClean');
200
+
201
+ /**
202
+ * Class representing an event.
203
+ */
204
+ class Event {
205
+ /**
206
+ * Create a new `Event`.
207
+ *
208
+ * @param {String} type The name of the event
209
+ * @throws {TypeError} If the `type` argument is not specified
210
+ */
211
+ constructor(type) {
212
+ this[kTarget] = null;
213
+ this[kType] = type;
214
+ }
215
+
216
+ /**
217
+ * @type {*}
218
+ */
219
+ get target() {
220
+ return this[kTarget];
221
+ }
222
+
223
+ /**
224
+ * @type {String}
225
+ */
226
+ get type() {
227
+ return this[kType];
228
+ }
229
+ }
230
+
231
+ Object.defineProperty(Event.prototype, 'target', { enumerable: true });
232
+ Object.defineProperty(Event.prototype, 'type', { enumerable: true });
233
+
234
+ /**
235
+ * Class representing a close event.
236
+ *
237
+ * @extends Event
238
+ */
239
+ class CloseEvent extends Event {
240
+ /**
241
+ * Create a new `CloseEvent`.
242
+ *
243
+ * @param {String} type The name of the event
244
+ * @param {Object} [options] A dictionary object that allows for setting
245
+ * attributes via object members of the same name
246
+ * @param {Number} [options.code=0] The status code explaining why the
247
+ * connection was closed
248
+ * @param {String} [options.reason=''] A human-readable string explaining why
249
+ * the connection was closed
250
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
251
+ * connection was cleanly closed
252
+ */
253
+ constructor(type, options = {}) {
254
+ super(type);
255
+
256
+ this[kCode] = options.code === undefined ? 0 : options.code;
257
+ this[kReason] = options.reason === undefined ? '' : options.reason;
258
+ this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
259
+ }
260
+
261
+ /**
262
+ * @type {Number}
263
+ */
264
+ get code() {
265
+ return this[kCode];
266
+ }
267
+
268
+ /**
269
+ * @type {String}
270
+ */
271
+ get reason() {
272
+ return this[kReason];
273
+ }
274
+
275
+ /**
276
+ * @type {Boolean}
277
+ */
278
+ get wasClean() {
279
+ return this[kWasClean];
280
+ }
281
+ }
282
+
283
+ Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
284
+ Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
285
+ Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
286
+
287
+ /**
288
+ * Class representing an error event.
289
+ *
290
+ * @extends Event
291
+ */
292
+ class ErrorEvent extends Event {
293
+ /**
294
+ * Create a new `ErrorEvent`.
295
+ *
296
+ * @param {String} type The name of the event
297
+ * @param {Object} [options] A dictionary object that allows for setting
298
+ * attributes via object members of the same name
299
+ * @param {*} [options.error=null] The error that generated this event
300
+ * @param {String} [options.message=''] The error message
301
+ */
302
+ constructor(type, options = {}) {
303
+ super(type);
304
+
305
+ this[kError] = options.error === undefined ? null : options.error;
306
+ this[kMessage] = options.message === undefined ? '' : options.message;
307
+ }
308
+
309
+ /**
310
+ * @type {*}
311
+ */
312
+ get error() {
313
+ return this[kError];
314
+ }
315
+
316
+ /**
317
+ * @type {String}
318
+ */
319
+ get message() {
320
+ return this[kMessage];
321
+ }
322
+ }
323
+
324
+ Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
325
+ Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
326
+
327
+ /**
328
+ * Class representing a message event.
329
+ *
330
+ * @extends Event
331
+ */
332
+ class MessageEvent extends Event {
333
+ /**
334
+ * Create a new `MessageEvent`.
335
+ *
336
+ * @param {String} type The name of the event
337
+ * @param {Object} [options] A dictionary object that allows for setting
338
+ * attributes via object members of the same name
339
+ * @param {*} [options.data=null] The message content
340
+ */
341
+ constructor(type, options = {}) {
342
+ super(type);
343
+
344
+ this[kData] = options.data === undefined ? null : options.data;
345
+ }
346
+
347
+ /**
348
+ * @type {*}
349
+ */
350
+ get data() {
351
+ return this[kData];
352
+ }
353
+ }
354
+
355
+ Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
356
+
357
+ /**
358
+ * This provides methods for emulating the `EventTarget` interface. It's not
359
+ * meant to be used directly.
360
+ *
361
+ * @mixin
362
+ */
363
+ const EventTarget = {
364
+ /**
365
+ * Register an event listener.
366
+ *
367
+ * @param {String} type A string representing the event type to listen for
368
+ * @param {(Function|Object)} handler The listener to add
369
+ * @param {Object} [options] An options object specifies characteristics about
370
+ * the event listener
371
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
372
+ * listener should be invoked at most once after being added. If `true`,
373
+ * the listener would be automatically removed when invoked.
374
+ * @public
375
+ */
376
+ addEventListener(type, handler, options = {}) {
377
+ for (const listener of this.listeners(type)) {
378
+ if (
379
+ !options[kForOnEventAttribute] &&
380
+ listener[kListener] === handler &&
381
+ !listener[kForOnEventAttribute]
382
+ ) {
383
+ return;
384
+ }
385
+ }
386
+
387
+ let wrapper;
388
+
389
+ if (type === 'message') {
390
+ wrapper = function onMessage(data, isBinary) {
391
+ const event = new MessageEvent('message', {
392
+ data: isBinary ? data : data.toString()
393
+ });
394
+
395
+ event[kTarget] = this;
396
+ callListener(handler, this, event);
397
+ };
398
+ } else if (type === 'close') {
399
+ wrapper = function onClose(code, message) {
400
+ const event = new CloseEvent('close', {
401
+ code,
402
+ reason: message.toString(),
403
+ wasClean: this._closeFrameReceived && this._closeFrameSent
404
+ });
405
+
406
+ event[kTarget] = this;
407
+ callListener(handler, this, event);
408
+ };
409
+ } else if (type === 'error') {
410
+ wrapper = function onError(error) {
411
+ const event = new ErrorEvent('error', {
412
+ error,
413
+ message: error.message
414
+ });
415
+
416
+ event[kTarget] = this;
417
+ callListener(handler, this, event);
418
+ };
419
+ } else if (type === 'open') {
420
+ wrapper = function onOpen() {
421
+ const event = new Event('open');
422
+
423
+ event[kTarget] = this;
424
+ callListener(handler, this, event);
425
+ };
426
+ } else {
427
+ return;
428
+ }
429
+
430
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
431
+ wrapper[kListener] = handler;
432
+
433
+ if (options.once) {
434
+ this.once(type, wrapper);
435
+ } else {
436
+ this.on(type, wrapper);
437
+ }
438
+ },
439
+
440
+ /**
441
+ * Remove an event listener.
442
+ *
443
+ * @param {String} type A string representing the event type to remove
444
+ * @param {(Function|Object)} handler The listener to remove
445
+ * @public
446
+ */
447
+ removeEventListener(type, handler) {
448
+ for (const listener of this.listeners(type)) {
449
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
450
+ this.removeListener(type, listener);
451
+ break;
452
+ }
453
+ }
454
+ }
455
+ };
456
+
457
+ module.exports = {
458
+ CloseEvent,
459
+ ErrorEvent,
460
+ Event,
461
+ EventTarget,
462
+ MessageEvent
463
+ };
464
+
465
+ /**
466
+ * Call an event listener
467
+ *
468
+ * @param {(Function|Object)} listener The listener to call
469
+ * @param {*} thisArg The value to use as `this`` when calling the listener
470
+ * @param {Event} event The event to pass to the listener
471
+ * @private
472
+ */
473
+ function callListener(listener, thisArg, event) {
474
+ if (typeof listener === 'object' && listener.handleEvent) {
475
+ listener.handleEvent.call(listener, event);
476
+ } else {
477
+ listener.call(thisArg, event);
478
+ }
479
+ }
480
+
481
+
482
+ /***/ }),
483
+
484
+ /***/ 252:
485
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
486
+
487
+ "use strict";
488
+
489
+
490
+ const { tokenChars } = __nccwpck_require__(23);
491
+
492
+ /**
493
+ * Adds an offer to the map of extension offers or a parameter to the map of
494
+ * parameters.
495
+ *
496
+ * @param {Object} dest The map of extension offers or parameters
497
+ * @param {String} name The extension or parameter name
498
+ * @param {(Object|Boolean|String)} elem The extension parameters or the
499
+ * parameter value
500
+ * @private
501
+ */
502
+ function push(dest, name, elem) {
503
+ if (dest[name] === undefined) dest[name] = [elem];
504
+ else dest[name].push(elem);
505
+ }
506
+
507
+ /**
508
+ * Parses the `Sec-WebSocket-Extensions` header into an object.
509
+ *
510
+ * @param {String} header The field value of the header
511
+ * @return {Object} The parsed object
512
+ * @public
513
+ */
514
+ function parse(header) {
515
+ const offers = Object.create(null);
516
+ let params = Object.create(null);
517
+ let mustUnescape = false;
518
+ let isEscaping = false;
519
+ let inQuotes = false;
520
+ let extensionName;
521
+ let paramName;
522
+ let start = -1;
523
+ let code = -1;
524
+ let end = -1;
525
+ let i = 0;
526
+
527
+ for (; i < header.length; i++) {
528
+ code = header.charCodeAt(i);
529
+
530
+ if (extensionName === undefined) {
531
+ if (end === -1 && tokenChars[code] === 1) {
532
+ if (start === -1) start = i;
533
+ } else if (
534
+ i !== 0 &&
535
+ (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
536
+ ) {
537
+ if (end === -1 && start !== -1) end = i;
538
+ } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
539
+ if (start === -1) {
540
+ throw new SyntaxError(`Unexpected character at index ${i}`);
541
+ }
542
+
543
+ if (end === -1) end = i;
544
+ const name = header.slice(start, end);
545
+ if (code === 0x2c) {
546
+ push(offers, name, params);
547
+ params = Object.create(null);
548
+ } else {
549
+ extensionName = name;
550
+ }
551
+
552
+ start = end = -1;
553
+ } else {
554
+ throw new SyntaxError(`Unexpected character at index ${i}`);
555
+ }
556
+ } else if (paramName === undefined) {
557
+ if (end === -1 && tokenChars[code] === 1) {
558
+ if (start === -1) start = i;
559
+ } else if (code === 0x20 || code === 0x09) {
560
+ if (end === -1 && start !== -1) end = i;
561
+ } else if (code === 0x3b || code === 0x2c) {
562
+ if (start === -1) {
563
+ throw new SyntaxError(`Unexpected character at index ${i}`);
564
+ }
565
+
566
+ if (end === -1) end = i;
567
+ push(params, header.slice(start, end), true);
568
+ if (code === 0x2c) {
569
+ push(offers, extensionName, params);
570
+ params = Object.create(null);
571
+ extensionName = undefined;
572
+ }
573
+
574
+ start = end = -1;
575
+ } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
576
+ paramName = header.slice(start, i);
577
+ start = end = -1;
578
+ } else {
579
+ throw new SyntaxError(`Unexpected character at index ${i}`);
580
+ }
581
+ } else {
582
+ //
583
+ // The value of a quoted-string after unescaping must conform to the
584
+ // token ABNF, so only token characters are valid.
585
+ // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
586
+ //
587
+ if (isEscaping) {
588
+ if (tokenChars[code] !== 1) {
589
+ throw new SyntaxError(`Unexpected character at index ${i}`);
590
+ }
591
+ if (start === -1) start = i;
592
+ else if (!mustUnescape) mustUnescape = true;
593
+ isEscaping = false;
594
+ } else if (inQuotes) {
595
+ if (tokenChars[code] === 1) {
596
+ if (start === -1) start = i;
597
+ } else if (code === 0x22 /* '"' */ && start !== -1) {
598
+ inQuotes = false;
599
+ end = i;
600
+ } else if (code === 0x5c /* '\' */) {
601
+ isEscaping = true;
602
+ } else {
603
+ throw new SyntaxError(`Unexpected character at index ${i}`);
604
+ }
605
+ } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
606
+ inQuotes = true;
607
+ } else if (end === -1 && tokenChars[code] === 1) {
608
+ if (start === -1) start = i;
609
+ } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
610
+ if (end === -1) end = i;
611
+ } else if (code === 0x3b || code === 0x2c) {
612
+ if (start === -1) {
613
+ throw new SyntaxError(`Unexpected character at index ${i}`);
614
+ }
615
+
616
+ if (end === -1) end = i;
617
+ let value = header.slice(start, end);
618
+ if (mustUnescape) {
619
+ value = value.replace(/\\/g, '');
620
+ mustUnescape = false;
621
+ }
622
+ push(params, paramName, value);
623
+ if (code === 0x2c) {
624
+ push(offers, extensionName, params);
625
+ params = Object.create(null);
626
+ extensionName = undefined;
627
+ }
628
+
629
+ paramName = undefined;
630
+ start = end = -1;
631
+ } else {
632
+ throw new SyntaxError(`Unexpected character at index ${i}`);
633
+ }
634
+ }
635
+ }
636
+
637
+ if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
638
+ throw new SyntaxError('Unexpected end of input');
639
+ }
640
+
641
+ if (end === -1) end = i;
642
+ const token = header.slice(start, end);
643
+ if (extensionName === undefined) {
644
+ push(offers, token, params);
645
+ } else {
646
+ if (paramName === undefined) {
647
+ push(params, token, true);
648
+ } else if (mustUnescape) {
649
+ push(params, paramName, token.replace(/\\/g, ''));
650
+ } else {
651
+ push(params, paramName, token);
652
+ }
653
+ push(offers, extensionName, params);
654
+ }
655
+
656
+ return offers;
657
+ }
658
+
659
+ /**
660
+ * Builds the `Sec-WebSocket-Extensions` header field value.
661
+ *
662
+ * @param {Object} extensions The map of extensions and parameters to format
663
+ * @return {String} A string representing the given object
664
+ * @public
665
+ */
666
+ function format(extensions) {
667
+ return Object.keys(extensions)
668
+ .map((extension) => {
669
+ let configurations = extensions[extension];
670
+ if (!Array.isArray(configurations)) configurations = [configurations];
671
+ return configurations
672
+ .map((params) => {
673
+ return [extension]
674
+ .concat(
675
+ Object.keys(params).map((k) => {
676
+ let values = params[k];
677
+ if (!Array.isArray(values)) values = [values];
678
+ return values
679
+ .map((v) => (v === true ? k : `${k}=${v}`))
680
+ .join('; ');
681
+ })
682
+ )
683
+ .join('; ');
684
+ })
685
+ .join(', ');
686
+ })
687
+ .join(', ');
688
+ }
689
+
690
+ module.exports = { format, parse };
691
+
692
+
693
+ /***/ }),
694
+
695
+ /***/ 869:
696
+ /***/ ((module) => {
697
+
698
+ "use strict";
699
+
700
+
701
+ const kDone = Symbol('kDone');
702
+ const kRun = Symbol('kRun');
703
+
704
+ /**
705
+ * A very simple job queue with adjustable concurrency. Adapted from
706
+ * https://github.com/STRML/async-limiter
707
+ */
708
+ class Limiter {
709
+ /**
710
+ * Creates a new `Limiter`.
711
+ *
712
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
713
+ * to run concurrently
714
+ */
715
+ constructor(concurrency) {
716
+ this[kDone] = () => {
717
+ this.pending--;
718
+ this[kRun]();
719
+ };
720
+ this.concurrency = concurrency || Infinity;
721
+ this.jobs = [];
722
+ this.pending = 0;
723
+ }
724
+
725
+ /**
726
+ * Adds a job to the queue.
727
+ *
728
+ * @param {Function} job The job to run
729
+ * @public
730
+ */
731
+ add(job) {
732
+ this.jobs.push(job);
733
+ this[kRun]();
734
+ }
735
+
736
+ /**
737
+ * Removes a job from the queue and runs it if possible.
738
+ *
739
+ * @private
740
+ */
741
+ [kRun]() {
742
+ if (this.pending === this.concurrency) return;
743
+
744
+ if (this.jobs.length) {
745
+ const job = this.jobs.shift();
746
+
747
+ this.pending++;
748
+ job(this[kDone]);
749
+ }
750
+ }
751
+ }
752
+
753
+ module.exports = Limiter;
754
+
755
+
756
+ /***/ }),
757
+
758
+ /***/ 330:
759
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
760
+
761
+ "use strict";
762
+
763
+
764
+ const zlib = __nccwpck_require__(796);
765
+
766
+ const bufferUtil = __nccwpck_require__(820);
767
+ const Limiter = __nccwpck_require__(869);
768
+ const { kStatusCode } = __nccwpck_require__(862);
769
+
770
+ const FastBuffer = Buffer[Symbol.species];
771
+ const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
772
+ const kPerMessageDeflate = Symbol('permessage-deflate');
773
+ const kTotalLength = Symbol('total-length');
774
+ const kCallback = Symbol('callback');
775
+ const kBuffers = Symbol('buffers');
776
+ const kError = Symbol('error');
777
+
778
+ //
779
+ // We limit zlib concurrency, which prevents severe memory fragmentation
780
+ // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
781
+ // and https://github.com/websockets/ws/issues/1202
782
+ //
783
+ // Intentionally global; it's the global thread pool that's an issue.
784
+ //
785
+ let zlibLimiter;
786
+
787
+ /**
788
+ * permessage-deflate implementation.
789
+ */
790
+ class PerMessageDeflate {
791
+ /**
792
+ * Creates a PerMessageDeflate instance.
793
+ *
794
+ * @param {Object} [options] Configuration options
795
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
796
+ * for, or request, a custom client window size
797
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
798
+ * acknowledge disabling of client context takeover
799
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
800
+ * calls to zlib
801
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
802
+ * use of a custom server window size
803
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
804
+ * disabling of server context takeover
805
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
806
+ * messages should not be compressed if context takeover is disabled
807
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
808
+ * deflate
809
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
810
+ * inflate
811
+ * @param {Boolean} [isServer=false] Create the instance in either server or
812
+ * client mode
813
+ * @param {Number} [maxPayload=0] The maximum allowed message length
814
+ */
815
+ constructor(options, isServer, maxPayload) {
816
+ this._maxPayload = maxPayload | 0;
817
+ this._options = options || {};
818
+ this._threshold =
819
+ this._options.threshold !== undefined ? this._options.threshold : 1024;
820
+ this._isServer = !!isServer;
821
+ this._deflate = null;
822
+ this._inflate = null;
823
+
824
+ this.params = null;
825
+
826
+ if (!zlibLimiter) {
827
+ const concurrency =
828
+ this._options.concurrencyLimit !== undefined
829
+ ? this._options.concurrencyLimit
830
+ : 10;
831
+ zlibLimiter = new Limiter(concurrency);
832
+ }
833
+ }
834
+
835
+ /**
836
+ * @type {String}
837
+ */
838
+ static get extensionName() {
839
+ return 'permessage-deflate';
840
+ }
841
+
842
+ /**
843
+ * Create an extension negotiation offer.
844
+ *
845
+ * @return {Object} Extension parameters
846
+ * @public
847
+ */
848
+ offer() {
849
+ const params = {};
850
+
851
+ if (this._options.serverNoContextTakeover) {
852
+ params.server_no_context_takeover = true;
853
+ }
854
+ if (this._options.clientNoContextTakeover) {
855
+ params.client_no_context_takeover = true;
856
+ }
857
+ if (this._options.serverMaxWindowBits) {
858
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
859
+ }
860
+ if (this._options.clientMaxWindowBits) {
861
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
862
+ } else if (this._options.clientMaxWindowBits == null) {
863
+ params.client_max_window_bits = true;
864
+ }
865
+
866
+ return params;
867
+ }
868
+
869
+ /**
870
+ * Accept an extension negotiation offer/response.
871
+ *
872
+ * @param {Array} configurations The extension negotiation offers/reponse
873
+ * @return {Object} Accepted configuration
874
+ * @public
875
+ */
876
+ accept(configurations) {
877
+ configurations = this.normalizeParams(configurations);
878
+
879
+ this.params = this._isServer
880
+ ? this.acceptAsServer(configurations)
881
+ : this.acceptAsClient(configurations);
882
+
883
+ return this.params;
884
+ }
885
+
886
+ /**
887
+ * Releases all resources used by the extension.
888
+ *
889
+ * @public
890
+ */
891
+ cleanup() {
892
+ if (this._inflate) {
893
+ this._inflate.close();
894
+ this._inflate = null;
895
+ }
896
+
897
+ if (this._deflate) {
898
+ const callback = this._deflate[kCallback];
899
+
900
+ this._deflate.close();
901
+ this._deflate = null;
902
+
903
+ if (callback) {
904
+ callback(
905
+ new Error(
906
+ 'The deflate stream was closed while data was being processed'
907
+ )
908
+ );
909
+ }
910
+ }
911
+ }
912
+
913
+ /**
914
+ * Accept an extension negotiation offer.
915
+ *
916
+ * @param {Array} offers The extension negotiation offers
917
+ * @return {Object} Accepted configuration
918
+ * @private
919
+ */
920
+ acceptAsServer(offers) {
921
+ const opts = this._options;
922
+ const accepted = offers.find((params) => {
923
+ if (
924
+ (opts.serverNoContextTakeover === false &&
925
+ params.server_no_context_takeover) ||
926
+ (params.server_max_window_bits &&
927
+ (opts.serverMaxWindowBits === false ||
928
+ (typeof opts.serverMaxWindowBits === 'number' &&
929
+ opts.serverMaxWindowBits > params.server_max_window_bits))) ||
930
+ (typeof opts.clientMaxWindowBits === 'number' &&
931
+ !params.client_max_window_bits)
932
+ ) {
933
+ return false;
934
+ }
935
+
936
+ return true;
937
+ });
938
+
939
+ if (!accepted) {
940
+ throw new Error('None of the extension offers can be accepted');
941
+ }
942
+
943
+ if (opts.serverNoContextTakeover) {
944
+ accepted.server_no_context_takeover = true;
945
+ }
946
+ if (opts.clientNoContextTakeover) {
947
+ accepted.client_no_context_takeover = true;
948
+ }
949
+ if (typeof opts.serverMaxWindowBits === 'number') {
950
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
951
+ }
952
+ if (typeof opts.clientMaxWindowBits === 'number') {
953
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
954
+ } else if (
955
+ accepted.client_max_window_bits === true ||
956
+ opts.clientMaxWindowBits === false
957
+ ) {
958
+ delete accepted.client_max_window_bits;
959
+ }
960
+
961
+ return accepted;
962
+ }
963
+
964
+ /**
965
+ * Accept the extension negotiation response.
966
+ *
967
+ * @param {Array} response The extension negotiation response
968
+ * @return {Object} Accepted configuration
969
+ * @private
970
+ */
971
+ acceptAsClient(response) {
972
+ const params = response[0];
973
+
974
+ if (
975
+ this._options.clientNoContextTakeover === false &&
976
+ params.client_no_context_takeover
977
+ ) {
978
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
979
+ }
980
+
981
+ if (!params.client_max_window_bits) {
982
+ if (typeof this._options.clientMaxWindowBits === 'number') {
983
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
984
+ }
985
+ } else if (
986
+ this._options.clientMaxWindowBits === false ||
987
+ (typeof this._options.clientMaxWindowBits === 'number' &&
988
+ params.client_max_window_bits > this._options.clientMaxWindowBits)
989
+ ) {
990
+ throw new Error(
991
+ 'Unexpected or invalid parameter "client_max_window_bits"'
992
+ );
993
+ }
994
+
995
+ return params;
996
+ }
997
+
998
+ /**
999
+ * Normalize parameters.
1000
+ *
1001
+ * @param {Array} configurations The extension negotiation offers/reponse
1002
+ * @return {Array} The offers/response with normalized parameters
1003
+ * @private
1004
+ */
1005
+ normalizeParams(configurations) {
1006
+ configurations.forEach((params) => {
1007
+ Object.keys(params).forEach((key) => {
1008
+ let value = params[key];
1009
+
1010
+ if (value.length > 1) {
1011
+ throw new Error(`Parameter "${key}" must have only a single value`);
1012
+ }
1013
+
1014
+ value = value[0];
1015
+
1016
+ if (key === 'client_max_window_bits') {
1017
+ if (value !== true) {
1018
+ const num = +value;
1019
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
1020
+ throw new TypeError(
1021
+ `Invalid value for parameter "${key}": ${value}`
1022
+ );
1023
+ }
1024
+ value = num;
1025
+ } else if (!this._isServer) {
1026
+ throw new TypeError(
1027
+ `Invalid value for parameter "${key}": ${value}`
1028
+ );
1029
+ }
1030
+ } else if (key === 'server_max_window_bits') {
1031
+ const num = +value;
1032
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
1033
+ throw new TypeError(
1034
+ `Invalid value for parameter "${key}": ${value}`
1035
+ );
1036
+ }
1037
+ value = num;
1038
+ } else if (
1039
+ key === 'client_no_context_takeover' ||
1040
+ key === 'server_no_context_takeover'
1041
+ ) {
1042
+ if (value !== true) {
1043
+ throw new TypeError(
1044
+ `Invalid value for parameter "${key}": ${value}`
1045
+ );
1046
+ }
1047
+ } else {
1048
+ throw new Error(`Unknown parameter "${key}"`);
1049
+ }
1050
+
1051
+ params[key] = value;
1052
+ });
1053
+ });
1054
+
1055
+ return configurations;
1056
+ }
1057
+
1058
+ /**
1059
+ * Decompress data. Concurrency limited.
1060
+ *
1061
+ * @param {Buffer} data Compressed data
1062
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
1063
+ * @param {Function} callback Callback
1064
+ * @public
1065
+ */
1066
+ decompress(data, fin, callback) {
1067
+ zlibLimiter.add((done) => {
1068
+ this._decompress(data, fin, (err, result) => {
1069
+ done();
1070
+ callback(err, result);
1071
+ });
1072
+ });
1073
+ }
1074
+
1075
+ /**
1076
+ * Compress data. Concurrency limited.
1077
+ *
1078
+ * @param {(Buffer|String)} data Data to compress
1079
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
1080
+ * @param {Function} callback Callback
1081
+ * @public
1082
+ */
1083
+ compress(data, fin, callback) {
1084
+ zlibLimiter.add((done) => {
1085
+ this._compress(data, fin, (err, result) => {
1086
+ done();
1087
+ callback(err, result);
1088
+ });
1089
+ });
1090
+ }
1091
+
1092
+ /**
1093
+ * Decompress data.
1094
+ *
1095
+ * @param {Buffer} data Compressed data
1096
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
1097
+ * @param {Function} callback Callback
1098
+ * @private
1099
+ */
1100
+ _decompress(data, fin, callback) {
1101
+ const endpoint = this._isServer ? 'client' : 'server';
1102
+
1103
+ if (!this._inflate) {
1104
+ const key = `${endpoint}_max_window_bits`;
1105
+ const windowBits =
1106
+ typeof this.params[key] !== 'number'
1107
+ ? zlib.Z_DEFAULT_WINDOWBITS
1108
+ : this.params[key];
1109
+
1110
+ this._inflate = zlib.createInflateRaw({
1111
+ ...this._options.zlibInflateOptions,
1112
+ windowBits
1113
+ });
1114
+ this._inflate[kPerMessageDeflate] = this;
1115
+ this._inflate[kTotalLength] = 0;
1116
+ this._inflate[kBuffers] = [];
1117
+ this._inflate.on('error', inflateOnError);
1118
+ this._inflate.on('data', inflateOnData);
1119
+ }
1120
+
1121
+ this._inflate[kCallback] = callback;
1122
+
1123
+ this._inflate.write(data);
1124
+ if (fin) this._inflate.write(TRAILER);
1125
+
1126
+ this._inflate.flush(() => {
1127
+ const err = this._inflate[kError];
1128
+
1129
+ if (err) {
1130
+ this._inflate.close();
1131
+ this._inflate = null;
1132
+ callback(err);
1133
+ return;
1134
+ }
1135
+
1136
+ const data = bufferUtil.concat(
1137
+ this._inflate[kBuffers],
1138
+ this._inflate[kTotalLength]
1139
+ );
1140
+
1141
+ if (this._inflate._readableState.endEmitted) {
1142
+ this._inflate.close();
1143
+ this._inflate = null;
1144
+ } else {
1145
+ this._inflate[kTotalLength] = 0;
1146
+ this._inflate[kBuffers] = [];
1147
+
1148
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
1149
+ this._inflate.reset();
1150
+ }
1151
+ }
1152
+
1153
+ callback(null, data);
1154
+ });
1155
+ }
1156
+
1157
+ /**
1158
+ * Compress data.
1159
+ *
1160
+ * @param {(Buffer|String)} data Data to compress
1161
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
1162
+ * @param {Function} callback Callback
1163
+ * @private
1164
+ */
1165
+ _compress(data, fin, callback) {
1166
+ const endpoint = this._isServer ? 'server' : 'client';
1167
+
1168
+ if (!this._deflate) {
1169
+ const key = `${endpoint}_max_window_bits`;
1170
+ const windowBits =
1171
+ typeof this.params[key] !== 'number'
1172
+ ? zlib.Z_DEFAULT_WINDOWBITS
1173
+ : this.params[key];
1174
+
1175
+ this._deflate = zlib.createDeflateRaw({
1176
+ ...this._options.zlibDeflateOptions,
1177
+ windowBits
1178
+ });
1179
+
1180
+ this._deflate[kTotalLength] = 0;
1181
+ this._deflate[kBuffers] = [];
1182
+
1183
+ this._deflate.on('data', deflateOnData);
1184
+ }
1185
+
1186
+ this._deflate[kCallback] = callback;
1187
+
1188
+ this._deflate.write(data);
1189
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
1190
+ if (!this._deflate) {
1191
+ //
1192
+ // The deflate stream was closed while data was being processed.
1193
+ //
1194
+ return;
1195
+ }
1196
+
1197
+ let data = bufferUtil.concat(
1198
+ this._deflate[kBuffers],
1199
+ this._deflate[kTotalLength]
1200
+ );
1201
+
1202
+ if (fin) {
1203
+ data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
1204
+ }
1205
+
1206
+ //
1207
+ // Ensure that the callback will not be called again in
1208
+ // `PerMessageDeflate#cleanup()`.
1209
+ //
1210
+ this._deflate[kCallback] = null;
1211
+
1212
+ this._deflate[kTotalLength] = 0;
1213
+ this._deflate[kBuffers] = [];
1214
+
1215
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
1216
+ this._deflate.reset();
1217
+ }
1218
+
1219
+ callback(null, data);
1220
+ });
1221
+ }
1222
+ }
1223
+
1224
+ module.exports = PerMessageDeflate;
1225
+
1226
+ /**
1227
+ * The listener of the `zlib.DeflateRaw` stream `'data'` event.
1228
+ *
1229
+ * @param {Buffer} chunk A chunk of data
1230
+ * @private
1231
+ */
1232
+ function deflateOnData(chunk) {
1233
+ this[kBuffers].push(chunk);
1234
+ this[kTotalLength] += chunk.length;
1235
+ }
1236
+
1237
+ /**
1238
+ * The listener of the `zlib.InflateRaw` stream `'data'` event.
1239
+ *
1240
+ * @param {Buffer} chunk A chunk of data
1241
+ * @private
1242
+ */
1243
+ function inflateOnData(chunk) {
1244
+ this[kTotalLength] += chunk.length;
1245
+
1246
+ if (
1247
+ this[kPerMessageDeflate]._maxPayload < 1 ||
1248
+ this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
1249
+ ) {
1250
+ this[kBuffers].push(chunk);
1251
+ return;
1252
+ }
1253
+
1254
+ this[kError] = new RangeError('Max payload size exceeded');
1255
+ this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
1256
+ this[kError][kStatusCode] = 1009;
1257
+ this.removeListener('data', inflateOnData);
1258
+ this.reset();
1259
+ }
1260
+
1261
+ /**
1262
+ * The listener of the `zlib.InflateRaw` stream `'error'` event.
1263
+ *
1264
+ * @param {Error} err The emitted error
1265
+ * @private
1266
+ */
1267
+ function inflateOnError(err) {
1268
+ //
1269
+ // There is no need to call `Zlib#close()` as the handle is automatically
1270
+ // closed when an error is emitted.
1271
+ //
1272
+ this[kPerMessageDeflate]._inflate = null;
1273
+ err[kStatusCode] = 1007;
1274
+ this[kCallback](err);
1275
+ }
1276
+
1277
+
1278
+ /***/ }),
1279
+
1280
+ /***/ 663:
1281
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
1282
+
1283
+ "use strict";
1284
+
1285
+
1286
+ const { Writable } = __nccwpck_require__(781);
1287
+
1288
+ const PerMessageDeflate = __nccwpck_require__(330);
1289
+ const {
1290
+ BINARY_TYPES,
1291
+ EMPTY_BUFFER,
1292
+ kStatusCode,
1293
+ kWebSocket
1294
+ } = __nccwpck_require__(862);
1295
+ const { concat, toArrayBuffer, unmask } = __nccwpck_require__(820);
1296
+ const { isValidStatusCode, isValidUTF8 } = __nccwpck_require__(23);
1297
+
1298
+ const FastBuffer = Buffer[Symbol.species];
1299
+
1300
+ const GET_INFO = 0;
1301
+ const GET_PAYLOAD_LENGTH_16 = 1;
1302
+ const GET_PAYLOAD_LENGTH_64 = 2;
1303
+ const GET_MASK = 3;
1304
+ const GET_DATA = 4;
1305
+ const INFLATING = 5;
1306
+ const DEFER_EVENT = 6;
1307
+
1308
+ /**
1309
+ * HyBi Receiver implementation.
1310
+ *
1311
+ * @extends Writable
1312
+ */
1313
+ class Receiver extends Writable {
1314
+ /**
1315
+ * Creates a Receiver instance.
1316
+ *
1317
+ * @param {Object} [options] Options object
1318
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
1319
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
1320
+ * multiple times in the same tick
1321
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
1322
+ * @param {Object} [options.extensions] An object containing the negotiated
1323
+ * extensions
1324
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
1325
+ * client or server mode
1326
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
1327
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
1328
+ * not to skip UTF-8 validation for text and close messages
1329
+ */
1330
+ constructor(options = {}) {
1331
+ super();
1332
+
1333
+ this._allowSynchronousEvents =
1334
+ options.allowSynchronousEvents !== undefined
1335
+ ? options.allowSynchronousEvents
1336
+ : true;
1337
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
1338
+ this._extensions = options.extensions || {};
1339
+ this._isServer = !!options.isServer;
1340
+ this._maxPayload = options.maxPayload | 0;
1341
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
1342
+ this[kWebSocket] = undefined;
1343
+
1344
+ this._bufferedBytes = 0;
1345
+ this._buffers = [];
1346
+
1347
+ this._compressed = false;
1348
+ this._payloadLength = 0;
1349
+ this._mask = undefined;
1350
+ this._fragmented = 0;
1351
+ this._masked = false;
1352
+ this._fin = false;
1353
+ this._opcode = 0;
1354
+
1355
+ this._totalPayloadLength = 0;
1356
+ this._messageLength = 0;
1357
+ this._fragments = [];
1358
+
1359
+ this._errored = false;
1360
+ this._loop = false;
1361
+ this._state = GET_INFO;
1362
+ }
1363
+
1364
+ /**
1365
+ * Implements `Writable.prototype._write()`.
1366
+ *
1367
+ * @param {Buffer} chunk The chunk of data to write
1368
+ * @param {String} encoding The character encoding of `chunk`
1369
+ * @param {Function} cb Callback
1370
+ * @private
1371
+ */
1372
+ _write(chunk, encoding, cb) {
1373
+ if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
1374
+
1375
+ this._bufferedBytes += chunk.length;
1376
+ this._buffers.push(chunk);
1377
+ this.startLoop(cb);
1378
+ }
1379
+
1380
+ /**
1381
+ * Consumes `n` bytes from the buffered data.
1382
+ *
1383
+ * @param {Number} n The number of bytes to consume
1384
+ * @return {Buffer} The consumed bytes
1385
+ * @private
1386
+ */
1387
+ consume(n) {
1388
+ this._bufferedBytes -= n;
1389
+
1390
+ if (n === this._buffers[0].length) return this._buffers.shift();
1391
+
1392
+ if (n < this._buffers[0].length) {
1393
+ const buf = this._buffers[0];
1394
+ this._buffers[0] = new FastBuffer(
1395
+ buf.buffer,
1396
+ buf.byteOffset + n,
1397
+ buf.length - n
1398
+ );
1399
+
1400
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
1401
+ }
1402
+
1403
+ const dst = Buffer.allocUnsafe(n);
1404
+
1405
+ do {
1406
+ const buf = this._buffers[0];
1407
+ const offset = dst.length - n;
1408
+
1409
+ if (n >= buf.length) {
1410
+ dst.set(this._buffers.shift(), offset);
1411
+ } else {
1412
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
1413
+ this._buffers[0] = new FastBuffer(
1414
+ buf.buffer,
1415
+ buf.byteOffset + n,
1416
+ buf.length - n
1417
+ );
1418
+ }
1419
+
1420
+ n -= buf.length;
1421
+ } while (n > 0);
1422
+
1423
+ return dst;
1424
+ }
1425
+
1426
+ /**
1427
+ * Starts the parsing loop.
1428
+ *
1429
+ * @param {Function} cb Callback
1430
+ * @private
1431
+ */
1432
+ startLoop(cb) {
1433
+ this._loop = true;
1434
+
1435
+ do {
1436
+ switch (this._state) {
1437
+ case GET_INFO:
1438
+ this.getInfo(cb);
1439
+ break;
1440
+ case GET_PAYLOAD_LENGTH_16:
1441
+ this.getPayloadLength16(cb);
1442
+ break;
1443
+ case GET_PAYLOAD_LENGTH_64:
1444
+ this.getPayloadLength64(cb);
1445
+ break;
1446
+ case GET_MASK:
1447
+ this.getMask();
1448
+ break;
1449
+ case GET_DATA:
1450
+ this.getData(cb);
1451
+ break;
1452
+ case INFLATING:
1453
+ case DEFER_EVENT:
1454
+ this._loop = false;
1455
+ return;
1456
+ }
1457
+ } while (this._loop);
1458
+
1459
+ if (!this._errored) cb();
1460
+ }
1461
+
1462
+ /**
1463
+ * Reads the first two bytes of a frame.
1464
+ *
1465
+ * @param {Function} cb Callback
1466
+ * @private
1467
+ */
1468
+ getInfo(cb) {
1469
+ if (this._bufferedBytes < 2) {
1470
+ this._loop = false;
1471
+ return;
1472
+ }
1473
+
1474
+ const buf = this.consume(2);
1475
+
1476
+ if ((buf[0] & 0x30) !== 0x00) {
1477
+ const error = this.createError(
1478
+ RangeError,
1479
+ 'RSV2 and RSV3 must be clear',
1480
+ true,
1481
+ 1002,
1482
+ 'WS_ERR_UNEXPECTED_RSV_2_3'
1483
+ );
1484
+
1485
+ cb(error);
1486
+ return;
1487
+ }
1488
+
1489
+ const compressed = (buf[0] & 0x40) === 0x40;
1490
+
1491
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1492
+ const error = this.createError(
1493
+ RangeError,
1494
+ 'RSV1 must be clear',
1495
+ true,
1496
+ 1002,
1497
+ 'WS_ERR_UNEXPECTED_RSV_1'
1498
+ );
1499
+
1500
+ cb(error);
1501
+ return;
1502
+ }
1503
+
1504
+ this._fin = (buf[0] & 0x80) === 0x80;
1505
+ this._opcode = buf[0] & 0x0f;
1506
+ this._payloadLength = buf[1] & 0x7f;
1507
+
1508
+ if (this._opcode === 0x00) {
1509
+ if (compressed) {
1510
+ const error = this.createError(
1511
+ RangeError,
1512
+ 'RSV1 must be clear',
1513
+ true,
1514
+ 1002,
1515
+ 'WS_ERR_UNEXPECTED_RSV_1'
1516
+ );
1517
+
1518
+ cb(error);
1519
+ return;
1520
+ }
1521
+
1522
+ if (!this._fragmented) {
1523
+ const error = this.createError(
1524
+ RangeError,
1525
+ 'invalid opcode 0',
1526
+ true,
1527
+ 1002,
1528
+ 'WS_ERR_INVALID_OPCODE'
1529
+ );
1530
+
1531
+ cb(error);
1532
+ return;
1533
+ }
1534
+
1535
+ this._opcode = this._fragmented;
1536
+ } else if (this._opcode === 0x01 || this._opcode === 0x02) {
1537
+ if (this._fragmented) {
1538
+ const error = this.createError(
1539
+ RangeError,
1540
+ `invalid opcode ${this._opcode}`,
1541
+ true,
1542
+ 1002,
1543
+ 'WS_ERR_INVALID_OPCODE'
1544
+ );
1545
+
1546
+ cb(error);
1547
+ return;
1548
+ }
1549
+
1550
+ this._compressed = compressed;
1551
+ } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
1552
+ if (!this._fin) {
1553
+ const error = this.createError(
1554
+ RangeError,
1555
+ 'FIN must be set',
1556
+ true,
1557
+ 1002,
1558
+ 'WS_ERR_EXPECTED_FIN'
1559
+ );
1560
+
1561
+ cb(error);
1562
+ return;
1563
+ }
1564
+
1565
+ if (compressed) {
1566
+ const error = this.createError(
1567
+ RangeError,
1568
+ 'RSV1 must be clear',
1569
+ true,
1570
+ 1002,
1571
+ 'WS_ERR_UNEXPECTED_RSV_1'
1572
+ );
1573
+
1574
+ cb(error);
1575
+ return;
1576
+ }
1577
+
1578
+ if (
1579
+ this._payloadLength > 0x7d ||
1580
+ (this._opcode === 0x08 && this._payloadLength === 1)
1581
+ ) {
1582
+ const error = this.createError(
1583
+ RangeError,
1584
+ `invalid payload length ${this._payloadLength}`,
1585
+ true,
1586
+ 1002,
1587
+ 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
1588
+ );
1589
+
1590
+ cb(error);
1591
+ return;
1592
+ }
1593
+ } else {
1594
+ const error = this.createError(
1595
+ RangeError,
1596
+ `invalid opcode ${this._opcode}`,
1597
+ true,
1598
+ 1002,
1599
+ 'WS_ERR_INVALID_OPCODE'
1600
+ );
1601
+
1602
+ cb(error);
1603
+ return;
1604
+ }
1605
+
1606
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1607
+ this._masked = (buf[1] & 0x80) === 0x80;
1608
+
1609
+ if (this._isServer) {
1610
+ if (!this._masked) {
1611
+ const error = this.createError(
1612
+ RangeError,
1613
+ 'MASK must be set',
1614
+ true,
1615
+ 1002,
1616
+ 'WS_ERR_EXPECTED_MASK'
1617
+ );
1618
+
1619
+ cb(error);
1620
+ return;
1621
+ }
1622
+ } else if (this._masked) {
1623
+ const error = this.createError(
1624
+ RangeError,
1625
+ 'MASK must be clear',
1626
+ true,
1627
+ 1002,
1628
+ 'WS_ERR_UNEXPECTED_MASK'
1629
+ );
1630
+
1631
+ cb(error);
1632
+ return;
1633
+ }
1634
+
1635
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1636
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1637
+ else this.haveLength(cb);
1638
+ }
1639
+
1640
+ /**
1641
+ * Gets extended payload length (7+16).
1642
+ *
1643
+ * @param {Function} cb Callback
1644
+ * @private
1645
+ */
1646
+ getPayloadLength16(cb) {
1647
+ if (this._bufferedBytes < 2) {
1648
+ this._loop = false;
1649
+ return;
1650
+ }
1651
+
1652
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1653
+ this.haveLength(cb);
1654
+ }
1655
+
1656
+ /**
1657
+ * Gets extended payload length (7+64).
1658
+ *
1659
+ * @param {Function} cb Callback
1660
+ * @private
1661
+ */
1662
+ getPayloadLength64(cb) {
1663
+ if (this._bufferedBytes < 8) {
1664
+ this._loop = false;
1665
+ return;
1666
+ }
1667
+
1668
+ const buf = this.consume(8);
1669
+ const num = buf.readUInt32BE(0);
1670
+
1671
+ //
1672
+ // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
1673
+ // if payload length is greater than this number.
1674
+ //
1675
+ if (num > Math.pow(2, 53 - 32) - 1) {
1676
+ const error = this.createError(
1677
+ RangeError,
1678
+ 'Unsupported WebSocket frame: payload length > 2^53 - 1',
1679
+ false,
1680
+ 1009,
1681
+ 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
1682
+ );
1683
+
1684
+ cb(error);
1685
+ return;
1686
+ }
1687
+
1688
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1689
+ this.haveLength(cb);
1690
+ }
1691
+
1692
+ /**
1693
+ * Payload length has been read.
1694
+ *
1695
+ * @param {Function} cb Callback
1696
+ * @private
1697
+ */
1698
+ haveLength(cb) {
1699
+ if (this._payloadLength && this._opcode < 0x08) {
1700
+ this._totalPayloadLength += this._payloadLength;
1701
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1702
+ const error = this.createError(
1703
+ RangeError,
1704
+ 'Max payload size exceeded',
1705
+ false,
1706
+ 1009,
1707
+ 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
1708
+ );
1709
+
1710
+ cb(error);
1711
+ return;
1712
+ }
1713
+ }
1714
+
1715
+ if (this._masked) this._state = GET_MASK;
1716
+ else this._state = GET_DATA;
1717
+ }
1718
+
1719
+ /**
1720
+ * Reads mask bytes.
1721
+ *
1722
+ * @private
1723
+ */
1724
+ getMask() {
1725
+ if (this._bufferedBytes < 4) {
1726
+ this._loop = false;
1727
+ return;
1728
+ }
1729
+
1730
+ this._mask = this.consume(4);
1731
+ this._state = GET_DATA;
1732
+ }
1733
+
1734
+ /**
1735
+ * Reads data bytes.
1736
+ *
1737
+ * @param {Function} cb Callback
1738
+ * @private
1739
+ */
1740
+ getData(cb) {
1741
+ let data = EMPTY_BUFFER;
1742
+
1743
+ if (this._payloadLength) {
1744
+ if (this._bufferedBytes < this._payloadLength) {
1745
+ this._loop = false;
1746
+ return;
1747
+ }
1748
+
1749
+ data = this.consume(this._payloadLength);
1750
+
1751
+ if (
1752
+ this._masked &&
1753
+ (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
1754
+ ) {
1755
+ unmask(data, this._mask);
1756
+ }
1757
+ }
1758
+
1759
+ if (this._opcode > 0x07) {
1760
+ this.controlMessage(data, cb);
1761
+ return;
1762
+ }
1763
+
1764
+ if (this._compressed) {
1765
+ this._state = INFLATING;
1766
+ this.decompress(data, cb);
1767
+ return;
1768
+ }
1769
+
1770
+ if (data.length) {
1771
+ //
1772
+ // This message is not compressed so its length is the sum of the payload
1773
+ // length of all fragments.
1774
+ //
1775
+ this._messageLength = this._totalPayloadLength;
1776
+ this._fragments.push(data);
1777
+ }
1778
+
1779
+ this.dataMessage(cb);
1780
+ }
1781
+
1782
+ /**
1783
+ * Decompresses data.
1784
+ *
1785
+ * @param {Buffer} data Compressed data
1786
+ * @param {Function} cb Callback
1787
+ * @private
1788
+ */
1789
+ decompress(data, cb) {
1790
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1791
+
1792
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1793
+ if (err) return cb(err);
1794
+
1795
+ if (buf.length) {
1796
+ this._messageLength += buf.length;
1797
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1798
+ const error = this.createError(
1799
+ RangeError,
1800
+ 'Max payload size exceeded',
1801
+ false,
1802
+ 1009,
1803
+ 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
1804
+ );
1805
+
1806
+ cb(error);
1807
+ return;
1808
+ }
1809
+
1810
+ this._fragments.push(buf);
1811
+ }
1812
+
1813
+ this.dataMessage(cb);
1814
+ if (this._state === GET_INFO) this.startLoop(cb);
1815
+ });
1816
+ }
1817
+
1818
+ /**
1819
+ * Handles a data message.
1820
+ *
1821
+ * @param {Function} cb Callback
1822
+ * @private
1823
+ */
1824
+ dataMessage(cb) {
1825
+ if (!this._fin) {
1826
+ this._state = GET_INFO;
1827
+ return;
1828
+ }
1829
+
1830
+ const messageLength = this._messageLength;
1831
+ const fragments = this._fragments;
1832
+
1833
+ this._totalPayloadLength = 0;
1834
+ this._messageLength = 0;
1835
+ this._fragmented = 0;
1836
+ this._fragments = [];
1837
+
1838
+ if (this._opcode === 2) {
1839
+ let data;
1840
+
1841
+ if (this._binaryType === 'nodebuffer') {
1842
+ data = concat(fragments, messageLength);
1843
+ } else if (this._binaryType === 'arraybuffer') {
1844
+ data = toArrayBuffer(concat(fragments, messageLength));
1845
+ } else {
1846
+ data = fragments;
1847
+ }
1848
+
1849
+ if (this._allowSynchronousEvents) {
1850
+ this.emit('message', data, true);
1851
+ this._state = GET_INFO;
1852
+ } else {
1853
+ this._state = DEFER_EVENT;
1854
+ setImmediate(() => {
1855
+ this.emit('message', data, true);
1856
+ this._state = GET_INFO;
1857
+ this.startLoop(cb);
1858
+ });
1859
+ }
1860
+ } else {
1861
+ const buf = concat(fragments, messageLength);
1862
+
1863
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1864
+ const error = this.createError(
1865
+ Error,
1866
+ 'invalid UTF-8 sequence',
1867
+ true,
1868
+ 1007,
1869
+ 'WS_ERR_INVALID_UTF8'
1870
+ );
1871
+
1872
+ cb(error);
1873
+ return;
1874
+ }
1875
+
1876
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1877
+ this.emit('message', buf, false);
1878
+ this._state = GET_INFO;
1879
+ } else {
1880
+ this._state = DEFER_EVENT;
1881
+ setImmediate(() => {
1882
+ this.emit('message', buf, false);
1883
+ this._state = GET_INFO;
1884
+ this.startLoop(cb);
1885
+ });
1886
+ }
1887
+ }
1888
+ }
1889
+
1890
+ /**
1891
+ * Handles a control message.
1892
+ *
1893
+ * @param {Buffer} data Data to handle
1894
+ * @return {(Error|RangeError|undefined)} A possible error
1895
+ * @private
1896
+ */
1897
+ controlMessage(data, cb) {
1898
+ if (this._opcode === 0x08) {
1899
+ if (data.length === 0) {
1900
+ this._loop = false;
1901
+ this.emit('conclude', 1005, EMPTY_BUFFER);
1902
+ this.end();
1903
+ } else {
1904
+ const code = data.readUInt16BE(0);
1905
+
1906
+ if (!isValidStatusCode(code)) {
1907
+ const error = this.createError(
1908
+ RangeError,
1909
+ `invalid status code ${code}`,
1910
+ true,
1911
+ 1002,
1912
+ 'WS_ERR_INVALID_CLOSE_CODE'
1913
+ );
1914
+
1915
+ cb(error);
1916
+ return;
1917
+ }
1918
+
1919
+ const buf = new FastBuffer(
1920
+ data.buffer,
1921
+ data.byteOffset + 2,
1922
+ data.length - 2
1923
+ );
1924
+
1925
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1926
+ const error = this.createError(
1927
+ Error,
1928
+ 'invalid UTF-8 sequence',
1929
+ true,
1930
+ 1007,
1931
+ 'WS_ERR_INVALID_UTF8'
1932
+ );
1933
+
1934
+ cb(error);
1935
+ return;
1936
+ }
1937
+
1938
+ this._loop = false;
1939
+ this.emit('conclude', code, buf);
1940
+ this.end();
1941
+ }
1942
+
1943
+ this._state = GET_INFO;
1944
+ return;
1945
+ }
1946
+
1947
+ if (this._allowSynchronousEvents) {
1948
+ this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
1949
+ this._state = GET_INFO;
1950
+ } else {
1951
+ this._state = DEFER_EVENT;
1952
+ setImmediate(() => {
1953
+ this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
1954
+ this._state = GET_INFO;
1955
+ this.startLoop(cb);
1956
+ });
1957
+ }
1958
+ }
1959
+
1960
+ /**
1961
+ * Builds an error object.
1962
+ *
1963
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1964
+ * @param {String} message The error message
1965
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1966
+ * `message`
1967
+ * @param {Number} statusCode The status code
1968
+ * @param {String} errorCode The exposed error code
1969
+ * @return {(Error|RangeError)} The error
1970
+ * @private
1971
+ */
1972
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1973
+ this._loop = false;
1974
+ this._errored = true;
1975
+
1976
+ const err = new ErrorCtor(
1977
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1978
+ );
1979
+
1980
+ Error.captureStackTrace(err, this.createError);
1981
+ err.code = errorCode;
1982
+ err[kStatusCode] = statusCode;
1983
+ return err;
1984
+ }
1985
+ }
1986
+
1987
+ module.exports = Receiver;
1988
+
1989
+
1990
+ /***/ }),
1991
+
1992
+ /***/ 19:
1993
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
1994
+
1995
+ "use strict";
1996
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */
1997
+
1998
+
1999
+
2000
+ const { Duplex } = __nccwpck_require__(781);
2001
+ const { randomFillSync } = __nccwpck_require__(113);
2002
+
2003
+ const PerMessageDeflate = __nccwpck_require__(330);
2004
+ const { EMPTY_BUFFER } = __nccwpck_require__(862);
2005
+ const { isValidStatusCode } = __nccwpck_require__(23);
2006
+ const { mask: applyMask, toBuffer } = __nccwpck_require__(820);
2007
+
2008
+ const kByteLength = Symbol('kByteLength');
2009
+ const maskBuffer = Buffer.alloc(4);
2010
+
2011
+ /**
2012
+ * HyBi Sender implementation.
2013
+ */
2014
+ class Sender {
2015
+ /**
2016
+ * Creates a Sender instance.
2017
+ *
2018
+ * @param {Duplex} socket The connection socket
2019
+ * @param {Object} [extensions] An object containing the negotiated extensions
2020
+ * @param {Function} [generateMask] The function used to generate the masking
2021
+ * key
2022
+ */
2023
+ constructor(socket, extensions, generateMask) {
2024
+ this._extensions = extensions || {};
2025
+
2026
+ if (generateMask) {
2027
+ this._generateMask = generateMask;
2028
+ this._maskBuffer = Buffer.alloc(4);
2029
+ }
2030
+
2031
+ this._socket = socket;
2032
+
2033
+ this._firstFragment = true;
2034
+ this._compress = false;
2035
+
2036
+ this._bufferedBytes = 0;
2037
+ this._deflating = false;
2038
+ this._queue = [];
2039
+ }
2040
+
2041
+ /**
2042
+ * Frames a piece of data according to the HyBi WebSocket protocol.
2043
+ *
2044
+ * @param {(Buffer|String)} data The data to frame
2045
+ * @param {Object} options Options object
2046
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
2047
+ * FIN bit
2048
+ * @param {Function} [options.generateMask] The function used to generate the
2049
+ * masking key
2050
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
2051
+ * `data`
2052
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
2053
+ * key
2054
+ * @param {Number} options.opcode The opcode
2055
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
2056
+ * modified
2057
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
2058
+ * RSV1 bit
2059
+ * @return {(Buffer|String)[]} The framed data
2060
+ * @public
2061
+ */
2062
+ static frame(data, options) {
2063
+ let mask;
2064
+ let merge = false;
2065
+ let offset = 2;
2066
+ let skipMasking = false;
2067
+
2068
+ if (options.mask) {
2069
+ mask = options.maskBuffer || maskBuffer;
2070
+
2071
+ if (options.generateMask) {
2072
+ options.generateMask(mask);
2073
+ } else {
2074
+ randomFillSync(mask, 0, 4);
2075
+ }
2076
+
2077
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
2078
+ offset = 6;
2079
+ }
2080
+
2081
+ let dataLength;
2082
+
2083
+ if (typeof data === 'string') {
2084
+ if (
2085
+ (!options.mask || skipMasking) &&
2086
+ options[kByteLength] !== undefined
2087
+ ) {
2088
+ dataLength = options[kByteLength];
2089
+ } else {
2090
+ data = Buffer.from(data);
2091
+ dataLength = data.length;
2092
+ }
2093
+ } else {
2094
+ dataLength = data.length;
2095
+ merge = options.mask && options.readOnly && !skipMasking;
2096
+ }
2097
+
2098
+ let payloadLength = dataLength;
2099
+
2100
+ if (dataLength >= 65536) {
2101
+ offset += 8;
2102
+ payloadLength = 127;
2103
+ } else if (dataLength > 125) {
2104
+ offset += 2;
2105
+ payloadLength = 126;
2106
+ }
2107
+
2108
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
2109
+
2110
+ target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
2111
+ if (options.rsv1) target[0] |= 0x40;
2112
+
2113
+ target[1] = payloadLength;
2114
+
2115
+ if (payloadLength === 126) {
2116
+ target.writeUInt16BE(dataLength, 2);
2117
+ } else if (payloadLength === 127) {
2118
+ target[2] = target[3] = 0;
2119
+ target.writeUIntBE(dataLength, 4, 6);
2120
+ }
2121
+
2122
+ if (!options.mask) return [target, data];
2123
+
2124
+ target[1] |= 0x80;
2125
+ target[offset - 4] = mask[0];
2126
+ target[offset - 3] = mask[1];
2127
+ target[offset - 2] = mask[2];
2128
+ target[offset - 1] = mask[3];
2129
+
2130
+ if (skipMasking) return [target, data];
2131
+
2132
+ if (merge) {
2133
+ applyMask(data, mask, target, offset, dataLength);
2134
+ return [target];
2135
+ }
2136
+
2137
+ applyMask(data, mask, data, 0, dataLength);
2138
+ return [target, data];
2139
+ }
2140
+
2141
+ /**
2142
+ * Sends a close message to the other peer.
2143
+ *
2144
+ * @param {Number} [code] The status code component of the body
2145
+ * @param {(String|Buffer)} [data] The message component of the body
2146
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
2147
+ * @param {Function} [cb] Callback
2148
+ * @public
2149
+ */
2150
+ close(code, data, mask, cb) {
2151
+ let buf;
2152
+
2153
+ if (code === undefined) {
2154
+ buf = EMPTY_BUFFER;
2155
+ } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
2156
+ throw new TypeError('First argument must be a valid error code number');
2157
+ } else if (data === undefined || !data.length) {
2158
+ buf = Buffer.allocUnsafe(2);
2159
+ buf.writeUInt16BE(code, 0);
2160
+ } else {
2161
+ const length = Buffer.byteLength(data);
2162
+
2163
+ if (length > 123) {
2164
+ throw new RangeError('The message must not be greater than 123 bytes');
2165
+ }
2166
+
2167
+ buf = Buffer.allocUnsafe(2 + length);
2168
+ buf.writeUInt16BE(code, 0);
2169
+
2170
+ if (typeof data === 'string') {
2171
+ buf.write(data, 2);
2172
+ } else {
2173
+ buf.set(data, 2);
2174
+ }
2175
+ }
2176
+
2177
+ const options = {
2178
+ [kByteLength]: buf.length,
2179
+ fin: true,
2180
+ generateMask: this._generateMask,
2181
+ mask,
2182
+ maskBuffer: this._maskBuffer,
2183
+ opcode: 0x08,
2184
+ readOnly: false,
2185
+ rsv1: false
2186
+ };
2187
+
2188
+ if (this._deflating) {
2189
+ this.enqueue([this.dispatch, buf, false, options, cb]);
2190
+ } else {
2191
+ this.sendFrame(Sender.frame(buf, options), cb);
2192
+ }
2193
+ }
2194
+
2195
+ /**
2196
+ * Sends a ping message to the other peer.
2197
+ *
2198
+ * @param {*} data The message to send
2199
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
2200
+ * @param {Function} [cb] Callback
2201
+ * @public
2202
+ */
2203
+ ping(data, mask, cb) {
2204
+ let byteLength;
2205
+ let readOnly;
2206
+
2207
+ if (typeof data === 'string') {
2208
+ byteLength = Buffer.byteLength(data);
2209
+ readOnly = false;
2210
+ } else {
2211
+ data = toBuffer(data);
2212
+ byteLength = data.length;
2213
+ readOnly = toBuffer.readOnly;
2214
+ }
2215
+
2216
+ if (byteLength > 125) {
2217
+ throw new RangeError('The data size must not be greater than 125 bytes');
2218
+ }
2219
+
2220
+ const options = {
2221
+ [kByteLength]: byteLength,
2222
+ fin: true,
2223
+ generateMask: this._generateMask,
2224
+ mask,
2225
+ maskBuffer: this._maskBuffer,
2226
+ opcode: 0x09,
2227
+ readOnly,
2228
+ rsv1: false
2229
+ };
2230
+
2231
+ if (this._deflating) {
2232
+ this.enqueue([this.dispatch, data, false, options, cb]);
2233
+ } else {
2234
+ this.sendFrame(Sender.frame(data, options), cb);
2235
+ }
2236
+ }
2237
+
2238
+ /**
2239
+ * Sends a pong message to the other peer.
2240
+ *
2241
+ * @param {*} data The message to send
2242
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
2243
+ * @param {Function} [cb] Callback
2244
+ * @public
2245
+ */
2246
+ pong(data, mask, cb) {
2247
+ let byteLength;
2248
+ let readOnly;
2249
+
2250
+ if (typeof data === 'string') {
2251
+ byteLength = Buffer.byteLength(data);
2252
+ readOnly = false;
2253
+ } else {
2254
+ data = toBuffer(data);
2255
+ byteLength = data.length;
2256
+ readOnly = toBuffer.readOnly;
2257
+ }
2258
+
2259
+ if (byteLength > 125) {
2260
+ throw new RangeError('The data size must not be greater than 125 bytes');
2261
+ }
2262
+
2263
+ const options = {
2264
+ [kByteLength]: byteLength,
2265
+ fin: true,
2266
+ generateMask: this._generateMask,
2267
+ mask,
2268
+ maskBuffer: this._maskBuffer,
2269
+ opcode: 0x0a,
2270
+ readOnly,
2271
+ rsv1: false
2272
+ };
2273
+
2274
+ if (this._deflating) {
2275
+ this.enqueue([this.dispatch, data, false, options, cb]);
2276
+ } else {
2277
+ this.sendFrame(Sender.frame(data, options), cb);
2278
+ }
2279
+ }
2280
+
2281
+ /**
2282
+ * Sends a data message to the other peer.
2283
+ *
2284
+ * @param {*} data The message to send
2285
+ * @param {Object} options Options object
2286
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
2287
+ * or text
2288
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
2289
+ * compress `data`
2290
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
2291
+ * last one
2292
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
2293
+ * `data`
2294
+ * @param {Function} [cb] Callback
2295
+ * @public
2296
+ */
2297
+ send(data, options, cb) {
2298
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
2299
+ let opcode = options.binary ? 2 : 1;
2300
+ let rsv1 = options.compress;
2301
+
2302
+ let byteLength;
2303
+ let readOnly;
2304
+
2305
+ if (typeof data === 'string') {
2306
+ byteLength = Buffer.byteLength(data);
2307
+ readOnly = false;
2308
+ } else {
2309
+ data = toBuffer(data);
2310
+ byteLength = data.length;
2311
+ readOnly = toBuffer.readOnly;
2312
+ }
2313
+
2314
+ if (this._firstFragment) {
2315
+ this._firstFragment = false;
2316
+ if (
2317
+ rsv1 &&
2318
+ perMessageDeflate &&
2319
+ perMessageDeflate.params[
2320
+ perMessageDeflate._isServer
2321
+ ? 'server_no_context_takeover'
2322
+ : 'client_no_context_takeover'
2323
+ ]
2324
+ ) {
2325
+ rsv1 = byteLength >= perMessageDeflate._threshold;
2326
+ }
2327
+ this._compress = rsv1;
2328
+ } else {
2329
+ rsv1 = false;
2330
+ opcode = 0;
2331
+ }
2332
+
2333
+ if (options.fin) this._firstFragment = true;
2334
+
2335
+ if (perMessageDeflate) {
2336
+ const opts = {
2337
+ [kByteLength]: byteLength,
2338
+ fin: options.fin,
2339
+ generateMask: this._generateMask,
2340
+ mask: options.mask,
2341
+ maskBuffer: this._maskBuffer,
2342
+ opcode,
2343
+ readOnly,
2344
+ rsv1
2345
+ };
2346
+
2347
+ if (this._deflating) {
2348
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
2349
+ } else {
2350
+ this.dispatch(data, this._compress, opts, cb);
2351
+ }
2352
+ } else {
2353
+ this.sendFrame(
2354
+ Sender.frame(data, {
2355
+ [kByteLength]: byteLength,
2356
+ fin: options.fin,
2357
+ generateMask: this._generateMask,
2358
+ mask: options.mask,
2359
+ maskBuffer: this._maskBuffer,
2360
+ opcode,
2361
+ readOnly,
2362
+ rsv1: false
2363
+ }),
2364
+ cb
2365
+ );
2366
+ }
2367
+ }
2368
+
2369
+ /**
2370
+ * Dispatches a message.
2371
+ *
2372
+ * @param {(Buffer|String)} data The message to send
2373
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
2374
+ * `data`
2375
+ * @param {Object} options Options object
2376
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
2377
+ * FIN bit
2378
+ * @param {Function} [options.generateMask] The function used to generate the
2379
+ * masking key
2380
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
2381
+ * `data`
2382
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
2383
+ * key
2384
+ * @param {Number} options.opcode The opcode
2385
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
2386
+ * modified
2387
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
2388
+ * RSV1 bit
2389
+ * @param {Function} [cb] Callback
2390
+ * @private
2391
+ */
2392
+ dispatch(data, compress, options, cb) {
2393
+ if (!compress) {
2394
+ this.sendFrame(Sender.frame(data, options), cb);
2395
+ return;
2396
+ }
2397
+
2398
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
2399
+
2400
+ this._bufferedBytes += options[kByteLength];
2401
+ this._deflating = true;
2402
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
2403
+ if (this._socket.destroyed) {
2404
+ const err = new Error(
2405
+ 'The socket was closed while data was being compressed'
2406
+ );
2407
+
2408
+ if (typeof cb === 'function') cb(err);
2409
+
2410
+ for (let i = 0; i < this._queue.length; i++) {
2411
+ const params = this._queue[i];
2412
+ const callback = params[params.length - 1];
2413
+
2414
+ if (typeof callback === 'function') callback(err);
2415
+ }
2416
+
2417
+ return;
2418
+ }
2419
+
2420
+ this._bufferedBytes -= options[kByteLength];
2421
+ this._deflating = false;
2422
+ options.readOnly = false;
2423
+ this.sendFrame(Sender.frame(buf, options), cb);
2424
+ this.dequeue();
2425
+ });
2426
+ }
2427
+
2428
+ /**
2429
+ * Executes queued send operations.
2430
+ *
2431
+ * @private
2432
+ */
2433
+ dequeue() {
2434
+ while (!this._deflating && this._queue.length) {
2435
+ const params = this._queue.shift();
2436
+
2437
+ this._bufferedBytes -= params[3][kByteLength];
2438
+ Reflect.apply(params[0], this, params.slice(1));
2439
+ }
2440
+ }
2441
+
2442
+ /**
2443
+ * Enqueues a send operation.
2444
+ *
2445
+ * @param {Array} params Send operation parameters.
2446
+ * @private
2447
+ */
2448
+ enqueue(params) {
2449
+ this._bufferedBytes += params[3][kByteLength];
2450
+ this._queue.push(params);
2451
+ }
2452
+
2453
+ /**
2454
+ * Sends a frame.
2455
+ *
2456
+ * @param {Buffer[]} list The frame to send
2457
+ * @param {Function} [cb] Callback
2458
+ * @private
2459
+ */
2460
+ sendFrame(list, cb) {
2461
+ if (list.length === 2) {
2462
+ this._socket.cork();
2463
+ this._socket.write(list[0]);
2464
+ this._socket.write(list[1], cb);
2465
+ this._socket.uncork();
2466
+ } else {
2467
+ this._socket.write(list[0], cb);
2468
+ }
2469
+ }
2470
+ }
2471
+
2472
+ module.exports = Sender;
2473
+
2474
+
2475
+ /***/ }),
2476
+
2477
+ /***/ 972:
2478
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2479
+
2480
+ "use strict";
2481
+
2482
+
2483
+ const { Duplex } = __nccwpck_require__(781);
2484
+
2485
+ /**
2486
+ * Emits the `'close'` event on a stream.
2487
+ *
2488
+ * @param {Duplex} stream The stream.
2489
+ * @private
2490
+ */
2491
+ function emitClose(stream) {
2492
+ stream.emit('close');
2493
+ }
2494
+
2495
+ /**
2496
+ * The listener of the `'end'` event.
2497
+ *
2498
+ * @private
2499
+ */
2500
+ function duplexOnEnd() {
2501
+ if (!this.destroyed && this._writableState.finished) {
2502
+ this.destroy();
2503
+ }
2504
+ }
2505
+
2506
+ /**
2507
+ * The listener of the `'error'` event.
2508
+ *
2509
+ * @param {Error} err The error
2510
+ * @private
2511
+ */
2512
+ function duplexOnError(err) {
2513
+ this.removeListener('error', duplexOnError);
2514
+ this.destroy();
2515
+ if (this.listenerCount('error') === 0) {
2516
+ // Do not suppress the throwing behavior.
2517
+ this.emit('error', err);
2518
+ }
2519
+ }
2520
+
2521
+ /**
2522
+ * Wraps a `WebSocket` in a duplex stream.
2523
+ *
2524
+ * @param {WebSocket} ws The `WebSocket` to wrap
2525
+ * @param {Object} [options] The options for the `Duplex` constructor
2526
+ * @return {Duplex} The duplex stream
2527
+ * @public
2528
+ */
2529
+ function createWebSocketStream(ws, options) {
2530
+ let terminateOnDestroy = true;
2531
+
2532
+ const duplex = new Duplex({
2533
+ ...options,
2534
+ autoDestroy: false,
2535
+ emitClose: false,
2536
+ objectMode: false,
2537
+ writableObjectMode: false
2538
+ });
2539
+
2540
+ ws.on('message', function message(msg, isBinary) {
2541
+ const data =
2542
+ !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
2543
+
2544
+ if (!duplex.push(data)) ws.pause();
2545
+ });
2546
+
2547
+ ws.once('error', function error(err) {
2548
+ if (duplex.destroyed) return;
2549
+
2550
+ // Prevent `ws.terminate()` from being called by `duplex._destroy()`.
2551
+ //
2552
+ // - If the `'error'` event is emitted before the `'open'` event, then
2553
+ // `ws.terminate()` is a noop as no socket is assigned.
2554
+ // - Otherwise, the error is re-emitted by the listener of the `'error'`
2555
+ // event of the `Receiver` object. The listener already closes the
2556
+ // connection by calling `ws.close()`. This allows a close frame to be
2557
+ // sent to the other peer. If `ws.terminate()` is called right after this,
2558
+ // then the close frame might not be sent.
2559
+ terminateOnDestroy = false;
2560
+ duplex.destroy(err);
2561
+ });
2562
+
2563
+ ws.once('close', function close() {
2564
+ if (duplex.destroyed) return;
2565
+
2566
+ duplex.push(null);
2567
+ });
2568
+
2569
+ duplex._destroy = function (err, callback) {
2570
+ if (ws.readyState === ws.CLOSED) {
2571
+ callback(err);
2572
+ process.nextTick(emitClose, duplex);
2573
+ return;
2574
+ }
2575
+
2576
+ let called = false;
2577
+
2578
+ ws.once('error', function error(err) {
2579
+ called = true;
2580
+ callback(err);
2581
+ });
2582
+
2583
+ ws.once('close', function close() {
2584
+ if (!called) callback(err);
2585
+ process.nextTick(emitClose, duplex);
2586
+ });
2587
+
2588
+ if (terminateOnDestroy) ws.terminate();
2589
+ };
2590
+
2591
+ duplex._final = function (callback) {
2592
+ if (ws.readyState === ws.CONNECTING) {
2593
+ ws.once('open', function open() {
2594
+ duplex._final(callback);
2595
+ });
2596
+ return;
2597
+ }
2598
+
2599
+ // If the value of the `_socket` property is `null` it means that `ws` is a
2600
+ // client websocket and the handshake failed. In fact, when this happens, a
2601
+ // socket is never assigned to the websocket. Wait for the `'error'` event
2602
+ // that will be emitted by the websocket.
2603
+ if (ws._socket === null) return;
2604
+
2605
+ if (ws._socket._writableState.finished) {
2606
+ callback();
2607
+ if (duplex._readableState.endEmitted) duplex.destroy();
2608
+ } else {
2609
+ ws._socket.once('finish', function finish() {
2610
+ // `duplex` is not destroyed here because the `'end'` event will be
2611
+ // emitted on `duplex` after this `'finish'` event. The EOF signaling
2612
+ // `null` chunk is, in fact, pushed when the websocket emits `'close'`.
2613
+ callback();
2614
+ });
2615
+ ws.close();
2616
+ }
2617
+ };
2618
+
2619
+ duplex._read = function () {
2620
+ if (ws.isPaused) ws.resume();
2621
+ };
2622
+
2623
+ duplex._write = function (chunk, encoding, callback) {
2624
+ if (ws.readyState === ws.CONNECTING) {
2625
+ ws.once('open', function open() {
2626
+ duplex._write(chunk, encoding, callback);
2627
+ });
2628
+ return;
2629
+ }
2630
+
2631
+ ws.send(chunk, callback);
2632
+ };
2633
+
2634
+ duplex.on('end', duplexOnEnd);
2635
+ duplex.on('error', duplexOnError);
2636
+ return duplex;
2637
+ }
2638
+
2639
+ module.exports = createWebSocketStream;
2640
+
2641
+
2642
+ /***/ }),
2643
+
2644
+ /***/ 156:
2645
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2646
+
2647
+ "use strict";
2648
+
2649
+
2650
+ const { tokenChars } = __nccwpck_require__(23);
2651
+
2652
+ /**
2653
+ * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
2654
+ *
2655
+ * @param {String} header The field value of the header
2656
+ * @return {Set} The subprotocol names
2657
+ * @public
2658
+ */
2659
+ function parse(header) {
2660
+ const protocols = new Set();
2661
+ let start = -1;
2662
+ let end = -1;
2663
+ let i = 0;
2664
+
2665
+ for (i; i < header.length; i++) {
2666
+ const code = header.charCodeAt(i);
2667
+
2668
+ if (end === -1 && tokenChars[code] === 1) {
2669
+ if (start === -1) start = i;
2670
+ } else if (
2671
+ i !== 0 &&
2672
+ (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
2673
+ ) {
2674
+ if (end === -1 && start !== -1) end = i;
2675
+ } else if (code === 0x2c /* ',' */) {
2676
+ if (start === -1) {
2677
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2678
+ }
2679
+
2680
+ if (end === -1) end = i;
2681
+
2682
+ const protocol = header.slice(start, end);
2683
+
2684
+ if (protocols.has(protocol)) {
2685
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
2686
+ }
2687
+
2688
+ protocols.add(protocol);
2689
+ start = end = -1;
2690
+ } else {
2691
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2692
+ }
2693
+ }
2694
+
2695
+ if (start === -1 || end !== -1) {
2696
+ throw new SyntaxError('Unexpected end of input');
2697
+ }
2698
+
2699
+ const protocol = header.slice(start, i);
2700
+
2701
+ if (protocols.has(protocol)) {
2702
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
2703
+ }
2704
+
2705
+ protocols.add(protocol);
2706
+ return protocols;
2707
+ }
2708
+
2709
+ module.exports = { parse };
2710
+
2711
+
2712
+ /***/ }),
2713
+
2714
+ /***/ 23:
2715
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2716
+
2717
+ "use strict";
2718
+
2719
+
2720
+ const { isUtf8 } = __nccwpck_require__(300);
2721
+
2722
+ //
2723
+ // Allowed token characters:
2724
+ //
2725
+ // '!', '#', '$', '%', '&', ''', '*', '+', '-',
2726
+ // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
2727
+ //
2728
+ // tokenChars[32] === 0 // ' '
2729
+ // tokenChars[33] === 1 // '!'
2730
+ // tokenChars[34] === 0 // '"'
2731
+ // ...
2732
+ //
2733
+ // prettier-ignore
2734
+ const tokenChars = [
2735
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
2736
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
2737
+ 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
2738
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
2739
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
2740
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
2741
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
2742
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
2743
+ ];
2744
+
2745
+ /**
2746
+ * Checks if a status code is allowed in a close frame.
2747
+ *
2748
+ * @param {Number} code The status code
2749
+ * @return {Boolean} `true` if the status code is valid, else `false`
2750
+ * @public
2751
+ */
2752
+ function isValidStatusCode(code) {
2753
+ return (
2754
+ (code >= 1000 &&
2755
+ code <= 1014 &&
2756
+ code !== 1004 &&
2757
+ code !== 1005 &&
2758
+ code !== 1006) ||
2759
+ (code >= 3000 && code <= 4999)
2760
+ );
2761
+ }
2762
+
2763
+ /**
2764
+ * Checks if a given buffer contains only correct UTF-8.
2765
+ * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
2766
+ * Markus Kuhn.
2767
+ *
2768
+ * @param {Buffer} buf The buffer to check
2769
+ * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
2770
+ * @public
2771
+ */
2772
+ function _isValidUTF8(buf) {
2773
+ const len = buf.length;
2774
+ let i = 0;
2775
+
2776
+ while (i < len) {
2777
+ if ((buf[i] & 0x80) === 0) {
2778
+ // 0xxxxxxx
2779
+ i++;
2780
+ } else if ((buf[i] & 0xe0) === 0xc0) {
2781
+ // 110xxxxx 10xxxxxx
2782
+ if (
2783
+ i + 1 === len ||
2784
+ (buf[i + 1] & 0xc0) !== 0x80 ||
2785
+ (buf[i] & 0xfe) === 0xc0 // Overlong
2786
+ ) {
2787
+ return false;
2788
+ }
2789
+
2790
+ i += 2;
2791
+ } else if ((buf[i] & 0xf0) === 0xe0) {
2792
+ // 1110xxxx 10xxxxxx 10xxxxxx
2793
+ if (
2794
+ i + 2 >= len ||
2795
+ (buf[i + 1] & 0xc0) !== 0x80 ||
2796
+ (buf[i + 2] & 0xc0) !== 0x80 ||
2797
+ (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
2798
+ (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
2799
+ ) {
2800
+ return false;
2801
+ }
2802
+
2803
+ i += 3;
2804
+ } else if ((buf[i] & 0xf8) === 0xf0) {
2805
+ // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2806
+ if (
2807
+ i + 3 >= len ||
2808
+ (buf[i + 1] & 0xc0) !== 0x80 ||
2809
+ (buf[i + 2] & 0xc0) !== 0x80 ||
2810
+ (buf[i + 3] & 0xc0) !== 0x80 ||
2811
+ (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
2812
+ (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
2813
+ buf[i] > 0xf4 // > U+10FFFF
2814
+ ) {
2815
+ return false;
2816
+ }
2817
+
2818
+ i += 4;
2819
+ } else {
2820
+ return false;
2821
+ }
2822
+ }
2823
+
2824
+ return true;
2825
+ }
2826
+
2827
+ module.exports = {
2828
+ isValidStatusCode,
2829
+ isValidUTF8: _isValidUTF8,
2830
+ tokenChars
2831
+ };
2832
+
2833
+ if (isUtf8) {
2834
+ module.exports.isValidUTF8 = function (buf) {
2835
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
2836
+ };
2837
+ } /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {
2838
+ try {
2839
+ const isValidUTF8 = __nccwpck_require__(177);
2840
+
2841
+ module.exports.isValidUTF8 = function (buf) {
2842
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
2843
+ };
2844
+ } catch (e) {
2845
+ // Continue regardless of the error.
2846
+ }
2847
+ }
2848
+
2849
+
2850
+ /***/ }),
2851
+
2852
+ /***/ 51:
2853
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2854
+
2855
+ "use strict";
2856
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
2857
+
2858
+
2859
+
2860
+ const EventEmitter = __nccwpck_require__(361);
2861
+ const http = __nccwpck_require__(685);
2862
+ const { Duplex } = __nccwpck_require__(781);
2863
+ const { createHash } = __nccwpck_require__(113);
2864
+
2865
+ const extension = __nccwpck_require__(252);
2866
+ const PerMessageDeflate = __nccwpck_require__(330);
2867
+ const subprotocol = __nccwpck_require__(156);
2868
+ const WebSocket = __nccwpck_require__(462);
2869
+ const { GUID, kWebSocket } = __nccwpck_require__(862);
2870
+
2871
+ const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
2872
+
2873
+ const RUNNING = 0;
2874
+ const CLOSING = 1;
2875
+ const CLOSED = 2;
2876
+
2877
+ /**
2878
+ * Class representing a WebSocket server.
2879
+ *
2880
+ * @extends EventEmitter
2881
+ */
2882
+ class WebSocketServer extends EventEmitter {
2883
+ /**
2884
+ * Create a `WebSocketServer` instance.
2885
+ *
2886
+ * @param {Object} options Configuration options
2887
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
2888
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2889
+ * multiple times in the same tick
2890
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
2891
+ * automatically send a pong in response to a ping
2892
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
2893
+ * pending connections
2894
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
2895
+ * track clients
2896
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
2897
+ * @param {String} [options.host] The hostname where to bind the server
2898
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
2899
+ * size
2900
+ * @param {Boolean} [options.noServer=false] Enable no server mode
2901
+ * @param {String} [options.path] Accept only connections matching this path
2902
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
2903
+ * permessage-deflate
2904
+ * @param {Number} [options.port] The port where to bind the server
2905
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
2906
+ * server to use
2907
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2908
+ * not to skip UTF-8 validation for text and close messages
2909
+ * @param {Function} [options.verifyClient] A hook to reject connections
2910
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
2911
+ * class to use. It must be the `WebSocket` class or class that extends it
2912
+ * @param {Function} [callback] A listener for the `listening` event
2913
+ */
2914
+ constructor(options, callback) {
2915
+ super();
2916
+
2917
+ options = {
2918
+ allowSynchronousEvents: true,
2919
+ autoPong: true,
2920
+ maxPayload: 100 * 1024 * 1024,
2921
+ skipUTF8Validation: false,
2922
+ perMessageDeflate: false,
2923
+ handleProtocols: null,
2924
+ clientTracking: true,
2925
+ verifyClient: null,
2926
+ noServer: false,
2927
+ backlog: null, // use default (511 as implemented in net.js)
2928
+ server: null,
2929
+ host: null,
2930
+ path: null,
2931
+ port: null,
2932
+ WebSocket,
2933
+ ...options
2934
+ };
2935
+
2936
+ if (
2937
+ (options.port == null && !options.server && !options.noServer) ||
2938
+ (options.port != null && (options.server || options.noServer)) ||
2939
+ (options.server && options.noServer)
2940
+ ) {
2941
+ throw new TypeError(
2942
+ 'One and only one of the "port", "server", or "noServer" options ' +
2943
+ 'must be specified'
2944
+ );
2945
+ }
2946
+
2947
+ if (options.port != null) {
2948
+ this._server = http.createServer((req, res) => {
2949
+ const body = http.STATUS_CODES[426];
2950
+
2951
+ res.writeHead(426, {
2952
+ 'Content-Length': body.length,
2953
+ 'Content-Type': 'text/plain'
2954
+ });
2955
+ res.end(body);
2956
+ });
2957
+ this._server.listen(
2958
+ options.port,
2959
+ options.host,
2960
+ options.backlog,
2961
+ callback
2962
+ );
2963
+ } else if (options.server) {
2964
+ this._server = options.server;
2965
+ }
2966
+
2967
+ if (this._server) {
2968
+ const emitConnection = this.emit.bind(this, 'connection');
2969
+
2970
+ this._removeListeners = addListeners(this._server, {
2971
+ listening: this.emit.bind(this, 'listening'),
2972
+ error: this.emit.bind(this, 'error'),
2973
+ upgrade: (req, socket, head) => {
2974
+ this.handleUpgrade(req, socket, head, emitConnection);
2975
+ }
2976
+ });
2977
+ }
2978
+
2979
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
2980
+ if (options.clientTracking) {
2981
+ this.clients = new Set();
2982
+ this._shouldEmitClose = false;
2983
+ }
2984
+
2985
+ this.options = options;
2986
+ this._state = RUNNING;
2987
+ }
2988
+
2989
+ /**
2990
+ * Returns the bound address, the address family name, and port of the server
2991
+ * as reported by the operating system if listening on an IP socket.
2992
+ * If the server is listening on a pipe or UNIX domain socket, the name is
2993
+ * returned as a string.
2994
+ *
2995
+ * @return {(Object|String|null)} The address of the server
2996
+ * @public
2997
+ */
2998
+ address() {
2999
+ if (this.options.noServer) {
3000
+ throw new Error('The server is operating in "noServer" mode');
3001
+ }
3002
+
3003
+ if (!this._server) return null;
3004
+ return this._server.address();
3005
+ }
3006
+
3007
+ /**
3008
+ * Stop the server from accepting new connections and emit the `'close'` event
3009
+ * when all existing connections are closed.
3010
+ *
3011
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3012
+ * @public
3013
+ */
3014
+ close(cb) {
3015
+ if (this._state === CLOSED) {
3016
+ if (cb) {
3017
+ this.once('close', () => {
3018
+ cb(new Error('The server is not running'));
3019
+ });
3020
+ }
3021
+
3022
+ process.nextTick(emitClose, this);
3023
+ return;
3024
+ }
3025
+
3026
+ if (cb) this.once('close', cb);
3027
+
3028
+ if (this._state === CLOSING) return;
3029
+ this._state = CLOSING;
3030
+
3031
+ if (this.options.noServer || this.options.server) {
3032
+ if (this._server) {
3033
+ this._removeListeners();
3034
+ this._removeListeners = this._server = null;
3035
+ }
3036
+
3037
+ if (this.clients) {
3038
+ if (!this.clients.size) {
3039
+ process.nextTick(emitClose, this);
3040
+ } else {
3041
+ this._shouldEmitClose = true;
3042
+ }
3043
+ } else {
3044
+ process.nextTick(emitClose, this);
3045
+ }
3046
+ } else {
3047
+ const server = this._server;
3048
+
3049
+ this._removeListeners();
3050
+ this._removeListeners = this._server = null;
3051
+
3052
+ //
3053
+ // The HTTP/S server was created internally. Close it, and rely on its
3054
+ // `'close'` event.
3055
+ //
3056
+ server.close(() => {
3057
+ emitClose(this);
3058
+ });
3059
+ }
3060
+ }
3061
+
3062
+ /**
3063
+ * See if a given request should be handled by this server instance.
3064
+ *
3065
+ * @param {http.IncomingMessage} req Request object to inspect
3066
+ * @return {Boolean} `true` if the request is valid, else `false`
3067
+ * @public
3068
+ */
3069
+ shouldHandle(req) {
3070
+ if (this.options.path) {
3071
+ const index = req.url.indexOf('?');
3072
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3073
+
3074
+ if (pathname !== this.options.path) return false;
3075
+ }
3076
+
3077
+ return true;
3078
+ }
3079
+
3080
+ /**
3081
+ * Handle a HTTP Upgrade request.
3082
+ *
3083
+ * @param {http.IncomingMessage} req The request object
3084
+ * @param {Duplex} socket The network socket between the server and client
3085
+ * @param {Buffer} head The first packet of the upgraded stream
3086
+ * @param {Function} cb Callback
3087
+ * @public
3088
+ */
3089
+ handleUpgrade(req, socket, head, cb) {
3090
+ socket.on('error', socketOnError);
3091
+
3092
+ const key = req.headers['sec-websocket-key'];
3093
+ const version = +req.headers['sec-websocket-version'];
3094
+
3095
+ if (req.method !== 'GET') {
3096
+ const message = 'Invalid HTTP method';
3097
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3098
+ return;
3099
+ }
3100
+
3101
+ if (req.headers.upgrade.toLowerCase() !== 'websocket') {
3102
+ const message = 'Invalid Upgrade header';
3103
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3104
+ return;
3105
+ }
3106
+
3107
+ if (!key || !keyRegex.test(key)) {
3108
+ const message = 'Missing or invalid Sec-WebSocket-Key header';
3109
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3110
+ return;
3111
+ }
3112
+
3113
+ if (version !== 8 && version !== 13) {
3114
+ const message = 'Missing or invalid Sec-WebSocket-Version header';
3115
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3116
+ return;
3117
+ }
3118
+
3119
+ if (!this.shouldHandle(req)) {
3120
+ abortHandshake(socket, 400);
3121
+ return;
3122
+ }
3123
+
3124
+ const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
3125
+ let protocols = new Set();
3126
+
3127
+ if (secWebSocketProtocol !== undefined) {
3128
+ try {
3129
+ protocols = subprotocol.parse(secWebSocketProtocol);
3130
+ } catch (err) {
3131
+ const message = 'Invalid Sec-WebSocket-Protocol header';
3132
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3133
+ return;
3134
+ }
3135
+ }
3136
+
3137
+ const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
3138
+ const extensions = {};
3139
+
3140
+ if (
3141
+ this.options.perMessageDeflate &&
3142
+ secWebSocketExtensions !== undefined
3143
+ ) {
3144
+ const perMessageDeflate = new PerMessageDeflate(
3145
+ this.options.perMessageDeflate,
3146
+ true,
3147
+ this.options.maxPayload
3148
+ );
3149
+
3150
+ try {
3151
+ const offers = extension.parse(secWebSocketExtensions);
3152
+
3153
+ if (offers[PerMessageDeflate.extensionName]) {
3154
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3155
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3156
+ }
3157
+ } catch (err) {
3158
+ const message =
3159
+ 'Invalid or unacceptable Sec-WebSocket-Extensions header';
3160
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3161
+ return;
3162
+ }
3163
+ }
3164
+
3165
+ //
3166
+ // Optionally call external client verification handler.
3167
+ //
3168
+ if (this.options.verifyClient) {
3169
+ const info = {
3170
+ origin:
3171
+ req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
3172
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3173
+ req
3174
+ };
3175
+
3176
+ if (this.options.verifyClient.length === 2) {
3177
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3178
+ if (!verified) {
3179
+ return abortHandshake(socket, code || 401, message, headers);
3180
+ }
3181
+
3182
+ this.completeUpgrade(
3183
+ extensions,
3184
+ key,
3185
+ protocols,
3186
+ req,
3187
+ socket,
3188
+ head,
3189
+ cb
3190
+ );
3191
+ });
3192
+ return;
3193
+ }
3194
+
3195
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3196
+ }
3197
+
3198
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3199
+ }
3200
+
3201
+ /**
3202
+ * Upgrade the connection to WebSocket.
3203
+ *
3204
+ * @param {Object} extensions The accepted extensions
3205
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3206
+ * @param {Set} protocols The subprotocols
3207
+ * @param {http.IncomingMessage} req The request object
3208
+ * @param {Duplex} socket The network socket between the server and client
3209
+ * @param {Buffer} head The first packet of the upgraded stream
3210
+ * @param {Function} cb Callback
3211
+ * @throws {Error} If called more than once with the same socket
3212
+ * @private
3213
+ */
3214
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3215
+ //
3216
+ // Destroy the socket if the client has already sent a FIN packet.
3217
+ //
3218
+ if (!socket.readable || !socket.writable) return socket.destroy();
3219
+
3220
+ if (socket[kWebSocket]) {
3221
+ throw new Error(
3222
+ 'server.handleUpgrade() was called more than once with the same ' +
3223
+ 'socket, possibly due to a misconfiguration'
3224
+ );
3225
+ }
3226
+
3227
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3228
+
3229
+ const digest = createHash('sha1')
3230
+ .update(key + GUID)
3231
+ .digest('base64');
3232
+
3233
+ const headers = [
3234
+ 'HTTP/1.1 101 Switching Protocols',
3235
+ 'Upgrade: websocket',
3236
+ 'Connection: Upgrade',
3237
+ `Sec-WebSocket-Accept: ${digest}`
3238
+ ];
3239
+
3240
+ const ws = new this.options.WebSocket(null, undefined, this.options);
3241
+
3242
+ if (protocols.size) {
3243
+ //
3244
+ // Optionally call external protocol selection handler.
3245
+ //
3246
+ const protocol = this.options.handleProtocols
3247
+ ? this.options.handleProtocols(protocols, req)
3248
+ : protocols.values().next().value;
3249
+
3250
+ if (protocol) {
3251
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3252
+ ws._protocol = protocol;
3253
+ }
3254
+ }
3255
+
3256
+ if (extensions[PerMessageDeflate.extensionName]) {
3257
+ const params = extensions[PerMessageDeflate.extensionName].params;
3258
+ const value = extension.format({
3259
+ [PerMessageDeflate.extensionName]: [params]
3260
+ });
3261
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3262
+ ws._extensions = extensions;
3263
+ }
3264
+
3265
+ //
3266
+ // Allow external modification/inspection of handshake headers.
3267
+ //
3268
+ this.emit('headers', headers, req);
3269
+
3270
+ socket.write(headers.concat('\r\n').join('\r\n'));
3271
+ socket.removeListener('error', socketOnError);
3272
+
3273
+ ws.setSocket(socket, head, {
3274
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3275
+ maxPayload: this.options.maxPayload,
3276
+ skipUTF8Validation: this.options.skipUTF8Validation
3277
+ });
3278
+
3279
+ if (this.clients) {
3280
+ this.clients.add(ws);
3281
+ ws.on('close', () => {
3282
+ this.clients.delete(ws);
3283
+
3284
+ if (this._shouldEmitClose && !this.clients.size) {
3285
+ process.nextTick(emitClose, this);
3286
+ }
3287
+ });
3288
+ }
3289
+
3290
+ cb(ws, req);
3291
+ }
3292
+ }
3293
+
3294
+ module.exports = WebSocketServer;
3295
+
3296
+ /**
3297
+ * Add event listeners on an `EventEmitter` using a map of <event, listener>
3298
+ * pairs.
3299
+ *
3300
+ * @param {EventEmitter} server The event emitter
3301
+ * @param {Object.<String, Function>} map The listeners to add
3302
+ * @return {Function} A function that will remove the added listeners when
3303
+ * called
3304
+ * @private
3305
+ */
3306
+ function addListeners(server, map) {
3307
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3308
+
3309
+ return function removeListeners() {
3310
+ for (const event of Object.keys(map)) {
3311
+ server.removeListener(event, map[event]);
3312
+ }
3313
+ };
3314
+ }
3315
+
3316
+ /**
3317
+ * Emit a `'close'` event on an `EventEmitter`.
3318
+ *
3319
+ * @param {EventEmitter} server The event emitter
3320
+ * @private
3321
+ */
3322
+ function emitClose(server) {
3323
+ server._state = CLOSED;
3324
+ server.emit('close');
3325
+ }
3326
+
3327
+ /**
3328
+ * Handle socket errors.
3329
+ *
3330
+ * @private
3331
+ */
3332
+ function socketOnError() {
3333
+ this.destroy();
3334
+ }
3335
+
3336
+ /**
3337
+ * Close the connection when preconditions are not fulfilled.
3338
+ *
3339
+ * @param {Duplex} socket The socket of the upgrade request
3340
+ * @param {Number} code The HTTP response status code
3341
+ * @param {String} [message] The HTTP response body
3342
+ * @param {Object} [headers] Additional HTTP response headers
3343
+ * @private
3344
+ */
3345
+ function abortHandshake(socket, code, message, headers) {
3346
+ //
3347
+ // The socket is writable unless the user destroyed or ended it before calling
3348
+ // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
3349
+ // error. Handling this does not make much sense as the worst that can happen
3350
+ // is that some of the data written by the user might be discarded due to the
3351
+ // call to `socket.end()` below, which triggers an `'error'` event that in
3352
+ // turn causes the socket to be destroyed.
3353
+ //
3354
+ message = message || http.STATUS_CODES[code];
3355
+ headers = {
3356
+ Connection: 'close',
3357
+ 'Content-Type': 'text/html',
3358
+ 'Content-Length': Buffer.byteLength(message),
3359
+ ...headers
3360
+ };
3361
+
3362
+ socket.once('finish', socket.destroy);
3363
+
3364
+ socket.end(
3365
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
3366
+ Object.keys(headers)
3367
+ .map((h) => `${h}: ${headers[h]}`)
3368
+ .join('\r\n') +
3369
+ '\r\n\r\n' +
3370
+ message
3371
+ );
3372
+ }
3373
+
3374
+ /**
3375
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
3376
+ * one listener for it, otherwise call `abortHandshake()`.
3377
+ *
3378
+ * @param {WebSocketServer} server The WebSocket server
3379
+ * @param {http.IncomingMessage} req The request object
3380
+ * @param {Duplex} socket The socket of the upgrade request
3381
+ * @param {Number} code The HTTP response status code
3382
+ * @param {String} message The HTTP response body
3383
+ * @private
3384
+ */
3385
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
3386
+ if (server.listenerCount('wsClientError')) {
3387
+ const err = new Error(message);
3388
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3389
+
3390
+ server.emit('wsClientError', err, socket, req);
3391
+ } else {
3392
+ abortHandshake(socket, code, message);
3393
+ }
3394
+ }
3395
+
3396
+
3397
+ /***/ }),
3398
+
3399
+ /***/ 462:
3400
+ /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
3401
+
3402
+ "use strict";
3403
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */
3404
+
3405
+
3406
+
3407
+ const EventEmitter = __nccwpck_require__(361);
3408
+ const https = __nccwpck_require__(687);
3409
+ const http = __nccwpck_require__(685);
3410
+ const net = __nccwpck_require__(808);
3411
+ const tls = __nccwpck_require__(404);
3412
+ const { randomBytes, createHash } = __nccwpck_require__(113);
3413
+ const { Duplex, Readable } = __nccwpck_require__(781);
3414
+ const { URL } = __nccwpck_require__(310);
3415
+
3416
+ const PerMessageDeflate = __nccwpck_require__(330);
3417
+ const Receiver = __nccwpck_require__(663);
3418
+ const Sender = __nccwpck_require__(19);
3419
+ const {
3420
+ BINARY_TYPES,
3421
+ EMPTY_BUFFER,
3422
+ GUID,
3423
+ kForOnEventAttribute,
3424
+ kListener,
3425
+ kStatusCode,
3426
+ kWebSocket,
3427
+ NOOP
3428
+ } = __nccwpck_require__(862);
3429
+ const {
3430
+ EventTarget: { addEventListener, removeEventListener }
3431
+ } = __nccwpck_require__(360);
3432
+ const { format, parse } = __nccwpck_require__(252);
3433
+ const { toBuffer } = __nccwpck_require__(820);
3434
+
3435
+ const closeTimeout = 30 * 1000;
3436
+ const kAborted = Symbol('kAborted');
3437
+ const protocolVersions = [8, 13];
3438
+ const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
3439
+ const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
3440
+
3441
+ /**
3442
+ * Class representing a WebSocket.
3443
+ *
3444
+ * @extends EventEmitter
3445
+ */
3446
+ class WebSocket extends EventEmitter {
3447
+ /**
3448
+ * Create a new `WebSocket`.
3449
+ *
3450
+ * @param {(String|URL)} address The URL to which to connect
3451
+ * @param {(String|String[])} [protocols] The subprotocols
3452
+ * @param {Object} [options] Connection options
3453
+ */
3454
+ constructor(address, protocols, options) {
3455
+ super();
3456
+
3457
+ this._binaryType = BINARY_TYPES[0];
3458
+ this._closeCode = 1006;
3459
+ this._closeFrameReceived = false;
3460
+ this._closeFrameSent = false;
3461
+ this._closeMessage = EMPTY_BUFFER;
3462
+ this._closeTimer = null;
3463
+ this._extensions = {};
3464
+ this._paused = false;
3465
+ this._protocol = '';
3466
+ this._readyState = WebSocket.CONNECTING;
3467
+ this._receiver = null;
3468
+ this._sender = null;
3469
+ this._socket = null;
3470
+
3471
+ if (address !== null) {
3472
+ this._bufferedAmount = 0;
3473
+ this._isServer = false;
3474
+ this._redirects = 0;
3475
+
3476
+ if (protocols === undefined) {
3477
+ protocols = [];
3478
+ } else if (!Array.isArray(protocols)) {
3479
+ if (typeof protocols === 'object' && protocols !== null) {
3480
+ options = protocols;
3481
+ protocols = [];
3482
+ } else {
3483
+ protocols = [protocols];
3484
+ }
3485
+ }
3486
+
3487
+ initAsClient(this, address, protocols, options);
3488
+ } else {
3489
+ this._autoPong = options.autoPong;
3490
+ this._isServer = true;
3491
+ }
3492
+ }
3493
+
3494
+ /**
3495
+ * This deviates from the WHATWG interface since ws doesn't support the
3496
+ * required default "blob" type (instead we define a custom "nodebuffer"
3497
+ * type).
3498
+ *
3499
+ * @type {String}
3500
+ */
3501
+ get binaryType() {
3502
+ return this._binaryType;
3503
+ }
3504
+
3505
+ set binaryType(type) {
3506
+ if (!BINARY_TYPES.includes(type)) return;
3507
+
3508
+ this._binaryType = type;
3509
+
3510
+ //
3511
+ // Allow to change `binaryType` on the fly.
3512
+ //
3513
+ if (this._receiver) this._receiver._binaryType = type;
3514
+ }
3515
+
3516
+ /**
3517
+ * @type {Number}
3518
+ */
3519
+ get bufferedAmount() {
3520
+ if (!this._socket) return this._bufferedAmount;
3521
+
3522
+ return this._socket._writableState.length + this._sender._bufferedBytes;
3523
+ }
3524
+
3525
+ /**
3526
+ * @type {String}
3527
+ */
3528
+ get extensions() {
3529
+ return Object.keys(this._extensions).join();
3530
+ }
3531
+
3532
+ /**
3533
+ * @type {Boolean}
3534
+ */
3535
+ get isPaused() {
3536
+ return this._paused;
3537
+ }
3538
+
3539
+ /**
3540
+ * @type {Function}
3541
+ */
3542
+ /* istanbul ignore next */
3543
+ get onclose() {
3544
+ return null;
3545
+ }
3546
+
3547
+ /**
3548
+ * @type {Function}
3549
+ */
3550
+ /* istanbul ignore next */
3551
+ get onerror() {
3552
+ return null;
3553
+ }
3554
+
3555
+ /**
3556
+ * @type {Function}
3557
+ */
3558
+ /* istanbul ignore next */
3559
+ get onopen() {
3560
+ return null;
3561
+ }
3562
+
3563
+ /**
3564
+ * @type {Function}
3565
+ */
3566
+ /* istanbul ignore next */
3567
+ get onmessage() {
3568
+ return null;
3569
+ }
3570
+
3571
+ /**
3572
+ * @type {String}
3573
+ */
3574
+ get protocol() {
3575
+ return this._protocol;
3576
+ }
3577
+
3578
+ /**
3579
+ * @type {Number}
3580
+ */
3581
+ get readyState() {
3582
+ return this._readyState;
3583
+ }
3584
+
3585
+ /**
3586
+ * @type {String}
3587
+ */
3588
+ get url() {
3589
+ return this._url;
3590
+ }
3591
+
3592
+ /**
3593
+ * Set up the socket and the internal resources.
3594
+ *
3595
+ * @param {Duplex} socket The network socket between the server and client
3596
+ * @param {Buffer} head The first packet of the upgraded stream
3597
+ * @param {Object} options Options object
3598
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
3599
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3600
+ * multiple times in the same tick
3601
+ * @param {Function} [options.generateMask] The function used to generate the
3602
+ * masking key
3603
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
3604
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3605
+ * not to skip UTF-8 validation for text and close messages
3606
+ * @private
3607
+ */
3608
+ setSocket(socket, head, options) {
3609
+ const receiver = new Receiver({
3610
+ allowSynchronousEvents: options.allowSynchronousEvents,
3611
+ binaryType: this.binaryType,
3612
+ extensions: this._extensions,
3613
+ isServer: this._isServer,
3614
+ maxPayload: options.maxPayload,
3615
+ skipUTF8Validation: options.skipUTF8Validation
3616
+ });
3617
+
3618
+ this._sender = new Sender(socket, this._extensions, options.generateMask);
3619
+ this._receiver = receiver;
3620
+ this._socket = socket;
3621
+
3622
+ receiver[kWebSocket] = this;
3623
+ socket[kWebSocket] = this;
3624
+
3625
+ receiver.on('conclude', receiverOnConclude);
3626
+ receiver.on('drain', receiverOnDrain);
3627
+ receiver.on('error', receiverOnError);
3628
+ receiver.on('message', receiverOnMessage);
3629
+ receiver.on('ping', receiverOnPing);
3630
+ receiver.on('pong', receiverOnPong);
3631
+
3632
+ //
3633
+ // These methods may not be available if `socket` is just a `Duplex`.
3634
+ //
3635
+ if (socket.setTimeout) socket.setTimeout(0);
3636
+ if (socket.setNoDelay) socket.setNoDelay();
3637
+
3638
+ if (head.length > 0) socket.unshift(head);
3639
+
3640
+ socket.on('close', socketOnClose);
3641
+ socket.on('data', socketOnData);
3642
+ socket.on('end', socketOnEnd);
3643
+ socket.on('error', socketOnError);
3644
+
3645
+ this._readyState = WebSocket.OPEN;
3646
+ this.emit('open');
3647
+ }
3648
+
3649
+ /**
3650
+ * Emit the `'close'` event.
3651
+ *
3652
+ * @private
3653
+ */
3654
+ emitClose() {
3655
+ if (!this._socket) {
3656
+ this._readyState = WebSocket.CLOSED;
3657
+ this.emit('close', this._closeCode, this._closeMessage);
3658
+ return;
3659
+ }
3660
+
3661
+ if (this._extensions[PerMessageDeflate.extensionName]) {
3662
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
3663
+ }
3664
+
3665
+ this._receiver.removeAllListeners();
3666
+ this._readyState = WebSocket.CLOSED;
3667
+ this.emit('close', this._closeCode, this._closeMessage);
3668
+ }
3669
+
3670
+ /**
3671
+ * Start a closing handshake.
3672
+ *
3673
+ * +----------+ +-----------+ +----------+
3674
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
3675
+ * | +----------+ +-----------+ +----------+ |
3676
+ * +----------+ +-----------+ |
3677
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
3678
+ * +----------+ +-----------+ |
3679
+ * | | | +---+ |
3680
+ * +------------------------+-->|fin| - - - -
3681
+ * | +---+ | +---+
3682
+ * - - - - -|fin|<---------------------+
3683
+ * +---+
3684
+ *
3685
+ * @param {Number} [code] Status code explaining why the connection is closing
3686
+ * @param {(String|Buffer)} [data] The reason why the connection is
3687
+ * closing
3688
+ * @public
3689
+ */
3690
+ close(code, data) {
3691
+ if (this.readyState === WebSocket.CLOSED) return;
3692
+ if (this.readyState === WebSocket.CONNECTING) {
3693
+ const msg = 'WebSocket was closed before the connection was established';
3694
+ abortHandshake(this, this._req, msg);
3695
+ return;
3696
+ }
3697
+
3698
+ if (this.readyState === WebSocket.CLOSING) {
3699
+ if (
3700
+ this._closeFrameSent &&
3701
+ (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
3702
+ ) {
3703
+ this._socket.end();
3704
+ }
3705
+
3706
+ return;
3707
+ }
3708
+
3709
+ this._readyState = WebSocket.CLOSING;
3710
+ this._sender.close(code, data, !this._isServer, (err) => {
3711
+ //
3712
+ // This error is handled by the `'error'` listener on the socket. We only
3713
+ // want to know if the close frame has been sent here.
3714
+ //
3715
+ if (err) return;
3716
+
3717
+ this._closeFrameSent = true;
3718
+
3719
+ if (
3720
+ this._closeFrameReceived ||
3721
+ this._receiver._writableState.errorEmitted
3722
+ ) {
3723
+ this._socket.end();
3724
+ }
3725
+ });
3726
+
3727
+ //
3728
+ // Specify a timeout for the closing handshake to complete.
3729
+ //
3730
+ this._closeTimer = setTimeout(
3731
+ this._socket.destroy.bind(this._socket),
3732
+ closeTimeout
3733
+ );
3734
+ }
3735
+
3736
+ /**
3737
+ * Pause the socket.
3738
+ *
3739
+ * @public
3740
+ */
3741
+ pause() {
3742
+ if (
3743
+ this.readyState === WebSocket.CONNECTING ||
3744
+ this.readyState === WebSocket.CLOSED
3745
+ ) {
3746
+ return;
3747
+ }
3748
+
3749
+ this._paused = true;
3750
+ this._socket.pause();
3751
+ }
3752
+
3753
+ /**
3754
+ * Send a ping.
3755
+ *
3756
+ * @param {*} [data] The data to send
3757
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
3758
+ * @param {Function} [cb] Callback which is executed when the ping is sent
3759
+ * @public
3760
+ */
3761
+ ping(data, mask, cb) {
3762
+ if (this.readyState === WebSocket.CONNECTING) {
3763
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
3764
+ }
3765
+
3766
+ if (typeof data === 'function') {
3767
+ cb = data;
3768
+ data = mask = undefined;
3769
+ } else if (typeof mask === 'function') {
3770
+ cb = mask;
3771
+ mask = undefined;
3772
+ }
3773
+
3774
+ if (typeof data === 'number') data = data.toString();
3775
+
3776
+ if (this.readyState !== WebSocket.OPEN) {
3777
+ sendAfterClose(this, data, cb);
3778
+ return;
3779
+ }
3780
+
3781
+ if (mask === undefined) mask = !this._isServer;
3782
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
3783
+ }
3784
+
3785
+ /**
3786
+ * Send a pong.
3787
+ *
3788
+ * @param {*} [data] The data to send
3789
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
3790
+ * @param {Function} [cb] Callback which is executed when the pong is sent
3791
+ * @public
3792
+ */
3793
+ pong(data, mask, cb) {
3794
+ if (this.readyState === WebSocket.CONNECTING) {
3795
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
3796
+ }
3797
+
3798
+ if (typeof data === 'function') {
3799
+ cb = data;
3800
+ data = mask = undefined;
3801
+ } else if (typeof mask === 'function') {
3802
+ cb = mask;
3803
+ mask = undefined;
3804
+ }
3805
+
3806
+ if (typeof data === 'number') data = data.toString();
3807
+
3808
+ if (this.readyState !== WebSocket.OPEN) {
3809
+ sendAfterClose(this, data, cb);
3810
+ return;
3811
+ }
3812
+
3813
+ if (mask === undefined) mask = !this._isServer;
3814
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
3815
+ }
3816
+
3817
+ /**
3818
+ * Resume the socket.
3819
+ *
3820
+ * @public
3821
+ */
3822
+ resume() {
3823
+ if (
3824
+ this.readyState === WebSocket.CONNECTING ||
3825
+ this.readyState === WebSocket.CLOSED
3826
+ ) {
3827
+ return;
3828
+ }
3829
+
3830
+ this._paused = false;
3831
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
3832
+ }
3833
+
3834
+ /**
3835
+ * Send a data message.
3836
+ *
3837
+ * @param {*} data The message to send
3838
+ * @param {Object} [options] Options object
3839
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
3840
+ * text
3841
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
3842
+ * `data`
3843
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
3844
+ * last one
3845
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
3846
+ * @param {Function} [cb] Callback which is executed when data is written out
3847
+ * @public
3848
+ */
3849
+ send(data, options, cb) {
3850
+ if (this.readyState === WebSocket.CONNECTING) {
3851
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
3852
+ }
3853
+
3854
+ if (typeof options === 'function') {
3855
+ cb = options;
3856
+ options = {};
3857
+ }
3858
+
3859
+ if (typeof data === 'number') data = data.toString();
3860
+
3861
+ if (this.readyState !== WebSocket.OPEN) {
3862
+ sendAfterClose(this, data, cb);
3863
+ return;
3864
+ }
3865
+
3866
+ const opts = {
3867
+ binary: typeof data !== 'string',
3868
+ mask: !this._isServer,
3869
+ compress: true,
3870
+ fin: true,
3871
+ ...options
3872
+ };
3873
+
3874
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
3875
+ opts.compress = false;
3876
+ }
3877
+
3878
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
3879
+ }
3880
+
3881
+ /**
3882
+ * Forcibly close the connection.
3883
+ *
3884
+ * @public
3885
+ */
3886
+ terminate() {
3887
+ if (this.readyState === WebSocket.CLOSED) return;
3888
+ if (this.readyState === WebSocket.CONNECTING) {
3889
+ const msg = 'WebSocket was closed before the connection was established';
3890
+ abortHandshake(this, this._req, msg);
3891
+ return;
3892
+ }
3893
+
3894
+ if (this._socket) {
3895
+ this._readyState = WebSocket.CLOSING;
3896
+ this._socket.destroy();
3897
+ }
3898
+ }
3899
+ }
3900
+
3901
+ /**
3902
+ * @constant {Number} CONNECTING
3903
+ * @memberof WebSocket
3904
+ */
3905
+ Object.defineProperty(WebSocket, 'CONNECTING', {
3906
+ enumerable: true,
3907
+ value: readyStates.indexOf('CONNECTING')
3908
+ });
3909
+
3910
+ /**
3911
+ * @constant {Number} CONNECTING
3912
+ * @memberof WebSocket.prototype
3913
+ */
3914
+ Object.defineProperty(WebSocket.prototype, 'CONNECTING', {
3915
+ enumerable: true,
3916
+ value: readyStates.indexOf('CONNECTING')
3917
+ });
3918
+
3919
+ /**
3920
+ * @constant {Number} OPEN
3921
+ * @memberof WebSocket
3922
+ */
3923
+ Object.defineProperty(WebSocket, 'OPEN', {
3924
+ enumerable: true,
3925
+ value: readyStates.indexOf('OPEN')
3926
+ });
3927
+
3928
+ /**
3929
+ * @constant {Number} OPEN
3930
+ * @memberof WebSocket.prototype
3931
+ */
3932
+ Object.defineProperty(WebSocket.prototype, 'OPEN', {
3933
+ enumerable: true,
3934
+ value: readyStates.indexOf('OPEN')
3935
+ });
3936
+
3937
+ /**
3938
+ * @constant {Number} CLOSING
3939
+ * @memberof WebSocket
3940
+ */
3941
+ Object.defineProperty(WebSocket, 'CLOSING', {
3942
+ enumerable: true,
3943
+ value: readyStates.indexOf('CLOSING')
3944
+ });
3945
+
3946
+ /**
3947
+ * @constant {Number} CLOSING
3948
+ * @memberof WebSocket.prototype
3949
+ */
3950
+ Object.defineProperty(WebSocket.prototype, 'CLOSING', {
3951
+ enumerable: true,
3952
+ value: readyStates.indexOf('CLOSING')
3953
+ });
3954
+
3955
+ /**
3956
+ * @constant {Number} CLOSED
3957
+ * @memberof WebSocket
3958
+ */
3959
+ Object.defineProperty(WebSocket, 'CLOSED', {
3960
+ enumerable: true,
3961
+ value: readyStates.indexOf('CLOSED')
3962
+ });
3963
+
3964
+ /**
3965
+ * @constant {Number} CLOSED
3966
+ * @memberof WebSocket.prototype
3967
+ */
3968
+ Object.defineProperty(WebSocket.prototype, 'CLOSED', {
3969
+ enumerable: true,
3970
+ value: readyStates.indexOf('CLOSED')
3971
+ });
3972
+
3973
+ [
3974
+ 'binaryType',
3975
+ 'bufferedAmount',
3976
+ 'extensions',
3977
+ 'isPaused',
3978
+ 'protocol',
3979
+ 'readyState',
3980
+ 'url'
3981
+ ].forEach((property) => {
3982
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
3983
+ });
3984
+
3985
+ //
3986
+ // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
3987
+ // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
3988
+ //
3989
+ ['open', 'error', 'close', 'message'].forEach((method) => {
3990
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
3991
+ enumerable: true,
3992
+ get() {
3993
+ for (const listener of this.listeners(method)) {
3994
+ if (listener[kForOnEventAttribute]) return listener[kListener];
3995
+ }
3996
+
3997
+ return null;
3998
+ },
3999
+ set(handler) {
4000
+ for (const listener of this.listeners(method)) {
4001
+ if (listener[kForOnEventAttribute]) {
4002
+ this.removeListener(method, listener);
4003
+ break;
4004
+ }
4005
+ }
4006
+
4007
+ if (typeof handler !== 'function') return;
4008
+
4009
+ this.addEventListener(method, handler, {
4010
+ [kForOnEventAttribute]: true
4011
+ });
4012
+ }
4013
+ });
4014
+ });
4015
+
4016
+ WebSocket.prototype.addEventListener = addEventListener;
4017
+ WebSocket.prototype.removeEventListener = removeEventListener;
4018
+
4019
+ module.exports = WebSocket;
4020
+
4021
+ /**
4022
+ * Initialize a WebSocket client.
4023
+ *
4024
+ * @param {WebSocket} websocket The client to initialize
4025
+ * @param {(String|URL)} address The URL to which to connect
4026
+ * @param {Array} protocols The subprotocols
4027
+ * @param {Object} [options] Connection options
4028
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
4029
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
4030
+ * times in the same tick
4031
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
4032
+ * automatically send a pong in response to a ping
4033
+ * @param {Function} [options.finishRequest] A function which can be used to
4034
+ * customize the headers of each http request before it is sent
4035
+ * @param {Boolean} [options.followRedirects=false] Whether or not to follow
4036
+ * redirects
4037
+ * @param {Function} [options.generateMask] The function used to generate the
4038
+ * masking key
4039
+ * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
4040
+ * handshake request
4041
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
4042
+ * size
4043
+ * @param {Number} [options.maxRedirects=10] The maximum number of redirects
4044
+ * allowed
4045
+ * @param {String} [options.origin] Value of the `Origin` or
4046
+ * `Sec-WebSocket-Origin` header
4047
+ * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
4048
+ * permessage-deflate
4049
+ * @param {Number} [options.protocolVersion=13] Value of the
4050
+ * `Sec-WebSocket-Version` header
4051
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
4052
+ * not to skip UTF-8 validation for text and close messages
4053
+ * @private
4054
+ */
4055
+ function initAsClient(websocket, address, protocols, options) {
4056
+ const opts = {
4057
+ allowSynchronousEvents: true,
4058
+ autoPong: true,
4059
+ protocolVersion: protocolVersions[1],
4060
+ maxPayload: 100 * 1024 * 1024,
4061
+ skipUTF8Validation: false,
4062
+ perMessageDeflate: true,
4063
+ followRedirects: false,
4064
+ maxRedirects: 10,
4065
+ ...options,
4066
+ socketPath: undefined,
4067
+ hostname: undefined,
4068
+ protocol: undefined,
4069
+ timeout: undefined,
4070
+ method: 'GET',
4071
+ host: undefined,
4072
+ path: undefined,
4073
+ port: undefined
4074
+ };
4075
+
4076
+ websocket._autoPong = opts.autoPong;
4077
+
4078
+ if (!protocolVersions.includes(opts.protocolVersion)) {
4079
+ throw new RangeError(
4080
+ `Unsupported protocol version: ${opts.protocolVersion} ` +
4081
+ `(supported versions: ${protocolVersions.join(', ')})`
4082
+ );
4083
+ }
4084
+
4085
+ let parsedUrl;
4086
+
4087
+ if (address instanceof URL) {
4088
+ parsedUrl = address;
4089
+ } else {
4090
+ try {
4091
+ parsedUrl = new URL(address);
4092
+ } catch (e) {
4093
+ throw new SyntaxError(`Invalid URL: ${address}`);
4094
+ }
4095
+ }
4096
+
4097
+ if (parsedUrl.protocol === 'http:') {
4098
+ parsedUrl.protocol = 'ws:';
4099
+ } else if (parsedUrl.protocol === 'https:') {
4100
+ parsedUrl.protocol = 'wss:';
4101
+ }
4102
+
4103
+ websocket._url = parsedUrl.href;
4104
+
4105
+ const isSecure = parsedUrl.protocol === 'wss:';
4106
+ const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
4107
+ let invalidUrlMessage;
4108
+
4109
+ if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
4110
+ invalidUrlMessage =
4111
+ 'The URL\'s protocol must be one of "ws:", "wss:", ' +
4112
+ '"http:", "https", or "ws+unix:"';
4113
+ } else if (isIpcUrl && !parsedUrl.pathname) {
4114
+ invalidUrlMessage = "The URL's pathname is empty";
4115
+ } else if (parsedUrl.hash) {
4116
+ invalidUrlMessage = 'The URL contains a fragment identifier';
4117
+ }
4118
+
4119
+ if (invalidUrlMessage) {
4120
+ const err = new SyntaxError(invalidUrlMessage);
4121
+
4122
+ if (websocket._redirects === 0) {
4123
+ throw err;
4124
+ } else {
4125
+ emitErrorAndClose(websocket, err);
4126
+ return;
4127
+ }
4128
+ }
4129
+
4130
+ const defaultPort = isSecure ? 443 : 80;
4131
+ const key = randomBytes(16).toString('base64');
4132
+ const request = isSecure ? https.request : http.request;
4133
+ const protocolSet = new Set();
4134
+ let perMessageDeflate;
4135
+
4136
+ opts.createConnection =
4137
+ opts.createConnection || (isSecure ? tlsConnect : netConnect);
4138
+ opts.defaultPort = opts.defaultPort || defaultPort;
4139
+ opts.port = parsedUrl.port || defaultPort;
4140
+ opts.host = parsedUrl.hostname.startsWith('[')
4141
+ ? parsedUrl.hostname.slice(1, -1)
4142
+ : parsedUrl.hostname;
4143
+ opts.headers = {
4144
+ ...opts.headers,
4145
+ 'Sec-WebSocket-Version': opts.protocolVersion,
4146
+ 'Sec-WebSocket-Key': key,
4147
+ Connection: 'Upgrade',
4148
+ Upgrade: 'websocket'
4149
+ };
4150
+ opts.path = parsedUrl.pathname + parsedUrl.search;
4151
+ opts.timeout = opts.handshakeTimeout;
4152
+
4153
+ if (opts.perMessageDeflate) {
4154
+ perMessageDeflate = new PerMessageDeflate(
4155
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
4156
+ false,
4157
+ opts.maxPayload
4158
+ );
4159
+ opts.headers['Sec-WebSocket-Extensions'] = format({
4160
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
4161
+ });
4162
+ }
4163
+ if (protocols.length) {
4164
+ for (const protocol of protocols) {
4165
+ if (
4166
+ typeof protocol !== 'string' ||
4167
+ !subprotocolRegex.test(protocol) ||
4168
+ protocolSet.has(protocol)
4169
+ ) {
4170
+ throw new SyntaxError(
4171
+ 'An invalid or duplicated subprotocol was specified'
4172
+ );
4173
+ }
4174
+
4175
+ protocolSet.add(protocol);
4176
+ }
4177
+
4178
+ opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
4179
+ }
4180
+ if (opts.origin) {
4181
+ if (opts.protocolVersion < 13) {
4182
+ opts.headers['Sec-WebSocket-Origin'] = opts.origin;
4183
+ } else {
4184
+ opts.headers.Origin = opts.origin;
4185
+ }
4186
+ }
4187
+ if (parsedUrl.username || parsedUrl.password) {
4188
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
4189
+ }
4190
+
4191
+ if (isIpcUrl) {
4192
+ const parts = opts.path.split(':');
4193
+
4194
+ opts.socketPath = parts[0];
4195
+ opts.path = parts[1];
4196
+ }
4197
+
4198
+ let req;
4199
+
4200
+ if (opts.followRedirects) {
4201
+ if (websocket._redirects === 0) {
4202
+ websocket._originalIpc = isIpcUrl;
4203
+ websocket._originalSecure = isSecure;
4204
+ websocket._originalHostOrSocketPath = isIpcUrl
4205
+ ? opts.socketPath
4206
+ : parsedUrl.host;
4207
+
4208
+ const headers = options && options.headers;
4209
+
4210
+ //
4211
+ // Shallow copy the user provided options so that headers can be changed
4212
+ // without mutating the original object.
4213
+ //
4214
+ options = { ...options, headers: {} };
4215
+
4216
+ if (headers) {
4217
+ for (const [key, value] of Object.entries(headers)) {
4218
+ options.headers[key.toLowerCase()] = value;
4219
+ }
4220
+ }
4221
+ } else if (websocket.listenerCount('redirect') === 0) {
4222
+ const isSameHost = isIpcUrl
4223
+ ? websocket._originalIpc
4224
+ ? opts.socketPath === websocket._originalHostOrSocketPath
4225
+ : false
4226
+ : websocket._originalIpc
4227
+ ? false
4228
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
4229
+
4230
+ if (!isSameHost || (websocket._originalSecure && !isSecure)) {
4231
+ //
4232
+ // Match curl 7.77.0 behavior and drop the following headers. These
4233
+ // headers are also dropped when following a redirect to a subdomain.
4234
+ //
4235
+ delete opts.headers.authorization;
4236
+ delete opts.headers.cookie;
4237
+
4238
+ if (!isSameHost) delete opts.headers.host;
4239
+
4240
+ opts.auth = undefined;
4241
+ }
4242
+ }
4243
+
4244
+ //
4245
+ // Match curl 7.77.0 behavior and make the first `Authorization` header win.
4246
+ // If the `Authorization` header is set, then there is nothing to do as it
4247
+ // will take precedence.
4248
+ //
4249
+ if (opts.auth && !options.headers.authorization) {
4250
+ options.headers.authorization =
4251
+ 'Basic ' + Buffer.from(opts.auth).toString('base64');
4252
+ }
4253
+
4254
+ req = websocket._req = request(opts);
4255
+
4256
+ if (websocket._redirects) {
4257
+ //
4258
+ // Unlike what is done for the `'upgrade'` event, no early exit is
4259
+ // triggered here if the user calls `websocket.close()` or
4260
+ // `websocket.terminate()` from a listener of the `'redirect'` event. This
4261
+ // is because the user can also call `request.destroy()` with an error
4262
+ // before calling `websocket.close()` or `websocket.terminate()` and this
4263
+ // would result in an error being emitted on the `request` object with no
4264
+ // `'error'` event listeners attached.
4265
+ //
4266
+ websocket.emit('redirect', websocket.url, req);
4267
+ }
4268
+ } else {
4269
+ req = websocket._req = request(opts);
4270
+ }
4271
+
4272
+ if (opts.timeout) {
4273
+ req.on('timeout', () => {
4274
+ abortHandshake(websocket, req, 'Opening handshake has timed out');
4275
+ });
4276
+ }
4277
+
4278
+ req.on('error', (err) => {
4279
+ if (req === null || req[kAborted]) return;
4280
+
4281
+ req = websocket._req = null;
4282
+ emitErrorAndClose(websocket, err);
4283
+ });
4284
+
4285
+ req.on('response', (res) => {
4286
+ const location = res.headers.location;
4287
+ const statusCode = res.statusCode;
4288
+
4289
+ if (
4290
+ location &&
4291
+ opts.followRedirects &&
4292
+ statusCode >= 300 &&
4293
+ statusCode < 400
4294
+ ) {
4295
+ if (++websocket._redirects > opts.maxRedirects) {
4296
+ abortHandshake(websocket, req, 'Maximum redirects exceeded');
4297
+ return;
4298
+ }
4299
+
4300
+ req.abort();
4301
+
4302
+ let addr;
4303
+
4304
+ try {
4305
+ addr = new URL(location, address);
4306
+ } catch (e) {
4307
+ const err = new SyntaxError(`Invalid URL: ${location}`);
4308
+ emitErrorAndClose(websocket, err);
4309
+ return;
4310
+ }
4311
+
4312
+ initAsClient(websocket, addr, protocols, options);
4313
+ } else if (!websocket.emit('unexpected-response', req, res)) {
4314
+ abortHandshake(
4315
+ websocket,
4316
+ req,
4317
+ `Unexpected server response: ${res.statusCode}`
4318
+ );
4319
+ }
4320
+ });
4321
+
4322
+ req.on('upgrade', (res, socket, head) => {
4323
+ websocket.emit('upgrade', res);
4324
+
4325
+ //
4326
+ // The user may have closed the connection from a listener of the
4327
+ // `'upgrade'` event.
4328
+ //
4329
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
4330
+
4331
+ req = websocket._req = null;
4332
+
4333
+ if (res.headers.upgrade.toLowerCase() !== 'websocket') {
4334
+ abortHandshake(websocket, socket, 'Invalid Upgrade header');
4335
+ return;
4336
+ }
4337
+
4338
+ const digest = createHash('sha1')
4339
+ .update(key + GUID)
4340
+ .digest('base64');
4341
+
4342
+ if (res.headers['sec-websocket-accept'] !== digest) {
4343
+ abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
4344
+ return;
4345
+ }
4346
+
4347
+ const serverProt = res.headers['sec-websocket-protocol'];
4348
+ let protError;
4349
+
4350
+ if (serverProt !== undefined) {
4351
+ if (!protocolSet.size) {
4352
+ protError = 'Server sent a subprotocol but none was requested';
4353
+ } else if (!protocolSet.has(serverProt)) {
4354
+ protError = 'Server sent an invalid subprotocol';
4355
+ }
4356
+ } else if (protocolSet.size) {
4357
+ protError = 'Server sent no subprotocol';
4358
+ }
4359
+
4360
+ if (protError) {
4361
+ abortHandshake(websocket, socket, protError);
4362
+ return;
4363
+ }
4364
+
4365
+ if (serverProt) websocket._protocol = serverProt;
4366
+
4367
+ const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
4368
+
4369
+ if (secWebSocketExtensions !== undefined) {
4370
+ if (!perMessageDeflate) {
4371
+ const message =
4372
+ 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
4373
+ 'was requested';
4374
+ abortHandshake(websocket, socket, message);
4375
+ return;
4376
+ }
4377
+
4378
+ let extensions;
4379
+
4380
+ try {
4381
+ extensions = parse(secWebSocketExtensions);
4382
+ } catch (err) {
4383
+ const message = 'Invalid Sec-WebSocket-Extensions header';
4384
+ abortHandshake(websocket, socket, message);
4385
+ return;
4386
+ }
4387
+
4388
+ const extensionNames = Object.keys(extensions);
4389
+
4390
+ if (
4391
+ extensionNames.length !== 1 ||
4392
+ extensionNames[0] !== PerMessageDeflate.extensionName
4393
+ ) {
4394
+ const message = 'Server indicated an extension that was not requested';
4395
+ abortHandshake(websocket, socket, message);
4396
+ return;
4397
+ }
4398
+
4399
+ try {
4400
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
4401
+ } catch (err) {
4402
+ const message = 'Invalid Sec-WebSocket-Extensions header';
4403
+ abortHandshake(websocket, socket, message);
4404
+ return;
4405
+ }
4406
+
4407
+ websocket._extensions[PerMessageDeflate.extensionName] =
4408
+ perMessageDeflate;
4409
+ }
4410
+
4411
+ websocket.setSocket(socket, head, {
4412
+ allowSynchronousEvents: opts.allowSynchronousEvents,
4413
+ generateMask: opts.generateMask,
4414
+ maxPayload: opts.maxPayload,
4415
+ skipUTF8Validation: opts.skipUTF8Validation
4416
+ });
4417
+ });
4418
+
4419
+ if (opts.finishRequest) {
4420
+ opts.finishRequest(req, websocket);
4421
+ } else {
4422
+ req.end();
4423
+ }
4424
+ }
4425
+
4426
+ /**
4427
+ * Emit the `'error'` and `'close'` events.
4428
+ *
4429
+ * @param {WebSocket} websocket The WebSocket instance
4430
+ * @param {Error} The error to emit
4431
+ * @private
4432
+ */
4433
+ function emitErrorAndClose(websocket, err) {
4434
+ websocket._readyState = WebSocket.CLOSING;
4435
+ websocket.emit('error', err);
4436
+ websocket.emitClose();
4437
+ }
4438
+
4439
+ /**
4440
+ * Create a `net.Socket` and initiate a connection.
4441
+ *
4442
+ * @param {Object} options Connection options
4443
+ * @return {net.Socket} The newly created socket used to start the connection
4444
+ * @private
4445
+ */
4446
+ function netConnect(options) {
4447
+ options.path = options.socketPath;
4448
+ return net.connect(options);
4449
+ }
4450
+
4451
+ /**
4452
+ * Create a `tls.TLSSocket` and initiate a connection.
4453
+ *
4454
+ * @param {Object} options Connection options
4455
+ * @return {tls.TLSSocket} The newly created socket used to start the connection
4456
+ * @private
4457
+ */
4458
+ function tlsConnect(options) {
4459
+ options.path = undefined;
4460
+
4461
+ if (!options.servername && options.servername !== '') {
4462
+ options.servername = net.isIP(options.host) ? '' : options.host;
4463
+ }
4464
+
4465
+ return tls.connect(options);
4466
+ }
4467
+
4468
+ /**
4469
+ * Abort the handshake and emit an error.
4470
+ *
4471
+ * @param {WebSocket} websocket The WebSocket instance
4472
+ * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
4473
+ * abort or the socket to destroy
4474
+ * @param {String} message The error message
4475
+ * @private
4476
+ */
4477
+ function abortHandshake(websocket, stream, message) {
4478
+ websocket._readyState = WebSocket.CLOSING;
4479
+
4480
+ const err = new Error(message);
4481
+ Error.captureStackTrace(err, abortHandshake);
4482
+
4483
+ if (stream.setHeader) {
4484
+ stream[kAborted] = true;
4485
+ stream.abort();
4486
+
4487
+ if (stream.socket && !stream.socket.destroyed) {
4488
+ //
4489
+ // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
4490
+ // called after the request completed. See
4491
+ // https://github.com/websockets/ws/issues/1869.
4492
+ //
4493
+ stream.socket.destroy();
4494
+ }
4495
+
4496
+ process.nextTick(emitErrorAndClose, websocket, err);
4497
+ } else {
4498
+ stream.destroy(err);
4499
+ stream.once('error', websocket.emit.bind(websocket, 'error'));
4500
+ stream.once('close', websocket.emitClose.bind(websocket));
4501
+ }
4502
+ }
4503
+
4504
+ /**
4505
+ * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
4506
+ * when the `readyState` attribute is `CLOSING` or `CLOSED`.
4507
+ *
4508
+ * @param {WebSocket} websocket The WebSocket instance
4509
+ * @param {*} [data] The data to send
4510
+ * @param {Function} [cb] Callback
4511
+ * @private
4512
+ */
4513
+ function sendAfterClose(websocket, data, cb) {
4514
+ if (data) {
4515
+ const length = toBuffer(data).length;
4516
+
4517
+ //
4518
+ // The `_bufferedAmount` property is used only when the peer is a client and
4519
+ // the opening handshake fails. Under these circumstances, in fact, the
4520
+ // `setSocket()` method is not called, so the `_socket` and `_sender`
4521
+ // properties are set to `null`.
4522
+ //
4523
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
4524
+ else websocket._bufferedAmount += length;
4525
+ }
4526
+
4527
+ if (cb) {
4528
+ const err = new Error(
4529
+ `WebSocket is not open: readyState ${websocket.readyState} ` +
4530
+ `(${readyStates[websocket.readyState]})`
4531
+ );
4532
+ process.nextTick(cb, err);
4533
+ }
4534
+ }
4535
+
4536
+ /**
4537
+ * The listener of the `Receiver` `'conclude'` event.
4538
+ *
4539
+ * @param {Number} code The status code
4540
+ * @param {Buffer} reason The reason for closing
4541
+ * @private
4542
+ */
4543
+ function receiverOnConclude(code, reason) {
4544
+ const websocket = this[kWebSocket];
4545
+
4546
+ websocket._closeFrameReceived = true;
4547
+ websocket._closeMessage = reason;
4548
+ websocket._closeCode = code;
4549
+
4550
+ if (websocket._socket[kWebSocket] === undefined) return;
4551
+
4552
+ websocket._socket.removeListener('data', socketOnData);
4553
+ process.nextTick(resume, websocket._socket);
4554
+
4555
+ if (code === 1005) websocket.close();
4556
+ else websocket.close(code, reason);
4557
+ }
4558
+
4559
+ /**
4560
+ * The listener of the `Receiver` `'drain'` event.
4561
+ *
4562
+ * @private
4563
+ */
4564
+ function receiverOnDrain() {
4565
+ const websocket = this[kWebSocket];
4566
+
4567
+ if (!websocket.isPaused) websocket._socket.resume();
4568
+ }
4569
+
4570
+ /**
4571
+ * The listener of the `Receiver` `'error'` event.
4572
+ *
4573
+ * @param {(RangeError|Error)} err The emitted error
4574
+ * @private
4575
+ */
4576
+ function receiverOnError(err) {
4577
+ const websocket = this[kWebSocket];
4578
+
4579
+ if (websocket._socket[kWebSocket] !== undefined) {
4580
+ websocket._socket.removeListener('data', socketOnData);
4581
+
4582
+ //
4583
+ // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
4584
+ // https://github.com/websockets/ws/issues/1940.
4585
+ //
4586
+ process.nextTick(resume, websocket._socket);
4587
+
4588
+ websocket.close(err[kStatusCode]);
4589
+ }
4590
+
4591
+ websocket.emit('error', err);
4592
+ }
4593
+
4594
+ /**
4595
+ * The listener of the `Receiver` `'finish'` event.
4596
+ *
4597
+ * @private
4598
+ */
4599
+ function receiverOnFinish() {
4600
+ this[kWebSocket].emitClose();
4601
+ }
4602
+
4603
+ /**
4604
+ * The listener of the `Receiver` `'message'` event.
4605
+ *
4606
+ * @param {Buffer|ArrayBuffer|Buffer[])} data The message
4607
+ * @param {Boolean} isBinary Specifies whether the message is binary or not
4608
+ * @private
4609
+ */
4610
+ function receiverOnMessage(data, isBinary) {
4611
+ this[kWebSocket].emit('message', data, isBinary);
4612
+ }
4613
+
4614
+ /**
4615
+ * The listener of the `Receiver` `'ping'` event.
4616
+ *
4617
+ * @param {Buffer} data The data included in the ping frame
4618
+ * @private
4619
+ */
4620
+ function receiverOnPing(data) {
4621
+ const websocket = this[kWebSocket];
4622
+
4623
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
4624
+ websocket.emit('ping', data);
4625
+ }
4626
+
4627
+ /**
4628
+ * The listener of the `Receiver` `'pong'` event.
4629
+ *
4630
+ * @param {Buffer} data The data included in the pong frame
4631
+ * @private
4632
+ */
4633
+ function receiverOnPong(data) {
4634
+ this[kWebSocket].emit('pong', data);
4635
+ }
4636
+
4637
+ /**
4638
+ * Resume a readable stream
4639
+ *
4640
+ * @param {Readable} stream The readable stream
4641
+ * @private
4642
+ */
4643
+ function resume(stream) {
4644
+ stream.resume();
4645
+ }
4646
+
4647
+ /**
4648
+ * The listener of the socket `'close'` event.
4649
+ *
4650
+ * @private
4651
+ */
4652
+ function socketOnClose() {
4653
+ const websocket = this[kWebSocket];
4654
+
4655
+ this.removeListener('close', socketOnClose);
4656
+ this.removeListener('data', socketOnData);
4657
+ this.removeListener('end', socketOnEnd);
4658
+
4659
+ websocket._readyState = WebSocket.CLOSING;
4660
+
4661
+ let chunk;
4662
+
4663
+ //
4664
+ // The close frame might not have been received or the `'end'` event emitted,
4665
+ // for example, if the socket was destroyed due to an error. Ensure that the
4666
+ // `receiver` stream is closed after writing any remaining buffered data to
4667
+ // it. If the readable side of the socket is in flowing mode then there is no
4668
+ // buffered data as everything has been already written and `readable.read()`
4669
+ // will return `null`. If instead, the socket is paused, any possible buffered
4670
+ // data will be read as a single chunk.
4671
+ //
4672
+ if (
4673
+ !this._readableState.endEmitted &&
4674
+ !websocket._closeFrameReceived &&
4675
+ !websocket._receiver._writableState.errorEmitted &&
4676
+ (chunk = websocket._socket.read()) !== null
4677
+ ) {
4678
+ websocket._receiver.write(chunk);
4679
+ }
4680
+
4681
+ websocket._receiver.end();
4682
+
4683
+ this[kWebSocket] = undefined;
4684
+
4685
+ clearTimeout(websocket._closeTimer);
4686
+
4687
+ if (
4688
+ websocket._receiver._writableState.finished ||
4689
+ websocket._receiver._writableState.errorEmitted
4690
+ ) {
4691
+ websocket.emitClose();
4692
+ } else {
4693
+ websocket._receiver.on('error', receiverOnFinish);
4694
+ websocket._receiver.on('finish', receiverOnFinish);
4695
+ }
4696
+ }
4697
+
4698
+ /**
4699
+ * The listener of the socket `'data'` event.
4700
+ *
4701
+ * @param {Buffer} chunk A chunk of data
4702
+ * @private
4703
+ */
4704
+ function socketOnData(chunk) {
4705
+ if (!this[kWebSocket]._receiver.write(chunk)) {
4706
+ this.pause();
4707
+ }
4708
+ }
4709
+
4710
+ /**
4711
+ * The listener of the socket `'end'` event.
4712
+ *
4713
+ * @private
4714
+ */
4715
+ function socketOnEnd() {
4716
+ const websocket = this[kWebSocket];
4717
+
4718
+ websocket._readyState = WebSocket.CLOSING;
4719
+ websocket._receiver.end();
4720
+ this.end();
4721
+ }
4722
+
4723
+ /**
4724
+ * The listener of the socket `'error'` event.
4725
+ *
4726
+ * @private
4727
+ */
4728
+ function socketOnError() {
4729
+ const websocket = this[kWebSocket];
4730
+
4731
+ this.removeListener('error', socketOnError);
4732
+ this.on('error', NOOP);
4733
+
4734
+ if (websocket) {
4735
+ websocket._readyState = WebSocket.CLOSING;
4736
+ this.destroy();
4737
+ }
4738
+ }
4739
+
4740
+
4741
+ /***/ }),
4742
+
4743
+ /***/ 471:
4744
+ /***/ ((module) => {
4745
+
4746
+ module.exports = eval("require")("bufferutil");
4747
+
4748
+
4749
+ /***/ }),
4750
+
4751
+ /***/ 177:
4752
+ /***/ ((module) => {
4753
+
4754
+ module.exports = eval("require")("utf-8-validate");
4755
+
4756
+
4757
+ /***/ }),
4758
+
4759
+ /***/ 300:
4760
+ /***/ ((module) => {
4761
+
4762
+ "use strict";
4763
+ module.exports = require("buffer");
4764
+
4765
+ /***/ }),
4766
+
4767
+ /***/ 113:
4768
+ /***/ ((module) => {
4769
+
4770
+ "use strict";
4771
+ module.exports = require("crypto");
4772
+
4773
+ /***/ }),
4774
+
4775
+ /***/ 361:
4776
+ /***/ ((module) => {
4777
+
4778
+ "use strict";
4779
+ module.exports = require("events");
4780
+
4781
+ /***/ }),
4782
+
4783
+ /***/ 685:
4784
+ /***/ ((module) => {
4785
+
4786
+ "use strict";
4787
+ module.exports = require("http");
4788
+
4789
+ /***/ }),
4790
+
4791
+ /***/ 687:
4792
+ /***/ ((module) => {
4793
+
4794
+ "use strict";
4795
+ module.exports = require("https");
4796
+
4797
+ /***/ }),
4798
+
4799
+ /***/ 808:
4800
+ /***/ ((module) => {
4801
+
4802
+ "use strict";
4803
+ module.exports = require("net");
4804
+
4805
+ /***/ }),
4806
+
4807
+ /***/ 781:
4808
+ /***/ ((module) => {
4809
+
4810
+ "use strict";
4811
+ module.exports = require("stream");
4812
+
4813
+ /***/ }),
4814
+
4815
+ /***/ 404:
4816
+ /***/ ((module) => {
4817
+
4818
+ "use strict";
4819
+ module.exports = require("tls");
4820
+
4821
+ /***/ }),
4822
+
4823
+ /***/ 310:
4824
+ /***/ ((module) => {
4825
+
4826
+ "use strict";
4827
+ module.exports = require("url");
4828
+
4829
+ /***/ }),
4830
+
4831
+ /***/ 796:
4832
+ /***/ ((module) => {
4833
+
4834
+ "use strict";
4835
+ module.exports = require("zlib");
4836
+
4837
+ /***/ })
4838
+
4839
+ /******/ });
4840
+ /************************************************************************/
4841
+ /******/ // The module cache
4842
+ /******/ var __webpack_module_cache__ = {};
4843
+ /******/
4844
+ /******/ // The require function
4845
+ /******/ function __nccwpck_require__(moduleId) {
4846
+ /******/ // Check if module is in cache
4847
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
4848
+ /******/ if (cachedModule !== undefined) {
4849
+ /******/ return cachedModule.exports;
4850
+ /******/ }
4851
+ /******/ // Create a new module (and put it into the cache)
4852
+ /******/ var module = __webpack_module_cache__[moduleId] = {
4853
+ /******/ // no module.id needed
4854
+ /******/ // no module.loaded needed
4855
+ /******/ exports: {}
4856
+ /******/ };
4857
+ /******/
4858
+ /******/ // Execute the module function
4859
+ /******/ var threw = true;
4860
+ /******/ try {
4861
+ /******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
4862
+ /******/ threw = false;
4863
+ /******/ } finally {
4864
+ /******/ if(threw) delete __webpack_module_cache__[moduleId];
4865
+ /******/ }
4866
+ /******/
4867
+ /******/ // Return the exports of the module
4868
+ /******/ return module.exports;
4869
+ /******/ }
4870
+ /******/
4871
+ /************************************************************************/
4872
+ /******/ /* webpack/runtime/compat */
4873
+ /******/
4874
+ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
4875
+ /******/
4876
+ /************************************************************************/
4877
+ /******/
4878
+ /******/ // startup
4879
+ /******/ // Load entry module and return exports
4880
+ /******/ // This entry module is referenced by other modules so it can't be inlined
4881
+ /******/ var __webpack_exports__ = __nccwpck_require__(514);
4882
+ /******/ module.exports = __webpack_exports__;
4883
+ /******/
4884
+ /******/ })()
4885
+ ;