tabmate 0.0.0-stage → 0.1.0

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