remotelink 0.4.0 → 0.4.2

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