@playcademy/vite-plugin 0.0.1-beta.17 → 0.0.1-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2910 -3
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -41067,6 +41067,7 @@ import { constants, KeyObject as KeyObject3 } from "node:crypto";
41067
41067
  import * as crypto5 from "node:crypto";
41068
41068
  import { promisify } from "node:util";
41069
41069
  import { KeyObject as KeyObject4, createSecretKey } from "node:crypto";
41070
+ import http from "node:http";
41070
41071
  import crypto7 from "node:crypto";
41071
41072
  var __create2 = Object.create;
41072
41073
  var __getProtoOf2 = Object.getPrototypeOf;
@@ -92878,6 +92879,2821 @@ var init_dist2 = __esm(() => {
92878
92879
  console.debug = log3("DEBUG");
92879
92880
  }
92880
92881
  });
92882
+ var require_constants3 = __commonJS2((exports, module2) => {
92883
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
92884
+ var hasBlob = typeof Blob !== "undefined";
92885
+ if (hasBlob)
92886
+ BINARY_TYPES.push("blob");
92887
+ module2.exports = {
92888
+ BINARY_TYPES,
92889
+ EMPTY_BUFFER: Buffer.alloc(0),
92890
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
92891
+ hasBlob,
92892
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
92893
+ kListener: Symbol("kListener"),
92894
+ kStatusCode: Symbol("status-code"),
92895
+ kWebSocket: Symbol("websocket"),
92896
+ NOOP: () => {}
92897
+ };
92898
+ });
92899
+ var require_buffer_util = __commonJS2((exports, module2) => {
92900
+ var { EMPTY_BUFFER } = require_constants3();
92901
+ var FastBuffer = Buffer[Symbol.species];
92902
+ function concat2(list, totalLength) {
92903
+ if (list.length === 0)
92904
+ return EMPTY_BUFFER;
92905
+ if (list.length === 1)
92906
+ return list[0];
92907
+ const target = Buffer.allocUnsafe(totalLength);
92908
+ let offset = 0;
92909
+ for (let i3 = 0;i3 < list.length; i3++) {
92910
+ const buf = list[i3];
92911
+ target.set(buf, offset);
92912
+ offset += buf.length;
92913
+ }
92914
+ if (offset < totalLength) {
92915
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
92916
+ }
92917
+ return target;
92918
+ }
92919
+ function _mask(source, mask, output, offset, length) {
92920
+ for (let i3 = 0;i3 < length; i3++) {
92921
+ output[offset + i3] = source[i3] ^ mask[i3 & 3];
92922
+ }
92923
+ }
92924
+ function _unmask(buffer, mask) {
92925
+ for (let i3 = 0;i3 < buffer.length; i3++) {
92926
+ buffer[i3] ^= mask[i3 & 3];
92927
+ }
92928
+ }
92929
+ function toArrayBuffer(buf) {
92930
+ if (buf.length === buf.buffer.byteLength) {
92931
+ return buf.buffer;
92932
+ }
92933
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
92934
+ }
92935
+ function toBuffer(data) {
92936
+ toBuffer.readOnly = true;
92937
+ if (Buffer.isBuffer(data))
92938
+ return data;
92939
+ let buf;
92940
+ if (data instanceof ArrayBuffer) {
92941
+ buf = new FastBuffer(data);
92942
+ } else if (ArrayBuffer.isView(data)) {
92943
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
92944
+ } else {
92945
+ buf = Buffer.from(data);
92946
+ toBuffer.readOnly = false;
92947
+ }
92948
+ return buf;
92949
+ }
92950
+ module2.exports = {
92951
+ concat: concat2,
92952
+ mask: _mask,
92953
+ toArrayBuffer,
92954
+ toBuffer,
92955
+ unmask: _unmask
92956
+ };
92957
+ if (!process.env.WS_NO_BUFFER_UTIL) {
92958
+ try {
92959
+ const bufferUtil = (() => {
92960
+ throw new Error("Cannot require module bufferutil");
92961
+ })();
92962
+ module2.exports.mask = function(source, mask, output, offset, length) {
92963
+ if (length < 48)
92964
+ _mask(source, mask, output, offset, length);
92965
+ else
92966
+ bufferUtil.mask(source, mask, output, offset, length);
92967
+ };
92968
+ module2.exports.unmask = function(buffer, mask) {
92969
+ if (buffer.length < 32)
92970
+ _unmask(buffer, mask);
92971
+ else
92972
+ bufferUtil.unmask(buffer, mask);
92973
+ };
92974
+ } catch (e) {}
92975
+ }
92976
+ });
92977
+ var require_limiter = __commonJS2((exports, module2) => {
92978
+ var kDone = Symbol("kDone");
92979
+ var kRun = Symbol("kRun");
92980
+
92981
+ class Limiter {
92982
+ constructor(concurrency) {
92983
+ this[kDone] = () => {
92984
+ this.pending--;
92985
+ this[kRun]();
92986
+ };
92987
+ this.concurrency = concurrency || Infinity;
92988
+ this.jobs = [];
92989
+ this.pending = 0;
92990
+ }
92991
+ add(job) {
92992
+ this.jobs.push(job);
92993
+ this[kRun]();
92994
+ }
92995
+ [kRun]() {
92996
+ if (this.pending === this.concurrency)
92997
+ return;
92998
+ if (this.jobs.length) {
92999
+ const job = this.jobs.shift();
93000
+ this.pending++;
93001
+ job(this[kDone]);
93002
+ }
93003
+ }
93004
+ }
93005
+ module2.exports = Limiter;
93006
+ });
93007
+ var require_permessage_deflate = __commonJS2((exports, module2) => {
93008
+ var zlib = __require2("zlib");
93009
+ var bufferUtil = require_buffer_util();
93010
+ var Limiter = require_limiter();
93011
+ var { kStatusCode } = require_constants3();
93012
+ var FastBuffer = Buffer[Symbol.species];
93013
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
93014
+ var kPerMessageDeflate = Symbol("permessage-deflate");
93015
+ var kTotalLength = Symbol("total-length");
93016
+ var kCallback = Symbol("callback");
93017
+ var kBuffers = Symbol("buffers");
93018
+ var kError = Symbol("error");
93019
+ var zlibLimiter;
93020
+
93021
+ class PerMessageDeflate {
93022
+ constructor(options, isServer, maxPayload) {
93023
+ this._maxPayload = maxPayload | 0;
93024
+ this._options = options || {};
93025
+ this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024;
93026
+ this._isServer = !!isServer;
93027
+ this._deflate = null;
93028
+ this._inflate = null;
93029
+ this.params = null;
93030
+ if (!zlibLimiter) {
93031
+ const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10;
93032
+ zlibLimiter = new Limiter(concurrency);
93033
+ }
93034
+ }
93035
+ static get extensionName() {
93036
+ return "permessage-deflate";
93037
+ }
93038
+ offer() {
93039
+ const params = {};
93040
+ if (this._options.serverNoContextTakeover) {
93041
+ params.server_no_context_takeover = true;
93042
+ }
93043
+ if (this._options.clientNoContextTakeover) {
93044
+ params.client_no_context_takeover = true;
93045
+ }
93046
+ if (this._options.serverMaxWindowBits) {
93047
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
93048
+ }
93049
+ if (this._options.clientMaxWindowBits) {
93050
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
93051
+ } else if (this._options.clientMaxWindowBits == null) {
93052
+ params.client_max_window_bits = true;
93053
+ }
93054
+ return params;
93055
+ }
93056
+ accept(configurations) {
93057
+ configurations = this.normalizeParams(configurations);
93058
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
93059
+ return this.params;
93060
+ }
93061
+ cleanup() {
93062
+ if (this._inflate) {
93063
+ this._inflate.close();
93064
+ this._inflate = null;
93065
+ }
93066
+ if (this._deflate) {
93067
+ const callback = this._deflate[kCallback];
93068
+ this._deflate.close();
93069
+ this._deflate = null;
93070
+ if (callback) {
93071
+ callback(new Error("The deflate stream was closed while data was being processed"));
93072
+ }
93073
+ }
93074
+ }
93075
+ acceptAsServer(offers) {
93076
+ const opts = this._options;
93077
+ const accepted = offers.find((params) => {
93078
+ 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) {
93079
+ return false;
93080
+ }
93081
+ return true;
93082
+ });
93083
+ if (!accepted) {
93084
+ throw new Error("None of the extension offers can be accepted");
93085
+ }
93086
+ if (opts.serverNoContextTakeover) {
93087
+ accepted.server_no_context_takeover = true;
93088
+ }
93089
+ if (opts.clientNoContextTakeover) {
93090
+ accepted.client_no_context_takeover = true;
93091
+ }
93092
+ if (typeof opts.serverMaxWindowBits === "number") {
93093
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
93094
+ }
93095
+ if (typeof opts.clientMaxWindowBits === "number") {
93096
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
93097
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
93098
+ delete accepted.client_max_window_bits;
93099
+ }
93100
+ return accepted;
93101
+ }
93102
+ acceptAsClient(response) {
93103
+ const params = response[0];
93104
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
93105
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
93106
+ }
93107
+ if (!params.client_max_window_bits) {
93108
+ if (typeof this._options.clientMaxWindowBits === "number") {
93109
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
93110
+ }
93111
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
93112
+ throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
93113
+ }
93114
+ return params;
93115
+ }
93116
+ normalizeParams(configurations) {
93117
+ configurations.forEach((params) => {
93118
+ Object.keys(params).forEach((key) => {
93119
+ let value = params[key];
93120
+ if (value.length > 1) {
93121
+ throw new Error(`Parameter "${key}" must have only a single value`);
93122
+ }
93123
+ value = value[0];
93124
+ if (key === "client_max_window_bits") {
93125
+ if (value !== true) {
93126
+ const num = +value;
93127
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
93128
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
93129
+ }
93130
+ value = num;
93131
+ } else if (!this._isServer) {
93132
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
93133
+ }
93134
+ } else if (key === "server_max_window_bits") {
93135
+ const num = +value;
93136
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
93137
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
93138
+ }
93139
+ value = num;
93140
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
93141
+ if (value !== true) {
93142
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
93143
+ }
93144
+ } else {
93145
+ throw new Error(`Unknown parameter "${key}"`);
93146
+ }
93147
+ params[key] = value;
93148
+ });
93149
+ });
93150
+ return configurations;
93151
+ }
93152
+ decompress(data, fin, callback) {
93153
+ zlibLimiter.add((done) => {
93154
+ this._decompress(data, fin, (err2, result) => {
93155
+ done();
93156
+ callback(err2, result);
93157
+ });
93158
+ });
93159
+ }
93160
+ compress(data, fin, callback) {
93161
+ zlibLimiter.add((done) => {
93162
+ this._compress(data, fin, (err2, result) => {
93163
+ done();
93164
+ callback(err2, result);
93165
+ });
93166
+ });
93167
+ }
93168
+ _decompress(data, fin, callback) {
93169
+ const endpoint = this._isServer ? "client" : "server";
93170
+ if (!this._inflate) {
93171
+ const key = `${endpoint}_max_window_bits`;
93172
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
93173
+ this._inflate = zlib.createInflateRaw({
93174
+ ...this._options.zlibInflateOptions,
93175
+ windowBits
93176
+ });
93177
+ this._inflate[kPerMessageDeflate] = this;
93178
+ this._inflate[kTotalLength] = 0;
93179
+ this._inflate[kBuffers] = [];
93180
+ this._inflate.on("error", inflateOnError);
93181
+ this._inflate.on("data", inflateOnData);
93182
+ }
93183
+ this._inflate[kCallback] = callback;
93184
+ this._inflate.write(data);
93185
+ if (fin)
93186
+ this._inflate.write(TRAILER);
93187
+ this._inflate.flush(() => {
93188
+ const err2 = this._inflate[kError];
93189
+ if (err2) {
93190
+ this._inflate.close();
93191
+ this._inflate = null;
93192
+ callback(err2);
93193
+ return;
93194
+ }
93195
+ const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
93196
+ if (this._inflate._readableState.endEmitted) {
93197
+ this._inflate.close();
93198
+ this._inflate = null;
93199
+ } else {
93200
+ this._inflate[kTotalLength] = 0;
93201
+ this._inflate[kBuffers] = [];
93202
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
93203
+ this._inflate.reset();
93204
+ }
93205
+ }
93206
+ callback(null, data2);
93207
+ });
93208
+ }
93209
+ _compress(data, fin, callback) {
93210
+ const endpoint = this._isServer ? "server" : "client";
93211
+ if (!this._deflate) {
93212
+ const key = `${endpoint}_max_window_bits`;
93213
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
93214
+ this._deflate = zlib.createDeflateRaw({
93215
+ ...this._options.zlibDeflateOptions,
93216
+ windowBits
93217
+ });
93218
+ this._deflate[kTotalLength] = 0;
93219
+ this._deflate[kBuffers] = [];
93220
+ this._deflate.on("data", deflateOnData);
93221
+ }
93222
+ this._deflate[kCallback] = callback;
93223
+ this._deflate.write(data);
93224
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
93225
+ if (!this._deflate) {
93226
+ return;
93227
+ }
93228
+ let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
93229
+ if (fin) {
93230
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
93231
+ }
93232
+ this._deflate[kCallback] = null;
93233
+ this._deflate[kTotalLength] = 0;
93234
+ this._deflate[kBuffers] = [];
93235
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
93236
+ this._deflate.reset();
93237
+ }
93238
+ callback(null, data2);
93239
+ });
93240
+ }
93241
+ }
93242
+ module2.exports = PerMessageDeflate;
93243
+ function deflateOnData(chunk) {
93244
+ this[kBuffers].push(chunk);
93245
+ this[kTotalLength] += chunk.length;
93246
+ }
93247
+ function inflateOnData(chunk) {
93248
+ this[kTotalLength] += chunk.length;
93249
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
93250
+ this[kBuffers].push(chunk);
93251
+ return;
93252
+ }
93253
+ this[kError] = new RangeError("Max payload size exceeded");
93254
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
93255
+ this[kError][kStatusCode] = 1009;
93256
+ this.removeListener("data", inflateOnData);
93257
+ this.reset();
93258
+ }
93259
+ function inflateOnError(err2) {
93260
+ this[kPerMessageDeflate]._inflate = null;
93261
+ if (this[kError]) {
93262
+ this[kCallback](this[kError]);
93263
+ return;
93264
+ }
93265
+ err2[kStatusCode] = 1007;
93266
+ this[kCallback](err2);
93267
+ }
93268
+ });
93269
+ var require_validation = __commonJS2((exports, module2) => {
93270
+ var { isUtf8 } = __require2("buffer");
93271
+ var { hasBlob } = require_constants3();
93272
+ var tokenChars = [
93273
+ 0,
93274
+ 0,
93275
+ 0,
93276
+ 0,
93277
+ 0,
93278
+ 0,
93279
+ 0,
93280
+ 0,
93281
+ 0,
93282
+ 0,
93283
+ 0,
93284
+ 0,
93285
+ 0,
93286
+ 0,
93287
+ 0,
93288
+ 0,
93289
+ 0,
93290
+ 0,
93291
+ 0,
93292
+ 0,
93293
+ 0,
93294
+ 0,
93295
+ 0,
93296
+ 0,
93297
+ 0,
93298
+ 0,
93299
+ 0,
93300
+ 0,
93301
+ 0,
93302
+ 0,
93303
+ 0,
93304
+ 0,
93305
+ 0,
93306
+ 1,
93307
+ 0,
93308
+ 1,
93309
+ 1,
93310
+ 1,
93311
+ 1,
93312
+ 1,
93313
+ 0,
93314
+ 0,
93315
+ 1,
93316
+ 1,
93317
+ 0,
93318
+ 1,
93319
+ 1,
93320
+ 0,
93321
+ 1,
93322
+ 1,
93323
+ 1,
93324
+ 1,
93325
+ 1,
93326
+ 1,
93327
+ 1,
93328
+ 1,
93329
+ 1,
93330
+ 1,
93331
+ 0,
93332
+ 0,
93333
+ 0,
93334
+ 0,
93335
+ 0,
93336
+ 0,
93337
+ 0,
93338
+ 1,
93339
+ 1,
93340
+ 1,
93341
+ 1,
93342
+ 1,
93343
+ 1,
93344
+ 1,
93345
+ 1,
93346
+ 1,
93347
+ 1,
93348
+ 1,
93349
+ 1,
93350
+ 1,
93351
+ 1,
93352
+ 1,
93353
+ 1,
93354
+ 1,
93355
+ 1,
93356
+ 1,
93357
+ 1,
93358
+ 1,
93359
+ 1,
93360
+ 1,
93361
+ 1,
93362
+ 1,
93363
+ 1,
93364
+ 0,
93365
+ 0,
93366
+ 0,
93367
+ 1,
93368
+ 1,
93369
+ 1,
93370
+ 1,
93371
+ 1,
93372
+ 1,
93373
+ 1,
93374
+ 1,
93375
+ 1,
93376
+ 1,
93377
+ 1,
93378
+ 1,
93379
+ 1,
93380
+ 1,
93381
+ 1,
93382
+ 1,
93383
+ 1,
93384
+ 1,
93385
+ 1,
93386
+ 1,
93387
+ 1,
93388
+ 1,
93389
+ 1,
93390
+ 1,
93391
+ 1,
93392
+ 1,
93393
+ 1,
93394
+ 1,
93395
+ 1,
93396
+ 0,
93397
+ 1,
93398
+ 0,
93399
+ 1,
93400
+ 0
93401
+ ];
93402
+ function isValidStatusCode(code) {
93403
+ return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999;
93404
+ }
93405
+ function _isValidUTF8(buf) {
93406
+ const len = buf.length;
93407
+ let i3 = 0;
93408
+ while (i3 < len) {
93409
+ if ((buf[i3] & 128) === 0) {
93410
+ i3++;
93411
+ } else if ((buf[i3] & 224) === 192) {
93412
+ if (i3 + 1 === len || (buf[i3 + 1] & 192) !== 128 || (buf[i3] & 254) === 192) {
93413
+ return false;
93414
+ }
93415
+ i3 += 2;
93416
+ } else if ((buf[i3] & 240) === 224) {
93417
+ if (i3 + 2 >= len || (buf[i3 + 1] & 192) !== 128 || (buf[i3 + 2] & 192) !== 128 || buf[i3] === 224 && (buf[i3 + 1] & 224) === 128 || buf[i3] === 237 && (buf[i3 + 1] & 224) === 160) {
93418
+ return false;
93419
+ }
93420
+ i3 += 3;
93421
+ } else if ((buf[i3] & 248) === 240) {
93422
+ if (i3 + 3 >= len || (buf[i3 + 1] & 192) !== 128 || (buf[i3 + 2] & 192) !== 128 || (buf[i3 + 3] & 192) !== 128 || buf[i3] === 240 && (buf[i3 + 1] & 240) === 128 || buf[i3] === 244 && buf[i3 + 1] > 143 || buf[i3] > 244) {
93423
+ return false;
93424
+ }
93425
+ i3 += 4;
93426
+ } else {
93427
+ return false;
93428
+ }
93429
+ }
93430
+ return true;
93431
+ }
93432
+ function isBlob(value) {
93433
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
93434
+ }
93435
+ module2.exports = {
93436
+ isBlob,
93437
+ isValidStatusCode,
93438
+ isValidUTF8: _isValidUTF8,
93439
+ tokenChars
93440
+ };
93441
+ if (isUtf8) {
93442
+ module2.exports.isValidUTF8 = function(buf) {
93443
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
93444
+ };
93445
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
93446
+ try {
93447
+ const isValidUTF8 = (() => {
93448
+ throw new Error("Cannot require module utf-8-validate");
93449
+ })();
93450
+ module2.exports.isValidUTF8 = function(buf) {
93451
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
93452
+ };
93453
+ } catch (e) {}
93454
+ }
93455
+ });
93456
+ var require_receiver = __commonJS2((exports, module2) => {
93457
+ var { Writable } = __require2("stream");
93458
+ var PerMessageDeflate = require_permessage_deflate();
93459
+ var {
93460
+ BINARY_TYPES,
93461
+ EMPTY_BUFFER,
93462
+ kStatusCode,
93463
+ kWebSocket
93464
+ } = require_constants3();
93465
+ var { concat: concat2, toArrayBuffer, unmask } = require_buffer_util();
93466
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
93467
+ var FastBuffer = Buffer[Symbol.species];
93468
+ var GET_INFO = 0;
93469
+ var GET_PAYLOAD_LENGTH_16 = 1;
93470
+ var GET_PAYLOAD_LENGTH_64 = 2;
93471
+ var GET_MASK = 3;
93472
+ var GET_DATA = 4;
93473
+ var INFLATING = 5;
93474
+ var DEFER_EVENT = 6;
93475
+
93476
+ class Receiver extends Writable {
93477
+ constructor(options = {}) {
93478
+ super();
93479
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true;
93480
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
93481
+ this._extensions = options.extensions || {};
93482
+ this._isServer = !!options.isServer;
93483
+ this._maxPayload = options.maxPayload | 0;
93484
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
93485
+ this[kWebSocket] = undefined;
93486
+ this._bufferedBytes = 0;
93487
+ this._buffers = [];
93488
+ this._compressed = false;
93489
+ this._payloadLength = 0;
93490
+ this._mask = undefined;
93491
+ this._fragmented = 0;
93492
+ this._masked = false;
93493
+ this._fin = false;
93494
+ this._opcode = 0;
93495
+ this._totalPayloadLength = 0;
93496
+ this._messageLength = 0;
93497
+ this._fragments = [];
93498
+ this._errored = false;
93499
+ this._loop = false;
93500
+ this._state = GET_INFO;
93501
+ }
93502
+ _write(chunk, encoding, cb) {
93503
+ if (this._opcode === 8 && this._state == GET_INFO)
93504
+ return cb();
93505
+ this._bufferedBytes += chunk.length;
93506
+ this._buffers.push(chunk);
93507
+ this.startLoop(cb);
93508
+ }
93509
+ consume(n3) {
93510
+ this._bufferedBytes -= n3;
93511
+ if (n3 === this._buffers[0].length)
93512
+ return this._buffers.shift();
93513
+ if (n3 < this._buffers[0].length) {
93514
+ const buf = this._buffers[0];
93515
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n3, buf.length - n3);
93516
+ return new FastBuffer(buf.buffer, buf.byteOffset, n3);
93517
+ }
93518
+ const dst = Buffer.allocUnsafe(n3);
93519
+ do {
93520
+ const buf = this._buffers[0];
93521
+ const offset = dst.length - n3;
93522
+ if (n3 >= buf.length) {
93523
+ dst.set(this._buffers.shift(), offset);
93524
+ } else {
93525
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n3), offset);
93526
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n3, buf.length - n3);
93527
+ }
93528
+ n3 -= buf.length;
93529
+ } while (n3 > 0);
93530
+ return dst;
93531
+ }
93532
+ startLoop(cb) {
93533
+ this._loop = true;
93534
+ do {
93535
+ switch (this._state) {
93536
+ case GET_INFO:
93537
+ this.getInfo(cb);
93538
+ break;
93539
+ case GET_PAYLOAD_LENGTH_16:
93540
+ this.getPayloadLength16(cb);
93541
+ break;
93542
+ case GET_PAYLOAD_LENGTH_64:
93543
+ this.getPayloadLength64(cb);
93544
+ break;
93545
+ case GET_MASK:
93546
+ this.getMask();
93547
+ break;
93548
+ case GET_DATA:
93549
+ this.getData(cb);
93550
+ break;
93551
+ case INFLATING:
93552
+ case DEFER_EVENT:
93553
+ this._loop = false;
93554
+ return;
93555
+ }
93556
+ } while (this._loop);
93557
+ if (!this._errored)
93558
+ cb();
93559
+ }
93560
+ getInfo(cb) {
93561
+ if (this._bufferedBytes < 2) {
93562
+ this._loop = false;
93563
+ return;
93564
+ }
93565
+ const buf = this.consume(2);
93566
+ if ((buf[0] & 48) !== 0) {
93567
+ const error2 = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3");
93568
+ cb(error2);
93569
+ return;
93570
+ }
93571
+ const compressed = (buf[0] & 64) === 64;
93572
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
93573
+ const error2 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
93574
+ cb(error2);
93575
+ return;
93576
+ }
93577
+ this._fin = (buf[0] & 128) === 128;
93578
+ this._opcode = buf[0] & 15;
93579
+ this._payloadLength = buf[1] & 127;
93580
+ if (this._opcode === 0) {
93581
+ if (compressed) {
93582
+ const error2 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
93583
+ cb(error2);
93584
+ return;
93585
+ }
93586
+ if (!this._fragmented) {
93587
+ const error2 = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE");
93588
+ cb(error2);
93589
+ return;
93590
+ }
93591
+ this._opcode = this._fragmented;
93592
+ } else if (this._opcode === 1 || this._opcode === 2) {
93593
+ if (this._fragmented) {
93594
+ const error2 = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
93595
+ cb(error2);
93596
+ return;
93597
+ }
93598
+ this._compressed = compressed;
93599
+ } else if (this._opcode > 7 && this._opcode < 11) {
93600
+ if (!this._fin) {
93601
+ const error2 = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN");
93602
+ cb(error2);
93603
+ return;
93604
+ }
93605
+ if (compressed) {
93606
+ const error2 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
93607
+ cb(error2);
93608
+ return;
93609
+ }
93610
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
93611
+ const error2 = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");
93612
+ cb(error2);
93613
+ return;
93614
+ }
93615
+ } else {
93616
+ const error2 = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
93617
+ cb(error2);
93618
+ return;
93619
+ }
93620
+ if (!this._fin && !this._fragmented)
93621
+ this._fragmented = this._opcode;
93622
+ this._masked = (buf[1] & 128) === 128;
93623
+ if (this._isServer) {
93624
+ if (!this._masked) {
93625
+ const error2 = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK");
93626
+ cb(error2);
93627
+ return;
93628
+ }
93629
+ } else if (this._masked) {
93630
+ const error2 = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK");
93631
+ cb(error2);
93632
+ return;
93633
+ }
93634
+ if (this._payloadLength === 126)
93635
+ this._state = GET_PAYLOAD_LENGTH_16;
93636
+ else if (this._payloadLength === 127)
93637
+ this._state = GET_PAYLOAD_LENGTH_64;
93638
+ else
93639
+ this.haveLength(cb);
93640
+ }
93641
+ getPayloadLength16(cb) {
93642
+ if (this._bufferedBytes < 2) {
93643
+ this._loop = false;
93644
+ return;
93645
+ }
93646
+ this._payloadLength = this.consume(2).readUInt16BE(0);
93647
+ this.haveLength(cb);
93648
+ }
93649
+ getPayloadLength64(cb) {
93650
+ if (this._bufferedBytes < 8) {
93651
+ this._loop = false;
93652
+ return;
93653
+ }
93654
+ const buf = this.consume(8);
93655
+ const num = buf.readUInt32BE(0);
93656
+ if (num > Math.pow(2, 21) - 1) {
93657
+ const error2 = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");
93658
+ cb(error2);
93659
+ return;
93660
+ }
93661
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
93662
+ this.haveLength(cb);
93663
+ }
93664
+ haveLength(cb) {
93665
+ if (this._payloadLength && this._opcode < 8) {
93666
+ this._totalPayloadLength += this._payloadLength;
93667
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
93668
+ const error2 = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
93669
+ cb(error2);
93670
+ return;
93671
+ }
93672
+ }
93673
+ if (this._masked)
93674
+ this._state = GET_MASK;
93675
+ else
93676
+ this._state = GET_DATA;
93677
+ }
93678
+ getMask() {
93679
+ if (this._bufferedBytes < 4) {
93680
+ this._loop = false;
93681
+ return;
93682
+ }
93683
+ this._mask = this.consume(4);
93684
+ this._state = GET_DATA;
93685
+ }
93686
+ getData(cb) {
93687
+ let data = EMPTY_BUFFER;
93688
+ if (this._payloadLength) {
93689
+ if (this._bufferedBytes < this._payloadLength) {
93690
+ this._loop = false;
93691
+ return;
93692
+ }
93693
+ data = this.consume(this._payloadLength);
93694
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
93695
+ unmask(data, this._mask);
93696
+ }
93697
+ }
93698
+ if (this._opcode > 7) {
93699
+ this.controlMessage(data, cb);
93700
+ return;
93701
+ }
93702
+ if (this._compressed) {
93703
+ this._state = INFLATING;
93704
+ this.decompress(data, cb);
93705
+ return;
93706
+ }
93707
+ if (data.length) {
93708
+ this._messageLength = this._totalPayloadLength;
93709
+ this._fragments.push(data);
93710
+ }
93711
+ this.dataMessage(cb);
93712
+ }
93713
+ decompress(data, cb) {
93714
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
93715
+ perMessageDeflate.decompress(data, this._fin, (err2, buf) => {
93716
+ if (err2)
93717
+ return cb(err2);
93718
+ if (buf.length) {
93719
+ this._messageLength += buf.length;
93720
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
93721
+ const error2 = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
93722
+ cb(error2);
93723
+ return;
93724
+ }
93725
+ this._fragments.push(buf);
93726
+ }
93727
+ this.dataMessage(cb);
93728
+ if (this._state === GET_INFO)
93729
+ this.startLoop(cb);
93730
+ });
93731
+ }
93732
+ dataMessage(cb) {
93733
+ if (!this._fin) {
93734
+ this._state = GET_INFO;
93735
+ return;
93736
+ }
93737
+ const messageLength = this._messageLength;
93738
+ const fragments = this._fragments;
93739
+ this._totalPayloadLength = 0;
93740
+ this._messageLength = 0;
93741
+ this._fragmented = 0;
93742
+ this._fragments = [];
93743
+ if (this._opcode === 2) {
93744
+ let data;
93745
+ if (this._binaryType === "nodebuffer") {
93746
+ data = concat2(fragments, messageLength);
93747
+ } else if (this._binaryType === "arraybuffer") {
93748
+ data = toArrayBuffer(concat2(fragments, messageLength));
93749
+ } else if (this._binaryType === "blob") {
93750
+ data = new Blob(fragments);
93751
+ } else {
93752
+ data = fragments;
93753
+ }
93754
+ if (this._allowSynchronousEvents) {
93755
+ this.emit("message", data, true);
93756
+ this._state = GET_INFO;
93757
+ } else {
93758
+ this._state = DEFER_EVENT;
93759
+ setImmediate(() => {
93760
+ this.emit("message", data, true);
93761
+ this._state = GET_INFO;
93762
+ this.startLoop(cb);
93763
+ });
93764
+ }
93765
+ } else {
93766
+ const buf = concat2(fragments, messageLength);
93767
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
93768
+ const error2 = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
93769
+ cb(error2);
93770
+ return;
93771
+ }
93772
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
93773
+ this.emit("message", buf, false);
93774
+ this._state = GET_INFO;
93775
+ } else {
93776
+ this._state = DEFER_EVENT;
93777
+ setImmediate(() => {
93778
+ this.emit("message", buf, false);
93779
+ this._state = GET_INFO;
93780
+ this.startLoop(cb);
93781
+ });
93782
+ }
93783
+ }
93784
+ }
93785
+ controlMessage(data, cb) {
93786
+ if (this._opcode === 8) {
93787
+ if (data.length === 0) {
93788
+ this._loop = false;
93789
+ this.emit("conclude", 1005, EMPTY_BUFFER);
93790
+ this.end();
93791
+ } else {
93792
+ const code = data.readUInt16BE(0);
93793
+ if (!isValidStatusCode(code)) {
93794
+ const error2 = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE");
93795
+ cb(error2);
93796
+ return;
93797
+ }
93798
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
93799
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
93800
+ const error2 = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
93801
+ cb(error2);
93802
+ return;
93803
+ }
93804
+ this._loop = false;
93805
+ this.emit("conclude", code, buf);
93806
+ this.end();
93807
+ }
93808
+ this._state = GET_INFO;
93809
+ return;
93810
+ }
93811
+ if (this._allowSynchronousEvents) {
93812
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
93813
+ this._state = GET_INFO;
93814
+ } else {
93815
+ this._state = DEFER_EVENT;
93816
+ setImmediate(() => {
93817
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
93818
+ this._state = GET_INFO;
93819
+ this.startLoop(cb);
93820
+ });
93821
+ }
93822
+ }
93823
+ createError(ErrorCtor, message3, prefix2, statusCode, errorCode) {
93824
+ this._loop = false;
93825
+ this._errored = true;
93826
+ const err2 = new ErrorCtor(prefix2 ? `Invalid WebSocket frame: ${message3}` : message3);
93827
+ Error.captureStackTrace(err2, this.createError);
93828
+ err2.code = errorCode;
93829
+ err2[kStatusCode] = statusCode;
93830
+ return err2;
93831
+ }
93832
+ }
93833
+ module2.exports = Receiver;
93834
+ });
93835
+ var require_sender = __commonJS2((exports, module2) => {
93836
+ var { Duplex } = __require2("stream");
93837
+ var { randomFillSync } = __require2("crypto");
93838
+ var PerMessageDeflate = require_permessage_deflate();
93839
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants3();
93840
+ var { isBlob, isValidStatusCode } = require_validation();
93841
+ var { mask: applyMask, toBuffer } = require_buffer_util();
93842
+ var kByteLength = Symbol("kByteLength");
93843
+ var maskBuffer = Buffer.alloc(4);
93844
+ var RANDOM_POOL_SIZE = 8192;
93845
+ var randomPool;
93846
+ var randomPoolPointer = RANDOM_POOL_SIZE;
93847
+ var DEFAULT = 0;
93848
+ var DEFLATING = 1;
93849
+ var GET_BLOB_DATA = 2;
93850
+
93851
+ class Sender {
93852
+ constructor(socket, extensions, generateMask) {
93853
+ this._extensions = extensions || {};
93854
+ if (generateMask) {
93855
+ this._generateMask = generateMask;
93856
+ this._maskBuffer = Buffer.alloc(4);
93857
+ }
93858
+ this._socket = socket;
93859
+ this._firstFragment = true;
93860
+ this._compress = false;
93861
+ this._bufferedBytes = 0;
93862
+ this._queue = [];
93863
+ this._state = DEFAULT;
93864
+ this.onerror = NOOP;
93865
+ this[kWebSocket] = undefined;
93866
+ }
93867
+ static frame(data, options) {
93868
+ let mask;
93869
+ let merge = false;
93870
+ let offset = 2;
93871
+ let skipMasking = false;
93872
+ if (options.mask) {
93873
+ mask = options.maskBuffer || maskBuffer;
93874
+ if (options.generateMask) {
93875
+ options.generateMask(mask);
93876
+ } else {
93877
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
93878
+ if (randomPool === undefined) {
93879
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
93880
+ }
93881
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
93882
+ randomPoolPointer = 0;
93883
+ }
93884
+ mask[0] = randomPool[randomPoolPointer++];
93885
+ mask[1] = randomPool[randomPoolPointer++];
93886
+ mask[2] = randomPool[randomPoolPointer++];
93887
+ mask[3] = randomPool[randomPoolPointer++];
93888
+ }
93889
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
93890
+ offset = 6;
93891
+ }
93892
+ let dataLength;
93893
+ if (typeof data === "string") {
93894
+ if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) {
93895
+ dataLength = options[kByteLength];
93896
+ } else {
93897
+ data = Buffer.from(data);
93898
+ dataLength = data.length;
93899
+ }
93900
+ } else {
93901
+ dataLength = data.length;
93902
+ merge = options.mask && options.readOnly && !skipMasking;
93903
+ }
93904
+ let payloadLength = dataLength;
93905
+ if (dataLength >= 65536) {
93906
+ offset += 8;
93907
+ payloadLength = 127;
93908
+ } else if (dataLength > 125) {
93909
+ offset += 2;
93910
+ payloadLength = 126;
93911
+ }
93912
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
93913
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
93914
+ if (options.rsv1)
93915
+ target[0] |= 64;
93916
+ target[1] = payloadLength;
93917
+ if (payloadLength === 126) {
93918
+ target.writeUInt16BE(dataLength, 2);
93919
+ } else if (payloadLength === 127) {
93920
+ target[2] = target[3] = 0;
93921
+ target.writeUIntBE(dataLength, 4, 6);
93922
+ }
93923
+ if (!options.mask)
93924
+ return [target, data];
93925
+ target[1] |= 128;
93926
+ target[offset - 4] = mask[0];
93927
+ target[offset - 3] = mask[1];
93928
+ target[offset - 2] = mask[2];
93929
+ target[offset - 1] = mask[3];
93930
+ if (skipMasking)
93931
+ return [target, data];
93932
+ if (merge) {
93933
+ applyMask(data, mask, target, offset, dataLength);
93934
+ return [target];
93935
+ }
93936
+ applyMask(data, mask, data, 0, dataLength);
93937
+ return [target, data];
93938
+ }
93939
+ close(code, data, mask, cb) {
93940
+ let buf;
93941
+ if (code === undefined) {
93942
+ buf = EMPTY_BUFFER;
93943
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
93944
+ throw new TypeError("First argument must be a valid error code number");
93945
+ } else if (data === undefined || !data.length) {
93946
+ buf = Buffer.allocUnsafe(2);
93947
+ buf.writeUInt16BE(code, 0);
93948
+ } else {
93949
+ const length = Buffer.byteLength(data);
93950
+ if (length > 123) {
93951
+ throw new RangeError("The message must not be greater than 123 bytes");
93952
+ }
93953
+ buf = Buffer.allocUnsafe(2 + length);
93954
+ buf.writeUInt16BE(code, 0);
93955
+ if (typeof data === "string") {
93956
+ buf.write(data, 2);
93957
+ } else {
93958
+ buf.set(data, 2);
93959
+ }
93960
+ }
93961
+ const options = {
93962
+ [kByteLength]: buf.length,
93963
+ fin: true,
93964
+ generateMask: this._generateMask,
93965
+ mask,
93966
+ maskBuffer: this._maskBuffer,
93967
+ opcode: 8,
93968
+ readOnly: false,
93969
+ rsv1: false
93970
+ };
93971
+ if (this._state !== DEFAULT) {
93972
+ this.enqueue([this.dispatch, buf, false, options, cb]);
93973
+ } else {
93974
+ this.sendFrame(Sender.frame(buf, options), cb);
93975
+ }
93976
+ }
93977
+ ping(data, mask, cb) {
93978
+ let byteLength;
93979
+ let readOnly;
93980
+ if (typeof data === "string") {
93981
+ byteLength = Buffer.byteLength(data);
93982
+ readOnly = false;
93983
+ } else if (isBlob(data)) {
93984
+ byteLength = data.size;
93985
+ readOnly = false;
93986
+ } else {
93987
+ data = toBuffer(data);
93988
+ byteLength = data.length;
93989
+ readOnly = toBuffer.readOnly;
93990
+ }
93991
+ if (byteLength > 125) {
93992
+ throw new RangeError("The data size must not be greater than 125 bytes");
93993
+ }
93994
+ const options = {
93995
+ [kByteLength]: byteLength,
93996
+ fin: true,
93997
+ generateMask: this._generateMask,
93998
+ mask,
93999
+ maskBuffer: this._maskBuffer,
94000
+ opcode: 9,
94001
+ readOnly,
94002
+ rsv1: false
94003
+ };
94004
+ if (isBlob(data)) {
94005
+ if (this._state !== DEFAULT) {
94006
+ this.enqueue([this.getBlobData, data, false, options, cb]);
94007
+ } else {
94008
+ this.getBlobData(data, false, options, cb);
94009
+ }
94010
+ } else if (this._state !== DEFAULT) {
94011
+ this.enqueue([this.dispatch, data, false, options, cb]);
94012
+ } else {
94013
+ this.sendFrame(Sender.frame(data, options), cb);
94014
+ }
94015
+ }
94016
+ pong(data, mask, cb) {
94017
+ let byteLength;
94018
+ let readOnly;
94019
+ if (typeof data === "string") {
94020
+ byteLength = Buffer.byteLength(data);
94021
+ readOnly = false;
94022
+ } else if (isBlob(data)) {
94023
+ byteLength = data.size;
94024
+ readOnly = false;
94025
+ } else {
94026
+ data = toBuffer(data);
94027
+ byteLength = data.length;
94028
+ readOnly = toBuffer.readOnly;
94029
+ }
94030
+ if (byteLength > 125) {
94031
+ throw new RangeError("The data size must not be greater than 125 bytes");
94032
+ }
94033
+ const options = {
94034
+ [kByteLength]: byteLength,
94035
+ fin: true,
94036
+ generateMask: this._generateMask,
94037
+ mask,
94038
+ maskBuffer: this._maskBuffer,
94039
+ opcode: 10,
94040
+ readOnly,
94041
+ rsv1: false
94042
+ };
94043
+ if (isBlob(data)) {
94044
+ if (this._state !== DEFAULT) {
94045
+ this.enqueue([this.getBlobData, data, false, options, cb]);
94046
+ } else {
94047
+ this.getBlobData(data, false, options, cb);
94048
+ }
94049
+ } else if (this._state !== DEFAULT) {
94050
+ this.enqueue([this.dispatch, data, false, options, cb]);
94051
+ } else {
94052
+ this.sendFrame(Sender.frame(data, options), cb);
94053
+ }
94054
+ }
94055
+ send(data, options, cb) {
94056
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
94057
+ let opcode = options.binary ? 2 : 1;
94058
+ let rsv1 = options.compress;
94059
+ let byteLength;
94060
+ let readOnly;
94061
+ if (typeof data === "string") {
94062
+ byteLength = Buffer.byteLength(data);
94063
+ readOnly = false;
94064
+ } else if (isBlob(data)) {
94065
+ byteLength = data.size;
94066
+ readOnly = false;
94067
+ } else {
94068
+ data = toBuffer(data);
94069
+ byteLength = data.length;
94070
+ readOnly = toBuffer.readOnly;
94071
+ }
94072
+ if (this._firstFragment) {
94073
+ this._firstFragment = false;
94074
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
94075
+ rsv1 = byteLength >= perMessageDeflate._threshold;
94076
+ }
94077
+ this._compress = rsv1;
94078
+ } else {
94079
+ rsv1 = false;
94080
+ opcode = 0;
94081
+ }
94082
+ if (options.fin)
94083
+ this._firstFragment = true;
94084
+ const opts = {
94085
+ [kByteLength]: byteLength,
94086
+ fin: options.fin,
94087
+ generateMask: this._generateMask,
94088
+ mask: options.mask,
94089
+ maskBuffer: this._maskBuffer,
94090
+ opcode,
94091
+ readOnly,
94092
+ rsv1
94093
+ };
94094
+ if (isBlob(data)) {
94095
+ if (this._state !== DEFAULT) {
94096
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
94097
+ } else {
94098
+ this.getBlobData(data, this._compress, opts, cb);
94099
+ }
94100
+ } else if (this._state !== DEFAULT) {
94101
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
94102
+ } else {
94103
+ this.dispatch(data, this._compress, opts, cb);
94104
+ }
94105
+ }
94106
+ getBlobData(blob2, compress, options, cb) {
94107
+ this._bufferedBytes += options[kByteLength];
94108
+ this._state = GET_BLOB_DATA;
94109
+ blob2.arrayBuffer().then((arrayBuffer) => {
94110
+ if (this._socket.destroyed) {
94111
+ const err2 = new Error("The socket was closed while the blob was being read");
94112
+ process.nextTick(callCallbacks, this, err2, cb);
94113
+ return;
94114
+ }
94115
+ this._bufferedBytes -= options[kByteLength];
94116
+ const data = toBuffer(arrayBuffer);
94117
+ if (!compress) {
94118
+ this._state = DEFAULT;
94119
+ this.sendFrame(Sender.frame(data, options), cb);
94120
+ this.dequeue();
94121
+ } else {
94122
+ this.dispatch(data, compress, options, cb);
94123
+ }
94124
+ }).catch((err2) => {
94125
+ process.nextTick(onError, this, err2, cb);
94126
+ });
94127
+ }
94128
+ dispatch(data, compress, options, cb) {
94129
+ if (!compress) {
94130
+ this.sendFrame(Sender.frame(data, options), cb);
94131
+ return;
94132
+ }
94133
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
94134
+ this._bufferedBytes += options[kByteLength];
94135
+ this._state = DEFLATING;
94136
+ perMessageDeflate.compress(data, options.fin, (_4, buf) => {
94137
+ if (this._socket.destroyed) {
94138
+ const err2 = new Error("The socket was closed while data was being compressed");
94139
+ callCallbacks(this, err2, cb);
94140
+ return;
94141
+ }
94142
+ this._bufferedBytes -= options[kByteLength];
94143
+ this._state = DEFAULT;
94144
+ options.readOnly = false;
94145
+ this.sendFrame(Sender.frame(buf, options), cb);
94146
+ this.dequeue();
94147
+ });
94148
+ }
94149
+ dequeue() {
94150
+ while (this._state === DEFAULT && this._queue.length) {
94151
+ const params = this._queue.shift();
94152
+ this._bufferedBytes -= params[3][kByteLength];
94153
+ Reflect.apply(params[0], this, params.slice(1));
94154
+ }
94155
+ }
94156
+ enqueue(params) {
94157
+ this._bufferedBytes += params[3][kByteLength];
94158
+ this._queue.push(params);
94159
+ }
94160
+ sendFrame(list, cb) {
94161
+ if (list.length === 2) {
94162
+ this._socket.cork();
94163
+ this._socket.write(list[0]);
94164
+ this._socket.write(list[1], cb);
94165
+ this._socket.uncork();
94166
+ } else {
94167
+ this._socket.write(list[0], cb);
94168
+ }
94169
+ }
94170
+ }
94171
+ module2.exports = Sender;
94172
+ function callCallbacks(sender, err2, cb) {
94173
+ if (typeof cb === "function")
94174
+ cb(err2);
94175
+ for (let i3 = 0;i3 < sender._queue.length; i3++) {
94176
+ const params = sender._queue[i3];
94177
+ const callback = params[params.length - 1];
94178
+ if (typeof callback === "function")
94179
+ callback(err2);
94180
+ }
94181
+ }
94182
+ function onError(sender, err2, cb) {
94183
+ callCallbacks(sender, err2, cb);
94184
+ sender.onerror(err2);
94185
+ }
94186
+ });
94187
+ var require_event_target = __commonJS2((exports, module2) => {
94188
+ var { kForOnEventAttribute, kListener } = require_constants3();
94189
+ var kCode = Symbol("kCode");
94190
+ var kData = Symbol("kData");
94191
+ var kError = Symbol("kError");
94192
+ var kMessage = Symbol("kMessage");
94193
+ var kReason = Symbol("kReason");
94194
+ var kTarget = Symbol("kTarget");
94195
+ var kType = Symbol("kType");
94196
+ var kWasClean = Symbol("kWasClean");
94197
+
94198
+ class Event {
94199
+ constructor(type) {
94200
+ this[kTarget] = null;
94201
+ this[kType] = type;
94202
+ }
94203
+ get target() {
94204
+ return this[kTarget];
94205
+ }
94206
+ get type() {
94207
+ return this[kType];
94208
+ }
94209
+ }
94210
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
94211
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
94212
+
94213
+ class CloseEvent extends Event {
94214
+ constructor(type, options = {}) {
94215
+ super(type);
94216
+ this[kCode] = options.code === undefined ? 0 : options.code;
94217
+ this[kReason] = options.reason === undefined ? "" : options.reason;
94218
+ this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
94219
+ }
94220
+ get code() {
94221
+ return this[kCode];
94222
+ }
94223
+ get reason() {
94224
+ return this[kReason];
94225
+ }
94226
+ get wasClean() {
94227
+ return this[kWasClean];
94228
+ }
94229
+ }
94230
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
94231
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
94232
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
94233
+
94234
+ class ErrorEvent extends Event {
94235
+ constructor(type, options = {}) {
94236
+ super(type);
94237
+ this[kError] = options.error === undefined ? null : options.error;
94238
+ this[kMessage] = options.message === undefined ? "" : options.message;
94239
+ }
94240
+ get error() {
94241
+ return this[kError];
94242
+ }
94243
+ get message() {
94244
+ return this[kMessage];
94245
+ }
94246
+ }
94247
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
94248
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
94249
+
94250
+ class MessageEvent extends Event {
94251
+ constructor(type, options = {}) {
94252
+ super(type);
94253
+ this[kData] = options.data === undefined ? null : options.data;
94254
+ }
94255
+ get data() {
94256
+ return this[kData];
94257
+ }
94258
+ }
94259
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
94260
+ var EventTarget = {
94261
+ addEventListener(type, handler, options = {}) {
94262
+ for (const listener of this.listeners(type)) {
94263
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
94264
+ return;
94265
+ }
94266
+ }
94267
+ let wrapper;
94268
+ if (type === "message") {
94269
+ wrapper = function onMessage(data, isBinary) {
94270
+ const event = new MessageEvent("message", {
94271
+ data: isBinary ? data : data.toString()
94272
+ });
94273
+ event[kTarget] = this;
94274
+ callListener(handler, this, event);
94275
+ };
94276
+ } else if (type === "close") {
94277
+ wrapper = function onClose(code, message3) {
94278
+ const event = new CloseEvent("close", {
94279
+ code,
94280
+ reason: message3.toString(),
94281
+ wasClean: this._closeFrameReceived && this._closeFrameSent
94282
+ });
94283
+ event[kTarget] = this;
94284
+ callListener(handler, this, event);
94285
+ };
94286
+ } else if (type === "error") {
94287
+ wrapper = function onError(error2) {
94288
+ const event = new ErrorEvent("error", {
94289
+ error: error2,
94290
+ message: error2.message
94291
+ });
94292
+ event[kTarget] = this;
94293
+ callListener(handler, this, event);
94294
+ };
94295
+ } else if (type === "open") {
94296
+ wrapper = function onOpen() {
94297
+ const event = new Event("open");
94298
+ event[kTarget] = this;
94299
+ callListener(handler, this, event);
94300
+ };
94301
+ } else {
94302
+ return;
94303
+ }
94304
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
94305
+ wrapper[kListener] = handler;
94306
+ if (options.once) {
94307
+ this.once(type, wrapper);
94308
+ } else {
94309
+ this.on(type, wrapper);
94310
+ }
94311
+ },
94312
+ removeEventListener(type, handler) {
94313
+ for (const listener of this.listeners(type)) {
94314
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
94315
+ this.removeListener(type, listener);
94316
+ break;
94317
+ }
94318
+ }
94319
+ }
94320
+ };
94321
+ module2.exports = {
94322
+ CloseEvent,
94323
+ ErrorEvent,
94324
+ Event,
94325
+ EventTarget,
94326
+ MessageEvent
94327
+ };
94328
+ function callListener(listener, thisArg, event) {
94329
+ if (typeof listener === "object" && listener.handleEvent) {
94330
+ listener.handleEvent.call(listener, event);
94331
+ } else {
94332
+ listener.call(thisArg, event);
94333
+ }
94334
+ }
94335
+ });
94336
+ var require_extension = __commonJS2((exports, module2) => {
94337
+ var { tokenChars } = require_validation();
94338
+ function push(dest, name3, elem) {
94339
+ if (dest[name3] === undefined)
94340
+ dest[name3] = [elem];
94341
+ else
94342
+ dest[name3].push(elem);
94343
+ }
94344
+ function parse2(header) {
94345
+ const offers = Object.create(null);
94346
+ let params = Object.create(null);
94347
+ let mustUnescape = false;
94348
+ let isEscaping = false;
94349
+ let inQuotes = false;
94350
+ let extensionName;
94351
+ let paramName;
94352
+ let start2 = -1;
94353
+ let code = -1;
94354
+ let end = -1;
94355
+ let i3 = 0;
94356
+ for (;i3 < header.length; i3++) {
94357
+ code = header.charCodeAt(i3);
94358
+ if (extensionName === undefined) {
94359
+ if (end === -1 && tokenChars[code] === 1) {
94360
+ if (start2 === -1)
94361
+ start2 = i3;
94362
+ } else if (i3 !== 0 && (code === 32 || code === 9)) {
94363
+ if (end === -1 && start2 !== -1)
94364
+ end = i3;
94365
+ } else if (code === 59 || code === 44) {
94366
+ if (start2 === -1) {
94367
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
94368
+ }
94369
+ if (end === -1)
94370
+ end = i3;
94371
+ const name3 = header.slice(start2, end);
94372
+ if (code === 44) {
94373
+ push(offers, name3, params);
94374
+ params = Object.create(null);
94375
+ } else {
94376
+ extensionName = name3;
94377
+ }
94378
+ start2 = end = -1;
94379
+ } else {
94380
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
94381
+ }
94382
+ } else if (paramName === undefined) {
94383
+ if (end === -1 && tokenChars[code] === 1) {
94384
+ if (start2 === -1)
94385
+ start2 = i3;
94386
+ } else if (code === 32 || code === 9) {
94387
+ if (end === -1 && start2 !== -1)
94388
+ end = i3;
94389
+ } else if (code === 59 || code === 44) {
94390
+ if (start2 === -1) {
94391
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
94392
+ }
94393
+ if (end === -1)
94394
+ end = i3;
94395
+ push(params, header.slice(start2, end), true);
94396
+ if (code === 44) {
94397
+ push(offers, extensionName, params);
94398
+ params = Object.create(null);
94399
+ extensionName = undefined;
94400
+ }
94401
+ start2 = end = -1;
94402
+ } else if (code === 61 && start2 !== -1 && end === -1) {
94403
+ paramName = header.slice(start2, i3);
94404
+ start2 = end = -1;
94405
+ } else {
94406
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
94407
+ }
94408
+ } else {
94409
+ if (isEscaping) {
94410
+ if (tokenChars[code] !== 1) {
94411
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
94412
+ }
94413
+ if (start2 === -1)
94414
+ start2 = i3;
94415
+ else if (!mustUnescape)
94416
+ mustUnescape = true;
94417
+ isEscaping = false;
94418
+ } else if (inQuotes) {
94419
+ if (tokenChars[code] === 1) {
94420
+ if (start2 === -1)
94421
+ start2 = i3;
94422
+ } else if (code === 34 && start2 !== -1) {
94423
+ inQuotes = false;
94424
+ end = i3;
94425
+ } else if (code === 92) {
94426
+ isEscaping = true;
94427
+ } else {
94428
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
94429
+ }
94430
+ } else if (code === 34 && header.charCodeAt(i3 - 1) === 61) {
94431
+ inQuotes = true;
94432
+ } else if (end === -1 && tokenChars[code] === 1) {
94433
+ if (start2 === -1)
94434
+ start2 = i3;
94435
+ } else if (start2 !== -1 && (code === 32 || code === 9)) {
94436
+ if (end === -1)
94437
+ end = i3;
94438
+ } else if (code === 59 || code === 44) {
94439
+ if (start2 === -1) {
94440
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
94441
+ }
94442
+ if (end === -1)
94443
+ end = i3;
94444
+ let value = header.slice(start2, end);
94445
+ if (mustUnescape) {
94446
+ value = value.replace(/\\/g, "");
94447
+ mustUnescape = false;
94448
+ }
94449
+ push(params, paramName, value);
94450
+ if (code === 44) {
94451
+ push(offers, extensionName, params);
94452
+ params = Object.create(null);
94453
+ extensionName = undefined;
94454
+ }
94455
+ paramName = undefined;
94456
+ start2 = end = -1;
94457
+ } else {
94458
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
94459
+ }
94460
+ }
94461
+ }
94462
+ if (start2 === -1 || inQuotes || code === 32 || code === 9) {
94463
+ throw new SyntaxError("Unexpected end of input");
94464
+ }
94465
+ if (end === -1)
94466
+ end = i3;
94467
+ const token = header.slice(start2, end);
94468
+ if (extensionName === undefined) {
94469
+ push(offers, token, params);
94470
+ } else {
94471
+ if (paramName === undefined) {
94472
+ push(params, token, true);
94473
+ } else if (mustUnescape) {
94474
+ push(params, paramName, token.replace(/\\/g, ""));
94475
+ } else {
94476
+ push(params, paramName, token);
94477
+ }
94478
+ push(offers, extensionName, params);
94479
+ }
94480
+ return offers;
94481
+ }
94482
+ function format2(extensions) {
94483
+ return Object.keys(extensions).map((extension) => {
94484
+ let configurations = extensions[extension];
94485
+ if (!Array.isArray(configurations))
94486
+ configurations = [configurations];
94487
+ return configurations.map((params) => {
94488
+ return [extension].concat(Object.keys(params).map((k3) => {
94489
+ let values = params[k3];
94490
+ if (!Array.isArray(values))
94491
+ values = [values];
94492
+ return values.map((v3) => v3 === true ? k3 : `${k3}=${v3}`).join("; ");
94493
+ })).join("; ");
94494
+ }).join(", ");
94495
+ }).join(", ");
94496
+ }
94497
+ module2.exports = { format: format2, parse: parse2 };
94498
+ });
94499
+ var require_websocket = __commonJS2((exports, module2) => {
94500
+ var EventEmitter = __require2("events");
94501
+ var https = __require2("https");
94502
+ var http2 = __require2("http");
94503
+ var net = __require2("net");
94504
+ var tls = __require2("tls");
94505
+ var { randomBytes, createHash } = __require2("crypto");
94506
+ var { Duplex, Readable: Readable2 } = __require2("stream");
94507
+ var { URL: URL2 } = __require2("url");
94508
+ var PerMessageDeflate = require_permessage_deflate();
94509
+ var Receiver = require_receiver();
94510
+ var Sender = require_sender();
94511
+ var { isBlob } = require_validation();
94512
+ var {
94513
+ BINARY_TYPES,
94514
+ EMPTY_BUFFER,
94515
+ GUID,
94516
+ kForOnEventAttribute,
94517
+ kListener,
94518
+ kStatusCode,
94519
+ kWebSocket,
94520
+ NOOP
94521
+ } = require_constants3();
94522
+ var {
94523
+ EventTarget: { addEventListener: addEventListener2, removeEventListener }
94524
+ } = require_event_target();
94525
+ var { format: format2, parse: parse2 } = require_extension();
94526
+ var { toBuffer } = require_buffer_util();
94527
+ var closeTimeout = 30000;
94528
+ var kAborted = Symbol("kAborted");
94529
+ var protocolVersions = [8, 13];
94530
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
94531
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
94532
+
94533
+ class WebSocket2 extends EventEmitter {
94534
+ constructor(address, protocols, options) {
94535
+ super();
94536
+ this._binaryType = BINARY_TYPES[0];
94537
+ this._closeCode = 1006;
94538
+ this._closeFrameReceived = false;
94539
+ this._closeFrameSent = false;
94540
+ this._closeMessage = EMPTY_BUFFER;
94541
+ this._closeTimer = null;
94542
+ this._errorEmitted = false;
94543
+ this._extensions = {};
94544
+ this._paused = false;
94545
+ this._protocol = "";
94546
+ this._readyState = WebSocket2.CONNECTING;
94547
+ this._receiver = null;
94548
+ this._sender = null;
94549
+ this._socket = null;
94550
+ if (address !== null) {
94551
+ this._bufferedAmount = 0;
94552
+ this._isServer = false;
94553
+ this._redirects = 0;
94554
+ if (protocols === undefined) {
94555
+ protocols = [];
94556
+ } else if (!Array.isArray(protocols)) {
94557
+ if (typeof protocols === "object" && protocols !== null) {
94558
+ options = protocols;
94559
+ protocols = [];
94560
+ } else {
94561
+ protocols = [protocols];
94562
+ }
94563
+ }
94564
+ initAsClient(this, address, protocols, options);
94565
+ } else {
94566
+ this._autoPong = options.autoPong;
94567
+ this._isServer = true;
94568
+ }
94569
+ }
94570
+ get binaryType() {
94571
+ return this._binaryType;
94572
+ }
94573
+ set binaryType(type) {
94574
+ if (!BINARY_TYPES.includes(type))
94575
+ return;
94576
+ this._binaryType = type;
94577
+ if (this._receiver)
94578
+ this._receiver._binaryType = type;
94579
+ }
94580
+ get bufferedAmount() {
94581
+ if (!this._socket)
94582
+ return this._bufferedAmount;
94583
+ return this._socket._writableState.length + this._sender._bufferedBytes;
94584
+ }
94585
+ get extensions() {
94586
+ return Object.keys(this._extensions).join();
94587
+ }
94588
+ get isPaused() {
94589
+ return this._paused;
94590
+ }
94591
+ get onclose() {
94592
+ return null;
94593
+ }
94594
+ get onerror() {
94595
+ return null;
94596
+ }
94597
+ get onopen() {
94598
+ return null;
94599
+ }
94600
+ get onmessage() {
94601
+ return null;
94602
+ }
94603
+ get protocol() {
94604
+ return this._protocol;
94605
+ }
94606
+ get readyState() {
94607
+ return this._readyState;
94608
+ }
94609
+ get url() {
94610
+ return this._url;
94611
+ }
94612
+ setSocket(socket, head, options) {
94613
+ const receiver = new Receiver({
94614
+ allowSynchronousEvents: options.allowSynchronousEvents,
94615
+ binaryType: this.binaryType,
94616
+ extensions: this._extensions,
94617
+ isServer: this._isServer,
94618
+ maxPayload: options.maxPayload,
94619
+ skipUTF8Validation: options.skipUTF8Validation
94620
+ });
94621
+ const sender = new Sender(socket, this._extensions, options.generateMask);
94622
+ this._receiver = receiver;
94623
+ this._sender = sender;
94624
+ this._socket = socket;
94625
+ receiver[kWebSocket] = this;
94626
+ sender[kWebSocket] = this;
94627
+ socket[kWebSocket] = this;
94628
+ receiver.on("conclude", receiverOnConclude);
94629
+ receiver.on("drain", receiverOnDrain);
94630
+ receiver.on("error", receiverOnError);
94631
+ receiver.on("message", receiverOnMessage);
94632
+ receiver.on("ping", receiverOnPing);
94633
+ receiver.on("pong", receiverOnPong);
94634
+ sender.onerror = senderOnError;
94635
+ if (socket.setTimeout)
94636
+ socket.setTimeout(0);
94637
+ if (socket.setNoDelay)
94638
+ socket.setNoDelay();
94639
+ if (head.length > 0)
94640
+ socket.unshift(head);
94641
+ socket.on("close", socketOnClose);
94642
+ socket.on("data", socketOnData);
94643
+ socket.on("end", socketOnEnd);
94644
+ socket.on("error", socketOnError);
94645
+ this._readyState = WebSocket2.OPEN;
94646
+ this.emit("open");
94647
+ }
94648
+ emitClose() {
94649
+ if (!this._socket) {
94650
+ this._readyState = WebSocket2.CLOSED;
94651
+ this.emit("close", this._closeCode, this._closeMessage);
94652
+ return;
94653
+ }
94654
+ if (this._extensions[PerMessageDeflate.extensionName]) {
94655
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
94656
+ }
94657
+ this._receiver.removeAllListeners();
94658
+ this._readyState = WebSocket2.CLOSED;
94659
+ this.emit("close", this._closeCode, this._closeMessage);
94660
+ }
94661
+ close(code, data) {
94662
+ if (this.readyState === WebSocket2.CLOSED)
94663
+ return;
94664
+ if (this.readyState === WebSocket2.CONNECTING) {
94665
+ const msg = "WebSocket was closed before the connection was established";
94666
+ abortHandshake(this, this._req, msg);
94667
+ return;
94668
+ }
94669
+ if (this.readyState === WebSocket2.CLOSING) {
94670
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
94671
+ this._socket.end();
94672
+ }
94673
+ return;
94674
+ }
94675
+ this._readyState = WebSocket2.CLOSING;
94676
+ this._sender.close(code, data, !this._isServer, (err2) => {
94677
+ if (err2)
94678
+ return;
94679
+ this._closeFrameSent = true;
94680
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
94681
+ this._socket.end();
94682
+ }
94683
+ });
94684
+ setCloseTimer(this);
94685
+ }
94686
+ pause() {
94687
+ if (this.readyState === WebSocket2.CONNECTING || this.readyState === WebSocket2.CLOSED) {
94688
+ return;
94689
+ }
94690
+ this._paused = true;
94691
+ this._socket.pause();
94692
+ }
94693
+ ping(data, mask, cb) {
94694
+ if (this.readyState === WebSocket2.CONNECTING) {
94695
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
94696
+ }
94697
+ if (typeof data === "function") {
94698
+ cb = data;
94699
+ data = mask = undefined;
94700
+ } else if (typeof mask === "function") {
94701
+ cb = mask;
94702
+ mask = undefined;
94703
+ }
94704
+ if (typeof data === "number")
94705
+ data = data.toString();
94706
+ if (this.readyState !== WebSocket2.OPEN) {
94707
+ sendAfterClose(this, data, cb);
94708
+ return;
94709
+ }
94710
+ if (mask === undefined)
94711
+ mask = !this._isServer;
94712
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
94713
+ }
94714
+ pong(data, mask, cb) {
94715
+ if (this.readyState === WebSocket2.CONNECTING) {
94716
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
94717
+ }
94718
+ if (typeof data === "function") {
94719
+ cb = data;
94720
+ data = mask = undefined;
94721
+ } else if (typeof mask === "function") {
94722
+ cb = mask;
94723
+ mask = undefined;
94724
+ }
94725
+ if (typeof data === "number")
94726
+ data = data.toString();
94727
+ if (this.readyState !== WebSocket2.OPEN) {
94728
+ sendAfterClose(this, data, cb);
94729
+ return;
94730
+ }
94731
+ if (mask === undefined)
94732
+ mask = !this._isServer;
94733
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
94734
+ }
94735
+ resume() {
94736
+ if (this.readyState === WebSocket2.CONNECTING || this.readyState === WebSocket2.CLOSED) {
94737
+ return;
94738
+ }
94739
+ this._paused = false;
94740
+ if (!this._receiver._writableState.needDrain)
94741
+ this._socket.resume();
94742
+ }
94743
+ send(data, options, cb) {
94744
+ if (this.readyState === WebSocket2.CONNECTING) {
94745
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
94746
+ }
94747
+ if (typeof options === "function") {
94748
+ cb = options;
94749
+ options = {};
94750
+ }
94751
+ if (typeof data === "number")
94752
+ data = data.toString();
94753
+ if (this.readyState !== WebSocket2.OPEN) {
94754
+ sendAfterClose(this, data, cb);
94755
+ return;
94756
+ }
94757
+ const opts = {
94758
+ binary: typeof data !== "string",
94759
+ mask: !this._isServer,
94760
+ compress: true,
94761
+ fin: true,
94762
+ ...options
94763
+ };
94764
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
94765
+ opts.compress = false;
94766
+ }
94767
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
94768
+ }
94769
+ terminate() {
94770
+ if (this.readyState === WebSocket2.CLOSED)
94771
+ return;
94772
+ if (this.readyState === WebSocket2.CONNECTING) {
94773
+ const msg = "WebSocket was closed before the connection was established";
94774
+ abortHandshake(this, this._req, msg);
94775
+ return;
94776
+ }
94777
+ if (this._socket) {
94778
+ this._readyState = WebSocket2.CLOSING;
94779
+ this._socket.destroy();
94780
+ }
94781
+ }
94782
+ }
94783
+ Object.defineProperty(WebSocket2, "CONNECTING", {
94784
+ enumerable: true,
94785
+ value: readyStates.indexOf("CONNECTING")
94786
+ });
94787
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
94788
+ enumerable: true,
94789
+ value: readyStates.indexOf("CONNECTING")
94790
+ });
94791
+ Object.defineProperty(WebSocket2, "OPEN", {
94792
+ enumerable: true,
94793
+ value: readyStates.indexOf("OPEN")
94794
+ });
94795
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
94796
+ enumerable: true,
94797
+ value: readyStates.indexOf("OPEN")
94798
+ });
94799
+ Object.defineProperty(WebSocket2, "CLOSING", {
94800
+ enumerable: true,
94801
+ value: readyStates.indexOf("CLOSING")
94802
+ });
94803
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
94804
+ enumerable: true,
94805
+ value: readyStates.indexOf("CLOSING")
94806
+ });
94807
+ Object.defineProperty(WebSocket2, "CLOSED", {
94808
+ enumerable: true,
94809
+ value: readyStates.indexOf("CLOSED")
94810
+ });
94811
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
94812
+ enumerable: true,
94813
+ value: readyStates.indexOf("CLOSED")
94814
+ });
94815
+ [
94816
+ "binaryType",
94817
+ "bufferedAmount",
94818
+ "extensions",
94819
+ "isPaused",
94820
+ "protocol",
94821
+ "readyState",
94822
+ "url"
94823
+ ].forEach((property) => {
94824
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
94825
+ });
94826
+ ["open", "error", "close", "message"].forEach((method) => {
94827
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
94828
+ enumerable: true,
94829
+ get() {
94830
+ for (const listener of this.listeners(method)) {
94831
+ if (listener[kForOnEventAttribute])
94832
+ return listener[kListener];
94833
+ }
94834
+ return null;
94835
+ },
94836
+ set(handler) {
94837
+ for (const listener of this.listeners(method)) {
94838
+ if (listener[kForOnEventAttribute]) {
94839
+ this.removeListener(method, listener);
94840
+ break;
94841
+ }
94842
+ }
94843
+ if (typeof handler !== "function")
94844
+ return;
94845
+ this.addEventListener(method, handler, {
94846
+ [kForOnEventAttribute]: true
94847
+ });
94848
+ }
94849
+ });
94850
+ });
94851
+ WebSocket2.prototype.addEventListener = addEventListener2;
94852
+ WebSocket2.prototype.removeEventListener = removeEventListener;
94853
+ module2.exports = WebSocket2;
94854
+ function initAsClient(websocket, address, protocols, options) {
94855
+ const opts = {
94856
+ allowSynchronousEvents: true,
94857
+ autoPong: true,
94858
+ protocolVersion: protocolVersions[1],
94859
+ maxPayload: 104857600,
94860
+ skipUTF8Validation: false,
94861
+ perMessageDeflate: true,
94862
+ followRedirects: false,
94863
+ maxRedirects: 10,
94864
+ ...options,
94865
+ socketPath: undefined,
94866
+ hostname: undefined,
94867
+ protocol: undefined,
94868
+ timeout: undefined,
94869
+ method: "GET",
94870
+ host: undefined,
94871
+ path: undefined,
94872
+ port: undefined
94873
+ };
94874
+ websocket._autoPong = opts.autoPong;
94875
+ if (!protocolVersions.includes(opts.protocolVersion)) {
94876
+ throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
94877
+ }
94878
+ let parsedUrl;
94879
+ if (address instanceof URL2) {
94880
+ parsedUrl = address;
94881
+ } else {
94882
+ try {
94883
+ parsedUrl = new URL2(address);
94884
+ } catch (e) {
94885
+ throw new SyntaxError(`Invalid URL: ${address}`);
94886
+ }
94887
+ }
94888
+ if (parsedUrl.protocol === "http:") {
94889
+ parsedUrl.protocol = "ws:";
94890
+ } else if (parsedUrl.protocol === "https:") {
94891
+ parsedUrl.protocol = "wss:";
94892
+ }
94893
+ websocket._url = parsedUrl.href;
94894
+ const isSecure = parsedUrl.protocol === "wss:";
94895
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
94896
+ let invalidUrlMessage;
94897
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
94898
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
94899
+ } else if (isIpcUrl && !parsedUrl.pathname) {
94900
+ invalidUrlMessage = "The URL's pathname is empty";
94901
+ } else if (parsedUrl.hash) {
94902
+ invalidUrlMessage = "The URL contains a fragment identifier";
94903
+ }
94904
+ if (invalidUrlMessage) {
94905
+ const err2 = new SyntaxError(invalidUrlMessage);
94906
+ if (websocket._redirects === 0) {
94907
+ throw err2;
94908
+ } else {
94909
+ emitErrorAndClose(websocket, err2);
94910
+ return;
94911
+ }
94912
+ }
94913
+ const defaultPort = isSecure ? 443 : 80;
94914
+ const key = randomBytes(16).toString("base64");
94915
+ const request = isSecure ? https.request : http2.request;
94916
+ const protocolSet = new Set;
94917
+ let perMessageDeflate;
94918
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
94919
+ opts.defaultPort = opts.defaultPort || defaultPort;
94920
+ opts.port = parsedUrl.port || defaultPort;
94921
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
94922
+ opts.headers = {
94923
+ ...opts.headers,
94924
+ "Sec-WebSocket-Version": opts.protocolVersion,
94925
+ "Sec-WebSocket-Key": key,
94926
+ Connection: "Upgrade",
94927
+ Upgrade: "websocket"
94928
+ };
94929
+ opts.path = parsedUrl.pathname + parsedUrl.search;
94930
+ opts.timeout = opts.handshakeTimeout;
94931
+ if (opts.perMessageDeflate) {
94932
+ perMessageDeflate = new PerMessageDeflate(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
94933
+ opts.headers["Sec-WebSocket-Extensions"] = format2({
94934
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
94935
+ });
94936
+ }
94937
+ if (protocols.length) {
94938
+ for (const protocol of protocols) {
94939
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
94940
+ throw new SyntaxError("An invalid or duplicated subprotocol was specified");
94941
+ }
94942
+ protocolSet.add(protocol);
94943
+ }
94944
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
94945
+ }
94946
+ if (opts.origin) {
94947
+ if (opts.protocolVersion < 13) {
94948
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
94949
+ } else {
94950
+ opts.headers.Origin = opts.origin;
94951
+ }
94952
+ }
94953
+ if (parsedUrl.username || parsedUrl.password) {
94954
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
94955
+ }
94956
+ if (isIpcUrl) {
94957
+ const parts2 = opts.path.split(":");
94958
+ opts.socketPath = parts2[0];
94959
+ opts.path = parts2[1];
94960
+ }
94961
+ let req;
94962
+ if (opts.followRedirects) {
94963
+ if (websocket._redirects === 0) {
94964
+ websocket._originalIpc = isIpcUrl;
94965
+ websocket._originalSecure = isSecure;
94966
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
94967
+ const headers = options && options.headers;
94968
+ options = { ...options, headers: {} };
94969
+ if (headers) {
94970
+ for (const [key2, value] of Object.entries(headers)) {
94971
+ options.headers[key2.toLowerCase()] = value;
94972
+ }
94973
+ }
94974
+ } else if (websocket.listenerCount("redirect") === 0) {
94975
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
94976
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
94977
+ delete opts.headers.authorization;
94978
+ delete opts.headers.cookie;
94979
+ if (!isSameHost)
94980
+ delete opts.headers.host;
94981
+ opts.auth = undefined;
94982
+ }
94983
+ }
94984
+ if (opts.auth && !options.headers.authorization) {
94985
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
94986
+ }
94987
+ req = websocket._req = request(opts);
94988
+ if (websocket._redirects) {
94989
+ websocket.emit("redirect", websocket.url, req);
94990
+ }
94991
+ } else {
94992
+ req = websocket._req = request(opts);
94993
+ }
94994
+ if (opts.timeout) {
94995
+ req.on("timeout", () => {
94996
+ abortHandshake(websocket, req, "Opening handshake has timed out");
94997
+ });
94998
+ }
94999
+ req.on("error", (err2) => {
95000
+ if (req === null || req[kAborted])
95001
+ return;
95002
+ req = websocket._req = null;
95003
+ emitErrorAndClose(websocket, err2);
95004
+ });
95005
+ req.on("response", (res) => {
95006
+ const location2 = res.headers.location;
95007
+ const statusCode = res.statusCode;
95008
+ if (location2 && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
95009
+ if (++websocket._redirects > opts.maxRedirects) {
95010
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
95011
+ return;
95012
+ }
95013
+ req.abort();
95014
+ let addr2;
95015
+ try {
95016
+ addr2 = new URL2(location2, address);
95017
+ } catch (e) {
95018
+ const err2 = new SyntaxError(`Invalid URL: ${location2}`);
95019
+ emitErrorAndClose(websocket, err2);
95020
+ return;
95021
+ }
95022
+ initAsClient(websocket, addr2, protocols, options);
95023
+ } else if (!websocket.emit("unexpected-response", req, res)) {
95024
+ abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
95025
+ }
95026
+ });
95027
+ req.on("upgrade", (res, socket, head) => {
95028
+ websocket.emit("upgrade", res);
95029
+ if (websocket.readyState !== WebSocket2.CONNECTING)
95030
+ return;
95031
+ req = websocket._req = null;
95032
+ const upgrade = res.headers.upgrade;
95033
+ if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
95034
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
95035
+ return;
95036
+ }
95037
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
95038
+ if (res.headers["sec-websocket-accept"] !== digest) {
95039
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
95040
+ return;
95041
+ }
95042
+ const serverProt = res.headers["sec-websocket-protocol"];
95043
+ let protError;
95044
+ if (serverProt !== undefined) {
95045
+ if (!protocolSet.size) {
95046
+ protError = "Server sent a subprotocol but none was requested";
95047
+ } else if (!protocolSet.has(serverProt)) {
95048
+ protError = "Server sent an invalid subprotocol";
95049
+ }
95050
+ } else if (protocolSet.size) {
95051
+ protError = "Server sent no subprotocol";
95052
+ }
95053
+ if (protError) {
95054
+ abortHandshake(websocket, socket, protError);
95055
+ return;
95056
+ }
95057
+ if (serverProt)
95058
+ websocket._protocol = serverProt;
95059
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
95060
+ if (secWebSocketExtensions !== undefined) {
95061
+ if (!perMessageDeflate) {
95062
+ const message3 = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
95063
+ abortHandshake(websocket, socket, message3);
95064
+ return;
95065
+ }
95066
+ let extensions;
95067
+ try {
95068
+ extensions = parse2(secWebSocketExtensions);
95069
+ } catch (err2) {
95070
+ const message3 = "Invalid Sec-WebSocket-Extensions header";
95071
+ abortHandshake(websocket, socket, message3);
95072
+ return;
95073
+ }
95074
+ const extensionNames = Object.keys(extensions);
95075
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
95076
+ const message3 = "Server indicated an extension that was not requested";
95077
+ abortHandshake(websocket, socket, message3);
95078
+ return;
95079
+ }
95080
+ try {
95081
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
95082
+ } catch (err2) {
95083
+ const message3 = "Invalid Sec-WebSocket-Extensions header";
95084
+ abortHandshake(websocket, socket, message3);
95085
+ return;
95086
+ }
95087
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
95088
+ }
95089
+ websocket.setSocket(socket, head, {
95090
+ allowSynchronousEvents: opts.allowSynchronousEvents,
95091
+ generateMask: opts.generateMask,
95092
+ maxPayload: opts.maxPayload,
95093
+ skipUTF8Validation: opts.skipUTF8Validation
95094
+ });
95095
+ });
95096
+ if (opts.finishRequest) {
95097
+ opts.finishRequest(req, websocket);
95098
+ } else {
95099
+ req.end();
95100
+ }
95101
+ }
95102
+ function emitErrorAndClose(websocket, err2) {
95103
+ websocket._readyState = WebSocket2.CLOSING;
95104
+ websocket._errorEmitted = true;
95105
+ websocket.emit("error", err2);
95106
+ websocket.emitClose();
95107
+ }
95108
+ function netConnect(options) {
95109
+ options.path = options.socketPath;
95110
+ return net.connect(options);
95111
+ }
95112
+ function tlsConnect(options) {
95113
+ options.path = undefined;
95114
+ if (!options.servername && options.servername !== "") {
95115
+ options.servername = net.isIP(options.host) ? "" : options.host;
95116
+ }
95117
+ return tls.connect(options);
95118
+ }
95119
+ function abortHandshake(websocket, stream, message3) {
95120
+ websocket._readyState = WebSocket2.CLOSING;
95121
+ const err2 = new Error(message3);
95122
+ Error.captureStackTrace(err2, abortHandshake);
95123
+ if (stream.setHeader) {
95124
+ stream[kAborted] = true;
95125
+ stream.abort();
95126
+ if (stream.socket && !stream.socket.destroyed) {
95127
+ stream.socket.destroy();
95128
+ }
95129
+ process.nextTick(emitErrorAndClose, websocket, err2);
95130
+ } else {
95131
+ stream.destroy(err2);
95132
+ stream.once("error", websocket.emit.bind(websocket, "error"));
95133
+ stream.once("close", websocket.emitClose.bind(websocket));
95134
+ }
95135
+ }
95136
+ function sendAfterClose(websocket, data, cb) {
95137
+ if (data) {
95138
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
95139
+ if (websocket._socket)
95140
+ websocket._sender._bufferedBytes += length;
95141
+ else
95142
+ websocket._bufferedAmount += length;
95143
+ }
95144
+ if (cb) {
95145
+ const err2 = new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
95146
+ process.nextTick(cb, err2);
95147
+ }
95148
+ }
95149
+ function receiverOnConclude(code, reason) {
95150
+ const websocket = this[kWebSocket];
95151
+ websocket._closeFrameReceived = true;
95152
+ websocket._closeMessage = reason;
95153
+ websocket._closeCode = code;
95154
+ if (websocket._socket[kWebSocket] === undefined)
95155
+ return;
95156
+ websocket._socket.removeListener("data", socketOnData);
95157
+ process.nextTick(resume, websocket._socket);
95158
+ if (code === 1005)
95159
+ websocket.close();
95160
+ else
95161
+ websocket.close(code, reason);
95162
+ }
95163
+ function receiverOnDrain() {
95164
+ const websocket = this[kWebSocket];
95165
+ if (!websocket.isPaused)
95166
+ websocket._socket.resume();
95167
+ }
95168
+ function receiverOnError(err2) {
95169
+ const websocket = this[kWebSocket];
95170
+ if (websocket._socket[kWebSocket] !== undefined) {
95171
+ websocket._socket.removeListener("data", socketOnData);
95172
+ process.nextTick(resume, websocket._socket);
95173
+ websocket.close(err2[kStatusCode]);
95174
+ }
95175
+ if (!websocket._errorEmitted) {
95176
+ websocket._errorEmitted = true;
95177
+ websocket.emit("error", err2);
95178
+ }
95179
+ }
95180
+ function receiverOnFinish() {
95181
+ this[kWebSocket].emitClose();
95182
+ }
95183
+ function receiverOnMessage(data, isBinary) {
95184
+ this[kWebSocket].emit("message", data, isBinary);
95185
+ }
95186
+ function receiverOnPing(data) {
95187
+ const websocket = this[kWebSocket];
95188
+ if (websocket._autoPong)
95189
+ websocket.pong(data, !this._isServer, NOOP);
95190
+ websocket.emit("ping", data);
95191
+ }
95192
+ function receiverOnPong(data) {
95193
+ this[kWebSocket].emit("pong", data);
95194
+ }
95195
+ function resume(stream) {
95196
+ stream.resume();
95197
+ }
95198
+ function senderOnError(err2) {
95199
+ const websocket = this[kWebSocket];
95200
+ if (websocket.readyState === WebSocket2.CLOSED)
95201
+ return;
95202
+ if (websocket.readyState === WebSocket2.OPEN) {
95203
+ websocket._readyState = WebSocket2.CLOSING;
95204
+ setCloseTimer(websocket);
95205
+ }
95206
+ this._socket.end();
95207
+ if (!websocket._errorEmitted) {
95208
+ websocket._errorEmitted = true;
95209
+ websocket.emit("error", err2);
95210
+ }
95211
+ }
95212
+ function setCloseTimer(websocket) {
95213
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), closeTimeout);
95214
+ }
95215
+ function socketOnClose() {
95216
+ const websocket = this[kWebSocket];
95217
+ this.removeListener("close", socketOnClose);
95218
+ this.removeListener("data", socketOnData);
95219
+ this.removeListener("end", socketOnEnd);
95220
+ websocket._readyState = WebSocket2.CLOSING;
95221
+ let chunk;
95222
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
95223
+ websocket._receiver.write(chunk);
95224
+ }
95225
+ websocket._receiver.end();
95226
+ this[kWebSocket] = undefined;
95227
+ clearTimeout(websocket._closeTimer);
95228
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
95229
+ websocket.emitClose();
95230
+ } else {
95231
+ websocket._receiver.on("error", receiverOnFinish);
95232
+ websocket._receiver.on("finish", receiverOnFinish);
95233
+ }
95234
+ }
95235
+ function socketOnData(chunk) {
95236
+ if (!this[kWebSocket]._receiver.write(chunk)) {
95237
+ this.pause();
95238
+ }
95239
+ }
95240
+ function socketOnEnd() {
95241
+ const websocket = this[kWebSocket];
95242
+ websocket._readyState = WebSocket2.CLOSING;
95243
+ websocket._receiver.end();
95244
+ this.end();
95245
+ }
95246
+ function socketOnError() {
95247
+ const websocket = this[kWebSocket];
95248
+ this.removeListener("error", socketOnError);
95249
+ this.on("error", NOOP);
95250
+ if (websocket) {
95251
+ websocket._readyState = WebSocket2.CLOSING;
95252
+ this.destroy();
95253
+ }
95254
+ }
95255
+ });
95256
+ var require_stream5 = __commonJS2((exports, module2) => {
95257
+ var WebSocket2 = require_websocket();
95258
+ var { Duplex } = __require2("stream");
95259
+ function emitClose(stream) {
95260
+ stream.emit("close");
95261
+ }
95262
+ function duplexOnEnd() {
95263
+ if (!this.destroyed && this._writableState.finished) {
95264
+ this.destroy();
95265
+ }
95266
+ }
95267
+ function duplexOnError(err2) {
95268
+ this.removeListener("error", duplexOnError);
95269
+ this.destroy();
95270
+ if (this.listenerCount("error") === 0) {
95271
+ this.emit("error", err2);
95272
+ }
95273
+ }
95274
+ function createWebSocketStream(ws, options) {
95275
+ let terminateOnDestroy = true;
95276
+ const duplex = new Duplex({
95277
+ ...options,
95278
+ autoDestroy: false,
95279
+ emitClose: false,
95280
+ objectMode: false,
95281
+ writableObjectMode: false
95282
+ });
95283
+ ws.on("message", function message(msg, isBinary) {
95284
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
95285
+ if (!duplex.push(data))
95286
+ ws.pause();
95287
+ });
95288
+ ws.once("error", function error(err2) {
95289
+ if (duplex.destroyed)
95290
+ return;
95291
+ terminateOnDestroy = false;
95292
+ duplex.destroy(err2);
95293
+ });
95294
+ ws.once("close", function close() {
95295
+ if (duplex.destroyed)
95296
+ return;
95297
+ duplex.push(null);
95298
+ });
95299
+ duplex._destroy = function(err2, callback) {
95300
+ if (ws.readyState === ws.CLOSED) {
95301
+ callback(err2);
95302
+ process.nextTick(emitClose, duplex);
95303
+ return;
95304
+ }
95305
+ let called = false;
95306
+ ws.once("error", function error(err3) {
95307
+ called = true;
95308
+ callback(err3);
95309
+ });
95310
+ ws.once("close", function close() {
95311
+ if (!called)
95312
+ callback(err2);
95313
+ process.nextTick(emitClose, duplex);
95314
+ });
95315
+ if (terminateOnDestroy)
95316
+ ws.terminate();
95317
+ };
95318
+ duplex._final = function(callback) {
95319
+ if (ws.readyState === ws.CONNECTING) {
95320
+ ws.once("open", function open() {
95321
+ duplex._final(callback);
95322
+ });
95323
+ return;
95324
+ }
95325
+ if (ws._socket === null)
95326
+ return;
95327
+ if (ws._socket._writableState.finished) {
95328
+ callback();
95329
+ if (duplex._readableState.endEmitted)
95330
+ duplex.destroy();
95331
+ } else {
95332
+ ws._socket.once("finish", function finish() {
95333
+ callback();
95334
+ });
95335
+ ws.close();
95336
+ }
95337
+ };
95338
+ duplex._read = function() {
95339
+ if (ws.isPaused)
95340
+ ws.resume();
95341
+ };
95342
+ duplex._write = function(chunk, encoding, callback) {
95343
+ if (ws.readyState === ws.CONNECTING) {
95344
+ ws.once("open", function open() {
95345
+ duplex._write(chunk, encoding, callback);
95346
+ });
95347
+ return;
95348
+ }
95349
+ ws.send(chunk, callback);
95350
+ };
95351
+ duplex.on("end", duplexOnEnd);
95352
+ duplex.on("error", duplexOnError);
95353
+ return duplex;
95354
+ }
95355
+ module2.exports = createWebSocketStream;
95356
+ });
95357
+ var require_subprotocol = __commonJS2((exports, module2) => {
95358
+ var { tokenChars } = require_validation();
95359
+ function parse2(header) {
95360
+ const protocols = new Set;
95361
+ let start2 = -1;
95362
+ let end = -1;
95363
+ let i3 = 0;
95364
+ for (i3;i3 < header.length; i3++) {
95365
+ const code = header.charCodeAt(i3);
95366
+ if (end === -1 && tokenChars[code] === 1) {
95367
+ if (start2 === -1)
95368
+ start2 = i3;
95369
+ } else if (i3 !== 0 && (code === 32 || code === 9)) {
95370
+ if (end === -1 && start2 !== -1)
95371
+ end = i3;
95372
+ } else if (code === 44) {
95373
+ if (start2 === -1) {
95374
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
95375
+ }
95376
+ if (end === -1)
95377
+ end = i3;
95378
+ const protocol2 = header.slice(start2, end);
95379
+ if (protocols.has(protocol2)) {
95380
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
95381
+ }
95382
+ protocols.add(protocol2);
95383
+ start2 = end = -1;
95384
+ } else {
95385
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
95386
+ }
95387
+ }
95388
+ if (start2 === -1 || end !== -1) {
95389
+ throw new SyntaxError("Unexpected end of input");
95390
+ }
95391
+ const protocol = header.slice(start2, i3);
95392
+ if (protocols.has(protocol)) {
95393
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
95394
+ }
95395
+ protocols.add(protocol);
95396
+ return protocols;
95397
+ }
95398
+ module2.exports = { parse: parse2 };
95399
+ });
95400
+ var require_websocket_server = __commonJS2((exports, module2) => {
95401
+ var EventEmitter = __require2("events");
95402
+ var http2 = __require2("http");
95403
+ var { Duplex } = __require2("stream");
95404
+ var { createHash } = __require2("crypto");
95405
+ var extension = require_extension();
95406
+ var PerMessageDeflate = require_permessage_deflate();
95407
+ var subprotocol = require_subprotocol();
95408
+ var WebSocket2 = require_websocket();
95409
+ var { GUID, kWebSocket } = require_constants3();
95410
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
95411
+ var RUNNING = 0;
95412
+ var CLOSING = 1;
95413
+ var CLOSED = 2;
95414
+
95415
+ class WebSocketServer extends EventEmitter {
95416
+ constructor(options, callback) {
95417
+ super();
95418
+ options = {
95419
+ allowSynchronousEvents: true,
95420
+ autoPong: true,
95421
+ maxPayload: 104857600,
95422
+ skipUTF8Validation: false,
95423
+ perMessageDeflate: false,
95424
+ handleProtocols: null,
95425
+ clientTracking: true,
95426
+ verifyClient: null,
95427
+ noServer: false,
95428
+ backlog: null,
95429
+ server: null,
95430
+ host: null,
95431
+ path: null,
95432
+ port: null,
95433
+ WebSocket: WebSocket2,
95434
+ ...options
95435
+ };
95436
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
95437
+ throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');
95438
+ }
95439
+ if (options.port != null) {
95440
+ this._server = http2.createServer((req, res) => {
95441
+ const body2 = http2.STATUS_CODES[426];
95442
+ res.writeHead(426, {
95443
+ "Content-Length": body2.length,
95444
+ "Content-Type": "text/plain"
95445
+ });
95446
+ res.end(body2);
95447
+ });
95448
+ this._server.listen(options.port, options.host, options.backlog, callback);
95449
+ } else if (options.server) {
95450
+ this._server = options.server;
95451
+ }
95452
+ if (this._server) {
95453
+ const emitConnection = this.emit.bind(this, "connection");
95454
+ this._removeListeners = addListeners(this._server, {
95455
+ listening: this.emit.bind(this, "listening"),
95456
+ error: this.emit.bind(this, "error"),
95457
+ upgrade: (req, socket, head) => {
95458
+ this.handleUpgrade(req, socket, head, emitConnection);
95459
+ }
95460
+ });
95461
+ }
95462
+ if (options.perMessageDeflate === true)
95463
+ options.perMessageDeflate = {};
95464
+ if (options.clientTracking) {
95465
+ this.clients = new Set;
95466
+ this._shouldEmitClose = false;
95467
+ }
95468
+ this.options = options;
95469
+ this._state = RUNNING;
95470
+ }
95471
+ address() {
95472
+ if (this.options.noServer) {
95473
+ throw new Error('The server is operating in "noServer" mode');
95474
+ }
95475
+ if (!this._server)
95476
+ return null;
95477
+ return this._server.address();
95478
+ }
95479
+ close(cb) {
95480
+ if (this._state === CLOSED) {
95481
+ if (cb) {
95482
+ this.once("close", () => {
95483
+ cb(new Error("The server is not running"));
95484
+ });
95485
+ }
95486
+ process.nextTick(emitClose, this);
95487
+ return;
95488
+ }
95489
+ if (cb)
95490
+ this.once("close", cb);
95491
+ if (this._state === CLOSING)
95492
+ return;
95493
+ this._state = CLOSING;
95494
+ if (this.options.noServer || this.options.server) {
95495
+ if (this._server) {
95496
+ this._removeListeners();
95497
+ this._removeListeners = this._server = null;
95498
+ }
95499
+ if (this.clients) {
95500
+ if (!this.clients.size) {
95501
+ process.nextTick(emitClose, this);
95502
+ } else {
95503
+ this._shouldEmitClose = true;
95504
+ }
95505
+ } else {
95506
+ process.nextTick(emitClose, this);
95507
+ }
95508
+ } else {
95509
+ const server2 = this._server;
95510
+ this._removeListeners();
95511
+ this._removeListeners = this._server = null;
95512
+ server2.close(() => {
95513
+ emitClose(this);
95514
+ });
95515
+ }
95516
+ }
95517
+ shouldHandle(req) {
95518
+ if (this.options.path) {
95519
+ const index6 = req.url.indexOf("?");
95520
+ const pathname = index6 !== -1 ? req.url.slice(0, index6) : req.url;
95521
+ if (pathname !== this.options.path)
95522
+ return false;
95523
+ }
95524
+ return true;
95525
+ }
95526
+ handleUpgrade(req, socket, head, cb) {
95527
+ socket.on("error", socketOnError);
95528
+ const key = req.headers["sec-websocket-key"];
95529
+ const upgrade = req.headers.upgrade;
95530
+ const version3 = +req.headers["sec-websocket-version"];
95531
+ if (req.method !== "GET") {
95532
+ const message3 = "Invalid HTTP method";
95533
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message3);
95534
+ return;
95535
+ }
95536
+ if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
95537
+ const message3 = "Invalid Upgrade header";
95538
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message3);
95539
+ return;
95540
+ }
95541
+ if (key === undefined || !keyRegex.test(key)) {
95542
+ const message3 = "Missing or invalid Sec-WebSocket-Key header";
95543
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message3);
95544
+ return;
95545
+ }
95546
+ if (version3 !== 8 && version3 !== 13) {
95547
+ const message3 = "Missing or invalid Sec-WebSocket-Version header";
95548
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message3);
95549
+ return;
95550
+ }
95551
+ if (!this.shouldHandle(req)) {
95552
+ abortHandshake(socket, 400);
95553
+ return;
95554
+ }
95555
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
95556
+ let protocols = new Set;
95557
+ if (secWebSocketProtocol !== undefined) {
95558
+ try {
95559
+ protocols = subprotocol.parse(secWebSocketProtocol);
95560
+ } catch (err2) {
95561
+ const message3 = "Invalid Sec-WebSocket-Protocol header";
95562
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message3);
95563
+ return;
95564
+ }
95565
+ }
95566
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
95567
+ const extensions = {};
95568
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) {
95569
+ const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
95570
+ try {
95571
+ const offers = extension.parse(secWebSocketExtensions);
95572
+ if (offers[PerMessageDeflate.extensionName]) {
95573
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
95574
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
95575
+ }
95576
+ } catch (err2) {
95577
+ const message3 = "Invalid or unacceptable Sec-WebSocket-Extensions header";
95578
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message3);
95579
+ return;
95580
+ }
95581
+ }
95582
+ if (this.options.verifyClient) {
95583
+ const info2 = {
95584
+ origin: req.headers[`${version3 === 8 ? "sec-websocket-origin" : "origin"}`],
95585
+ secure: !!(req.socket.authorized || req.socket.encrypted),
95586
+ req
95587
+ };
95588
+ if (this.options.verifyClient.length === 2) {
95589
+ this.options.verifyClient(info2, (verified, code, message3, headers) => {
95590
+ if (!verified) {
95591
+ return abortHandshake(socket, code || 401, message3, headers);
95592
+ }
95593
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
95594
+ });
95595
+ return;
95596
+ }
95597
+ if (!this.options.verifyClient(info2))
95598
+ return abortHandshake(socket, 401);
95599
+ }
95600
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
95601
+ }
95602
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
95603
+ if (!socket.readable || !socket.writable)
95604
+ return socket.destroy();
95605
+ if (socket[kWebSocket]) {
95606
+ throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
95607
+ }
95608
+ if (this._state > RUNNING)
95609
+ return abortHandshake(socket, 503);
95610
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
95611
+ const headers = [
95612
+ "HTTP/1.1 101 Switching Protocols",
95613
+ "Upgrade: websocket",
95614
+ "Connection: Upgrade",
95615
+ `Sec-WebSocket-Accept: ${digest}`
95616
+ ];
95617
+ const ws = new this.options.WebSocket(null, undefined, this.options);
95618
+ if (protocols.size) {
95619
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
95620
+ if (protocol) {
95621
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
95622
+ ws._protocol = protocol;
95623
+ }
95624
+ }
95625
+ if (extensions[PerMessageDeflate.extensionName]) {
95626
+ const params = extensions[PerMessageDeflate.extensionName].params;
95627
+ const value = extension.format({
95628
+ [PerMessageDeflate.extensionName]: [params]
95629
+ });
95630
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
95631
+ ws._extensions = extensions;
95632
+ }
95633
+ this.emit("headers", headers, req);
95634
+ socket.write(headers.concat(`\r
95635
+ `).join(`\r
95636
+ `));
95637
+ socket.removeListener("error", socketOnError);
95638
+ ws.setSocket(socket, head, {
95639
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
95640
+ maxPayload: this.options.maxPayload,
95641
+ skipUTF8Validation: this.options.skipUTF8Validation
95642
+ });
95643
+ if (this.clients) {
95644
+ this.clients.add(ws);
95645
+ ws.on("close", () => {
95646
+ this.clients.delete(ws);
95647
+ if (this._shouldEmitClose && !this.clients.size) {
95648
+ process.nextTick(emitClose, this);
95649
+ }
95650
+ });
95651
+ }
95652
+ cb(ws, req);
95653
+ }
95654
+ }
95655
+ module2.exports = WebSocketServer;
95656
+ function addListeners(server2, map) {
95657
+ for (const event of Object.keys(map))
95658
+ server2.on(event, map[event]);
95659
+ return function removeListeners() {
95660
+ for (const event of Object.keys(map)) {
95661
+ server2.removeListener(event, map[event]);
95662
+ }
95663
+ };
95664
+ }
95665
+ function emitClose(server2) {
95666
+ server2._state = CLOSED;
95667
+ server2.emit("close");
95668
+ }
95669
+ function socketOnError() {
95670
+ this.destroy();
95671
+ }
95672
+ function abortHandshake(socket, code, message3, headers) {
95673
+ message3 = message3 || http2.STATUS_CODES[code];
95674
+ headers = {
95675
+ Connection: "close",
95676
+ "Content-Type": "text/html",
95677
+ "Content-Length": Buffer.byteLength(message3),
95678
+ ...headers
95679
+ };
95680
+ socket.once("finish", socket.destroy);
95681
+ socket.end(`HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r
95682
+ ` + Object.keys(headers).map((h3) => `${h3}: ${headers[h3]}`).join(`\r
95683
+ `) + `\r
95684
+ \r
95685
+ ` + message3);
95686
+ }
95687
+ function abortHandshakeOrEmitwsClientError(server2, req, socket, code, message3) {
95688
+ if (server2.listenerCount("wsClientError")) {
95689
+ const err2 = new Error(message3);
95690
+ Error.captureStackTrace(err2, abortHandshakeOrEmitwsClientError);
95691
+ server2.emit("wsClientError", err2, socket, req);
95692
+ } else {
95693
+ abortHandshake(socket, code, message3);
95694
+ }
95695
+ }
95696
+ });
92881
95697
  var RequestError = class extends Error {
92882
95698
  constructor(message, options) {
92883
95699
  super(message, options);
@@ -94913,7 +97729,7 @@ var logger = (fn = console.log) => {
94913
97729
  };
94914
97730
  var package_default = {
94915
97731
  name: "@playcademy/sandbox",
94916
- version: "0.1.0-beta.13",
97732
+ version: "0.1.0-beta.15",
94917
97733
  description: "Local development server for Playcademy game development",
94918
97734
  type: "module",
94919
97735
  exports: {
@@ -108110,13 +110926,104 @@ async function createRealtimeServer(options = {}) {
108110
110926
  }
108111
110927
  return server;
108112
110928
  }
110929
+ var import_stream2 = __toESM2(require_stream5(), 1);
110930
+ var import_receiver = __toESM2(require_receiver(), 1);
110931
+ var import_sender = __toESM2(require_sender(), 1);
110932
+ var import_websocket = __toESM2(require_websocket(), 1);
110933
+ var import_websocket_server = __toESM2(require_websocket_server(), 1);
110934
+ async function createSandboxRealtimeServer(options = {}) {
110935
+ const config2 = await loadConfig(options);
110936
+ const httpServer = http.createServer((req, res) => {
110937
+ if (req.url?.endsWith(config2.healthCheckPath)) {
110938
+ const body2 = JSON.stringify({
110939
+ status: "OK",
110940
+ connections: getActiveConnections(),
110941
+ timestamp: new Date().toISOString()
110942
+ });
110943
+ res.writeHead(200, { "Content-Type": "application/json" });
110944
+ res.end(body2);
110945
+ return;
110946
+ }
110947
+ res.writeHead(200);
110948
+ res.end("Playcademy realtime relay (sandbox)");
110949
+ });
110950
+ const wss = new import_websocket_server.default({ noServer: true });
110951
+ wss.on("connection", (ws) => {
110952
+ addConnection();
110953
+ ws.on("close", () => {
110954
+ removeConnection();
110955
+ });
110956
+ ws.on("message", (data) => {
110957
+ wss.clients.forEach((client2) => {
110958
+ if (client2.readyState === import_websocket.default.OPEN) {
110959
+ client2.send(data);
110960
+ }
110961
+ });
110962
+ });
110963
+ });
110964
+ httpServer.on("upgrade", async (request, socket, head) => {
110965
+ const fullUrl = `http://${request.headers.host}${request.url}`;
110966
+ const token = extractTokenFromUrl(fullUrl);
110967
+ if (!token) {
110968
+ socket.write(`HTTP/1.1 401 Unauthorized\r
110969
+ \r
110970
+ `);
110971
+ socket.destroy();
110972
+ return;
110973
+ }
110974
+ const authResult = await verifyToken(token, config2.betterAuthSecret);
110975
+ if (!authResult.success) {
110976
+ socket.write(`HTTP/1.1 401 Unauthorized\r
110977
+ \r
110978
+ `);
110979
+ socket.destroy();
110980
+ return;
110981
+ }
110982
+ wss.handleUpgrade(request, socket, head, (ws) => {
110983
+ const data = {
110984
+ userId: authResult.userId,
110985
+ gameId: authResult.gameId,
110986
+ joinedChannels: new Set,
110987
+ requestedChannel: null,
110988
+ isAuthenticated: true
110989
+ };
110990
+ ws.data = data;
110991
+ wss.emit("connection", ws, request);
110992
+ });
110993
+ });
110994
+ await new Promise((resolve2) => {
110995
+ httpServer.listen(config2.port, () => resolve2());
110996
+ });
110997
+ if (!options.quiet) {
110998
+ log2.info("Sandbox realtime server started", {
110999
+ port: config2.port,
111000
+ healthCheck: `http://localhost:${config2.port}${config2.healthCheckPath}`
111001
+ });
111002
+ }
111003
+ return {
111004
+ port: config2.port,
111005
+ stop() {
111006
+ wss.clients.forEach((client2) => client2.close());
111007
+ wss.close();
111008
+ httpServer.close();
111009
+ }
111010
+ };
111011
+ }
108113
111012
  async function startRealtimeServer(realtimeOptions, betterAuthSecret) {
108114
111013
  if (!realtimeOptions.enabled) {
108115
111014
  return null;
108116
111015
  }
108117
111016
  if (typeof Bun === "undefined") {
108118
- console.warn("[sandbox] Bun runtime not detected – realtime server disabled.");
108119
- return null;
111017
+ try {
111018
+ return await createSandboxRealtimeServer({
111019
+ port: realtimeOptions.port,
111020
+ betterAuthSecret,
111021
+ quiet: true
111022
+ });
111023
+ } catch (err2) {
111024
+ console.warn("[sandbox] Bun runtime not detected - fallback realtime server failed to start.", err2);
111025
+ return null;
111026
+ }
108120
111027
  }
108121
111028
  try {
108122
111029
  return await createRealtimeServer({