@elizaos/plugin-tee 0.1.8-alpha.1 → 0.1.9

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