opencode-feishu 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11,7 +11,8 @@ import zlib from 'zlib';
11
11
  import stream3, { Readable } from 'stream';
12
12
  import { EventEmitter } from 'events';
13
13
  import qs from 'querystring';
14
- import { ProxyAgent } from 'proxy-agent';
14
+ import WebSocket from 'ws';
15
+ import { HttpsProxyAgent } from 'https-proxy-agent';
15
16
 
16
17
  var __create = Object.create;
17
18
  var __defProp = Object.defineProperty;
@@ -14778,3609 +14779,6 @@ var require_lodash3 = __commonJS({
14778
14779
  }
14779
14780
  });
14780
14781
 
14781
- // node_modules/ws/lib/constants.js
14782
- var require_constants = __commonJS({
14783
- "node_modules/ws/lib/constants.js"(exports2, module2) {
14784
- var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
14785
- var hasBlob = typeof Blob !== "undefined";
14786
- if (hasBlob) BINARY_TYPES.push("blob");
14787
- module2.exports = {
14788
- BINARY_TYPES,
14789
- CLOSE_TIMEOUT: 3e4,
14790
- EMPTY_BUFFER: Buffer.alloc(0),
14791
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
14792
- hasBlob,
14793
- kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
14794
- kListener: /* @__PURE__ */ Symbol("kListener"),
14795
- kStatusCode: /* @__PURE__ */ Symbol("status-code"),
14796
- kWebSocket: /* @__PURE__ */ Symbol("websocket"),
14797
- NOOP: () => {
14798
- }
14799
- };
14800
- }
14801
- });
14802
-
14803
- // node_modules/ws/lib/buffer-util.js
14804
- var require_buffer_util = __commonJS({
14805
- "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
14806
- var { EMPTY_BUFFER } = require_constants();
14807
- var FastBuffer = Buffer[Symbol.species];
14808
- function concat(list, totalLength) {
14809
- if (list.length === 0) return EMPTY_BUFFER;
14810
- if (list.length === 1) return list[0];
14811
- const target = Buffer.allocUnsafe(totalLength);
14812
- let offset = 0;
14813
- for (let i = 0; i < list.length; i++) {
14814
- const buf = list[i];
14815
- target.set(buf, offset);
14816
- offset += buf.length;
14817
- }
14818
- if (offset < totalLength) {
14819
- return new FastBuffer(target.buffer, target.byteOffset, offset);
14820
- }
14821
- return target;
14822
- }
14823
- function _mask(source, mask, output, offset, length) {
14824
- for (let i = 0; i < length; i++) {
14825
- output[offset + i] = source[i] ^ mask[i & 3];
14826
- }
14827
- }
14828
- function _unmask(buffer, mask) {
14829
- for (let i = 0; i < buffer.length; i++) {
14830
- buffer[i] ^= mask[i & 3];
14831
- }
14832
- }
14833
- function toArrayBuffer(buf) {
14834
- if (buf.length === buf.buffer.byteLength) {
14835
- return buf.buffer;
14836
- }
14837
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
14838
- }
14839
- function toBuffer(data) {
14840
- toBuffer.readOnly = true;
14841
- if (Buffer.isBuffer(data)) return data;
14842
- let buf;
14843
- if (data instanceof ArrayBuffer) {
14844
- buf = new FastBuffer(data);
14845
- } else if (ArrayBuffer.isView(data)) {
14846
- buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
14847
- } else {
14848
- buf = Buffer.from(data);
14849
- toBuffer.readOnly = false;
14850
- }
14851
- return buf;
14852
- }
14853
- module2.exports = {
14854
- concat,
14855
- mask: _mask,
14856
- toArrayBuffer,
14857
- toBuffer,
14858
- unmask: _unmask
14859
- };
14860
- if (!process.env.WS_NO_BUFFER_UTIL) {
14861
- try {
14862
- const bufferUtil = __require("bufferutil");
14863
- module2.exports.mask = function(source, mask, output, offset, length) {
14864
- if (length < 48) _mask(source, mask, output, offset, length);
14865
- else bufferUtil.mask(source, mask, output, offset, length);
14866
- };
14867
- module2.exports.unmask = function(buffer, mask) {
14868
- if (buffer.length < 32) _unmask(buffer, mask);
14869
- else bufferUtil.unmask(buffer, mask);
14870
- };
14871
- } catch (e) {
14872
- }
14873
- }
14874
- }
14875
- });
14876
-
14877
- // node_modules/ws/lib/limiter.js
14878
- var require_limiter = __commonJS({
14879
- "node_modules/ws/lib/limiter.js"(exports2, module2) {
14880
- var kDone = /* @__PURE__ */ Symbol("kDone");
14881
- var kRun = /* @__PURE__ */ Symbol("kRun");
14882
- var Limiter = class {
14883
- /**
14884
- * Creates a new `Limiter`.
14885
- *
14886
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
14887
- * to run concurrently
14888
- */
14889
- constructor(concurrency) {
14890
- this[kDone] = () => {
14891
- this.pending--;
14892
- this[kRun]();
14893
- };
14894
- this.concurrency = concurrency || Infinity;
14895
- this.jobs = [];
14896
- this.pending = 0;
14897
- }
14898
- /**
14899
- * Adds a job to the queue.
14900
- *
14901
- * @param {Function} job The job to run
14902
- * @public
14903
- */
14904
- add(job) {
14905
- this.jobs.push(job);
14906
- this[kRun]();
14907
- }
14908
- /**
14909
- * Removes a job from the queue and runs it if possible.
14910
- *
14911
- * @private
14912
- */
14913
- [kRun]() {
14914
- if (this.pending === this.concurrency) return;
14915
- if (this.jobs.length) {
14916
- const job = this.jobs.shift();
14917
- this.pending++;
14918
- job(this[kDone]);
14919
- }
14920
- }
14921
- };
14922
- module2.exports = Limiter;
14923
- }
14924
- });
14925
-
14926
- // node_modules/ws/lib/permessage-deflate.js
14927
- var require_permessage_deflate = __commonJS({
14928
- "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
14929
- var zlib2 = __require("zlib");
14930
- var bufferUtil = require_buffer_util();
14931
- var Limiter = require_limiter();
14932
- var { kStatusCode } = require_constants();
14933
- var FastBuffer = Buffer[Symbol.species];
14934
- var TRAILER = Buffer.from([0, 0, 255, 255]);
14935
- var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
14936
- var kTotalLength = /* @__PURE__ */ Symbol("total-length");
14937
- var kCallback = /* @__PURE__ */ Symbol("callback");
14938
- var kBuffers = /* @__PURE__ */ Symbol("buffers");
14939
- var kError = /* @__PURE__ */ Symbol("error");
14940
- var zlibLimiter;
14941
- var PerMessageDeflate = class {
14942
- /**
14943
- * Creates a PerMessageDeflate instance.
14944
- *
14945
- * @param {Object} [options] Configuration options
14946
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
14947
- * for, or request, a custom client window size
14948
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
14949
- * acknowledge disabling of client context takeover
14950
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
14951
- * calls to zlib
14952
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
14953
- * use of a custom server window size
14954
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
14955
- * disabling of server context takeover
14956
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
14957
- * messages should not be compressed if context takeover is disabled
14958
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
14959
- * deflate
14960
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
14961
- * inflate
14962
- * @param {Boolean} [isServer=false] Create the instance in either server or
14963
- * client mode
14964
- * @param {Number} [maxPayload=0] The maximum allowed message length
14965
- */
14966
- constructor(options, isServer, maxPayload) {
14967
- this._maxPayload = maxPayload | 0;
14968
- this._options = options || {};
14969
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
14970
- this._isServer = !!isServer;
14971
- this._deflate = null;
14972
- this._inflate = null;
14973
- this.params = null;
14974
- if (!zlibLimiter) {
14975
- const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
14976
- zlibLimiter = new Limiter(concurrency);
14977
- }
14978
- }
14979
- /**
14980
- * @type {String}
14981
- */
14982
- static get extensionName() {
14983
- return "permessage-deflate";
14984
- }
14985
- /**
14986
- * Create an extension negotiation offer.
14987
- *
14988
- * @return {Object} Extension parameters
14989
- * @public
14990
- */
14991
- offer() {
14992
- const params = {};
14993
- if (this._options.serverNoContextTakeover) {
14994
- params.server_no_context_takeover = true;
14995
- }
14996
- if (this._options.clientNoContextTakeover) {
14997
- params.client_no_context_takeover = true;
14998
- }
14999
- if (this._options.serverMaxWindowBits) {
15000
- params.server_max_window_bits = this._options.serverMaxWindowBits;
15001
- }
15002
- if (this._options.clientMaxWindowBits) {
15003
- params.client_max_window_bits = this._options.clientMaxWindowBits;
15004
- } else if (this._options.clientMaxWindowBits == null) {
15005
- params.client_max_window_bits = true;
15006
- }
15007
- return params;
15008
- }
15009
- /**
15010
- * Accept an extension negotiation offer/response.
15011
- *
15012
- * @param {Array} configurations The extension negotiation offers/reponse
15013
- * @return {Object} Accepted configuration
15014
- * @public
15015
- */
15016
- accept(configurations) {
15017
- configurations = this.normalizeParams(configurations);
15018
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
15019
- return this.params;
15020
- }
15021
- /**
15022
- * Releases all resources used by the extension.
15023
- *
15024
- * @public
15025
- */
15026
- cleanup() {
15027
- if (this._inflate) {
15028
- this._inflate.close();
15029
- this._inflate = null;
15030
- }
15031
- if (this._deflate) {
15032
- const callback = this._deflate[kCallback];
15033
- this._deflate.close();
15034
- this._deflate = null;
15035
- if (callback) {
15036
- callback(
15037
- new Error(
15038
- "The deflate stream was closed while data was being processed"
15039
- )
15040
- );
15041
- }
15042
- }
15043
- }
15044
- /**
15045
- * Accept an extension negotiation offer.
15046
- *
15047
- * @param {Array} offers The extension negotiation offers
15048
- * @return {Object} Accepted configuration
15049
- * @private
15050
- */
15051
- acceptAsServer(offers) {
15052
- const opts = this._options;
15053
- const accepted = offers.find((params) => {
15054
- 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) {
15055
- return false;
15056
- }
15057
- return true;
15058
- });
15059
- if (!accepted) {
15060
- throw new Error("None of the extension offers can be accepted");
15061
- }
15062
- if (opts.serverNoContextTakeover) {
15063
- accepted.server_no_context_takeover = true;
15064
- }
15065
- if (opts.clientNoContextTakeover) {
15066
- accepted.client_no_context_takeover = true;
15067
- }
15068
- if (typeof opts.serverMaxWindowBits === "number") {
15069
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
15070
- }
15071
- if (typeof opts.clientMaxWindowBits === "number") {
15072
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
15073
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
15074
- delete accepted.client_max_window_bits;
15075
- }
15076
- return accepted;
15077
- }
15078
- /**
15079
- * Accept the extension negotiation response.
15080
- *
15081
- * @param {Array} response The extension negotiation response
15082
- * @return {Object} Accepted configuration
15083
- * @private
15084
- */
15085
- acceptAsClient(response) {
15086
- const params = response[0];
15087
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
15088
- throw new Error('Unexpected parameter "client_no_context_takeover"');
15089
- }
15090
- if (!params.client_max_window_bits) {
15091
- if (typeof this._options.clientMaxWindowBits === "number") {
15092
- params.client_max_window_bits = this._options.clientMaxWindowBits;
15093
- }
15094
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
15095
- throw new Error(
15096
- 'Unexpected or invalid parameter "client_max_window_bits"'
15097
- );
15098
- }
15099
- return params;
15100
- }
15101
- /**
15102
- * Normalize parameters.
15103
- *
15104
- * @param {Array} configurations The extension negotiation offers/reponse
15105
- * @return {Array} The offers/response with normalized parameters
15106
- * @private
15107
- */
15108
- normalizeParams(configurations) {
15109
- configurations.forEach((params) => {
15110
- Object.keys(params).forEach((key) => {
15111
- let value = params[key];
15112
- if (value.length > 1) {
15113
- throw new Error(`Parameter "${key}" must have only a single value`);
15114
- }
15115
- value = value[0];
15116
- if (key === "client_max_window_bits") {
15117
- if (value !== true) {
15118
- const num = +value;
15119
- if (!Number.isInteger(num) || num < 8 || num > 15) {
15120
- throw new TypeError(
15121
- `Invalid value for parameter "${key}": ${value}`
15122
- );
15123
- }
15124
- value = num;
15125
- } else if (!this._isServer) {
15126
- throw new TypeError(
15127
- `Invalid value for parameter "${key}": ${value}`
15128
- );
15129
- }
15130
- } else if (key === "server_max_window_bits") {
15131
- const num = +value;
15132
- if (!Number.isInteger(num) || num < 8 || num > 15) {
15133
- throw new TypeError(
15134
- `Invalid value for parameter "${key}": ${value}`
15135
- );
15136
- }
15137
- value = num;
15138
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
15139
- if (value !== true) {
15140
- throw new TypeError(
15141
- `Invalid value for parameter "${key}": ${value}`
15142
- );
15143
- }
15144
- } else {
15145
- throw new Error(`Unknown parameter "${key}"`);
15146
- }
15147
- params[key] = value;
15148
- });
15149
- });
15150
- return configurations;
15151
- }
15152
- /**
15153
- * Decompress data. Concurrency limited.
15154
- *
15155
- * @param {Buffer} data Compressed data
15156
- * @param {Boolean} fin Specifies whether or not this is the last fragment
15157
- * @param {Function} callback Callback
15158
- * @public
15159
- */
15160
- decompress(data, fin, callback) {
15161
- zlibLimiter.add((done) => {
15162
- this._decompress(data, fin, (err, result) => {
15163
- done();
15164
- callback(err, result);
15165
- });
15166
- });
15167
- }
15168
- /**
15169
- * Compress data. Concurrency limited.
15170
- *
15171
- * @param {(Buffer|String)} data Data to compress
15172
- * @param {Boolean} fin Specifies whether or not this is the last fragment
15173
- * @param {Function} callback Callback
15174
- * @public
15175
- */
15176
- compress(data, fin, callback) {
15177
- zlibLimiter.add((done) => {
15178
- this._compress(data, fin, (err, result) => {
15179
- done();
15180
- callback(err, result);
15181
- });
15182
- });
15183
- }
15184
- /**
15185
- * Decompress data.
15186
- *
15187
- * @param {Buffer} data Compressed data
15188
- * @param {Boolean} fin Specifies whether or not this is the last fragment
15189
- * @param {Function} callback Callback
15190
- * @private
15191
- */
15192
- _decompress(data, fin, callback) {
15193
- const endpoint = this._isServer ? "client" : "server";
15194
- if (!this._inflate) {
15195
- const key = `${endpoint}_max_window_bits`;
15196
- const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
15197
- this._inflate = zlib2.createInflateRaw({
15198
- ...this._options.zlibInflateOptions,
15199
- windowBits
15200
- });
15201
- this._inflate[kPerMessageDeflate] = this;
15202
- this._inflate[kTotalLength] = 0;
15203
- this._inflate[kBuffers] = [];
15204
- this._inflate.on("error", inflateOnError);
15205
- this._inflate.on("data", inflateOnData);
15206
- }
15207
- this._inflate[kCallback] = callback;
15208
- this._inflate.write(data);
15209
- if (fin) this._inflate.write(TRAILER);
15210
- this._inflate.flush(() => {
15211
- const err = this._inflate[kError];
15212
- if (err) {
15213
- this._inflate.close();
15214
- this._inflate = null;
15215
- callback(err);
15216
- return;
15217
- }
15218
- const data2 = bufferUtil.concat(
15219
- this._inflate[kBuffers],
15220
- this._inflate[kTotalLength]
15221
- );
15222
- if (this._inflate._readableState.endEmitted) {
15223
- this._inflate.close();
15224
- this._inflate = null;
15225
- } else {
15226
- this._inflate[kTotalLength] = 0;
15227
- this._inflate[kBuffers] = [];
15228
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
15229
- this._inflate.reset();
15230
- }
15231
- }
15232
- callback(null, data2);
15233
- });
15234
- }
15235
- /**
15236
- * Compress data.
15237
- *
15238
- * @param {(Buffer|String)} data Data to compress
15239
- * @param {Boolean} fin Specifies whether or not this is the last fragment
15240
- * @param {Function} callback Callback
15241
- * @private
15242
- */
15243
- _compress(data, fin, callback) {
15244
- const endpoint = this._isServer ? "server" : "client";
15245
- if (!this._deflate) {
15246
- const key = `${endpoint}_max_window_bits`;
15247
- const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
15248
- this._deflate = zlib2.createDeflateRaw({
15249
- ...this._options.zlibDeflateOptions,
15250
- windowBits
15251
- });
15252
- this._deflate[kTotalLength] = 0;
15253
- this._deflate[kBuffers] = [];
15254
- this._deflate.on("data", deflateOnData);
15255
- }
15256
- this._deflate[kCallback] = callback;
15257
- this._deflate.write(data);
15258
- this._deflate.flush(zlib2.Z_SYNC_FLUSH, () => {
15259
- if (!this._deflate) {
15260
- return;
15261
- }
15262
- let data2 = bufferUtil.concat(
15263
- this._deflate[kBuffers],
15264
- this._deflate[kTotalLength]
15265
- );
15266
- if (fin) {
15267
- data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
15268
- }
15269
- this._deflate[kCallback] = null;
15270
- this._deflate[kTotalLength] = 0;
15271
- this._deflate[kBuffers] = [];
15272
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
15273
- this._deflate.reset();
15274
- }
15275
- callback(null, data2);
15276
- });
15277
- }
15278
- };
15279
- module2.exports = PerMessageDeflate;
15280
- function deflateOnData(chunk) {
15281
- this[kBuffers].push(chunk);
15282
- this[kTotalLength] += chunk.length;
15283
- }
15284
- function inflateOnData(chunk) {
15285
- this[kTotalLength] += chunk.length;
15286
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
15287
- this[kBuffers].push(chunk);
15288
- return;
15289
- }
15290
- this[kError] = new RangeError("Max payload size exceeded");
15291
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
15292
- this[kError][kStatusCode] = 1009;
15293
- this.removeListener("data", inflateOnData);
15294
- this.reset();
15295
- }
15296
- function inflateOnError(err) {
15297
- this[kPerMessageDeflate]._inflate = null;
15298
- if (this[kError]) {
15299
- this[kCallback](this[kError]);
15300
- return;
15301
- }
15302
- err[kStatusCode] = 1007;
15303
- this[kCallback](err);
15304
- }
15305
- }
15306
- });
15307
-
15308
- // node_modules/ws/lib/validation.js
15309
- var require_validation = __commonJS({
15310
- "node_modules/ws/lib/validation.js"(exports2, module2) {
15311
- var { isUtf8 } = __require("buffer");
15312
- var { hasBlob } = require_constants();
15313
- var tokenChars = [
15314
- 0,
15315
- 0,
15316
- 0,
15317
- 0,
15318
- 0,
15319
- 0,
15320
- 0,
15321
- 0,
15322
- 0,
15323
- 0,
15324
- 0,
15325
- 0,
15326
- 0,
15327
- 0,
15328
- 0,
15329
- 0,
15330
- // 0 - 15
15331
- 0,
15332
- 0,
15333
- 0,
15334
- 0,
15335
- 0,
15336
- 0,
15337
- 0,
15338
- 0,
15339
- 0,
15340
- 0,
15341
- 0,
15342
- 0,
15343
- 0,
15344
- 0,
15345
- 0,
15346
- 0,
15347
- // 16 - 31
15348
- 0,
15349
- 1,
15350
- 0,
15351
- 1,
15352
- 1,
15353
- 1,
15354
- 1,
15355
- 1,
15356
- 0,
15357
- 0,
15358
- 1,
15359
- 1,
15360
- 0,
15361
- 1,
15362
- 1,
15363
- 0,
15364
- // 32 - 47
15365
- 1,
15366
- 1,
15367
- 1,
15368
- 1,
15369
- 1,
15370
- 1,
15371
- 1,
15372
- 1,
15373
- 1,
15374
- 1,
15375
- 0,
15376
- 0,
15377
- 0,
15378
- 0,
15379
- 0,
15380
- 0,
15381
- // 48 - 63
15382
- 0,
15383
- 1,
15384
- 1,
15385
- 1,
15386
- 1,
15387
- 1,
15388
- 1,
15389
- 1,
15390
- 1,
15391
- 1,
15392
- 1,
15393
- 1,
15394
- 1,
15395
- 1,
15396
- 1,
15397
- 1,
15398
- // 64 - 79
15399
- 1,
15400
- 1,
15401
- 1,
15402
- 1,
15403
- 1,
15404
- 1,
15405
- 1,
15406
- 1,
15407
- 1,
15408
- 1,
15409
- 1,
15410
- 0,
15411
- 0,
15412
- 0,
15413
- 1,
15414
- 1,
15415
- // 80 - 95
15416
- 1,
15417
- 1,
15418
- 1,
15419
- 1,
15420
- 1,
15421
- 1,
15422
- 1,
15423
- 1,
15424
- 1,
15425
- 1,
15426
- 1,
15427
- 1,
15428
- 1,
15429
- 1,
15430
- 1,
15431
- 1,
15432
- // 96 - 111
15433
- 1,
15434
- 1,
15435
- 1,
15436
- 1,
15437
- 1,
15438
- 1,
15439
- 1,
15440
- 1,
15441
- 1,
15442
- 1,
15443
- 1,
15444
- 0,
15445
- 1,
15446
- 0,
15447
- 1,
15448
- 0
15449
- // 112 - 127
15450
- ];
15451
- function isValidStatusCode(code) {
15452
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
15453
- }
15454
- function _isValidUTF8(buf) {
15455
- const len = buf.length;
15456
- let i = 0;
15457
- while (i < len) {
15458
- if ((buf[i] & 128) === 0) {
15459
- i++;
15460
- } else if ((buf[i] & 224) === 192) {
15461
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
15462
- return false;
15463
- }
15464
- i += 2;
15465
- } else if ((buf[i] & 240) === 224) {
15466
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
15467
- buf[i] === 237 && (buf[i + 1] & 224) === 160) {
15468
- return false;
15469
- }
15470
- i += 3;
15471
- } else if ((buf[i] & 248) === 240) {
15472
- if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
15473
- buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
15474
- return false;
15475
- }
15476
- i += 4;
15477
- } else {
15478
- return false;
15479
- }
15480
- }
15481
- return true;
15482
- }
15483
- function isBlob2(value) {
15484
- 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");
15485
- }
15486
- module2.exports = {
15487
- isBlob: isBlob2,
15488
- isValidStatusCode,
15489
- isValidUTF8: _isValidUTF8,
15490
- tokenChars
15491
- };
15492
- if (isUtf8) {
15493
- module2.exports.isValidUTF8 = function(buf) {
15494
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
15495
- };
15496
- } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
15497
- try {
15498
- const isValidUTF8 = __require("utf-8-validate");
15499
- module2.exports.isValidUTF8 = function(buf) {
15500
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
15501
- };
15502
- } catch (e) {
15503
- }
15504
- }
15505
- }
15506
- });
15507
-
15508
- // node_modules/ws/lib/receiver.js
15509
- var require_receiver = __commonJS({
15510
- "node_modules/ws/lib/receiver.js"(exports2, module2) {
15511
- var { Writable } = __require("stream");
15512
- var PerMessageDeflate = require_permessage_deflate();
15513
- var {
15514
- BINARY_TYPES,
15515
- EMPTY_BUFFER,
15516
- kStatusCode,
15517
- kWebSocket
15518
- } = require_constants();
15519
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
15520
- var { isValidStatusCode, isValidUTF8 } = require_validation();
15521
- var FastBuffer = Buffer[Symbol.species];
15522
- var GET_INFO = 0;
15523
- var GET_PAYLOAD_LENGTH_16 = 1;
15524
- var GET_PAYLOAD_LENGTH_64 = 2;
15525
- var GET_MASK = 3;
15526
- var GET_DATA = 4;
15527
- var INFLATING = 5;
15528
- var DEFER_EVENT = 6;
15529
- var Receiver2 = class extends Writable {
15530
- /**
15531
- * Creates a Receiver instance.
15532
- *
15533
- * @param {Object} [options] Options object
15534
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
15535
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
15536
- * multiple times in the same tick
15537
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
15538
- * @param {Object} [options.extensions] An object containing the negotiated
15539
- * extensions
15540
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
15541
- * client or server mode
15542
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
15543
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
15544
- * not to skip UTF-8 validation for text and close messages
15545
- */
15546
- constructor(options = {}) {
15547
- super();
15548
- this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
15549
- this._binaryType = options.binaryType || BINARY_TYPES[0];
15550
- this._extensions = options.extensions || {};
15551
- this._isServer = !!options.isServer;
15552
- this._maxPayload = options.maxPayload | 0;
15553
- this._skipUTF8Validation = !!options.skipUTF8Validation;
15554
- this[kWebSocket] = void 0;
15555
- this._bufferedBytes = 0;
15556
- this._buffers = [];
15557
- this._compressed = false;
15558
- this._payloadLength = 0;
15559
- this._mask = void 0;
15560
- this._fragmented = 0;
15561
- this._masked = false;
15562
- this._fin = false;
15563
- this._opcode = 0;
15564
- this._totalPayloadLength = 0;
15565
- this._messageLength = 0;
15566
- this._fragments = [];
15567
- this._errored = false;
15568
- this._loop = false;
15569
- this._state = GET_INFO;
15570
- }
15571
- /**
15572
- * Implements `Writable.prototype._write()`.
15573
- *
15574
- * @param {Buffer} chunk The chunk of data to write
15575
- * @param {String} encoding The character encoding of `chunk`
15576
- * @param {Function} cb Callback
15577
- * @private
15578
- */
15579
- _write(chunk, encoding, cb) {
15580
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
15581
- this._bufferedBytes += chunk.length;
15582
- this._buffers.push(chunk);
15583
- this.startLoop(cb);
15584
- }
15585
- /**
15586
- * Consumes `n` bytes from the buffered data.
15587
- *
15588
- * @param {Number} n The number of bytes to consume
15589
- * @return {Buffer} The consumed bytes
15590
- * @private
15591
- */
15592
- consume(n) {
15593
- this._bufferedBytes -= n;
15594
- if (n === this._buffers[0].length) return this._buffers.shift();
15595
- if (n < this._buffers[0].length) {
15596
- const buf = this._buffers[0];
15597
- this._buffers[0] = new FastBuffer(
15598
- buf.buffer,
15599
- buf.byteOffset + n,
15600
- buf.length - n
15601
- );
15602
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
15603
- }
15604
- const dst = Buffer.allocUnsafe(n);
15605
- do {
15606
- const buf = this._buffers[0];
15607
- const offset = dst.length - n;
15608
- if (n >= buf.length) {
15609
- dst.set(this._buffers.shift(), offset);
15610
- } else {
15611
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
15612
- this._buffers[0] = new FastBuffer(
15613
- buf.buffer,
15614
- buf.byteOffset + n,
15615
- buf.length - n
15616
- );
15617
- }
15618
- n -= buf.length;
15619
- } while (n > 0);
15620
- return dst;
15621
- }
15622
- /**
15623
- * Starts the parsing loop.
15624
- *
15625
- * @param {Function} cb Callback
15626
- * @private
15627
- */
15628
- startLoop(cb) {
15629
- this._loop = true;
15630
- do {
15631
- switch (this._state) {
15632
- case GET_INFO:
15633
- this.getInfo(cb);
15634
- break;
15635
- case GET_PAYLOAD_LENGTH_16:
15636
- this.getPayloadLength16(cb);
15637
- break;
15638
- case GET_PAYLOAD_LENGTH_64:
15639
- this.getPayloadLength64(cb);
15640
- break;
15641
- case GET_MASK:
15642
- this.getMask();
15643
- break;
15644
- case GET_DATA:
15645
- this.getData(cb);
15646
- break;
15647
- case INFLATING:
15648
- case DEFER_EVENT:
15649
- this._loop = false;
15650
- return;
15651
- }
15652
- } while (this._loop);
15653
- if (!this._errored) cb();
15654
- }
15655
- /**
15656
- * Reads the first two bytes of a frame.
15657
- *
15658
- * @param {Function} cb Callback
15659
- * @private
15660
- */
15661
- getInfo(cb) {
15662
- if (this._bufferedBytes < 2) {
15663
- this._loop = false;
15664
- return;
15665
- }
15666
- const buf = this.consume(2);
15667
- if ((buf[0] & 48) !== 0) {
15668
- const error = this.createError(
15669
- RangeError,
15670
- "RSV2 and RSV3 must be clear",
15671
- true,
15672
- 1002,
15673
- "WS_ERR_UNEXPECTED_RSV_2_3"
15674
- );
15675
- cb(error);
15676
- return;
15677
- }
15678
- const compressed = (buf[0] & 64) === 64;
15679
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
15680
- const error = this.createError(
15681
- RangeError,
15682
- "RSV1 must be clear",
15683
- true,
15684
- 1002,
15685
- "WS_ERR_UNEXPECTED_RSV_1"
15686
- );
15687
- cb(error);
15688
- return;
15689
- }
15690
- this._fin = (buf[0] & 128) === 128;
15691
- this._opcode = buf[0] & 15;
15692
- this._payloadLength = buf[1] & 127;
15693
- if (this._opcode === 0) {
15694
- if (compressed) {
15695
- const error = this.createError(
15696
- RangeError,
15697
- "RSV1 must be clear",
15698
- true,
15699
- 1002,
15700
- "WS_ERR_UNEXPECTED_RSV_1"
15701
- );
15702
- cb(error);
15703
- return;
15704
- }
15705
- if (!this._fragmented) {
15706
- const error = this.createError(
15707
- RangeError,
15708
- "invalid opcode 0",
15709
- true,
15710
- 1002,
15711
- "WS_ERR_INVALID_OPCODE"
15712
- );
15713
- cb(error);
15714
- return;
15715
- }
15716
- this._opcode = this._fragmented;
15717
- } else if (this._opcode === 1 || this._opcode === 2) {
15718
- if (this._fragmented) {
15719
- const error = this.createError(
15720
- RangeError,
15721
- `invalid opcode ${this._opcode}`,
15722
- true,
15723
- 1002,
15724
- "WS_ERR_INVALID_OPCODE"
15725
- );
15726
- cb(error);
15727
- return;
15728
- }
15729
- this._compressed = compressed;
15730
- } else if (this._opcode > 7 && this._opcode < 11) {
15731
- if (!this._fin) {
15732
- const error = this.createError(
15733
- RangeError,
15734
- "FIN must be set",
15735
- true,
15736
- 1002,
15737
- "WS_ERR_EXPECTED_FIN"
15738
- );
15739
- cb(error);
15740
- return;
15741
- }
15742
- if (compressed) {
15743
- const error = this.createError(
15744
- RangeError,
15745
- "RSV1 must be clear",
15746
- true,
15747
- 1002,
15748
- "WS_ERR_UNEXPECTED_RSV_1"
15749
- );
15750
- cb(error);
15751
- return;
15752
- }
15753
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
15754
- const error = this.createError(
15755
- RangeError,
15756
- `invalid payload length ${this._payloadLength}`,
15757
- true,
15758
- 1002,
15759
- "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
15760
- );
15761
- cb(error);
15762
- return;
15763
- }
15764
- } else {
15765
- const error = this.createError(
15766
- RangeError,
15767
- `invalid opcode ${this._opcode}`,
15768
- true,
15769
- 1002,
15770
- "WS_ERR_INVALID_OPCODE"
15771
- );
15772
- cb(error);
15773
- return;
15774
- }
15775
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
15776
- this._masked = (buf[1] & 128) === 128;
15777
- if (this._isServer) {
15778
- if (!this._masked) {
15779
- const error = this.createError(
15780
- RangeError,
15781
- "MASK must be set",
15782
- true,
15783
- 1002,
15784
- "WS_ERR_EXPECTED_MASK"
15785
- );
15786
- cb(error);
15787
- return;
15788
- }
15789
- } else if (this._masked) {
15790
- const error = this.createError(
15791
- RangeError,
15792
- "MASK must be clear",
15793
- true,
15794
- 1002,
15795
- "WS_ERR_UNEXPECTED_MASK"
15796
- );
15797
- cb(error);
15798
- return;
15799
- }
15800
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
15801
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
15802
- else this.haveLength(cb);
15803
- }
15804
- /**
15805
- * Gets extended payload length (7+16).
15806
- *
15807
- * @param {Function} cb Callback
15808
- * @private
15809
- */
15810
- getPayloadLength16(cb) {
15811
- if (this._bufferedBytes < 2) {
15812
- this._loop = false;
15813
- return;
15814
- }
15815
- this._payloadLength = this.consume(2).readUInt16BE(0);
15816
- this.haveLength(cb);
15817
- }
15818
- /**
15819
- * Gets extended payload length (7+64).
15820
- *
15821
- * @param {Function} cb Callback
15822
- * @private
15823
- */
15824
- getPayloadLength64(cb) {
15825
- if (this._bufferedBytes < 8) {
15826
- this._loop = false;
15827
- return;
15828
- }
15829
- const buf = this.consume(8);
15830
- const num = buf.readUInt32BE(0);
15831
- if (num > Math.pow(2, 53 - 32) - 1) {
15832
- const error = this.createError(
15833
- RangeError,
15834
- "Unsupported WebSocket frame: payload length > 2^53 - 1",
15835
- false,
15836
- 1009,
15837
- "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
15838
- );
15839
- cb(error);
15840
- return;
15841
- }
15842
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
15843
- this.haveLength(cb);
15844
- }
15845
- /**
15846
- * Payload length has been read.
15847
- *
15848
- * @param {Function} cb Callback
15849
- * @private
15850
- */
15851
- haveLength(cb) {
15852
- if (this._payloadLength && this._opcode < 8) {
15853
- this._totalPayloadLength += this._payloadLength;
15854
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
15855
- const error = this.createError(
15856
- RangeError,
15857
- "Max payload size exceeded",
15858
- false,
15859
- 1009,
15860
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
15861
- );
15862
- cb(error);
15863
- return;
15864
- }
15865
- }
15866
- if (this._masked) this._state = GET_MASK;
15867
- else this._state = GET_DATA;
15868
- }
15869
- /**
15870
- * Reads mask bytes.
15871
- *
15872
- * @private
15873
- */
15874
- getMask() {
15875
- if (this._bufferedBytes < 4) {
15876
- this._loop = false;
15877
- return;
15878
- }
15879
- this._mask = this.consume(4);
15880
- this._state = GET_DATA;
15881
- }
15882
- /**
15883
- * Reads data bytes.
15884
- *
15885
- * @param {Function} cb Callback
15886
- * @private
15887
- */
15888
- getData(cb) {
15889
- let data = EMPTY_BUFFER;
15890
- if (this._payloadLength) {
15891
- if (this._bufferedBytes < this._payloadLength) {
15892
- this._loop = false;
15893
- return;
15894
- }
15895
- data = this.consume(this._payloadLength);
15896
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
15897
- unmask(data, this._mask);
15898
- }
15899
- }
15900
- if (this._opcode > 7) {
15901
- this.controlMessage(data, cb);
15902
- return;
15903
- }
15904
- if (this._compressed) {
15905
- this._state = INFLATING;
15906
- this.decompress(data, cb);
15907
- return;
15908
- }
15909
- if (data.length) {
15910
- this._messageLength = this._totalPayloadLength;
15911
- this._fragments.push(data);
15912
- }
15913
- this.dataMessage(cb);
15914
- }
15915
- /**
15916
- * Decompresses data.
15917
- *
15918
- * @param {Buffer} data Compressed data
15919
- * @param {Function} cb Callback
15920
- * @private
15921
- */
15922
- decompress(data, cb) {
15923
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
15924
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
15925
- if (err) return cb(err);
15926
- if (buf.length) {
15927
- this._messageLength += buf.length;
15928
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
15929
- const error = this.createError(
15930
- RangeError,
15931
- "Max payload size exceeded",
15932
- false,
15933
- 1009,
15934
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
15935
- );
15936
- cb(error);
15937
- return;
15938
- }
15939
- this._fragments.push(buf);
15940
- }
15941
- this.dataMessage(cb);
15942
- if (this._state === GET_INFO) this.startLoop(cb);
15943
- });
15944
- }
15945
- /**
15946
- * Handles a data message.
15947
- *
15948
- * @param {Function} cb Callback
15949
- * @private
15950
- */
15951
- dataMessage(cb) {
15952
- if (!this._fin) {
15953
- this._state = GET_INFO;
15954
- return;
15955
- }
15956
- const messageLength = this._messageLength;
15957
- const fragments = this._fragments;
15958
- this._totalPayloadLength = 0;
15959
- this._messageLength = 0;
15960
- this._fragmented = 0;
15961
- this._fragments = [];
15962
- if (this._opcode === 2) {
15963
- let data;
15964
- if (this._binaryType === "nodebuffer") {
15965
- data = concat(fragments, messageLength);
15966
- } else if (this._binaryType === "arraybuffer") {
15967
- data = toArrayBuffer(concat(fragments, messageLength));
15968
- } else if (this._binaryType === "blob") {
15969
- data = new Blob(fragments);
15970
- } else {
15971
- data = fragments;
15972
- }
15973
- if (this._allowSynchronousEvents) {
15974
- this.emit("message", data, true);
15975
- this._state = GET_INFO;
15976
- } else {
15977
- this._state = DEFER_EVENT;
15978
- setImmediate(() => {
15979
- this.emit("message", data, true);
15980
- this._state = GET_INFO;
15981
- this.startLoop(cb);
15982
- });
15983
- }
15984
- } else {
15985
- const buf = concat(fragments, messageLength);
15986
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
15987
- const error = this.createError(
15988
- Error,
15989
- "invalid UTF-8 sequence",
15990
- true,
15991
- 1007,
15992
- "WS_ERR_INVALID_UTF8"
15993
- );
15994
- cb(error);
15995
- return;
15996
- }
15997
- if (this._state === INFLATING || this._allowSynchronousEvents) {
15998
- this.emit("message", buf, false);
15999
- this._state = GET_INFO;
16000
- } else {
16001
- this._state = DEFER_EVENT;
16002
- setImmediate(() => {
16003
- this.emit("message", buf, false);
16004
- this._state = GET_INFO;
16005
- this.startLoop(cb);
16006
- });
16007
- }
16008
- }
16009
- }
16010
- /**
16011
- * Handles a control message.
16012
- *
16013
- * @param {Buffer} data Data to handle
16014
- * @return {(Error|RangeError|undefined)} A possible error
16015
- * @private
16016
- */
16017
- controlMessage(data, cb) {
16018
- if (this._opcode === 8) {
16019
- if (data.length === 0) {
16020
- this._loop = false;
16021
- this.emit("conclude", 1005, EMPTY_BUFFER);
16022
- this.end();
16023
- } else {
16024
- const code = data.readUInt16BE(0);
16025
- if (!isValidStatusCode(code)) {
16026
- const error = this.createError(
16027
- RangeError,
16028
- `invalid status code ${code}`,
16029
- true,
16030
- 1002,
16031
- "WS_ERR_INVALID_CLOSE_CODE"
16032
- );
16033
- cb(error);
16034
- return;
16035
- }
16036
- const buf = new FastBuffer(
16037
- data.buffer,
16038
- data.byteOffset + 2,
16039
- data.length - 2
16040
- );
16041
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
16042
- const error = this.createError(
16043
- Error,
16044
- "invalid UTF-8 sequence",
16045
- true,
16046
- 1007,
16047
- "WS_ERR_INVALID_UTF8"
16048
- );
16049
- cb(error);
16050
- return;
16051
- }
16052
- this._loop = false;
16053
- this.emit("conclude", code, buf);
16054
- this.end();
16055
- }
16056
- this._state = GET_INFO;
16057
- return;
16058
- }
16059
- if (this._allowSynchronousEvents) {
16060
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
16061
- this._state = GET_INFO;
16062
- } else {
16063
- this._state = DEFER_EVENT;
16064
- setImmediate(() => {
16065
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
16066
- this._state = GET_INFO;
16067
- this.startLoop(cb);
16068
- });
16069
- }
16070
- }
16071
- /**
16072
- * Builds an error object.
16073
- *
16074
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
16075
- * @param {String} message The error message
16076
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
16077
- * `message`
16078
- * @param {Number} statusCode The status code
16079
- * @param {String} errorCode The exposed error code
16080
- * @return {(Error|RangeError)} The error
16081
- * @private
16082
- */
16083
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
16084
- this._loop = false;
16085
- this._errored = true;
16086
- const err = new ErrorCtor(
16087
- prefix ? `Invalid WebSocket frame: ${message}` : message
16088
- );
16089
- Error.captureStackTrace(err, this.createError);
16090
- err.code = errorCode;
16091
- err[kStatusCode] = statusCode;
16092
- return err;
16093
- }
16094
- };
16095
- module2.exports = Receiver2;
16096
- }
16097
- });
16098
-
16099
- // node_modules/ws/lib/sender.js
16100
- var require_sender = __commonJS({
16101
- "node_modules/ws/lib/sender.js"(exports2, module2) {
16102
- var { Duplex } = __require("stream");
16103
- var { randomFillSync } = __require("crypto");
16104
- var PerMessageDeflate = require_permessage_deflate();
16105
- var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
16106
- var { isBlob: isBlob2, isValidStatusCode } = require_validation();
16107
- var { mask: applyMask, toBuffer } = require_buffer_util();
16108
- var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
16109
- var maskBuffer = Buffer.alloc(4);
16110
- var RANDOM_POOL_SIZE = 8 * 1024;
16111
- var randomPool;
16112
- var randomPoolPointer = RANDOM_POOL_SIZE;
16113
- var DEFAULT = 0;
16114
- var DEFLATING = 1;
16115
- var GET_BLOB_DATA = 2;
16116
- var Sender2 = class _Sender {
16117
- /**
16118
- * Creates a Sender instance.
16119
- *
16120
- * @param {Duplex} socket The connection socket
16121
- * @param {Object} [extensions] An object containing the negotiated extensions
16122
- * @param {Function} [generateMask] The function used to generate the masking
16123
- * key
16124
- */
16125
- constructor(socket, extensions, generateMask) {
16126
- this._extensions = extensions || {};
16127
- if (generateMask) {
16128
- this._generateMask = generateMask;
16129
- this._maskBuffer = Buffer.alloc(4);
16130
- }
16131
- this._socket = socket;
16132
- this._firstFragment = true;
16133
- this._compress = false;
16134
- this._bufferedBytes = 0;
16135
- this._queue = [];
16136
- this._state = DEFAULT;
16137
- this.onerror = NOOP;
16138
- this[kWebSocket] = void 0;
16139
- }
16140
- /**
16141
- * Frames a piece of data according to the HyBi WebSocket protocol.
16142
- *
16143
- * @param {(Buffer|String)} data The data to frame
16144
- * @param {Object} options Options object
16145
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
16146
- * FIN bit
16147
- * @param {Function} [options.generateMask] The function used to generate the
16148
- * masking key
16149
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
16150
- * `data`
16151
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
16152
- * key
16153
- * @param {Number} options.opcode The opcode
16154
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
16155
- * modified
16156
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
16157
- * RSV1 bit
16158
- * @return {(Buffer|String)[]} The framed data
16159
- * @public
16160
- */
16161
- static frame(data, options) {
16162
- let mask;
16163
- let merge3 = false;
16164
- let offset = 2;
16165
- let skipMasking = false;
16166
- if (options.mask) {
16167
- mask = options.maskBuffer || maskBuffer;
16168
- if (options.generateMask) {
16169
- options.generateMask(mask);
16170
- } else {
16171
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
16172
- if (randomPool === void 0) {
16173
- randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
16174
- }
16175
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
16176
- randomPoolPointer = 0;
16177
- }
16178
- mask[0] = randomPool[randomPoolPointer++];
16179
- mask[1] = randomPool[randomPoolPointer++];
16180
- mask[2] = randomPool[randomPoolPointer++];
16181
- mask[3] = randomPool[randomPoolPointer++];
16182
- }
16183
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
16184
- offset = 6;
16185
- }
16186
- let dataLength;
16187
- if (typeof data === "string") {
16188
- if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
16189
- dataLength = options[kByteLength];
16190
- } else {
16191
- data = Buffer.from(data);
16192
- dataLength = data.length;
16193
- }
16194
- } else {
16195
- dataLength = data.length;
16196
- merge3 = options.mask && options.readOnly && !skipMasking;
16197
- }
16198
- let payloadLength = dataLength;
16199
- if (dataLength >= 65536) {
16200
- offset += 8;
16201
- payloadLength = 127;
16202
- } else if (dataLength > 125) {
16203
- offset += 2;
16204
- payloadLength = 126;
16205
- }
16206
- const target = Buffer.allocUnsafe(merge3 ? dataLength + offset : offset);
16207
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
16208
- if (options.rsv1) target[0] |= 64;
16209
- target[1] = payloadLength;
16210
- if (payloadLength === 126) {
16211
- target.writeUInt16BE(dataLength, 2);
16212
- } else if (payloadLength === 127) {
16213
- target[2] = target[3] = 0;
16214
- target.writeUIntBE(dataLength, 4, 6);
16215
- }
16216
- if (!options.mask) return [target, data];
16217
- target[1] |= 128;
16218
- target[offset - 4] = mask[0];
16219
- target[offset - 3] = mask[1];
16220
- target[offset - 2] = mask[2];
16221
- target[offset - 1] = mask[3];
16222
- if (skipMasking) return [target, data];
16223
- if (merge3) {
16224
- applyMask(data, mask, target, offset, dataLength);
16225
- return [target];
16226
- }
16227
- applyMask(data, mask, data, 0, dataLength);
16228
- return [target, data];
16229
- }
16230
- /**
16231
- * Sends a close message to the other peer.
16232
- *
16233
- * @param {Number} [code] The status code component of the body
16234
- * @param {(String|Buffer)} [data] The message component of the body
16235
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
16236
- * @param {Function} [cb] Callback
16237
- * @public
16238
- */
16239
- close(code, data, mask, cb) {
16240
- let buf;
16241
- if (code === void 0) {
16242
- buf = EMPTY_BUFFER;
16243
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
16244
- throw new TypeError("First argument must be a valid error code number");
16245
- } else if (data === void 0 || !data.length) {
16246
- buf = Buffer.allocUnsafe(2);
16247
- buf.writeUInt16BE(code, 0);
16248
- } else {
16249
- const length = Buffer.byteLength(data);
16250
- if (length > 123) {
16251
- throw new RangeError("The message must not be greater than 123 bytes");
16252
- }
16253
- buf = Buffer.allocUnsafe(2 + length);
16254
- buf.writeUInt16BE(code, 0);
16255
- if (typeof data === "string") {
16256
- buf.write(data, 2);
16257
- } else {
16258
- buf.set(data, 2);
16259
- }
16260
- }
16261
- const options = {
16262
- [kByteLength]: buf.length,
16263
- fin: true,
16264
- generateMask: this._generateMask,
16265
- mask,
16266
- maskBuffer: this._maskBuffer,
16267
- opcode: 8,
16268
- readOnly: false,
16269
- rsv1: false
16270
- };
16271
- if (this._state !== DEFAULT) {
16272
- this.enqueue([this.dispatch, buf, false, options, cb]);
16273
- } else {
16274
- this.sendFrame(_Sender.frame(buf, options), cb);
16275
- }
16276
- }
16277
- /**
16278
- * Sends a ping message to the other peer.
16279
- *
16280
- * @param {*} data The message to send
16281
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
16282
- * @param {Function} [cb] Callback
16283
- * @public
16284
- */
16285
- ping(data, mask, cb) {
16286
- let byteLength;
16287
- let readOnly;
16288
- if (typeof data === "string") {
16289
- byteLength = Buffer.byteLength(data);
16290
- readOnly = false;
16291
- } else if (isBlob2(data)) {
16292
- byteLength = data.size;
16293
- readOnly = false;
16294
- } else {
16295
- data = toBuffer(data);
16296
- byteLength = data.length;
16297
- readOnly = toBuffer.readOnly;
16298
- }
16299
- if (byteLength > 125) {
16300
- throw new RangeError("The data size must not be greater than 125 bytes");
16301
- }
16302
- const options = {
16303
- [kByteLength]: byteLength,
16304
- fin: true,
16305
- generateMask: this._generateMask,
16306
- mask,
16307
- maskBuffer: this._maskBuffer,
16308
- opcode: 9,
16309
- readOnly,
16310
- rsv1: false
16311
- };
16312
- if (isBlob2(data)) {
16313
- if (this._state !== DEFAULT) {
16314
- this.enqueue([this.getBlobData, data, false, options, cb]);
16315
- } else {
16316
- this.getBlobData(data, false, options, cb);
16317
- }
16318
- } else if (this._state !== DEFAULT) {
16319
- this.enqueue([this.dispatch, data, false, options, cb]);
16320
- } else {
16321
- this.sendFrame(_Sender.frame(data, options), cb);
16322
- }
16323
- }
16324
- /**
16325
- * Sends a pong message to the other peer.
16326
- *
16327
- * @param {*} data The message to send
16328
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
16329
- * @param {Function} [cb] Callback
16330
- * @public
16331
- */
16332
- pong(data, mask, cb) {
16333
- let byteLength;
16334
- let readOnly;
16335
- if (typeof data === "string") {
16336
- byteLength = Buffer.byteLength(data);
16337
- readOnly = false;
16338
- } else if (isBlob2(data)) {
16339
- byteLength = data.size;
16340
- readOnly = false;
16341
- } else {
16342
- data = toBuffer(data);
16343
- byteLength = data.length;
16344
- readOnly = toBuffer.readOnly;
16345
- }
16346
- if (byteLength > 125) {
16347
- throw new RangeError("The data size must not be greater than 125 bytes");
16348
- }
16349
- const options = {
16350
- [kByteLength]: byteLength,
16351
- fin: true,
16352
- generateMask: this._generateMask,
16353
- mask,
16354
- maskBuffer: this._maskBuffer,
16355
- opcode: 10,
16356
- readOnly,
16357
- rsv1: false
16358
- };
16359
- if (isBlob2(data)) {
16360
- if (this._state !== DEFAULT) {
16361
- this.enqueue([this.getBlobData, data, false, options, cb]);
16362
- } else {
16363
- this.getBlobData(data, false, options, cb);
16364
- }
16365
- } else if (this._state !== DEFAULT) {
16366
- this.enqueue([this.dispatch, data, false, options, cb]);
16367
- } else {
16368
- this.sendFrame(_Sender.frame(data, options), cb);
16369
- }
16370
- }
16371
- /**
16372
- * Sends a data message to the other peer.
16373
- *
16374
- * @param {*} data The message to send
16375
- * @param {Object} options Options object
16376
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
16377
- * or text
16378
- * @param {Boolean} [options.compress=false] Specifies whether or not to
16379
- * compress `data`
16380
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
16381
- * last one
16382
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
16383
- * `data`
16384
- * @param {Function} [cb] Callback
16385
- * @public
16386
- */
16387
- send(data, options, cb) {
16388
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
16389
- let opcode = options.binary ? 2 : 1;
16390
- let rsv1 = options.compress;
16391
- let byteLength;
16392
- let readOnly;
16393
- if (typeof data === "string") {
16394
- byteLength = Buffer.byteLength(data);
16395
- readOnly = false;
16396
- } else if (isBlob2(data)) {
16397
- byteLength = data.size;
16398
- readOnly = false;
16399
- } else {
16400
- data = toBuffer(data);
16401
- byteLength = data.length;
16402
- readOnly = toBuffer.readOnly;
16403
- }
16404
- if (this._firstFragment) {
16405
- this._firstFragment = false;
16406
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
16407
- rsv1 = byteLength >= perMessageDeflate._threshold;
16408
- }
16409
- this._compress = rsv1;
16410
- } else {
16411
- rsv1 = false;
16412
- opcode = 0;
16413
- }
16414
- if (options.fin) this._firstFragment = true;
16415
- const opts = {
16416
- [kByteLength]: byteLength,
16417
- fin: options.fin,
16418
- generateMask: this._generateMask,
16419
- mask: options.mask,
16420
- maskBuffer: this._maskBuffer,
16421
- opcode,
16422
- readOnly,
16423
- rsv1
16424
- };
16425
- if (isBlob2(data)) {
16426
- if (this._state !== DEFAULT) {
16427
- this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
16428
- } else {
16429
- this.getBlobData(data, this._compress, opts, cb);
16430
- }
16431
- } else if (this._state !== DEFAULT) {
16432
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
16433
- } else {
16434
- this.dispatch(data, this._compress, opts, cb);
16435
- }
16436
- }
16437
- /**
16438
- * Gets the contents of a blob as binary data.
16439
- *
16440
- * @param {Blob} blob The blob
16441
- * @param {Boolean} [compress=false] Specifies whether or not to compress
16442
- * the data
16443
- * @param {Object} options Options object
16444
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
16445
- * FIN bit
16446
- * @param {Function} [options.generateMask] The function used to generate the
16447
- * masking key
16448
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
16449
- * `data`
16450
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
16451
- * key
16452
- * @param {Number} options.opcode The opcode
16453
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
16454
- * modified
16455
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
16456
- * RSV1 bit
16457
- * @param {Function} [cb] Callback
16458
- * @private
16459
- */
16460
- getBlobData(blob, compress, options, cb) {
16461
- this._bufferedBytes += options[kByteLength];
16462
- this._state = GET_BLOB_DATA;
16463
- blob.arrayBuffer().then((arrayBuffer) => {
16464
- if (this._socket.destroyed) {
16465
- const err = new Error(
16466
- "The socket was closed while the blob was being read"
16467
- );
16468
- process.nextTick(callCallbacks, this, err, cb);
16469
- return;
16470
- }
16471
- this._bufferedBytes -= options[kByteLength];
16472
- const data = toBuffer(arrayBuffer);
16473
- if (!compress) {
16474
- this._state = DEFAULT;
16475
- this.sendFrame(_Sender.frame(data, options), cb);
16476
- this.dequeue();
16477
- } else {
16478
- this.dispatch(data, compress, options, cb);
16479
- }
16480
- }).catch((err) => {
16481
- process.nextTick(onError, this, err, cb);
16482
- });
16483
- }
16484
- /**
16485
- * Dispatches a message.
16486
- *
16487
- * @param {(Buffer|String)} data The message to send
16488
- * @param {Boolean} [compress=false] Specifies whether or not to compress
16489
- * `data`
16490
- * @param {Object} options Options object
16491
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
16492
- * FIN bit
16493
- * @param {Function} [options.generateMask] The function used to generate the
16494
- * masking key
16495
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
16496
- * `data`
16497
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
16498
- * key
16499
- * @param {Number} options.opcode The opcode
16500
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
16501
- * modified
16502
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
16503
- * RSV1 bit
16504
- * @param {Function} [cb] Callback
16505
- * @private
16506
- */
16507
- dispatch(data, compress, options, cb) {
16508
- if (!compress) {
16509
- this.sendFrame(_Sender.frame(data, options), cb);
16510
- return;
16511
- }
16512
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
16513
- this._bufferedBytes += options[kByteLength];
16514
- this._state = DEFLATING;
16515
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
16516
- if (this._socket.destroyed) {
16517
- const err = new Error(
16518
- "The socket was closed while data was being compressed"
16519
- );
16520
- callCallbacks(this, err, cb);
16521
- return;
16522
- }
16523
- this._bufferedBytes -= options[kByteLength];
16524
- this._state = DEFAULT;
16525
- options.readOnly = false;
16526
- this.sendFrame(_Sender.frame(buf, options), cb);
16527
- this.dequeue();
16528
- });
16529
- }
16530
- /**
16531
- * Executes queued send operations.
16532
- *
16533
- * @private
16534
- */
16535
- dequeue() {
16536
- while (this._state === DEFAULT && this._queue.length) {
16537
- const params = this._queue.shift();
16538
- this._bufferedBytes -= params[3][kByteLength];
16539
- Reflect.apply(params[0], this, params.slice(1));
16540
- }
16541
- }
16542
- /**
16543
- * Enqueues a send operation.
16544
- *
16545
- * @param {Array} params Send operation parameters.
16546
- * @private
16547
- */
16548
- enqueue(params) {
16549
- this._bufferedBytes += params[3][kByteLength];
16550
- this._queue.push(params);
16551
- }
16552
- /**
16553
- * Sends a frame.
16554
- *
16555
- * @param {(Buffer | String)[]} list The frame to send
16556
- * @param {Function} [cb] Callback
16557
- * @private
16558
- */
16559
- sendFrame(list, cb) {
16560
- if (list.length === 2) {
16561
- this._socket.cork();
16562
- this._socket.write(list[0]);
16563
- this._socket.write(list[1], cb);
16564
- this._socket.uncork();
16565
- } else {
16566
- this._socket.write(list[0], cb);
16567
- }
16568
- }
16569
- };
16570
- module2.exports = Sender2;
16571
- function callCallbacks(sender, err, cb) {
16572
- if (typeof cb === "function") cb(err);
16573
- for (let i = 0; i < sender._queue.length; i++) {
16574
- const params = sender._queue[i];
16575
- const callback = params[params.length - 1];
16576
- if (typeof callback === "function") callback(err);
16577
- }
16578
- }
16579
- function onError(sender, err, cb) {
16580
- callCallbacks(sender, err, cb);
16581
- sender.onerror(err);
16582
- }
16583
- }
16584
- });
16585
-
16586
- // node_modules/ws/lib/event-target.js
16587
- var require_event_target = __commonJS({
16588
- "node_modules/ws/lib/event-target.js"(exports2, module2) {
16589
- var { kForOnEventAttribute, kListener } = require_constants();
16590
- var kCode = /* @__PURE__ */ Symbol("kCode");
16591
- var kData = /* @__PURE__ */ Symbol("kData");
16592
- var kError = /* @__PURE__ */ Symbol("kError");
16593
- var kMessage = /* @__PURE__ */ Symbol("kMessage");
16594
- var kReason = /* @__PURE__ */ Symbol("kReason");
16595
- var kTarget = /* @__PURE__ */ Symbol("kTarget");
16596
- var kType = /* @__PURE__ */ Symbol("kType");
16597
- var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
16598
- var Event = class {
16599
- /**
16600
- * Create a new `Event`.
16601
- *
16602
- * @param {String} type The name of the event
16603
- * @throws {TypeError} If the `type` argument is not specified
16604
- */
16605
- constructor(type) {
16606
- this[kTarget] = null;
16607
- this[kType] = type;
16608
- }
16609
- /**
16610
- * @type {*}
16611
- */
16612
- get target() {
16613
- return this[kTarget];
16614
- }
16615
- /**
16616
- * @type {String}
16617
- */
16618
- get type() {
16619
- return this[kType];
16620
- }
16621
- };
16622
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
16623
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
16624
- var CloseEvent = class extends Event {
16625
- /**
16626
- * Create a new `CloseEvent`.
16627
- *
16628
- * @param {String} type The name of the event
16629
- * @param {Object} [options] A dictionary object that allows for setting
16630
- * attributes via object members of the same name
16631
- * @param {Number} [options.code=0] The status code explaining why the
16632
- * connection was closed
16633
- * @param {String} [options.reason=''] A human-readable string explaining why
16634
- * the connection was closed
16635
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
16636
- * connection was cleanly closed
16637
- */
16638
- constructor(type, options = {}) {
16639
- super(type);
16640
- this[kCode] = options.code === void 0 ? 0 : options.code;
16641
- this[kReason] = options.reason === void 0 ? "" : options.reason;
16642
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
16643
- }
16644
- /**
16645
- * @type {Number}
16646
- */
16647
- get code() {
16648
- return this[kCode];
16649
- }
16650
- /**
16651
- * @type {String}
16652
- */
16653
- get reason() {
16654
- return this[kReason];
16655
- }
16656
- /**
16657
- * @type {Boolean}
16658
- */
16659
- get wasClean() {
16660
- return this[kWasClean];
16661
- }
16662
- };
16663
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
16664
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
16665
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
16666
- var ErrorEvent = class extends Event {
16667
- /**
16668
- * Create a new `ErrorEvent`.
16669
- *
16670
- * @param {String} type The name of the event
16671
- * @param {Object} [options] A dictionary object that allows for setting
16672
- * attributes via object members of the same name
16673
- * @param {*} [options.error=null] The error that generated this event
16674
- * @param {String} [options.message=''] The error message
16675
- */
16676
- constructor(type, options = {}) {
16677
- super(type);
16678
- this[kError] = options.error === void 0 ? null : options.error;
16679
- this[kMessage] = options.message === void 0 ? "" : options.message;
16680
- }
16681
- /**
16682
- * @type {*}
16683
- */
16684
- get error() {
16685
- return this[kError];
16686
- }
16687
- /**
16688
- * @type {String}
16689
- */
16690
- get message() {
16691
- return this[kMessage];
16692
- }
16693
- };
16694
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
16695
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
16696
- var MessageEvent = class extends Event {
16697
- /**
16698
- * Create a new `MessageEvent`.
16699
- *
16700
- * @param {String} type The name of the event
16701
- * @param {Object} [options] A dictionary object that allows for setting
16702
- * attributes via object members of the same name
16703
- * @param {*} [options.data=null] The message content
16704
- */
16705
- constructor(type, options = {}) {
16706
- super(type);
16707
- this[kData] = options.data === void 0 ? null : options.data;
16708
- }
16709
- /**
16710
- * @type {*}
16711
- */
16712
- get data() {
16713
- return this[kData];
16714
- }
16715
- };
16716
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
16717
- var EventTarget = {
16718
- /**
16719
- * Register an event listener.
16720
- *
16721
- * @param {String} type A string representing the event type to listen for
16722
- * @param {(Function|Object)} handler The listener to add
16723
- * @param {Object} [options] An options object specifies characteristics about
16724
- * the event listener
16725
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
16726
- * listener should be invoked at most once after being added. If `true`,
16727
- * the listener would be automatically removed when invoked.
16728
- * @public
16729
- */
16730
- addEventListener(type, handler, options = {}) {
16731
- for (const listener of this.listeners(type)) {
16732
- if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
16733
- return;
16734
- }
16735
- }
16736
- let wrapper;
16737
- if (type === "message") {
16738
- wrapper = function onMessage(data, isBinary) {
16739
- const event = new MessageEvent("message", {
16740
- data: isBinary ? data : data.toString()
16741
- });
16742
- event[kTarget] = this;
16743
- callListener(handler, this, event);
16744
- };
16745
- } else if (type === "close") {
16746
- wrapper = function onClose(code, message) {
16747
- const event = new CloseEvent("close", {
16748
- code,
16749
- reason: message.toString(),
16750
- wasClean: this._closeFrameReceived && this._closeFrameSent
16751
- });
16752
- event[kTarget] = this;
16753
- callListener(handler, this, event);
16754
- };
16755
- } else if (type === "error") {
16756
- wrapper = function onError(error) {
16757
- const event = new ErrorEvent("error", {
16758
- error,
16759
- message: error.message
16760
- });
16761
- event[kTarget] = this;
16762
- callListener(handler, this, event);
16763
- };
16764
- } else if (type === "open") {
16765
- wrapper = function onOpen() {
16766
- const event = new Event("open");
16767
- event[kTarget] = this;
16768
- callListener(handler, this, event);
16769
- };
16770
- } else {
16771
- return;
16772
- }
16773
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
16774
- wrapper[kListener] = handler;
16775
- if (options.once) {
16776
- this.once(type, wrapper);
16777
- } else {
16778
- this.on(type, wrapper);
16779
- }
16780
- },
16781
- /**
16782
- * Remove an event listener.
16783
- *
16784
- * @param {String} type A string representing the event type to remove
16785
- * @param {(Function|Object)} handler The listener to remove
16786
- * @public
16787
- */
16788
- removeEventListener(type, handler) {
16789
- for (const listener of this.listeners(type)) {
16790
- if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
16791
- this.removeListener(type, listener);
16792
- break;
16793
- }
16794
- }
16795
- }
16796
- };
16797
- module2.exports = {
16798
- CloseEvent,
16799
- ErrorEvent,
16800
- Event,
16801
- EventTarget,
16802
- MessageEvent
16803
- };
16804
- function callListener(listener, thisArg, event) {
16805
- if (typeof listener === "object" && listener.handleEvent) {
16806
- listener.handleEvent.call(listener, event);
16807
- } else {
16808
- listener.call(thisArg, event);
16809
- }
16810
- }
16811
- }
16812
- });
16813
-
16814
- // node_modules/ws/lib/extension.js
16815
- var require_extension = __commonJS({
16816
- "node_modules/ws/lib/extension.js"(exports2, module2) {
16817
- var { tokenChars } = require_validation();
16818
- function push(dest, name, elem) {
16819
- if (dest[name] === void 0) dest[name] = [elem];
16820
- else dest[name].push(elem);
16821
- }
16822
- function parse(header) {
16823
- const offers = /* @__PURE__ */ Object.create(null);
16824
- let params = /* @__PURE__ */ Object.create(null);
16825
- let mustUnescape = false;
16826
- let isEscaping = false;
16827
- let inQuotes = false;
16828
- let extensionName;
16829
- let paramName;
16830
- let start = -1;
16831
- let code = -1;
16832
- let end = -1;
16833
- let i = 0;
16834
- for (; i < header.length; i++) {
16835
- code = header.charCodeAt(i);
16836
- if (extensionName === void 0) {
16837
- if (end === -1 && tokenChars[code] === 1) {
16838
- if (start === -1) start = i;
16839
- } else if (i !== 0 && (code === 32 || code === 9)) {
16840
- if (end === -1 && start !== -1) end = i;
16841
- } else if (code === 59 || code === 44) {
16842
- if (start === -1) {
16843
- throw new SyntaxError(`Unexpected character at index ${i}`);
16844
- }
16845
- if (end === -1) end = i;
16846
- const name = header.slice(start, end);
16847
- if (code === 44) {
16848
- push(offers, name, params);
16849
- params = /* @__PURE__ */ Object.create(null);
16850
- } else {
16851
- extensionName = name;
16852
- }
16853
- start = end = -1;
16854
- } else {
16855
- throw new SyntaxError(`Unexpected character at index ${i}`);
16856
- }
16857
- } else if (paramName === void 0) {
16858
- if (end === -1 && tokenChars[code] === 1) {
16859
- if (start === -1) start = i;
16860
- } else if (code === 32 || code === 9) {
16861
- if (end === -1 && start !== -1) end = i;
16862
- } else if (code === 59 || code === 44) {
16863
- if (start === -1) {
16864
- throw new SyntaxError(`Unexpected character at index ${i}`);
16865
- }
16866
- if (end === -1) end = i;
16867
- push(params, header.slice(start, end), true);
16868
- if (code === 44) {
16869
- push(offers, extensionName, params);
16870
- params = /* @__PURE__ */ Object.create(null);
16871
- extensionName = void 0;
16872
- }
16873
- start = end = -1;
16874
- } else if (code === 61 && start !== -1 && end === -1) {
16875
- paramName = header.slice(start, i);
16876
- start = end = -1;
16877
- } else {
16878
- throw new SyntaxError(`Unexpected character at index ${i}`);
16879
- }
16880
- } else {
16881
- if (isEscaping) {
16882
- if (tokenChars[code] !== 1) {
16883
- throw new SyntaxError(`Unexpected character at index ${i}`);
16884
- }
16885
- if (start === -1) start = i;
16886
- else if (!mustUnescape) mustUnescape = true;
16887
- isEscaping = false;
16888
- } else if (inQuotes) {
16889
- if (tokenChars[code] === 1) {
16890
- if (start === -1) start = i;
16891
- } else if (code === 34 && start !== -1) {
16892
- inQuotes = false;
16893
- end = i;
16894
- } else if (code === 92) {
16895
- isEscaping = true;
16896
- } else {
16897
- throw new SyntaxError(`Unexpected character at index ${i}`);
16898
- }
16899
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
16900
- inQuotes = true;
16901
- } else if (end === -1 && tokenChars[code] === 1) {
16902
- if (start === -1) start = i;
16903
- } else if (start !== -1 && (code === 32 || code === 9)) {
16904
- if (end === -1) end = i;
16905
- } else if (code === 59 || code === 44) {
16906
- if (start === -1) {
16907
- throw new SyntaxError(`Unexpected character at index ${i}`);
16908
- }
16909
- if (end === -1) end = i;
16910
- let value = header.slice(start, end);
16911
- if (mustUnescape) {
16912
- value = value.replace(/\\/g, "");
16913
- mustUnescape = false;
16914
- }
16915
- push(params, paramName, value);
16916
- if (code === 44) {
16917
- push(offers, extensionName, params);
16918
- params = /* @__PURE__ */ Object.create(null);
16919
- extensionName = void 0;
16920
- }
16921
- paramName = void 0;
16922
- start = end = -1;
16923
- } else {
16924
- throw new SyntaxError(`Unexpected character at index ${i}`);
16925
- }
16926
- }
16927
- }
16928
- if (start === -1 || inQuotes || code === 32 || code === 9) {
16929
- throw new SyntaxError("Unexpected end of input");
16930
- }
16931
- if (end === -1) end = i;
16932
- const token = header.slice(start, end);
16933
- if (extensionName === void 0) {
16934
- push(offers, token, params);
16935
- } else {
16936
- if (paramName === void 0) {
16937
- push(params, token, true);
16938
- } else if (mustUnescape) {
16939
- push(params, paramName, token.replace(/\\/g, ""));
16940
- } else {
16941
- push(params, paramName, token);
16942
- }
16943
- push(offers, extensionName, params);
16944
- }
16945
- return offers;
16946
- }
16947
- function format(extensions) {
16948
- return Object.keys(extensions).map((extension) => {
16949
- let configurations = extensions[extension];
16950
- if (!Array.isArray(configurations)) configurations = [configurations];
16951
- return configurations.map((params) => {
16952
- return [extension].concat(
16953
- Object.keys(params).map((k) => {
16954
- let values = params[k];
16955
- if (!Array.isArray(values)) values = [values];
16956
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
16957
- })
16958
- ).join("; ");
16959
- }).join(", ");
16960
- }).join(", ");
16961
- }
16962
- module2.exports = { format, parse };
16963
- }
16964
- });
16965
-
16966
- // node_modules/ws/lib/websocket.js
16967
- var require_websocket = __commonJS({
16968
- "node_modules/ws/lib/websocket.js"(exports2, module2) {
16969
- var EventEmitter2 = __require("events");
16970
- var https2 = __require("https");
16971
- var http3 = __require("http");
16972
- var net = __require("net");
16973
- var tls = __require("tls");
16974
- var { randomBytes, createHash } = __require("crypto");
16975
- var { Duplex, Readable: Readable2 } = __require("stream");
16976
- var { URL: URL2 } = __require("url");
16977
- var PerMessageDeflate = require_permessage_deflate();
16978
- var Receiver2 = require_receiver();
16979
- var Sender2 = require_sender();
16980
- var { isBlob: isBlob2 } = require_validation();
16981
- var {
16982
- BINARY_TYPES,
16983
- CLOSE_TIMEOUT,
16984
- EMPTY_BUFFER,
16985
- GUID,
16986
- kForOnEventAttribute,
16987
- kListener,
16988
- kStatusCode,
16989
- kWebSocket,
16990
- NOOP
16991
- } = require_constants();
16992
- var {
16993
- EventTarget: { addEventListener, removeEventListener }
16994
- } = require_event_target();
16995
- var { format, parse } = require_extension();
16996
- var { toBuffer } = require_buffer_util();
16997
- var kAborted = /* @__PURE__ */ Symbol("kAborted");
16998
- var protocolVersions = [8, 13];
16999
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
17000
- var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
17001
- var WebSocket2 = class _WebSocket extends EventEmitter2 {
17002
- /**
17003
- * Create a new `WebSocket`.
17004
- *
17005
- * @param {(String|URL)} address The URL to which to connect
17006
- * @param {(String|String[])} [protocols] The subprotocols
17007
- * @param {Object} [options] Connection options
17008
- */
17009
- constructor(address, protocols, options) {
17010
- super();
17011
- this._binaryType = BINARY_TYPES[0];
17012
- this._closeCode = 1006;
17013
- this._closeFrameReceived = false;
17014
- this._closeFrameSent = false;
17015
- this._closeMessage = EMPTY_BUFFER;
17016
- this._closeTimer = null;
17017
- this._errorEmitted = false;
17018
- this._extensions = {};
17019
- this._paused = false;
17020
- this._protocol = "";
17021
- this._readyState = _WebSocket.CONNECTING;
17022
- this._receiver = null;
17023
- this._sender = null;
17024
- this._socket = null;
17025
- if (address !== null) {
17026
- this._bufferedAmount = 0;
17027
- this._isServer = false;
17028
- this._redirects = 0;
17029
- if (protocols === void 0) {
17030
- protocols = [];
17031
- } else if (!Array.isArray(protocols)) {
17032
- if (typeof protocols === "object" && protocols !== null) {
17033
- options = protocols;
17034
- protocols = [];
17035
- } else {
17036
- protocols = [protocols];
17037
- }
17038
- }
17039
- initAsClient(this, address, protocols, options);
17040
- } else {
17041
- this._autoPong = options.autoPong;
17042
- this._closeTimeout = options.closeTimeout;
17043
- this._isServer = true;
17044
- }
17045
- }
17046
- /**
17047
- * For historical reasons, the custom "nodebuffer" type is used by the default
17048
- * instead of "blob".
17049
- *
17050
- * @type {String}
17051
- */
17052
- get binaryType() {
17053
- return this._binaryType;
17054
- }
17055
- set binaryType(type) {
17056
- if (!BINARY_TYPES.includes(type)) return;
17057
- this._binaryType = type;
17058
- if (this._receiver) this._receiver._binaryType = type;
17059
- }
17060
- /**
17061
- * @type {Number}
17062
- */
17063
- get bufferedAmount() {
17064
- if (!this._socket) return this._bufferedAmount;
17065
- return this._socket._writableState.length + this._sender._bufferedBytes;
17066
- }
17067
- /**
17068
- * @type {String}
17069
- */
17070
- get extensions() {
17071
- return Object.keys(this._extensions).join();
17072
- }
17073
- /**
17074
- * @type {Boolean}
17075
- */
17076
- get isPaused() {
17077
- return this._paused;
17078
- }
17079
- /**
17080
- * @type {Function}
17081
- */
17082
- /* istanbul ignore next */
17083
- get onclose() {
17084
- return null;
17085
- }
17086
- /**
17087
- * @type {Function}
17088
- */
17089
- /* istanbul ignore next */
17090
- get onerror() {
17091
- return null;
17092
- }
17093
- /**
17094
- * @type {Function}
17095
- */
17096
- /* istanbul ignore next */
17097
- get onopen() {
17098
- return null;
17099
- }
17100
- /**
17101
- * @type {Function}
17102
- */
17103
- /* istanbul ignore next */
17104
- get onmessage() {
17105
- return null;
17106
- }
17107
- /**
17108
- * @type {String}
17109
- */
17110
- get protocol() {
17111
- return this._protocol;
17112
- }
17113
- /**
17114
- * @type {Number}
17115
- */
17116
- get readyState() {
17117
- return this._readyState;
17118
- }
17119
- /**
17120
- * @type {String}
17121
- */
17122
- get url() {
17123
- return this._url;
17124
- }
17125
- /**
17126
- * Set up the socket and the internal resources.
17127
- *
17128
- * @param {Duplex} socket The network socket between the server and client
17129
- * @param {Buffer} head The first packet of the upgraded stream
17130
- * @param {Object} options Options object
17131
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
17132
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
17133
- * multiple times in the same tick
17134
- * @param {Function} [options.generateMask] The function used to generate the
17135
- * masking key
17136
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
17137
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
17138
- * not to skip UTF-8 validation for text and close messages
17139
- * @private
17140
- */
17141
- setSocket(socket, head, options) {
17142
- const receiver = new Receiver2({
17143
- allowSynchronousEvents: options.allowSynchronousEvents,
17144
- binaryType: this.binaryType,
17145
- extensions: this._extensions,
17146
- isServer: this._isServer,
17147
- maxPayload: options.maxPayload,
17148
- skipUTF8Validation: options.skipUTF8Validation
17149
- });
17150
- const sender = new Sender2(socket, this._extensions, options.generateMask);
17151
- this._receiver = receiver;
17152
- this._sender = sender;
17153
- this._socket = socket;
17154
- receiver[kWebSocket] = this;
17155
- sender[kWebSocket] = this;
17156
- socket[kWebSocket] = this;
17157
- receiver.on("conclude", receiverOnConclude);
17158
- receiver.on("drain", receiverOnDrain);
17159
- receiver.on("error", receiverOnError);
17160
- receiver.on("message", receiverOnMessage);
17161
- receiver.on("ping", receiverOnPing);
17162
- receiver.on("pong", receiverOnPong);
17163
- sender.onerror = senderOnError;
17164
- if (socket.setTimeout) socket.setTimeout(0);
17165
- if (socket.setNoDelay) socket.setNoDelay();
17166
- if (head.length > 0) socket.unshift(head);
17167
- socket.on("close", socketOnClose);
17168
- socket.on("data", socketOnData);
17169
- socket.on("end", socketOnEnd);
17170
- socket.on("error", socketOnError);
17171
- this._readyState = _WebSocket.OPEN;
17172
- this.emit("open");
17173
- }
17174
- /**
17175
- * Emit the `'close'` event.
17176
- *
17177
- * @private
17178
- */
17179
- emitClose() {
17180
- if (!this._socket) {
17181
- this._readyState = _WebSocket.CLOSED;
17182
- this.emit("close", this._closeCode, this._closeMessage);
17183
- return;
17184
- }
17185
- if (this._extensions[PerMessageDeflate.extensionName]) {
17186
- this._extensions[PerMessageDeflate.extensionName].cleanup();
17187
- }
17188
- this._receiver.removeAllListeners();
17189
- this._readyState = _WebSocket.CLOSED;
17190
- this.emit("close", this._closeCode, this._closeMessage);
17191
- }
17192
- /**
17193
- * Start a closing handshake.
17194
- *
17195
- * +----------+ +-----------+ +----------+
17196
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
17197
- * | +----------+ +-----------+ +----------+ |
17198
- * +----------+ +-----------+ |
17199
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
17200
- * +----------+ +-----------+ |
17201
- * | | | +---+ |
17202
- * +------------------------+-->|fin| - - - -
17203
- * | +---+ | +---+
17204
- * - - - - -|fin|<---------------------+
17205
- * +---+
17206
- *
17207
- * @param {Number} [code] Status code explaining why the connection is closing
17208
- * @param {(String|Buffer)} [data] The reason why the connection is
17209
- * closing
17210
- * @public
17211
- */
17212
- close(code, data) {
17213
- if (this.readyState === _WebSocket.CLOSED) return;
17214
- if (this.readyState === _WebSocket.CONNECTING) {
17215
- const msg = "WebSocket was closed before the connection was established";
17216
- abortHandshake(this, this._req, msg);
17217
- return;
17218
- }
17219
- if (this.readyState === _WebSocket.CLOSING) {
17220
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
17221
- this._socket.end();
17222
- }
17223
- return;
17224
- }
17225
- this._readyState = _WebSocket.CLOSING;
17226
- this._sender.close(code, data, !this._isServer, (err) => {
17227
- if (err) return;
17228
- this._closeFrameSent = true;
17229
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
17230
- this._socket.end();
17231
- }
17232
- });
17233
- setCloseTimer(this);
17234
- }
17235
- /**
17236
- * Pause the socket.
17237
- *
17238
- * @public
17239
- */
17240
- pause() {
17241
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
17242
- return;
17243
- }
17244
- this._paused = true;
17245
- this._socket.pause();
17246
- }
17247
- /**
17248
- * Send a ping.
17249
- *
17250
- * @param {*} [data] The data to send
17251
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
17252
- * @param {Function} [cb] Callback which is executed when the ping is sent
17253
- * @public
17254
- */
17255
- ping(data, mask, cb) {
17256
- if (this.readyState === _WebSocket.CONNECTING) {
17257
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
17258
- }
17259
- if (typeof data === "function") {
17260
- cb = data;
17261
- data = mask = void 0;
17262
- } else if (typeof mask === "function") {
17263
- cb = mask;
17264
- mask = void 0;
17265
- }
17266
- if (typeof data === "number") data = data.toString();
17267
- if (this.readyState !== _WebSocket.OPEN) {
17268
- sendAfterClose(this, data, cb);
17269
- return;
17270
- }
17271
- if (mask === void 0) mask = !this._isServer;
17272
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
17273
- }
17274
- /**
17275
- * Send a pong.
17276
- *
17277
- * @param {*} [data] The data to send
17278
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
17279
- * @param {Function} [cb] Callback which is executed when the pong is sent
17280
- * @public
17281
- */
17282
- pong(data, mask, cb) {
17283
- if (this.readyState === _WebSocket.CONNECTING) {
17284
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
17285
- }
17286
- if (typeof data === "function") {
17287
- cb = data;
17288
- data = mask = void 0;
17289
- } else if (typeof mask === "function") {
17290
- cb = mask;
17291
- mask = void 0;
17292
- }
17293
- if (typeof data === "number") data = data.toString();
17294
- if (this.readyState !== _WebSocket.OPEN) {
17295
- sendAfterClose(this, data, cb);
17296
- return;
17297
- }
17298
- if (mask === void 0) mask = !this._isServer;
17299
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
17300
- }
17301
- /**
17302
- * Resume the socket.
17303
- *
17304
- * @public
17305
- */
17306
- resume() {
17307
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
17308
- return;
17309
- }
17310
- this._paused = false;
17311
- if (!this._receiver._writableState.needDrain) this._socket.resume();
17312
- }
17313
- /**
17314
- * Send a data message.
17315
- *
17316
- * @param {*} data The message to send
17317
- * @param {Object} [options] Options object
17318
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
17319
- * text
17320
- * @param {Boolean} [options.compress] Specifies whether or not to compress
17321
- * `data`
17322
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
17323
- * last one
17324
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
17325
- * @param {Function} [cb] Callback which is executed when data is written out
17326
- * @public
17327
- */
17328
- send(data, options, cb) {
17329
- if (this.readyState === _WebSocket.CONNECTING) {
17330
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
17331
- }
17332
- if (typeof options === "function") {
17333
- cb = options;
17334
- options = {};
17335
- }
17336
- if (typeof data === "number") data = data.toString();
17337
- if (this.readyState !== _WebSocket.OPEN) {
17338
- sendAfterClose(this, data, cb);
17339
- return;
17340
- }
17341
- const opts = {
17342
- binary: typeof data !== "string",
17343
- mask: !this._isServer,
17344
- compress: true,
17345
- fin: true,
17346
- ...options
17347
- };
17348
- if (!this._extensions[PerMessageDeflate.extensionName]) {
17349
- opts.compress = false;
17350
- }
17351
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
17352
- }
17353
- /**
17354
- * Forcibly close the connection.
17355
- *
17356
- * @public
17357
- */
17358
- terminate() {
17359
- if (this.readyState === _WebSocket.CLOSED) return;
17360
- if (this.readyState === _WebSocket.CONNECTING) {
17361
- const msg = "WebSocket was closed before the connection was established";
17362
- abortHandshake(this, this._req, msg);
17363
- return;
17364
- }
17365
- if (this._socket) {
17366
- this._readyState = _WebSocket.CLOSING;
17367
- this._socket.destroy();
17368
- }
17369
- }
17370
- };
17371
- Object.defineProperty(WebSocket2, "CONNECTING", {
17372
- enumerable: true,
17373
- value: readyStates.indexOf("CONNECTING")
17374
- });
17375
- Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
17376
- enumerable: true,
17377
- value: readyStates.indexOf("CONNECTING")
17378
- });
17379
- Object.defineProperty(WebSocket2, "OPEN", {
17380
- enumerable: true,
17381
- value: readyStates.indexOf("OPEN")
17382
- });
17383
- Object.defineProperty(WebSocket2.prototype, "OPEN", {
17384
- enumerable: true,
17385
- value: readyStates.indexOf("OPEN")
17386
- });
17387
- Object.defineProperty(WebSocket2, "CLOSING", {
17388
- enumerable: true,
17389
- value: readyStates.indexOf("CLOSING")
17390
- });
17391
- Object.defineProperty(WebSocket2.prototype, "CLOSING", {
17392
- enumerable: true,
17393
- value: readyStates.indexOf("CLOSING")
17394
- });
17395
- Object.defineProperty(WebSocket2, "CLOSED", {
17396
- enumerable: true,
17397
- value: readyStates.indexOf("CLOSED")
17398
- });
17399
- Object.defineProperty(WebSocket2.prototype, "CLOSED", {
17400
- enumerable: true,
17401
- value: readyStates.indexOf("CLOSED")
17402
- });
17403
- [
17404
- "binaryType",
17405
- "bufferedAmount",
17406
- "extensions",
17407
- "isPaused",
17408
- "protocol",
17409
- "readyState",
17410
- "url"
17411
- ].forEach((property) => {
17412
- Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
17413
- });
17414
- ["open", "error", "close", "message"].forEach((method) => {
17415
- Object.defineProperty(WebSocket2.prototype, `on${method}`, {
17416
- enumerable: true,
17417
- get() {
17418
- for (const listener of this.listeners(method)) {
17419
- if (listener[kForOnEventAttribute]) return listener[kListener];
17420
- }
17421
- return null;
17422
- },
17423
- set(handler) {
17424
- for (const listener of this.listeners(method)) {
17425
- if (listener[kForOnEventAttribute]) {
17426
- this.removeListener(method, listener);
17427
- break;
17428
- }
17429
- }
17430
- if (typeof handler !== "function") return;
17431
- this.addEventListener(method, handler, {
17432
- [kForOnEventAttribute]: true
17433
- });
17434
- }
17435
- });
17436
- });
17437
- WebSocket2.prototype.addEventListener = addEventListener;
17438
- WebSocket2.prototype.removeEventListener = removeEventListener;
17439
- module2.exports = WebSocket2;
17440
- function initAsClient(websocket, address, protocols, options) {
17441
- const opts = {
17442
- allowSynchronousEvents: true,
17443
- autoPong: true,
17444
- closeTimeout: CLOSE_TIMEOUT,
17445
- protocolVersion: protocolVersions[1],
17446
- maxPayload: 100 * 1024 * 1024,
17447
- skipUTF8Validation: false,
17448
- perMessageDeflate: true,
17449
- followRedirects: false,
17450
- maxRedirects: 10,
17451
- ...options,
17452
- socketPath: void 0,
17453
- hostname: void 0,
17454
- protocol: void 0,
17455
- timeout: void 0,
17456
- method: "GET",
17457
- host: void 0,
17458
- path: void 0,
17459
- port: void 0
17460
- };
17461
- websocket._autoPong = opts.autoPong;
17462
- websocket._closeTimeout = opts.closeTimeout;
17463
- if (!protocolVersions.includes(opts.protocolVersion)) {
17464
- throw new RangeError(
17465
- `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
17466
- );
17467
- }
17468
- let parsedUrl;
17469
- if (address instanceof URL2) {
17470
- parsedUrl = address;
17471
- } else {
17472
- try {
17473
- parsedUrl = new URL2(address);
17474
- } catch (e) {
17475
- throw new SyntaxError(`Invalid URL: ${address}`);
17476
- }
17477
- }
17478
- if (parsedUrl.protocol === "http:") {
17479
- parsedUrl.protocol = "ws:";
17480
- } else if (parsedUrl.protocol === "https:") {
17481
- parsedUrl.protocol = "wss:";
17482
- }
17483
- websocket._url = parsedUrl.href;
17484
- const isSecure = parsedUrl.protocol === "wss:";
17485
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
17486
- let invalidUrlMessage;
17487
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
17488
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
17489
- } else if (isIpcUrl && !parsedUrl.pathname) {
17490
- invalidUrlMessage = "The URL's pathname is empty";
17491
- } else if (parsedUrl.hash) {
17492
- invalidUrlMessage = "The URL contains a fragment identifier";
17493
- }
17494
- if (invalidUrlMessage) {
17495
- const err = new SyntaxError(invalidUrlMessage);
17496
- if (websocket._redirects === 0) {
17497
- throw err;
17498
- } else {
17499
- emitErrorAndClose(websocket, err);
17500
- return;
17501
- }
17502
- }
17503
- const defaultPort = isSecure ? 443 : 80;
17504
- const key = randomBytes(16).toString("base64");
17505
- const request = isSecure ? https2.request : http3.request;
17506
- const protocolSet = /* @__PURE__ */ new Set();
17507
- let perMessageDeflate;
17508
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
17509
- opts.defaultPort = opts.defaultPort || defaultPort;
17510
- opts.port = parsedUrl.port || defaultPort;
17511
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
17512
- opts.headers = {
17513
- ...opts.headers,
17514
- "Sec-WebSocket-Version": opts.protocolVersion,
17515
- "Sec-WebSocket-Key": key,
17516
- Connection: "Upgrade",
17517
- Upgrade: "websocket"
17518
- };
17519
- opts.path = parsedUrl.pathname + parsedUrl.search;
17520
- opts.timeout = opts.handshakeTimeout;
17521
- if (opts.perMessageDeflate) {
17522
- perMessageDeflate = new PerMessageDeflate(
17523
- opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
17524
- false,
17525
- opts.maxPayload
17526
- );
17527
- opts.headers["Sec-WebSocket-Extensions"] = format({
17528
- [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
17529
- });
17530
- }
17531
- if (protocols.length) {
17532
- for (const protocol of protocols) {
17533
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
17534
- throw new SyntaxError(
17535
- "An invalid or duplicated subprotocol was specified"
17536
- );
17537
- }
17538
- protocolSet.add(protocol);
17539
- }
17540
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
17541
- }
17542
- if (opts.origin) {
17543
- if (opts.protocolVersion < 13) {
17544
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
17545
- } else {
17546
- opts.headers.Origin = opts.origin;
17547
- }
17548
- }
17549
- if (parsedUrl.username || parsedUrl.password) {
17550
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
17551
- }
17552
- if (isIpcUrl) {
17553
- const parts = opts.path.split(":");
17554
- opts.socketPath = parts[0];
17555
- opts.path = parts[1];
17556
- }
17557
- let req;
17558
- if (opts.followRedirects) {
17559
- if (websocket._redirects === 0) {
17560
- websocket._originalIpc = isIpcUrl;
17561
- websocket._originalSecure = isSecure;
17562
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
17563
- const headers = options && options.headers;
17564
- options = { ...options, headers: {} };
17565
- if (headers) {
17566
- for (const [key2, value] of Object.entries(headers)) {
17567
- options.headers[key2.toLowerCase()] = value;
17568
- }
17569
- }
17570
- } else if (websocket.listenerCount("redirect") === 0) {
17571
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
17572
- if (!isSameHost || websocket._originalSecure && !isSecure) {
17573
- delete opts.headers.authorization;
17574
- delete opts.headers.cookie;
17575
- if (!isSameHost) delete opts.headers.host;
17576
- opts.auth = void 0;
17577
- }
17578
- }
17579
- if (opts.auth && !options.headers.authorization) {
17580
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
17581
- }
17582
- req = websocket._req = request(opts);
17583
- if (websocket._redirects) {
17584
- websocket.emit("redirect", websocket.url, req);
17585
- }
17586
- } else {
17587
- req = websocket._req = request(opts);
17588
- }
17589
- if (opts.timeout) {
17590
- req.on("timeout", () => {
17591
- abortHandshake(websocket, req, "Opening handshake has timed out");
17592
- });
17593
- }
17594
- req.on("error", (err) => {
17595
- if (req === null || req[kAborted]) return;
17596
- req = websocket._req = null;
17597
- emitErrorAndClose(websocket, err);
17598
- });
17599
- req.on("response", (res) => {
17600
- const location = res.headers.location;
17601
- const statusCode = res.statusCode;
17602
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
17603
- if (++websocket._redirects > opts.maxRedirects) {
17604
- abortHandshake(websocket, req, "Maximum redirects exceeded");
17605
- return;
17606
- }
17607
- req.abort();
17608
- let addr;
17609
- try {
17610
- addr = new URL2(location, address);
17611
- } catch (e) {
17612
- const err = new SyntaxError(`Invalid URL: ${location}`);
17613
- emitErrorAndClose(websocket, err);
17614
- return;
17615
- }
17616
- initAsClient(websocket, addr, protocols, options);
17617
- } else if (!websocket.emit("unexpected-response", req, res)) {
17618
- abortHandshake(
17619
- websocket,
17620
- req,
17621
- `Unexpected server response: ${res.statusCode}`
17622
- );
17623
- }
17624
- });
17625
- req.on("upgrade", (res, socket, head) => {
17626
- websocket.emit("upgrade", res);
17627
- if (websocket.readyState !== WebSocket2.CONNECTING) return;
17628
- req = websocket._req = null;
17629
- const upgrade = res.headers.upgrade;
17630
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
17631
- abortHandshake(websocket, socket, "Invalid Upgrade header");
17632
- return;
17633
- }
17634
- const digest = createHash("sha1").update(key + GUID).digest("base64");
17635
- if (res.headers["sec-websocket-accept"] !== digest) {
17636
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
17637
- return;
17638
- }
17639
- const serverProt = res.headers["sec-websocket-protocol"];
17640
- let protError;
17641
- if (serverProt !== void 0) {
17642
- if (!protocolSet.size) {
17643
- protError = "Server sent a subprotocol but none was requested";
17644
- } else if (!protocolSet.has(serverProt)) {
17645
- protError = "Server sent an invalid subprotocol";
17646
- }
17647
- } else if (protocolSet.size) {
17648
- protError = "Server sent no subprotocol";
17649
- }
17650
- if (protError) {
17651
- abortHandshake(websocket, socket, protError);
17652
- return;
17653
- }
17654
- if (serverProt) websocket._protocol = serverProt;
17655
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
17656
- if (secWebSocketExtensions !== void 0) {
17657
- if (!perMessageDeflate) {
17658
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
17659
- abortHandshake(websocket, socket, message);
17660
- return;
17661
- }
17662
- let extensions;
17663
- try {
17664
- extensions = parse(secWebSocketExtensions);
17665
- } catch (err) {
17666
- const message = "Invalid Sec-WebSocket-Extensions header";
17667
- abortHandshake(websocket, socket, message);
17668
- return;
17669
- }
17670
- const extensionNames = Object.keys(extensions);
17671
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
17672
- const message = "Server indicated an extension that was not requested";
17673
- abortHandshake(websocket, socket, message);
17674
- return;
17675
- }
17676
- try {
17677
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
17678
- } catch (err) {
17679
- const message = "Invalid Sec-WebSocket-Extensions header";
17680
- abortHandshake(websocket, socket, message);
17681
- return;
17682
- }
17683
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
17684
- }
17685
- websocket.setSocket(socket, head, {
17686
- allowSynchronousEvents: opts.allowSynchronousEvents,
17687
- generateMask: opts.generateMask,
17688
- maxPayload: opts.maxPayload,
17689
- skipUTF8Validation: opts.skipUTF8Validation
17690
- });
17691
- });
17692
- if (opts.finishRequest) {
17693
- opts.finishRequest(req, websocket);
17694
- } else {
17695
- req.end();
17696
- }
17697
- }
17698
- function emitErrorAndClose(websocket, err) {
17699
- websocket._readyState = WebSocket2.CLOSING;
17700
- websocket._errorEmitted = true;
17701
- websocket.emit("error", err);
17702
- websocket.emitClose();
17703
- }
17704
- function netConnect(options) {
17705
- options.path = options.socketPath;
17706
- return net.connect(options);
17707
- }
17708
- function tlsConnect(options) {
17709
- options.path = void 0;
17710
- if (!options.servername && options.servername !== "") {
17711
- options.servername = net.isIP(options.host) ? "" : options.host;
17712
- }
17713
- return tls.connect(options);
17714
- }
17715
- function abortHandshake(websocket, stream4, message) {
17716
- websocket._readyState = WebSocket2.CLOSING;
17717
- const err = new Error(message);
17718
- Error.captureStackTrace(err, abortHandshake);
17719
- if (stream4.setHeader) {
17720
- stream4[kAborted] = true;
17721
- stream4.abort();
17722
- if (stream4.socket && !stream4.socket.destroyed) {
17723
- stream4.socket.destroy();
17724
- }
17725
- process.nextTick(emitErrorAndClose, websocket, err);
17726
- } else {
17727
- stream4.destroy(err);
17728
- stream4.once("error", websocket.emit.bind(websocket, "error"));
17729
- stream4.once("close", websocket.emitClose.bind(websocket));
17730
- }
17731
- }
17732
- function sendAfterClose(websocket, data, cb) {
17733
- if (data) {
17734
- const length = isBlob2(data) ? data.size : toBuffer(data).length;
17735
- if (websocket._socket) websocket._sender._bufferedBytes += length;
17736
- else websocket._bufferedAmount += length;
17737
- }
17738
- if (cb) {
17739
- const err = new Error(
17740
- `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
17741
- );
17742
- process.nextTick(cb, err);
17743
- }
17744
- }
17745
- function receiverOnConclude(code, reason) {
17746
- const websocket = this[kWebSocket];
17747
- websocket._closeFrameReceived = true;
17748
- websocket._closeMessage = reason;
17749
- websocket._closeCode = code;
17750
- if (websocket._socket[kWebSocket] === void 0) return;
17751
- websocket._socket.removeListener("data", socketOnData);
17752
- process.nextTick(resume, websocket._socket);
17753
- if (code === 1005) websocket.close();
17754
- else websocket.close(code, reason);
17755
- }
17756
- function receiverOnDrain() {
17757
- const websocket = this[kWebSocket];
17758
- if (!websocket.isPaused) websocket._socket.resume();
17759
- }
17760
- function receiverOnError(err) {
17761
- const websocket = this[kWebSocket];
17762
- if (websocket._socket[kWebSocket] !== void 0) {
17763
- websocket._socket.removeListener("data", socketOnData);
17764
- process.nextTick(resume, websocket._socket);
17765
- websocket.close(err[kStatusCode]);
17766
- }
17767
- if (!websocket._errorEmitted) {
17768
- websocket._errorEmitted = true;
17769
- websocket.emit("error", err);
17770
- }
17771
- }
17772
- function receiverOnFinish() {
17773
- this[kWebSocket].emitClose();
17774
- }
17775
- function receiverOnMessage(data, isBinary) {
17776
- this[kWebSocket].emit("message", data, isBinary);
17777
- }
17778
- function receiverOnPing(data) {
17779
- const websocket = this[kWebSocket];
17780
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
17781
- websocket.emit("ping", data);
17782
- }
17783
- function receiverOnPong(data) {
17784
- this[kWebSocket].emit("pong", data);
17785
- }
17786
- function resume(stream4) {
17787
- stream4.resume();
17788
- }
17789
- function senderOnError(err) {
17790
- const websocket = this[kWebSocket];
17791
- if (websocket.readyState === WebSocket2.CLOSED) return;
17792
- if (websocket.readyState === WebSocket2.OPEN) {
17793
- websocket._readyState = WebSocket2.CLOSING;
17794
- setCloseTimer(websocket);
17795
- }
17796
- this._socket.end();
17797
- if (!websocket._errorEmitted) {
17798
- websocket._errorEmitted = true;
17799
- websocket.emit("error", err);
17800
- }
17801
- }
17802
- function setCloseTimer(websocket) {
17803
- websocket._closeTimer = setTimeout(
17804
- websocket._socket.destroy.bind(websocket._socket),
17805
- websocket._closeTimeout
17806
- );
17807
- }
17808
- function socketOnClose() {
17809
- const websocket = this[kWebSocket];
17810
- this.removeListener("close", socketOnClose);
17811
- this.removeListener("data", socketOnData);
17812
- this.removeListener("end", socketOnEnd);
17813
- websocket._readyState = WebSocket2.CLOSING;
17814
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
17815
- const chunk = this.read(this._readableState.length);
17816
- websocket._receiver.write(chunk);
17817
- }
17818
- websocket._receiver.end();
17819
- this[kWebSocket] = void 0;
17820
- clearTimeout(websocket._closeTimer);
17821
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
17822
- websocket.emitClose();
17823
- } else {
17824
- websocket._receiver.on("error", receiverOnFinish);
17825
- websocket._receiver.on("finish", receiverOnFinish);
17826
- }
17827
- }
17828
- function socketOnData(chunk) {
17829
- if (!this[kWebSocket]._receiver.write(chunk)) {
17830
- this.pause();
17831
- }
17832
- }
17833
- function socketOnEnd() {
17834
- const websocket = this[kWebSocket];
17835
- websocket._readyState = WebSocket2.CLOSING;
17836
- websocket._receiver.end();
17837
- this.end();
17838
- }
17839
- function socketOnError() {
17840
- const websocket = this[kWebSocket];
17841
- this.removeListener("error", socketOnError);
17842
- this.on("error", NOOP);
17843
- if (websocket) {
17844
- websocket._readyState = WebSocket2.CLOSING;
17845
- this.destroy();
17846
- }
17847
- }
17848
- }
17849
- });
17850
-
17851
- // node_modules/ws/lib/stream.js
17852
- var require_stream = __commonJS({
17853
- "node_modules/ws/lib/stream.js"(exports2, module2) {
17854
- require_websocket();
17855
- var { Duplex } = __require("stream");
17856
- function emitClose(stream4) {
17857
- stream4.emit("close");
17858
- }
17859
- function duplexOnEnd() {
17860
- if (!this.destroyed && this._writableState.finished) {
17861
- this.destroy();
17862
- }
17863
- }
17864
- function duplexOnError(err) {
17865
- this.removeListener("error", duplexOnError);
17866
- this.destroy();
17867
- if (this.listenerCount("error") === 0) {
17868
- this.emit("error", err);
17869
- }
17870
- }
17871
- function createWebSocketStream2(ws, options) {
17872
- let terminateOnDestroy = true;
17873
- const duplex = new Duplex({
17874
- ...options,
17875
- autoDestroy: false,
17876
- emitClose: false,
17877
- objectMode: false,
17878
- writableObjectMode: false
17879
- });
17880
- ws.on("message", function message(msg, isBinary) {
17881
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
17882
- if (!duplex.push(data)) ws.pause();
17883
- });
17884
- ws.once("error", function error(err) {
17885
- if (duplex.destroyed) return;
17886
- terminateOnDestroy = false;
17887
- duplex.destroy(err);
17888
- });
17889
- ws.once("close", function close() {
17890
- if (duplex.destroyed) return;
17891
- duplex.push(null);
17892
- });
17893
- duplex._destroy = function(err, callback) {
17894
- if (ws.readyState === ws.CLOSED) {
17895
- callback(err);
17896
- process.nextTick(emitClose, duplex);
17897
- return;
17898
- }
17899
- let called = false;
17900
- ws.once("error", function error(err2) {
17901
- called = true;
17902
- callback(err2);
17903
- });
17904
- ws.once("close", function close() {
17905
- if (!called) callback(err);
17906
- process.nextTick(emitClose, duplex);
17907
- });
17908
- if (terminateOnDestroy) ws.terminate();
17909
- };
17910
- duplex._final = function(callback) {
17911
- if (ws.readyState === ws.CONNECTING) {
17912
- ws.once("open", function open() {
17913
- duplex._final(callback);
17914
- });
17915
- return;
17916
- }
17917
- if (ws._socket === null) return;
17918
- if (ws._socket._writableState.finished) {
17919
- callback();
17920
- if (duplex._readableState.endEmitted) duplex.destroy();
17921
- } else {
17922
- ws._socket.once("finish", function finish() {
17923
- callback();
17924
- });
17925
- ws.close();
17926
- }
17927
- };
17928
- duplex._read = function() {
17929
- if (ws.isPaused) ws.resume();
17930
- };
17931
- duplex._write = function(chunk, encoding, callback) {
17932
- if (ws.readyState === ws.CONNECTING) {
17933
- ws.once("open", function open() {
17934
- duplex._write(chunk, encoding, callback);
17935
- });
17936
- return;
17937
- }
17938
- ws.send(chunk, callback);
17939
- };
17940
- duplex.on("end", duplexOnEnd);
17941
- duplex.on("error", duplexOnError);
17942
- return duplex;
17943
- }
17944
- module2.exports = createWebSocketStream2;
17945
- }
17946
- });
17947
-
17948
- // node_modules/ws/lib/subprotocol.js
17949
- var require_subprotocol = __commonJS({
17950
- "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
17951
- var { tokenChars } = require_validation();
17952
- function parse(header) {
17953
- const protocols = /* @__PURE__ */ new Set();
17954
- let start = -1;
17955
- let end = -1;
17956
- let i = 0;
17957
- for (i; i < header.length; i++) {
17958
- const code = header.charCodeAt(i);
17959
- if (end === -1 && tokenChars[code] === 1) {
17960
- if (start === -1) start = i;
17961
- } else if (i !== 0 && (code === 32 || code === 9)) {
17962
- if (end === -1 && start !== -1) end = i;
17963
- } else if (code === 44) {
17964
- if (start === -1) {
17965
- throw new SyntaxError(`Unexpected character at index ${i}`);
17966
- }
17967
- if (end === -1) end = i;
17968
- const protocol2 = header.slice(start, end);
17969
- if (protocols.has(protocol2)) {
17970
- throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
17971
- }
17972
- protocols.add(protocol2);
17973
- start = end = -1;
17974
- } else {
17975
- throw new SyntaxError(`Unexpected character at index ${i}`);
17976
- }
17977
- }
17978
- if (start === -1 || end !== -1) {
17979
- throw new SyntaxError("Unexpected end of input");
17980
- }
17981
- const protocol = header.slice(start, i);
17982
- if (protocols.has(protocol)) {
17983
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
17984
- }
17985
- protocols.add(protocol);
17986
- return protocols;
17987
- }
17988
- module2.exports = { parse };
17989
- }
17990
- });
17991
-
17992
- // node_modules/ws/lib/websocket-server.js
17993
- var require_websocket_server = __commonJS({
17994
- "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
17995
- var EventEmitter2 = __require("events");
17996
- var http3 = __require("http");
17997
- var { Duplex } = __require("stream");
17998
- var { createHash } = __require("crypto");
17999
- var extension = require_extension();
18000
- var PerMessageDeflate = require_permessage_deflate();
18001
- var subprotocol = require_subprotocol();
18002
- var WebSocket2 = require_websocket();
18003
- var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
18004
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
18005
- var RUNNING = 0;
18006
- var CLOSING = 1;
18007
- var CLOSED = 2;
18008
- var WebSocketServer2 = class extends EventEmitter2 {
18009
- /**
18010
- * Create a `WebSocketServer` instance.
18011
- *
18012
- * @param {Object} options Configuration options
18013
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
18014
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
18015
- * multiple times in the same tick
18016
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
18017
- * automatically send a pong in response to a ping
18018
- * @param {Number} [options.backlog=511] The maximum length of the queue of
18019
- * pending connections
18020
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
18021
- * track clients
18022
- * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
18023
- * wait for the closing handshake to finish after `websocket.close()` is
18024
- * called
18025
- * @param {Function} [options.handleProtocols] A hook to handle protocols
18026
- * @param {String} [options.host] The hostname where to bind the server
18027
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
18028
- * size
18029
- * @param {Boolean} [options.noServer=false] Enable no server mode
18030
- * @param {String} [options.path] Accept only connections matching this path
18031
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
18032
- * permessage-deflate
18033
- * @param {Number} [options.port] The port where to bind the server
18034
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
18035
- * server to use
18036
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
18037
- * not to skip UTF-8 validation for text and close messages
18038
- * @param {Function} [options.verifyClient] A hook to reject connections
18039
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
18040
- * class to use. It must be the `WebSocket` class or class that extends it
18041
- * @param {Function} [callback] A listener for the `listening` event
18042
- */
18043
- constructor(options, callback) {
18044
- super();
18045
- options = {
18046
- allowSynchronousEvents: true,
18047
- autoPong: true,
18048
- maxPayload: 100 * 1024 * 1024,
18049
- skipUTF8Validation: false,
18050
- perMessageDeflate: false,
18051
- handleProtocols: null,
18052
- clientTracking: true,
18053
- closeTimeout: CLOSE_TIMEOUT,
18054
- verifyClient: null,
18055
- noServer: false,
18056
- backlog: null,
18057
- // use default (511 as implemented in net.js)
18058
- server: null,
18059
- host: null,
18060
- path: null,
18061
- port: null,
18062
- WebSocket: WebSocket2,
18063
- ...options
18064
- };
18065
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
18066
- throw new TypeError(
18067
- 'One and only one of the "port", "server", or "noServer" options must be specified'
18068
- );
18069
- }
18070
- if (options.port != null) {
18071
- this._server = http3.createServer((req, res) => {
18072
- const body = http3.STATUS_CODES[426];
18073
- res.writeHead(426, {
18074
- "Content-Length": body.length,
18075
- "Content-Type": "text/plain"
18076
- });
18077
- res.end(body);
18078
- });
18079
- this._server.listen(
18080
- options.port,
18081
- options.host,
18082
- options.backlog,
18083
- callback
18084
- );
18085
- } else if (options.server) {
18086
- this._server = options.server;
18087
- }
18088
- if (this._server) {
18089
- const emitConnection = this.emit.bind(this, "connection");
18090
- this._removeListeners = addListeners(this._server, {
18091
- listening: this.emit.bind(this, "listening"),
18092
- error: this.emit.bind(this, "error"),
18093
- upgrade: (req, socket, head) => {
18094
- this.handleUpgrade(req, socket, head, emitConnection);
18095
- }
18096
- });
18097
- }
18098
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
18099
- if (options.clientTracking) {
18100
- this.clients = /* @__PURE__ */ new Set();
18101
- this._shouldEmitClose = false;
18102
- }
18103
- this.options = options;
18104
- this._state = RUNNING;
18105
- }
18106
- /**
18107
- * Returns the bound address, the address family name, and port of the server
18108
- * as reported by the operating system if listening on an IP socket.
18109
- * If the server is listening on a pipe or UNIX domain socket, the name is
18110
- * returned as a string.
18111
- *
18112
- * @return {(Object|String|null)} The address of the server
18113
- * @public
18114
- */
18115
- address() {
18116
- if (this.options.noServer) {
18117
- throw new Error('The server is operating in "noServer" mode');
18118
- }
18119
- if (!this._server) return null;
18120
- return this._server.address();
18121
- }
18122
- /**
18123
- * Stop the server from accepting new connections and emit the `'close'` event
18124
- * when all existing connections are closed.
18125
- *
18126
- * @param {Function} [cb] A one-time listener for the `'close'` event
18127
- * @public
18128
- */
18129
- close(cb) {
18130
- if (this._state === CLOSED) {
18131
- if (cb) {
18132
- this.once("close", () => {
18133
- cb(new Error("The server is not running"));
18134
- });
18135
- }
18136
- process.nextTick(emitClose, this);
18137
- return;
18138
- }
18139
- if (cb) this.once("close", cb);
18140
- if (this._state === CLOSING) return;
18141
- this._state = CLOSING;
18142
- if (this.options.noServer || this.options.server) {
18143
- if (this._server) {
18144
- this._removeListeners();
18145
- this._removeListeners = this._server = null;
18146
- }
18147
- if (this.clients) {
18148
- if (!this.clients.size) {
18149
- process.nextTick(emitClose, this);
18150
- } else {
18151
- this._shouldEmitClose = true;
18152
- }
18153
- } else {
18154
- process.nextTick(emitClose, this);
18155
- }
18156
- } else {
18157
- const server = this._server;
18158
- this._removeListeners();
18159
- this._removeListeners = this._server = null;
18160
- server.close(() => {
18161
- emitClose(this);
18162
- });
18163
- }
18164
- }
18165
- /**
18166
- * See if a given request should be handled by this server instance.
18167
- *
18168
- * @param {http.IncomingMessage} req Request object to inspect
18169
- * @return {Boolean} `true` if the request is valid, else `false`
18170
- * @public
18171
- */
18172
- shouldHandle(req) {
18173
- if (this.options.path) {
18174
- const index = req.url.indexOf("?");
18175
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
18176
- if (pathname !== this.options.path) return false;
18177
- }
18178
- return true;
18179
- }
18180
- /**
18181
- * Handle a HTTP Upgrade request.
18182
- *
18183
- * @param {http.IncomingMessage} req The request object
18184
- * @param {Duplex} socket The network socket between the server and client
18185
- * @param {Buffer} head The first packet of the upgraded stream
18186
- * @param {Function} cb Callback
18187
- * @public
18188
- */
18189
- handleUpgrade(req, socket, head, cb) {
18190
- socket.on("error", socketOnError);
18191
- const key = req.headers["sec-websocket-key"];
18192
- const upgrade = req.headers.upgrade;
18193
- const version = +req.headers["sec-websocket-version"];
18194
- if (req.method !== "GET") {
18195
- const message = "Invalid HTTP method";
18196
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
18197
- return;
18198
- }
18199
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
18200
- const message = "Invalid Upgrade header";
18201
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
18202
- return;
18203
- }
18204
- if (key === void 0 || !keyRegex.test(key)) {
18205
- const message = "Missing or invalid Sec-WebSocket-Key header";
18206
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
18207
- return;
18208
- }
18209
- if (version !== 13 && version !== 8) {
18210
- const message = "Missing or invalid Sec-WebSocket-Version header";
18211
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
18212
- "Sec-WebSocket-Version": "13, 8"
18213
- });
18214
- return;
18215
- }
18216
- if (!this.shouldHandle(req)) {
18217
- abortHandshake(socket, 400);
18218
- return;
18219
- }
18220
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
18221
- let protocols = /* @__PURE__ */ new Set();
18222
- if (secWebSocketProtocol !== void 0) {
18223
- try {
18224
- protocols = subprotocol.parse(secWebSocketProtocol);
18225
- } catch (err) {
18226
- const message = "Invalid Sec-WebSocket-Protocol header";
18227
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
18228
- return;
18229
- }
18230
- }
18231
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
18232
- const extensions = {};
18233
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
18234
- const perMessageDeflate = new PerMessageDeflate(
18235
- this.options.perMessageDeflate,
18236
- true,
18237
- this.options.maxPayload
18238
- );
18239
- try {
18240
- const offers = extension.parse(secWebSocketExtensions);
18241
- if (offers[PerMessageDeflate.extensionName]) {
18242
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
18243
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
18244
- }
18245
- } catch (err) {
18246
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
18247
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
18248
- return;
18249
- }
18250
- }
18251
- if (this.options.verifyClient) {
18252
- const info = {
18253
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
18254
- secure: !!(req.socket.authorized || req.socket.encrypted),
18255
- req
18256
- };
18257
- if (this.options.verifyClient.length === 2) {
18258
- this.options.verifyClient(info, (verified, code, message, headers) => {
18259
- if (!verified) {
18260
- return abortHandshake(socket, code || 401, message, headers);
18261
- }
18262
- this.completeUpgrade(
18263
- extensions,
18264
- key,
18265
- protocols,
18266
- req,
18267
- socket,
18268
- head,
18269
- cb
18270
- );
18271
- });
18272
- return;
18273
- }
18274
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
18275
- }
18276
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
18277
- }
18278
- /**
18279
- * Upgrade the connection to WebSocket.
18280
- *
18281
- * @param {Object} extensions The accepted extensions
18282
- * @param {String} key The value of the `Sec-WebSocket-Key` header
18283
- * @param {Set} protocols The subprotocols
18284
- * @param {http.IncomingMessage} req The request object
18285
- * @param {Duplex} socket The network socket between the server and client
18286
- * @param {Buffer} head The first packet of the upgraded stream
18287
- * @param {Function} cb Callback
18288
- * @throws {Error} If called more than once with the same socket
18289
- * @private
18290
- */
18291
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
18292
- if (!socket.readable || !socket.writable) return socket.destroy();
18293
- if (socket[kWebSocket]) {
18294
- throw new Error(
18295
- "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
18296
- );
18297
- }
18298
- if (this._state > RUNNING) return abortHandshake(socket, 503);
18299
- const digest = createHash("sha1").update(key + GUID).digest("base64");
18300
- const headers = [
18301
- "HTTP/1.1 101 Switching Protocols",
18302
- "Upgrade: websocket",
18303
- "Connection: Upgrade",
18304
- `Sec-WebSocket-Accept: ${digest}`
18305
- ];
18306
- const ws = new this.options.WebSocket(null, void 0, this.options);
18307
- if (protocols.size) {
18308
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
18309
- if (protocol) {
18310
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
18311
- ws._protocol = protocol;
18312
- }
18313
- }
18314
- if (extensions[PerMessageDeflate.extensionName]) {
18315
- const params = extensions[PerMessageDeflate.extensionName].params;
18316
- const value = extension.format({
18317
- [PerMessageDeflate.extensionName]: [params]
18318
- });
18319
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
18320
- ws._extensions = extensions;
18321
- }
18322
- this.emit("headers", headers, req);
18323
- socket.write(headers.concat("\r\n").join("\r\n"));
18324
- socket.removeListener("error", socketOnError);
18325
- ws.setSocket(socket, head, {
18326
- allowSynchronousEvents: this.options.allowSynchronousEvents,
18327
- maxPayload: this.options.maxPayload,
18328
- skipUTF8Validation: this.options.skipUTF8Validation
18329
- });
18330
- if (this.clients) {
18331
- this.clients.add(ws);
18332
- ws.on("close", () => {
18333
- this.clients.delete(ws);
18334
- if (this._shouldEmitClose && !this.clients.size) {
18335
- process.nextTick(emitClose, this);
18336
- }
18337
- });
18338
- }
18339
- cb(ws, req);
18340
- }
18341
- };
18342
- module2.exports = WebSocketServer2;
18343
- function addListeners(server, map) {
18344
- for (const event of Object.keys(map)) server.on(event, map[event]);
18345
- return function removeListeners() {
18346
- for (const event of Object.keys(map)) {
18347
- server.removeListener(event, map[event]);
18348
- }
18349
- };
18350
- }
18351
- function emitClose(server) {
18352
- server._state = CLOSED;
18353
- server.emit("close");
18354
- }
18355
- function socketOnError() {
18356
- this.destroy();
18357
- }
18358
- function abortHandshake(socket, code, message, headers) {
18359
- message = message || http3.STATUS_CODES[code];
18360
- headers = {
18361
- Connection: "close",
18362
- "Content-Type": "text/html",
18363
- "Content-Length": Buffer.byteLength(message),
18364
- ...headers
18365
- };
18366
- socket.once("finish", socket.destroy);
18367
- socket.end(
18368
- `HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r
18369
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
18370
- );
18371
- }
18372
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
18373
- if (server.listenerCount("wsClientError")) {
18374
- const err = new Error(message);
18375
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
18376
- server.emit("wsClientError", err, socket, req);
18377
- } else {
18378
- abortHandshake(socket, code, message, headers);
18379
- }
18380
- }
18381
- }
18382
- });
18383
-
18384
14782
  // node_modules/@protobufjs/aspromise/index.js
18385
14783
  var require_aspromise = __commonJS({
18386
14784
  "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) {
@@ -23347,16 +19745,6 @@ var import_qs = __toESM(require_lib());
23347
19745
  var import_lodash = __toESM(require_lodash());
23348
19746
  var import_lodash2 = __toESM(require_lodash2());
23349
19747
  __toESM(require_lodash3());
23350
-
23351
- // node_modules/ws/wrapper.mjs
23352
- __toESM(require_stream(), 1);
23353
- __toESM(require_receiver(), 1);
23354
- __toESM(require_sender(), 1);
23355
- var import_websocket = __toESM(require_websocket(), 1);
23356
- __toESM(require_websocket_server(), 1);
23357
- var wrapper_default = import_websocket.default;
23358
-
23359
- // node_modules/@larksuiteoapi/node-sdk/es/index.js
23360
19748
  function __rest(s, e) {
23361
19749
  var t = {};
23362
19750
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -102085,7 +98473,7 @@ var WSClient = class {
102085
98473
  let wsInstance;
102086
98474
  try {
102087
98475
  const { agent } = this;
102088
- wsInstance = new wrapper_default(connectUrl, { agent });
98476
+ wsInstance = new WebSocket(connectUrl, { agent });
102089
98477
  } catch (e) {
102090
98478
  this.logger.error("[ws]", "new WebSocket error");
102091
98479
  }
@@ -102184,7 +98572,7 @@ var WSClient = class {
102184
98572
  pingLoop() {
102185
98573
  const { serviceId, pingInterval } = this.wsConfig.getWS();
102186
98574
  const wsInstance = this.wsConfig.getWSInstance();
102187
- if ((wsInstance === null || wsInstance === void 0 ? void 0 : wsInstance.readyState) === wrapper_default.OPEN) {
98575
+ if ((wsInstance === null || wsInstance === void 0 ? void 0 : wsInstance.readyState) === WebSocket.OPEN) {
102188
98576
  const frame = {
102189
98577
  headers: [{
102190
98578
  key: HeaderKey.type,
@@ -102285,7 +98673,7 @@ var WSClient = class {
102285
98673
  sendMessage(data) {
102286
98674
  var _a;
102287
98675
  const wsInstance = this.wsConfig.getWSInstance();
102288
- if ((wsInstance === null || wsInstance === void 0 ? void 0 : wsInstance.readyState) === wrapper_default.OPEN) {
98676
+ if ((wsInstance === null || wsInstance === void 0 ? void 0 : wsInstance.readyState) === WebSocket.OPEN) {
102289
98677
  const resp = pbbp2.Frame.encode(data).finish();
102290
98678
  (_a = this.wsConfig.getWSInstance()) === null || _a === void 0 ? void 0 : _a.send(resp, (err) => {
102291
98679
  if (err) {
@@ -102379,8 +98767,9 @@ function startFeishuGateway(options) {
102379
98767
  const { config, botOpenId = "", onMessage, onBotAdded, log } = options;
102380
98768
  const { appId, appSecret } = config;
102381
98769
  const proxyUrl = process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.ALL_PROXY || "";
102382
- const wsAgent = new ProxyAgent();
98770
+ let wsAgent;
102383
98771
  if (proxyUrl) {
98772
+ wsAgent = new HttpsProxyAgent(proxyUrl);
102384
98773
  log("info", "WS proxy enabled", { proxy: proxyUrl });
102385
98774
  }
102386
98775
  const sdkConfig = {
@@ -102431,6 +98820,7 @@ function startFeishuGateway(options) {
102431
98820
  const sender = data.sender;
102432
98821
  const senderId = sender?.sender_id?.open_id ?? "";
102433
98822
  const rootId = message.root_id;
98823
+ const createTime = message.create_time;
102434
98824
  const ctx = {
102435
98825
  chatId: String(chatId),
102436
98826
  messageId: messageId ?? "",
@@ -102439,6 +98829,7 @@ function startFeishuGateway(options) {
102439
98829
  chatType,
102440
98830
  senderId,
102441
98831
  rootId,
98832
+ createTime,
102442
98833
  shouldReply
102443
98834
  };
102444
98835
  log("info", "\u6536\u5230\u98DE\u4E66\u6D88\u606F", {
@@ -102479,7 +98870,7 @@ function startFeishuGateway(options) {
102479
98870
  };
102480
98871
  const wsClient = new WSClient({
102481
98872
  ...sdkConfig,
102482
- agent: wsAgent,
98873
+ ...wsAgent ? { agent: wsAgent } : {},
102483
98874
  loggerLevel: logLevelMap[config.logLevel] ?? LoggerLevel.info,
102484
98875
  logger: {
102485
98876
  error: (...msg) => log("error", "[lark.ws]", { msg }),
@@ -102623,15 +99014,18 @@ async function getOrCreateSession(client, sessionKey, directory) {
102623
99014
  var POLL_INTERVAL_MS = 1500;
102624
99015
  var STABLE_POLLS = 2;
102625
99016
  async function handleChat(ctx, deps) {
102626
- const { content, chatId, chatType, senderId, shouldReply } = ctx;
99017
+ const { content, chatId, chatType, senderId, createTime, shouldReply } = ctx;
102627
99018
  if (!content.trim()) return;
102628
99019
  const { config, client, feishuClient, log, directory } = deps;
102629
99020
  const query = directory ? { directory } : void 0;
102630
99021
  const sessionKey = buildSessionKey(chatType, chatType === "p2p" ? senderId : chatId);
102631
99022
  const session = await getOrCreateSession(client, sessionKey, directory);
99023
+ const timeStr = createTime ? new Date(Number(createTime)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }) : "";
102632
99024
  let promptContent = content;
102633
99025
  if (chatType === "group" && senderId) {
102634
- promptContent = `[${senderId}]: ${content}`;
99026
+ promptContent = timeStr ? `[${timeStr}] [${senderId}]: ${content}` : `[${senderId}]: ${content}`;
99027
+ } else if (timeStr) {
99028
+ promptContent = `[${timeStr}] ${content}`;
102635
99029
  }
102636
99030
  if (!shouldReply) {
102637
99031
  try {