@eduwork/dsh-remote-access 0.0.0-stage → 0.1.1

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