claw.events 0.1.3 → 1.0.1

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