@apps-in-toss/web-framework 0.0.22 → 0.0.24

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 (40) hide show
  1. package/dist/cli/{chunk-RUDG2MMT.js → chunk-34QS4NNF.js} +1 -1
  2. package/dist/cli/{chunk-HDRFXOPA.js → chunk-AZQN2M6D.js} +2 -2
  3. package/dist/cli/index.js +3853 -15
  4. package/dist/cli/{lib-NMFBQRQ2.js → lib-GNFDOQZX.js} +1 -1
  5. package/dist/cli/{typescript-THSIDFIK.js → typescript-YVXHBAAI.js} +2 -2
  6. package/dist/prebuilt/dev.android.js +36148 -34816
  7. package/dist/prebuilt/dev.ios.js +36899 -35567
  8. package/dist/prebuilt/prod.android.js +38400 -1
  9. package/dist/prebuilt/prod.ios.js +38464 -1
  10. package/dist/prebuilt/prod.json +6 -6
  11. package/dist-web/index.d.ts +2 -104
  12. package/dist-web/index.js +2 -104
  13. package/package.json +16 -15
  14. package/dist-web/appLogin.d.ts +0 -30
  15. package/dist-web/bridge.d.ts +0 -25
  16. package/dist-web/bridge.js +0 -1
  17. package/dist-web/checkoutPayment.d.ts +0 -125
  18. package/dist-web/closeView.d.ts +0 -23
  19. package/dist-web/executePayment.d.ts +0 -266
  20. package/dist-web/fetchAlbumPhotos.d.ts +0 -78
  21. package/dist-web/fetchContacts.d.ts +0 -109
  22. package/dist-web/generateHapticFeedback.d.ts +0 -49
  23. package/dist-web/getClipboardText.d.ts +0 -40
  24. package/dist-web/getCurrentLocation.d.ts +0 -144
  25. package/dist-web/getDeviceId.d.ts +0 -31
  26. package/dist-web/getLocale.d.ts +0 -30
  27. package/dist-web/getNetworkStatus.d.ts +0 -54
  28. package/dist-web/getOperationalEnvironment.d.ts +0 -35
  29. package/dist-web/getPlatformOS.d.ts +0 -35
  30. package/dist-web/getSchemeUri.d.ts +0 -25
  31. package/dist-web/getTossAppVersion.d.ts +0 -31
  32. package/dist-web/getTossShareLink.d.ts +0 -31
  33. package/dist-web/openCamera.d.ts +0 -78
  34. package/dist-web/openURL.d.ts +0 -38
  35. package/dist-web/setClipboardText.d.ts +0 -32
  36. package/dist-web/setIosSwipeGestureEnabled.d.ts +0 -39
  37. package/dist-web/setScreenAwakeMode.d.ts +0 -68
  38. package/dist-web/setSecureScreen.d.ts +0 -33
  39. package/dist-web/share.d.ts +0 -36
  40. package/dist-web/startUpdateLocation.d.ts +0 -183
package/dist/cli/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
2
  import {
3
3
  require_typescript
4
- } from "./chunk-RUDG2MMT.js";
4
+ } from "./chunk-34QS4NNF.js";
5
5
  import {
6
6
  __commonJS,
7
7
  __dirname,
@@ -10,7 +10,7 @@ import {
10
10
  __require,
11
11
  __toESM,
12
12
  init_esm_shims
13
- } from "./chunk-HDRFXOPA.js";
13
+ } from "./chunk-AZQN2M6D.js";
14
14
 
15
15
  // ../../.yarn/cache/sisteransi-npm-1.0.5-a80f5ef7c8-230ac975cc.zip/node_modules/sisteransi/src/index.js
16
16
  var require_src = __commonJS({
@@ -5581,7 +5581,7 @@ ${error.message}`;
5581
5581
  exports.loadTsSync = loadTsSync;
5582
5582
  var loadTs = async function loadTs2(filepath, content) {
5583
5583
  if (typescript === void 0) {
5584
- typescript = (await import("./typescript-THSIDFIK.js")).default;
5584
+ typescript = (await import("./typescript-YVXHBAAI.js")).default;
5585
5585
  }
5586
5586
  const compiledFilepath = `${filepath.slice(0, -2)}mjs`;
5587
5587
  let transpiledContent;
@@ -52122,6 +52122,3621 @@ var require_cross_spawn = __commonJS({
52122
52122
  }
52123
52123
  });
52124
52124
 
52125
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/constants.js
52126
+ var require_constants2 = __commonJS({
52127
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/constants.js"(exports, module) {
52128
+ "use strict";
52129
+ init_esm_shims();
52130
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
52131
+ var hasBlob = typeof Blob !== "undefined";
52132
+ if (hasBlob) BINARY_TYPES.push("blob");
52133
+ module.exports = {
52134
+ BINARY_TYPES,
52135
+ EMPTY_BUFFER: Buffer.alloc(0),
52136
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
52137
+ hasBlob,
52138
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
52139
+ kListener: Symbol("kListener"),
52140
+ kStatusCode: Symbol("status-code"),
52141
+ kWebSocket: Symbol("websocket"),
52142
+ NOOP: () => {
52143
+ }
52144
+ };
52145
+ }
52146
+ });
52147
+
52148
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/buffer-util.js
52149
+ var require_buffer_util = __commonJS({
52150
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/buffer-util.js"(exports, module) {
52151
+ "use strict";
52152
+ init_esm_shims();
52153
+ var { EMPTY_BUFFER } = require_constants2();
52154
+ var FastBuffer = Buffer[Symbol.species];
52155
+ function concat(list, totalLength) {
52156
+ if (list.length === 0) return EMPTY_BUFFER;
52157
+ if (list.length === 1) return list[0];
52158
+ const target = Buffer.allocUnsafe(totalLength);
52159
+ let offset = 0;
52160
+ for (let i2 = 0; i2 < list.length; i2++) {
52161
+ const buf = list[i2];
52162
+ target.set(buf, offset);
52163
+ offset += buf.length;
52164
+ }
52165
+ if (offset < totalLength) {
52166
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
52167
+ }
52168
+ return target;
52169
+ }
52170
+ function _mask(source, mask, output, offset, length) {
52171
+ for (let i2 = 0; i2 < length; i2++) {
52172
+ output[offset + i2] = source[i2] ^ mask[i2 & 3];
52173
+ }
52174
+ }
52175
+ function _unmask(buffer, mask) {
52176
+ for (let i2 = 0; i2 < buffer.length; i2++) {
52177
+ buffer[i2] ^= mask[i2 & 3];
52178
+ }
52179
+ }
52180
+ function toArrayBuffer(buf) {
52181
+ if (buf.length === buf.buffer.byteLength) {
52182
+ return buf.buffer;
52183
+ }
52184
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
52185
+ }
52186
+ function toBuffer(data) {
52187
+ toBuffer.readOnly = true;
52188
+ if (Buffer.isBuffer(data)) return data;
52189
+ let buf;
52190
+ if (data instanceof ArrayBuffer) {
52191
+ buf = new FastBuffer(data);
52192
+ } else if (ArrayBuffer.isView(data)) {
52193
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
52194
+ } else {
52195
+ buf = Buffer.from(data);
52196
+ toBuffer.readOnly = false;
52197
+ }
52198
+ return buf;
52199
+ }
52200
+ module.exports = {
52201
+ concat,
52202
+ mask: _mask,
52203
+ toArrayBuffer,
52204
+ toBuffer,
52205
+ unmask: _unmask
52206
+ };
52207
+ if (!process.env.WS_NO_BUFFER_UTIL) {
52208
+ try {
52209
+ const bufferUtil = __require("bufferutil");
52210
+ module.exports.mask = function(source, mask, output, offset, length) {
52211
+ if (length < 48) _mask(source, mask, output, offset, length);
52212
+ else bufferUtil.mask(source, mask, output, offset, length);
52213
+ };
52214
+ module.exports.unmask = function(buffer, mask) {
52215
+ if (buffer.length < 32) _unmask(buffer, mask);
52216
+ else bufferUtil.unmask(buffer, mask);
52217
+ };
52218
+ } catch (e2) {
52219
+ }
52220
+ }
52221
+ }
52222
+ });
52223
+
52224
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/limiter.js
52225
+ var require_limiter = __commonJS({
52226
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/limiter.js"(exports, module) {
52227
+ "use strict";
52228
+ init_esm_shims();
52229
+ var kDone = Symbol("kDone");
52230
+ var kRun = Symbol("kRun");
52231
+ var Limiter = class {
52232
+ /**
52233
+ * Creates a new `Limiter`.
52234
+ *
52235
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
52236
+ * to run concurrently
52237
+ */
52238
+ constructor(concurrency) {
52239
+ this[kDone] = () => {
52240
+ this.pending--;
52241
+ this[kRun]();
52242
+ };
52243
+ this.concurrency = concurrency || Infinity;
52244
+ this.jobs = [];
52245
+ this.pending = 0;
52246
+ }
52247
+ /**
52248
+ * Adds a job to the queue.
52249
+ *
52250
+ * @param {Function} job The job to run
52251
+ * @public
52252
+ */
52253
+ add(job) {
52254
+ this.jobs.push(job);
52255
+ this[kRun]();
52256
+ }
52257
+ /**
52258
+ * Removes a job from the queue and runs it if possible.
52259
+ *
52260
+ * @private
52261
+ */
52262
+ [kRun]() {
52263
+ if (this.pending === this.concurrency) return;
52264
+ if (this.jobs.length) {
52265
+ const job = this.jobs.shift();
52266
+ this.pending++;
52267
+ job(this[kDone]);
52268
+ }
52269
+ }
52270
+ };
52271
+ module.exports = Limiter;
52272
+ }
52273
+ });
52274
+
52275
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/permessage-deflate.js
52276
+ var require_permessage_deflate = __commonJS({
52277
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
52278
+ "use strict";
52279
+ init_esm_shims();
52280
+ var zlib = __require("zlib");
52281
+ var bufferUtil = require_buffer_util();
52282
+ var Limiter = require_limiter();
52283
+ var { kStatusCode } = require_constants2();
52284
+ var FastBuffer = Buffer[Symbol.species];
52285
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
52286
+ var kPerMessageDeflate = Symbol("permessage-deflate");
52287
+ var kTotalLength = Symbol("total-length");
52288
+ var kCallback = Symbol("callback");
52289
+ var kBuffers = Symbol("buffers");
52290
+ var kError = Symbol("error");
52291
+ var zlibLimiter;
52292
+ var PerMessageDeflate = class {
52293
+ /**
52294
+ * Creates a PerMessageDeflate instance.
52295
+ *
52296
+ * @param {Object} [options] Configuration options
52297
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
52298
+ * for, or request, a custom client window size
52299
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
52300
+ * acknowledge disabling of client context takeover
52301
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
52302
+ * calls to zlib
52303
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
52304
+ * use of a custom server window size
52305
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
52306
+ * disabling of server context takeover
52307
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
52308
+ * messages should not be compressed if context takeover is disabled
52309
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
52310
+ * deflate
52311
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
52312
+ * inflate
52313
+ * @param {Boolean} [isServer=false] Create the instance in either server or
52314
+ * client mode
52315
+ * @param {Number} [maxPayload=0] The maximum allowed message length
52316
+ */
52317
+ constructor(options, isServer, maxPayload) {
52318
+ this._maxPayload = maxPayload | 0;
52319
+ this._options = options || {};
52320
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
52321
+ this._isServer = !!isServer;
52322
+ this._deflate = null;
52323
+ this._inflate = null;
52324
+ this.params = null;
52325
+ if (!zlibLimiter) {
52326
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
52327
+ zlibLimiter = new Limiter(concurrency);
52328
+ }
52329
+ }
52330
+ /**
52331
+ * @type {String}
52332
+ */
52333
+ static get extensionName() {
52334
+ return "permessage-deflate";
52335
+ }
52336
+ /**
52337
+ * Create an extension negotiation offer.
52338
+ *
52339
+ * @return {Object} Extension parameters
52340
+ * @public
52341
+ */
52342
+ offer() {
52343
+ const params = {};
52344
+ if (this._options.serverNoContextTakeover) {
52345
+ params.server_no_context_takeover = true;
52346
+ }
52347
+ if (this._options.clientNoContextTakeover) {
52348
+ params.client_no_context_takeover = true;
52349
+ }
52350
+ if (this._options.serverMaxWindowBits) {
52351
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
52352
+ }
52353
+ if (this._options.clientMaxWindowBits) {
52354
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
52355
+ } else if (this._options.clientMaxWindowBits == null) {
52356
+ params.client_max_window_bits = true;
52357
+ }
52358
+ return params;
52359
+ }
52360
+ /**
52361
+ * Accept an extension negotiation offer/response.
52362
+ *
52363
+ * @param {Array} configurations The extension negotiation offers/reponse
52364
+ * @return {Object} Accepted configuration
52365
+ * @public
52366
+ */
52367
+ accept(configurations) {
52368
+ configurations = this.normalizeParams(configurations);
52369
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
52370
+ return this.params;
52371
+ }
52372
+ /**
52373
+ * Releases all resources used by the extension.
52374
+ *
52375
+ * @public
52376
+ */
52377
+ cleanup() {
52378
+ if (this._inflate) {
52379
+ this._inflate.close();
52380
+ this._inflate = null;
52381
+ }
52382
+ if (this._deflate) {
52383
+ const callback = this._deflate[kCallback];
52384
+ this._deflate.close();
52385
+ this._deflate = null;
52386
+ if (callback) {
52387
+ callback(
52388
+ new Error(
52389
+ "The deflate stream was closed while data was being processed"
52390
+ )
52391
+ );
52392
+ }
52393
+ }
52394
+ }
52395
+ /**
52396
+ * Accept an extension negotiation offer.
52397
+ *
52398
+ * @param {Array} offers The extension negotiation offers
52399
+ * @return {Object} Accepted configuration
52400
+ * @private
52401
+ */
52402
+ acceptAsServer(offers) {
52403
+ const opts = this._options;
52404
+ const accepted = offers.find((params) => {
52405
+ 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) {
52406
+ return false;
52407
+ }
52408
+ return true;
52409
+ });
52410
+ if (!accepted) {
52411
+ throw new Error("None of the extension offers can be accepted");
52412
+ }
52413
+ if (opts.serverNoContextTakeover) {
52414
+ accepted.server_no_context_takeover = true;
52415
+ }
52416
+ if (opts.clientNoContextTakeover) {
52417
+ accepted.client_no_context_takeover = true;
52418
+ }
52419
+ if (typeof opts.serverMaxWindowBits === "number") {
52420
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
52421
+ }
52422
+ if (typeof opts.clientMaxWindowBits === "number") {
52423
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
52424
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
52425
+ delete accepted.client_max_window_bits;
52426
+ }
52427
+ return accepted;
52428
+ }
52429
+ /**
52430
+ * Accept the extension negotiation response.
52431
+ *
52432
+ * @param {Array} response The extension negotiation response
52433
+ * @return {Object} Accepted configuration
52434
+ * @private
52435
+ */
52436
+ acceptAsClient(response) {
52437
+ const params = response[0];
52438
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
52439
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
52440
+ }
52441
+ if (!params.client_max_window_bits) {
52442
+ if (typeof this._options.clientMaxWindowBits === "number") {
52443
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
52444
+ }
52445
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
52446
+ throw new Error(
52447
+ 'Unexpected or invalid parameter "client_max_window_bits"'
52448
+ );
52449
+ }
52450
+ return params;
52451
+ }
52452
+ /**
52453
+ * Normalize parameters.
52454
+ *
52455
+ * @param {Array} configurations The extension negotiation offers/reponse
52456
+ * @return {Array} The offers/response with normalized parameters
52457
+ * @private
52458
+ */
52459
+ normalizeParams(configurations) {
52460
+ configurations.forEach((params) => {
52461
+ Object.keys(params).forEach((key) => {
52462
+ let value2 = params[key];
52463
+ if (value2.length > 1) {
52464
+ throw new Error(`Parameter "${key}" must have only a single value`);
52465
+ }
52466
+ value2 = value2[0];
52467
+ if (key === "client_max_window_bits") {
52468
+ if (value2 !== true) {
52469
+ const num = +value2;
52470
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
52471
+ throw new TypeError(
52472
+ `Invalid value for parameter "${key}": ${value2}`
52473
+ );
52474
+ }
52475
+ value2 = num;
52476
+ } else if (!this._isServer) {
52477
+ throw new TypeError(
52478
+ `Invalid value for parameter "${key}": ${value2}`
52479
+ );
52480
+ }
52481
+ } else if (key === "server_max_window_bits") {
52482
+ const num = +value2;
52483
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
52484
+ throw new TypeError(
52485
+ `Invalid value for parameter "${key}": ${value2}`
52486
+ );
52487
+ }
52488
+ value2 = num;
52489
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
52490
+ if (value2 !== true) {
52491
+ throw new TypeError(
52492
+ `Invalid value for parameter "${key}": ${value2}`
52493
+ );
52494
+ }
52495
+ } else {
52496
+ throw new Error(`Unknown parameter "${key}"`);
52497
+ }
52498
+ params[key] = value2;
52499
+ });
52500
+ });
52501
+ return configurations;
52502
+ }
52503
+ /**
52504
+ * Decompress data. Concurrency limited.
52505
+ *
52506
+ * @param {Buffer} data Compressed data
52507
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
52508
+ * @param {Function} callback Callback
52509
+ * @public
52510
+ */
52511
+ decompress(data, fin, callback) {
52512
+ zlibLimiter.add((done) => {
52513
+ this._decompress(data, fin, (err, result) => {
52514
+ done();
52515
+ callback(err, result);
52516
+ });
52517
+ });
52518
+ }
52519
+ /**
52520
+ * Compress data. Concurrency limited.
52521
+ *
52522
+ * @param {(Buffer|String)} data Data to compress
52523
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
52524
+ * @param {Function} callback Callback
52525
+ * @public
52526
+ */
52527
+ compress(data, fin, callback) {
52528
+ zlibLimiter.add((done) => {
52529
+ this._compress(data, fin, (err, result) => {
52530
+ done();
52531
+ callback(err, result);
52532
+ });
52533
+ });
52534
+ }
52535
+ /**
52536
+ * Decompress data.
52537
+ *
52538
+ * @param {Buffer} data Compressed data
52539
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
52540
+ * @param {Function} callback Callback
52541
+ * @private
52542
+ */
52543
+ _decompress(data, fin, callback) {
52544
+ const endpoint = this._isServer ? "client" : "server";
52545
+ if (!this._inflate) {
52546
+ const key = `${endpoint}_max_window_bits`;
52547
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
52548
+ this._inflate = zlib.createInflateRaw({
52549
+ ...this._options.zlibInflateOptions,
52550
+ windowBits
52551
+ });
52552
+ this._inflate[kPerMessageDeflate] = this;
52553
+ this._inflate[kTotalLength] = 0;
52554
+ this._inflate[kBuffers] = [];
52555
+ this._inflate.on("error", inflateOnError);
52556
+ this._inflate.on("data", inflateOnData);
52557
+ }
52558
+ this._inflate[kCallback] = callback;
52559
+ this._inflate.write(data);
52560
+ if (fin) this._inflate.write(TRAILER);
52561
+ this._inflate.flush(() => {
52562
+ const err = this._inflate[kError];
52563
+ if (err) {
52564
+ this._inflate.close();
52565
+ this._inflate = null;
52566
+ callback(err);
52567
+ return;
52568
+ }
52569
+ const data2 = bufferUtil.concat(
52570
+ this._inflate[kBuffers],
52571
+ this._inflate[kTotalLength]
52572
+ );
52573
+ if (this._inflate._readableState.endEmitted) {
52574
+ this._inflate.close();
52575
+ this._inflate = null;
52576
+ } else {
52577
+ this._inflate[kTotalLength] = 0;
52578
+ this._inflate[kBuffers] = [];
52579
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
52580
+ this._inflate.reset();
52581
+ }
52582
+ }
52583
+ callback(null, data2);
52584
+ });
52585
+ }
52586
+ /**
52587
+ * Compress data.
52588
+ *
52589
+ * @param {(Buffer|String)} data Data to compress
52590
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
52591
+ * @param {Function} callback Callback
52592
+ * @private
52593
+ */
52594
+ _compress(data, fin, callback) {
52595
+ const endpoint = this._isServer ? "server" : "client";
52596
+ if (!this._deflate) {
52597
+ const key = `${endpoint}_max_window_bits`;
52598
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
52599
+ this._deflate = zlib.createDeflateRaw({
52600
+ ...this._options.zlibDeflateOptions,
52601
+ windowBits
52602
+ });
52603
+ this._deflate[kTotalLength] = 0;
52604
+ this._deflate[kBuffers] = [];
52605
+ this._deflate.on("data", deflateOnData);
52606
+ }
52607
+ this._deflate[kCallback] = callback;
52608
+ this._deflate.write(data);
52609
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
52610
+ if (!this._deflate) {
52611
+ return;
52612
+ }
52613
+ let data2 = bufferUtil.concat(
52614
+ this._deflate[kBuffers],
52615
+ this._deflate[kTotalLength]
52616
+ );
52617
+ if (fin) {
52618
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
52619
+ }
52620
+ this._deflate[kCallback] = null;
52621
+ this._deflate[kTotalLength] = 0;
52622
+ this._deflate[kBuffers] = [];
52623
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
52624
+ this._deflate.reset();
52625
+ }
52626
+ callback(null, data2);
52627
+ });
52628
+ }
52629
+ };
52630
+ module.exports = PerMessageDeflate;
52631
+ function deflateOnData(chunk) {
52632
+ this[kBuffers].push(chunk);
52633
+ this[kTotalLength] += chunk.length;
52634
+ }
52635
+ function inflateOnData(chunk) {
52636
+ this[kTotalLength] += chunk.length;
52637
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
52638
+ this[kBuffers].push(chunk);
52639
+ return;
52640
+ }
52641
+ this[kError] = new RangeError("Max payload size exceeded");
52642
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
52643
+ this[kError][kStatusCode] = 1009;
52644
+ this.removeListener("data", inflateOnData);
52645
+ this.reset();
52646
+ }
52647
+ function inflateOnError(err) {
52648
+ this[kPerMessageDeflate]._inflate = null;
52649
+ err[kStatusCode] = 1007;
52650
+ this[kCallback](err);
52651
+ }
52652
+ }
52653
+ });
52654
+
52655
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/validation.js
52656
+ var require_validation = __commonJS({
52657
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/validation.js"(exports, module) {
52658
+ "use strict";
52659
+ init_esm_shims();
52660
+ var { isUtf8 } = __require("buffer");
52661
+ var { hasBlob } = require_constants2();
52662
+ var tokenChars = [
52663
+ 0,
52664
+ 0,
52665
+ 0,
52666
+ 0,
52667
+ 0,
52668
+ 0,
52669
+ 0,
52670
+ 0,
52671
+ 0,
52672
+ 0,
52673
+ 0,
52674
+ 0,
52675
+ 0,
52676
+ 0,
52677
+ 0,
52678
+ 0,
52679
+ // 0 - 15
52680
+ 0,
52681
+ 0,
52682
+ 0,
52683
+ 0,
52684
+ 0,
52685
+ 0,
52686
+ 0,
52687
+ 0,
52688
+ 0,
52689
+ 0,
52690
+ 0,
52691
+ 0,
52692
+ 0,
52693
+ 0,
52694
+ 0,
52695
+ 0,
52696
+ // 16 - 31
52697
+ 0,
52698
+ 1,
52699
+ 0,
52700
+ 1,
52701
+ 1,
52702
+ 1,
52703
+ 1,
52704
+ 1,
52705
+ 0,
52706
+ 0,
52707
+ 1,
52708
+ 1,
52709
+ 0,
52710
+ 1,
52711
+ 1,
52712
+ 0,
52713
+ // 32 - 47
52714
+ 1,
52715
+ 1,
52716
+ 1,
52717
+ 1,
52718
+ 1,
52719
+ 1,
52720
+ 1,
52721
+ 1,
52722
+ 1,
52723
+ 1,
52724
+ 0,
52725
+ 0,
52726
+ 0,
52727
+ 0,
52728
+ 0,
52729
+ 0,
52730
+ // 48 - 63
52731
+ 0,
52732
+ 1,
52733
+ 1,
52734
+ 1,
52735
+ 1,
52736
+ 1,
52737
+ 1,
52738
+ 1,
52739
+ 1,
52740
+ 1,
52741
+ 1,
52742
+ 1,
52743
+ 1,
52744
+ 1,
52745
+ 1,
52746
+ 1,
52747
+ // 64 - 79
52748
+ 1,
52749
+ 1,
52750
+ 1,
52751
+ 1,
52752
+ 1,
52753
+ 1,
52754
+ 1,
52755
+ 1,
52756
+ 1,
52757
+ 1,
52758
+ 1,
52759
+ 0,
52760
+ 0,
52761
+ 0,
52762
+ 1,
52763
+ 1,
52764
+ // 80 - 95
52765
+ 1,
52766
+ 1,
52767
+ 1,
52768
+ 1,
52769
+ 1,
52770
+ 1,
52771
+ 1,
52772
+ 1,
52773
+ 1,
52774
+ 1,
52775
+ 1,
52776
+ 1,
52777
+ 1,
52778
+ 1,
52779
+ 1,
52780
+ 1,
52781
+ // 96 - 111
52782
+ 1,
52783
+ 1,
52784
+ 1,
52785
+ 1,
52786
+ 1,
52787
+ 1,
52788
+ 1,
52789
+ 1,
52790
+ 1,
52791
+ 1,
52792
+ 1,
52793
+ 0,
52794
+ 1,
52795
+ 0,
52796
+ 1,
52797
+ 0
52798
+ // 112 - 127
52799
+ ];
52800
+ function isValidStatusCode(code) {
52801
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
52802
+ }
52803
+ function _isValidUTF8(buf) {
52804
+ const len = buf.length;
52805
+ let i2 = 0;
52806
+ while (i2 < len) {
52807
+ if ((buf[i2] & 128) === 0) {
52808
+ i2++;
52809
+ } else if ((buf[i2] & 224) === 192) {
52810
+ if (i2 + 1 === len || (buf[i2 + 1] & 192) !== 128 || (buf[i2] & 254) === 192) {
52811
+ return false;
52812
+ }
52813
+ i2 += 2;
52814
+ } else if ((buf[i2] & 240) === 224) {
52815
+ if (i2 + 2 >= len || (buf[i2 + 1] & 192) !== 128 || (buf[i2 + 2] & 192) !== 128 || buf[i2] === 224 && (buf[i2 + 1] & 224) === 128 || // Overlong
52816
+ buf[i2] === 237 && (buf[i2 + 1] & 224) === 160) {
52817
+ return false;
52818
+ }
52819
+ i2 += 3;
52820
+ } else if ((buf[i2] & 248) === 240) {
52821
+ if (i2 + 3 >= len || (buf[i2 + 1] & 192) !== 128 || (buf[i2 + 2] & 192) !== 128 || (buf[i2 + 3] & 192) !== 128 || buf[i2] === 240 && (buf[i2 + 1] & 240) === 128 || // Overlong
52822
+ buf[i2] === 244 && buf[i2 + 1] > 143 || buf[i2] > 244) {
52823
+ return false;
52824
+ }
52825
+ i2 += 4;
52826
+ } else {
52827
+ return false;
52828
+ }
52829
+ }
52830
+ return true;
52831
+ }
52832
+ function isBlob(value2) {
52833
+ return hasBlob && typeof value2 === "object" && typeof value2.arrayBuffer === "function" && typeof value2.type === "string" && typeof value2.stream === "function" && (value2[Symbol.toStringTag] === "Blob" || value2[Symbol.toStringTag] === "File");
52834
+ }
52835
+ module.exports = {
52836
+ isBlob,
52837
+ isValidStatusCode,
52838
+ isValidUTF8: _isValidUTF8,
52839
+ tokenChars
52840
+ };
52841
+ if (isUtf8) {
52842
+ module.exports.isValidUTF8 = function(buf) {
52843
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
52844
+ };
52845
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
52846
+ try {
52847
+ const isValidUTF8 = __require("utf-8-validate");
52848
+ module.exports.isValidUTF8 = function(buf) {
52849
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
52850
+ };
52851
+ } catch (e2) {
52852
+ }
52853
+ }
52854
+ }
52855
+ });
52856
+
52857
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/receiver.js
52858
+ var require_receiver = __commonJS({
52859
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/receiver.js"(exports, module) {
52860
+ "use strict";
52861
+ init_esm_shims();
52862
+ var { Writable: Writable4 } = __require("stream");
52863
+ var PerMessageDeflate = require_permessage_deflate();
52864
+ var {
52865
+ BINARY_TYPES,
52866
+ EMPTY_BUFFER,
52867
+ kStatusCode,
52868
+ kWebSocket
52869
+ } = require_constants2();
52870
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
52871
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
52872
+ var FastBuffer = Buffer[Symbol.species];
52873
+ var GET_INFO = 0;
52874
+ var GET_PAYLOAD_LENGTH_16 = 1;
52875
+ var GET_PAYLOAD_LENGTH_64 = 2;
52876
+ var GET_MASK = 3;
52877
+ var GET_DATA = 4;
52878
+ var INFLATING = 5;
52879
+ var DEFER_EVENT = 6;
52880
+ var Receiver2 = class extends Writable4 {
52881
+ /**
52882
+ * Creates a Receiver instance.
52883
+ *
52884
+ * @param {Object} [options] Options object
52885
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
52886
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
52887
+ * multiple times in the same tick
52888
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
52889
+ * @param {Object} [options.extensions] An object containing the negotiated
52890
+ * extensions
52891
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
52892
+ * client or server mode
52893
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
52894
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
52895
+ * not to skip UTF-8 validation for text and close messages
52896
+ */
52897
+ constructor(options = {}) {
52898
+ super();
52899
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
52900
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
52901
+ this._extensions = options.extensions || {};
52902
+ this._isServer = !!options.isServer;
52903
+ this._maxPayload = options.maxPayload | 0;
52904
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
52905
+ this[kWebSocket] = void 0;
52906
+ this._bufferedBytes = 0;
52907
+ this._buffers = [];
52908
+ this._compressed = false;
52909
+ this._payloadLength = 0;
52910
+ this._mask = void 0;
52911
+ this._fragmented = 0;
52912
+ this._masked = false;
52913
+ this._fin = false;
52914
+ this._opcode = 0;
52915
+ this._totalPayloadLength = 0;
52916
+ this._messageLength = 0;
52917
+ this._fragments = [];
52918
+ this._errored = false;
52919
+ this._loop = false;
52920
+ this._state = GET_INFO;
52921
+ }
52922
+ /**
52923
+ * Implements `Writable.prototype._write()`.
52924
+ *
52925
+ * @param {Buffer} chunk The chunk of data to write
52926
+ * @param {String} encoding The character encoding of `chunk`
52927
+ * @param {Function} cb Callback
52928
+ * @private
52929
+ */
52930
+ _write(chunk, encoding, cb) {
52931
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
52932
+ this._bufferedBytes += chunk.length;
52933
+ this._buffers.push(chunk);
52934
+ this.startLoop(cb);
52935
+ }
52936
+ /**
52937
+ * Consumes `n` bytes from the buffered data.
52938
+ *
52939
+ * @param {Number} n The number of bytes to consume
52940
+ * @return {Buffer} The consumed bytes
52941
+ * @private
52942
+ */
52943
+ consume(n2) {
52944
+ this._bufferedBytes -= n2;
52945
+ if (n2 === this._buffers[0].length) return this._buffers.shift();
52946
+ if (n2 < this._buffers[0].length) {
52947
+ const buf = this._buffers[0];
52948
+ this._buffers[0] = new FastBuffer(
52949
+ buf.buffer,
52950
+ buf.byteOffset + n2,
52951
+ buf.length - n2
52952
+ );
52953
+ return new FastBuffer(buf.buffer, buf.byteOffset, n2);
52954
+ }
52955
+ const dst = Buffer.allocUnsafe(n2);
52956
+ do {
52957
+ const buf = this._buffers[0];
52958
+ const offset = dst.length - n2;
52959
+ if (n2 >= buf.length) {
52960
+ dst.set(this._buffers.shift(), offset);
52961
+ } else {
52962
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n2), offset);
52963
+ this._buffers[0] = new FastBuffer(
52964
+ buf.buffer,
52965
+ buf.byteOffset + n2,
52966
+ buf.length - n2
52967
+ );
52968
+ }
52969
+ n2 -= buf.length;
52970
+ } while (n2 > 0);
52971
+ return dst;
52972
+ }
52973
+ /**
52974
+ * Starts the parsing loop.
52975
+ *
52976
+ * @param {Function} cb Callback
52977
+ * @private
52978
+ */
52979
+ startLoop(cb) {
52980
+ this._loop = true;
52981
+ do {
52982
+ switch (this._state) {
52983
+ case GET_INFO:
52984
+ this.getInfo(cb);
52985
+ break;
52986
+ case GET_PAYLOAD_LENGTH_16:
52987
+ this.getPayloadLength16(cb);
52988
+ break;
52989
+ case GET_PAYLOAD_LENGTH_64:
52990
+ this.getPayloadLength64(cb);
52991
+ break;
52992
+ case GET_MASK:
52993
+ this.getMask();
52994
+ break;
52995
+ case GET_DATA:
52996
+ this.getData(cb);
52997
+ break;
52998
+ case INFLATING:
52999
+ case DEFER_EVENT:
53000
+ this._loop = false;
53001
+ return;
53002
+ }
53003
+ } while (this._loop);
53004
+ if (!this._errored) cb();
53005
+ }
53006
+ /**
53007
+ * Reads the first two bytes of a frame.
53008
+ *
53009
+ * @param {Function} cb Callback
53010
+ * @private
53011
+ */
53012
+ getInfo(cb) {
53013
+ if (this._bufferedBytes < 2) {
53014
+ this._loop = false;
53015
+ return;
53016
+ }
53017
+ const buf = this.consume(2);
53018
+ if ((buf[0] & 48) !== 0) {
53019
+ const error = this.createError(
53020
+ RangeError,
53021
+ "RSV2 and RSV3 must be clear",
53022
+ true,
53023
+ 1002,
53024
+ "WS_ERR_UNEXPECTED_RSV_2_3"
53025
+ );
53026
+ cb(error);
53027
+ return;
53028
+ }
53029
+ const compressed = (buf[0] & 64) === 64;
53030
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
53031
+ const error = this.createError(
53032
+ RangeError,
53033
+ "RSV1 must be clear",
53034
+ true,
53035
+ 1002,
53036
+ "WS_ERR_UNEXPECTED_RSV_1"
53037
+ );
53038
+ cb(error);
53039
+ return;
53040
+ }
53041
+ this._fin = (buf[0] & 128) === 128;
53042
+ this._opcode = buf[0] & 15;
53043
+ this._payloadLength = buf[1] & 127;
53044
+ if (this._opcode === 0) {
53045
+ if (compressed) {
53046
+ const error = this.createError(
53047
+ RangeError,
53048
+ "RSV1 must be clear",
53049
+ true,
53050
+ 1002,
53051
+ "WS_ERR_UNEXPECTED_RSV_1"
53052
+ );
53053
+ cb(error);
53054
+ return;
53055
+ }
53056
+ if (!this._fragmented) {
53057
+ const error = this.createError(
53058
+ RangeError,
53059
+ "invalid opcode 0",
53060
+ true,
53061
+ 1002,
53062
+ "WS_ERR_INVALID_OPCODE"
53063
+ );
53064
+ cb(error);
53065
+ return;
53066
+ }
53067
+ this._opcode = this._fragmented;
53068
+ } else if (this._opcode === 1 || this._opcode === 2) {
53069
+ if (this._fragmented) {
53070
+ const error = this.createError(
53071
+ RangeError,
53072
+ `invalid opcode ${this._opcode}`,
53073
+ true,
53074
+ 1002,
53075
+ "WS_ERR_INVALID_OPCODE"
53076
+ );
53077
+ cb(error);
53078
+ return;
53079
+ }
53080
+ this._compressed = compressed;
53081
+ } else if (this._opcode > 7 && this._opcode < 11) {
53082
+ if (!this._fin) {
53083
+ const error = this.createError(
53084
+ RangeError,
53085
+ "FIN must be set",
53086
+ true,
53087
+ 1002,
53088
+ "WS_ERR_EXPECTED_FIN"
53089
+ );
53090
+ cb(error);
53091
+ return;
53092
+ }
53093
+ if (compressed) {
53094
+ const error = this.createError(
53095
+ RangeError,
53096
+ "RSV1 must be clear",
53097
+ true,
53098
+ 1002,
53099
+ "WS_ERR_UNEXPECTED_RSV_1"
53100
+ );
53101
+ cb(error);
53102
+ return;
53103
+ }
53104
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
53105
+ const error = this.createError(
53106
+ RangeError,
53107
+ `invalid payload length ${this._payloadLength}`,
53108
+ true,
53109
+ 1002,
53110
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
53111
+ );
53112
+ cb(error);
53113
+ return;
53114
+ }
53115
+ } else {
53116
+ const error = this.createError(
53117
+ RangeError,
53118
+ `invalid opcode ${this._opcode}`,
53119
+ true,
53120
+ 1002,
53121
+ "WS_ERR_INVALID_OPCODE"
53122
+ );
53123
+ cb(error);
53124
+ return;
53125
+ }
53126
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
53127
+ this._masked = (buf[1] & 128) === 128;
53128
+ if (this._isServer) {
53129
+ if (!this._masked) {
53130
+ const error = this.createError(
53131
+ RangeError,
53132
+ "MASK must be set",
53133
+ true,
53134
+ 1002,
53135
+ "WS_ERR_EXPECTED_MASK"
53136
+ );
53137
+ cb(error);
53138
+ return;
53139
+ }
53140
+ } else if (this._masked) {
53141
+ const error = this.createError(
53142
+ RangeError,
53143
+ "MASK must be clear",
53144
+ true,
53145
+ 1002,
53146
+ "WS_ERR_UNEXPECTED_MASK"
53147
+ );
53148
+ cb(error);
53149
+ return;
53150
+ }
53151
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
53152
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
53153
+ else this.haveLength(cb);
53154
+ }
53155
+ /**
53156
+ * Gets extended payload length (7+16).
53157
+ *
53158
+ * @param {Function} cb Callback
53159
+ * @private
53160
+ */
53161
+ getPayloadLength16(cb) {
53162
+ if (this._bufferedBytes < 2) {
53163
+ this._loop = false;
53164
+ return;
53165
+ }
53166
+ this._payloadLength = this.consume(2).readUInt16BE(0);
53167
+ this.haveLength(cb);
53168
+ }
53169
+ /**
53170
+ * Gets extended payload length (7+64).
53171
+ *
53172
+ * @param {Function} cb Callback
53173
+ * @private
53174
+ */
53175
+ getPayloadLength64(cb) {
53176
+ if (this._bufferedBytes < 8) {
53177
+ this._loop = false;
53178
+ return;
53179
+ }
53180
+ const buf = this.consume(8);
53181
+ const num = buf.readUInt32BE(0);
53182
+ if (num > Math.pow(2, 53 - 32) - 1) {
53183
+ const error = this.createError(
53184
+ RangeError,
53185
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
53186
+ false,
53187
+ 1009,
53188
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
53189
+ );
53190
+ cb(error);
53191
+ return;
53192
+ }
53193
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
53194
+ this.haveLength(cb);
53195
+ }
53196
+ /**
53197
+ * Payload length has been read.
53198
+ *
53199
+ * @param {Function} cb Callback
53200
+ * @private
53201
+ */
53202
+ haveLength(cb) {
53203
+ if (this._payloadLength && this._opcode < 8) {
53204
+ this._totalPayloadLength += this._payloadLength;
53205
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
53206
+ const error = this.createError(
53207
+ RangeError,
53208
+ "Max payload size exceeded",
53209
+ false,
53210
+ 1009,
53211
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
53212
+ );
53213
+ cb(error);
53214
+ return;
53215
+ }
53216
+ }
53217
+ if (this._masked) this._state = GET_MASK;
53218
+ else this._state = GET_DATA;
53219
+ }
53220
+ /**
53221
+ * Reads mask bytes.
53222
+ *
53223
+ * @private
53224
+ */
53225
+ getMask() {
53226
+ if (this._bufferedBytes < 4) {
53227
+ this._loop = false;
53228
+ return;
53229
+ }
53230
+ this._mask = this.consume(4);
53231
+ this._state = GET_DATA;
53232
+ }
53233
+ /**
53234
+ * Reads data bytes.
53235
+ *
53236
+ * @param {Function} cb Callback
53237
+ * @private
53238
+ */
53239
+ getData(cb) {
53240
+ let data = EMPTY_BUFFER;
53241
+ if (this._payloadLength) {
53242
+ if (this._bufferedBytes < this._payloadLength) {
53243
+ this._loop = false;
53244
+ return;
53245
+ }
53246
+ data = this.consume(this._payloadLength);
53247
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
53248
+ unmask(data, this._mask);
53249
+ }
53250
+ }
53251
+ if (this._opcode > 7) {
53252
+ this.controlMessage(data, cb);
53253
+ return;
53254
+ }
53255
+ if (this._compressed) {
53256
+ this._state = INFLATING;
53257
+ this.decompress(data, cb);
53258
+ return;
53259
+ }
53260
+ if (data.length) {
53261
+ this._messageLength = this._totalPayloadLength;
53262
+ this._fragments.push(data);
53263
+ }
53264
+ this.dataMessage(cb);
53265
+ }
53266
+ /**
53267
+ * Decompresses data.
53268
+ *
53269
+ * @param {Buffer} data Compressed data
53270
+ * @param {Function} cb Callback
53271
+ * @private
53272
+ */
53273
+ decompress(data, cb) {
53274
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
53275
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
53276
+ if (err) return cb(err);
53277
+ if (buf.length) {
53278
+ this._messageLength += buf.length;
53279
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
53280
+ const error = this.createError(
53281
+ RangeError,
53282
+ "Max payload size exceeded",
53283
+ false,
53284
+ 1009,
53285
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
53286
+ );
53287
+ cb(error);
53288
+ return;
53289
+ }
53290
+ this._fragments.push(buf);
53291
+ }
53292
+ this.dataMessage(cb);
53293
+ if (this._state === GET_INFO) this.startLoop(cb);
53294
+ });
53295
+ }
53296
+ /**
53297
+ * Handles a data message.
53298
+ *
53299
+ * @param {Function} cb Callback
53300
+ * @private
53301
+ */
53302
+ dataMessage(cb) {
53303
+ if (!this._fin) {
53304
+ this._state = GET_INFO;
53305
+ return;
53306
+ }
53307
+ const messageLength = this._messageLength;
53308
+ const fragments = this._fragments;
53309
+ this._totalPayloadLength = 0;
53310
+ this._messageLength = 0;
53311
+ this._fragmented = 0;
53312
+ this._fragments = [];
53313
+ if (this._opcode === 2) {
53314
+ let data;
53315
+ if (this._binaryType === "nodebuffer") {
53316
+ data = concat(fragments, messageLength);
53317
+ } else if (this._binaryType === "arraybuffer") {
53318
+ data = toArrayBuffer(concat(fragments, messageLength));
53319
+ } else if (this._binaryType === "blob") {
53320
+ data = new Blob(fragments);
53321
+ } else {
53322
+ data = fragments;
53323
+ }
53324
+ if (this._allowSynchronousEvents) {
53325
+ this.emit("message", data, true);
53326
+ this._state = GET_INFO;
53327
+ } else {
53328
+ this._state = DEFER_EVENT;
53329
+ setImmediate(() => {
53330
+ this.emit("message", data, true);
53331
+ this._state = GET_INFO;
53332
+ this.startLoop(cb);
53333
+ });
53334
+ }
53335
+ } else {
53336
+ const buf = concat(fragments, messageLength);
53337
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
53338
+ const error = this.createError(
53339
+ Error,
53340
+ "invalid UTF-8 sequence",
53341
+ true,
53342
+ 1007,
53343
+ "WS_ERR_INVALID_UTF8"
53344
+ );
53345
+ cb(error);
53346
+ return;
53347
+ }
53348
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
53349
+ this.emit("message", buf, false);
53350
+ this._state = GET_INFO;
53351
+ } else {
53352
+ this._state = DEFER_EVENT;
53353
+ setImmediate(() => {
53354
+ this.emit("message", buf, false);
53355
+ this._state = GET_INFO;
53356
+ this.startLoop(cb);
53357
+ });
53358
+ }
53359
+ }
53360
+ }
53361
+ /**
53362
+ * Handles a control message.
53363
+ *
53364
+ * @param {Buffer} data Data to handle
53365
+ * @return {(Error|RangeError|undefined)} A possible error
53366
+ * @private
53367
+ */
53368
+ controlMessage(data, cb) {
53369
+ if (this._opcode === 8) {
53370
+ if (data.length === 0) {
53371
+ this._loop = false;
53372
+ this.emit("conclude", 1005, EMPTY_BUFFER);
53373
+ this.end();
53374
+ } else {
53375
+ const code = data.readUInt16BE(0);
53376
+ if (!isValidStatusCode(code)) {
53377
+ const error = this.createError(
53378
+ RangeError,
53379
+ `invalid status code ${code}`,
53380
+ true,
53381
+ 1002,
53382
+ "WS_ERR_INVALID_CLOSE_CODE"
53383
+ );
53384
+ cb(error);
53385
+ return;
53386
+ }
53387
+ const buf = new FastBuffer(
53388
+ data.buffer,
53389
+ data.byteOffset + 2,
53390
+ data.length - 2
53391
+ );
53392
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
53393
+ const error = this.createError(
53394
+ Error,
53395
+ "invalid UTF-8 sequence",
53396
+ true,
53397
+ 1007,
53398
+ "WS_ERR_INVALID_UTF8"
53399
+ );
53400
+ cb(error);
53401
+ return;
53402
+ }
53403
+ this._loop = false;
53404
+ this.emit("conclude", code, buf);
53405
+ this.end();
53406
+ }
53407
+ this._state = GET_INFO;
53408
+ return;
53409
+ }
53410
+ if (this._allowSynchronousEvents) {
53411
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
53412
+ this._state = GET_INFO;
53413
+ } else {
53414
+ this._state = DEFER_EVENT;
53415
+ setImmediate(() => {
53416
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
53417
+ this._state = GET_INFO;
53418
+ this.startLoop(cb);
53419
+ });
53420
+ }
53421
+ }
53422
+ /**
53423
+ * Builds an error object.
53424
+ *
53425
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
53426
+ * @param {String} message The error message
53427
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
53428
+ * `message`
53429
+ * @param {Number} statusCode The status code
53430
+ * @param {String} errorCode The exposed error code
53431
+ * @return {(Error|RangeError)} The error
53432
+ * @private
53433
+ */
53434
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
53435
+ this._loop = false;
53436
+ this._errored = true;
53437
+ const err = new ErrorCtor(
53438
+ prefix ? `Invalid WebSocket frame: ${message}` : message
53439
+ );
53440
+ Error.captureStackTrace(err, this.createError);
53441
+ err.code = errorCode;
53442
+ err[kStatusCode] = statusCode;
53443
+ return err;
53444
+ }
53445
+ };
53446
+ module.exports = Receiver2;
53447
+ }
53448
+ });
53449
+
53450
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/sender.js
53451
+ var require_sender = __commonJS({
53452
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/sender.js"(exports, module) {
53453
+ "use strict";
53454
+ init_esm_shims();
53455
+ var { Duplex: Duplex4 } = __require("stream");
53456
+ var { randomFillSync } = __require("crypto");
53457
+ var PerMessageDeflate = require_permessage_deflate();
53458
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants2();
53459
+ var { isBlob, isValidStatusCode } = require_validation();
53460
+ var { mask: applyMask, toBuffer } = require_buffer_util();
53461
+ var kByteLength = Symbol("kByteLength");
53462
+ var maskBuffer = Buffer.alloc(4);
53463
+ var RANDOM_POOL_SIZE = 8 * 1024;
53464
+ var randomPool;
53465
+ var randomPoolPointer = RANDOM_POOL_SIZE;
53466
+ var DEFAULT = 0;
53467
+ var DEFLATING = 1;
53468
+ var GET_BLOB_DATA = 2;
53469
+ var Sender2 = class _Sender {
53470
+ /**
53471
+ * Creates a Sender instance.
53472
+ *
53473
+ * @param {Duplex} socket The connection socket
53474
+ * @param {Object} [extensions] An object containing the negotiated extensions
53475
+ * @param {Function} [generateMask] The function used to generate the masking
53476
+ * key
53477
+ */
53478
+ constructor(socket, extensions, generateMask) {
53479
+ this._extensions = extensions || {};
53480
+ if (generateMask) {
53481
+ this._generateMask = generateMask;
53482
+ this._maskBuffer = Buffer.alloc(4);
53483
+ }
53484
+ this._socket = socket;
53485
+ this._firstFragment = true;
53486
+ this._compress = false;
53487
+ this._bufferedBytes = 0;
53488
+ this._queue = [];
53489
+ this._state = DEFAULT;
53490
+ this.onerror = NOOP;
53491
+ this[kWebSocket] = void 0;
53492
+ }
53493
+ /**
53494
+ * Frames a piece of data according to the HyBi WebSocket protocol.
53495
+ *
53496
+ * @param {(Buffer|String)} data The data to frame
53497
+ * @param {Object} options Options object
53498
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
53499
+ * FIN bit
53500
+ * @param {Function} [options.generateMask] The function used to generate the
53501
+ * masking key
53502
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
53503
+ * `data`
53504
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
53505
+ * key
53506
+ * @param {Number} options.opcode The opcode
53507
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
53508
+ * modified
53509
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
53510
+ * RSV1 bit
53511
+ * @return {(Buffer|String)[]} The framed data
53512
+ * @public
53513
+ */
53514
+ static frame(data, options) {
53515
+ let mask;
53516
+ let merge = false;
53517
+ let offset = 2;
53518
+ let skipMasking = false;
53519
+ if (options.mask) {
53520
+ mask = options.maskBuffer || maskBuffer;
53521
+ if (options.generateMask) {
53522
+ options.generateMask(mask);
53523
+ } else {
53524
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
53525
+ if (randomPool === void 0) {
53526
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
53527
+ }
53528
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
53529
+ randomPoolPointer = 0;
53530
+ }
53531
+ mask[0] = randomPool[randomPoolPointer++];
53532
+ mask[1] = randomPool[randomPoolPointer++];
53533
+ mask[2] = randomPool[randomPoolPointer++];
53534
+ mask[3] = randomPool[randomPoolPointer++];
53535
+ }
53536
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
53537
+ offset = 6;
53538
+ }
53539
+ let dataLength;
53540
+ if (typeof data === "string") {
53541
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
53542
+ dataLength = options[kByteLength];
53543
+ } else {
53544
+ data = Buffer.from(data);
53545
+ dataLength = data.length;
53546
+ }
53547
+ } else {
53548
+ dataLength = data.length;
53549
+ merge = options.mask && options.readOnly && !skipMasking;
53550
+ }
53551
+ let payloadLength = dataLength;
53552
+ if (dataLength >= 65536) {
53553
+ offset += 8;
53554
+ payloadLength = 127;
53555
+ } else if (dataLength > 125) {
53556
+ offset += 2;
53557
+ payloadLength = 126;
53558
+ }
53559
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
53560
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
53561
+ if (options.rsv1) target[0] |= 64;
53562
+ target[1] = payloadLength;
53563
+ if (payloadLength === 126) {
53564
+ target.writeUInt16BE(dataLength, 2);
53565
+ } else if (payloadLength === 127) {
53566
+ target[2] = target[3] = 0;
53567
+ target.writeUIntBE(dataLength, 4, 6);
53568
+ }
53569
+ if (!options.mask) return [target, data];
53570
+ target[1] |= 128;
53571
+ target[offset - 4] = mask[0];
53572
+ target[offset - 3] = mask[1];
53573
+ target[offset - 2] = mask[2];
53574
+ target[offset - 1] = mask[3];
53575
+ if (skipMasking) return [target, data];
53576
+ if (merge) {
53577
+ applyMask(data, mask, target, offset, dataLength);
53578
+ return [target];
53579
+ }
53580
+ applyMask(data, mask, data, 0, dataLength);
53581
+ return [target, data];
53582
+ }
53583
+ /**
53584
+ * Sends a close message to the other peer.
53585
+ *
53586
+ * @param {Number} [code] The status code component of the body
53587
+ * @param {(String|Buffer)} [data] The message component of the body
53588
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
53589
+ * @param {Function} [cb] Callback
53590
+ * @public
53591
+ */
53592
+ close(code, data, mask, cb) {
53593
+ let buf;
53594
+ if (code === void 0) {
53595
+ buf = EMPTY_BUFFER;
53596
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
53597
+ throw new TypeError("First argument must be a valid error code number");
53598
+ } else if (data === void 0 || !data.length) {
53599
+ buf = Buffer.allocUnsafe(2);
53600
+ buf.writeUInt16BE(code, 0);
53601
+ } else {
53602
+ const length = Buffer.byteLength(data);
53603
+ if (length > 123) {
53604
+ throw new RangeError("The message must not be greater than 123 bytes");
53605
+ }
53606
+ buf = Buffer.allocUnsafe(2 + length);
53607
+ buf.writeUInt16BE(code, 0);
53608
+ if (typeof data === "string") {
53609
+ buf.write(data, 2);
53610
+ } else {
53611
+ buf.set(data, 2);
53612
+ }
53613
+ }
53614
+ const options = {
53615
+ [kByteLength]: buf.length,
53616
+ fin: true,
53617
+ generateMask: this._generateMask,
53618
+ mask,
53619
+ maskBuffer: this._maskBuffer,
53620
+ opcode: 8,
53621
+ readOnly: false,
53622
+ rsv1: false
53623
+ };
53624
+ if (this._state !== DEFAULT) {
53625
+ this.enqueue([this.dispatch, buf, false, options, cb]);
53626
+ } else {
53627
+ this.sendFrame(_Sender.frame(buf, options), cb);
53628
+ }
53629
+ }
53630
+ /**
53631
+ * Sends a ping message to the other peer.
53632
+ *
53633
+ * @param {*} data The message to send
53634
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
53635
+ * @param {Function} [cb] Callback
53636
+ * @public
53637
+ */
53638
+ ping(data, mask, cb) {
53639
+ let byteLength;
53640
+ let readOnly;
53641
+ if (typeof data === "string") {
53642
+ byteLength = Buffer.byteLength(data);
53643
+ readOnly = false;
53644
+ } else if (isBlob(data)) {
53645
+ byteLength = data.size;
53646
+ readOnly = false;
53647
+ } else {
53648
+ data = toBuffer(data);
53649
+ byteLength = data.length;
53650
+ readOnly = toBuffer.readOnly;
53651
+ }
53652
+ if (byteLength > 125) {
53653
+ throw new RangeError("The data size must not be greater than 125 bytes");
53654
+ }
53655
+ const options = {
53656
+ [kByteLength]: byteLength,
53657
+ fin: true,
53658
+ generateMask: this._generateMask,
53659
+ mask,
53660
+ maskBuffer: this._maskBuffer,
53661
+ opcode: 9,
53662
+ readOnly,
53663
+ rsv1: false
53664
+ };
53665
+ if (isBlob(data)) {
53666
+ if (this._state !== DEFAULT) {
53667
+ this.enqueue([this.getBlobData, data, false, options, cb]);
53668
+ } else {
53669
+ this.getBlobData(data, false, options, cb);
53670
+ }
53671
+ } else if (this._state !== DEFAULT) {
53672
+ this.enqueue([this.dispatch, data, false, options, cb]);
53673
+ } else {
53674
+ this.sendFrame(_Sender.frame(data, options), cb);
53675
+ }
53676
+ }
53677
+ /**
53678
+ * Sends a pong message to the other peer.
53679
+ *
53680
+ * @param {*} data The message to send
53681
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
53682
+ * @param {Function} [cb] Callback
53683
+ * @public
53684
+ */
53685
+ pong(data, mask, cb) {
53686
+ let byteLength;
53687
+ let readOnly;
53688
+ if (typeof data === "string") {
53689
+ byteLength = Buffer.byteLength(data);
53690
+ readOnly = false;
53691
+ } else if (isBlob(data)) {
53692
+ byteLength = data.size;
53693
+ readOnly = false;
53694
+ } else {
53695
+ data = toBuffer(data);
53696
+ byteLength = data.length;
53697
+ readOnly = toBuffer.readOnly;
53698
+ }
53699
+ if (byteLength > 125) {
53700
+ throw new RangeError("The data size must not be greater than 125 bytes");
53701
+ }
53702
+ const options = {
53703
+ [kByteLength]: byteLength,
53704
+ fin: true,
53705
+ generateMask: this._generateMask,
53706
+ mask,
53707
+ maskBuffer: this._maskBuffer,
53708
+ opcode: 10,
53709
+ readOnly,
53710
+ rsv1: false
53711
+ };
53712
+ if (isBlob(data)) {
53713
+ if (this._state !== DEFAULT) {
53714
+ this.enqueue([this.getBlobData, data, false, options, cb]);
53715
+ } else {
53716
+ this.getBlobData(data, false, options, cb);
53717
+ }
53718
+ } else if (this._state !== DEFAULT) {
53719
+ this.enqueue([this.dispatch, data, false, options, cb]);
53720
+ } else {
53721
+ this.sendFrame(_Sender.frame(data, options), cb);
53722
+ }
53723
+ }
53724
+ /**
53725
+ * Sends a data message to the other peer.
53726
+ *
53727
+ * @param {*} data The message to send
53728
+ * @param {Object} options Options object
53729
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
53730
+ * or text
53731
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
53732
+ * compress `data`
53733
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
53734
+ * last one
53735
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
53736
+ * `data`
53737
+ * @param {Function} [cb] Callback
53738
+ * @public
53739
+ */
53740
+ send(data, options, cb) {
53741
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
53742
+ let opcode = options.binary ? 2 : 1;
53743
+ let rsv1 = options.compress;
53744
+ let byteLength;
53745
+ let readOnly;
53746
+ if (typeof data === "string") {
53747
+ byteLength = Buffer.byteLength(data);
53748
+ readOnly = false;
53749
+ } else if (isBlob(data)) {
53750
+ byteLength = data.size;
53751
+ readOnly = false;
53752
+ } else {
53753
+ data = toBuffer(data);
53754
+ byteLength = data.length;
53755
+ readOnly = toBuffer.readOnly;
53756
+ }
53757
+ if (this._firstFragment) {
53758
+ this._firstFragment = false;
53759
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
53760
+ rsv1 = byteLength >= perMessageDeflate._threshold;
53761
+ }
53762
+ this._compress = rsv1;
53763
+ } else {
53764
+ rsv1 = false;
53765
+ opcode = 0;
53766
+ }
53767
+ if (options.fin) this._firstFragment = true;
53768
+ const opts = {
53769
+ [kByteLength]: byteLength,
53770
+ fin: options.fin,
53771
+ generateMask: this._generateMask,
53772
+ mask: options.mask,
53773
+ maskBuffer: this._maskBuffer,
53774
+ opcode,
53775
+ readOnly,
53776
+ rsv1
53777
+ };
53778
+ if (isBlob(data)) {
53779
+ if (this._state !== DEFAULT) {
53780
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
53781
+ } else {
53782
+ this.getBlobData(data, this._compress, opts, cb);
53783
+ }
53784
+ } else if (this._state !== DEFAULT) {
53785
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
53786
+ } else {
53787
+ this.dispatch(data, this._compress, opts, cb);
53788
+ }
53789
+ }
53790
+ /**
53791
+ * Gets the contents of a blob as binary data.
53792
+ *
53793
+ * @param {Blob} blob The blob
53794
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
53795
+ * the data
53796
+ * @param {Object} options Options object
53797
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
53798
+ * FIN bit
53799
+ * @param {Function} [options.generateMask] The function used to generate the
53800
+ * masking key
53801
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
53802
+ * `data`
53803
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
53804
+ * key
53805
+ * @param {Number} options.opcode The opcode
53806
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
53807
+ * modified
53808
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
53809
+ * RSV1 bit
53810
+ * @param {Function} [cb] Callback
53811
+ * @private
53812
+ */
53813
+ getBlobData(blob, compress, options, cb) {
53814
+ this._bufferedBytes += options[kByteLength];
53815
+ this._state = GET_BLOB_DATA;
53816
+ blob.arrayBuffer().then((arrayBuffer) => {
53817
+ if (this._socket.destroyed) {
53818
+ const err = new Error(
53819
+ "The socket was closed while the blob was being read"
53820
+ );
53821
+ process.nextTick(callCallbacks, this, err, cb);
53822
+ return;
53823
+ }
53824
+ this._bufferedBytes -= options[kByteLength];
53825
+ const data = toBuffer(arrayBuffer);
53826
+ if (!compress) {
53827
+ this._state = DEFAULT;
53828
+ this.sendFrame(_Sender.frame(data, options), cb);
53829
+ this.dequeue();
53830
+ } else {
53831
+ this.dispatch(data, compress, options, cb);
53832
+ }
53833
+ }).catch((err) => {
53834
+ process.nextTick(onError, this, err, cb);
53835
+ });
53836
+ }
53837
+ /**
53838
+ * Dispatches a message.
53839
+ *
53840
+ * @param {(Buffer|String)} data The message to send
53841
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
53842
+ * `data`
53843
+ * @param {Object} options Options object
53844
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
53845
+ * FIN bit
53846
+ * @param {Function} [options.generateMask] The function used to generate the
53847
+ * masking key
53848
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
53849
+ * `data`
53850
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
53851
+ * key
53852
+ * @param {Number} options.opcode The opcode
53853
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
53854
+ * modified
53855
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
53856
+ * RSV1 bit
53857
+ * @param {Function} [cb] Callback
53858
+ * @private
53859
+ */
53860
+ dispatch(data, compress, options, cb) {
53861
+ if (!compress) {
53862
+ this.sendFrame(_Sender.frame(data, options), cb);
53863
+ return;
53864
+ }
53865
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
53866
+ this._bufferedBytes += options[kByteLength];
53867
+ this._state = DEFLATING;
53868
+ perMessageDeflate.compress(data, options.fin, (_2, buf) => {
53869
+ if (this._socket.destroyed) {
53870
+ const err = new Error(
53871
+ "The socket was closed while data was being compressed"
53872
+ );
53873
+ callCallbacks(this, err, cb);
53874
+ return;
53875
+ }
53876
+ this._bufferedBytes -= options[kByteLength];
53877
+ this._state = DEFAULT;
53878
+ options.readOnly = false;
53879
+ this.sendFrame(_Sender.frame(buf, options), cb);
53880
+ this.dequeue();
53881
+ });
53882
+ }
53883
+ /**
53884
+ * Executes queued send operations.
53885
+ *
53886
+ * @private
53887
+ */
53888
+ dequeue() {
53889
+ while (this._state === DEFAULT && this._queue.length) {
53890
+ const params = this._queue.shift();
53891
+ this._bufferedBytes -= params[3][kByteLength];
53892
+ Reflect.apply(params[0], this, params.slice(1));
53893
+ }
53894
+ }
53895
+ /**
53896
+ * Enqueues a send operation.
53897
+ *
53898
+ * @param {Array} params Send operation parameters.
53899
+ * @private
53900
+ */
53901
+ enqueue(params) {
53902
+ this._bufferedBytes += params[3][kByteLength];
53903
+ this._queue.push(params);
53904
+ }
53905
+ /**
53906
+ * Sends a frame.
53907
+ *
53908
+ * @param {(Buffer | String)[]} list The frame to send
53909
+ * @param {Function} [cb] Callback
53910
+ * @private
53911
+ */
53912
+ sendFrame(list, cb) {
53913
+ if (list.length === 2) {
53914
+ this._socket.cork();
53915
+ this._socket.write(list[0]);
53916
+ this._socket.write(list[1], cb);
53917
+ this._socket.uncork();
53918
+ } else {
53919
+ this._socket.write(list[0], cb);
53920
+ }
53921
+ }
53922
+ };
53923
+ module.exports = Sender2;
53924
+ function callCallbacks(sender, err, cb) {
53925
+ if (typeof cb === "function") cb(err);
53926
+ for (let i2 = 0; i2 < sender._queue.length; i2++) {
53927
+ const params = sender._queue[i2];
53928
+ const callback = params[params.length - 1];
53929
+ if (typeof callback === "function") callback(err);
53930
+ }
53931
+ }
53932
+ function onError(sender, err, cb) {
53933
+ callCallbacks(sender, err, cb);
53934
+ sender.onerror(err);
53935
+ }
53936
+ }
53937
+ });
53938
+
53939
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/event-target.js
53940
+ var require_event_target = __commonJS({
53941
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/event-target.js"(exports, module) {
53942
+ "use strict";
53943
+ init_esm_shims();
53944
+ var { kForOnEventAttribute, kListener } = require_constants2();
53945
+ var kCode = Symbol("kCode");
53946
+ var kData = Symbol("kData");
53947
+ var kError = Symbol("kError");
53948
+ var kMessage = Symbol("kMessage");
53949
+ var kReason = Symbol("kReason");
53950
+ var kTarget = Symbol("kTarget");
53951
+ var kType = Symbol("kType");
53952
+ var kWasClean = Symbol("kWasClean");
53953
+ var Event2 = class {
53954
+ /**
53955
+ * Create a new `Event`.
53956
+ *
53957
+ * @param {String} type The name of the event
53958
+ * @throws {TypeError} If the `type` argument is not specified
53959
+ */
53960
+ constructor(type) {
53961
+ this[kTarget] = null;
53962
+ this[kType] = type;
53963
+ }
53964
+ /**
53965
+ * @type {*}
53966
+ */
53967
+ get target() {
53968
+ return this[kTarget];
53969
+ }
53970
+ /**
53971
+ * @type {String}
53972
+ */
53973
+ get type() {
53974
+ return this[kType];
53975
+ }
53976
+ };
53977
+ Object.defineProperty(Event2.prototype, "target", { enumerable: true });
53978
+ Object.defineProperty(Event2.prototype, "type", { enumerable: true });
53979
+ var CloseEvent2 = class extends Event2 {
53980
+ /**
53981
+ * Create a new `CloseEvent`.
53982
+ *
53983
+ * @param {String} type The name of the event
53984
+ * @param {Object} [options] A dictionary object that allows for setting
53985
+ * attributes via object members of the same name
53986
+ * @param {Number} [options.code=0] The status code explaining why the
53987
+ * connection was closed
53988
+ * @param {String} [options.reason=''] A human-readable string explaining why
53989
+ * the connection was closed
53990
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
53991
+ * connection was cleanly closed
53992
+ */
53993
+ constructor(type, options = {}) {
53994
+ super(type);
53995
+ this[kCode] = options.code === void 0 ? 0 : options.code;
53996
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
53997
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
53998
+ }
53999
+ /**
54000
+ * @type {Number}
54001
+ */
54002
+ get code() {
54003
+ return this[kCode];
54004
+ }
54005
+ /**
54006
+ * @type {String}
54007
+ */
54008
+ get reason() {
54009
+ return this[kReason];
54010
+ }
54011
+ /**
54012
+ * @type {Boolean}
54013
+ */
54014
+ get wasClean() {
54015
+ return this[kWasClean];
54016
+ }
54017
+ };
54018
+ Object.defineProperty(CloseEvent2.prototype, "code", { enumerable: true });
54019
+ Object.defineProperty(CloseEvent2.prototype, "reason", { enumerable: true });
54020
+ Object.defineProperty(CloseEvent2.prototype, "wasClean", { enumerable: true });
54021
+ var ErrorEvent2 = class extends Event2 {
54022
+ /**
54023
+ * Create a new `ErrorEvent`.
54024
+ *
54025
+ * @param {String} type The name of the event
54026
+ * @param {Object} [options] A dictionary object that allows for setting
54027
+ * attributes via object members of the same name
54028
+ * @param {*} [options.error=null] The error that generated this event
54029
+ * @param {String} [options.message=''] The error message
54030
+ */
54031
+ constructor(type, options = {}) {
54032
+ super(type);
54033
+ this[kError] = options.error === void 0 ? null : options.error;
54034
+ this[kMessage] = options.message === void 0 ? "" : options.message;
54035
+ }
54036
+ /**
54037
+ * @type {*}
54038
+ */
54039
+ get error() {
54040
+ return this[kError];
54041
+ }
54042
+ /**
54043
+ * @type {String}
54044
+ */
54045
+ get message() {
54046
+ return this[kMessage];
54047
+ }
54048
+ };
54049
+ Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true });
54050
+ Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true });
54051
+ var MessageEvent2 = class extends Event2 {
54052
+ /**
54053
+ * Create a new `MessageEvent`.
54054
+ *
54055
+ * @param {String} type The name of the event
54056
+ * @param {Object} [options] A dictionary object that allows for setting
54057
+ * attributes via object members of the same name
54058
+ * @param {*} [options.data=null] The message content
54059
+ */
54060
+ constructor(type, options = {}) {
54061
+ super(type);
54062
+ this[kData] = options.data === void 0 ? null : options.data;
54063
+ }
54064
+ /**
54065
+ * @type {*}
54066
+ */
54067
+ get data() {
54068
+ return this[kData];
54069
+ }
54070
+ };
54071
+ Object.defineProperty(MessageEvent2.prototype, "data", { enumerable: true });
54072
+ var EventTarget = {
54073
+ /**
54074
+ * Register an event listener.
54075
+ *
54076
+ * @param {String} type A string representing the event type to listen for
54077
+ * @param {(Function|Object)} handler The listener to add
54078
+ * @param {Object} [options] An options object specifies characteristics about
54079
+ * the event listener
54080
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
54081
+ * listener should be invoked at most once after being added. If `true`,
54082
+ * the listener would be automatically removed when invoked.
54083
+ * @public
54084
+ */
54085
+ addEventListener(type, handler, options = {}) {
54086
+ for (const listener of this.listeners(type)) {
54087
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
54088
+ return;
54089
+ }
54090
+ }
54091
+ let wrapper;
54092
+ if (type === "message") {
54093
+ wrapper = function onMessage2(data, isBinary) {
54094
+ const event = new MessageEvent2("message", {
54095
+ data: isBinary ? data : data.toString()
54096
+ });
54097
+ event[kTarget] = this;
54098
+ callListener(handler, this, event);
54099
+ };
54100
+ } else if (type === "close") {
54101
+ wrapper = function onClose(code, message) {
54102
+ const event = new CloseEvent2("close", {
54103
+ code,
54104
+ reason: message.toString(),
54105
+ wasClean: this._closeFrameReceived && this._closeFrameSent
54106
+ });
54107
+ event[kTarget] = this;
54108
+ callListener(handler, this, event);
54109
+ };
54110
+ } else if (type === "error") {
54111
+ wrapper = function onError(error) {
54112
+ const event = new ErrorEvent2("error", {
54113
+ error,
54114
+ message: error.message
54115
+ });
54116
+ event[kTarget] = this;
54117
+ callListener(handler, this, event);
54118
+ };
54119
+ } else if (type === "open") {
54120
+ wrapper = function onOpen() {
54121
+ const event = new Event2("open");
54122
+ event[kTarget] = this;
54123
+ callListener(handler, this, event);
54124
+ };
54125
+ } else {
54126
+ return;
54127
+ }
54128
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
54129
+ wrapper[kListener] = handler;
54130
+ if (options.once) {
54131
+ this.once(type, wrapper);
54132
+ } else {
54133
+ this.on(type, wrapper);
54134
+ }
54135
+ },
54136
+ /**
54137
+ * Remove an event listener.
54138
+ *
54139
+ * @param {String} type A string representing the event type to remove
54140
+ * @param {(Function|Object)} handler The listener to remove
54141
+ * @public
54142
+ */
54143
+ removeEventListener(type, handler) {
54144
+ for (const listener of this.listeners(type)) {
54145
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
54146
+ this.removeListener(type, listener);
54147
+ break;
54148
+ }
54149
+ }
54150
+ }
54151
+ };
54152
+ module.exports = {
54153
+ CloseEvent: CloseEvent2,
54154
+ ErrorEvent: ErrorEvent2,
54155
+ Event: Event2,
54156
+ EventTarget,
54157
+ MessageEvent: MessageEvent2
54158
+ };
54159
+ function callListener(listener, thisArg, event) {
54160
+ if (typeof listener === "object" && listener.handleEvent) {
54161
+ listener.handleEvent.call(listener, event);
54162
+ } else {
54163
+ listener.call(thisArg, event);
54164
+ }
54165
+ }
54166
+ }
54167
+ });
54168
+
54169
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/extension.js
54170
+ var require_extension = __commonJS({
54171
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/extension.js"(exports, module) {
54172
+ "use strict";
54173
+ init_esm_shims();
54174
+ var { tokenChars } = require_validation();
54175
+ function push(dest, name, elem) {
54176
+ if (dest[name] === void 0) dest[name] = [elem];
54177
+ else dest[name].push(elem);
54178
+ }
54179
+ function parse(header) {
54180
+ const offers = /* @__PURE__ */ Object.create(null);
54181
+ let params = /* @__PURE__ */ Object.create(null);
54182
+ let mustUnescape = false;
54183
+ let isEscaping = false;
54184
+ let inQuotes = false;
54185
+ let extensionName;
54186
+ let paramName;
54187
+ let start = -1;
54188
+ let code = -1;
54189
+ let end = -1;
54190
+ let i2 = 0;
54191
+ for (; i2 < header.length; i2++) {
54192
+ code = header.charCodeAt(i2);
54193
+ if (extensionName === void 0) {
54194
+ if (end === -1 && tokenChars[code] === 1) {
54195
+ if (start === -1) start = i2;
54196
+ } else if (i2 !== 0 && (code === 32 || code === 9)) {
54197
+ if (end === -1 && start !== -1) end = i2;
54198
+ } else if (code === 59 || code === 44) {
54199
+ if (start === -1) {
54200
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
54201
+ }
54202
+ if (end === -1) end = i2;
54203
+ const name = header.slice(start, end);
54204
+ if (code === 44) {
54205
+ push(offers, name, params);
54206
+ params = /* @__PURE__ */ Object.create(null);
54207
+ } else {
54208
+ extensionName = name;
54209
+ }
54210
+ start = end = -1;
54211
+ } else {
54212
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
54213
+ }
54214
+ } else if (paramName === void 0) {
54215
+ if (end === -1 && tokenChars[code] === 1) {
54216
+ if (start === -1) start = i2;
54217
+ } else if (code === 32 || code === 9) {
54218
+ if (end === -1 && start !== -1) end = i2;
54219
+ } else if (code === 59 || code === 44) {
54220
+ if (start === -1) {
54221
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
54222
+ }
54223
+ if (end === -1) end = i2;
54224
+ push(params, header.slice(start, end), true);
54225
+ if (code === 44) {
54226
+ push(offers, extensionName, params);
54227
+ params = /* @__PURE__ */ Object.create(null);
54228
+ extensionName = void 0;
54229
+ }
54230
+ start = end = -1;
54231
+ } else if (code === 61 && start !== -1 && end === -1) {
54232
+ paramName = header.slice(start, i2);
54233
+ start = end = -1;
54234
+ } else {
54235
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
54236
+ }
54237
+ } else {
54238
+ if (isEscaping) {
54239
+ if (tokenChars[code] !== 1) {
54240
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
54241
+ }
54242
+ if (start === -1) start = i2;
54243
+ else if (!mustUnescape) mustUnescape = true;
54244
+ isEscaping = false;
54245
+ } else if (inQuotes) {
54246
+ if (tokenChars[code] === 1) {
54247
+ if (start === -1) start = i2;
54248
+ } else if (code === 34 && start !== -1) {
54249
+ inQuotes = false;
54250
+ end = i2;
54251
+ } else if (code === 92) {
54252
+ isEscaping = true;
54253
+ } else {
54254
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
54255
+ }
54256
+ } else if (code === 34 && header.charCodeAt(i2 - 1) === 61) {
54257
+ inQuotes = true;
54258
+ } else if (end === -1 && tokenChars[code] === 1) {
54259
+ if (start === -1) start = i2;
54260
+ } else if (start !== -1 && (code === 32 || code === 9)) {
54261
+ if (end === -1) end = i2;
54262
+ } else if (code === 59 || code === 44) {
54263
+ if (start === -1) {
54264
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
54265
+ }
54266
+ if (end === -1) end = i2;
54267
+ let value2 = header.slice(start, end);
54268
+ if (mustUnescape) {
54269
+ value2 = value2.replace(/\\/g, "");
54270
+ mustUnescape = false;
54271
+ }
54272
+ push(params, paramName, value2);
54273
+ if (code === 44) {
54274
+ push(offers, extensionName, params);
54275
+ params = /* @__PURE__ */ Object.create(null);
54276
+ extensionName = void 0;
54277
+ }
54278
+ paramName = void 0;
54279
+ start = end = -1;
54280
+ } else {
54281
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
54282
+ }
54283
+ }
54284
+ }
54285
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
54286
+ throw new SyntaxError("Unexpected end of input");
54287
+ }
54288
+ if (end === -1) end = i2;
54289
+ const token = header.slice(start, end);
54290
+ if (extensionName === void 0) {
54291
+ push(offers, token, params);
54292
+ } else {
54293
+ if (paramName === void 0) {
54294
+ push(params, token, true);
54295
+ } else if (mustUnescape) {
54296
+ push(params, paramName, token.replace(/\\/g, ""));
54297
+ } else {
54298
+ push(params, paramName, token);
54299
+ }
54300
+ push(offers, extensionName, params);
54301
+ }
54302
+ return offers;
54303
+ }
54304
+ function format2(extensions) {
54305
+ return Object.keys(extensions).map((extension) => {
54306
+ let configurations = extensions[extension];
54307
+ if (!Array.isArray(configurations)) configurations = [configurations];
54308
+ return configurations.map((params) => {
54309
+ return [extension].concat(
54310
+ Object.keys(params).map((k3) => {
54311
+ let values = params[k3];
54312
+ if (!Array.isArray(values)) values = [values];
54313
+ return values.map((v) => v === true ? k3 : `${k3}=${v}`).join("; ");
54314
+ })
54315
+ ).join("; ");
54316
+ }).join(", ");
54317
+ }).join(", ");
54318
+ }
54319
+ module.exports = { format: format2, parse };
54320
+ }
54321
+ });
54322
+
54323
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/websocket.js
54324
+ var require_websocket = __commonJS({
54325
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/websocket.js"(exports, module) {
54326
+ "use strict";
54327
+ init_esm_shims();
54328
+ var EventEmitter2 = __require("events");
54329
+ var https = __require("https");
54330
+ var http = __require("http");
54331
+ var net = __require("net");
54332
+ var tls = __require("tls");
54333
+ var { randomBytes, createHash } = __require("crypto");
54334
+ var { Duplex: Duplex4, Readable: Readable5 } = __require("stream");
54335
+ var { URL: URL2 } = __require("url");
54336
+ var PerMessageDeflate = require_permessage_deflate();
54337
+ var Receiver2 = require_receiver();
54338
+ var Sender2 = require_sender();
54339
+ var { isBlob } = require_validation();
54340
+ var {
54341
+ BINARY_TYPES,
54342
+ EMPTY_BUFFER,
54343
+ GUID,
54344
+ kForOnEventAttribute,
54345
+ kListener,
54346
+ kStatusCode,
54347
+ kWebSocket,
54348
+ NOOP
54349
+ } = require_constants2();
54350
+ var {
54351
+ EventTarget: { addEventListener: addEventListener2, removeEventListener }
54352
+ } = require_event_target();
54353
+ var { format: format2, parse } = require_extension();
54354
+ var { toBuffer } = require_buffer_util();
54355
+ var closeTimeout = 30 * 1e3;
54356
+ var kAborted = Symbol("kAborted");
54357
+ var protocolVersions = [8, 13];
54358
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
54359
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
54360
+ var WebSocket2 = class _WebSocket extends EventEmitter2 {
54361
+ /**
54362
+ * Create a new `WebSocket`.
54363
+ *
54364
+ * @param {(String|URL)} address The URL to which to connect
54365
+ * @param {(String|String[])} [protocols] The subprotocols
54366
+ * @param {Object} [options] Connection options
54367
+ */
54368
+ constructor(address, protocols, options) {
54369
+ super();
54370
+ this._binaryType = BINARY_TYPES[0];
54371
+ this._closeCode = 1006;
54372
+ this._closeFrameReceived = false;
54373
+ this._closeFrameSent = false;
54374
+ this._closeMessage = EMPTY_BUFFER;
54375
+ this._closeTimer = null;
54376
+ this._errorEmitted = false;
54377
+ this._extensions = {};
54378
+ this._paused = false;
54379
+ this._protocol = "";
54380
+ this._readyState = _WebSocket.CONNECTING;
54381
+ this._receiver = null;
54382
+ this._sender = null;
54383
+ this._socket = null;
54384
+ if (address !== null) {
54385
+ this._bufferedAmount = 0;
54386
+ this._isServer = false;
54387
+ this._redirects = 0;
54388
+ if (protocols === void 0) {
54389
+ protocols = [];
54390
+ } else if (!Array.isArray(protocols)) {
54391
+ if (typeof protocols === "object" && protocols !== null) {
54392
+ options = protocols;
54393
+ protocols = [];
54394
+ } else {
54395
+ protocols = [protocols];
54396
+ }
54397
+ }
54398
+ initAsClient(this, address, protocols, options);
54399
+ } else {
54400
+ this._autoPong = options.autoPong;
54401
+ this._isServer = true;
54402
+ }
54403
+ }
54404
+ /**
54405
+ * For historical reasons, the custom "nodebuffer" type is used by the default
54406
+ * instead of "blob".
54407
+ *
54408
+ * @type {String}
54409
+ */
54410
+ get binaryType() {
54411
+ return this._binaryType;
54412
+ }
54413
+ set binaryType(type) {
54414
+ if (!BINARY_TYPES.includes(type)) return;
54415
+ this._binaryType = type;
54416
+ if (this._receiver) this._receiver._binaryType = type;
54417
+ }
54418
+ /**
54419
+ * @type {Number}
54420
+ */
54421
+ get bufferedAmount() {
54422
+ if (!this._socket) return this._bufferedAmount;
54423
+ return this._socket._writableState.length + this._sender._bufferedBytes;
54424
+ }
54425
+ /**
54426
+ * @type {String}
54427
+ */
54428
+ get extensions() {
54429
+ return Object.keys(this._extensions).join();
54430
+ }
54431
+ /**
54432
+ * @type {Boolean}
54433
+ */
54434
+ get isPaused() {
54435
+ return this._paused;
54436
+ }
54437
+ /**
54438
+ * @type {Function}
54439
+ */
54440
+ /* istanbul ignore next */
54441
+ get onclose() {
54442
+ return null;
54443
+ }
54444
+ /**
54445
+ * @type {Function}
54446
+ */
54447
+ /* istanbul ignore next */
54448
+ get onerror() {
54449
+ return null;
54450
+ }
54451
+ /**
54452
+ * @type {Function}
54453
+ */
54454
+ /* istanbul ignore next */
54455
+ get onopen() {
54456
+ return null;
54457
+ }
54458
+ /**
54459
+ * @type {Function}
54460
+ */
54461
+ /* istanbul ignore next */
54462
+ get onmessage() {
54463
+ return null;
54464
+ }
54465
+ /**
54466
+ * @type {String}
54467
+ */
54468
+ get protocol() {
54469
+ return this._protocol;
54470
+ }
54471
+ /**
54472
+ * @type {Number}
54473
+ */
54474
+ get readyState() {
54475
+ return this._readyState;
54476
+ }
54477
+ /**
54478
+ * @type {String}
54479
+ */
54480
+ get url() {
54481
+ return this._url;
54482
+ }
54483
+ /**
54484
+ * Set up the socket and the internal resources.
54485
+ *
54486
+ * @param {Duplex} socket The network socket between the server and client
54487
+ * @param {Buffer} head The first packet of the upgraded stream
54488
+ * @param {Object} options Options object
54489
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
54490
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
54491
+ * multiple times in the same tick
54492
+ * @param {Function} [options.generateMask] The function used to generate the
54493
+ * masking key
54494
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
54495
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
54496
+ * not to skip UTF-8 validation for text and close messages
54497
+ * @private
54498
+ */
54499
+ setSocket(socket, head, options) {
54500
+ const receiver = new Receiver2({
54501
+ allowSynchronousEvents: options.allowSynchronousEvents,
54502
+ binaryType: this.binaryType,
54503
+ extensions: this._extensions,
54504
+ isServer: this._isServer,
54505
+ maxPayload: options.maxPayload,
54506
+ skipUTF8Validation: options.skipUTF8Validation
54507
+ });
54508
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
54509
+ this._receiver = receiver;
54510
+ this._sender = sender;
54511
+ this._socket = socket;
54512
+ receiver[kWebSocket] = this;
54513
+ sender[kWebSocket] = this;
54514
+ socket[kWebSocket] = this;
54515
+ receiver.on("conclude", receiverOnConclude);
54516
+ receiver.on("drain", receiverOnDrain);
54517
+ receiver.on("error", receiverOnError);
54518
+ receiver.on("message", receiverOnMessage);
54519
+ receiver.on("ping", receiverOnPing);
54520
+ receiver.on("pong", receiverOnPong);
54521
+ sender.onerror = senderOnError;
54522
+ if (socket.setTimeout) socket.setTimeout(0);
54523
+ if (socket.setNoDelay) socket.setNoDelay();
54524
+ if (head.length > 0) socket.unshift(head);
54525
+ socket.on("close", socketOnClose);
54526
+ socket.on("data", socketOnData);
54527
+ socket.on("end", socketOnEnd);
54528
+ socket.on("error", socketOnError);
54529
+ this._readyState = _WebSocket.OPEN;
54530
+ this.emit("open");
54531
+ }
54532
+ /**
54533
+ * Emit the `'close'` event.
54534
+ *
54535
+ * @private
54536
+ */
54537
+ emitClose() {
54538
+ if (!this._socket) {
54539
+ this._readyState = _WebSocket.CLOSED;
54540
+ this.emit("close", this._closeCode, this._closeMessage);
54541
+ return;
54542
+ }
54543
+ if (this._extensions[PerMessageDeflate.extensionName]) {
54544
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
54545
+ }
54546
+ this._receiver.removeAllListeners();
54547
+ this._readyState = _WebSocket.CLOSED;
54548
+ this.emit("close", this._closeCode, this._closeMessage);
54549
+ }
54550
+ /**
54551
+ * Start a closing handshake.
54552
+ *
54553
+ * +----------+ +-----------+ +----------+
54554
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
54555
+ * | +----------+ +-----------+ +----------+ |
54556
+ * +----------+ +-----------+ |
54557
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
54558
+ * +----------+ +-----------+ |
54559
+ * | | | +---+ |
54560
+ * +------------------------+-->|fin| - - - -
54561
+ * | +---+ | +---+
54562
+ * - - - - -|fin|<---------------------+
54563
+ * +---+
54564
+ *
54565
+ * @param {Number} [code] Status code explaining why the connection is closing
54566
+ * @param {(String|Buffer)} [data] The reason why the connection is
54567
+ * closing
54568
+ * @public
54569
+ */
54570
+ close(code, data) {
54571
+ if (this.readyState === _WebSocket.CLOSED) return;
54572
+ if (this.readyState === _WebSocket.CONNECTING) {
54573
+ const msg = "WebSocket was closed before the connection was established";
54574
+ abortHandshake(this, this._req, msg);
54575
+ return;
54576
+ }
54577
+ if (this.readyState === _WebSocket.CLOSING) {
54578
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
54579
+ this._socket.end();
54580
+ }
54581
+ return;
54582
+ }
54583
+ this._readyState = _WebSocket.CLOSING;
54584
+ this._sender.close(code, data, !this._isServer, (err) => {
54585
+ if (err) return;
54586
+ this._closeFrameSent = true;
54587
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
54588
+ this._socket.end();
54589
+ }
54590
+ });
54591
+ setCloseTimer(this);
54592
+ }
54593
+ /**
54594
+ * Pause the socket.
54595
+ *
54596
+ * @public
54597
+ */
54598
+ pause() {
54599
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
54600
+ return;
54601
+ }
54602
+ this._paused = true;
54603
+ this._socket.pause();
54604
+ }
54605
+ /**
54606
+ * Send a ping.
54607
+ *
54608
+ * @param {*} [data] The data to send
54609
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
54610
+ * @param {Function} [cb] Callback which is executed when the ping is sent
54611
+ * @public
54612
+ */
54613
+ ping(data, mask, cb) {
54614
+ if (this.readyState === _WebSocket.CONNECTING) {
54615
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
54616
+ }
54617
+ if (typeof data === "function") {
54618
+ cb = data;
54619
+ data = mask = void 0;
54620
+ } else if (typeof mask === "function") {
54621
+ cb = mask;
54622
+ mask = void 0;
54623
+ }
54624
+ if (typeof data === "number") data = data.toString();
54625
+ if (this.readyState !== _WebSocket.OPEN) {
54626
+ sendAfterClose(this, data, cb);
54627
+ return;
54628
+ }
54629
+ if (mask === void 0) mask = !this._isServer;
54630
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
54631
+ }
54632
+ /**
54633
+ * Send a pong.
54634
+ *
54635
+ * @param {*} [data] The data to send
54636
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
54637
+ * @param {Function} [cb] Callback which is executed when the pong is sent
54638
+ * @public
54639
+ */
54640
+ pong(data, mask, cb) {
54641
+ if (this.readyState === _WebSocket.CONNECTING) {
54642
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
54643
+ }
54644
+ if (typeof data === "function") {
54645
+ cb = data;
54646
+ data = mask = void 0;
54647
+ } else if (typeof mask === "function") {
54648
+ cb = mask;
54649
+ mask = void 0;
54650
+ }
54651
+ if (typeof data === "number") data = data.toString();
54652
+ if (this.readyState !== _WebSocket.OPEN) {
54653
+ sendAfterClose(this, data, cb);
54654
+ return;
54655
+ }
54656
+ if (mask === void 0) mask = !this._isServer;
54657
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
54658
+ }
54659
+ /**
54660
+ * Resume the socket.
54661
+ *
54662
+ * @public
54663
+ */
54664
+ resume() {
54665
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
54666
+ return;
54667
+ }
54668
+ this._paused = false;
54669
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
54670
+ }
54671
+ /**
54672
+ * Send a data message.
54673
+ *
54674
+ * @param {*} data The message to send
54675
+ * @param {Object} [options] Options object
54676
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
54677
+ * text
54678
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
54679
+ * `data`
54680
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
54681
+ * last one
54682
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
54683
+ * @param {Function} [cb] Callback which is executed when data is written out
54684
+ * @public
54685
+ */
54686
+ send(data, options, cb) {
54687
+ if (this.readyState === _WebSocket.CONNECTING) {
54688
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
54689
+ }
54690
+ if (typeof options === "function") {
54691
+ cb = options;
54692
+ options = {};
54693
+ }
54694
+ if (typeof data === "number") data = data.toString();
54695
+ if (this.readyState !== _WebSocket.OPEN) {
54696
+ sendAfterClose(this, data, cb);
54697
+ return;
54698
+ }
54699
+ const opts = {
54700
+ binary: typeof data !== "string",
54701
+ mask: !this._isServer,
54702
+ compress: true,
54703
+ fin: true,
54704
+ ...options
54705
+ };
54706
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
54707
+ opts.compress = false;
54708
+ }
54709
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
54710
+ }
54711
+ /**
54712
+ * Forcibly close the connection.
54713
+ *
54714
+ * @public
54715
+ */
54716
+ terminate() {
54717
+ if (this.readyState === _WebSocket.CLOSED) return;
54718
+ if (this.readyState === _WebSocket.CONNECTING) {
54719
+ const msg = "WebSocket was closed before the connection was established";
54720
+ abortHandshake(this, this._req, msg);
54721
+ return;
54722
+ }
54723
+ if (this._socket) {
54724
+ this._readyState = _WebSocket.CLOSING;
54725
+ this._socket.destroy();
54726
+ }
54727
+ }
54728
+ };
54729
+ Object.defineProperty(WebSocket2, "CONNECTING", {
54730
+ enumerable: true,
54731
+ value: readyStates.indexOf("CONNECTING")
54732
+ });
54733
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
54734
+ enumerable: true,
54735
+ value: readyStates.indexOf("CONNECTING")
54736
+ });
54737
+ Object.defineProperty(WebSocket2, "OPEN", {
54738
+ enumerable: true,
54739
+ value: readyStates.indexOf("OPEN")
54740
+ });
54741
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
54742
+ enumerable: true,
54743
+ value: readyStates.indexOf("OPEN")
54744
+ });
54745
+ Object.defineProperty(WebSocket2, "CLOSING", {
54746
+ enumerable: true,
54747
+ value: readyStates.indexOf("CLOSING")
54748
+ });
54749
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
54750
+ enumerable: true,
54751
+ value: readyStates.indexOf("CLOSING")
54752
+ });
54753
+ Object.defineProperty(WebSocket2, "CLOSED", {
54754
+ enumerable: true,
54755
+ value: readyStates.indexOf("CLOSED")
54756
+ });
54757
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
54758
+ enumerable: true,
54759
+ value: readyStates.indexOf("CLOSED")
54760
+ });
54761
+ [
54762
+ "binaryType",
54763
+ "bufferedAmount",
54764
+ "extensions",
54765
+ "isPaused",
54766
+ "protocol",
54767
+ "readyState",
54768
+ "url"
54769
+ ].forEach((property) => {
54770
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
54771
+ });
54772
+ ["open", "error", "close", "message"].forEach((method) => {
54773
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
54774
+ enumerable: true,
54775
+ get() {
54776
+ for (const listener of this.listeners(method)) {
54777
+ if (listener[kForOnEventAttribute]) return listener[kListener];
54778
+ }
54779
+ return null;
54780
+ },
54781
+ set(handler) {
54782
+ for (const listener of this.listeners(method)) {
54783
+ if (listener[kForOnEventAttribute]) {
54784
+ this.removeListener(method, listener);
54785
+ break;
54786
+ }
54787
+ }
54788
+ if (typeof handler !== "function") return;
54789
+ this.addEventListener(method, handler, {
54790
+ [kForOnEventAttribute]: true
54791
+ });
54792
+ }
54793
+ });
54794
+ });
54795
+ WebSocket2.prototype.addEventListener = addEventListener2;
54796
+ WebSocket2.prototype.removeEventListener = removeEventListener;
54797
+ module.exports = WebSocket2;
54798
+ function initAsClient(websocket, address, protocols, options) {
54799
+ const opts = {
54800
+ allowSynchronousEvents: true,
54801
+ autoPong: true,
54802
+ protocolVersion: protocolVersions[1],
54803
+ maxPayload: 100 * 1024 * 1024,
54804
+ skipUTF8Validation: false,
54805
+ perMessageDeflate: true,
54806
+ followRedirects: false,
54807
+ maxRedirects: 10,
54808
+ ...options,
54809
+ socketPath: void 0,
54810
+ hostname: void 0,
54811
+ protocol: void 0,
54812
+ timeout: void 0,
54813
+ method: "GET",
54814
+ host: void 0,
54815
+ path: void 0,
54816
+ port: void 0
54817
+ };
54818
+ websocket._autoPong = opts.autoPong;
54819
+ if (!protocolVersions.includes(opts.protocolVersion)) {
54820
+ throw new RangeError(
54821
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
54822
+ );
54823
+ }
54824
+ let parsedUrl;
54825
+ if (address instanceof URL2) {
54826
+ parsedUrl = address;
54827
+ } else {
54828
+ try {
54829
+ parsedUrl = new URL2(address);
54830
+ } catch (e2) {
54831
+ throw new SyntaxError(`Invalid URL: ${address}`);
54832
+ }
54833
+ }
54834
+ if (parsedUrl.protocol === "http:") {
54835
+ parsedUrl.protocol = "ws:";
54836
+ } else if (parsedUrl.protocol === "https:") {
54837
+ parsedUrl.protocol = "wss:";
54838
+ }
54839
+ websocket._url = parsedUrl.href;
54840
+ const isSecure = parsedUrl.protocol === "wss:";
54841
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
54842
+ let invalidUrlMessage;
54843
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
54844
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`;
54845
+ } else if (isIpcUrl && !parsedUrl.pathname) {
54846
+ invalidUrlMessage = "The URL's pathname is empty";
54847
+ } else if (parsedUrl.hash) {
54848
+ invalidUrlMessage = "The URL contains a fragment identifier";
54849
+ }
54850
+ if (invalidUrlMessage) {
54851
+ const err = new SyntaxError(invalidUrlMessage);
54852
+ if (websocket._redirects === 0) {
54853
+ throw err;
54854
+ } else {
54855
+ emitErrorAndClose(websocket, err);
54856
+ return;
54857
+ }
54858
+ }
54859
+ const defaultPort = isSecure ? 443 : 80;
54860
+ const key = randomBytes(16).toString("base64");
54861
+ const request = isSecure ? https.request : http.request;
54862
+ const protocolSet = /* @__PURE__ */ new Set();
54863
+ let perMessageDeflate;
54864
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
54865
+ opts.defaultPort = opts.defaultPort || defaultPort;
54866
+ opts.port = parsedUrl.port || defaultPort;
54867
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
54868
+ opts.headers = {
54869
+ ...opts.headers,
54870
+ "Sec-WebSocket-Version": opts.protocolVersion,
54871
+ "Sec-WebSocket-Key": key,
54872
+ Connection: "Upgrade",
54873
+ Upgrade: "websocket"
54874
+ };
54875
+ opts.path = parsedUrl.pathname + parsedUrl.search;
54876
+ opts.timeout = opts.handshakeTimeout;
54877
+ if (opts.perMessageDeflate) {
54878
+ perMessageDeflate = new PerMessageDeflate(
54879
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
54880
+ false,
54881
+ opts.maxPayload
54882
+ );
54883
+ opts.headers["Sec-WebSocket-Extensions"] = format2({
54884
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
54885
+ });
54886
+ }
54887
+ if (protocols.length) {
54888
+ for (const protocol of protocols) {
54889
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
54890
+ throw new SyntaxError(
54891
+ "An invalid or duplicated subprotocol was specified"
54892
+ );
54893
+ }
54894
+ protocolSet.add(protocol);
54895
+ }
54896
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
54897
+ }
54898
+ if (opts.origin) {
54899
+ if (opts.protocolVersion < 13) {
54900
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
54901
+ } else {
54902
+ opts.headers.Origin = opts.origin;
54903
+ }
54904
+ }
54905
+ if (parsedUrl.username || parsedUrl.password) {
54906
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
54907
+ }
54908
+ if (isIpcUrl) {
54909
+ const parts = opts.path.split(":");
54910
+ opts.socketPath = parts[0];
54911
+ opts.path = parts[1];
54912
+ }
54913
+ let req;
54914
+ if (opts.followRedirects) {
54915
+ if (websocket._redirects === 0) {
54916
+ websocket._originalIpc = isIpcUrl;
54917
+ websocket._originalSecure = isSecure;
54918
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
54919
+ const headers = options && options.headers;
54920
+ options = { ...options, headers: {} };
54921
+ if (headers) {
54922
+ for (const [key2, value2] of Object.entries(headers)) {
54923
+ options.headers[key2.toLowerCase()] = value2;
54924
+ }
54925
+ }
54926
+ } else if (websocket.listenerCount("redirect") === 0) {
54927
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
54928
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
54929
+ delete opts.headers.authorization;
54930
+ delete opts.headers.cookie;
54931
+ if (!isSameHost) delete opts.headers.host;
54932
+ opts.auth = void 0;
54933
+ }
54934
+ }
54935
+ if (opts.auth && !options.headers.authorization) {
54936
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
54937
+ }
54938
+ req = websocket._req = request(opts);
54939
+ if (websocket._redirects) {
54940
+ websocket.emit("redirect", websocket.url, req);
54941
+ }
54942
+ } else {
54943
+ req = websocket._req = request(opts);
54944
+ }
54945
+ if (opts.timeout) {
54946
+ req.on("timeout", () => {
54947
+ abortHandshake(websocket, req, "Opening handshake has timed out");
54948
+ });
54949
+ }
54950
+ req.on("error", (err) => {
54951
+ if (req === null || req[kAborted]) return;
54952
+ req = websocket._req = null;
54953
+ emitErrorAndClose(websocket, err);
54954
+ });
54955
+ req.on("response", (res) => {
54956
+ const location = res.headers.location;
54957
+ const statusCode = res.statusCode;
54958
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
54959
+ if (++websocket._redirects > opts.maxRedirects) {
54960
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
54961
+ return;
54962
+ }
54963
+ req.abort();
54964
+ let addr;
54965
+ try {
54966
+ addr = new URL2(location, address);
54967
+ } catch (e2) {
54968
+ const err = new SyntaxError(`Invalid URL: ${location}`);
54969
+ emitErrorAndClose(websocket, err);
54970
+ return;
54971
+ }
54972
+ initAsClient(websocket, addr, protocols, options);
54973
+ } else if (!websocket.emit("unexpected-response", req, res)) {
54974
+ abortHandshake(
54975
+ websocket,
54976
+ req,
54977
+ `Unexpected server response: ${res.statusCode}`
54978
+ );
54979
+ }
54980
+ });
54981
+ req.on("upgrade", (res, socket, head) => {
54982
+ websocket.emit("upgrade", res);
54983
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
54984
+ req = websocket._req = null;
54985
+ const upgrade = res.headers.upgrade;
54986
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
54987
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
54988
+ return;
54989
+ }
54990
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
54991
+ if (res.headers["sec-websocket-accept"] !== digest) {
54992
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
54993
+ return;
54994
+ }
54995
+ const serverProt = res.headers["sec-websocket-protocol"];
54996
+ let protError;
54997
+ if (serverProt !== void 0) {
54998
+ if (!protocolSet.size) {
54999
+ protError = "Server sent a subprotocol but none was requested";
55000
+ } else if (!protocolSet.has(serverProt)) {
55001
+ protError = "Server sent an invalid subprotocol";
55002
+ }
55003
+ } else if (protocolSet.size) {
55004
+ protError = "Server sent no subprotocol";
55005
+ }
55006
+ if (protError) {
55007
+ abortHandshake(websocket, socket, protError);
55008
+ return;
55009
+ }
55010
+ if (serverProt) websocket._protocol = serverProt;
55011
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
55012
+ if (secWebSocketExtensions !== void 0) {
55013
+ if (!perMessageDeflate) {
55014
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
55015
+ abortHandshake(websocket, socket, message);
55016
+ return;
55017
+ }
55018
+ let extensions;
55019
+ try {
55020
+ extensions = parse(secWebSocketExtensions);
55021
+ } catch (err) {
55022
+ const message = "Invalid Sec-WebSocket-Extensions header";
55023
+ abortHandshake(websocket, socket, message);
55024
+ return;
55025
+ }
55026
+ const extensionNames = Object.keys(extensions);
55027
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
55028
+ const message = "Server indicated an extension that was not requested";
55029
+ abortHandshake(websocket, socket, message);
55030
+ return;
55031
+ }
55032
+ try {
55033
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
55034
+ } catch (err) {
55035
+ const message = "Invalid Sec-WebSocket-Extensions header";
55036
+ abortHandshake(websocket, socket, message);
55037
+ return;
55038
+ }
55039
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
55040
+ }
55041
+ websocket.setSocket(socket, head, {
55042
+ allowSynchronousEvents: opts.allowSynchronousEvents,
55043
+ generateMask: opts.generateMask,
55044
+ maxPayload: opts.maxPayload,
55045
+ skipUTF8Validation: opts.skipUTF8Validation
55046
+ });
55047
+ });
55048
+ if (opts.finishRequest) {
55049
+ opts.finishRequest(req, websocket);
55050
+ } else {
55051
+ req.end();
55052
+ }
55053
+ }
55054
+ function emitErrorAndClose(websocket, err) {
55055
+ websocket._readyState = WebSocket2.CLOSING;
55056
+ websocket._errorEmitted = true;
55057
+ websocket.emit("error", err);
55058
+ websocket.emitClose();
55059
+ }
55060
+ function netConnect(options) {
55061
+ options.path = options.socketPath;
55062
+ return net.connect(options);
55063
+ }
55064
+ function tlsConnect(options) {
55065
+ options.path = void 0;
55066
+ if (!options.servername && options.servername !== "") {
55067
+ options.servername = net.isIP(options.host) ? "" : options.host;
55068
+ }
55069
+ return tls.connect(options);
55070
+ }
55071
+ function abortHandshake(websocket, stream, message) {
55072
+ websocket._readyState = WebSocket2.CLOSING;
55073
+ const err = new Error(message);
55074
+ Error.captureStackTrace(err, abortHandshake);
55075
+ if (stream.setHeader) {
55076
+ stream[kAborted] = true;
55077
+ stream.abort();
55078
+ if (stream.socket && !stream.socket.destroyed) {
55079
+ stream.socket.destroy();
55080
+ }
55081
+ process.nextTick(emitErrorAndClose, websocket, err);
55082
+ } else {
55083
+ stream.destroy(err);
55084
+ stream.once("error", websocket.emit.bind(websocket, "error"));
55085
+ stream.once("close", websocket.emitClose.bind(websocket));
55086
+ }
55087
+ }
55088
+ function sendAfterClose(websocket, data, cb) {
55089
+ if (data) {
55090
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
55091
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
55092
+ else websocket._bufferedAmount += length;
55093
+ }
55094
+ if (cb) {
55095
+ const err = new Error(
55096
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
55097
+ );
55098
+ process.nextTick(cb, err);
55099
+ }
55100
+ }
55101
+ function receiverOnConclude(code, reason) {
55102
+ const websocket = this[kWebSocket];
55103
+ websocket._closeFrameReceived = true;
55104
+ websocket._closeMessage = reason;
55105
+ websocket._closeCode = code;
55106
+ if (websocket._socket[kWebSocket] === void 0) return;
55107
+ websocket._socket.removeListener("data", socketOnData);
55108
+ process.nextTick(resume, websocket._socket);
55109
+ if (code === 1005) websocket.close();
55110
+ else websocket.close(code, reason);
55111
+ }
55112
+ function receiverOnDrain() {
55113
+ const websocket = this[kWebSocket];
55114
+ if (!websocket.isPaused) websocket._socket.resume();
55115
+ }
55116
+ function receiverOnError(err) {
55117
+ const websocket = this[kWebSocket];
55118
+ if (websocket._socket[kWebSocket] !== void 0) {
55119
+ websocket._socket.removeListener("data", socketOnData);
55120
+ process.nextTick(resume, websocket._socket);
55121
+ websocket.close(err[kStatusCode]);
55122
+ }
55123
+ if (!websocket._errorEmitted) {
55124
+ websocket._errorEmitted = true;
55125
+ websocket.emit("error", err);
55126
+ }
55127
+ }
55128
+ function receiverOnFinish() {
55129
+ this[kWebSocket].emitClose();
55130
+ }
55131
+ function receiverOnMessage(data, isBinary) {
55132
+ this[kWebSocket].emit("message", data, isBinary);
55133
+ }
55134
+ function receiverOnPing(data) {
55135
+ const websocket = this[kWebSocket];
55136
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
55137
+ websocket.emit("ping", data);
55138
+ }
55139
+ function receiverOnPong(data) {
55140
+ this[kWebSocket].emit("pong", data);
55141
+ }
55142
+ function resume(stream) {
55143
+ stream.resume();
55144
+ }
55145
+ function senderOnError(err) {
55146
+ const websocket = this[kWebSocket];
55147
+ if (websocket.readyState === WebSocket2.CLOSED) return;
55148
+ if (websocket.readyState === WebSocket2.OPEN) {
55149
+ websocket._readyState = WebSocket2.CLOSING;
55150
+ setCloseTimer(websocket);
55151
+ }
55152
+ this._socket.end();
55153
+ if (!websocket._errorEmitted) {
55154
+ websocket._errorEmitted = true;
55155
+ websocket.emit("error", err);
55156
+ }
55157
+ }
55158
+ function setCloseTimer(websocket) {
55159
+ websocket._closeTimer = setTimeout(
55160
+ websocket._socket.destroy.bind(websocket._socket),
55161
+ closeTimeout
55162
+ );
55163
+ }
55164
+ function socketOnClose() {
55165
+ const websocket = this[kWebSocket];
55166
+ this.removeListener("close", socketOnClose);
55167
+ this.removeListener("data", socketOnData);
55168
+ this.removeListener("end", socketOnEnd);
55169
+ websocket._readyState = WebSocket2.CLOSING;
55170
+ let chunk;
55171
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
55172
+ websocket._receiver.write(chunk);
55173
+ }
55174
+ websocket._receiver.end();
55175
+ this[kWebSocket] = void 0;
55176
+ clearTimeout(websocket._closeTimer);
55177
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
55178
+ websocket.emitClose();
55179
+ } else {
55180
+ websocket._receiver.on("error", receiverOnFinish);
55181
+ websocket._receiver.on("finish", receiverOnFinish);
55182
+ }
55183
+ }
55184
+ function socketOnData(chunk) {
55185
+ if (!this[kWebSocket]._receiver.write(chunk)) {
55186
+ this.pause();
55187
+ }
55188
+ }
55189
+ function socketOnEnd() {
55190
+ const websocket = this[kWebSocket];
55191
+ websocket._readyState = WebSocket2.CLOSING;
55192
+ websocket._receiver.end();
55193
+ this.end();
55194
+ }
55195
+ function socketOnError() {
55196
+ const websocket = this[kWebSocket];
55197
+ this.removeListener("error", socketOnError);
55198
+ this.on("error", NOOP);
55199
+ if (websocket) {
55200
+ websocket._readyState = WebSocket2.CLOSING;
55201
+ this.destroy();
55202
+ }
55203
+ }
55204
+ }
55205
+ });
55206
+
55207
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/stream.js
55208
+ var require_stream = __commonJS({
55209
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/stream.js"(exports, module) {
55210
+ "use strict";
55211
+ init_esm_shims();
55212
+ var WebSocket2 = require_websocket();
55213
+ var { Duplex: Duplex4 } = __require("stream");
55214
+ function emitClose(stream) {
55215
+ stream.emit("close");
55216
+ }
55217
+ function duplexOnEnd() {
55218
+ if (!this.destroyed && this._writableState.finished) {
55219
+ this.destroy();
55220
+ }
55221
+ }
55222
+ function duplexOnError(err) {
55223
+ this.removeListener("error", duplexOnError);
55224
+ this.destroy();
55225
+ if (this.listenerCount("error") === 0) {
55226
+ this.emit("error", err);
55227
+ }
55228
+ }
55229
+ function createWebSocketStream2(ws, options) {
55230
+ let terminateOnDestroy = true;
55231
+ const duplex2 = new Duplex4({
55232
+ ...options,
55233
+ autoDestroy: false,
55234
+ emitClose: false,
55235
+ objectMode: false,
55236
+ writableObjectMode: false
55237
+ });
55238
+ ws.on("message", function message(msg, isBinary) {
55239
+ const data = !isBinary && duplex2._readableState.objectMode ? msg.toString() : msg;
55240
+ if (!duplex2.push(data)) ws.pause();
55241
+ });
55242
+ ws.once("error", function error(err) {
55243
+ if (duplex2.destroyed) return;
55244
+ terminateOnDestroy = false;
55245
+ duplex2.destroy(err);
55246
+ });
55247
+ ws.once("close", function close() {
55248
+ if (duplex2.destroyed) return;
55249
+ duplex2.push(null);
55250
+ });
55251
+ duplex2._destroy = function(err, callback) {
55252
+ if (ws.readyState === ws.CLOSED) {
55253
+ callback(err);
55254
+ process.nextTick(emitClose, duplex2);
55255
+ return;
55256
+ }
55257
+ let called = false;
55258
+ ws.once("error", function error(err2) {
55259
+ called = true;
55260
+ callback(err2);
55261
+ });
55262
+ ws.once("close", function close() {
55263
+ if (!called) callback(err);
55264
+ process.nextTick(emitClose, duplex2);
55265
+ });
55266
+ if (terminateOnDestroy) ws.terminate();
55267
+ };
55268
+ duplex2._final = function(callback) {
55269
+ if (ws.readyState === ws.CONNECTING) {
55270
+ ws.once("open", function open() {
55271
+ duplex2._final(callback);
55272
+ });
55273
+ return;
55274
+ }
55275
+ if (ws._socket === null) return;
55276
+ if (ws._socket._writableState.finished) {
55277
+ callback();
55278
+ if (duplex2._readableState.endEmitted) duplex2.destroy();
55279
+ } else {
55280
+ ws._socket.once("finish", function finish() {
55281
+ callback();
55282
+ });
55283
+ ws.close();
55284
+ }
55285
+ };
55286
+ duplex2._read = function() {
55287
+ if (ws.isPaused) ws.resume();
55288
+ };
55289
+ duplex2._write = function(chunk, encoding, callback) {
55290
+ if (ws.readyState === ws.CONNECTING) {
55291
+ ws.once("open", function open() {
55292
+ duplex2._write(chunk, encoding, callback);
55293
+ });
55294
+ return;
55295
+ }
55296
+ ws.send(chunk, callback);
55297
+ };
55298
+ duplex2.on("end", duplexOnEnd);
55299
+ duplex2.on("error", duplexOnError);
55300
+ return duplex2;
55301
+ }
55302
+ module.exports = createWebSocketStream2;
55303
+ }
55304
+ });
55305
+
55306
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/subprotocol.js
55307
+ var require_subprotocol = __commonJS({
55308
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/subprotocol.js"(exports, module) {
55309
+ "use strict";
55310
+ init_esm_shims();
55311
+ var { tokenChars } = require_validation();
55312
+ function parse(header) {
55313
+ const protocols = /* @__PURE__ */ new Set();
55314
+ let start = -1;
55315
+ let end = -1;
55316
+ let i2 = 0;
55317
+ for (i2; i2 < header.length; i2++) {
55318
+ const code = header.charCodeAt(i2);
55319
+ if (end === -1 && tokenChars[code] === 1) {
55320
+ if (start === -1) start = i2;
55321
+ } else if (i2 !== 0 && (code === 32 || code === 9)) {
55322
+ if (end === -1 && start !== -1) end = i2;
55323
+ } else if (code === 44) {
55324
+ if (start === -1) {
55325
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
55326
+ }
55327
+ if (end === -1) end = i2;
55328
+ const protocol2 = header.slice(start, end);
55329
+ if (protocols.has(protocol2)) {
55330
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
55331
+ }
55332
+ protocols.add(protocol2);
55333
+ start = end = -1;
55334
+ } else {
55335
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
55336
+ }
55337
+ }
55338
+ if (start === -1 || end !== -1) {
55339
+ throw new SyntaxError("Unexpected end of input");
55340
+ }
55341
+ const protocol = header.slice(start, i2);
55342
+ if (protocols.has(protocol)) {
55343
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
55344
+ }
55345
+ protocols.add(protocol);
55346
+ return protocols;
55347
+ }
55348
+ module.exports = { parse };
55349
+ }
55350
+ });
55351
+
55352
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/websocket-server.js
55353
+ var require_websocket_server = __commonJS({
55354
+ "../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/lib/websocket-server.js"(exports, module) {
55355
+ "use strict";
55356
+ init_esm_shims();
55357
+ var EventEmitter2 = __require("events");
55358
+ var http = __require("http");
55359
+ var { Duplex: Duplex4 } = __require("stream");
55360
+ var { createHash } = __require("crypto");
55361
+ var extension = require_extension();
55362
+ var PerMessageDeflate = require_permessage_deflate();
55363
+ var subprotocol = require_subprotocol();
55364
+ var WebSocket2 = require_websocket();
55365
+ var { GUID, kWebSocket } = require_constants2();
55366
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
55367
+ var RUNNING = 0;
55368
+ var CLOSING = 1;
55369
+ var CLOSED = 2;
55370
+ var WebSocketServer2 = class extends EventEmitter2 {
55371
+ /**
55372
+ * Create a `WebSocketServer` instance.
55373
+ *
55374
+ * @param {Object} options Configuration options
55375
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
55376
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
55377
+ * multiple times in the same tick
55378
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
55379
+ * automatically send a pong in response to a ping
55380
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
55381
+ * pending connections
55382
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
55383
+ * track clients
55384
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
55385
+ * @param {String} [options.host] The hostname where to bind the server
55386
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
55387
+ * size
55388
+ * @param {Boolean} [options.noServer=false] Enable no server mode
55389
+ * @param {String} [options.path] Accept only connections matching this path
55390
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
55391
+ * permessage-deflate
55392
+ * @param {Number} [options.port] The port where to bind the server
55393
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
55394
+ * server to use
55395
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
55396
+ * not to skip UTF-8 validation for text and close messages
55397
+ * @param {Function} [options.verifyClient] A hook to reject connections
55398
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
55399
+ * class to use. It must be the `WebSocket` class or class that extends it
55400
+ * @param {Function} [callback] A listener for the `listening` event
55401
+ */
55402
+ constructor(options, callback) {
55403
+ super();
55404
+ options = {
55405
+ allowSynchronousEvents: true,
55406
+ autoPong: true,
55407
+ maxPayload: 100 * 1024 * 1024,
55408
+ skipUTF8Validation: false,
55409
+ perMessageDeflate: false,
55410
+ handleProtocols: null,
55411
+ clientTracking: true,
55412
+ verifyClient: null,
55413
+ noServer: false,
55414
+ backlog: null,
55415
+ // use default (511 as implemented in net.js)
55416
+ server: null,
55417
+ host: null,
55418
+ path: null,
55419
+ port: null,
55420
+ WebSocket: WebSocket2,
55421
+ ...options
55422
+ };
55423
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
55424
+ throw new TypeError(
55425
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
55426
+ );
55427
+ }
55428
+ if (options.port != null) {
55429
+ this._server = http.createServer((req, res) => {
55430
+ const body = http.STATUS_CODES[426];
55431
+ res.writeHead(426, {
55432
+ "Content-Length": body.length,
55433
+ "Content-Type": "text/plain"
55434
+ });
55435
+ res.end(body);
55436
+ });
55437
+ this._server.listen(
55438
+ options.port,
55439
+ options.host,
55440
+ options.backlog,
55441
+ callback
55442
+ );
55443
+ } else if (options.server) {
55444
+ this._server = options.server;
55445
+ }
55446
+ if (this._server) {
55447
+ const emitConnection = this.emit.bind(this, "connection");
55448
+ this._removeListeners = addListeners(this._server, {
55449
+ listening: this.emit.bind(this, "listening"),
55450
+ error: this.emit.bind(this, "error"),
55451
+ upgrade: (req, socket, head) => {
55452
+ this.handleUpgrade(req, socket, head, emitConnection);
55453
+ }
55454
+ });
55455
+ }
55456
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
55457
+ if (options.clientTracking) {
55458
+ this.clients = /* @__PURE__ */ new Set();
55459
+ this._shouldEmitClose = false;
55460
+ }
55461
+ this.options = options;
55462
+ this._state = RUNNING;
55463
+ }
55464
+ /**
55465
+ * Returns the bound address, the address family name, and port of the server
55466
+ * as reported by the operating system if listening on an IP socket.
55467
+ * If the server is listening on a pipe or UNIX domain socket, the name is
55468
+ * returned as a string.
55469
+ *
55470
+ * @return {(Object|String|null)} The address of the server
55471
+ * @public
55472
+ */
55473
+ address() {
55474
+ if (this.options.noServer) {
55475
+ throw new Error('The server is operating in "noServer" mode');
55476
+ }
55477
+ if (!this._server) return null;
55478
+ return this._server.address();
55479
+ }
55480
+ /**
55481
+ * Stop the server from accepting new connections and emit the `'close'` event
55482
+ * when all existing connections are closed.
55483
+ *
55484
+ * @param {Function} [cb] A one-time listener for the `'close'` event
55485
+ * @public
55486
+ */
55487
+ close(cb) {
55488
+ if (this._state === CLOSED) {
55489
+ if (cb) {
55490
+ this.once("close", () => {
55491
+ cb(new Error("The server is not running"));
55492
+ });
55493
+ }
55494
+ process.nextTick(emitClose, this);
55495
+ return;
55496
+ }
55497
+ if (cb) this.once("close", cb);
55498
+ if (this._state === CLOSING) return;
55499
+ this._state = CLOSING;
55500
+ if (this.options.noServer || this.options.server) {
55501
+ if (this._server) {
55502
+ this._removeListeners();
55503
+ this._removeListeners = this._server = null;
55504
+ }
55505
+ if (this.clients) {
55506
+ if (!this.clients.size) {
55507
+ process.nextTick(emitClose, this);
55508
+ } else {
55509
+ this._shouldEmitClose = true;
55510
+ }
55511
+ } else {
55512
+ process.nextTick(emitClose, this);
55513
+ }
55514
+ } else {
55515
+ const server = this._server;
55516
+ this._removeListeners();
55517
+ this._removeListeners = this._server = null;
55518
+ server.close(() => {
55519
+ emitClose(this);
55520
+ });
55521
+ }
55522
+ }
55523
+ /**
55524
+ * See if a given request should be handled by this server instance.
55525
+ *
55526
+ * @param {http.IncomingMessage} req Request object to inspect
55527
+ * @return {Boolean} `true` if the request is valid, else `false`
55528
+ * @public
55529
+ */
55530
+ shouldHandle(req) {
55531
+ if (this.options.path) {
55532
+ const index = req.url.indexOf("?");
55533
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
55534
+ if (pathname !== this.options.path) return false;
55535
+ }
55536
+ return true;
55537
+ }
55538
+ /**
55539
+ * Handle a HTTP Upgrade request.
55540
+ *
55541
+ * @param {http.IncomingMessage} req The request object
55542
+ * @param {Duplex} socket The network socket between the server and client
55543
+ * @param {Buffer} head The first packet of the upgraded stream
55544
+ * @param {Function} cb Callback
55545
+ * @public
55546
+ */
55547
+ handleUpgrade(req, socket, head, cb) {
55548
+ socket.on("error", socketOnError);
55549
+ const key = req.headers["sec-websocket-key"];
55550
+ const upgrade = req.headers.upgrade;
55551
+ const version = +req.headers["sec-websocket-version"];
55552
+ if (req.method !== "GET") {
55553
+ const message = "Invalid HTTP method";
55554
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
55555
+ return;
55556
+ }
55557
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
55558
+ const message = "Invalid Upgrade header";
55559
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
55560
+ return;
55561
+ }
55562
+ if (key === void 0 || !keyRegex.test(key)) {
55563
+ const message = "Missing or invalid Sec-WebSocket-Key header";
55564
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
55565
+ return;
55566
+ }
55567
+ if (version !== 8 && version !== 13) {
55568
+ const message = "Missing or invalid Sec-WebSocket-Version header";
55569
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
55570
+ return;
55571
+ }
55572
+ if (!this.shouldHandle(req)) {
55573
+ abortHandshake(socket, 400);
55574
+ return;
55575
+ }
55576
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
55577
+ let protocols = /* @__PURE__ */ new Set();
55578
+ if (secWebSocketProtocol !== void 0) {
55579
+ try {
55580
+ protocols = subprotocol.parse(secWebSocketProtocol);
55581
+ } catch (err) {
55582
+ const message = "Invalid Sec-WebSocket-Protocol header";
55583
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
55584
+ return;
55585
+ }
55586
+ }
55587
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
55588
+ const extensions = {};
55589
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
55590
+ const perMessageDeflate = new PerMessageDeflate(
55591
+ this.options.perMessageDeflate,
55592
+ true,
55593
+ this.options.maxPayload
55594
+ );
55595
+ try {
55596
+ const offers = extension.parse(secWebSocketExtensions);
55597
+ if (offers[PerMessageDeflate.extensionName]) {
55598
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
55599
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
55600
+ }
55601
+ } catch (err) {
55602
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
55603
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
55604
+ return;
55605
+ }
55606
+ }
55607
+ if (this.options.verifyClient) {
55608
+ const info = {
55609
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
55610
+ secure: !!(req.socket.authorized || req.socket.encrypted),
55611
+ req
55612
+ };
55613
+ if (this.options.verifyClient.length === 2) {
55614
+ this.options.verifyClient(info, (verified, code, message, headers) => {
55615
+ if (!verified) {
55616
+ return abortHandshake(socket, code || 401, message, headers);
55617
+ }
55618
+ this.completeUpgrade(
55619
+ extensions,
55620
+ key,
55621
+ protocols,
55622
+ req,
55623
+ socket,
55624
+ head,
55625
+ cb
55626
+ );
55627
+ });
55628
+ return;
55629
+ }
55630
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
55631
+ }
55632
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
55633
+ }
55634
+ /**
55635
+ * Upgrade the connection to WebSocket.
55636
+ *
55637
+ * @param {Object} extensions The accepted extensions
55638
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
55639
+ * @param {Set} protocols The subprotocols
55640
+ * @param {http.IncomingMessage} req The request object
55641
+ * @param {Duplex} socket The network socket between the server and client
55642
+ * @param {Buffer} head The first packet of the upgraded stream
55643
+ * @param {Function} cb Callback
55644
+ * @throws {Error} If called more than once with the same socket
55645
+ * @private
55646
+ */
55647
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
55648
+ if (!socket.readable || !socket.writable) return socket.destroy();
55649
+ if (socket[kWebSocket]) {
55650
+ throw new Error(
55651
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
55652
+ );
55653
+ }
55654
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
55655
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
55656
+ const headers = [
55657
+ "HTTP/1.1 101 Switching Protocols",
55658
+ "Upgrade: websocket",
55659
+ "Connection: Upgrade",
55660
+ `Sec-WebSocket-Accept: ${digest}`
55661
+ ];
55662
+ const ws = new this.options.WebSocket(null, void 0, this.options);
55663
+ if (protocols.size) {
55664
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
55665
+ if (protocol) {
55666
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
55667
+ ws._protocol = protocol;
55668
+ }
55669
+ }
55670
+ if (extensions[PerMessageDeflate.extensionName]) {
55671
+ const params = extensions[PerMessageDeflate.extensionName].params;
55672
+ const value2 = extension.format({
55673
+ [PerMessageDeflate.extensionName]: [params]
55674
+ });
55675
+ headers.push(`Sec-WebSocket-Extensions: ${value2}`);
55676
+ ws._extensions = extensions;
55677
+ }
55678
+ this.emit("headers", headers, req);
55679
+ socket.write(headers.concat("\r\n").join("\r\n"));
55680
+ socket.removeListener("error", socketOnError);
55681
+ ws.setSocket(socket, head, {
55682
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
55683
+ maxPayload: this.options.maxPayload,
55684
+ skipUTF8Validation: this.options.skipUTF8Validation
55685
+ });
55686
+ if (this.clients) {
55687
+ this.clients.add(ws);
55688
+ ws.on("close", () => {
55689
+ this.clients.delete(ws);
55690
+ if (this._shouldEmitClose && !this.clients.size) {
55691
+ process.nextTick(emitClose, this);
55692
+ }
55693
+ });
55694
+ }
55695
+ cb(ws, req);
55696
+ }
55697
+ };
55698
+ module.exports = WebSocketServer2;
55699
+ function addListeners(server, map) {
55700
+ for (const event of Object.keys(map)) server.on(event, map[event]);
55701
+ return function removeListeners() {
55702
+ for (const event of Object.keys(map)) {
55703
+ server.removeListener(event, map[event]);
55704
+ }
55705
+ };
55706
+ }
55707
+ function emitClose(server) {
55708
+ server._state = CLOSED;
55709
+ server.emit("close");
55710
+ }
55711
+ function socketOnError() {
55712
+ this.destroy();
55713
+ }
55714
+ function abortHandshake(socket, code, message, headers) {
55715
+ message = message || http.STATUS_CODES[code];
55716
+ headers = {
55717
+ Connection: "close",
55718
+ "Content-Type": "text/html",
55719
+ "Content-Length": Buffer.byteLength(message),
55720
+ ...headers
55721
+ };
55722
+ socket.once("finish", socket.destroy);
55723
+ socket.end(
55724
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
55725
+ ` + Object.keys(headers).map((h2) => `${h2}: ${headers[h2]}`).join("\r\n") + "\r\n\r\n" + message
55726
+ );
55727
+ }
55728
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
55729
+ if (server.listenerCount("wsClientError")) {
55730
+ const err = new Error(message);
55731
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
55732
+ server.emit("wsClientError", err, socket, req);
55733
+ } else {
55734
+ abortHandshake(socket, code, message);
55735
+ }
55736
+ }
55737
+ }
55738
+ });
55739
+
52125
55740
  // ../../.yarn/cache/picocolors-npm-1.1.1-b0c45fa35e-e2e3e8170a.zip/node_modules/picocolors/picocolors.js
52126
55741
  var require_picocolors2 = __commonJS({
52127
55742
  "../../.yarn/cache/picocolors-npm-1.1.1-b0c45fa35e-e2e3e8170a.zip/node_modules/picocolors/picocolors.js"(exports, module) {
@@ -52376,7 +55991,7 @@ var Command = class {
52376
55991
  const commandClass = this.constructor;
52377
55992
  const cascade = commandClass.schema;
52378
55993
  if (Array.isArray(cascade)) {
52379
- const { isDict, isUnknown, applyCascade } = await import("./lib-NMFBQRQ2.js");
55994
+ const { isDict, isUnknown, applyCascade } = await import("./lib-GNFDOQZX.js");
52380
55995
  const schema = applyCascade(isDict(isUnknown()), cascade);
52381
55996
  const errors = [];
52382
55997
  const coercions = [];
@@ -55531,7 +59146,7 @@ var npmRunPathEnv = ({ env = process4.env, ...options } = {}) => {
55531
59146
 
55532
59147
  // ../../.yarn/cache/execa-npm-9.5.2-ac35c57136-94782a6282.zip/node_modules/execa/lib/terminate/kill.js
55533
59148
  init_esm_shims();
55534
- import { setTimeout } from "node:timers/promises";
59149
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
55535
59150
 
55536
59151
  // ../../.yarn/cache/execa-npm-9.5.2-ac35c57136-94782a6282.zip/node_modules/execa/lib/return/final-error.js
55537
59152
  init_esm_shims();
@@ -56044,7 +59659,7 @@ var killOnTimeout = async ({ kill, forceKillAfterDelay, context, controllerSigna
56044
59659
  return;
56045
59660
  }
56046
59661
  try {
56047
- await setTimeout(forceKillAfterDelay, void 0, { signal: controllerSignal });
59662
+ await setTimeout2(forceKillAfterDelay, void 0, { signal: controllerSignal });
56048
59663
  if (kill("SIGKILL")) {
56049
59664
  context.isForcefullyTerminated ??= true;
56050
59665
  }
@@ -56683,7 +60298,7 @@ var getReason = ({ reason }) => {
56683
60298
 
56684
60299
  // ../../.yarn/cache/execa-npm-9.5.2-ac35c57136-94782a6282.zip/node_modules/execa/lib/terminate/timeout.js
56685
60300
  init_esm_shims();
56686
- import { setTimeout as setTimeout2 } from "node:timers/promises";
60301
+ import { setTimeout as setTimeout3 } from "node:timers/promises";
56687
60302
  var validateTimeout = ({ timeout }) => {
56688
60303
  if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout < 0)) {
56689
60304
  throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
@@ -56691,7 +60306,7 @@ var validateTimeout = ({ timeout }) => {
56691
60306
  };
56692
60307
  var throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === void 0 ? [] : [killAfterTimeout(subprocess, timeout, context, controller)];
56693
60308
  var killAfterTimeout = async (subprocess, timeout, context, { signal }) => {
56694
- await setTimeout2(timeout, void 0, { signal });
60309
+ await setTimeout3(timeout, void 0, { signal });
56695
60310
  context.terminationReason ??= "timeout";
56696
60311
  subprocess.kill();
56697
60312
  throw new DiscardedError();
@@ -60425,7 +64040,7 @@ init_esm_shims();
60425
64040
 
60426
64041
  // ../../.yarn/cache/execa-npm-9.5.2-ac35c57136-94782a6282.zip/node_modules/execa/lib/io/contents.js
60427
64042
  init_esm_shims();
60428
- import { setImmediate } from "node:timers/promises";
64043
+ import { setImmediate as setImmediate2 } from "node:timers/promises";
60429
64044
 
60430
64045
  // ../../.yarn/cache/execa-npm-9.5.2-ac35c57136-94782a6282.zip/node_modules/execa/lib/io/iterate.js
60431
64046
  init_esm_shims();
@@ -60578,7 +64193,7 @@ var logOutputAsync = async ({ stream, onStreamEnd, fdNumber, encoding, allMixed,
60578
64193
  await logLines(linesIterable, stream, fdNumber, verboseInfo);
60579
64194
  };
60580
64195
  var resumeStream = async (stream) => {
60581
- await setImmediate();
64196
+ await setImmediate2();
60582
64197
  if (stream.readableFlowing === null) {
60583
64198
  stream.resume();
60584
64199
  }
@@ -62324,6 +65939,162 @@ import path9 from "path";
62324
65939
  import { fileURLToPath as fileURLToPath4 } from "url";
62325
65940
  import { transform as transform2 } from "@babel/core";
62326
65941
 
65942
+ // ../../.yarn/__virtual__/@hono-node-ws-virtual-785f464fc0/0/cache/@hono-node-ws-npm-1.1.3-0f8a52633d-8b87483902.zip/node_modules/@hono/node-ws/dist/index.js
65943
+ init_esm_shims();
65944
+
65945
+ // ../../.yarn/__virtual__/ws-virtual-8cab04b328/0/cache/ws-npm-8.18.1-166778b26f-e498965d69.zip/node_modules/ws/wrapper.mjs
65946
+ init_esm_shims();
65947
+ var import_stream4 = __toESM(require_stream(), 1);
65948
+ var import_receiver = __toESM(require_receiver(), 1);
65949
+ var import_sender = __toESM(require_sender(), 1);
65950
+ var import_websocket = __toESM(require_websocket(), 1);
65951
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
65952
+
65953
+ // ../../.yarn/__virtual__/@hono-node-ws-virtual-785f464fc0/0/cache/@hono-node-ws-npm-1.1.3-0f8a52633d-8b87483902.zip/node_modules/@hono/node-ws/dist/index.js
65954
+ var CloseEvent = globalThis.CloseEvent ?? class extends Event {
65955
+ #eventInitDict;
65956
+ constructor(type, eventInitDict = {}) {
65957
+ super(type, eventInitDict);
65958
+ this.#eventInitDict = eventInitDict;
65959
+ }
65960
+ get wasClean() {
65961
+ return this.#eventInitDict.wasClean ?? false;
65962
+ }
65963
+ get code() {
65964
+ return this.#eventInitDict.code ?? 0;
65965
+ }
65966
+ get reason() {
65967
+ return this.#eventInitDict.reason ?? "";
65968
+ }
65969
+ };
65970
+ var createNodeWebSocket = (init) => {
65971
+ const wss = new import_websocket_server.default({ noServer: true });
65972
+ const waiterMap = /* @__PURE__ */ new Map();
65973
+ wss.on("connection", (ws, request) => {
65974
+ const waiter = waiterMap.get(request);
65975
+ if (waiter) {
65976
+ waiter.resolve(ws);
65977
+ waiterMap.delete(request);
65978
+ }
65979
+ });
65980
+ const nodeUpgradeWebSocket = (request, response) => {
65981
+ return new Promise((resolve) => {
65982
+ waiterMap.set(request, { resolve, response });
65983
+ });
65984
+ };
65985
+ return {
65986
+ injectWebSocket(server) {
65987
+ server.on("upgrade", async (request, socket, head) => {
65988
+ const url = new URL(request.url ?? "/", init.baseUrl ?? "http://localhost");
65989
+ const headers = new Headers();
65990
+ for (const key in request.headers) {
65991
+ const value2 = request.headers[key];
65992
+ if (!value2) {
65993
+ continue;
65994
+ }
65995
+ headers.append(key, Array.isArray(value2) ? value2[0] : value2);
65996
+ }
65997
+ const response = await init.app.request(
65998
+ url,
65999
+ { headers },
66000
+ { incoming: request, outgoing: void 0 }
66001
+ );
66002
+ const waiter = waiterMap.get(request);
66003
+ if (!waiter || waiter.response !== response) {
66004
+ socket.end(
66005
+ "HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"
66006
+ );
66007
+ waiterMap.delete(request);
66008
+ return;
66009
+ }
66010
+ wss.handleUpgrade(request, socket, head, (ws) => {
66011
+ wss.emit("connection", ws, request);
66012
+ });
66013
+ });
66014
+ },
66015
+ upgradeWebSocket: (createEvents, options) => async function upgradeWebSocket(c4, next) {
66016
+ if (c4.req.header("upgrade")?.toLowerCase() !== "websocket") {
66017
+ await next();
66018
+ return;
66019
+ }
66020
+ const response = new Response();
66021
+ (async () => {
66022
+ const ws = await nodeUpgradeWebSocket(c4.env.incoming, response);
66023
+ let events;
66024
+ try {
66025
+ events = await createEvents(c4);
66026
+ } catch (e2) {
66027
+ ;
66028
+ (options?.onError ?? console.error)(e2);
66029
+ ws.close();
66030
+ return;
66031
+ }
66032
+ const ctx = {
66033
+ binaryType: "arraybuffer",
66034
+ close(code, reason) {
66035
+ ws.close(code, reason);
66036
+ },
66037
+ protocol: ws.protocol,
66038
+ raw: ws,
66039
+ get readyState() {
66040
+ return ws.readyState;
66041
+ },
66042
+ send(source, opts) {
66043
+ ws.send(source, {
66044
+ compress: opts?.compress
66045
+ });
66046
+ },
66047
+ url: new URL(c4.req.url)
66048
+ };
66049
+ try {
66050
+ events?.onOpen?.(new Event("open"), ctx);
66051
+ } catch (e2) {
66052
+ ;
66053
+ (options?.onError ?? console.error)(e2);
66054
+ }
66055
+ ws.on("message", (data, isBinary) => {
66056
+ const datas = Array.isArray(data) ? data : [data];
66057
+ for (const data2 of datas) {
66058
+ try {
66059
+ events?.onMessage?.(
66060
+ new MessageEvent("message", {
66061
+ data: isBinary ? data2 instanceof ArrayBuffer ? data2 : data2.buffer.slice(data2.byteOffset, data2.byteOffset + data2.byteLength) : data2.toString("utf-8")
66062
+ }),
66063
+ ctx
66064
+ );
66065
+ } catch (e2) {
66066
+ ;
66067
+ (options?.onError ?? console.error)(e2);
66068
+ }
66069
+ }
66070
+ });
66071
+ ws.on("close", (code, reason) => {
66072
+ try {
66073
+ events?.onClose?.(new CloseEvent("close", { code, reason: reason.toString() }), ctx);
66074
+ } catch (e2) {
66075
+ ;
66076
+ (options?.onError ?? console.error)(e2);
66077
+ }
66078
+ });
66079
+ ws.on("error", (error) => {
66080
+ try {
66081
+ events?.onError?.(
66082
+ new ErrorEvent("error", {
66083
+ error
66084
+ }),
66085
+ ctx
66086
+ );
66087
+ } catch (e2) {
66088
+ ;
66089
+ (options?.onError ?? console.error)(e2);
66090
+ }
66091
+ });
66092
+ })();
66093
+ return response;
66094
+ }
66095
+ };
66096
+ };
66097
+
62327
66098
  // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/index.js
62328
66099
  init_esm_shims();
62329
66100
 
@@ -63910,6 +67681,42 @@ var Hono2 = class extends Hono {
63910
67681
  }
63911
67682
  };
63912
67683
 
67684
+ // src/server.ts
67685
+ var import_picocolors3 = __toESM(require_picocolors2(), 1);
67686
+
67687
+ // src/logger/HMRLogger.ts
67688
+ init_esm_shims();
67689
+ var import_picocolors2 = __toESM(require_picocolors2(), 1);
67690
+ function createTag(level) {
67691
+ const baseTag = import_picocolors2.default.bold(import_picocolors2.default.bgCyan(import_picocolors2.default.white(" RN ")));
67692
+ const levelText = import_picocolors2.default.bold(` ${level.toUpperCase()} `);
67693
+ let levelTag = levelText;
67694
+ switch (level) {
67695
+ case "info":
67696
+ levelTag = import_picocolors2.default.bgCyan(import_picocolors2.default.white(levelText));
67697
+ break;
67698
+ case "warn":
67699
+ levelTag = import_picocolors2.default.bgYellow(import_picocolors2.default.white(levelText));
67700
+ break;
67701
+ case "error":
67702
+ levelTag = import_picocolors2.default.bgRed(import_picocolors2.default.white(levelText));
67703
+ break;
67704
+ case "log":
67705
+ levelTag = import_picocolors2.default.bgWhite(import_picocolors2.default.black(levelText));
67706
+ break;
67707
+ default:
67708
+ levelTag = import_picocolors2.default.gray(levelText);
67709
+ break;
67710
+ }
67711
+ return `${baseTag} ${levelTag}`;
67712
+ }
67713
+ function createHMRLogger() {
67714
+ const log = (level, ...data) => {
67715
+ console.log(createTag(level), ...data);
67716
+ };
67717
+ return { log };
67718
+ }
67719
+
63913
67720
  // src/server.ts
63914
67721
  function parsePermissions(permissions) {
63915
67722
  const permissionMap = /* @__PURE__ */ new Map();
@@ -63939,6 +67746,35 @@ function parsePermissions(permissions) {
63939
67746
  }
63940
67747
  return Array.from(permissionMap.entries()).map(([name, accesses]) => `${name}:${Array.from(accesses).sort().join("")}`).sort().join(",");
63941
67748
  }
67749
+ function createWebSocketServer(app) {
67750
+ const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
67751
+ const logger = createHMRLogger();
67752
+ app.get(
67753
+ // End-point for `HMRClient` connection in React Native core.
67754
+ "/hot",
67755
+ upgradeWebSocket(() => ({
67756
+ onMessage(event) {
67757
+ if (typeof event.data !== "string") {
67758
+ return;
67759
+ }
67760
+ const { type, level, data } = JSON.parse(event.data);
67761
+ if (type !== "log") {
67762
+ return;
67763
+ }
67764
+ if (typeof type === "string" && Array.isArray(data)) {
67765
+ logger.log(level, ...data);
67766
+ }
67767
+ },
67768
+ onClose() {
67769
+ logger.log("info", "Device disconnected");
67770
+ },
67771
+ onError(error) {
67772
+ console.error(import_picocolors3.default.red("WebSocket Error"), error);
67773
+ }
67774
+ }))
67775
+ );
67776
+ return { injectWebSocket };
67777
+ }
63942
67778
  var createApp = ({ appName, web, permissions, webViewProps, brand }) => {
63943
67779
  const app = new Hono2();
63944
67780
  const transformCache = /* @__PURE__ */ new Map();
@@ -63997,12 +67833,13 @@ var createApp = ({ appName, web, permissions, webViewProps, brand }) => {
63997
67833
  transformCache.set(key, transformedCode);
63998
67834
  return c4.body(transformedCode);
63999
67835
  });
64000
- return app;
67836
+ const wss = createWebSocketServer(app);
67837
+ return { app, wss };
64001
67838
  };
64002
67839
 
64003
67840
  // src/utils/printLogo.ts
64004
67841
  init_esm_shims();
64005
- var import_picocolors2 = __toESM(require_picocolors2(), 1);
67842
+ var import_picocolors4 = __toESM(require_picocolors2(), 1);
64006
67843
  var LOGO = [
64007
67844
  "\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557",
64008
67845
  "\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2554\u255D",
@@ -64018,7 +67855,7 @@ function printLogo() {
64018
67855
  console.log(LOGO.join("\n"));
64019
67856
  const padding = new Array(Math.floor(maxLength / 2 - GREETING_MESSAGE.length / 2)).fill(" ").join("");
64020
67857
  console.log(`
64021
- ${padding}${import_picocolors2.default.blue(GREETING_MESSAGE)}
67858
+ ${padding}${import_picocolors4.default.blue(GREETING_MESSAGE)}
64022
67859
  `);
64023
67860
  }
64024
67861
 
@@ -64033,8 +67870,8 @@ var DevCommand = class extends Command {
64033
67870
  async execute() {
64034
67871
  const packageRoot = getPackageRoot();
64035
67872
  const config = await loadConfig();
64036
- const app = createApp(config);
64037
- serve(
67873
+ const { app, wss } = createApp(config);
67874
+ const server = serve(
64038
67875
  {
64039
67876
  hostname: "0.0.0.0",
64040
67877
  fetch: app.fetch,
@@ -64051,6 +67888,7 @@ var DevCommand = class extends Command {
64051
67888
  });
64052
67889
  }
64053
67890
  );
67891
+ wss.injectWebSocket(server);
64054
67892
  }
64055
67893
  };
64056
67894