@gradio/client 0.0.1 → 0.1.0

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