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