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