crossws 0.4.2 → 0.4.4

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