agentmomo 0.1.1

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