@monolayer/sdk 1.2.3 → 1.2.4-canary.1

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