@holydeck/cli 2026.9.2

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