@vitejs/devtools-rpc 0.0.0-alpha.8 → 0.1.0

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