@pointylab/dsh 0.0.0-stage → 0.4.3

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