@tonyclaw/agent-inspector 4.0.8 → 4.0.10

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