skalpel 2.0.16 → 2.0.18

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