@4pm/cli 0.8.0 → 0.8.3

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