fixparser-plugin-messagestore-kdb 0.0.1-init

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