crossws 0.2.4 → 0.3.1

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