@harperfast/agent 0.13.0 → 0.13.2

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