@shopify/create-app 3.58.2 → 3.59.0

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