@dvmkit/dvm-cli 0.0.0 → 0.1.5

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