1import { r as require$$5 } from './__vite-browser-external-cb19bde2.js'; 2 3function getDefaultExportFromCjs(x) { 4 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; 5} 6function getAugmentedNamespace(n) { 7 if (n.__esModule) 8 return n; 9 var f = n.default; 10 if (typeof f == "function") { 11 var a = function a2() { 12 if (this instanceof a2) { 13 var args = [null]; 14 args.push.apply(args, arguments); 15 var Ctor = Function.bind.apply(f, args); 16 return new Ctor(); 17 } 18 return f.apply(this, arguments); 19 }; 20 a.prototype = f.prototype; 21 } else 22 a = {}; 23 Object.defineProperty(a, "__esModule", { value: true }); 24 Object.keys(n).forEach(function(k) { 25 var d = Object.getOwnPropertyDescriptor(n, k); 26 Object.defineProperty(a, k, d.get ? d : { 27 enumerable: true, 28 get: function() { 29 return n[k]; 30 } 31 }); 32 }); 33 return a; 34} 35const { Duplex } = require$$5; 36function emitClose$1(stream2) { 37 stream2.emit("close"); 38} 39function duplexOnEnd() { 40 if (!this.destroyed && this._writableState.finished) { 41 this.destroy(); 42 } 43} 44function duplexOnError(err) { 45 this.removeListener("error", duplexOnError); 46 this.destroy(); 47 if (this.listenerCount("error") === 0) { 48 this.emit("error", err); 49 } 50} 51function createWebSocketStream(ws, options) { 52 let terminateOnDestroy = true; 53 const duplex = new Duplex({ 54 ...options, 55 autoDestroy: false, 56 emitClose: false, 57 objectMode: false, 58 writableObjectMode: false 59 }); 60 ws.on("message", function message(msg, isBinary) { 61 const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; 62 if (!duplex.push(data)) 63 ws.pause(); 64 }); 65 ws.once("error", function error2(err) { 66 if (duplex.destroyed) 67 return; 68 terminateOnDestroy = false; 69 duplex.destroy(err); 70 }); 71 ws.once("close", function close() { 72 if (duplex.destroyed) 73 return; 74 duplex.push(null); 75 }); 76 duplex._destroy = function(err, callback) { 77 if (ws.readyState === ws.CLOSED) { 78 callback(err); 79 process.nextTick(emitClose$1, duplex); 80 return; 81 } 82 let called = false; 83 ws.once("error", function error2(err2) { 84 called = true; 85 callback(err2); 86 }); 87 ws.once("close", function close() { 88 if (!called) 89 callback(err); 90 process.nextTick(emitClose$1, duplex); 91 }); 92 if (terminateOnDestroy) 93 ws.terminate(); 94 }; 95 duplex._final = function(callback) { 96 if (ws.readyState === ws.CONNECTING) { 97 ws.once("open", function open() { 98 duplex._final(callback); 99 }); 100 return; 101 } 102 if (ws._socket === null) 103 return; 104 if (ws._socket._writableState.finished) { 105 callback(); 106 if (duplex._readableState.endEmitted) 107 duplex.destroy(); 108 } else { 109 ws._socket.once("finish", function finish() { 110 callback(); 111 }); 112 ws.close(); 113 } 114 }; 115 duplex._read = function() { 116 if (ws.isPaused) 117 ws.resume(); 118 }; 119 duplex._write = function(chunk, encoding, callback) { 120 if (ws.readyState === ws.CONNECTING) { 121 ws.once("open", function open() { 122 duplex._write(chunk, encoding, callback); 123 }); 124 return; 125 } 126 ws.send(chunk, callback); 127 }; 128 duplex.on("end", duplexOnEnd); 129 duplex.on("error", duplexOnError); 130 return duplex; 131} 132var stream = createWebSocketStream; 133const stream$1 = /* @__PURE__ */ getDefaultExportFromCjs(stream); 134var bufferUtil$1 = { exports: {} }; 135var constants = {
136 BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"], 137 EMPTY_BUFFER: Buffer.alloc(0), 138 GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", 139 kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), 140 kListener: Symbol("kListener"), 141 kStatusCode: Symbol("status-code"), 142 kWebSocket: Symbol("websocket"), 143 NOOP: () => { 144 } 145}; 146var unmask$1; 147var mask; 148const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants; 149const FastBuffer$2 = Buffer[Symbol.species]; 150function concat$1(list, totalLength) { 151 if (list.length === 0) 152 return EMPTY_BUFFER$3; 153 if (list.length === 1) 154 return list[0]; 155 const target = Buffer.allocUnsafe(totalLength); 156 let offset = 0; 157 for (let i = 0; i < list.length; i++) { 158 const buf = list[i]; 159 target.set(buf, offset); 160 offset += buf.length; 161 } 162 if (offset < totalLength) { 163 return new FastBuffer$2(target.buffer, target.byteOffset, offset); 164 } 165 return target; 166} 167function _mask(source, mask2, output, offset, length) { 168 for (let i = 0; i < length; i++) { 169 output[offset + i] = source[i] ^ mask2[i & 3]; 170 } 171} 172function _unmask(buffer, mask2) { 173 for (let i = 0; i < buffer.length; i++) { 174 buffer[i] ^= mask2[i & 3]; 175 } 176} 177function toArrayBuffer$1(buf) { 178 if (buf.length === buf.buffer.byteLength) { 179 return buf.buffer; 180 } 181 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); 182} 183function toBuffer$2(data) { 184 toBuffer$2.readOnly = true; 185 if (Buffer.isBuffer(data)) 186 return data; 187 let buf; 188 if (data instanceof ArrayBuffer) { 189 buf = new FastBuffer$2(data); 190 } else if (ArrayBuffer.isView(data)) { 191 buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength); 192 } else { 193 buf = Buffer.from(data); 194 toBuffer$2.readOnly = false; 195 } 196 return buf; 197} 198bufferUtil$1.exports = { 199 concat: concat$1, 200 mask: _mask, 201 toArrayBuffer: toArrayBuffer$1, 202 toBuffer: toBuffer$2, 203 unmask: _unmask 204}; 205if (!({}).WS_NO_BUFFER_UTIL) { 206 try { 207 const bufferUtil2 = require("bufferutil"); 208 mask = bufferUtil$1.exports.mask = function(source, mask2, output, offset, length) { 209 if (length < 48) 210 _mask(source, mask2, output, offset, length); 211 else 212 bufferUtil2.mask(source, mask2, output, offset, length); 213 }; 214 unmask$1 = bufferUtil$1.exports.unmask = function(buffer, mask2) { 215 if (buffer.length < 32) 216 _unmask(buffer, mask2); 217 else 218 bufferUtil2.unmask(buffer, mask2); 219 }; 220 } catch (e) { 221 } 222} 223var bufferUtilExports = bufferUtil$1.exports; 224const kDone = Symbol("kDone"); 225const kRun = Symbol("kRun"); 226let Limiter$1 = class Limiter { 227 /** 228 * Creates a new `Limiter`. 229 * 230 * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed 231 * to run concurrently 232 */ 233 constructor(concurrency) { 234 this[kDone] = () => { 235 this.pending--; 236 this[kRun](); 237 }; 238 this.concurrency = concurrency || Infinity; 239 this.jobs = []; 240 this.pending = 0; 241 } 242 /** 243 * Adds a job to the queue. 244 * 245 * @param {Function} job The job to run 246 * @public 247 */ 248 add(job) { 249 this.jobs.push(job);
250 this[kRun](); 251 } 252 /** 253 * Removes a job from the queue and runs it if possible. 254 * 255 * @private 256 */ 257 [kRun]() { 258 if (this.pending === this.concurrency) 259 return; 260 if (this.jobs.length) { 261 const job = this.jobs.shift(); 262 this.pending++; 263 job(this[kDone]); 264 } 265 } 266}; 267var limiter = Limiter$1; 268const zlib = require$$5; 269const bufferUtil = bufferUtilExports; 270const Limiter2 = limiter; 271const { kStatusCode: kStatusCode$2 } = constants; 272const FastBuffer$1 = Buffer[Symbol.species]; 273const TRAILER = Buffer.from([0, 0, 255, 255]); 274const kPerMessageDeflate = Symbol("permessage-deflate"); 275const kTotalLength = Symbol("total-length"); 276const kCallback = Symbol("callback"); 277const kBuffers = Symbol("buffers"); 278const kError$1 = Symbol("error"); 279let zlibLimiter; 280let PerMessageDeflate$4 = class PerMessageDeflate { 281 /** 282 * Creates a PerMessageDeflate instance. 283 * 284 * @param {Object} [options] Configuration options 285 * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support 286 * for, or request, a custom client window size 287 * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ 288 * acknowledge disabling of client context takeover 289 * @param {Number} [options.concurrencyLimit=10] The number of concurrent 290 * calls to zlib 291 * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the 292 * use of a custom server window size 293 * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept 294 * disabling of server context takeover 295 * @param {Number} [options.threshold=1024] Size (in bytes) below which 296 * messages should not be compressed if context takeover is disabled 297 * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on 298 * deflate 299 * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on 300 * inflate 301 * @param {Boolean} [isServer=false] Create the instance in either server or 302 * client mode 303 * @param {Number} [maxPayload=0] The maximum allowed message length 304 */ 305 constructor(options, isServer, maxPayload) { 306 this._maxPayload = maxPayload | 0; 307 this._options = options || {}; 308 this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024; 309 this._isServer = !!isServer; 310 this._deflate = null; 311 this._inflate = null; 312 this.params = null; 313 if (!zlibLimiter) { 314 const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10; 315 zlibLimiter = new Limiter2(concurrency); 316 } 317 } 318 /** 319 * @type {String} 320 */ 321 static get extensionName() { 322 return "permessage-deflate"; 323 } 324 /** 325 * Create an extension negotiation offer. 326 * 327 * @return {Object} Extension parameters 328 * @public 329 */ 330 offer() { 331 const params = {}; 332 if (this._options.serverNoContextTakeover) { 333 params.server_no_context_takeover = true; 334 } 335 if (this._options.clientNoContextTakeover) { 336 params.client_no_context_takeover = true; 337 } 338 if (this._options.serverMaxWindowBits) { 339 params.server_max_window_bits = this._options.serverMaxWindowBits; 340 } 341 if (this._options.clientMaxWindowBits) { 342 params.client_max_window_bits = this._options.clientMaxWindowBits; 343 } else if (this._options.clientMaxWindowBits == null) { 344 params.client_max_window_bits = true; 345 } 346 return params; 347 } 348 /** 349 * Accept an extension negotiation offer/response. 350 * 351 * @param {Array} configurations The extension negotiation offers/reponse 352 * @return {Object} Accepted configuration 353 * @public 354 */ 355 accept(configurations) { 356 configurations = this.normalizeParams(configurations); 357 this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); 358 return this.params; 359 } 360 /** 361 * Releases all resources used by the extension. 362 * 363 * @public 364 */ 365 cleanup() { 366 if (this._inflate) { 367 this._inflate.close(); 368 this._inflate = null; 369 } 370 if (this._deflate) { 371 const callback = this._deflate[kCallback]; 372 this._deflate.close(); 373 this._deflate = null; 374 if (callback) { 375 callback( 376 new Error( 377 "The deflate stream was closed while data was being processed" 378 ) 379 ); 380 } 381 } 382 } 383 /** 384 * Accept an extension negotiation offer. 385 * 386 * @param {Array} offers The extension negotiation offers 387 * @return {Object} Accepted configuration 388 * @private 389 */ 390 acceptAsServer(offers) { 391 const opts = this._options; 392 const accepted = offers.find((params) => { 393 if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "
393number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { 394 return false; 395 } 396 return true; 397 }); 398 if (!accepted) { 399 throw new Error("None of the extension offers can be accepted"); 400 } 401 if (opts.serverNoContextTakeover) { 402 accepted.server_no_context_takeover = true; 403 } 404 if (opts.clientNoContextTakeover) { 405 accepted.client_no_context_takeover = true; 406 } 407 if (typeof opts.serverMaxWindowBits === "number") { 408 accepted.server_max_window_bits = opts.serverMaxWindowBits; 409 } 410 if (typeof opts.clientMaxWindowBits === "number") { 411 accepted.client_max_window_bits = opts.clientMaxWindowBits; 412 } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { 413 delete accepted.client_max_window_bits; 414 } 415 return accepted; 416 } 417 /** 418 * Accept the extension negotiation response. 419 * 420 * @param {Array} response The extension negotiation response 421 * @return {Object} Accepted configuration 422 * @private 423 */ 424 acceptAsClient(response) { 425 const params = response[0]; 426 if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { 427 throw new Error('Unexpected parameter "client_no_context_takeover"'); 428 } 429 if (!params.client_max_window_bits) {
vendor: 4,703 bytes, lines 430-577
430 if (typeof this._options.clientMaxWindowBits === "number") { 431 params.client_max_window_bits = this._options.clientMaxWindowBits; 432 } 433 } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { 434 throw new Error( 435 'Unexpected or invalid parameter "client_max_window_bits"' 436 ); 437 } 438 return params; 439 } 440 /** 441 * Normalize parameters. 442 * 443 * @param {Array} configurations The extension negotiation offers/reponse 444 * @return {Array} The offers/response with normalized parameters 445 * @private 446 */ 447 normalizeParams(configurations) { 448 configurations.forEach((params) => { 449 Object.keys(params).forEach((key) => { 450 let value = params[key]; 451 if (value.length > 1) { 452 throw new Error(`Parameter "${key}" must have only a single value`); 453 } 454 value = value[0]; 455 if (key === "client_max_window_bits") { 456 if (value !== true) { 457 const num = +value; 458 if (!Number.isInteger(num) || num < 8 || num > 15) { 459 throw new TypeError( 460 `Invalid value for parameter "${key}": ${value}` 461 ); 462 } 463 value = num; 464 } else if (!this._isServer) { 465 throw new TypeError( 466 `Invalid value for parameter "${key}": ${value}` 467 ); 468 } 469 } else if (key === "server_max_window_bits") { 470 const num = +value; 471 if (!Number.isInteger(num) || num < 8 || num > 15) { 472 throw new TypeError( 473 `Invalid value for parameter "${key}": ${value}` 474 ); 475 } 476 value = num; 477 } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { 478 if (value !== true) { 479 throw new TypeError( 480 `Invalid value for parameter "${key}": ${value}` 481 ); 482 } 483 } else { 484 throw new Error(`Unknown parameter "${key}"`); 485 } 486 params[key] = value; 487 }); 488 }); 489 return configurations; 490 } 491 /** 492 * Decompress data. Concurrency limited. 493 * 494 * @param {Buffer} data Compressed data 495 * @param {Boolean} fin Specifies whether or not this is the last fragment 496 * @param {Function} callback Callback 497 * @public 498 */ 499 decompress(data, fin, callback) { 500 zlibLimiter.add((done) => { 501 this._decompress(data, fin, (err, result) => { 502 done(); 503 callback(err, result); 504 }); 505 }); 506 } 507 /** 508 * Compress data. Concurrency limited. 509 * 510 * @param {(Buffer|String)} data Data to compress 511 * @param {Boolean} fin Specifies whether or not this is the last fragment 512 * @param {Function} callback Callback 513 * @public 514 */ 515 compress(data, fin, callback) { 516 zlibLimiter.add((done) => { 517 this._compress(data, fin, (err, result) => { 518 done(); 519 callback(err, result); 520 }); 521 }); 522 } 523 /** 524 * Decompress data. 525 * 526 * @param {Buffer} data Compressed data 527 * @param {Boolean} fin Specifies whether or not this is the last fragment 528 * @param {Function} callback Callback 529 * @private 530 */ 531 _decompress(data, fin, callback) { 532 const endpoint = this._isServer ? "client" : "server"; 533 if (!this._inflate) { 534 const key = `${endpoint}_max_window_bits`; 535 const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; 536 this._inflate = zlib.createInflateRaw({ 537 ...this._options.zlibInflateOptions, 538 windowBits 539 }); 540 this._inflate[kPerMessageDeflate] = this; 541 this._inflate[kTotalLength] = 0; 542 this._inflate[kBuffers] = []; 543 this._inflate.on("error", inflateOnError); 544 this._inflate.on("data", inflateOnData); 545 } 546 this._inflate[kCallback] = callback; 547 this._inflate.write(data); 548 if (fin) 549 this._inflate.write(TRAILER); 550 this._inflate.flush(() => { 551 const err = this._inflate[kError$1]; 552 if (err) { 553 this._inflate.close(); 554 this._inflate = null; 555 callback(err); 556 return; 557 } 558 const data2 = bufferUtil.concat( 559 this._inflate[kBuffers], 560 this._inflate[kTotalLength] 561 ); 562 if (this._inflate._readableState.endEmitted) { 563 this._inflate.close(); 564 this._inflate = null; 565 } else { 566 this._inflate[kTotalLength] = 0; 567 this._inflate[kBuffers] = []; 568 if (fin && this.params[`${endpoint}_no_context_takeover`]) { 569 this._inflate.reset(); 570 } 571 } 572 callback(null, data2); 573 }); 574 } 575 /** 576 * Compress data. 577 *
578 * @param {(Buffer|String)} data Data to compress 579 * @param {Boolean} fin Specifies whether or not this is the last fragment 580 * @param {Function} callback Callback 581 * @private 582 */ 583 _compress(data, fin, callback) { 584 const endpoint = this._isServer ? "server" : "client"; 585 if (!this._deflate) { 586 const key = `${endpoint}_max_window_bits`; 587 const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; 588 this._deflate = zlib.createDeflateRaw({ 589 ...this._options.zlibDeflateOptions, 590 windowBits 591 }); 592 this._deflate[kTotalLength] = 0; 593 this._deflate[kBuffers] = []; 594 this._deflate.on("data", deflateOnData); 595 } 596 this._deflate[kCallback] = callback; 597 this._deflate.write(data); 598 this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { 599 if (!this._deflate) { 600 return; 601 } 602 let data2 = bufferUtil.concat( 603 this._deflate[kBuffers], 604 this._deflate[kTotalLength] 605 ); 606 if (fin) { 607 data2 = new FastBuffer$1(data2.buffer, data2.byteOffset, data2.length - 4); 608 } 609 this._deflate[kCallback] = null; 610 this._deflate[kTotalLength] = 0; 611 this._deflate[kBuffers] = []; 612 if (fin && this.params[`${endpoint}_no_context_takeover`]) { 613 this._deflate.reset(); 614 } 615 callback(null, data2); 616 }); 617 } 618}; 619var permessageDeflate = PerMessageDeflate$4; 620function deflateOnData(chunk) { 621 this[kBuffers].push(chunk); 622 this[kTotalLength] += chunk.length; 623} 624function inflateOnData(chunk) { 625 this[kTotalLength] += chunk.length; 626 if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { 627 this[kBuffers].push(chunk); 628 return; 629 } 630 this[kError$1] = new RangeError("Max payload size exceeded"); 631 this[kError$1].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; 632 this[kError$1][kStatusCode$2] = 1009; 633 this.removeListener("data", inflateOnData); 634 this.reset(); 635} 636function inflateOnError(err) { 637 this[kPerMessageDeflate]._inflate = null; 638 err[kStatusCode$2] = 1007; 639 this[kCallback](err); 640} 641var validation = { exports: {} }; 642const __viteOptionalPeerDep_utf8Validate_ws = {}; 643const __viteOptionalPeerDep_utf8Validate_ws$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ 644 __proto__: null, 645 default: __viteOptionalPeerDep_utf8Validate_ws 646}, Symbol.toStringTag, { value: "Module" })); 647const require$$1 = /* @__PURE__ */ getAugmentedNamespace(__viteOptionalPeerDep_utf8Validate_ws$1); 648var isValidUTF8_1; 649const { isUtf8 } = require$$5; 650const tokenChars$2 = [ 651 0, 652 0, 653 0, 654 0, 655 0, 656 0, 657 0, 658 0, 659 0, 660 0, 661 0, 662 0, 663 0, 664 0, 665 0, 666 0, 667 // 0 - 15 668 0, 669 0, 670 0, 671 0, 672 0, 673 0, 674 0, 675 0, 676 0, 677 0, 678 0, 679 0, 680 0, 681 0, 682 0, 683 0, 684 // 16 - 31 685 0, 686 1, 687 0, 688 1, 689 1, 690 1, 691 1, 692 1, 693 0, 694 0, 695 1, 696 1, 697 0, 698 1, 699 1, 700 0, 701 // 32 - 47 702 1, 703 1, 704 1, 705 1, 706 1, 707 1, 708 1, 709 1, 710 1, 711 1, 712 0, 713 0, 714 0, 715 0, 716 0, 717 0, 718 // 48 - 63 719 0, 720 1, 721 1, 722 1, 723 1, 724 1, 725 1, 726 1, 727 1, 728 1, 729 1, 730 1, 731 1, 732 1, 733 1, 734 1, 735 // 64 - 79 736 1, 737 1, 738 1, 739 1, 740 1, 741 1, 742 1, 743 1, 744 1, 745 1, 746 1, 747 0, 748 0, 749 0, 750 1, 751 1, 752 // 80 - 95 753 1, 754 1, 755 1, 756 1, 757 1, 758 1, 759 1, 760 1, 761 1, 762 1, 763 1, 764 1, 765 1, 766 1, 767 1, 768 1, 769 // 96 - 111 770 1, 771 1, 772 1, 773 1, 774 1, 775 1, 776 1, 777 1, 778 1, 779 1, 780 1, 781 0, 782 1, 783 0, 784 1, 785 0 786 // 112 - 127 787]; 788function isValidStatusCode$2(code) { 789 return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999; 790} 791function _isValidUTF8(buf) { 792 const len = buf.length; 793 let i = 0; 794 while (i < len) { 795 if ((buf[i] & 128) === 0) { 796 i++; 797 } else if ((buf[i] & 224) === 192) { 798 if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { 799 return false; 800 } 801 i += 2; 802 } else if ((buf[i] & 240) === 224) { 803 if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong 804 buf[i] === 237 && (buf[i + 1] & 224) === 160) { 805 return false; 806 } 807 i += 3; 808 } else if ((buf[i] & 248) === 240) { 809 if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong 810 buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { 811 return false;
812 } 813 i += 4; 814 } else { 815 return false; 816 } 817 } 818 return true; 819} 820validation.exports = { 821 isValidStatusCode: isValidStatusCode$2, 822 isValidUTF8: _isValidUTF8, 823 tokenChars: tokenChars$2 824}; 825if (isUtf8) { 826 isValidUTF8_1 = validation.exports.isValidUTF8 = function(buf) { 827 return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); 828 }; 829} else if (!({}).WS_NO_UTF_8_VALIDATE) { 830 try { 831 const isValidUTF82 = require$$1; 832 isValidUTF8_1 = validation.exports.isValidUTF8 = function(buf) { 833 return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF82(buf); 834 }; 835 } catch (e) { 836 } 837} 838var validationExports = validation.exports; 839const { Writable } = require$$5; 840const PerMessageDeflate$3 = permessageDeflate; 841const { 842 BINARY_TYPES: BINARY_TYPES$1, 843 EMPTY_BUFFER: EMPTY_BUFFER$2, 844 kStatusCode: kStatusCode$1, 845 kWebSocket: kWebSocket$2 846} = constants; 847const { concat, toArrayBuffer, unmask } = bufferUtilExports; 848const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports; 849const FastBuffer = Buffer[Symbol.species]; 850const GET_INFO = 0; 851const GET_PAYLOAD_LENGTH_16 = 1; 852const GET_PAYLOAD_LENGTH_64 = 2; 853const GET_MASK = 3; 854const GET_DATA = 4; 855const INFLATING = 5; 856let Receiver$1 = class Receiver extends Writable { 857 /** 858 * Creates a Receiver instance. 859 * 860 * @param {Object} [options] Options object 861 * @param {String} [options.binaryType=nodebuffer] The type for binary data 862 * @param {Object} [options.extensions] An object containing the negotiated 863 * extensions 864 * @param {Boolean} [options.isServer=false] Specifies whether to operate in 865 * client or server mode 866 * @param {Number} [options.maxPayload=0] The maximum allowed message length 867 * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or 868 * not to skip UTF-8 validation for text and close messages 869 */ 870 constructor(options = {}) { 871 super(); 872 this._binaryType = options.binaryType || BINARY_TYPES$1[0]; 873 this._extensions = options.extensions || {}; 874 this._isServer = !!options.isServer; 875 this._maxPayload = options.maxPayload | 0; 876 this._skipUTF8Validation = !!options.skipUTF8Validation; 877 this[kWebSocket$2] = void 0; 878 this._bufferedBytes = 0; 879 this._buffers = []; 880 this._compressed = false; 881 this._payloadLength = 0; 882 this._mask = void 0; 883 this._fragmented = 0; 884 this._masked = false; 885 this._fin = false; 886 this._opcode = 0; 887 this._totalPayloadLength = 0; 888 this._messageLength = 0; 889 this._fragments = []; 890 this._state = GET_INFO; 891 this._loop = false; 892 } 893 /** 894 * Implements `Writable.prototype._write()`. 895 * 896 * @param {Buffer} chunk The chunk of data to write 897 * @param {String} encoding The character encoding of `chunk` 898 * @param {Function} cb Callback 899 * @private 900 */ 901 _write(chunk, encoding, cb) { 902 if (this._opcode === 8 && this._state == GET_INFO) 903 return cb(); 904 this._bufferedBytes += chunk.length; 905 this._buffers.push(chunk); 906 this.startLoop(cb); 907 } 908 /** 909 * Consumes `n` bytes from the buffered data. 910 * 911 * @param {Number} n The number of bytes to consume 912 * @return {Buffer} The consumed bytes 913 * @private 914 */ 915 consume(n) { 916 this._bufferedBytes -= n; 917 if (n === this._buffers[0].length) 918 return this._buffers.shift(); 919 if (n < this._buffers[0].length) { 920 const buf = this._buffers[0]; 921 this._buffers[0] = new FastBuffer( 922 buf.buffer, 923 buf.byteOffset + n, 924 buf.length - n 925 ); 926 return new FastBuffer(buf.buffer, buf.byteOffset, n); 927 } 928 const dst = Buffer.allocUnsafe(n); 929 do { 930 const buf = this._buffers[0]; 931 const offset = dst.length - n; 932 if (n >= buf.length) { 933 dst.set(this._buffers.shift(), offset); 934 } else { 935 dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); 936 this._buffers[0] = new FastBuffer( 937 buf.buffer, 938 buf.byteOffset + n, 939 buf.length - n 940 ); 941 } 942 n -= buf.length; 943 } while (n > 0); 944 return dst; 945 } 946 /** 947 * Starts the parsing loop. 948 * 949 * @param {Function} cb Callback 950 * @private 951 */ 952 startLoop(cb) { 953 let err; 954 this._loop = true; 955 do { 956 switch (this._state) { 957 case GET_INFO: 958 err = this.getInfo(); 959 break; 960 case GET_PAYLOAD_LENGTH_16: 961 err = this.getPayloadLength16(); 962 break; 963 case GET_PAYLOAD_LENGTH_64: 964 err = this.getPayloadLength64(); 965 break; 966 case GET_MASK: 967 this.getMask(); 968 break; 969 case GET_DATA: 970 err = this.getData(cb); 971 break; 972 default: 973 this._loop = false;
vendor: 8,546 bytes, lines 974-1314
974 return; 975 } 976 } while (this._loop); 977 cb(err); 978 } 979 /** 980 * Reads the first two bytes of a frame. 981 * 982 * @return {(RangeError|undefined)} A possible error 983 * @private 984 */ 985 getInfo() { 986 if (this._bufferedBytes < 2) { 987 this._loop = false; 988 return; 989 } 990 const buf = this.consume(2); 991 if ((buf[0] & 48) !== 0) { 992 this._loop = false; 993 return error( 994 RangeError, 995 "RSV2 and RSV3 must be clear", 996 true, 997 1002, 998 "WS_ERR_UNEXPECTED_RSV_2_3" 999 ); 1000 } 1001 const compressed = (buf[0] & 64) === 64; 1002 if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) { 1003 this._loop = false; 1004 return error( 1005 RangeError, 1006 "RSV1 must be clear", 1007 true, 1008 1002, 1009 "WS_ERR_UNEXPECTED_RSV_1" 1010 ); 1011 } 1012 this._fin = (buf[0] & 128) === 128; 1013 this._opcode = buf[0] & 15; 1014 this._payloadLength = buf[1] & 127; 1015 if (this._opcode === 0) { 1016 if (compressed) { 1017 this._loop = false; 1018 return error( 1019 RangeError, 1020 "RSV1 must be clear", 1021 true, 1022 1002, 1023 "WS_ERR_UNEXPECTED_RSV_1" 1024 ); 1025 } 1026 if (!this._fragmented) { 1027 this._loop = false; 1028 return error( 1029 RangeError, 1030 "invalid opcode 0", 1031 true, 1032 1002, 1033 "WS_ERR_INVALID_OPCODE" 1034 ); 1035 } 1036 this._opcode = this._fragmented; 1037 } else if (this._opcode === 1 || this._opcode === 2) { 1038 if (this._fragmented) { 1039 this._loop = false; 1040 return error( 1041 RangeError, 1042 `invalid opcode ${this._opcode}`, 1043 true, 1044 1002, 1045 "WS_ERR_INVALID_OPCODE" 1046 ); 1047 } 1048 this._compressed = compressed; 1049 } else if (this._opcode > 7 && this._opcode < 11) { 1050 if (!this._fin) { 1051 this._loop = false; 1052 return error( 1053 RangeError, 1054 "FIN must be set", 1055 true, 1056 1002, 1057 "WS_ERR_EXPECTED_FIN" 1058 ); 1059 } 1060 if (compressed) { 1061 this._loop = false; 1062 return error( 1063 RangeError, 1064 "RSV1 must be clear", 1065 true, 1066 1002, 1067 "WS_ERR_UNEXPECTED_RSV_1" 1068 ); 1069 } 1070 if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { 1071 this._loop = false; 1072 return error( 1073 RangeError, 1074 `invalid payload length ${this._payloadLength}`, 1075 true, 1076 1002, 1077 "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" 1078 ); 1079 } 1080 } else { 1081 this._loop = false; 1082 return error( 1083 RangeError, 1084 `invalid opcode ${this._opcode}`, 1085 true, 1086 1002, 1087 "WS_ERR_INVALID_OPCODE" 1088 ); 1089 } 1090 if (!this._fin && !this._fragmented) 1091 this._fragmented = this._opcode; 1092 this._masked = (buf[1] & 128) === 128; 1093 if (this._isServer) { 1094 if (!this._masked) { 1095 this._loop = false; 1096 return error( 1097 RangeError, 1098 "MASK must be set", 1099 true, 1100 1002, 1101 "WS_ERR_EXPECTED_MASK" 1102 ); 1103 } 1104 } else if (this._masked) { 1105 this._loop = false; 1106 return error( 1107 RangeError, 1108 "MASK must be clear", 1109 true, 1110 1002, 1111 "WS_ERR_UNEXPECTED_MASK" 1112 ); 1113 } 1114 if (this._payloadLength === 126) 1115 this._state = GET_PAYLOAD_LENGTH_16; 1116 else if (this._payloadLength === 127) 1117 this._state = GET_PAYLOAD_LENGTH_64; 1118 else 1119 return this.haveLength(); 1120 } 1121 /** 1122 * Gets extended payload length (7+16). 1123 * 1124 * @return {(RangeError|undefined)} A possible error 1125 * @private 1126 */ 1127 getPayloadLength16() { 1128 if (this._bufferedBytes < 2) { 1129 this._loop = false; 1130 return; 1131 } 1132 this._payloadLength = this.consume(2).readUInt16BE(0); 1133 return this.haveLength(); 1134 } 1135 /** 1136 * Gets extended payload length (7+64). 1137 * 1138 * @return {(RangeError|undefined)} A possible error 1139 * @private 1140 */ 1141 getPayloadLength64() { 1142 if (this._bufferedBytes < 8) { 1143 this._loop = false; 1144 return; 1145 } 1146 const buf = this.consume(8); 1147 const num = buf.readUInt32BE(0); 1148 if (num > Math.pow(2, 53 - 32) - 1) { 1149 this._loop = false; 1150 return error( 1151 RangeError, 1152 "Unsupported WebSocket frame: payload length > 2^53 - 1", 1153 false, 1154 1009, 1155 "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" 1156 ); 1157 } 1158 this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); 1159 return this.haveLength(); 1160 } 1161 /** 1162 * Payload length has been read. 1163 * 1164 * @return {(RangeError|undefined)} A possible error 1165 * @private 1166 */ 1167 haveLength() { 1168 if (this._payloadLength && this._opcode < 8) { 1169 this._totalPayloadLength += this._payloadLength; 1170 if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { 1171 this._loop = false; 1172 return error( 1173 RangeError, 1174 "Max payload size exceeded", 1175 false, 1176 1009, 1177 "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" 1178 ); 1179 } 1180 } 1181 if (this._masked) 1182 this._state = GET_MASK; 1183 else 1184 this._state = GET_DATA; 1185 } 1186 /** 1187 * Reads mask bytes. 1188 * 1189 * @private 1190 */ 1191 getMask() { 1192 if (this._bufferedBytes < 4) { 1193 this._loop = false; 1194 return; 1195 } 1196 this._mask = this.consume(4); 1197 this._state = GET_DATA; 1198 } 1199 /** 1200 * Reads data bytes. 1201 * 1202 * @param {Function} cb Callback 1203 * @return {(Error|RangeError|undefined)} A possible error 1204 * @private 1205 */ 1206 getData(cb) { 1207 let data = EMPTY_BUFFER$2; 1208 if (this._payloadLength) { 1209 if (this._bufferedBytes < this._payloadLength) { 1210 this._loop = false; 1211 return; 1212 } 1213 data = this.consume(this._payloadLength); 1214 if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { 1215 unmask(data, this._mask); 1216 } 1217 } 1218 if (this._opcode > 7) 1219 return this.controlMessage(data); 1220 if (this._compressed) { 1221 this._state = INFLATING; 1222 this.decompress(data, cb); 1223 return; 1224 } 1225 if (data.length) { 1226 this._messageLength = this._totalPayloadLength; 1227 this._fragments.push(data); 1228 } 1229 return this.dataMessage(); 1230 } 1231 /** 1232 * Decompresses data. 1233 * 1234 * @param {Buffer} data Compressed data 1235 * @param {Function} cb Callback 1236 * @private 1237 */ 1238 decompress(data, cb) { 1239 const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName]; 1240 perMessageDeflate.decompress(data, this._fin, (err, buf) => { 1241 if (err) 1242 return cb(err); 1243 if (buf.length) { 1244 this._messageLength += buf.length; 1245 if (this._messageLength > this._maxPayload && this._maxPayload > 0) { 1246 return cb( 1247 error( 1248 RangeError, 1249 "Max payload size exceeded", 1250 false, 1251 1009, 1252 "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" 1253 ) 1254 ); 1255 } 1256 this._fragments.push(buf); 1257 } 1258 const er = this.dataMessage(); 1259 if (er) 1260 return cb(er); 1261 this.startLoop(cb); 1262 }); 1263 } 1264 /** 1265 * Handles a data message. 1266 * 1267 * @return {(Error|undefined)} A possible error 1268 * @private 1269 */ 1270 dataMessage() { 1271 if (this._fin) { 1272 const messageLength = this._messageLength; 1273 const fragments = this._fragments; 1274 this._totalPayloadLength = 0; 1275 this._messageLength = 0; 1276 this._fragmented = 0; 1277 this._fragments = []; 1278 if (this._opcode === 2) { 1279 let data; 1280 if (this._binaryType === "nodebuffer") { 1281 data = concat(fragments, messageLength); 1282 } else if (this._binaryType === "arraybuffer") { 1283 data = toArrayBuffer(concat(fragments, messageLength)); 1284 } else { 1285 data = fragments; 1286 } 1287 this.emit("message", data, true); 1288 } else { 1289 const buf = concat(fragments, messageLength); 1290 if (!this._skipUTF8Validation && !isValidUTF8(buf)) { 1291 this._loop = false; 1292 return error( 1293 Error, 1294 "invalid UTF-8 sequence", 1295 true, 1296 1007, 1297 "WS_ERR_INVALID_UTF8" 1298 ); 1299 } 1300 this.emit("message", buf, false); 1301 } 1302 } 1303 this._state = GET_INFO; 1304 } 1305 /** 1306 * Handles a control message. 1307 * 1308 * @param {Buffer} data Data to handle 1309 * @return {(Error|RangeError|undefined)} A possible error 1310 * @private 1311 */ 1312 controlMessage(data) { 1313 if (this._opcode === 8) { 1314 this._loop = false;
1315 if (data.length === 0) { 1316 this.emit("conclude", 1005, EMPTY_BUFFER$2); 1317 this.end(); 1318 } else { 1319 const code = data.readUInt16BE(0); 1320 if (!isValidStatusCode$1(code)) { 1321 return error( 1322 RangeError, 1323 `invalid status code ${code}`, 1324 true, 1325 1002, 1326 "WS_ERR_INVALID_CLOSE_CODE" 1327 ); 1328 } 1329 const buf = new FastBuffer( 1330 data.buffer, 1331 data.byteOffset + 2, 1332 data.length - 2 1333 ); 1334 if (!this._skipUTF8Validation && !isValidUTF8(buf)) { 1335 return error( 1336 Error, 1337 "invalid UTF-8 sequence", 1338 true, 1339 1007, 1340 "WS_ERR_INVALID_UTF8" 1341 ); 1342 } 1343 this.emit("conclude", code, buf); 1344 this.end(); 1345 } 1346 } else if (this._opcode === 9) { 1347 this.emit("ping", data); 1348 } else { 1349 this.emit("pong", data); 1350 } 1351 this._state = GET_INFO; 1352 } 1353}; 1354var receiver = Receiver$1; 1355function error(ErrorCtor, message, prefix, statusCode, errorCode) { 1356 const err = new ErrorCtor( 1357 prefix ? `Invalid WebSocket frame: ${message}` : message 1358 ); 1359 Error.captureStackTrace(err, error); 1360 err.code = errorCode; 1361 err[kStatusCode$1] = statusCode; 1362 return err; 1363} 1364const receiver$1 = /* @__PURE__ */ getDefaultExportFromCjs(receiver); 1365const { randomFillSync } = require$$5; 1366const PerMessageDeflate$2 = permessageDeflate; 1367const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants; 1368const { isValidStatusCode } = validationExports; 1369const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports; 1370const kByteLength = Symbol("kByteLength"); 1371const maskBuffer = Buffer.alloc(4); 1372let Sender$1 = class Sender { 1373 /** 1374 * Creates a Sender instance. 1375 * 1376 * @param {(net.Socket|tls.Socket)} socket The connection socket 1377 * @param {Object} [extensions] An object containing the negotiated extensions 1378 * @param {Function} [generateMask] The function used to generate the masking 1379 * key 1380 */ 1381 constructor(socket, extensions, generateMask) { 1382 this._extensions = extensions || {}; 1383 if (generateMask) { 1384 this._generateMask = generateMask; 1385 this._maskBuffer = Buffer.alloc(4); 1386 } 1387 this._socket = socket; 1388 this._firstFragment = true; 1389 this._compress = false; 1390 this._bufferedBytes = 0; 1391 this._deflating = false; 1392 this._queue = []; 1393 } 1394 /** 1395 * Frames a piece of data according to the HyBi WebSocket protocol. 1396 * 1397 * @param {(Buffer|String)} data The data to frame 1398 * @param {Object} options Options object 1399 * @param {Boolean} [options.fin=false] Specifies whether or not to set the 1400 * FIN bit 1401 * @param {Function} [options.generateMask] The function used to generate the 1402 * masking key 1403 * @param {Boolean} [options.mask=false] Specifies whether or not to mask 1404 * `data` 1405 * @param {Buffer} [options.maskBuffer] The buffer used to store the masking 1406 * key 1407 * @param {Number} options.opcode The opcode 1408 * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be 1409 * modified 1410 * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the 1411 * RSV1 bit 1412 * @return {(Buffer|String)[]} The framed data 1413 * @public 1414 */ 1415 static frame(data, options) { 1416 let mask2; 1417 let merge = false; 1418 let offset = 2; 1419 let skipMasking = false; 1420 if (options.mask) { 1421 mask2 = options.maskBuffer || maskBuffer; 1422 if (options.generateMask) { 1423 options.generateMask(mask2); 1424 } else { 1425 randomFillSync(mask2, 0, 4); 1426 } 1427 skipMasking = (mask2[0] | mask2[1] | mask2[2] | mask2[3]) === 0; 1428 offset = 6; 1429 } 1430 let dataLength; 1431 if (typeof data === "string") { 1432 if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { 1433 dataLength = options[kByteLength]; 1434 } else { 1435 data = Buffer.from(data); 1436 dataLength = data.length; 1437 } 1438 } else { 1439 dataLength = data.length; 1440 merge = options.mask && options.readOnly && !skipMasking; 1441 } 1442 let payloadLength = dataLength; 1443 if (dataLength >= 65536) { 1444 offset += 8; 1445 payloadLength = 127; 1446 } else if (dataLength > 125) { 1447 offset += 2; 1448 payloadLength = 126; 1449 } 1450 const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); 1451 target[0] = options.fin ? options.opcode | 128 : options.opcode; 1452 if (options.rsv1) 1453 target[0] |= 64; 1454 target[1] = payloadLength; 1455 if (payloadLength === 126) { 1456 target.writeUInt16BE(dataLength, 2); 1457 } else if (payloadLength === 127) { 1458 target[2] = target[3] = 0; 1459 target.writeUIntBE(dataLength, 4, 6); 1460 } 1461 if (!options.mask) 1462 return [target, data]; 1463 target[1] |= 128; 1464 target[offset - 4] = mask2[0]; 1465 target[offset - 3] = mask2[1]; 1466 target[offset - 2] = mask2[2]; 1467 target[offset - 1] = mask2[3]; 1468 if (skipMasking) 1469 return [target, data]; 1470 if (merge) { 1471 applyMask(data, mask2, target, offset, dataLength); 1472 return [target]; 1473 } 1474 applyMask(data, mask2, data, 0, dataLength); 1475 return [target, data]; 1476 } 1477 /** 1478 * Sends a close message to the other peer. 1479 * 1480 * @param {Number} [code] The status code component of the body 1481 * @param {(String|Buffer)} [data] The message component of the body 1482 * @param {Boolean} [mask=false] Specifies whether or not to mask the message 1483 * @param {Function} [cb] Callback 1484 * @public 1485 */ 1486 close(code, data, mask2, cb) { 1487 let buf; 1488 if (code === void 0) { 1489 buf = EMPTY_BUFFER$1; 1490 } else if (typeof code !== "number" || !isValidStatusCode(code)) { 1491 throw new TypeError("First argument must be a valid error code number"); 1492 } else if (data === void 0 || !data.length) { 1493 buf = Buffer.allocUnsafe(2); 1494 buf.writeUInt16BE(code, 0); 1495 } else { 1496 const length = Buffer.byteLength(data); 1497 if (length > 123) { 1498 throw new RangeError("The message must not be greater than 123 bytes"); 1499 } 1500 buf = Buffer.allocUnsafe(2 + length); 1501 buf.writeUInt16BE(code, 0); 1502 if (typeof data === "string") { 1503 buf.write(data, 2); 1504 } else { 1505 buf.set(data, 2); 1506 } 1507 } 1508 const options = { 1509 [kByteLength]: buf.length, 1510 fin: true, 1511 generateMask: this._generateMask, 1512 mask: mask2, 1513 maskBuffer: this._maskBuffer, 1514 opcode: 8, 1515 readOnly: false, 1516 rsv1: false 1517 }; 1518 if (this._deflating) { 1519 this.enqueue([this.dispatch, buf, false, options, cb]); 1520 } else { 1521 this.sendFrame(Sender.frame(buf, options), cb); 1522 } 1523 } 1524 /** 1525 * Sends a ping message to the other peer. 1526 * 1527 * @param {*} data The message to send 1528 * @param {Boolean} [mask=false] Specifies whether or not to mask `data` 1529 * @param {Function} [cb] Callback 1530 * @public 1531 */ 1532 ping(data, mask2, cb) { 1533 let byteLength; 1534 let readOnly; 1535 if (typeof data === "string") { 1536 byteLength = Buffer.byteLength(data); 1537 readOnly = false;
vendor: 5,040 bytes, lines 1538-1702
1538 } else { 1539 data = toBuffer$1(data); 1540 byteLength = data.length; 1541 readOnly = toBuffer$1.readOnly; 1542 } 1543 if (byteLength > 125) { 1544 throw new RangeError("The data size must not be greater than 125 bytes"); 1545 } 1546 const options = { 1547 [kByteLength]: byteLength, 1548 fin: true, 1549 generateMask: this._generateMask, 1550 mask: mask2, 1551 maskBuffer: this._maskBuffer, 1552 opcode: 9, 1553 readOnly, 1554 rsv1: false 1555 }; 1556 if (this._deflating) { 1557 this.enqueue([this.dispatch, data, false, options, cb]); 1558 } else { 1559 this.sendFrame(Sender.frame(data, options), cb); 1560 } 1561 } 1562 /** 1563 * Sends a pong message to the other peer. 1564 * 1565 * @param {*} data The message to send 1566 * @param {Boolean} [mask=false] Specifies whether or not to mask `data` 1567 * @param {Function} [cb] Callback 1568 * @public 1569 */ 1570 pong(data, mask2, cb) { 1571 let byteLength; 1572 let readOnly; 1573 if (typeof data === "string") { 1574 byteLength = Buffer.byteLength(data); 1575 readOnly = false; 1576 } else { 1577 data = toBuffer$1(data); 1578 byteLength = data.length; 1579 readOnly = toBuffer$1.readOnly; 1580 } 1581 if (byteLength > 125) { 1582 throw new RangeError("The data size must not be greater than 125 bytes"); 1583 } 1584 const options = { 1585 [kByteLength]: byteLength, 1586 fin: true, 1587 generateMask: this._generateMask, 1588 mask: mask2, 1589 maskBuffer: this._maskBuffer, 1590 opcode: 10, 1591 readOnly, 1592 rsv1: false 1593 }; 1594 if (this._deflating) { 1595 this.enqueue([this.dispatch, data, false, options, cb]); 1596 } else { 1597 this.sendFrame(Sender.frame(data, options), cb); 1598 } 1599 } 1600 /** 1601 * Sends a data message to the other peer. 1602 * 1603 * @param {*} data The message to send 1604 * @param {Object} options Options object 1605 * @param {Boolean} [options.binary=false] Specifies whether `data` is binary 1606 * or text 1607 * @param {Boolean} [options.compress=false] Specifies whether or not to 1608 * compress `data` 1609 * @param {Boolean} [options.fin=false] Specifies whether the fragment is the 1610 * last one 1611 * @param {Boolean} [options.mask=false] Specifies whether or not to mask 1612 * `data` 1613 * @param {Function} [cb] Callback 1614 * @public 1615 */ 1616 send(data, options, cb) { 1617 const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; 1618 let opcode = options.binary ? 2 : 1; 1619 let rsv1 = options.compress; 1620 let byteLength; 1621 let readOnly; 1622 if (typeof data === "string") { 1623 byteLength = Buffer.byteLength(data); 1624 readOnly = false; 1625 } else { 1626 data = toBuffer$1(data); 1627 byteLength = data.length; 1628 readOnly = toBuffer$1.readOnly; 1629 } 1630 if (this._firstFragment) { 1631 this._firstFragment = false; 1632 if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { 1633 rsv1 = byteLength >= perMessageDeflate._threshold; 1634 } 1635 this._compress = rsv1; 1636 } else { 1637 rsv1 = false; 1638 opcode = 0; 1639 } 1640 if (options.fin) 1641 this._firstFragment = true; 1642 if (perMessageDeflate) { 1643 const opts = { 1644 [kByteLength]: byteLength, 1645 fin: options.fin, 1646 generateMask: this._generateMask, 1647 mask: options.mask, 1648 maskBuffer: this._maskBuffer, 1649 opcode, 1650 readOnly, 1651 rsv1 1652 }; 1653 if (this._deflating) { 1654 this.enqueue([this.dispatch, data, this._compress, opts, cb]); 1655 } else { 1656 this.dispatch(data, this._compress, opts, cb); 1657 } 1658 } else { 1659 this.sendFrame( 1660 Sender.frame(data, { 1661 [kByteLength]: byteLength, 1662 fin: options.fin, 1663 generateMask: this._generateMask, 1664 mask: options.mask, 1665 maskBuffer: this._maskBuffer, 1666 opcode, 1667 readOnly, 1668 rsv1: false 1669 }), 1670 cb 1671 ); 1672 } 1673 } 1674 /** 1675 * Dispatches a message. 1676 * 1677 * @param {(Buffer|String)} data The message to send 1678 * @param {Boolean} [compress=false] Specifies whether or not to compress 1679 * `data` 1680 * @param {Object} options Options object 1681 * @param {Boolean} [options.fin=false] Specifies whether or not to set the 1682 * FIN bit 1683 * @param {Function} [options.generateMask] The function used to generate the 1684 * masking key 1685 * @param {Boolean} [options.mask=false] Specifies whether or not to mask 1686 * `data` 1687 * @param {Buffer} [options.maskBuffer] The buffer used to store the masking 1688 * key 1689 * @param {Number} options.opcode The opcode 1690 * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be 1691 * modified 1692 * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the 1693 * RSV1 bit 1694 * @param {Function} [cb] Callback 1695 * @private 1696 */ 1697 dispatch(data, compress, options, cb) { 1698 if (!compress) { 1699 this.sendFrame(Sender.frame(data, options), cb); 1700 return; 1701 } 1702 const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
1703 this._bufferedBytes += options[kByteLength]; 1704 this._deflating = true; 1705 perMessageDeflate.compress(data, options.fin, (_, buf) => { 1706 if (this._socket.destroyed) { 1707 const err = new Error( 1708 "The socket was closed while data was being compressed" 1709 ); 1710 if (typeof cb === "function") 1711 cb(err); 1712 for (let i = 0; i < this._queue.length; i++) { 1713 const params = this._queue[i]; 1714 const callback = params[params.length - 1]; 1715 if (typeof callback === "function") 1716 callback(err); 1717 } 1718 return; 1719 } 1720 this._bufferedBytes -= options[kByteLength]; 1721 this._deflating = false; 1722 options.readOnly = false; 1723 this.sendFrame(Sender.frame(buf, options), cb); 1724 this.dequeue(); 1725 }); 1726 } 1727 /** 1728 * Executes queued send operations. 1729 * 1730 * @private 1731 */ 1732 dequeue() { 1733 while (!this._deflating && this._queue.length) { 1734 const params = this._queue.shift(); 1735 this._bufferedBytes -= params[3][kByteLength]; 1736 Reflect.apply(params[0], this, params.slice(1)); 1737 } 1738 } 1739 /** 1740 * Enqueues a send operation. 1741 * 1742 * @param {Array} params Send operation parameters. 1743 * @private 1744 */ 1745 enqueue(params) { 1746 this._bufferedBytes += params[3][kByteLength]; 1747 this._queue.push(params); 1748 } 1749 /** 1750 * Sends a frame. 1751 * 1752 * @param {Buffer[]} list The frame to send 1753 * @param {Function} [cb] Callback 1754 * @private 1755 */ 1756 sendFrame(list, cb) { 1757 if (list.length === 2) { 1758 this._socket.cork(); 1759 this._socket.write(list[0]); 1760 this._socket.write(list[1], cb); 1761 this._socket.uncork(); 1762 } else { 1763 this._socket.write(list[0], cb); 1764 } 1765 } 1766}; 1767var sender = Sender$1; 1768const sender$1 = /* @__PURE__ */ getDefaultExportFromCjs(sender); 1769const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants; 1770const kCode = Symbol("kCode"); 1771const kData = Symbol("kData"); 1772const kError = Symbol("kError"); 1773const kMessage = Symbol("kMessage"); 1774const kReason = Symbol("kReason"); 1775const kTarget = Symbol("kTarget"); 1776const kType = Symbol("kType"); 1777const kWasClean = Symbol("kWasClean"); 1778class Event { 1779 /** 1780 * Create a new `Event`. 1781 * 1782 * @param {String} type The name of the event 1783 * @throws {TypeError} If the `type` argument is not specified 1784 */ 1785 constructor(type) { 1786 this[kTarget] = null; 1787 this[kType] = type; 1788 } 1789 /** 1790 * @type {*} 1791 */ 1792 get target() { 1793 return this[kTarget]; 1794 } 1795 /** 1796 * @type {String} 1797 */ 1798 get type() { 1799 return this[kType]; 1800 } 1801} 1802Object.defineProperty(Event.prototype, "target", { enumerable: true }); 1803Object.defineProperty(Event.prototype, "type", { enumerable: true }); 1804class CloseEvent extends Event { 1805 /** 1806 * Create a new `CloseEvent`. 1807 * 1808 * @param {String} type The name of the event 1809 * @param {Object} [options] A dictionary object that allows for setting 1810 * attributes via object members of the same name 1811 * @param {Number} [options.code=0] The status code explaining why the 1812 * connection was closed 1813 * @param {String} [options.reason=''] A human-readable string explaining why 1814 * the connection was closed 1815 * @param {Boolean} [options.wasClean=false] Indicates whether or not the 1816 * connection was cleanly closed 1817 */ 1818 constructor(type, options = {}) { 1819 super(type); 1820 this[kCode] = options.code === void 0 ? 0 : options.code; 1821 this[kReason] = options.reason === void 0 ? "" : options.reason; 1822 this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean; 1823 } 1824 /** 1825 * @type {Number} 1826 */ 1827 get code() { 1828 return this[kCode]; 1829 } 1830 /** 1831 * @type {String} 1832 */ 1833 get reason() { 1834 return this[kReason]; 1835 } 1836 /** 1837 * @type {Boolean} 1838 */ 1839 get wasClean() { 1840 return this[kWasClean]; 1841 } 1842} 1843Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); 1844Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); 1845Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); 1846class ErrorEvent extends Event { 1847 /** 1848 * Create a new `ErrorEvent`. 1849 * 1850 * @param {String} type The name of the event 1851 * @param {Object} [options] A dictionary object that allows for setting 1852 * attributes via object members of the same name 1853 * @param {*} [options.error=null] The error that generated this event 1854 * @param {String} [options.message=''] The error message 1855 */ 1856 constructor(type, options = {}) { 1857 super(type); 1858 this[kError] = options.error === void 0 ? null : options.error; 1859 this[kMessage] = options.message === void 0 ? "" : options.message; 1860 } 1861 /** 1862 * @type {*} 1863 */ 1864 get error() { 1865 return this[kError]; 1866 } 1867 /** 1868 * @type {String} 1869 */ 1870 get message() { 1871 return this[kMessage]; 1872 } 1873} 1874Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); 1875Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1876class MessageEvent extends Event { 1877 /** 1878 * Create a new `MessageEvent`. 1879 * 1880 * @param {String} type The name of the event 1881 * @param {Object} [options] A dictionary object that allows for setting 1882 * attributes via object members of the same name 1883 * @param {*} [options.data=null] The message content 1884 */ 1885 constructor(type, options = {}) { 1886 super(type); 1887 this[kData] = options.data === void 0 ? null : options.data; 1888 } 1889 /** 1890 * @type {*} 1891 */ 1892 get data() { 1893 return this[kData]; 1894 } 1895} 1896Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); 1897const EventTarget = { 1898 /** 1899 * Register an event listener. 1900 * 1901 * @param {String} type A string representing the event type to listen for 1902 * @param {(Function|Object)} handler The listener to add 1903 * @param {Object} [options] An options object specifies characteristics about 1904 * the event listener 1905 * @param {Boolean} [options.once=false] A `Boolean` indicating that the 1906 * listener should be invoked at most once after being added. If `true`, 1907 * the listener would be automatically removed when invoked. 1908 * @public 1909 */ 1910 addEventListener(type, handler, options = {}) { 1911 for (const listener of this.listeners(type)) { 1912 if (!options[kForOnEventAttribute$1] && listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) { 1913 return; 1914 } 1915 } 1916 let wrapper; 1917 if (type === "message") { 1918 wrapper = function onMessage(data, isBinary) { 1919 const event = new MessageEvent("message", { 1920 data: isBinary ? data : data.toString() 1921 }); 1922 event[kTarget] = this; 1923 callListener(handler, this, event); 1924 }; 1925 } else if (type === "close") { 1926 wrapper = function onClose(code, message) { 1927 const event = new CloseEvent("close", { 1928 code, 1929 reason: message.toString(), 1930 wasClean: this._closeFrameReceived && this._closeFrameSent 1931 }); 1932 event[kTarget] = this; 1933 callListener(handler, this, event); 1934 }; 1935 } else if (type === "error") { 1936 wrapper = function onError(error2) { 1937 const event = new ErrorEvent("error", { 1938 error: error2, 1939 message: error2.message 1940 }); 1941 event[kTarget] = this; 1942 callListener(handler, this, event); 1943 }; 1944 } else if (type === "open") { 1945 wrapper = function onOpen() { 1946 const event = new Event("open"); 1947 event[kTarget] = this; 1948 callListener(handler, this, event); 1949 }; 1950 } else { 1951 return; 1952 } 1953 wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1]; 1954 wrapper[kListener$1] = handler; 1955 if (options.once) { 1956 this.once(type, wrapper); 1957 } else { 1958 this.on(type, wrapper); 1959 } 1960 }, 1961 /** 1962 * Remove an event listener. 1963 * 1964 * @param {String} type A string representing the event type to remove 1965 * @param {(Function|Object)} handler The listener to remove 1966 * @public 1967 */ 1968 removeEventListener(type, handler) { 1969 for (const listener of this.listeners(type)) { 1970 if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) { 1971 this.removeListener(type, listener); 1972 break; 1973 } 1974 } 1975 } 1976}; 1977var eventTarget = { 1978 CloseEvent, 1979 ErrorEvent, 1980 Event, 1981 EventTarget, 1982 MessageEvent 1983}; 1984function callListener(listener, thisArg, event) { 1985 if (typeof listener === "object" && listener.handleEvent) { 1986 listener.handleEvent.call(listener, event); 1987 } else { 1988 listener.call(thisArg, event); 1989 } 1990} 1991const { tokenChars: tokenChars$1 } = validationExports; 1992function push(dest, name, elem) { 1993 if (dest[name] === void 0) 1994 dest[name] = [elem]; 1995 else 1996 dest[name].push(elem); 1997} 1998function parse$2(header) { 1999 const offers = /* @__PURE__ */ Object.create(null); 2000 let params = /* @__PURE__ */ Object.create(null); 2001 let mustUnescape = false;
vendor: 3,265 bytes, lines 2002-2101
2002 let isEscaping = false; 2003 let inQuotes = false; 2004 let extensionName; 2005 let paramName; 2006 let start = -1; 2007 let code = -1; 2008 let end = -1; 2009 let i = 0; 2010 for (; i < header.length; i++) { 2011 code = header.charCodeAt(i); 2012 if (extensionName === void 0) { 2013 if (end === -1 && tokenChars$1[code] === 1) { 2014 if (start === -1) 2015 start = i; 2016 } else if (i !== 0 && (code === 32 || code === 9)) { 2017 if (end === -1 && start !== -1) 2018 end = i; 2019 } else if (code === 59 || code === 44) { 2020 if (start === -1) { 2021 throw new SyntaxError(`Unexpected character at index ${i}`); 2022 } 2023 if (end === -1) 2024 end = i; 2025 const name = header.slice(start, end); 2026 if (code === 44) { 2027 push(offers, name, params); 2028 params = /* @__PURE__ */ Object.create(null); 2029 } else { 2030 extensionName = name; 2031 } 2032 start = end = -1; 2033 } else { 2034 throw new SyntaxError(`Unexpected character at index ${i}`); 2035 } 2036 } else if (paramName === void 0) { 2037 if (end === -1 && tokenChars$1[code] === 1) { 2038 if (start === -1) 2039 start = i; 2040 } else if (code === 32 || code === 9) { 2041 if (end === -1 && start !== -1) 2042 end = i; 2043 } else if (code === 59 || code === 44) { 2044 if (start === -1) { 2045 throw new SyntaxError(`Unexpected character at index ${i}`); 2046 } 2047 if (end === -1) 2048 end = i; 2049 push(params, header.slice(start, end), true); 2050 if (code === 44) { 2051 push(offers, extensionName, params); 2052 params = /* @__PURE__ */ Object.create(null); 2053 extensionName = void 0; 2054 } 2055 start = end = -1; 2056 } else if (code === 61 && start !== -1 && end === -1) { 2057 paramName = header.slice(start, i); 2058 start = end = -1; 2059 } else { 2060 throw new SyntaxError(`Unexpected character at index ${i}`); 2061 } 2062 } else { 2063 if (isEscaping) { 2064 if (tokenChars$1[code] !== 1) { 2065 throw new SyntaxError(`Unexpected character at index ${i}`); 2066 } 2067 if (start === -1) 2068 start = i; 2069 else if (!mustUnescape) 2070 mustUnescape = true; 2071 isEscaping = false; 2072 } else if (inQuotes) { 2073 if (tokenChars$1[code] === 1) { 2074 if (start === -1) 2075 start = i; 2076 } else if (code === 34 && start !== -1) { 2077 inQuotes = false; 2078 end = i; 2079 } else if (code === 92) { 2080 isEscaping = true; 2081 } else { 2082 throw new SyntaxError(`Unexpected character at index ${i}`); 2083 } 2084 } else if (code === 34 && header.charCodeAt(i - 1) === 61) { 2085 inQuotes = true; 2086 } else if (end === -1 && tokenChars$1[code] === 1) { 2087 if (start === -1) 2088 start = i; 2089 } else if (start !== -1 && (code === 32 || code === 9)) { 2090 if (end === -1) 2091 end = i; 2092 } else if (code === 59 || code === 44) { 2093 if (start === -1) { 2094 throw new SyntaxError(`Unexpected character at index ${i}`); 2095 } 2096 if (end === -1) 2097 end = i; 2098 let value = header.slice(start, end); 2099 if (mustUnescape) { 2100 value = value.replace(/\\/g, ""); 2101 mustUnescape = false;
2102 } 2103 push(params, paramName, value); 2104 if (code === 44) { 2105 push(offers, extensionName, params); 2106 params = /* @__PURE__ */ Object.create(null); 2107 extensionName = void 0; 2108 } 2109 paramName = void 0; 2110 start = end = -1; 2111 } else { 2112 throw new SyntaxError(`Unexpected character at index ${i}`); 2113 } 2114 } 2115 } 2116 if (start === -1 || inQuotes || code === 32 || code === 9) { 2117 throw new SyntaxError("Unexpected end of input"); 2118 } 2119 if (end === -1) 2120 end = i; 2121 const token = header.slice(start, end); 2122 if (extensionName === void 0) { 2123 push(offers, token, params); 2124 } else { 2125 if (paramName === void 0) { 2126 push(params, token, true); 2127 } else if (mustUnescape) { 2128 push(params, paramName, token.replace(/\\/g, "")); 2129 } else { 2130 push(params, paramName, token); 2131 } 2132 push(offers, extensionName, params); 2133 } 2134 return offers; 2135} 2136function format$1(extensions) { 2137 return Object.keys(extensions).map((extension2) => { 2138 let configurations = extensions[extension2]; 2139 if (!Array.isArray(configurations)) 2140 configurations = [configurations]; 2141 return configurations.map((params) => { 2142 return [extension2].concat( 2143 Object.keys(params).map((k) => { 2144 let values = params[k]; 2145 if (!Array.isArray(values)) 2146 values = [values]; 2147 return values.map((v) => v === true ? k : `${k}=${v}`).join("; "); 2148 }) 2149 ).join("; "); 2150 }).join(", "); 2151 }).join(", "); 2152} 2153var extension$1 = { format: format$1, parse: parse$2 }; 2154const EventEmitter$1 = require$$5; 2155const https = require$$5; 2156const http$1 = require$$5; 2157const net = require$$5; 2158const tls = require$$5; 2159const { randomBytes, createHash: createHash$1 } = require$$5; 2160const { URL } = require$$5; 2161const PerMessageDeflate$1 = permessageDeflate; 2162const Receiver2 = receiver; 2163const Sender2 = sender; 2164const { 2165 BINARY_TYPES, 2166 EMPTY_BUFFER, 2167 GUID: GUID$1, 2168 kForOnEventAttribute, 2169 kListener, 2170 kStatusCode, 2171 kWebSocket: kWebSocket$1, 2172 NOOP 2173} = constants; 2174const { 2175 EventTarget: { addEventListener, removeEventListener } 2176} = eventTarget; 2177const { format, parse: parse$1 } = extension$1; 2178const { toBuffer } = bufferUtilExports; 2179const closeTimeout = 30 * 1e3; 2180const kAborted = Symbol("kAborted"); 2181const protocolVersions = [8, 13]; 2182const readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; 2183const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; 2184let WebSocket$1 = class WebSocket extends EventEmitter$1 { 2185 /** 2186 * Create a new `WebSocket`. 2187 * 2188 * @param {(String|URL)} address The URL to which to connect 2189 * @param {(String|String[])} [protocols] The subprotocols 2190 * @param {Object} [options] Connection options 2191 */ 2192 constructor(address, protocols, options) { 2193 super(); 2194 this._binaryType = BINARY_TYPES[0]; 2195 this._closeCode = 1006; 2196 this._closeFrameReceived = false; 2197 this._closeFrameSent = false; 2198 this._closeMessage = EMPTY_BUFFER; 2199 this._closeTimer = null; 2200 this._extensions = {}; 2201 this._paused = false; 2202 this._protocol = ""; 2203 this._readyState = WebSocket.CONNECTING; 2204 this._receiver = null; 2205 this._sender = null; 2206 this._socket = null; 2207 if (address !== null) { 2208 this._bufferedAmount = 0; 2209 this._isServer = false; 2210 this._redirects = 0; 2211 if (protocols === void 0) { 2212 protocols = []; 2213 } else if (!Array.isArray(protocols)) { 2214 if (typeof protocols === "object" && protocols !== null) { 2215 options = protocols; 2216 protocols = []; 2217 } else { 2218 protocols = [protocols]; 2219 } 2220 } 2221 initAsClient(this, address, protocols, options); 2222 } else { 2223 this._isServer = true; 2224 } 2225 } 2226 /** 2227 * This deviates from the WHATWG interface since ws doesn't support the 2228 * required default "blob" type (instead we define a custom "nodebuffer" 2229 * type). 2230 * 2231 * @type {String} 2232 */ 2233 get binaryType() { 2234 return this._binaryType; 2235 } 2236 set binaryType(type) { 2237 if (!BINARY_TYPES.includes(type)) 2238 return; 2239 this._binaryType = type; 2240 if (this._receiver) 2241 this._receiver._binaryType = type; 2242 } 2243 /** 2244 * @type {Number} 2245 */ 2246 get bufferedAmount() { 2247 if (!this._socket) 2248 return this._bufferedAmount; 2249 return this._socket._writableState.length + this._sender._bufferedBytes; 2250 } 2251 /** 2252 * @type {String} 2253 */ 2254 get extensions() { 2255 return Object.keys(this._extensions).join(); 2256 } 2257 /** 2258 * @type {Boolean} 2259 */ 2260 get isPaused() { 2261 return this._paused; 2262 } 2263 /** 2264 * @type {Function} 2265 */ 2266 /* istanbul ignore next */ 2267 get onclose() { 2268 return null; 2269 } 2270 /** 2271 * @type {Function} 2272 */ 2273 /* istanbul ignore next */
vendor: 16,084 bytes, lines 2274-2795
2274 get onerror() { 2275 return null; 2276 } 2277 /** 2278 * @type {Function} 2279 */ 2280 /* istanbul ignore next */ 2281 get onopen() { 2282 return null; 2283 } 2284 /** 2285 * @type {Function} 2286 */ 2287 /* istanbul ignore next */ 2288 get onmessage() { 2289 return null; 2290 } 2291 /** 2292 * @type {String} 2293 */ 2294 get protocol() { 2295 return this._protocol; 2296 } 2297 /** 2298 * @type {Number} 2299 */ 2300 get readyState() { 2301 return this._readyState; 2302 } 2303 /** 2304 * @type {String} 2305 */ 2306 get url() { 2307 return this._url; 2308 } 2309 /** 2310 * Set up the socket and the internal resources. 2311 * 2312 * @param {(net.Socket|tls.Socket)} socket The network socket between the 2313 * server and client 2314 * @param {Buffer} head The first packet of the upgraded stream 2315 * @param {Object} options Options object 2316 * @param {Function} [options.generateMask] The function used to generate the 2317 * masking key 2318 * @param {Number} [options.maxPayload=0] The maximum allowed message size 2319 * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or 2320 * not to skip UTF-8 validation for text and close messages 2321 * @private 2322 */ 2323 setSocket(socket, head, options) { 2324 const receiver2 = new Receiver2({ 2325 binaryType: this.binaryType, 2326 extensions: this._extensions, 2327 isServer: this._isServer, 2328 maxPayload: options.maxPayload, 2329 skipUTF8Validation: options.skipUTF8Validation 2330 }); 2331 this._sender = new Sender2(socket, this._extensions, options.generateMask); 2332 this._receiver = receiver2; 2333 this._socket = socket; 2334 receiver2[kWebSocket$1] = this; 2335 socket[kWebSocket$1] = this; 2336 receiver2.on("conclude", receiverOnConclude); 2337 receiver2.on("drain", receiverOnDrain); 2338 receiver2.on("error", receiverOnError); 2339 receiver2.on("message", receiverOnMessage); 2340 receiver2.on("ping", receiverOnPing); 2341 receiver2.on("pong", receiverOnPong); 2342 socket.setTimeout(0); 2343 socket.setNoDelay(); 2344 if (head.length > 0) 2345 socket.unshift(head); 2346 socket.on("close", socketOnClose); 2347 socket.on("data", socketOnData); 2348 socket.on("end", socketOnEnd); 2349 socket.on("error", socketOnError$1); 2350 this._readyState = WebSocket.OPEN; 2351 this.emit("open"); 2352 } 2353 /** 2354 * Emit the `'close'` event. 2355 * 2356 * @private 2357 */ 2358 emitClose() { 2359 if (!this._socket) { 2360 this._readyState = WebSocket.CLOSED; 2361 this.emit("close", this._closeCode, this._closeMessage); 2362 return; 2363 } 2364 if (this._extensions[PerMessageDeflate$1.extensionName]) { 2365 this._extensions[PerMessageDeflate$1.extensionName].cleanup(); 2366 } 2367 this._receiver.removeAllListeners(); 2368 this._readyState = WebSocket.CLOSED; 2369 this.emit("close", this._closeCode, this._closeMessage); 2370 } 2371 /** 2372 * Start a closing handshake. 2373 * 2374 * +----------+ +-----------+ +----------+ 2375 * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - 2376 * | +----------+ +-----------+ +----------+ | 2377 * +----------+ +-----------+ | 2378 * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING 2379 * +----------+ +-----------+ | 2380 * | | | +---+ | 2381 * +------------------------+-->|fin| - - - - 2382 * | +---+ | +---+ 2383 * - - - - -|fin|<---------------------+ 2384 * +---+ 2385 * 2386 * @param {Number} [code] Status code explaining why the connection is closing 2387 * @param {(String|Buffer)} [data] The reason why the connection is 2388 * closing 2389 * @public 2390 */ 2391 close(code, data) { 2392 if (this.readyState === WebSocket.CLOSED) 2393 return; 2394 if (this.readyState === WebSocket.CONNECTING) { 2395 const msg = "WebSocket was closed before the connection was established"; 2396 abortHandshake$1(this, this._req, msg); 2397 return; 2398 } 2399 if (this.readyState === WebSocket.CLOSING) { 2400 if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { 2401 this._socket.end(); 2402 } 2403 return; 2404 } 2405 this._readyState = WebSocket.CLOSING; 2406 this._sender.close(code, data, !this._isServer, (err) => { 2407 if (err) 2408 return; 2409 this._closeFrameSent = true; 2410 if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { 2411 this._socket.end(); 2412 } 2413 }); 2414 this._closeTimer = setTimeout( 2415 this._socket.destroy.bind(this._socket), 2416 closeTimeout 2417 ); 2418 } 2419 /** 2420 * Pause the socket. 2421 * 2422 * @public 2423 */ 2424 pause() { 2425 if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) { 2426 return; 2427 } 2428 this._paused = true; 2429 this._socket.pause(); 2430 } 2431 /** 2432 * Send a ping. 2433 * 2434 * @param {*} [data] The data to send 2435 * @param {Boolean} [mask] Indicates whether or not to mask `data` 2436 * @param {Function} [cb] Callback which is executed when the ping is sent 2437 * @public 2438 */ 2439 ping(data, mask2, cb) { 2440 if (this.readyState === WebSocket.CONNECTING) { 2441 throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); 2442 } 2443 if (typeof data === "function") { 2444 cb = data; 2445 data = mask2 = void 0; 2446 } else if (typeof mask2 === "function") { 2447 cb = mask2; 2448 mask2 = void 0; 2449 } 2450 if (typeof data === "number") 2451 data = data.toString(); 2452 if (this.readyState !== WebSocket.OPEN) { 2453 sendAfterClose(this, data, cb); 2454 return; 2455 } 2456 if (mask2 === void 0) 2457 mask2 = !this._isServer; 2458 this._sender.ping(data || EMPTY_BUFFER, mask2, cb); 2459 } 2460 /** 2461 * Send a pong. 2462 * 2463 * @param {*} [data] The data to send 2464 * @param {Boolean} [mask] Indicates whether or not to mask `data` 2465 * @param {Function} [cb] Callback which is executed when the pong is sent 2466 * @public 2467 */ 2468 pong(data, mask2, cb) { 2469 if (this.readyState === WebSocket.CONNECTING) { 2470 throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); 2471 } 2472 if (typeof data === "function") { 2473 cb = data; 2474 data = mask2 = void 0; 2475 } else if (typeof mask2 === "function") { 2476 cb = mask2; 2477 mask2 = void 0; 2478 } 2479 if (typeof data === "number") 2480 data = data.toString(); 2481 if (this.readyState !== WebSocket.OPEN) { 2482 sendAfterClose(this, data, cb); 2483 return; 2484 } 2485 if (mask2 === void 0) 2486 mask2 = !this._isServer; 2487 this._sender.pong(data || EMPTY_BUFFER, mask2, cb); 2488 } 2489 /** 2490 * Resume the socket. 2491 * 2492 * @public 2493 */ 2494 resume() { 2495 if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) { 2496 return; 2497 } 2498 this._paused = false; 2499 if (!this._receiver._writableState.needDrain) 2500 this._socket.resume(); 2501 } 2502 /** 2503 * Send a data message. 2504 * 2505 * @param {*} data The message to send 2506 * @param {Object} [options] Options object 2507 * @param {Boolean} [options.binary] Specifies whether `data` is binary or 2508 * text 2509 * @param {Boolean} [options.compress] Specifies whether or not to compress 2510 * `data` 2511 * @param {Boolean} [options.fin=true] Specifies whether the fragment is the 2512 * last one 2513 * @param {Boolean} [options.mask] Specifies whether or not to mask `data` 2514 * @param {Function} [cb] Callback which is executed when data is written out 2515 * @public 2516 */ 2517 send(data, options, cb) { 2518 if (this.readyState === WebSocket.CONNECTING) { 2519 throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); 2520 } 2521 if (typeof options === "function") { 2522 cb = options; 2523 options = {}; 2524 } 2525 if (typeof data === "number") 2526 data = data.toString(); 2527 if (this.readyState !== WebSocket.OPEN) { 2528 sendAfterClose(this, data, cb); 2529 return; 2530 } 2531 const opts = { 2532 binary: typeof data !== "string", 2533 mask: !this._isServer, 2534 compress: true, 2535 fin: true, 2536 ...options 2537 }; 2538 if (!this._extensions[PerMessageDeflate$1.extensionName]) { 2539 opts.compress = false; 2540 } 2541 this._sender.send(data || EMPTY_BUFFER, opts, cb); 2542 } 2543 /** 2544 * Forcibly close the connection. 2545 * 2546 * @public 2547 */ 2548 terminate() { 2549 if (this.readyState === WebSocket.CLOSED) 2550 return; 2551 if (this.readyState === WebSocket.CONNECTING) { 2552 const msg = "WebSocket was closed before the connection was established"; 2553 abortHandshake$1(this, this._req, msg); 2554 return; 2555 } 2556 if (this._socket) { 2557 this._readyState = WebSocket.CLOSING; 2558 this._socket.destroy(); 2559 } 2560 } 2561}; 2562Object.defineProperty(WebSocket$1, "CONNECTING", { 2563 enumerable: true, 2564 value: readyStates.indexOf("CONNECTING") 2565}); 2566Object.defineProperty(WebSocket$1.prototype, "CONNECTING", { 2567 enumerable: true, 2568 value: readyStates.indexOf("CONNECTING") 2569}); 2570Object.defineProperty(WebSocket$1, "OPEN", { 2571 enumerable: true, 2572 value: readyStates.indexOf("OPEN") 2573}); 2574Object.defineProperty(WebSocket$1.prototype, "OPEN", { 2575 enumerable: true, 2576 value: readyStates.indexOf("OPEN") 2577}); 2578Object.defineProperty(WebSocket$1, "CLOSING", { 2579 enumerable: true, 2580 value: readyStates.indexOf("CLOSING") 2581}); 2582Object.defineProperty(WebSocket$1.prototype, "CLOSING", { 2583 enumerable: true, 2584 value: readyStates.indexOf("CLOSING") 2585}); 2586Object.defineProperty(WebSocket$1, "CLOSED", { 2587 enumerable: true, 2588 value: readyStates.indexOf("CLOSED") 2589}); 2590Object.defineProperty(WebSocket$1.prototype, "CLOSED", { 2591 enumerable: true, 2592 value: readyStates.indexOf("CLOSED") 2593}); 2594[ 2595 "binaryType", 2596 "bufferedAmount", 2597 "extensions", 2598 "isPaused", 2599 "protocol", 2600 "readyState", 2601 "url" 2602].forEach((property) => { 2603 Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true }); 2604}); 2605["open", "error", "close", "message"].forEach((method) => { 2606 Object.defineProperty(WebSocket$1.prototype, `on${method}`, { 2607 enumerable: true, 2608 get() { 2609 for (const listener of this.listeners(method)) { 2610 if (listener[kForOnEventAttribute]) 2611 return listener[kListener]; 2612 } 2613 return null; 2614 }, 2615 set(handler) { 2616 for (const listener of this.listeners(method)) { 2617 if (listener[kForOnEventAttribute]) { 2618 this.removeListener(method, listener); 2619 break; 2620 } 2621 } 2622 if (typeof handler !== "function") 2623 return; 2624 this.addEventListener(method, handler, { 2625 [kForOnEventAttribute]: true 2626 }); 2627 } 2628 }); 2629}); 2630WebSocket$1.prototype.addEventListener = addEventListener; 2631WebSocket$1.prototype.removeEventListener = removeEventListener; 2632var websocket = WebSocket$1; 2633function initAsClient(websocket2, address, protocols, options) { 2634 const opts = { 2635 protocolVersion: protocolVersions[1], 2636 maxPayload: 100 * 1024 * 1024, 2637 skipUTF8Validation: false, 2638 perMessageDeflate: true, 2639 followRedirects: false, 2640 maxRedirects: 10, 2641 ...options, 2642 createConnection: void 0, 2643 socketPath: void 0, 2644 hostname: void 0, 2645 protocol: void 0, 2646 timeout: void 0, 2647 method: "GET", 2648 host: void 0, 2649 path: void 0, 2650 port: void 0 2651 }; 2652 if (!protocolVersions.includes(opts.protocolVersion)) { 2653 throw new RangeError( 2654 `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` 2655 ); 2656 } 2657 let parsedUrl; 2658 if (address instanceof URL) { 2659 parsedUrl = address; 2660 websocket2._url = address.href; 2661 } else { 2662 try { 2663 parsedUrl = new URL(address); 2664 } catch (e) { 2665 throw new SyntaxError(`Invalid URL: ${address}`); 2666 } 2667 websocket2._url = address; 2668 } 2669 const isSecure = parsedUrl.protocol === "wss:"; 2670 const isIpcUrl = parsedUrl.protocol === "ws+unix:"; 2671 let invalidUrlMessage; 2672 if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { 2673 invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", or "ws+unix:"`; 2674 } else if (isIpcUrl && !parsedUrl.pathname) { 2675 invalidUrlMessage = "The URL's pathname is empty"; 2676 } else if (parsedUrl.hash) { 2677 invalidUrlMessage = "The URL contains a fragment identifier"; 2678 } 2679 if (invalidUrlMessage) { 2680 const err = new SyntaxError(invalidUrlMessage); 2681 if (websocket2._redirects === 0) { 2682 throw err; 2683 } else { 2684 emitErrorAndClose(websocket2, err); 2685 return; 2686 } 2687 } 2688 const defaultPort = isSecure ? 443 : 80; 2689 const key = randomBytes(16).toString("base64"); 2690 const request = isSecure ? https.request : http$1.request; 2691 const protocolSet = /* @__PURE__ */ new Set(); 2692 let perMessageDeflate; 2693 opts.createConnection = isSecure ? tlsConnect : netConnect; 2694 opts.defaultPort = opts.defaultPort || defaultPort; 2695 opts.port = parsedUrl.port || defaultPort; 2696 opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; 2697 opts.headers = { 2698 ...opts.headers, 2699 "Sec-WebSocket-Version": opts.protocolVersion, 2700 "Sec-WebSocket-Key": key, 2701 Connection: "Upgrade", 2702 Upgrade: "websocket" 2703 }; 2704 opts.path = parsedUrl.pathname + parsedUrl.search; 2705 opts.timeout = opts.handshakeTimeout; 2706 if (opts.perMessageDeflate) { 2707 perMessageDeflate = new PerMessageDeflate$1( 2708 opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, 2709 false, 2710 opts.maxPayload 2711 ); 2712 opts.headers["Sec-WebSocket-Extensions"] = format({ 2713 [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer() 2714 }); 2715 } 2716 if (protocols.length) { 2717 for (const protocol of protocols) { 2718 if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { 2719 throw new SyntaxError( 2720 "An invalid or duplicated subprotocol was specified" 2721 ); 2722 } 2723 protocolSet.add(protocol); 2724 } 2725 opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); 2726 } 2727 if (opts.origin) { 2728 if (opts.protocolVersion < 13) { 2729 opts.headers["Sec-WebSocket-Origin"] = opts.origin; 2730 } else { 2731 opts.headers.Origin = opts.origin; 2732 } 2733 } 2734 if (parsedUrl.username || parsedUrl.password) { 2735 opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; 2736 } 2737 if (isIpcUrl) { 2738 const parts = opts.path.split(":"); 2739 opts.socketPath = parts[0]; 2740 opts.path = parts[1]; 2741 } 2742 let req; 2743 if (opts.followRedirects) { 2744 if (websocket2._redirects === 0) { 2745 websocket2._originalIpc = isIpcUrl; 2746 websocket2._originalSecure = isSecure; 2747 websocket2._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; 2748 const headers = options && options.headers; 2749 options = { ...options, headers: {} }; 2750 if (headers) { 2751 for (const [key2, value] of Object.entries(headers)) { 2752 options.headers[key2.toLowerCase()] = value; 2753 } 2754 } 2755 } else if (websocket2.listenerCount("redirect") === 0) { 2756 const isSameHost = isIpcUrl ? websocket2._originalIpc ? opts.socketPath === websocket2._originalHostOrSocketPath : false : websocket2._originalIpc ? false : parsedUrl.host === websocket2._originalHostOrSocketPath; 2757 if (!isSameHost || websocket2._originalSecure && !isSecure) { 2758 delete opts.headers.authorization; 2759 delete opts.headers.cookie; 2760 if (!isSameHost) 2761 delete opts.headers.host; 2762 opts.auth = void 0; 2763 } 2764 } 2765 if (opts.auth && !options.headers.authorization) { 2766 options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); 2767 } 2768 req = websocket2._req = request(opts); 2769 if (websocket2._redirects) { 2770 websocket2.emit("redirect", websocket2.url, req); 2771 } 2772 } else { 2773 req = websocket2._req = request(opts); 2774 } 2775 if (opts.timeout) { 2776 req.on("timeout", () => { 2777 abortHandshake$1(websocket2, req, "Opening handshake has timed out"); 2778 }); 2779 } 2780 req.on("error", (err) => { 2781 if (req === null || req[kAborted]) 2782 return; 2783 req = websocket2._req = null; 2784 emitErrorAndClose(websocket2, err); 2785 }); 2786 req.on("response", (res) => { 2787 const location = res.headers.location; 2788 const statusCode = res.statusCode; 2789 if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) { 2790 if (++websocket2._redirects > opts.maxRedirects) { 2791 abortHandshake$1(websocket2, req, "Maximum redirects exceeded"); 2792 return; 2793 } 2794 req.abort(); 2795 let addr;
vendor: 14,235 bytes, lines 2796-3222
2796 try { 2797 addr = new URL(location, address); 2798 } catch (e) { 2799 const err = new SyntaxError(`Invalid URL: ${location}`); 2800 emitErrorAndClose(websocket2, err); 2801 return; 2802 } 2803 initAsClient(websocket2, addr, protocols, options); 2804 } else if (!websocket2.emit("unexpected-response", req, res)) { 2805 abortHandshake$1( 2806 websocket2, 2807 req, 2808 `Unexpected server response: ${res.statusCode}` 2809 ); 2810 } 2811 }); 2812 req.on("upgrade", (res, socket, head) => { 2813 websocket2.emit("upgrade", res); 2814 if (websocket2.readyState !== WebSocket$1.CONNECTING) 2815 return; 2816 req = websocket2._req = null; 2817 if (res.headers.upgrade.toLowerCase() !== "websocket") { 2818 abortHandshake$1(websocket2, socket, "Invalid Upgrade header"); 2819 return; 2820 } 2821 const digest = createHash$1("sha1").update(key + GUID$1).digest("base64"); 2822 if (res.headers["sec-websocket-accept"] !== digest) { 2823 abortHandshake$1(websocket2, socket, "Invalid Sec-WebSocket-Accept header"); 2824 return; 2825 } 2826 const serverProt = res.headers["sec-websocket-protocol"]; 2827 let protError; 2828 if (serverProt !== void 0) { 2829 if (!protocolSet.size) { 2830 protError = "Server sent a subprotocol but none was requested"; 2831 } else if (!protocolSet.has(serverProt)) { 2832 protError = "Server sent an invalid subprotocol"; 2833 } 2834 } else if (protocolSet.size) { 2835 protError = "Server sent no subprotocol"; 2836 } 2837 if (protError) { 2838 abortHandshake$1(websocket2, socket, protError); 2839 return; 2840 } 2841 if (serverProt) 2842 websocket2._protocol = serverProt; 2843 const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; 2844 if (secWebSocketExtensions !== void 0) { 2845 if (!perMessageDeflate) { 2846 const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested"; 2847 abortHandshake$1(websocket2, socket, message); 2848 return; 2849 } 2850 let extensions; 2851 try { 2852 extensions = parse$1(secWebSocketExtensions); 2853 } catch (err) { 2854 const message = "Invalid Sec-WebSocket-Extensions header"; 2855 abortHandshake$1(websocket2, socket, message); 2856 return; 2857 } 2858 const extensionNames = Object.keys(extensions); 2859 if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate$1.extensionName) { 2860 const message = "Server indicated an extension that was not requested"; 2861 abortHandshake$1(websocket2, socket, message); 2862 return; 2863 } 2864 try { 2865 perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]); 2866 } catch (err) { 2867 const message = "Invalid Sec-WebSocket-Extensions header"; 2868 abortHandshake$1(websocket2, socket, message); 2869 return; 2870 } 2871 websocket2._extensions[PerMessageDeflate$1.extensionName] = perMessageDeflate; 2872 } 2873 websocket2.setSocket(socket, head, { 2874 generateMask: opts.generateMask, 2875 maxPayload: opts.maxPayload, 2876 skipUTF8Validation: opts.skipUTF8Validation 2877 }); 2878 }); 2879 if (opts.finishRequest) { 2880 opts.finishRequest(req, websocket2); 2881 } else { 2882 req.end(); 2883 } 2884} 2885function emitErrorAndClose(websocket2, err) { 2886 websocket2._readyState = WebSocket$1.CLOSING; 2887 websocket2.emit("error", err); 2888 websocket2.emitClose(); 2889} 2890function netConnect(options) { 2891 options.path = options.socketPath; 2892 return net.connect(options); 2893} 2894function tlsConnect(options) { 2895 options.path = void 0; 2896 if (!options.servername && options.servername !== "") { 2897 options.servername = net.isIP(options.host) ? "" : options.host; 2898 } 2899 return tls.connect(options); 2900} 2901function abortHandshake$1(websocket2, stream2, message) { 2902 websocket2._readyState = WebSocket$1.CLOSING; 2903 const err = new Error(message); 2904 Error.captureStackTrace(err, abortHandshake$1); 2905 if (stream2.setHeader) { 2906 stream2[kAborted] = true; 2907 stream2.abort(); 2908 if (stream2.socket && !stream2.socket.destroyed) { 2909 stream2.socket.destroy(); 2910 } 2911 process.nextTick(emitErrorAndClose, websocket2, err); 2912 } else { 2913 stream2.destroy(err); 2914 stream2.once("error", websocket2.emit.bind(websocket2, "error")); 2915 stream2.once("close", websocket2.emitClose.bind(websocket2)); 2916 } 2917} 2918function sendAfterClose(websocket2, data, cb) { 2919 if (data) { 2920 const length = toBuffer(data).length; 2921 if (websocket2._socket) 2922 websocket2._sender._bufferedBytes += length; 2923 else 2924 websocket2._bufferedAmount += length; 2925 } 2926 if (cb) { 2927 const err = new Error( 2928 `WebSocket is not open: readyState ${websocket2.readyState} (${readyStates[websocket2.readyState]})` 2929 ); 2930 process.nextTick(cb, err); 2931 } 2932} 2933function receiverOnConclude(code, reason) { 2934 const websocket2 = this[kWebSocket$1]; 2935 websocket2._closeFrameReceived = true; 2936 websocket2._closeMessage = reason; 2937 websocket2._closeCode = code; 2938 if (websocket2._socket[kWebSocket$1] === void 0) 2939 return; 2940 websocket2._socket.removeListener("data", socketOnData); 2941 process.nextTick(resume, websocket2._socket); 2942 if (code === 1005) 2943 websocket2.close(); 2944 else 2945 websocket2.close(code, reason); 2946} 2947function receiverOnDrain() { 2948 const websocket2 = this[kWebSocket$1]; 2949 if (!websocket2.isPaused) 2950 websocket2._socket.resume(); 2951} 2952function receiverOnError(err) { 2953 const websocket2 = this[kWebSocket$1]; 2954 if (websocket2._socket[kWebSocket$1] !== void 0) { 2955 websocket2._socket.removeListener("data", socketOnData); 2956 process.nextTick(resume, websocket2._socket); 2957 websocket2.close(err[kStatusCode]); 2958 } 2959 websocket2.emit("error", err); 2960} 2961function receiverOnFinish() { 2962 this[kWebSocket$1].emitClose(); 2963} 2964function receiverOnMessage(data, isBinary) { 2965 this[kWebSocket$1].emit("message", data, isBinary); 2966} 2967function receiverOnPing(data) { 2968 const websocket2 = this[kWebSocket$1]; 2969 websocket2.pong(data, !websocket2._isServer, NOOP); 2970 websocket2.emit("ping", data); 2971} 2972function receiverOnPong(data) { 2973 this[kWebSocket$1].emit("pong", data); 2974} 2975function resume(stream2) { 2976 stream2.resume(); 2977} 2978function socketOnClose() { 2979 const websocket2 = this[kWebSocket$1]; 2980 this.removeListener("close", socketOnClose); 2981 this.removeListener("data", socketOnData); 2982 this.removeListener("end", socketOnEnd); 2983 websocket2._readyState = WebSocket$1.CLOSING; 2984 let chunk; 2985 if (!this._readableState.endEmitted && !websocket2._closeFrameReceived && !websocket2._receiver._writableState.errorEmitted && (chunk = websocket2._socket.read()) !== null) { 2986 websocket2._receiver.write(chunk); 2987 } 2988 websocket2._receiver.end(); 2989 this[kWebSocket$1] = void 0; 2990 clearTimeout(websocket2._closeTimer); 2991 if (websocket2._receiver._writableState.finished || websocket2._receiver._writableState.errorEmitted) { 2992 websocket2.emitClose(); 2993 } else { 2994 websocket2._receiver.on("error", receiverOnFinish); 2995 websocket2._receiver.on("finish", receiverOnFinish); 2996 } 2997} 2998function socketOnData(chunk) { 2999 if (!this[kWebSocket$1]._receiver.write(chunk)) { 3000 this.pause(); 3001 } 3002} 3003function socketOnEnd() { 3004 const websocket2 = this[kWebSocket$1]; 3005 websocket2._readyState = WebSocket$1.CLOSING; 3006 websocket2._receiver.end(); 3007 this.end(); 3008} 3009function socketOnError$1() { 3010 const websocket2 = this[kWebSocket$1]; 3011 this.removeListener("error", socketOnError$1); 3012 this.on("error", NOOP); 3013 if (websocket2) { 3014 websocket2._readyState = WebSocket$1.CLOSING; 3015 this.destroy(); 3016 } 3017} 3018const WebSocket$2 = /* @__PURE__ */ getDefaultExportFromCjs(websocket); 3019const { tokenChars } = validationExports; 3020function parse(header) { 3021 const protocols = /* @__PURE__ */ new Set(); 3022 let start = -1; 3023 let end = -1; 3024 let i = 0; 3025 for (i; i < header.length; i++) { 3026 const code = header.charCodeAt(i); 3027 if (end === -1 && tokenChars[code] === 1) { 3028 if (start === -1) 3029 start = i; 3030 } else if (i !== 0 && (code === 32 || code === 9)) { 3031 if (end === -1 && start !== -1) 3032 end = i; 3033 } else if (code === 44) { 3034 if (start === -1) { 3035 throw new SyntaxError(`Unexpected character at index ${i}`); 3036 } 3037 if (end === -1) 3038 end = i; 3039 const protocol2 = header.slice(start, end); 3040 if (protocols.has(protocol2)) { 3041 throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); 3042 } 3043 protocols.add(protocol2); 3044 start = end = -1; 3045 } else { 3046 throw new SyntaxError(`Unexpected character at index ${i}`); 3047 } 3048 } 3049 if (start === -1 || end !== -1) { 3050 throw new SyntaxError("Unexpected end of input"); 3051 } 3052 const protocol = header.slice(start, i); 3053 if (protocols.has(protocol)) { 3054 throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); 3055 } 3056 protocols.add(protocol); 3057 return protocols; 3058} 3059var subprotocol$1 = { parse }; 3060const EventEmitter = require$$5; 3061const http = require$$5; 3062const { createHash } = require$$5; 3063const extension = extension$1; 3064const PerMessageDeflate2 = permessageDeflate; 3065const subprotocol = subprotocol$1; 3066const WebSocket2 = websocket; 3067const { GUID, kWebSocket } = constants; 3068const keyRegex = /^[+/0-9A-Za-z]{22}==$/; 3069const RUNNING = 0; 3070const CLOSING = 1; 3071const CLOSED = 2; 3072class WebSocketServer extends EventEmitter { 3073 /** 3074 * Create a `WebSocketServer` instance. 3075 * 3076 * @param {Object} options Configuration options 3077 * @param {Number} [options.backlog=511] The maximum length of the queue of 3078 * pending connections 3079 * @param {Boolean} [options.clientTracking=true] Specifies whether or not to 3080 * track clients 3081 * @param {Function} [options.handleProtocols] A hook to handle protocols 3082 * @param {String} [options.host] The hostname where to bind the server 3083 * @param {Number} [options.maxPayload=104857600] The maximum allowed message 3084 * size 3085 * @param {Boolean} [options.noServer=false] Enable no server mode 3086 * @param {String} [options.path] Accept only connections matching this path 3087 * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable 3088 * permessage-deflate 3089 * @param {Number} [options.port] The port where to bind the server 3090 * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S 3091 * server to use 3092 * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or 3093 * not to skip UTF-8 validation for text and close messages 3094 * @param {Function} [options.verifyClient] A hook to reject connections 3095 * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` 3096 * class to use. It must be the `WebSocket` class or class that extends it 3097 * @param {Function} [callback] A listener for the `listening` event 3098 */ 3099 constructor(options, callback) { 3100 super(); 3101 options = { 3102 maxPayload: 100 * 1024 * 1024, 3103 skipUTF8Validation: false, 3104 perMessageDeflate: false, 3105 handleProtocols: null, 3106 clientTracking: true, 3107 verifyClient: null, 3108 noServer: false, 3109 backlog: null, 3110 // use default (511 as implemented in net.js) 3111 server: null, 3112 host: null, 3113 path: null, 3114 port: null, 3115 WebSocket: WebSocket2, 3116 ...options 3117 }; 3118 if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { 3119 throw new TypeError( 3120 'One and only one of the "port", "server", or "noServer" options must be specified' 3121 ); 3122 } 3123 if (options.port != null) { 3124 this._server = http.createServer((req, res) => { 3125 const body = http.STATUS_CODES[426]; 3126 res.writeHead(426, { 3127 "Content-Length": body.length, 3128 "Content-Type": "text/plain" 3129 }); 3130 res.end(body); 3131 }); 3132 this._server.listen( 3133 options.port, 3134 options.host, 3135 options.backlog, 3136 callback 3137 ); 3138 } else if (options.server) { 3139 this._server = options.server; 3140 } 3141 if (this._server) { 3142 const emitConnection = this.emit.bind(this, "connection"); 3143 this._removeListeners = addListeners(this._server, { 3144 listening: this.emit.bind(this, "listening"), 3145 error: this.emit.bind(this, "error"), 3146 upgrade: (req, socket, head) => { 3147 this.handleUpgrade(req, socket, head, emitConnection); 3148 } 3149 }); 3150 } 3151 if (options.perMessageDeflate === true) 3152 options.perMessageDeflate = {}; 3153 if (options.clientTracking) { 3154 this.clients = /* @__PURE__ */ new Set(); 3155 this._shouldEmitClose = false; 3156 } 3157 this.options = options; 3158 this._state = RUNNING; 3159 } 3160 /** 3161 * Returns the bound address, the address family name, and port of the server 3162 * as reported by the operating system if listening on an IP socket. 3163 * If the server is listening on a pipe or UNIX domain socket, the name is 3164 * returned as a string. 3165 * 3166 * @return {(Object|String|null)} The address of the server 3167 * @public 3168 */ 3169 address() { 3170 if (this.options.noServer) { 3171 throw new Error('The server is operating in "noServer" mode'); 3172 } 3173 if (!this._server) 3174 return null; 3175 return this._server.address(); 3176 } 3177 /** 3178 * Stop the server from accepting new connections and emit the `'close'` event 3179 * when all existing connections are closed. 3180 * 3181 * @param {Function} [cb] A one-time listener for the `'close'` event 3182 * @public 3183 */ 3184 close(cb) { 3185 if (this._state === CLOSED) { 3186 if (cb) { 3187 this.once("close", () => { 3188 cb(new Error("The server is not running")); 3189 }); 3190 } 3191 process.nextTick(emitClose, this); 3192 return; 3193 } 3194 if (cb) 3195 this.once("close", cb); 3196 if (this._state === CLOSING) 3197 return; 3198 this._state = CLOSING; 3199 if (this.options.noServer || this.options.server) { 3200 if (this._server) { 3201 this._removeListeners(); 3202 this._removeListeners = this._server = null; 3203 } 3204 if (this.clients) { 3205 if (!this.clients.size) { 3206 process.nextTick(emitClose, this); 3207 } else { 3208 this._shouldEmitClose = true; 3209 } 3210 } else { 3211 process.nextTick(emitClose, this); 3212 } 3213 } else { 3214 const server = this._server; 3215 this._removeListeners(); 3216 this._removeListeners = this._server = null; 3217 server.close(() => { 3218 emitClose(this); 3219 }); 3220 } 3221 } 3222 /**
3223 * See if a given request should be handled by this server instance. 3224 * 3225 * @param {http.IncomingMessage} req Request object to inspect 3226 * @return {Boolean} `true` if the request is valid, else `false` 3227 * @public 3228 */ 3229 shouldHandle(req) { 3230 if (this.options.path) { 3231 const index = req.url.indexOf("?"); 3232 const pathname = index !== -1 ? req.url.slice(0, index) : req.url; 3233 if (pathname !== this.options.path) 3234 return false; 3235 } 3236 return true; 3237 } 3238 /** 3239 * Handle a HTTP Upgrade request. 3240 * 3241 * @param {http.IncomingMessage} req The request object 3242 * @param {(net.Socket|tls.Socket)} socket The network socket between the 3243 * server and client 3244 * @param {Buffer} head The first packet of the upgraded stream 3245 * @param {Function} cb Callback 3246 * @public 3247 */ 3248 handleUpgrade(req, socket, head, cb) { 3249 socket.on("error", socketOnError); 3250 const key = req.headers["sec-websocket-key"]; 3251 const version = +req.headers["sec-websocket-version"]; 3252 if (req.method !== "GET") { 3253 const message = "Invalid HTTP method"; 3254 abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); 3255 return; 3256 } 3257 if (req.headers.upgrade.toLowerCase() !== "websocket") { 3258 const message = "Invalid Upgrade header"; 3259 abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); 3260 return; 3261 } 3262 if (!key || !keyRegex.test(key)) { 3263 const message = "Missing or invalid Sec-WebSocket-Key header"; 3264 abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); 3265 return; 3266 } 3267 if (version !== 8 && version !== 13) { 3268 const message = "Missing or invalid Sec-WebSocket-Version header"; 3269 abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); 3270 return; 3271 } 3272 if (!this.shouldHandle(req)) { 3273 abortHandshake(socket, 400); 3274 return; 3275 } 3276 const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; 3277 let protocols = /* @__PURE__ */ new Set(); 3278 if (secWebSocketProtocol !== void 0) { 3279 try { 3280 protocols = subprotocol.parse(secWebSocketProtocol); 3281 } catch (err) { 3282 const message = "Invalid Sec-WebSocket-Protocol header"; 3283 abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); 3284 return; 3285 } 3286 } 3287 const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; 3288 const extensions = {}; 3289 if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) { 3290 const perMessageDeflate = new PerMessageDeflate2( 3291 this.options.perMessageDeflate, 3292 true, 3293 this.options.maxPayload 3294 );
vendor: 5,357 bytes, lines 3295-3444
3295 try { 3296 const offers = extension.parse(secWebSocketExtensions); 3297 if (offers[PerMessageDeflate2.extensionName]) { 3298 perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]); 3299 extensions[PerMessageDeflate2.extensionName] = perMessageDeflate; 3300 } 3301 } catch (err) { 3302 const message = "Invalid or unacceptable Sec-WebSocket-Extensions header"; 3303 abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); 3304 return; 3305 } 3306 } 3307 if (this.options.verifyClient) { 3308 const info = { 3309 origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`], 3310 secure: !!(req.socket.authorized || req.socket.encrypted), 3311 req 3312 }; 3313 if (this.options.verifyClient.length === 2) { 3314 this.options.verifyClient(info, (verified, code, message, headers) => { 3315 if (!verified) { 3316 return abortHandshake(socket, code || 401, message, headers); 3317 } 3318 this.completeUpgrade( 3319 extensions, 3320 key, 3321 protocols, 3322 req, 3323 socket, 3324 head, 3325 cb 3326 ); 3327 }); 3328 return; 3329 } 3330 if (!this.options.verifyClient(info)) 3331 return abortHandshake(socket, 401); 3332 } 3333 this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); 3334 } 3335 /** 3336 * Upgrade the connection to WebSocket. 3337 * 3338 * @param {Object} extensions The accepted extensions 3339 * @param {String} key The value of the `Sec-WebSocket-Key` header 3340 * @param {Set} protocols The subprotocols 3341 * @param {http.IncomingMessage} req The request object 3342 * @param {(net.Socket|tls.Socket)} socket The network socket between the 3343 * server and client 3344 * @param {Buffer} head The first packet of the upgraded stream 3345 * @param {Function} cb Callback 3346 * @throws {Error} If called more than once with the same socket 3347 * @private 3348 */ 3349 completeUpgrade(extensions, key, protocols, req, socket, head, cb) { 3350 if (!socket.readable || !socket.writable) 3351 return socket.destroy(); 3352 if (socket[kWebSocket]) { 3353 throw new Error( 3354 "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration" 3355 ); 3356 } 3357 if (this._state > RUNNING) 3358 return abortHandshake(socket, 503); 3359 const digest = createHash("sha1").update(key + GUID).digest("base64"); 3360 const headers = [ 3361 "HTTP/1.1 101 Switching Protocols", 3362 "Upgrade: websocket", 3363 "Connection: Upgrade", 3364 `Sec-WebSocket-Accept: ${digest}` 3365 ]; 3366 const ws = new this.options.WebSocket(null); 3367 if (protocols.size) { 3368 const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; 3369 if (protocol) { 3370 headers.push(`Sec-WebSocket-Protocol: ${protocol}`); 3371 ws._protocol = protocol; 3372 } 3373 } 3374 if (extensions[PerMessageDeflate2.extensionName]) { 3375 const params = extensions[PerMessageDeflate2.extensionName].params; 3376 const value = extension.format({ 3377 [PerMessageDeflate2.extensionName]: [params] 3378 }); 3379 headers.push(`Sec-WebSocket-Extensions: ${value}`); 3380 ws._extensions = extensions; 3381 } 3382 this.emit("headers", headers, req); 3383 socket.write(headers.concat("\r\n").join("\r\n")); 3384 socket.removeListener("error", socketOnError); 3385 ws.setSocket(socket, head, { 3386 maxPayload: this.options.maxPayload, 3387 skipUTF8Validation: this.options.skipUTF8Validation 3388 }); 3389 if (this.clients) { 3390 this.clients.add(ws); 3391 ws.on("close", () => { 3392 this.clients.delete(ws); 3393 if (this._shouldEmitClose && !this.clients.size) { 3394 process.nextTick(emitClose, this); 3395 } 3396 }); 3397 } 3398 cb(ws, req); 3399 } 3400} 3401var websocketServer = WebSocketServer; 3402function addListeners(server, map) { 3403 for (const event of Object.keys(map)) 3404 server.on(event, map[event]); 3405 return function removeListeners() { 3406 for (const event of Object.keys(map)) { 3407 server.removeListener(event, map[event]); 3408 } 3409 }; 3410} 3411function emitClose(server) { 3412 server._state = CLOSED; 3413 server.emit("close"); 3414} 3415function socketOnError() { 3416 this.destroy(); 3417} 3418function abortHandshake(socket, code, message, headers) { 3419 message = message || http.STATUS_CODES[code]; 3420 headers = { 3421 Connection: "close", 3422 "Content-Type": "text/html", 3423 "Content-Length": Buffer.byteLength(message), 3424 ...headers 3425 }; 3426 socket.once("finish", socket.destroy); 3427 socket.end( 3428 `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r 3429` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message 3430 ); 3431} 3432function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { 3433 if (server.listenerCount("wsClientError")) { 3434 const err = new Error(message); 3435 Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); 3436 server.emit("wsClientError", err, socket, req); 3437 } else { 3438 abortHandshake(socket, code, message); 3439 } 3440} 3441const websocketServer$1 = /* @__PURE__ */ getDefaultExportFromCjs(websocketServer); 3442 3443export { receiver$1 as Receiver, sender$1 as Sender, WebSocket$2 as WebSocket, websocketServer$1 as WebSocketServer, stream$1 as createWebSocketStream, WebSocket$2 as default }; 3444//# sourceMappingURL=wrapper-6f348d45-eeeb8bd1.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.