pinokiod 1.2.38 → 1.2.39

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