@vitejs/devtools-rpc 0.0.0-alpha.33 → 0.0.0-alpha.34

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