@unionschool/easy-agents 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1471 @@
1
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */
2
+
3
+ 'use strict';
4
+
5
+ const EventEmitter = require('events');
6
+ const https = require('https');
7
+ const http = require('http');
8
+ const net = require('net');
9
+ const querystring = require('querystring');
10
+ const tls = require('tls');
11
+ const { randomBytes, createHash } = require('crypto');
12
+ const { Duplex, Readable } = require('stream');
13
+ const { URL } = require('url');
14
+
15
+ const PerMessageDeflate = require('./permessage-deflate');
16
+ const Receiver = require('./receiver');
17
+ const Sender = require('./sender');
18
+ const { isBlob } = require('./validation');
19
+
20
+ const {
21
+ BINARY_TYPES,
22
+ CLOSE_TIMEOUT,
23
+ EMPTY_BUFFER,
24
+ GUID,
25
+ kForOnEventAttribute,
26
+ kListener,
27
+ kStatusCode,
28
+ kWebSocket,
29
+ NOOP
30
+ } = require('./constants');
31
+ const {
32
+ EventTarget: { addEventListener, removeEventListener }
33
+ } = require('./event-target');
34
+ const { format, parse } = require('./extension');
35
+ const { toBuffer } = require('./buffer-util');
36
+
37
+ const kAborted = Symbol('kAborted');
38
+ const protocolVersions = [8, 13];
39
+ const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
40
+ const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
41
+
42
+ /**
43
+ * Class representing a WebSocket.
44
+ *
45
+ * @extends EventEmitter
46
+ */
47
+ class WebSocket extends EventEmitter {
48
+ /**
49
+ * Create a new `WebSocket`.
50
+ *
51
+ * @param {(String|URL)} address The URL to which to connect
52
+ * @param {(String|String[])} [protocols] The subprotocols
53
+ * @param {Object} [options] Connection options
54
+ */
55
+ constructor(address, protocols, options) {
56
+ super();
57
+
58
+ this._binaryType = BINARY_TYPES[0];
59
+ this._closeCode = 1006;
60
+ this._closeFrameReceived = false;
61
+ this._closeFrameSent = false;
62
+ this._closeMessage = EMPTY_BUFFER;
63
+ this._closeTimer = null;
64
+ this._errorEmitted = false;
65
+ this._extensions = {};
66
+ this._paused = false;
67
+ this._protocol = '';
68
+ this._readyState = WebSocket.CONNECTING;
69
+ this._receiver = null;
70
+ this._sender = null;
71
+ this._socket = null;
72
+
73
+ if (address !== null) {
74
+ this._bufferedAmount = 0;
75
+ this._isServer = false;
76
+ this._redirects = 0;
77
+
78
+ if (protocols === undefined) {
79
+ if (!options || options.protocols === undefined) {
80
+ protocols = [];
81
+ } else if (Array.isArray(options.protocols)) {
82
+ protocols = options.protocols;
83
+ } else {
84
+ protocols = [options.protocols];
85
+ }
86
+ } else if (!Array.isArray(protocols)) {
87
+ if (typeof protocols === 'object' && protocols !== null) {
88
+ options = protocols;
89
+
90
+ if (options.protocols === undefined) {
91
+ protocols = [];
92
+ } else if (Array.isArray(options.protocols)) {
93
+ protocols = options.protocols;
94
+ } else {
95
+ protocols = [options.protocols];
96
+ }
97
+ } else {
98
+ protocols = [protocols];
99
+ }
100
+ }
101
+
102
+ options = initAsClient(this, address, protocols, options);
103
+ } else {
104
+ this._isServer = true;
105
+ }
106
+
107
+ if (options.autoPong) {
108
+ this._autoPong = true;
109
+ this._autoPongComplete = () => autoPongComplete(this);
110
+ this._pendingAutoPongs = 0;
111
+ this._maxPendingAutoPongs = options.maxPendingAutoPongs | 0;
112
+ }
113
+
114
+ this._closeTimeout = options.closeTimeout;
115
+ }
116
+
117
+ /**
118
+ * For historical reasons, the custom "nodebuffer" type is used by the default
119
+ * instead of "blob".
120
+ *
121
+ * @type {String}
122
+ */
123
+ get binaryType() {
124
+ return this._binaryType;
125
+ }
126
+
127
+ set binaryType(type) {
128
+ if (!BINARY_TYPES.includes(type)) return;
129
+
130
+ this._binaryType = type;
131
+
132
+ //
133
+ // Allow to change `binaryType` on the fly.
134
+ //
135
+ if (this._receiver) this._receiver._binaryType = type;
136
+ }
137
+
138
+ /**
139
+ * @type {Number}
140
+ */
141
+ get bufferedAmount() {
142
+ if (!this._socket) return this._bufferedAmount;
143
+
144
+ return this._socket._writableState.length + this._sender._bufferedBytes;
145
+ }
146
+
147
+ /**
148
+ * @type {String}
149
+ */
150
+ get extensions() {
151
+ return Object.keys(this._extensions).join();
152
+ }
153
+
154
+ /**
155
+ * @type {Boolean}
156
+ */
157
+ get isPaused() {
158
+ return this._paused;
159
+ }
160
+
161
+ /**
162
+ * @type {Function}
163
+ */
164
+ /* istanbul ignore next */
165
+ get onclose() {
166
+ return null;
167
+ }
168
+
169
+ /**
170
+ * @type {Function}
171
+ */
172
+ /* istanbul ignore next */
173
+ get onerror() {
174
+ return null;
175
+ }
176
+
177
+ /**
178
+ * @type {Function}
179
+ */
180
+ /* istanbul ignore next */
181
+ get onopen() {
182
+ return null;
183
+ }
184
+
185
+ /**
186
+ * @type {Function}
187
+ */
188
+ /* istanbul ignore next */
189
+ get onmessage() {
190
+ return null;
191
+ }
192
+
193
+ /**
194
+ * @type {String}
195
+ */
196
+ get protocol() {
197
+ return this._protocol;
198
+ }
199
+
200
+ /**
201
+ * @type {Number}
202
+ */
203
+ get readyState() {
204
+ return this._readyState;
205
+ }
206
+
207
+ /**
208
+ * @type {String}
209
+ */
210
+ get url() {
211
+ return this._url;
212
+ }
213
+
214
+ /**
215
+ * Set up the socket and the internal resources.
216
+ *
217
+ * @param {Duplex} socket The network socket between the server and client
218
+ * @param {Buffer} head The first packet of the upgraded stream
219
+ * @param {Object} options Options object
220
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
221
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
222
+ * multiple times in the same tick
223
+ * @param {Function} [options.generateMask] The function used to generate the
224
+ * masking key
225
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
226
+ * buffered data chunks
227
+ * @param {Number} [options.maxFragments=0] The maximum number of message
228
+ * fragments
229
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
230
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
231
+ * not to skip UTF-8 validation for text and close messages
232
+ * @private
233
+ */
234
+ setSocket(socket, head, options) {
235
+ const receiver = new Receiver({
236
+ allowSynchronousEvents: options.allowSynchronousEvents,
237
+ binaryType: this.binaryType,
238
+ extensions: this._extensions,
239
+ isServer: this._isServer,
240
+ maxBufferedChunks: options.maxBufferedChunks,
241
+ maxFragments: options.maxFragments,
242
+ maxPayload: options.maxPayload,
243
+ skipUTF8Validation: options.skipUTF8Validation
244
+ });
245
+
246
+ const sender = new Sender(socket, this._extensions, options.generateMask);
247
+
248
+ this._receiver = receiver;
249
+ this._sender = sender;
250
+ this._socket = socket;
251
+
252
+ receiver[kWebSocket] = this;
253
+ sender[kWebSocket] = this;
254
+ socket[kWebSocket] = this;
255
+
256
+ receiver.on('conclude', receiverOnConclude);
257
+ receiver.on('drain', receiverOnDrain);
258
+ receiver.on('error', receiverOnError);
259
+ receiver.on('message', receiverOnMessage);
260
+ receiver.on('ping', receiverOnPing);
261
+ receiver.on('pong', receiverOnPong);
262
+
263
+ sender.onerror = senderOnError;
264
+
265
+ //
266
+ // These methods may not be available if `socket` is just a `Duplex`.
267
+ //
268
+ if (socket.setTimeout) socket.setTimeout(0);
269
+ if (socket.setNoDelay) socket.setNoDelay();
270
+
271
+ if (head.length > 0) socket.unshift(head);
272
+
273
+ socket.on('close', socketOnClose);
274
+ socket.on('data', socketOnData);
275
+ socket.on('end', socketOnEnd);
276
+ socket.on('error', socketOnError);
277
+
278
+ this._readyState = WebSocket.OPEN;
279
+ this.emit('open');
280
+ }
281
+
282
+ /**
283
+ * Emit the `'close'` event.
284
+ *
285
+ * @private
286
+ */
287
+ emitClose() {
288
+ if (!this._socket) {
289
+ this._readyState = WebSocket.CLOSED;
290
+ this.emit('close', this._closeCode, this._closeMessage);
291
+ return;
292
+ }
293
+
294
+ if (this._extensions[PerMessageDeflate.extensionName]) {
295
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
296
+ }
297
+
298
+ this._receiver.removeAllListeners();
299
+ this._readyState = WebSocket.CLOSED;
300
+ this.emit('close', this._closeCode, this._closeMessage);
301
+ }
302
+
303
+ /**
304
+ * Start a closing handshake.
305
+ *
306
+ * +----------+ +-----------+ +----------+
307
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
308
+ * | +----------+ +-----------+ +----------+ |
309
+ * +----------+ +-----------+ |
310
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
311
+ * +----------+ +-----------+ |
312
+ * | | | +---+ |
313
+ * +------------------------+-->|fin| - - - -
314
+ * | +---+ | +---+
315
+ * - - - - -|fin|<---------------------+
316
+ * +---+
317
+ *
318
+ * @param {Number} [code] Status code explaining why the connection is closing
319
+ * @param {(String|Buffer)} [data] The reason why the connection is
320
+ * closing
321
+ * @public
322
+ */
323
+ close(code, data) {
324
+ if (this.readyState === WebSocket.CLOSED) return;
325
+ if (this.readyState === WebSocket.CONNECTING) {
326
+ const msg = 'WebSocket was closed before the connection was established';
327
+ abortHandshake(this, this._req, msg);
328
+ return;
329
+ }
330
+
331
+ if (this.readyState === WebSocket.CLOSING) {
332
+ if (
333
+ this._closeFrameSent &&
334
+ (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
335
+ ) {
336
+ this._socket.end();
337
+ }
338
+
339
+ return;
340
+ }
341
+
342
+ this._sender.close(code, data, !this._isServer, (err) => {
343
+ //
344
+ // This error is handled by the `'error'` listener on the socket. We only
345
+ // want to know if the close frame has been sent here.
346
+ //
347
+ if (err) return;
348
+
349
+ this._closeFrameSent = true;
350
+
351
+ if (
352
+ this._closeFrameReceived ||
353
+ this._receiver._writableState.errorEmitted
354
+ ) {
355
+ this._socket.end();
356
+ }
357
+ });
358
+
359
+ this._readyState = WebSocket.CLOSING;
360
+ setCloseTimer(this);
361
+ }
362
+
363
+ /**
364
+ * Pause the socket.
365
+ *
366
+ * @public
367
+ */
368
+ pause() {
369
+ if (
370
+ this.readyState === WebSocket.CONNECTING ||
371
+ this.readyState === WebSocket.CLOSED
372
+ ) {
373
+ return;
374
+ }
375
+
376
+ this._paused = true;
377
+ this._socket.pause();
378
+ }
379
+
380
+ /**
381
+ * Send a ping.
382
+ *
383
+ * @param {*} [data] The data to send
384
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
385
+ * @param {Function} [cb] Callback which is executed when the ping is sent
386
+ * @public
387
+ */
388
+ ping(data, mask, cb) {
389
+ if (this.readyState === WebSocket.CONNECTING) {
390
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
391
+ }
392
+
393
+ if (typeof data === 'function') {
394
+ cb = data;
395
+ data = mask = undefined;
396
+ } else if (typeof mask === 'function') {
397
+ cb = mask;
398
+ mask = undefined;
399
+ }
400
+
401
+ if (typeof data === 'number') data = data.toString();
402
+
403
+ if (this.readyState !== WebSocket.OPEN) {
404
+ sendAfterClose(this, data, cb);
405
+ return;
406
+ }
407
+
408
+ if (mask === undefined) mask = !this._isServer;
409
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
410
+ }
411
+
412
+ /**
413
+ * Send a pong.
414
+ *
415
+ * @param {*} [data] The data to send
416
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
417
+ * @param {Function} [cb] Callback which is executed when the pong is sent
418
+ * @public
419
+ */
420
+ pong(data, mask, cb) {
421
+ if (this.readyState === WebSocket.CONNECTING) {
422
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
423
+ }
424
+
425
+ if (typeof data === 'function') {
426
+ cb = data;
427
+ data = mask = undefined;
428
+ } else if (typeof mask === 'function') {
429
+ cb = mask;
430
+ mask = undefined;
431
+ }
432
+
433
+ if (typeof data === 'number') data = data.toString();
434
+
435
+ if (this.readyState !== WebSocket.OPEN) {
436
+ sendAfterClose(this, data, cb);
437
+ return;
438
+ }
439
+
440
+ if (mask === undefined) mask = !this._isServer;
441
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
442
+ }
443
+
444
+ /**
445
+ * Resume the socket.
446
+ *
447
+ * @public
448
+ */
449
+ resume() {
450
+ if (
451
+ this.readyState === WebSocket.CONNECTING ||
452
+ this.readyState === WebSocket.CLOSED
453
+ ) {
454
+ return;
455
+ }
456
+
457
+ this._paused = false;
458
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
459
+ }
460
+
461
+ /**
462
+ * Send a data message.
463
+ *
464
+ * @param {*} data The message to send
465
+ * @param {Object} [options] Options object
466
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
467
+ * text
468
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
469
+ * `data`
470
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
471
+ * last one
472
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
473
+ * @param {Function} [cb] Callback which is executed when data is written out
474
+ * @public
475
+ */
476
+ send(data, options, cb) {
477
+ if (this.readyState === WebSocket.CONNECTING) {
478
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
479
+ }
480
+
481
+ if (typeof options === 'function') {
482
+ cb = options;
483
+ options = {};
484
+ }
485
+
486
+ if (typeof data === 'number') data = data.toString();
487
+
488
+ if (this.readyState !== WebSocket.OPEN) {
489
+ sendAfterClose(this, data, cb);
490
+ return;
491
+ }
492
+
493
+ const opts = {
494
+ binary: typeof data !== 'string',
495
+ mask: !this._isServer,
496
+ compress: true,
497
+ fin: true,
498
+ ...options
499
+ };
500
+
501
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
502
+ opts.compress = false;
503
+ }
504
+
505
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
506
+ }
507
+
508
+ /**
509
+ * Forcibly close the connection.
510
+ *
511
+ * @public
512
+ */
513
+ terminate() {
514
+ if (this.readyState === WebSocket.CLOSED) return;
515
+ if (this.readyState === WebSocket.CONNECTING) {
516
+ const msg = 'WebSocket was closed before the connection was established';
517
+ abortHandshake(this, this._req, msg);
518
+ return;
519
+ }
520
+
521
+ if (this._socket) {
522
+ this._readyState = WebSocket.CLOSING;
523
+ this._socket.destroy();
524
+ }
525
+ }
526
+ }
527
+
528
+ /**
529
+ * @constant {Number} CONNECTING
530
+ * @memberof WebSocket
531
+ */
532
+ Object.defineProperty(WebSocket, 'CONNECTING', {
533
+ enumerable: true,
534
+ value: readyStates.indexOf('CONNECTING')
535
+ });
536
+
537
+ /**
538
+ * @constant {Number} CONNECTING
539
+ * @memberof WebSocket.prototype
540
+ */
541
+ Object.defineProperty(WebSocket.prototype, 'CONNECTING', {
542
+ enumerable: true,
543
+ value: readyStates.indexOf('CONNECTING')
544
+ });
545
+
546
+ /**
547
+ * @constant {Number} OPEN
548
+ * @memberof WebSocket
549
+ */
550
+ Object.defineProperty(WebSocket, 'OPEN', {
551
+ enumerable: true,
552
+ value: readyStates.indexOf('OPEN')
553
+ });
554
+
555
+ /**
556
+ * @constant {Number} OPEN
557
+ * @memberof WebSocket.prototype
558
+ */
559
+ Object.defineProperty(WebSocket.prototype, 'OPEN', {
560
+ enumerable: true,
561
+ value: readyStates.indexOf('OPEN')
562
+ });
563
+
564
+ /**
565
+ * @constant {Number} CLOSING
566
+ * @memberof WebSocket
567
+ */
568
+ Object.defineProperty(WebSocket, 'CLOSING', {
569
+ enumerable: true,
570
+ value: readyStates.indexOf('CLOSING')
571
+ });
572
+
573
+ /**
574
+ * @constant {Number} CLOSING
575
+ * @memberof WebSocket.prototype
576
+ */
577
+ Object.defineProperty(WebSocket.prototype, 'CLOSING', {
578
+ enumerable: true,
579
+ value: readyStates.indexOf('CLOSING')
580
+ });
581
+
582
+ /**
583
+ * @constant {Number} CLOSED
584
+ * @memberof WebSocket
585
+ */
586
+ Object.defineProperty(WebSocket, 'CLOSED', {
587
+ enumerable: true,
588
+ value: readyStates.indexOf('CLOSED')
589
+ });
590
+
591
+ /**
592
+ * @constant {Number} CLOSED
593
+ * @memberof WebSocket.prototype
594
+ */
595
+ Object.defineProperty(WebSocket.prototype, 'CLOSED', {
596
+ enumerable: true,
597
+ value: readyStates.indexOf('CLOSED')
598
+ });
599
+
600
+ [
601
+ 'binaryType',
602
+ 'bufferedAmount',
603
+ 'extensions',
604
+ 'isPaused',
605
+ 'protocol',
606
+ 'readyState',
607
+ 'url'
608
+ ].forEach((property) => {
609
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
610
+ });
611
+
612
+ //
613
+ // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
614
+ // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
615
+ //
616
+ ['open', 'error', 'close', 'message'].forEach((method) => {
617
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
618
+ enumerable: true,
619
+ get() {
620
+ for (const listener of this.listeners(method)) {
621
+ if (listener[kForOnEventAttribute]) return listener[kListener];
622
+ }
623
+
624
+ return null;
625
+ },
626
+ set(handler) {
627
+ for (const listener of this.listeners(method)) {
628
+ if (listener[kForOnEventAttribute]) {
629
+ this.removeListener(method, listener);
630
+ break;
631
+ }
632
+ }
633
+
634
+ if (typeof handler !== 'function') return;
635
+
636
+ this.addEventListener(method, handler, {
637
+ [kForOnEventAttribute]: true
638
+ });
639
+ }
640
+ });
641
+ });
642
+
643
+ WebSocket.prototype.addEventListener = addEventListener;
644
+ WebSocket.prototype.removeEventListener = removeEventListener;
645
+
646
+ module.exports = WebSocket;
647
+
648
+ /**
649
+ * Initialize a WebSocket client.
650
+ *
651
+ * @param {WebSocket} websocket The client to initialize
652
+ * @param {(String|URL)} address The URL to which to connect
653
+ * @param {Array} protocols The subprotocols
654
+ * @param {Object} [options] Connection options
655
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
656
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
657
+ * times in the same tick
658
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
659
+ * automatically send a pong in response to a ping
660
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
661
+ * for the closing handshake to finish after `websocket.close()` is called
662
+ * @param {Function} [options.finishRequest] A function which can be used to
663
+ * customize the headers of each http request before it is sent
664
+ * @param {Boolean} [options.followRedirects=false] Whether or not to follow
665
+ * redirects
666
+ * @param {Function} [options.generateMask] The function used to generate the
667
+ * masking key
668
+ * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
669
+ * handshake request
670
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
671
+ * buffered data chunks
672
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
673
+ * fragments
674
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
675
+ * size
676
+ * @param {Number} [options.maxPendingAutoPongs=60] The maximum number of
677
+ * pending automatic pongs
678
+ * @param {Number} [options.maxRedirects=10] The maximum number of redirects
679
+ * allowed
680
+ * @param {String} [options.origin] Value of the `Origin` or
681
+ * `Sec-WebSocket-Origin` header
682
+ * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
683
+ * permessage-deflate
684
+ * @param {Number} [options.protocolVersion=13] Value of the
685
+ * `Sec-WebSocket-Version` header
686
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
687
+ * not to skip UTF-8 validation for text and close messages
688
+ * @return {Object} The resolved options object used for initialization
689
+ * @private
690
+ */
691
+ function initAsClient(websocket, address, protocols, options) {
692
+ const opts = {
693
+ allowSynchronousEvents: true,
694
+ autoPong: true,
695
+ closeTimeout: CLOSE_TIMEOUT,
696
+ protocolVersion: protocolVersions[1],
697
+ maxBufferedChunks: 256 * 1024,
698
+ maxFragments: 16 * 1024,
699
+ maxPayload: 100 * 1024 * 1024,
700
+ maxPendingAutoPongs: 60,
701
+ skipUTF8Validation: false,
702
+ perMessageDeflate: true,
703
+ followRedirects: false,
704
+ maxRedirects: 10,
705
+ ...options,
706
+ socketPath: undefined,
707
+ hostname: undefined,
708
+ protocol: undefined,
709
+ protocols: undefined,
710
+ timeout: undefined,
711
+ method: 'GET',
712
+ host: undefined,
713
+ path: undefined,
714
+ port: undefined
715
+ };
716
+
717
+ if (!protocolVersions.includes(opts.protocolVersion)) {
718
+ throw new RangeError(
719
+ `Unsupported protocol version: ${opts.protocolVersion} ` +
720
+ `(supported versions: ${protocolVersions.join(', ')})`
721
+ );
722
+ }
723
+
724
+ let parsedUrl;
725
+
726
+ if (address instanceof URL) {
727
+ parsedUrl = address;
728
+ } else {
729
+ try {
730
+ parsedUrl = new URL(address);
731
+ } catch {
732
+ throw new SyntaxError(`Invalid URL: ${address}`);
733
+ }
734
+ }
735
+
736
+ if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
737
+ parsedUrl = new URL(parsedUrl);
738
+ parsedUrl.protocol = parsedUrl.protocol === 'http:' ? 'ws:' : 'wss:';
739
+ }
740
+
741
+ websocket._url = parsedUrl.href;
742
+
743
+ const isSecure = parsedUrl.protocol === 'wss:';
744
+ const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
745
+ let invalidUrlMessage;
746
+
747
+ if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
748
+ invalidUrlMessage =
749
+ 'The URL\'s protocol must be one of "ws:", "wss:", ' +
750
+ '"http:", "https:", or "ws+unix:"';
751
+ } else if (isIpcUrl && !parsedUrl.pathname) {
752
+ invalidUrlMessage = "The URL's pathname is empty";
753
+ } else if (parsedUrl.hash) {
754
+ invalidUrlMessage = 'The URL contains a fragment identifier';
755
+ }
756
+
757
+ if (invalidUrlMessage) {
758
+ const err = new SyntaxError(invalidUrlMessage);
759
+
760
+ if (websocket._redirects === 0) {
761
+ throw err;
762
+ } else {
763
+ emitErrorAndClose(websocket, err);
764
+ return;
765
+ }
766
+ }
767
+
768
+ const defaultPort = isSecure ? 443 : 80;
769
+ const key = randomBytes(16).toString('base64');
770
+ const request = isSecure ? https.request : http.request;
771
+ const protocolSet = new Set();
772
+ let perMessageDeflate;
773
+
774
+ opts.createConnection =
775
+ opts.createConnection || (isSecure ? tlsConnect : netConnect);
776
+ opts.defaultPort = opts.defaultPort || defaultPort;
777
+ opts.port = parsedUrl.port || defaultPort;
778
+ opts.host = parsedUrl.hostname.startsWith('[')
779
+ ? parsedUrl.hostname.slice(1, -1)
780
+ : parsedUrl.hostname;
781
+ opts.headers = {
782
+ ...opts.headers,
783
+ 'Sec-WebSocket-Version': opts.protocolVersion,
784
+ 'Sec-WebSocket-Key': key,
785
+ Connection: 'Upgrade',
786
+ Upgrade: 'websocket'
787
+ };
788
+ opts.path = parsedUrl.pathname + parsedUrl.search;
789
+ opts.timeout = opts.handshakeTimeout;
790
+
791
+ if (opts.perMessageDeflate) {
792
+ perMessageDeflate = new PerMessageDeflate({
793
+ ...opts.perMessageDeflate,
794
+ isServer: false,
795
+ maxPayload: opts.maxPayload
796
+ });
797
+ opts.headers['Sec-WebSocket-Extensions'] = format({
798
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
799
+ });
800
+ }
801
+ if (protocols.length) {
802
+ for (const protocol of protocols) {
803
+ if (
804
+ typeof protocol !== 'string' ||
805
+ !subprotocolRegex.test(protocol) ||
806
+ protocolSet.has(protocol)
807
+ ) {
808
+ throw new SyntaxError(
809
+ 'An invalid or duplicated subprotocol was specified'
810
+ );
811
+ }
812
+
813
+ protocolSet.add(protocol);
814
+ }
815
+
816
+ opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
817
+ }
818
+ if (opts.origin) {
819
+ if (opts.protocolVersion < 13) {
820
+ opts.headers['Sec-WebSocket-Origin'] = opts.origin;
821
+ } else {
822
+ opts.headers.Origin = opts.origin;
823
+ }
824
+ }
825
+ if (parsedUrl.username || parsedUrl.password) {
826
+ const username = querystring.unescape(parsedUrl.username);
827
+ const password = querystring.unescape(parsedUrl.password);
828
+
829
+ opts.auth = `${username}:${password}`;
830
+ }
831
+
832
+ if (isIpcUrl) {
833
+ const i = opts.path.indexOf(':');
834
+
835
+ if (i === -1) {
836
+ opts.socketPath = opts.path;
837
+ opts.path = '';
838
+ } else {
839
+ opts.socketPath = opts.path.slice(0, i);
840
+ opts.path = opts.path.slice(i + 1);
841
+ }
842
+ }
843
+
844
+ let req;
845
+
846
+ if (opts.followRedirects) {
847
+ if (websocket._redirects === 0) {
848
+ websocket._originalIpc = isIpcUrl;
849
+ websocket._originalSecure = isSecure;
850
+ websocket._originalHostOrSocketPath = isIpcUrl
851
+ ? opts.socketPath
852
+ : parsedUrl.host;
853
+
854
+ const headers = options && options.headers;
855
+
856
+ //
857
+ // Shallow copy the user provided options so that headers can be changed
858
+ // without mutating the original object.
859
+ //
860
+ options = { ...options, headers: {} };
861
+
862
+ if (headers) {
863
+ for (const [key, value] of Object.entries(headers)) {
864
+ options.headers[key.toLowerCase()] = value;
865
+ }
866
+ }
867
+ } else if (websocket.listenerCount('redirect') === 0) {
868
+ const isSameHost = isIpcUrl
869
+ ? websocket._originalIpc
870
+ ? opts.socketPath === websocket._originalHostOrSocketPath
871
+ : false
872
+ : websocket._originalIpc
873
+ ? false
874
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
875
+
876
+ if (!isSameHost || (websocket._originalSecure && !isSecure)) {
877
+ //
878
+ // Match curl 7.77.0 behavior and drop the following headers. These
879
+ // headers are also dropped when following a redirect to a subdomain.
880
+ //
881
+ delete opts.headers.authorization;
882
+ delete opts.headers.cookie;
883
+
884
+ if (!isSameHost) delete opts.headers.host;
885
+
886
+ opts.auth = undefined;
887
+ }
888
+ }
889
+
890
+ //
891
+ // Match curl 7.77.0 behavior and make the first `Authorization` header win.
892
+ // If the `Authorization` header is set, then there is nothing to do as it
893
+ // will take precedence.
894
+ //
895
+ if (opts.auth && !options.headers.authorization) {
896
+ options.headers.authorization =
897
+ 'Basic ' + Buffer.from(opts.auth).toString('base64');
898
+ }
899
+
900
+ req = websocket._req = request(opts);
901
+
902
+ if (websocket._redirects) {
903
+ //
904
+ // Unlike what is done for the `'upgrade'` event, no early exit is
905
+ // triggered here if the user calls `websocket.close()` or
906
+ // `websocket.terminate()` from a listener of the `'redirect'` event. This
907
+ // is because the user can also call `request.destroy()` with an error
908
+ // before calling `websocket.close()` or `websocket.terminate()` and this
909
+ // would result in an error being emitted on the `request` object with no
910
+ // `'error'` event listeners attached.
911
+ //
912
+ websocket.emit('redirect', websocket.url, req);
913
+ }
914
+ } else {
915
+ req = websocket._req = request(opts);
916
+ }
917
+
918
+ if (opts.timeout) {
919
+ req.on('timeout', () => {
920
+ abortHandshake(websocket, req, 'Opening handshake has timed out');
921
+ });
922
+ }
923
+
924
+ req.on('error', (err) => {
925
+ if (req === null || req[kAborted]) return;
926
+
927
+ req = websocket._req = null;
928
+ emitErrorAndClose(websocket, err);
929
+ });
930
+
931
+ req.on('response', (res) => {
932
+ const location = res.headers.location;
933
+ const statusCode = res.statusCode;
934
+
935
+ if (
936
+ location &&
937
+ opts.followRedirects &&
938
+ statusCode >= 300 &&
939
+ statusCode < 400
940
+ ) {
941
+ if (++websocket._redirects > opts.maxRedirects) {
942
+ abortHandshake(websocket, req, 'Maximum redirects exceeded');
943
+ return;
944
+ }
945
+
946
+ req.abort();
947
+
948
+ let addr;
949
+
950
+ try {
951
+ addr = new URL(location, address);
952
+ } catch (e) {
953
+ const err = new SyntaxError(`Invalid URL: ${location}`);
954
+ emitErrorAndClose(websocket, err);
955
+ return;
956
+ }
957
+
958
+ initAsClient(websocket, addr, protocols, options);
959
+ } else if (!websocket.emit('unexpected-response', req, res)) {
960
+ abortHandshake(
961
+ websocket,
962
+ req,
963
+ `Unexpected server response: ${res.statusCode}`
964
+ );
965
+ }
966
+ });
967
+
968
+ req.on('upgrade', (res, socket, head) => {
969
+ websocket.emit('upgrade', res);
970
+
971
+ //
972
+ // The user may have closed the connection from a listener of the
973
+ // `'upgrade'` event.
974
+ //
975
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
976
+
977
+ req = websocket._req = null;
978
+
979
+ const upgrade = res.headers.upgrade;
980
+
981
+ if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
982
+ abortHandshake(websocket, socket, 'Invalid Upgrade header');
983
+ return;
984
+ }
985
+
986
+ const digest = createHash('sha1')
987
+ .update(key + GUID)
988
+ .digest('base64');
989
+
990
+ if (res.headers['sec-websocket-accept'] !== digest) {
991
+ abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
992
+ return;
993
+ }
994
+
995
+ const serverProt = res.headers['sec-websocket-protocol'];
996
+ let protError;
997
+
998
+ if (serverProt !== undefined) {
999
+ if (!protocolSet.size) {
1000
+ protError = 'Server sent a subprotocol but none was requested';
1001
+ } else if (!protocolSet.has(serverProt)) {
1002
+ protError = 'Server sent an invalid subprotocol';
1003
+ }
1004
+ } else if (protocolSet.size) {
1005
+ protError = 'Server sent no subprotocol';
1006
+ }
1007
+
1008
+ if (protError) {
1009
+ abortHandshake(websocket, socket, protError);
1010
+ return;
1011
+ }
1012
+
1013
+ if (serverProt) websocket._protocol = serverProt;
1014
+
1015
+ const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
1016
+
1017
+ if (secWebSocketExtensions !== undefined) {
1018
+ if (!perMessageDeflate) {
1019
+ const message =
1020
+ 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
1021
+ 'was requested';
1022
+ abortHandshake(websocket, socket, message);
1023
+ return;
1024
+ }
1025
+
1026
+ let extensions;
1027
+
1028
+ try {
1029
+ extensions = parse(secWebSocketExtensions);
1030
+ } catch (err) {
1031
+ const message = 'Invalid Sec-WebSocket-Extensions header';
1032
+ abortHandshake(websocket, socket, message);
1033
+ return;
1034
+ }
1035
+
1036
+ const extensionNames = Object.keys(extensions);
1037
+
1038
+ if (
1039
+ extensionNames.length !== 1 ||
1040
+ extensionNames[0] !== PerMessageDeflate.extensionName
1041
+ ) {
1042
+ const message = 'Server indicated an extension that was not requested';
1043
+ abortHandshake(websocket, socket, message);
1044
+ return;
1045
+ }
1046
+
1047
+ try {
1048
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
1049
+ } catch (err) {
1050
+ const message = 'Invalid Sec-WebSocket-Extensions header';
1051
+ abortHandshake(websocket, socket, message);
1052
+ return;
1053
+ }
1054
+
1055
+ websocket._extensions[PerMessageDeflate.extensionName] =
1056
+ perMessageDeflate;
1057
+ }
1058
+
1059
+ websocket.setSocket(socket, head, {
1060
+ allowSynchronousEvents: opts.allowSynchronousEvents,
1061
+ generateMask: opts.generateMask,
1062
+ maxBufferedChunks: opts.maxBufferedChunks,
1063
+ maxFragments: opts.maxFragments,
1064
+ maxPayload: opts.maxPayload,
1065
+ skipUTF8Validation: opts.skipUTF8Validation
1066
+ });
1067
+ });
1068
+
1069
+ if (opts.finishRequest) {
1070
+ opts.finishRequest(req, websocket);
1071
+ } else {
1072
+ req.end();
1073
+ }
1074
+
1075
+ return opts;
1076
+ }
1077
+
1078
+ /**
1079
+ * Emit the `'error'` and `'close'` events.
1080
+ *
1081
+ * @param {WebSocket} websocket The WebSocket instance
1082
+ * @param {Error} The error to emit
1083
+ * @private
1084
+ */
1085
+ function emitErrorAndClose(websocket, err) {
1086
+ websocket._readyState = WebSocket.CLOSING;
1087
+ //
1088
+ // The following assignment is practically useless and is done only for
1089
+ // consistency.
1090
+ //
1091
+ websocket._errorEmitted = true;
1092
+ websocket.emit('error', err);
1093
+ websocket.emitClose();
1094
+ }
1095
+
1096
+ /**
1097
+ * Create a `net.Socket` and initiate a connection.
1098
+ *
1099
+ * @param {Object} options Connection options
1100
+ * @return {net.Socket} The newly created socket used to start the connection
1101
+ * @private
1102
+ */
1103
+ function netConnect(options) {
1104
+ options.path = options.socketPath;
1105
+ return net.connect(options);
1106
+ }
1107
+
1108
+ /**
1109
+ * Create a `tls.TLSSocket` and initiate a connection.
1110
+ *
1111
+ * @param {Object} options Connection options
1112
+ * @return {tls.TLSSocket} The newly created socket used to start the connection
1113
+ * @private
1114
+ */
1115
+ function tlsConnect(options) {
1116
+ options.path = undefined;
1117
+
1118
+ if (!options.servername && options.servername !== '') {
1119
+ options.servername = net.isIP(options.host) ? '' : options.host;
1120
+ }
1121
+
1122
+ return tls.connect(options);
1123
+ }
1124
+
1125
+ /**
1126
+ * Abort the handshake and emit an error.
1127
+ *
1128
+ * @param {WebSocket} websocket The WebSocket instance
1129
+ * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
1130
+ * abort or the socket to destroy
1131
+ * @param {String} message The error message
1132
+ * @private
1133
+ */
1134
+ function abortHandshake(websocket, stream, message) {
1135
+ websocket._readyState = WebSocket.CLOSING;
1136
+
1137
+ const err = new Error(message);
1138
+ Error.captureStackTrace(err, abortHandshake);
1139
+
1140
+ if (stream.setHeader) {
1141
+ stream[kAborted] = true;
1142
+ stream.abort();
1143
+
1144
+ if (stream.socket && !stream.socket.destroyed) {
1145
+ //
1146
+ // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
1147
+ // called after the request completed. See
1148
+ // https://github.com/websockets/ws/issues/1869.
1149
+ //
1150
+ stream.socket.destroy();
1151
+ }
1152
+
1153
+ process.nextTick(emitErrorAndClose, websocket, err);
1154
+ } else {
1155
+ stream.destroy(err);
1156
+ stream.once('error', websocket.emit.bind(websocket, 'error'));
1157
+ stream.once('close', websocket.emitClose.bind(websocket));
1158
+ }
1159
+ }
1160
+
1161
+ /**
1162
+ * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
1163
+ * when the `readyState` attribute is `CLOSING` or `CLOSED`.
1164
+ *
1165
+ * @param {WebSocket} websocket The WebSocket instance
1166
+ * @param {*} [data] The data to send
1167
+ * @param {Function} [cb] Callback
1168
+ * @private
1169
+ */
1170
+ function sendAfterClose(websocket, data, cb) {
1171
+ if (data) {
1172
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
1173
+
1174
+ //
1175
+ // The `_bufferedAmount` property is used only when the peer is a client and
1176
+ // the opening handshake fails. Under these circumstances, in fact, the
1177
+ // `setSocket()` method is not called, so the `_socket` and `_sender`
1178
+ // properties are set to `null`.
1179
+ //
1180
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
1181
+ else websocket._bufferedAmount += length;
1182
+ }
1183
+
1184
+ if (cb) {
1185
+ const err = new Error(
1186
+ `WebSocket is not open: readyState ${websocket.readyState} ` +
1187
+ `(${readyStates[websocket.readyState]})`
1188
+ );
1189
+ process.nextTick(cb, err);
1190
+ }
1191
+ }
1192
+
1193
+ /**
1194
+ * The listener of the `Receiver` `'conclude'` event.
1195
+ *
1196
+ * @param {Number} code The status code
1197
+ * @param {Buffer} reason The reason for closing
1198
+ * @private
1199
+ */
1200
+ function receiverOnConclude(code, reason) {
1201
+ const websocket = this[kWebSocket];
1202
+
1203
+ websocket._closeFrameReceived = true;
1204
+ websocket._closeCode = code;
1205
+
1206
+ //
1207
+ // The reason is a view into the buffer the socket delivered. Copy it so that
1208
+ // the `WebSocket` does not keep that buffer alive. The copy is not pooled
1209
+ // because a pooled one would keep the pool alive in the same way.
1210
+ //
1211
+ if (reason.length === 0) {
1212
+ websocket._closeMessage = EMPTY_BUFFER;
1213
+ } else {
1214
+ websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
1215
+ websocket._closeMessage.set(reason);
1216
+ }
1217
+
1218
+ if (websocket._socket[kWebSocket] === undefined) return;
1219
+
1220
+ websocket._socket.removeListener('data', socketOnData);
1221
+ process.nextTick(resume, websocket._socket);
1222
+
1223
+ if (code === 1005) websocket.close();
1224
+ else websocket.close(code, reason);
1225
+ }
1226
+
1227
+ /**
1228
+ * The listener of the `Receiver` `'drain'` event.
1229
+ *
1230
+ * @private
1231
+ */
1232
+ function receiverOnDrain() {
1233
+ const websocket = this[kWebSocket];
1234
+
1235
+ if (!websocket.isPaused) websocket._socket.resume();
1236
+ }
1237
+
1238
+ /**
1239
+ * The listener of the `Receiver` `'error'` event.
1240
+ *
1241
+ * @param {(RangeError|Error)} err The emitted error
1242
+ * @private
1243
+ */
1244
+ function receiverOnError(err) {
1245
+ const websocket = this[kWebSocket];
1246
+
1247
+ if (websocket._socket[kWebSocket] !== undefined) {
1248
+ websocket._socket.removeListener('data', socketOnData);
1249
+
1250
+ //
1251
+ // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
1252
+ // https://github.com/websockets/ws/issues/1940.
1253
+ //
1254
+ process.nextTick(resume, websocket._socket);
1255
+
1256
+ websocket.close(err[kStatusCode]);
1257
+ }
1258
+
1259
+ if (!websocket._errorEmitted) {
1260
+ websocket._errorEmitted = true;
1261
+ websocket.emit('error', err);
1262
+ }
1263
+ }
1264
+
1265
+ /**
1266
+ * The listener of the `Receiver` `'finish'` event.
1267
+ *
1268
+ * @private
1269
+ */
1270
+ function receiverOnFinish() {
1271
+ this[kWebSocket].emitClose();
1272
+ }
1273
+
1274
+ /**
1275
+ * The listener of the `Receiver` `'message'` event.
1276
+ *
1277
+ * @param {Buffer|ArrayBuffer|Buffer[])} data The message
1278
+ * @param {Boolean} isBinary Specifies whether the message is binary or not
1279
+ * @private
1280
+ */
1281
+ function receiverOnMessage(data, isBinary) {
1282
+ this[kWebSocket].emit('message', data, isBinary);
1283
+ }
1284
+
1285
+ /**
1286
+ * The listener of the `Receiver` `'ping'` event.
1287
+ *
1288
+ * @param {Buffer} data The data included in the ping frame
1289
+ * @private
1290
+ */
1291
+ function receiverOnPing(data) {
1292
+ const websocket = this[kWebSocket];
1293
+
1294
+ if (websocket._autoPong && websocket.readyState === WebSocket.OPEN) {
1295
+ if (
1296
+ websocket._maxPendingAutoPongs > 0 &&
1297
+ websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs
1298
+ ) {
1299
+ websocket.terminate();
1300
+ } else {
1301
+ websocket._pendingAutoPongs++;
1302
+ websocket.pong(data, !this._isServer, websocket._autoPongComplete);
1303
+ }
1304
+ }
1305
+
1306
+ websocket.emit('ping', data);
1307
+ }
1308
+
1309
+ /**
1310
+ * The callback for automatic pong responses.
1311
+ *
1312
+ * @param {WebSocket} websocket The WebSocket instance
1313
+ * @private
1314
+ */
1315
+ function autoPongComplete(websocket) {
1316
+ websocket._pendingAutoPongs--;
1317
+ }
1318
+
1319
+ /**
1320
+ * The listener of the `Receiver` `'pong'` event.
1321
+ *
1322
+ * @param {Buffer} data The data included in the pong frame
1323
+ * @private
1324
+ */
1325
+ function receiverOnPong(data) {
1326
+ this[kWebSocket].emit('pong', data);
1327
+ }
1328
+
1329
+ /**
1330
+ * Resume a readable stream
1331
+ *
1332
+ * @param {Readable} stream The readable stream
1333
+ * @private
1334
+ */
1335
+ function resume(stream) {
1336
+ stream.resume();
1337
+ }
1338
+
1339
+ /**
1340
+ * The `Sender` error event handler.
1341
+ *
1342
+ * @param {Error} The error
1343
+ * @private
1344
+ */
1345
+ function senderOnError(err) {
1346
+ const websocket = this[kWebSocket];
1347
+
1348
+ if (websocket.readyState === WebSocket.CLOSED) return;
1349
+ if (websocket.readyState === WebSocket.OPEN) {
1350
+ websocket._readyState = WebSocket.CLOSING;
1351
+ setCloseTimer(websocket);
1352
+ }
1353
+
1354
+ //
1355
+ // `socket.end()` is used instead of `socket.destroy()` to allow the other
1356
+ // peer to finish sending queued data. There is no need to set a timer here
1357
+ // because `CLOSING` means that it is already set or not needed.
1358
+ //
1359
+ this._socket.end();
1360
+
1361
+ if (!websocket._errorEmitted) {
1362
+ websocket._errorEmitted = true;
1363
+ websocket.emit('error', err);
1364
+ }
1365
+ }
1366
+
1367
+ /**
1368
+ * Set a timer to destroy the underlying raw socket of a WebSocket.
1369
+ *
1370
+ * @param {WebSocket} websocket The WebSocket instance
1371
+ * @private
1372
+ */
1373
+ function setCloseTimer(websocket) {
1374
+ websocket._closeTimer = setTimeout(
1375
+ websocket._socket.destroy.bind(websocket._socket),
1376
+ websocket._closeTimeout
1377
+ );
1378
+ }
1379
+
1380
+ /**
1381
+ * The listener of the socket `'close'` event.
1382
+ *
1383
+ * @private
1384
+ */
1385
+ function socketOnClose() {
1386
+ const websocket = this[kWebSocket];
1387
+
1388
+ this.removeListener('close', socketOnClose);
1389
+ this.removeListener('data', socketOnData);
1390
+ this.removeListener('end', socketOnEnd);
1391
+
1392
+ websocket._readyState = WebSocket.CLOSING;
1393
+
1394
+ //
1395
+ // The close frame might not have been received or the `'end'` event emitted,
1396
+ // for example, if the socket was destroyed due to an error. Ensure that the
1397
+ // `receiver` stream is closed after writing any remaining buffered data to
1398
+ // it. If the readable side of the socket is in flowing mode then there is no
1399
+ // buffered data as everything has been already written. If instead, the
1400
+ // socket is paused, any possible buffered data will be read as a single
1401
+ // chunk.
1402
+ //
1403
+ if (
1404
+ !this._readableState.endEmitted &&
1405
+ !websocket._closeFrameReceived &&
1406
+ !websocket._receiver._writableState.errorEmitted &&
1407
+ this._readableState.length !== 0
1408
+ ) {
1409
+ const chunk = this.read(this._readableState.length);
1410
+
1411
+ websocket._receiver.write(chunk);
1412
+ }
1413
+
1414
+ websocket._receiver.end();
1415
+
1416
+ this[kWebSocket] = undefined;
1417
+
1418
+ clearTimeout(websocket._closeTimer);
1419
+
1420
+ if (
1421
+ websocket._receiver._writableState.finished ||
1422
+ websocket._receiver._writableState.errorEmitted
1423
+ ) {
1424
+ websocket.emitClose();
1425
+ } else {
1426
+ websocket._receiver.on('error', receiverOnFinish);
1427
+ websocket._receiver.on('finish', receiverOnFinish);
1428
+ }
1429
+ }
1430
+
1431
+ /**
1432
+ * The listener of the socket `'data'` event.
1433
+ *
1434
+ * @param {Buffer} chunk A chunk of data
1435
+ * @private
1436
+ */
1437
+ function socketOnData(chunk) {
1438
+ if (!this[kWebSocket]._receiver.write(chunk)) {
1439
+ this.pause();
1440
+ }
1441
+ }
1442
+
1443
+ /**
1444
+ * The listener of the socket `'end'` event.
1445
+ *
1446
+ * @private
1447
+ */
1448
+ function socketOnEnd() {
1449
+ const websocket = this[kWebSocket];
1450
+
1451
+ websocket._readyState = WebSocket.CLOSING;
1452
+ websocket._receiver.end();
1453
+ this.end();
1454
+ }
1455
+
1456
+ /**
1457
+ * The listener of the socket `'error'` event.
1458
+ *
1459
+ * @private
1460
+ */
1461
+ function socketOnError() {
1462
+ const websocket = this[kWebSocket];
1463
+
1464
+ this.removeListener('error', socketOnError);
1465
+ this.on('error', NOOP);
1466
+
1467
+ if (websocket) {
1468
+ websocket._readyState = WebSocket.CLOSING;
1469
+ this.destroy();
1470
+ }
1471
+ }