@agentdocumentformat/cli 0.7.2

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 (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +45 -0
  3. package/dist/adf.mjs +162 -0
  4. package/dist/chunks/APEv2Parser-2CNNHMXV.mjs +22 -0
  5. package/dist/chunks/AiffParser-7BR4RL6G.mjs +162 -0
  6. package/dist/chunks/App-L5L37JI5.mjs +16747 -0
  7. package/dist/chunks/AsfParser-VVRSLFOM.mjs +538 -0
  8. package/dist/chunks/DsdiffParser-CMD4AX7A.mjs +156 -0
  9. package/dist/chunks/DsfParser-UOGZDS2M.mjs +94 -0
  10. package/dist/chunks/FlacParser-HB3T3CD4.mjs +23 -0
  11. package/dist/chunks/MP4Parser-66HBRUSX.mjs +973 -0
  12. package/dist/chunks/MatroskaParser-J3HUIMEW.mjs +579 -0
  13. package/dist/chunks/MpegParser-YW6LIUEW.mjs +442 -0
  14. package/dist/chunks/MusepackParser-PAUSXP7D.mjs +252 -0
  15. package/dist/chunks/OggParser-NUBV3GWC.mjs +359 -0
  16. package/dist/chunks/WavPackParser-WQAGT7TC.mjs +171 -0
  17. package/dist/chunks/WaveParser-EWLQVDX4.mjs +238 -0
  18. package/dist/chunks/adf-schema-JRU2BTOG.mjs +62 -0
  19. package/dist/chunks/build-QF5W473T.mjs +60 -0
  20. package/dist/chunks/chatgpt-subscription-BQGWYZXE.mjs +23 -0
  21. package/dist/chunks/chunk-2DIECGFL.mjs +6 -0
  22. package/dist/chunks/chunk-2NAP2ZF7.mjs +60 -0
  23. package/dist/chunks/chunk-3AT7IIP7.mjs +25696 -0
  24. package/dist/chunks/chunk-3GNIDM53.mjs +35 -0
  25. package/dist/chunks/chunk-3M4ZPOA3.mjs +1477 -0
  26. package/dist/chunks/chunk-4MQPTCXY.mjs +510 -0
  27. package/dist/chunks/chunk-5PO5PKRV.mjs +366 -0
  28. package/dist/chunks/chunk-5QU5VY7N.mjs +52 -0
  29. package/dist/chunks/chunk-5W7KES6P.mjs +436 -0
  30. package/dist/chunks/chunk-62NE4LG4.mjs +61 -0
  31. package/dist/chunks/chunk-64OKE4X3.mjs +45 -0
  32. package/dist/chunks/chunk-6GJ4QHRI.mjs +1278 -0
  33. package/dist/chunks/chunk-6VQEXLE2.mjs +144 -0
  34. package/dist/chunks/chunk-6XUV6EK6.mjs +41 -0
  35. package/dist/chunks/chunk-776TSXEP.mjs +43 -0
  36. package/dist/chunks/chunk-7CV2SA3H.mjs +285 -0
  37. package/dist/chunks/chunk-7MTRVW2U.mjs +3103 -0
  38. package/dist/chunks/chunk-7N2R2VCG.mjs +1434 -0
  39. package/dist/chunks/chunk-7T2YMTWL.mjs +374 -0
  40. package/dist/chunks/chunk-7XYNI52E.mjs +149 -0
  41. package/dist/chunks/chunk-APHX6HSV.mjs +7731 -0
  42. package/dist/chunks/chunk-APRU6PHC.mjs +40 -0
  43. package/dist/chunks/chunk-AUYKRQPJ.mjs +499 -0
  44. package/dist/chunks/chunk-DXWDD5XJ.mjs +136 -0
  45. package/dist/chunks/chunk-EWL5FG4I.mjs +39 -0
  46. package/dist/chunks/chunk-EYX2YLJW.mjs +117 -0
  47. package/dist/chunks/chunk-F5ELW46V.mjs +27 -0
  48. package/dist/chunks/chunk-G426FACA.mjs +49 -0
  49. package/dist/chunks/chunk-GEKSJHIV.mjs +2472 -0
  50. package/dist/chunks/chunk-HBUENVQL.mjs +570 -0
  51. package/dist/chunks/chunk-HPVFJYXR.mjs +112 -0
  52. package/dist/chunks/chunk-HWLWPXQ7.mjs +721 -0
  53. package/dist/chunks/chunk-I2HJYHFT.mjs +665 -0
  54. package/dist/chunks/chunk-I3UYSITV.mjs +68 -0
  55. package/dist/chunks/chunk-IC4JDZCI.mjs +3864 -0
  56. package/dist/chunks/chunk-IHDDCZBS.mjs +112 -0
  57. package/dist/chunks/chunk-IIGMZHQQ.mjs +10416 -0
  58. package/dist/chunks/chunk-KWFOS5WC.mjs +41 -0
  59. package/dist/chunks/chunk-LAZIXV2F.mjs +5290 -0
  60. package/dist/chunks/chunk-LFMB4PAA.mjs +10814 -0
  61. package/dist/chunks/chunk-M2RX3S2T.mjs +49 -0
  62. package/dist/chunks/chunk-M3WPIJYM.mjs +65 -0
  63. package/dist/chunks/chunk-NBTUWMGP.mjs +263 -0
  64. package/dist/chunks/chunk-NGK6PVSF.mjs +2676 -0
  65. package/dist/chunks/chunk-NZ7JTHEO.mjs +85 -0
  66. package/dist/chunks/chunk-OQN33RGQ.mjs +52 -0
  67. package/dist/chunks/chunk-RIX34QHC.mjs +2935 -0
  68. package/dist/chunks/chunk-SGUTYISF.mjs +16 -0
  69. package/dist/chunks/chunk-SLJ5L7PY.mjs +1473 -0
  70. package/dist/chunks/chunk-SLUKGXKH.mjs +68 -0
  71. package/dist/chunks/chunk-TMT32MXT.mjs +419 -0
  72. package/dist/chunks/chunk-UYY5M2PB.mjs +151 -0
  73. package/dist/chunks/chunk-VAUOM3IN.mjs +298 -0
  74. package/dist/chunks/chunk-VMHTYDH4.mjs +172 -0
  75. package/dist/chunks/chunk-VZS54AA5.mjs +200 -0
  76. package/dist/chunks/chunk-WFQUVXML.mjs +295 -0
  77. package/dist/chunks/chunk-X34PDRUH.mjs +809 -0
  78. package/dist/chunks/chunk-XNPZBLYL.mjs +33 -0
  79. package/dist/chunks/chunk-XX7OSWTO.mjs +157 -0
  80. package/dist/chunks/chunk-XYTWGHFS.mjs +600 -0
  81. package/dist/chunks/chunk-XYV3VCIX.mjs +336 -0
  82. package/dist/chunks/chunk-Y5ZLKFLE.mjs +1469 -0
  83. package/dist/chunks/chunk-ZJKXHM4Q.mjs +230 -0
  84. package/dist/chunks/cli-TCMBNZF6.mjs +1030 -0
  85. package/dist/chunks/commands-DTEKM4ZL.mjs +20 -0
  86. package/dist/chunks/daemon-ZC3FZ2P4.mjs +112449 -0
  87. package/dist/chunks/daemon-control-WDX7PMTC.mjs +300 -0
  88. package/dist/chunks/daemon-token-WRSULP7G.mjs +23 -0
  89. package/dist/chunks/devtools-H7CI2ZVG.mjs +85 -0
  90. package/dist/chunks/discord-IWDQJA7A.mjs +70588 -0
  91. package/dist/chunks/dist-C57KYFS2.mjs +4952 -0
  92. package/dist/chunks/dist-I3XBAGDL.mjs +11 -0
  93. package/dist/chunks/email-V4Q4VJON.mjs +58679 -0
  94. package/dist/chunks/environment-NX277MQG.mjs +15 -0
  95. package/dist/chunks/grok-subscription-4PYX7TBF.mjs +19 -0
  96. package/dist/chunks/layout-EPJQNFAI.mjs +22 -0
  97. package/dist/chunks/lib-N7FCZWKH.mjs +4038 -0
  98. package/dist/chunks/open-OTQDGDH5.mjs +36 -0
  99. package/dist/chunks/parser-JVY2PWSM.mjs +19 -0
  100. package/dist/chunks/pipeline-executor-BHBSJX2K.mjs +19 -0
  101. package/dist/chunks/react-IUIDQ5LX.mjs +11 -0
  102. package/dist/chunks/screen-54BUTYCW.mjs +27 -0
  103. package/dist/chunks/slack-3L5QTDZX.mjs +8113 -0
  104. package/dist/chunks/store-WR7TZJZS.mjs +32 -0
  105. package/dist/chunks/telegram-5ISVFBV3.mjs +14918 -0
  106. package/dist/chunks/terminal-O5WO7C5U.mjs +48 -0
  107. package/dist/chunks/theme-NORU4J74.mjs +20 -0
  108. package/dist/chunks/themes-F2FKU7CP.mjs +23 -0
  109. package/dist/chunks/token-6G3HCMNX.mjs +54 -0
  110. package/dist/chunks/token-util-UXYSDQIW.mjs +12 -0
  111. package/dist/chunks/tui-ODVYUIMT.mjs +197 -0
  112. package/dist/chunks/welcome-XHXFV7SH.mjs +32 -0
  113. package/dist/chunks/whatsapp-XSAMNGPJ.mjs +85412 -0
  114. package/dist/chunks/xterm-headless-YF53XWXE.mjs +3353 -0
  115. package/package.json +53 -0
  116. package/resources/wasm/coreutils.LICENSE +18 -0
  117. package/resources/wasm/coreutils.wasm +0 -0
@@ -0,0 +1,2676 @@
1
+ import { createRequire as __adfCreateRequire } from 'node:module';
2
+ import { fileURLToPath as __adfFileURLToPath } from 'node:url';
3
+ import { dirname as __adfDirname } from 'node:path';
4
+ const require = __adfCreateRequire(import.meta.url);
5
+ const __filename = __adfFileURLToPath(import.meta.url);
6
+ const __dirname = __adfDirname(__filename);
7
+ import {
8
+ __commonJS,
9
+ __require
10
+ } from "./chunk-M2RX3S2T.mjs";
11
+
12
+ // node_modules/ws/lib/constants.js
13
+ var require_constants = __commonJS({
14
+ "node_modules/ws/lib/constants.js"(exports, module) {
15
+ "use strict";
16
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"], hasBlob = typeof Blob < "u";
17
+ hasBlob && BINARY_TYPES.push("blob");
18
+ module.exports = {
19
+ BINARY_TYPES,
20
+ CLOSE_TIMEOUT: 3e4,
21
+ EMPTY_BUFFER: Buffer.alloc(0),
22
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
23
+ hasBlob,
24
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
25
+ kListener: /* @__PURE__ */ Symbol("kListener"),
26
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
27
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
28
+ NOOP: () => {
29
+ }
30
+ };
31
+ }
32
+ });
33
+
34
+ // node_modules/ws/lib/buffer-util.js
35
+ var require_buffer_util = __commonJS({
36
+ "node_modules/ws/lib/buffer-util.js"(exports, module) {
37
+ "use strict";
38
+ var { EMPTY_BUFFER } = require_constants(), FastBuffer = Buffer[Symbol.species];
39
+ function concat(list, totalLength) {
40
+ if (list.length === 0) return EMPTY_BUFFER;
41
+ if (list.length === 1) return list[0];
42
+ let target = Buffer.allocUnsafe(totalLength), offset = 0;
43
+ for (let i = 0; i < list.length; i++) {
44
+ let buf = list[i];
45
+ target.set(buf, offset), offset += buf.length;
46
+ }
47
+ return offset < totalLength ? new FastBuffer(target.buffer, target.byteOffset, offset) : target;
48
+ }
49
+ function _mask(source, mask, output, offset, length) {
50
+ for (let i = 0; i < length; i++)
51
+ output[offset + i] = source[i] ^ mask[i & 3];
52
+ }
53
+ function _unmask(buffer, mask) {
54
+ for (let i = 0; i < buffer.length; i++)
55
+ buffer[i] ^= mask[i & 3];
56
+ }
57
+ function toArrayBuffer(buf) {
58
+ return buf.length === buf.buffer.byteLength ? buf.buffer : buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
59
+ }
60
+ function toBuffer(data) {
61
+ if (toBuffer.readOnly = !0, Buffer.isBuffer(data)) return data;
62
+ let buf;
63
+ return data instanceof ArrayBuffer ? buf = new FastBuffer(data) : ArrayBuffer.isView(data) ? buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength) : (buf = Buffer.from(data), toBuffer.readOnly = !1), buf;
64
+ }
65
+ module.exports = {
66
+ concat,
67
+ mask: _mask,
68
+ toArrayBuffer,
69
+ toBuffer,
70
+ unmask: _unmask
71
+ };
72
+ if (!process.env.WS_NO_BUFFER_UTIL)
73
+ try {
74
+ let bufferUtil = __require("bufferutil");
75
+ module.exports.mask = function(source, mask, output, offset, length) {
76
+ length < 48 ? _mask(source, mask, output, offset, length) : bufferUtil.mask(source, mask, output, offset, length);
77
+ }, module.exports.unmask = function(buffer, mask) {
78
+ buffer.length < 32 ? _unmask(buffer, mask) : bufferUtil.unmask(buffer, mask);
79
+ };
80
+ } catch {
81
+ }
82
+ }
83
+ });
84
+
85
+ // node_modules/ws/lib/limiter.js
86
+ var require_limiter = __commonJS({
87
+ "node_modules/ws/lib/limiter.js"(exports, module) {
88
+ "use strict";
89
+ var kDone = /* @__PURE__ */ Symbol("kDone"), kRun = /* @__PURE__ */ Symbol("kRun"), Limiter = class {
90
+ /**
91
+ * Creates a new `Limiter`.
92
+ *
93
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
94
+ * to run concurrently
95
+ */
96
+ constructor(concurrency) {
97
+ this[kDone] = () => {
98
+ this.pending--, this[kRun]();
99
+ }, this.concurrency = concurrency || 1 / 0, this.jobs = [], this.pending = 0;
100
+ }
101
+ /**
102
+ * Adds a job to the queue.
103
+ *
104
+ * @param {Function} job The job to run
105
+ * @public
106
+ */
107
+ add(job) {
108
+ this.jobs.push(job), this[kRun]();
109
+ }
110
+ /**
111
+ * Removes a job from the queue and runs it if possible.
112
+ *
113
+ * @private
114
+ */
115
+ [kRun]() {
116
+ if (this.pending !== this.concurrency && this.jobs.length) {
117
+ let job = this.jobs.shift();
118
+ this.pending++, job(this[kDone]);
119
+ }
120
+ }
121
+ };
122
+ module.exports = Limiter;
123
+ }
124
+ });
125
+
126
+ // node_modules/ws/lib/permessage-deflate.js
127
+ var require_permessage_deflate = __commonJS({
128
+ "node_modules/ws/lib/permessage-deflate.js"(exports, module) {
129
+ "use strict";
130
+ var zlib = __require("zlib"), bufferUtil = require_buffer_util(), Limiter = require_limiter(), { kStatusCode } = require_constants(), FastBuffer = Buffer[Symbol.species], TRAILER = Buffer.from([0, 0, 255, 255]), kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate"), kTotalLength = /* @__PURE__ */ Symbol("total-length"), kCallback = /* @__PURE__ */ Symbol("callback"), kBuffers = /* @__PURE__ */ Symbol("buffers"), kError = /* @__PURE__ */ Symbol("error"), zlibLimiter, PerMessageDeflate = class {
131
+ /**
132
+ * Creates a PerMessageDeflate instance.
133
+ *
134
+ * @param {Object} [options] Configuration options
135
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
136
+ * for, or request, a custom client window size
137
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
138
+ * acknowledge disabling of client context takeover
139
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
140
+ * calls to zlib
141
+ * @param {Boolean} [options.isServer=false] Create the instance in either
142
+ * server or client mode
143
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
144
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
145
+ * use of a custom server window size
146
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
147
+ * disabling of server context takeover
148
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
149
+ * messages should not be compressed if context takeover is disabled
150
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
151
+ * deflate
152
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
153
+ * inflate
154
+ */
155
+ constructor(options) {
156
+ if (this._options = 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, !zlibLimiter) {
157
+ let concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
158
+ zlibLimiter = new Limiter(concurrency);
159
+ }
160
+ }
161
+ /**
162
+ * @type {String}
163
+ */
164
+ static get extensionName() {
165
+ return "permessage-deflate";
166
+ }
167
+ /**
168
+ * Create an extension negotiation offer.
169
+ *
170
+ * @return {Object} Extension parameters
171
+ * @public
172
+ */
173
+ offer() {
174
+ let params = {};
175
+ return this._options.serverNoContextTakeover && (params.server_no_context_takeover = !0), this._options.clientNoContextTakeover && (params.client_no_context_takeover = !0), this._options.serverMaxWindowBits && (params.server_max_window_bits = this._options.serverMaxWindowBits), this._options.clientMaxWindowBits ? params.client_max_window_bits = this._options.clientMaxWindowBits : this._options.clientMaxWindowBits == null && (params.client_max_window_bits = !0), params;
176
+ }
177
+ /**
178
+ * Accept an extension negotiation offer/response.
179
+ *
180
+ * @param {Array} configurations The extension negotiation offers/reponse
181
+ * @return {Object} Accepted configuration
182
+ * @public
183
+ */
184
+ accept(configurations) {
185
+ return configurations = this.normalizeParams(configurations), this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations), this.params;
186
+ }
187
+ /**
188
+ * Releases all resources used by the extension.
189
+ *
190
+ * @public
191
+ */
192
+ cleanup() {
193
+ if (this._inflate && (this._inflate.close(), this._inflate = null), this._deflate) {
194
+ let callback = this._deflate[kCallback];
195
+ this._deflate.close(), this._deflate = null, callback && callback(
196
+ new Error(
197
+ "The deflate stream was closed while data was being processed"
198
+ )
199
+ );
200
+ }
201
+ }
202
+ /**
203
+ * Accept an extension negotiation offer.
204
+ *
205
+ * @param {Array} offers The extension negotiation offers
206
+ * @return {Object} Accepted configuration
207
+ * @private
208
+ */
209
+ acceptAsServer(offers) {
210
+ let opts = this._options, accepted = offers.find((params) => !(opts.serverNoContextTakeover === !1 && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === !1 || typeof opts.serverMaxWindowBits == "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits == "number" && (typeof params.client_max_window_bits == "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)));
211
+ if (!accepted)
212
+ throw new Error("None of the extension offers can be accepted");
213
+ return opts.serverNoContextTakeover && (accepted.server_no_context_takeover = !0), opts.clientNoContextTakeover && (accepted.client_no_context_takeover = !0), typeof opts.serverMaxWindowBits == "number" && (accepted.server_max_window_bits = opts.serverMaxWindowBits), typeof opts.clientMaxWindowBits == "number" ? accepted.client_max_window_bits = opts.clientMaxWindowBits : (accepted.client_max_window_bits === !0 || opts.clientMaxWindowBits === !1) && delete accepted.client_max_window_bits, accepted;
214
+ }
215
+ /**
216
+ * Accept the extension negotiation response.
217
+ *
218
+ * @param {Array} response The extension negotiation response
219
+ * @return {Object} Accepted configuration
220
+ * @private
221
+ */
222
+ acceptAsClient(response) {
223
+ let params = response[0];
224
+ if (this._options.clientNoContextTakeover === !1 && params.client_no_context_takeover)
225
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
226
+ if (!params.client_max_window_bits)
227
+ typeof this._options.clientMaxWindowBits == "number" && (params.client_max_window_bits = this._options.clientMaxWindowBits);
228
+ else if (this._options.clientMaxWindowBits === !1 || typeof this._options.clientMaxWindowBits == "number" && params.client_max_window_bits > this._options.clientMaxWindowBits)
229
+ throw new Error(
230
+ 'Unexpected or invalid parameter "client_max_window_bits"'
231
+ );
232
+ return params;
233
+ }
234
+ /**
235
+ * Normalize parameters.
236
+ *
237
+ * @param {Array} configurations The extension negotiation offers/reponse
238
+ * @return {Array} The offers/response with normalized parameters
239
+ * @private
240
+ */
241
+ normalizeParams(configurations) {
242
+ return configurations.forEach((params) => {
243
+ Object.keys(params).forEach((key) => {
244
+ let value = params[key];
245
+ if (value.length > 1)
246
+ throw new Error(`Parameter "${key}" must have only a single value`);
247
+ if (value = value[0], key === "client_max_window_bits") {
248
+ if (value !== !0) {
249
+ let num = +value;
250
+ if (!Number.isInteger(num) || num < 8 || num > 15)
251
+ throw new TypeError(
252
+ `Invalid value for parameter "${key}": ${value}`
253
+ );
254
+ value = num;
255
+ } else if (!this._isServer)
256
+ throw new TypeError(
257
+ `Invalid value for parameter "${key}": ${value}`
258
+ );
259
+ } else if (key === "server_max_window_bits") {
260
+ let num = +value;
261
+ if (!Number.isInteger(num) || num < 8 || num > 15)
262
+ throw new TypeError(
263
+ `Invalid value for parameter "${key}": ${value}`
264
+ );
265
+ value = num;
266
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
267
+ if (value !== !0)
268
+ throw new TypeError(
269
+ `Invalid value for parameter "${key}": ${value}`
270
+ );
271
+ } else
272
+ throw new Error(`Unknown parameter "${key}"`);
273
+ params[key] = value;
274
+ });
275
+ }), configurations;
276
+ }
277
+ /**
278
+ * Decompress data. Concurrency limited.
279
+ *
280
+ * @param {Buffer} data Compressed data
281
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
282
+ * @param {Function} callback Callback
283
+ * @public
284
+ */
285
+ decompress(data, fin, callback) {
286
+ zlibLimiter.add((done) => {
287
+ this._decompress(data, fin, (err, result) => {
288
+ done(), callback(err, result);
289
+ });
290
+ });
291
+ }
292
+ /**
293
+ * Compress data. Concurrency limited.
294
+ *
295
+ * @param {(Buffer|String)} data Data to compress
296
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
297
+ * @param {Function} callback Callback
298
+ * @public
299
+ */
300
+ compress(data, fin, callback) {
301
+ zlibLimiter.add((done) => {
302
+ this._compress(data, fin, (err, result) => {
303
+ done(), callback(err, result);
304
+ });
305
+ });
306
+ }
307
+ /**
308
+ * Decompress data.
309
+ *
310
+ * @param {Buffer} data Compressed data
311
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
312
+ * @param {Function} callback Callback
313
+ * @private
314
+ */
315
+ _decompress(data, fin, callback) {
316
+ let endpoint = this._isServer ? "client" : "server";
317
+ if (!this._inflate) {
318
+ let key = `${endpoint}_max_window_bits`, windowBits = typeof this.params[key] != "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
319
+ this._inflate = zlib.createInflateRaw({
320
+ ...this._options.zlibInflateOptions,
321
+ windowBits
322
+ }), this._inflate[kPerMessageDeflate] = this, this._inflate[kTotalLength] = 0, this._inflate[kBuffers] = [], this._inflate.on("error", inflateOnError), this._inflate.on("data", inflateOnData);
323
+ }
324
+ this._inflate[kCallback] = callback, this._inflate.write(data), fin && this._inflate.write(TRAILER), this._inflate.flush(() => {
325
+ let err = this._inflate[kError];
326
+ if (err) {
327
+ this._inflate.close(), this._inflate = null, callback(err);
328
+ return;
329
+ }
330
+ let data2 = bufferUtil.concat(
331
+ this._inflate[kBuffers],
332
+ this._inflate[kTotalLength]
333
+ );
334
+ this._inflate._readableState.endEmitted ? (this._inflate.close(), this._inflate = null) : (this._inflate[kTotalLength] = 0, this._inflate[kBuffers] = [], fin && this.params[`${endpoint}_no_context_takeover`] && this._inflate.reset()), callback(null, data2);
335
+ });
336
+ }
337
+ /**
338
+ * Compress data.
339
+ *
340
+ * @param {(Buffer|String)} data Data to compress
341
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
342
+ * @param {Function} callback Callback
343
+ * @private
344
+ */
345
+ _compress(data, fin, callback) {
346
+ let endpoint = this._isServer ? "server" : "client";
347
+ if (!this._deflate) {
348
+ let key = `${endpoint}_max_window_bits`, windowBits = typeof this.params[key] != "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
349
+ this._deflate = zlib.createDeflateRaw({
350
+ ...this._options.zlibDeflateOptions,
351
+ windowBits
352
+ }), this._deflate[kTotalLength] = 0, this._deflate[kBuffers] = [], this._deflate.on("data", deflateOnData);
353
+ }
354
+ this._deflate[kCallback] = callback, this._deflate.write(data), this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
355
+ if (!this._deflate)
356
+ return;
357
+ let data2 = bufferUtil.concat(
358
+ this._deflate[kBuffers],
359
+ this._deflate[kTotalLength]
360
+ );
361
+ fin && (data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4)), this._deflate[kCallback] = null, this._deflate[kTotalLength] = 0, this._deflate[kBuffers] = [], fin && this.params[`${endpoint}_no_context_takeover`] && this._deflate.reset(), callback(null, data2);
362
+ });
363
+ }
364
+ };
365
+ module.exports = PerMessageDeflate;
366
+ function deflateOnData(chunk) {
367
+ this[kBuffers].push(chunk), this[kTotalLength] += chunk.length;
368
+ }
369
+ function inflateOnData(chunk) {
370
+ if (this[kTotalLength] += chunk.length, this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
371
+ this[kBuffers].push(chunk);
372
+ return;
373
+ }
374
+ this[kError] = new RangeError("Max payload size exceeded"), this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH", this[kError][kStatusCode] = 1009, this.removeListener("data", inflateOnData), this.reset();
375
+ }
376
+ function inflateOnError(err) {
377
+ if (this[kPerMessageDeflate]._inflate = null, this[kError]) {
378
+ this[kCallback](this[kError]);
379
+ return;
380
+ }
381
+ err[kStatusCode] = 1007, this[kCallback](err);
382
+ }
383
+ }
384
+ });
385
+
386
+ // node_modules/ws/lib/validation.js
387
+ var require_validation = __commonJS({
388
+ "node_modules/ws/lib/validation.js"(exports, module) {
389
+ "use strict";
390
+ var { isUtf8 } = __require("buffer"), { hasBlob } = require_constants(), tokenChars = [
391
+ 0,
392
+ 0,
393
+ 0,
394
+ 0,
395
+ 0,
396
+ 0,
397
+ 0,
398
+ 0,
399
+ 0,
400
+ 0,
401
+ 0,
402
+ 0,
403
+ 0,
404
+ 0,
405
+ 0,
406
+ 0,
407
+ // 0 - 15
408
+ 0,
409
+ 0,
410
+ 0,
411
+ 0,
412
+ 0,
413
+ 0,
414
+ 0,
415
+ 0,
416
+ 0,
417
+ 0,
418
+ 0,
419
+ 0,
420
+ 0,
421
+ 0,
422
+ 0,
423
+ 0,
424
+ // 16 - 31
425
+ 0,
426
+ 1,
427
+ 0,
428
+ 1,
429
+ 1,
430
+ 1,
431
+ 1,
432
+ 1,
433
+ 0,
434
+ 0,
435
+ 1,
436
+ 1,
437
+ 0,
438
+ 1,
439
+ 1,
440
+ 0,
441
+ // 32 - 47
442
+ 1,
443
+ 1,
444
+ 1,
445
+ 1,
446
+ 1,
447
+ 1,
448
+ 1,
449
+ 1,
450
+ 1,
451
+ 1,
452
+ 0,
453
+ 0,
454
+ 0,
455
+ 0,
456
+ 0,
457
+ 0,
458
+ // 48 - 63
459
+ 0,
460
+ 1,
461
+ 1,
462
+ 1,
463
+ 1,
464
+ 1,
465
+ 1,
466
+ 1,
467
+ 1,
468
+ 1,
469
+ 1,
470
+ 1,
471
+ 1,
472
+ 1,
473
+ 1,
474
+ 1,
475
+ // 64 - 79
476
+ 1,
477
+ 1,
478
+ 1,
479
+ 1,
480
+ 1,
481
+ 1,
482
+ 1,
483
+ 1,
484
+ 1,
485
+ 1,
486
+ 1,
487
+ 0,
488
+ 0,
489
+ 0,
490
+ 1,
491
+ 1,
492
+ // 80 - 95
493
+ 1,
494
+ 1,
495
+ 1,
496
+ 1,
497
+ 1,
498
+ 1,
499
+ 1,
500
+ 1,
501
+ 1,
502
+ 1,
503
+ 1,
504
+ 1,
505
+ 1,
506
+ 1,
507
+ 1,
508
+ 1,
509
+ // 96 - 111
510
+ 1,
511
+ 1,
512
+ 1,
513
+ 1,
514
+ 1,
515
+ 1,
516
+ 1,
517
+ 1,
518
+ 1,
519
+ 1,
520
+ 1,
521
+ 0,
522
+ 1,
523
+ 0,
524
+ 1,
525
+ 0
526
+ // 112 - 127
527
+ ];
528
+ function isValidStatusCode(code) {
529
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
530
+ }
531
+ function _isValidUTF8(buf) {
532
+ let len = buf.length, i = 0;
533
+ for (; i < len; )
534
+ if ((buf[i] & 128) === 0)
535
+ i++;
536
+ else if ((buf[i] & 224) === 192) {
537
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192)
538
+ return !1;
539
+ i += 2;
540
+ } else if ((buf[i] & 240) === 224) {
541
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
542
+ buf[i] === 237 && (buf[i + 1] & 224) === 160)
543
+ return !1;
544
+ i += 3;
545
+ } else if ((buf[i] & 248) === 240) {
546
+ 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
547
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244)
548
+ return !1;
549
+ i += 4;
550
+ } else
551
+ return !1;
552
+ return !0;
553
+ }
554
+ function isBlob(value) {
555
+ 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");
556
+ }
557
+ module.exports = {
558
+ isBlob,
559
+ isValidStatusCode,
560
+ isValidUTF8: _isValidUTF8,
561
+ tokenChars
562
+ };
563
+ if (isUtf8)
564
+ module.exports.isValidUTF8 = function(buf) {
565
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
566
+ };
567
+ else if (!process.env.WS_NO_UTF_8_VALIDATE)
568
+ try {
569
+ let isValidUTF8 = __require("utf-8-validate");
570
+ module.exports.isValidUTF8 = function(buf) {
571
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
572
+ };
573
+ } catch {
574
+ }
575
+ }
576
+ });
577
+
578
+ // node_modules/ws/lib/receiver.js
579
+ var require_receiver = __commonJS({
580
+ "node_modules/ws/lib/receiver.js"(exports, module) {
581
+ "use strict";
582
+ var { Writable } = __require("stream"), PerMessageDeflate = require_permessage_deflate(), {
583
+ BINARY_TYPES,
584
+ EMPTY_BUFFER,
585
+ kStatusCode,
586
+ kWebSocket
587
+ } = require_constants(), { concat, toArrayBuffer, unmask } = require_buffer_util(), { isValidStatusCode, isValidUTF8 } = require_validation(), FastBuffer = Buffer[Symbol.species], GET_INFO = 0, GET_PAYLOAD_LENGTH_16 = 1, GET_PAYLOAD_LENGTH_64 = 2, GET_MASK = 3, GET_DATA = 4, INFLATING = 5, DEFER_EVENT = 6, Receiver = class extends Writable {
588
+ /**
589
+ * Creates a Receiver instance.
590
+ *
591
+ * @param {Object} [options] Options object
592
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
593
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
594
+ * multiple times in the same tick
595
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
596
+ * @param {Object} [options.extensions] An object containing the negotiated
597
+ * extensions
598
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
599
+ * client or server mode
600
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
601
+ * buffered data chunks
602
+ * @param {Number} [options.maxFragments=0] The maximum number of message
603
+ * fragments
604
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
605
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
606
+ * not to skip UTF-8 validation for text and close messages
607
+ */
608
+ constructor(options = {}) {
609
+ super(), this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : !0, this._binaryType = options.binaryType || BINARY_TYPES[0], this._extensions = options.extensions || {}, this._isServer = !!options.isServer, this._maxBufferedChunks = options.maxBufferedChunks | 0, this._maxFragments = options.maxFragments | 0, this._maxPayload = options.maxPayload | 0, this._skipUTF8Validation = !!options.skipUTF8Validation, this[kWebSocket] = 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._numFragments = 0, this._fragments = [], this._errored = !1, this._loop = !1, this._state = GET_INFO;
610
+ }
611
+ /**
612
+ * Implements `Writable.prototype._write()`.
613
+ *
614
+ * @param {Buffer} chunk The chunk of data to write
615
+ * @param {String} encoding The character encoding of `chunk`
616
+ * @param {Function} cb Callback
617
+ * @private
618
+ */
619
+ _write(chunk, encoding, cb) {
620
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
621
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
622
+ cb(
623
+ this.createError(
624
+ RangeError,
625
+ "Too many buffered chunks",
626
+ !1,
627
+ 1008,
628
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
629
+ )
630
+ );
631
+ return;
632
+ }
633
+ this._bufferedBytes += chunk.length, this._buffers.push(chunk), this.startLoop(cb);
634
+ }
635
+ /**
636
+ * Consumes `n` bytes from the buffered data.
637
+ *
638
+ * @param {Number} n The number of bytes to consume
639
+ * @return {Buffer} The consumed bytes
640
+ * @private
641
+ */
642
+ consume(n) {
643
+ if (this._bufferedBytes -= n, n === this._buffers[0].length) return this._buffers.shift();
644
+ if (n < this._buffers[0].length) {
645
+ let buf = this._buffers[0];
646
+ return this._buffers[0] = new FastBuffer(
647
+ buf.buffer,
648
+ buf.byteOffset + n,
649
+ buf.length - n
650
+ ), new FastBuffer(buf.buffer, buf.byteOffset, n);
651
+ }
652
+ let dst = Buffer.allocUnsafe(n);
653
+ do {
654
+ let buf = this._buffers[0], offset = dst.length - n;
655
+ n >= buf.length ? dst.set(this._buffers.shift(), offset) : (dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset), this._buffers[0] = new FastBuffer(
656
+ buf.buffer,
657
+ buf.byteOffset + n,
658
+ buf.length - n
659
+ )), n -= buf.length;
660
+ } while (n > 0);
661
+ return dst;
662
+ }
663
+ /**
664
+ * Starts the parsing loop.
665
+ *
666
+ * @param {Function} cb Callback
667
+ * @private
668
+ */
669
+ startLoop(cb) {
670
+ this._loop = !0;
671
+ do
672
+ switch (this._state) {
673
+ case GET_INFO:
674
+ this.getInfo(cb);
675
+ break;
676
+ case GET_PAYLOAD_LENGTH_16:
677
+ this.getPayloadLength16(cb);
678
+ break;
679
+ case GET_PAYLOAD_LENGTH_64:
680
+ this.getPayloadLength64(cb);
681
+ break;
682
+ case GET_MASK:
683
+ this.getMask();
684
+ break;
685
+ case GET_DATA:
686
+ this.getData(cb);
687
+ break;
688
+ case INFLATING:
689
+ case DEFER_EVENT:
690
+ this._loop = !1;
691
+ return;
692
+ }
693
+ while (this._loop);
694
+ this._errored || cb();
695
+ }
696
+ /**
697
+ * Reads the first two bytes of a frame.
698
+ *
699
+ * @param {Function} cb Callback
700
+ * @private
701
+ */
702
+ getInfo(cb) {
703
+ if (this._bufferedBytes < 2) {
704
+ this._loop = !1;
705
+ return;
706
+ }
707
+ let buf = this.consume(2);
708
+ if ((buf[0] & 48) !== 0) {
709
+ let error = this.createError(
710
+ RangeError,
711
+ "RSV2 and RSV3 must be clear",
712
+ !0,
713
+ 1002,
714
+ "WS_ERR_UNEXPECTED_RSV_2_3"
715
+ );
716
+ cb(error);
717
+ return;
718
+ }
719
+ let compressed = (buf[0] & 64) === 64;
720
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
721
+ let error = this.createError(
722
+ RangeError,
723
+ "RSV1 must be clear",
724
+ !0,
725
+ 1002,
726
+ "WS_ERR_UNEXPECTED_RSV_1"
727
+ );
728
+ cb(error);
729
+ return;
730
+ }
731
+ if (this._fin = (buf[0] & 128) === 128, this._opcode = buf[0] & 15, this._payloadLength = buf[1] & 127, this._opcode === 0) {
732
+ if (compressed) {
733
+ let error = this.createError(
734
+ RangeError,
735
+ "RSV1 must be clear",
736
+ !0,
737
+ 1002,
738
+ "WS_ERR_UNEXPECTED_RSV_1"
739
+ );
740
+ cb(error);
741
+ return;
742
+ }
743
+ if (!this._fragmented) {
744
+ let error = this.createError(
745
+ RangeError,
746
+ "invalid opcode 0",
747
+ !0,
748
+ 1002,
749
+ "WS_ERR_INVALID_OPCODE"
750
+ );
751
+ cb(error);
752
+ return;
753
+ }
754
+ this._opcode = this._fragmented;
755
+ } else if (this._opcode === 1 || this._opcode === 2) {
756
+ if (this._fragmented) {
757
+ let error = this.createError(
758
+ RangeError,
759
+ `invalid opcode ${this._opcode}`,
760
+ !0,
761
+ 1002,
762
+ "WS_ERR_INVALID_OPCODE"
763
+ );
764
+ cb(error);
765
+ return;
766
+ }
767
+ this._compressed = compressed;
768
+ } else if (this._opcode > 7 && this._opcode < 11) {
769
+ if (!this._fin) {
770
+ let error = this.createError(
771
+ RangeError,
772
+ "FIN must be set",
773
+ !0,
774
+ 1002,
775
+ "WS_ERR_EXPECTED_FIN"
776
+ );
777
+ cb(error);
778
+ return;
779
+ }
780
+ if (compressed) {
781
+ let error = this.createError(
782
+ RangeError,
783
+ "RSV1 must be clear",
784
+ !0,
785
+ 1002,
786
+ "WS_ERR_UNEXPECTED_RSV_1"
787
+ );
788
+ cb(error);
789
+ return;
790
+ }
791
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
792
+ let error = this.createError(
793
+ RangeError,
794
+ `invalid payload length ${this._payloadLength}`,
795
+ !0,
796
+ 1002,
797
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
798
+ );
799
+ cb(error);
800
+ return;
801
+ }
802
+ } else {
803
+ let error = this.createError(
804
+ RangeError,
805
+ `invalid opcode ${this._opcode}`,
806
+ !0,
807
+ 1002,
808
+ "WS_ERR_INVALID_OPCODE"
809
+ );
810
+ cb(error);
811
+ return;
812
+ }
813
+ if (!this._fin && !this._fragmented && (this._fragmented = this._opcode), this._masked = (buf[1] & 128) === 128, this._isServer) {
814
+ if (!this._masked) {
815
+ let error = this.createError(
816
+ RangeError,
817
+ "MASK must be set",
818
+ !0,
819
+ 1002,
820
+ "WS_ERR_EXPECTED_MASK"
821
+ );
822
+ cb(error);
823
+ return;
824
+ }
825
+ } else if (this._masked) {
826
+ let error = this.createError(
827
+ RangeError,
828
+ "MASK must be clear",
829
+ !0,
830
+ 1002,
831
+ "WS_ERR_UNEXPECTED_MASK"
832
+ );
833
+ cb(error);
834
+ return;
835
+ }
836
+ this._payloadLength === 126 ? this._state = GET_PAYLOAD_LENGTH_16 : this._payloadLength === 127 ? this._state = GET_PAYLOAD_LENGTH_64 : this.haveLength(cb);
837
+ }
838
+ /**
839
+ * Gets extended payload length (7+16).
840
+ *
841
+ * @param {Function} cb Callback
842
+ * @private
843
+ */
844
+ getPayloadLength16(cb) {
845
+ if (this._bufferedBytes < 2) {
846
+ this._loop = !1;
847
+ return;
848
+ }
849
+ this._payloadLength = this.consume(2).readUInt16BE(0), this.haveLength(cb);
850
+ }
851
+ /**
852
+ * Gets extended payload length (7+64).
853
+ *
854
+ * @param {Function} cb Callback
855
+ * @private
856
+ */
857
+ getPayloadLength64(cb) {
858
+ if (this._bufferedBytes < 8) {
859
+ this._loop = !1;
860
+ return;
861
+ }
862
+ let buf = this.consume(8), num = buf.readUInt32BE(0);
863
+ if (num > Math.pow(2, 21) - 1) {
864
+ let error = this.createError(
865
+ RangeError,
866
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
867
+ !1,
868
+ 1009,
869
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
870
+ );
871
+ cb(error);
872
+ return;
873
+ }
874
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4), this.haveLength(cb);
875
+ }
876
+ /**
877
+ * Payload length has been read.
878
+ *
879
+ * @param {Function} cb Callback
880
+ * @private
881
+ */
882
+ haveLength(cb) {
883
+ if (this._payloadLength && this._opcode < 8 && (this._totalPayloadLength += this._payloadLength, this._totalPayloadLength > this._maxPayload && this._maxPayload > 0)) {
884
+ let error = this.createError(
885
+ RangeError,
886
+ "Max payload size exceeded",
887
+ !1,
888
+ 1009,
889
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
890
+ );
891
+ cb(error);
892
+ return;
893
+ }
894
+ this._masked ? this._state = GET_MASK : this._state = GET_DATA;
895
+ }
896
+ /**
897
+ * Reads mask bytes.
898
+ *
899
+ * @private
900
+ */
901
+ getMask() {
902
+ if (this._bufferedBytes < 4) {
903
+ this._loop = !1;
904
+ return;
905
+ }
906
+ this._mask = this.consume(4), this._state = GET_DATA;
907
+ }
908
+ /**
909
+ * Reads data bytes.
910
+ *
911
+ * @param {Function} cb Callback
912
+ * @private
913
+ */
914
+ getData(cb) {
915
+ let data = EMPTY_BUFFER;
916
+ if (this._payloadLength) {
917
+ if (this._bufferedBytes < this._payloadLength) {
918
+ this._loop = !1;
919
+ return;
920
+ }
921
+ data = this.consume(this._payloadLength), this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 && unmask(data, this._mask);
922
+ }
923
+ if (this._opcode > 7) {
924
+ this.controlMessage(data, cb);
925
+ return;
926
+ }
927
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
928
+ let error = this.createError(
929
+ RangeError,
930
+ "Too many message fragments",
931
+ !1,
932
+ 1008,
933
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
934
+ );
935
+ cb(error);
936
+ return;
937
+ }
938
+ if (this._compressed) {
939
+ this._state = INFLATING, this.decompress(data, cb);
940
+ return;
941
+ }
942
+ data.length && (this._messageLength = this._totalPayloadLength, this._fragments.push(data)), this.dataMessage(cb);
943
+ }
944
+ /**
945
+ * Decompresses data.
946
+ *
947
+ * @param {Buffer} data Compressed data
948
+ * @param {Function} cb Callback
949
+ * @private
950
+ */
951
+ decompress(data, cb) {
952
+ this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
953
+ if (err) return cb(err);
954
+ if (buf.length) {
955
+ if (this._messageLength += buf.length, this._messageLength > this._maxPayload && this._maxPayload > 0) {
956
+ let error = this.createError(
957
+ RangeError,
958
+ "Max payload size exceeded",
959
+ !1,
960
+ 1009,
961
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
962
+ );
963
+ cb(error);
964
+ return;
965
+ }
966
+ this._fragments.push(buf);
967
+ }
968
+ this.dataMessage(cb), this._state === GET_INFO && this.startLoop(cb);
969
+ });
970
+ }
971
+ /**
972
+ * Handles a data message.
973
+ *
974
+ * @param {Function} cb Callback
975
+ * @private
976
+ */
977
+ dataMessage(cb) {
978
+ if (!this._fin) {
979
+ this._state = GET_INFO;
980
+ return;
981
+ }
982
+ let messageLength = this._messageLength, fragments = this._fragments;
983
+ if (this._totalPayloadLength = 0, this._messageLength = 0, this._fragmented = 0, this._numFragments = 0, this._fragments = [], this._opcode === 2) {
984
+ let data;
985
+ this._binaryType === "nodebuffer" ? data = concat(fragments, messageLength) : this._binaryType === "arraybuffer" ? data = toArrayBuffer(concat(fragments, messageLength)) : this._binaryType === "blob" ? data = new Blob(fragments) : data = fragments, this._allowSynchronousEvents ? (this.emit("message", data, !0), this._state = GET_INFO) : (this._state = DEFER_EVENT, setImmediate(() => {
986
+ this.emit("message", data, !0), this._state = GET_INFO, this.startLoop(cb);
987
+ }));
988
+ } else {
989
+ let buf = concat(fragments, messageLength);
990
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
991
+ let error = this.createError(
992
+ Error,
993
+ "invalid UTF-8 sequence",
994
+ !0,
995
+ 1007,
996
+ "WS_ERR_INVALID_UTF8"
997
+ );
998
+ cb(error);
999
+ return;
1000
+ }
1001
+ this._state === INFLATING || this._allowSynchronousEvents ? (this.emit("message", buf, !1), this._state = GET_INFO) : (this._state = DEFER_EVENT, setImmediate(() => {
1002
+ this.emit("message", buf, !1), this._state = GET_INFO, this.startLoop(cb);
1003
+ }));
1004
+ }
1005
+ }
1006
+ /**
1007
+ * Handles a control message.
1008
+ *
1009
+ * @param {Buffer} data Data to handle
1010
+ * @return {(Error|RangeError|undefined)} A possible error
1011
+ * @private
1012
+ */
1013
+ controlMessage(data, cb) {
1014
+ if (this._opcode === 8) {
1015
+ if (data.length === 0)
1016
+ this._loop = !1, this.emit("conclude", 1005, EMPTY_BUFFER), this.end();
1017
+ else {
1018
+ let code = data.readUInt16BE(0);
1019
+ if (!isValidStatusCode(code)) {
1020
+ let error = this.createError(
1021
+ RangeError,
1022
+ `invalid status code ${code}`,
1023
+ !0,
1024
+ 1002,
1025
+ "WS_ERR_INVALID_CLOSE_CODE"
1026
+ );
1027
+ cb(error);
1028
+ return;
1029
+ }
1030
+ let buf = new FastBuffer(
1031
+ data.buffer,
1032
+ data.byteOffset + 2,
1033
+ data.length - 2
1034
+ );
1035
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1036
+ let error = this.createError(
1037
+ Error,
1038
+ "invalid UTF-8 sequence",
1039
+ !0,
1040
+ 1007,
1041
+ "WS_ERR_INVALID_UTF8"
1042
+ );
1043
+ cb(error);
1044
+ return;
1045
+ }
1046
+ this._loop = !1, this.emit("conclude", code, buf), this.end();
1047
+ }
1048
+ this._state = GET_INFO;
1049
+ return;
1050
+ }
1051
+ this._allowSynchronousEvents ? (this.emit(this._opcode === 9 ? "ping" : "pong", data), this._state = GET_INFO) : (this._state = DEFER_EVENT, setImmediate(() => {
1052
+ this.emit(this._opcode === 9 ? "ping" : "pong", data), this._state = GET_INFO, this.startLoop(cb);
1053
+ }));
1054
+ }
1055
+ /**
1056
+ * Builds an error object.
1057
+ *
1058
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1059
+ * @param {String} message The error message
1060
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1061
+ * `message`
1062
+ * @param {Number} statusCode The status code
1063
+ * @param {String} errorCode The exposed error code
1064
+ * @return {(Error|RangeError)} The error
1065
+ * @private
1066
+ */
1067
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1068
+ this._loop = !1, this._errored = !0;
1069
+ let err = new ErrorCtor(
1070
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1071
+ );
1072
+ return Error.captureStackTrace(err, this.createError), err.code = errorCode, err[kStatusCode] = statusCode, err;
1073
+ }
1074
+ };
1075
+ module.exports = Receiver;
1076
+ }
1077
+ });
1078
+
1079
+ // node_modules/ws/lib/sender.js
1080
+ var require_sender = __commonJS({
1081
+ "node_modules/ws/lib/sender.js"(exports, module) {
1082
+ "use strict";
1083
+ var { Duplex } = __require("stream"), { randomFillSync } = __require("crypto"), {
1084
+ types: { isUint8Array }
1085
+ } = __require("util"), PerMessageDeflate = require_permessage_deflate(), { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants(), { isBlob, isValidStatusCode } = require_validation(), { mask: applyMask, toBuffer } = require_buffer_util(), kByteLength = /* @__PURE__ */ Symbol("kByteLength"), maskBuffer = Buffer.alloc(4), RANDOM_POOL_SIZE = 8 * 1024, randomPool, randomPoolPointer = RANDOM_POOL_SIZE, DEFAULT = 0, DEFLATING = 1, GET_BLOB_DATA = 2, Sender = class _Sender {
1086
+ /**
1087
+ * Creates a Sender instance.
1088
+ *
1089
+ * @param {Duplex} socket The connection socket
1090
+ * @param {Object} [extensions] An object containing the negotiated extensions
1091
+ * @param {Function} [generateMask] The function used to generate the masking
1092
+ * key
1093
+ */
1094
+ constructor(socket, extensions, generateMask) {
1095
+ this._extensions = extensions || {}, generateMask && (this._generateMask = generateMask, this._maskBuffer = Buffer.alloc(4)), this._socket = socket, this._firstFragment = !0, this._compress = !1, this._bufferedBytes = 0, this._queue = [], this._state = DEFAULT, this.onerror = NOOP, this[kWebSocket] = void 0;
1096
+ }
1097
+ /**
1098
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1099
+ *
1100
+ * @param {(Buffer|String)} data The data to frame
1101
+ * @param {Object} options Options object
1102
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1103
+ * FIN bit
1104
+ * @param {Function} [options.generateMask] The function used to generate the
1105
+ * masking key
1106
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1107
+ * `data`
1108
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1109
+ * key
1110
+ * @param {Number} options.opcode The opcode
1111
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1112
+ * modified
1113
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1114
+ * RSV1 bit
1115
+ * @return {(Buffer|String)[]} The framed data
1116
+ * @public
1117
+ */
1118
+ static frame(data, options) {
1119
+ let mask, merge = !1, offset = 2, skipMasking = !1;
1120
+ options.mask && (mask = options.maskBuffer || maskBuffer, options.generateMask ? options.generateMask(mask) : (randomPoolPointer === RANDOM_POOL_SIZE && (randomPool === void 0 && (randomPool = Buffer.alloc(RANDOM_POOL_SIZE)), randomFillSync(randomPool, 0, RANDOM_POOL_SIZE), randomPoolPointer = 0), mask[0] = randomPool[randomPoolPointer++], mask[1] = randomPool[randomPoolPointer++], mask[2] = randomPool[randomPoolPointer++], mask[3] = randomPool[randomPoolPointer++]), skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0, offset = 6);
1121
+ let dataLength;
1122
+ typeof data == "string" ? (!options.mask || skipMasking) && options[kByteLength] !== void 0 ? dataLength = options[kByteLength] : (data = Buffer.from(data), dataLength = data.length) : (dataLength = data.length, merge = options.mask && options.readOnly && !skipMasking);
1123
+ let payloadLength = dataLength;
1124
+ dataLength >= 65536 ? (offset += 8, payloadLength = 127) : dataLength > 125 && (offset += 2, payloadLength = 126);
1125
+ let target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1126
+ return target[0] = options.fin ? options.opcode | 128 : options.opcode, options.rsv1 && (target[0] |= 64), target[1] = payloadLength, payloadLength === 126 ? target.writeUInt16BE(dataLength, 2) : payloadLength === 127 && (target[2] = target[3] = 0, target.writeUIntBE(dataLength, 4, 6)), options.mask ? (target[1] |= 128, target[offset - 4] = mask[0], target[offset - 3] = mask[1], target[offset - 2] = mask[2], target[offset - 1] = mask[3], skipMasking ? [target, data] : merge ? (applyMask(data, mask, target, offset, dataLength), [target]) : (applyMask(data, mask, data, 0, dataLength), [target, data])) : [target, data];
1127
+ }
1128
+ /**
1129
+ * Sends a close message to the other peer.
1130
+ *
1131
+ * @param {Number} [code] The status code component of the body
1132
+ * @param {(String|Buffer)} [data] The message component of the body
1133
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1134
+ * @param {Function} [cb] Callback
1135
+ * @public
1136
+ */
1137
+ close(code, data, mask, cb) {
1138
+ let buf;
1139
+ if (code === void 0)
1140
+ buf = EMPTY_BUFFER;
1141
+ else {
1142
+ if (typeof code != "number" || !isValidStatusCode(code))
1143
+ throw new TypeError("First argument must be a valid error code number");
1144
+ if (data === void 0 || !data.length)
1145
+ buf = Buffer.allocUnsafe(2), buf.writeUInt16BE(code, 0);
1146
+ else {
1147
+ let length = Buffer.byteLength(data);
1148
+ if (length > 123)
1149
+ throw new RangeError("The message must not be greater than 123 bytes");
1150
+ if (buf = Buffer.allocUnsafe(2 + length), buf.writeUInt16BE(code, 0), typeof data == "string")
1151
+ buf.write(data, 2);
1152
+ else if (isUint8Array(data))
1153
+ buf.set(data, 2);
1154
+ else
1155
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1156
+ }
1157
+ }
1158
+ let options = {
1159
+ [kByteLength]: buf.length,
1160
+ fin: !0,
1161
+ generateMask: this._generateMask,
1162
+ mask,
1163
+ maskBuffer: this._maskBuffer,
1164
+ opcode: 8,
1165
+ readOnly: !1,
1166
+ rsv1: !1
1167
+ };
1168
+ this._state !== DEFAULT ? this.enqueue([this.dispatch, buf, !1, options, cb]) : this.sendFrame(_Sender.frame(buf, options), cb);
1169
+ }
1170
+ /**
1171
+ * Sends a ping message to the other peer.
1172
+ *
1173
+ * @param {*} data The message to send
1174
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1175
+ * @param {Function} [cb] Callback
1176
+ * @public
1177
+ */
1178
+ ping(data, mask, cb) {
1179
+ let byteLength, readOnly;
1180
+ if (typeof data == "string" ? (byteLength = Buffer.byteLength(data), readOnly = !1) : isBlob(data) ? (byteLength = data.size, readOnly = !1) : (data = toBuffer(data), byteLength = data.length, readOnly = toBuffer.readOnly), byteLength > 125)
1181
+ throw new RangeError("The data size must not be greater than 125 bytes");
1182
+ let options = {
1183
+ [kByteLength]: byteLength,
1184
+ fin: !0,
1185
+ generateMask: this._generateMask,
1186
+ mask,
1187
+ maskBuffer: this._maskBuffer,
1188
+ opcode: 9,
1189
+ readOnly,
1190
+ rsv1: !1
1191
+ };
1192
+ isBlob(data) ? this._state !== DEFAULT ? this.enqueue([this.getBlobData, data, !1, options, cb]) : this.getBlobData(data, !1, options, cb) : this._state !== DEFAULT ? this.enqueue([this.dispatch, data, !1, options, cb]) : this.sendFrame(_Sender.frame(data, options), cb);
1193
+ }
1194
+ /**
1195
+ * Sends a pong message to the other peer.
1196
+ *
1197
+ * @param {*} data The message to send
1198
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1199
+ * @param {Function} [cb] Callback
1200
+ * @public
1201
+ */
1202
+ pong(data, mask, cb) {
1203
+ let byteLength, readOnly;
1204
+ if (typeof data == "string" ? (byteLength = Buffer.byteLength(data), readOnly = !1) : isBlob(data) ? (byteLength = data.size, readOnly = !1) : (data = toBuffer(data), byteLength = data.length, readOnly = toBuffer.readOnly), byteLength > 125)
1205
+ throw new RangeError("The data size must not be greater than 125 bytes");
1206
+ let options = {
1207
+ [kByteLength]: byteLength,
1208
+ fin: !0,
1209
+ generateMask: this._generateMask,
1210
+ mask,
1211
+ maskBuffer: this._maskBuffer,
1212
+ opcode: 10,
1213
+ readOnly,
1214
+ rsv1: !1
1215
+ };
1216
+ isBlob(data) ? this._state !== DEFAULT ? this.enqueue([this.getBlobData, data, !1, options, cb]) : this.getBlobData(data, !1, options, cb) : this._state !== DEFAULT ? this.enqueue([this.dispatch, data, !1, options, cb]) : this.sendFrame(_Sender.frame(data, options), cb);
1217
+ }
1218
+ /**
1219
+ * Sends a data message to the other peer.
1220
+ *
1221
+ * @param {*} data The message to send
1222
+ * @param {Object} options Options object
1223
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1224
+ * or text
1225
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1226
+ * compress `data`
1227
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1228
+ * last one
1229
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1230
+ * `data`
1231
+ * @param {Function} [cb] Callback
1232
+ * @public
1233
+ */
1234
+ send(data, options, cb) {
1235
+ let perMessageDeflate = this._extensions[PerMessageDeflate.extensionName], opcode = options.binary ? 2 : 1, rsv1 = options.compress, byteLength, readOnly;
1236
+ typeof data == "string" ? (byteLength = Buffer.byteLength(data), readOnly = !1) : isBlob(data) ? (byteLength = data.size, readOnly = !1) : (data = toBuffer(data), byteLength = data.length, readOnly = toBuffer.readOnly), this._firstFragment ? (this._firstFragment = !1, rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"] && (rsv1 = byteLength >= perMessageDeflate._threshold), this._compress = rsv1) : (rsv1 = !1, opcode = 0), options.fin && (this._firstFragment = !0);
1237
+ let opts = {
1238
+ [kByteLength]: byteLength,
1239
+ fin: options.fin,
1240
+ generateMask: this._generateMask,
1241
+ mask: options.mask,
1242
+ maskBuffer: this._maskBuffer,
1243
+ opcode,
1244
+ readOnly,
1245
+ rsv1
1246
+ };
1247
+ isBlob(data) ? this._state !== DEFAULT ? this.enqueue([this.getBlobData, data, this._compress, opts, cb]) : this.getBlobData(data, this._compress, opts, cb) : this._state !== DEFAULT ? this.enqueue([this.dispatch, data, this._compress, opts, cb]) : this.dispatch(data, this._compress, opts, cb);
1248
+ }
1249
+ /**
1250
+ * Gets the contents of a blob as binary data.
1251
+ *
1252
+ * @param {Blob} blob The blob
1253
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1254
+ * the data
1255
+ * @param {Object} options Options object
1256
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1257
+ * FIN bit
1258
+ * @param {Function} [options.generateMask] The function used to generate the
1259
+ * masking key
1260
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1261
+ * `data`
1262
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1263
+ * key
1264
+ * @param {Number} options.opcode The opcode
1265
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1266
+ * modified
1267
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1268
+ * RSV1 bit
1269
+ * @param {Function} [cb] Callback
1270
+ * @private
1271
+ */
1272
+ getBlobData(blob, compress, options, cb) {
1273
+ this._bufferedBytes += options[kByteLength], this._state = GET_BLOB_DATA, blob.arrayBuffer().then((arrayBuffer) => {
1274
+ if (this._socket.destroyed) {
1275
+ let err = new Error(
1276
+ "The socket was closed while the blob was being read"
1277
+ );
1278
+ process.nextTick(callCallbacks, this, err, cb);
1279
+ return;
1280
+ }
1281
+ this._bufferedBytes -= options[kByteLength];
1282
+ let data = toBuffer(arrayBuffer);
1283
+ compress ? this.dispatch(data, compress, options, cb) : (this._state = DEFAULT, this.sendFrame(_Sender.frame(data, options), cb), this.dequeue());
1284
+ }).catch((err) => {
1285
+ process.nextTick(onError, this, err, cb);
1286
+ });
1287
+ }
1288
+ /**
1289
+ * Dispatches a message.
1290
+ *
1291
+ * @param {(Buffer|String)} data The message to send
1292
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1293
+ * `data`
1294
+ * @param {Object} options Options object
1295
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1296
+ * FIN bit
1297
+ * @param {Function} [options.generateMask] The function used to generate the
1298
+ * masking key
1299
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1300
+ * `data`
1301
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1302
+ * key
1303
+ * @param {Number} options.opcode The opcode
1304
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1305
+ * modified
1306
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1307
+ * RSV1 bit
1308
+ * @param {Function} [cb] Callback
1309
+ * @private
1310
+ */
1311
+ dispatch(data, compress, options, cb) {
1312
+ if (!compress) {
1313
+ this.sendFrame(_Sender.frame(data, options), cb);
1314
+ return;
1315
+ }
1316
+ let perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1317
+ this._bufferedBytes += options[kByteLength], this._state = DEFLATING, perMessageDeflate.compress(data, options.fin, (_, buf) => {
1318
+ if (this._socket.destroyed) {
1319
+ let err = new Error(
1320
+ "The socket was closed while data was being compressed"
1321
+ );
1322
+ callCallbacks(this, err, cb);
1323
+ return;
1324
+ }
1325
+ this._bufferedBytes -= options[kByteLength], this._state = DEFAULT, options.readOnly = !1, this.sendFrame(_Sender.frame(buf, options), cb), this.dequeue();
1326
+ });
1327
+ }
1328
+ /**
1329
+ * Executes queued send operations.
1330
+ *
1331
+ * @private
1332
+ */
1333
+ dequeue() {
1334
+ for (; this._state === DEFAULT && this._queue.length; ) {
1335
+ let params = this._queue.shift();
1336
+ this._bufferedBytes -= params[3][kByteLength], Reflect.apply(params[0], this, params.slice(1));
1337
+ }
1338
+ }
1339
+ /**
1340
+ * Enqueues a send operation.
1341
+ *
1342
+ * @param {Array} params Send operation parameters.
1343
+ * @private
1344
+ */
1345
+ enqueue(params) {
1346
+ this._bufferedBytes += params[3][kByteLength], this._queue.push(params);
1347
+ }
1348
+ /**
1349
+ * Sends a frame.
1350
+ *
1351
+ * @param {(Buffer | String)[]} list The frame to send
1352
+ * @param {Function} [cb] Callback
1353
+ * @private
1354
+ */
1355
+ sendFrame(list, cb) {
1356
+ list.length === 2 ? (this._socket.cork(), this._socket.write(list[0]), this._socket.write(list[1], cb), this._socket.uncork()) : this._socket.write(list[0], cb);
1357
+ }
1358
+ };
1359
+ module.exports = Sender;
1360
+ function callCallbacks(sender, err, cb) {
1361
+ typeof cb == "function" && cb(err);
1362
+ for (let i = 0; i < sender._queue.length; i++) {
1363
+ let params = sender._queue[i], callback = params[params.length - 1];
1364
+ typeof callback == "function" && callback(err);
1365
+ }
1366
+ }
1367
+ function onError(sender, err, cb) {
1368
+ callCallbacks(sender, err, cb), sender.onerror(err);
1369
+ }
1370
+ }
1371
+ });
1372
+
1373
+ // node_modules/ws/lib/extension.js
1374
+ var require_extension = __commonJS({
1375
+ "node_modules/ws/lib/extension.js"(exports, module) {
1376
+ "use strict";
1377
+ var { tokenChars } = require_validation();
1378
+ function push(dest, name, elem) {
1379
+ dest[name] === void 0 ? dest[name] = [elem] : dest[name].push(elem);
1380
+ }
1381
+ function parse(header) {
1382
+ let offers = /* @__PURE__ */ Object.create(null), params = /* @__PURE__ */ Object.create(null), mustUnescape = !1, isEscaping = !1, inQuotes = !1, extensionName, paramName, start = -1, code = -1, end = -1, i = 0;
1383
+ for (; i < header.length; i++)
1384
+ if (code = header.charCodeAt(i), extensionName === void 0)
1385
+ if (end === -1 && tokenChars[code] === 1)
1386
+ start === -1 && (start = i);
1387
+ else if (i !== 0 && (code === 32 || code === 9))
1388
+ end === -1 && start !== -1 && (end = i);
1389
+ else if (code === 59 || code === 44) {
1390
+ if (start === -1)
1391
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1392
+ end === -1 && (end = i);
1393
+ let name = header.slice(start, end);
1394
+ code === 44 ? (push(offers, name, params), params = /* @__PURE__ */ Object.create(null)) : extensionName = name, start = end = -1;
1395
+ } else
1396
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1397
+ else if (paramName === void 0)
1398
+ if (end === -1 && tokenChars[code] === 1)
1399
+ start === -1 && (start = i);
1400
+ else if (code === 32 || code === 9)
1401
+ end === -1 && start !== -1 && (end = i);
1402
+ else if (code === 59 || code === 44) {
1403
+ if (start === -1)
1404
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1405
+ end === -1 && (end = i), push(params, header.slice(start, end), !0), code === 44 && (push(offers, extensionName, params), params = /* @__PURE__ */ Object.create(null), extensionName = void 0), start = end = -1;
1406
+ } else if (code === 61 && start !== -1 && end === -1)
1407
+ paramName = header.slice(start, i), start = end = -1;
1408
+ else
1409
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1410
+ else if (isEscaping) {
1411
+ if (tokenChars[code] !== 1)
1412
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1413
+ start === -1 ? start = i : mustUnescape || (mustUnescape = !0), isEscaping = !1;
1414
+ } else if (inQuotes)
1415
+ if (tokenChars[code] === 1)
1416
+ start === -1 && (start = i);
1417
+ else if (code === 34 && start !== -1)
1418
+ inQuotes = !1, end = i;
1419
+ else if (code === 92)
1420
+ isEscaping = !0;
1421
+ else
1422
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1423
+ else if (code === 34 && header.charCodeAt(i - 1) === 61)
1424
+ inQuotes = !0;
1425
+ else if (end === -1 && tokenChars[code] === 1)
1426
+ start === -1 && (start = i);
1427
+ else if (start !== -1 && (code === 32 || code === 9))
1428
+ end === -1 && (end = i);
1429
+ else if (code === 59 || code === 44) {
1430
+ if (start === -1)
1431
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1432
+ end === -1 && (end = i);
1433
+ let value = header.slice(start, end);
1434
+ mustUnescape && (value = value.replace(/\\/g, ""), mustUnescape = !1), push(params, paramName, value), code === 44 && (push(offers, extensionName, params), params = /* @__PURE__ */ Object.create(null), extensionName = void 0), paramName = void 0, start = end = -1;
1435
+ } else
1436
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1437
+ if (start === -1 || inQuotes || code === 32 || code === 9)
1438
+ throw new SyntaxError("Unexpected end of input");
1439
+ end === -1 && (end = i);
1440
+ let token = header.slice(start, end);
1441
+ return extensionName === void 0 ? push(offers, token, params) : (paramName === void 0 ? push(params, token, !0) : mustUnescape ? push(params, paramName, token.replace(/\\/g, "")) : push(params, paramName, token), push(offers, extensionName, params)), offers;
1442
+ }
1443
+ function format(extensions) {
1444
+ return Object.keys(extensions).map((extension) => {
1445
+ let configurations = extensions[extension];
1446
+ return Array.isArray(configurations) || (configurations = [configurations]), configurations.map((params) => [extension].concat(
1447
+ Object.keys(params).map((k) => {
1448
+ let values = params[k];
1449
+ return Array.isArray(values) || (values = [values]), values.map((v) => v === !0 ? k : `${k}=${v}`).join("; ");
1450
+ })
1451
+ ).join("; ")).join(", ");
1452
+ }).join(", ");
1453
+ }
1454
+ module.exports = { format, parse };
1455
+ }
1456
+ });
1457
+
1458
+ // node_modules/ws/lib/event-target.js
1459
+ var require_event_target = __commonJS({
1460
+ "node_modules/ws/lib/event-target.js"(exports, module) {
1461
+ "use strict";
1462
+ var { kForOnEventAttribute, kListener } = require_constants(), kCode = /* @__PURE__ */ Symbol("kCode"), kData = /* @__PURE__ */ Symbol("kData"), kError = /* @__PURE__ */ Symbol("kError"), kMessage = /* @__PURE__ */ Symbol("kMessage"), kReason = /* @__PURE__ */ Symbol("kReason"), kTarget = /* @__PURE__ */ Symbol("kTarget"), kType = /* @__PURE__ */ Symbol("kType"), kWasClean = /* @__PURE__ */ Symbol("kWasClean"), Event = class {
1463
+ /**
1464
+ * Create a new `Event`.
1465
+ *
1466
+ * @param {String} type The name of the event
1467
+ * @throws {TypeError} If the `type` argument is not specified
1468
+ */
1469
+ constructor(type) {
1470
+ this[kTarget] = null, this[kType] = type;
1471
+ }
1472
+ /**
1473
+ * @type {*}
1474
+ */
1475
+ get target() {
1476
+ return this[kTarget];
1477
+ }
1478
+ /**
1479
+ * @type {String}
1480
+ */
1481
+ get type() {
1482
+ return this[kType];
1483
+ }
1484
+ };
1485
+ Object.defineProperty(Event.prototype, "target", { enumerable: !0 });
1486
+ Object.defineProperty(Event.prototype, "type", { enumerable: !0 });
1487
+ var CloseEvent = class extends Event {
1488
+ /**
1489
+ * Create a new `CloseEvent`.
1490
+ *
1491
+ * @param {String} type The name of the event
1492
+ * @param {Object} [options] A dictionary object that allows for setting
1493
+ * attributes via object members of the same name
1494
+ * @param {Number} [options.code=0] The status code explaining why the
1495
+ * connection was closed
1496
+ * @param {String} [options.reason=''] A human-readable string explaining why
1497
+ * the connection was closed
1498
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1499
+ * connection was cleanly closed
1500
+ */
1501
+ constructor(type, options = {}) {
1502
+ super(type), this[kCode] = options.code === void 0 ? 0 : options.code, this[kReason] = options.reason === void 0 ? "" : options.reason, this[kWasClean] = options.wasClean === void 0 ? !1 : options.wasClean;
1503
+ }
1504
+ /**
1505
+ * @type {Number}
1506
+ */
1507
+ get code() {
1508
+ return this[kCode];
1509
+ }
1510
+ /**
1511
+ * @type {String}
1512
+ */
1513
+ get reason() {
1514
+ return this[kReason];
1515
+ }
1516
+ /**
1517
+ * @type {Boolean}
1518
+ */
1519
+ get wasClean() {
1520
+ return this[kWasClean];
1521
+ }
1522
+ };
1523
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: !0 });
1524
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: !0 });
1525
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: !0 });
1526
+ var ErrorEvent = class extends Event {
1527
+ /**
1528
+ * Create a new `ErrorEvent`.
1529
+ *
1530
+ * @param {String} type The name of the event
1531
+ * @param {Object} [options] A dictionary object that allows for setting
1532
+ * attributes via object members of the same name
1533
+ * @param {*} [options.error=null] The error that generated this event
1534
+ * @param {String} [options.message=''] The error message
1535
+ */
1536
+ constructor(type, options = {}) {
1537
+ super(type), this[kError] = options.error === void 0 ? null : options.error, this[kMessage] = options.message === void 0 ? "" : options.message;
1538
+ }
1539
+ /**
1540
+ * @type {*}
1541
+ */
1542
+ get error() {
1543
+ return this[kError];
1544
+ }
1545
+ /**
1546
+ * @type {String}
1547
+ */
1548
+ get message() {
1549
+ return this[kMessage];
1550
+ }
1551
+ };
1552
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: !0 });
1553
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: !0 });
1554
+ var MessageEvent = class extends Event {
1555
+ /**
1556
+ * Create a new `MessageEvent`.
1557
+ *
1558
+ * @param {String} type The name of the event
1559
+ * @param {Object} [options] A dictionary object that allows for setting
1560
+ * attributes via object members of the same name
1561
+ * @param {*} [options.data=null] The message content
1562
+ */
1563
+ constructor(type, options = {}) {
1564
+ super(type), this[kData] = options.data === void 0 ? null : options.data;
1565
+ }
1566
+ /**
1567
+ * @type {*}
1568
+ */
1569
+ get data() {
1570
+ return this[kData];
1571
+ }
1572
+ };
1573
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: !0 });
1574
+ var EventTarget = {
1575
+ /**
1576
+ * Register an event listener.
1577
+ *
1578
+ * @param {String} type A string representing the event type to listen for
1579
+ * @param {(Function|Object)} handler The listener to add
1580
+ * @param {Object} [options] An options object specifies characteristics about
1581
+ * the event listener
1582
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1583
+ * listener should be invoked at most once after being added. If `true`,
1584
+ * the listener would be automatically removed when invoked.
1585
+ * @public
1586
+ */
1587
+ addEventListener(type, handler, options = {}) {
1588
+ for (let listener of this.listeners(type))
1589
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute])
1590
+ return;
1591
+ let wrapper;
1592
+ if (type === "message")
1593
+ wrapper = function(data, isBinary) {
1594
+ let event = new MessageEvent("message", {
1595
+ data: isBinary ? data : data.toString()
1596
+ });
1597
+ event[kTarget] = this, callListener(handler, this, event);
1598
+ };
1599
+ else if (type === "close")
1600
+ wrapper = function(code, message) {
1601
+ let event = new CloseEvent("close", {
1602
+ code,
1603
+ reason: message.toString(),
1604
+ wasClean: this._closeFrameReceived && this._closeFrameSent
1605
+ });
1606
+ event[kTarget] = this, callListener(handler, this, event);
1607
+ };
1608
+ else if (type === "error")
1609
+ wrapper = function(error) {
1610
+ let event = new ErrorEvent("error", {
1611
+ error,
1612
+ message: error.message
1613
+ });
1614
+ event[kTarget] = this, callListener(handler, this, event);
1615
+ };
1616
+ else if (type === "open")
1617
+ wrapper = function() {
1618
+ let event = new Event("open");
1619
+ event[kTarget] = this, callListener(handler, this, event);
1620
+ };
1621
+ else
1622
+ return;
1623
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute], wrapper[kListener] = handler, options.once ? this.once(type, wrapper) : this.on(type, wrapper);
1624
+ },
1625
+ /**
1626
+ * Remove an event listener.
1627
+ *
1628
+ * @param {String} type A string representing the event type to remove
1629
+ * @param {(Function|Object)} handler The listener to remove
1630
+ * @public
1631
+ */
1632
+ removeEventListener(type, handler) {
1633
+ for (let listener of this.listeners(type))
1634
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1635
+ this.removeListener(type, listener);
1636
+ break;
1637
+ }
1638
+ }
1639
+ };
1640
+ module.exports = {
1641
+ CloseEvent,
1642
+ ErrorEvent,
1643
+ Event,
1644
+ EventTarget,
1645
+ MessageEvent
1646
+ };
1647
+ function callListener(listener, thisArg, event) {
1648
+ typeof listener == "object" && listener.handleEvent ? listener.handleEvent.call(listener, event) : listener.call(thisArg, event);
1649
+ }
1650
+ }
1651
+ });
1652
+
1653
+ // node_modules/ws/lib/websocket.js
1654
+ var require_websocket = __commonJS({
1655
+ "node_modules/ws/lib/websocket.js"(exports, module) {
1656
+ "use strict";
1657
+ var EventEmitter = __require("events"), https = __require("https"), http = __require("http"), net = __require("net"), tls = __require("tls"), { randomBytes, createHash } = __require("crypto"), { Duplex, Readable } = __require("stream"), { URL } = __require("url"), PerMessageDeflate = require_permessage_deflate(), Receiver = require_receiver(), Sender = require_sender(), { isBlob } = require_validation(), {
1658
+ BINARY_TYPES,
1659
+ CLOSE_TIMEOUT,
1660
+ EMPTY_BUFFER,
1661
+ GUID,
1662
+ kForOnEventAttribute,
1663
+ kListener,
1664
+ kStatusCode,
1665
+ kWebSocket,
1666
+ NOOP
1667
+ } = require_constants(), {
1668
+ EventTarget: { addEventListener, removeEventListener }
1669
+ } = require_event_target(), { format, parse } = require_extension(), { toBuffer } = require_buffer_util(), kAborted = /* @__PURE__ */ Symbol("kAborted"), protocolVersions = [8, 13], readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"], subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/, WebSocket = class _WebSocket extends EventEmitter {
1670
+ /**
1671
+ * Create a new `WebSocket`.
1672
+ *
1673
+ * @param {(String|URL)} address The URL to which to connect
1674
+ * @param {(String|String[])} [protocols] The subprotocols
1675
+ * @param {Object} [options] Connection options
1676
+ */
1677
+ constructor(address, protocols, options) {
1678
+ super(), this._binaryType = BINARY_TYPES[0], this._closeCode = 1006, this._closeFrameReceived = !1, this._closeFrameSent = !1, this._closeMessage = EMPTY_BUFFER, this._closeTimer = null, this._errorEmitted = !1, this._extensions = {}, this._paused = !1, this._protocol = "", this._readyState = _WebSocket.CONNECTING, this._receiver = null, this._sender = null, this._socket = null, address !== null ? (this._bufferedAmount = 0, this._isServer = !1, this._redirects = 0, protocols === void 0 ? protocols = [] : Array.isArray(protocols) || (typeof protocols == "object" && protocols !== null ? (options = protocols, protocols = []) : protocols = [protocols]), initAsClient(this, address, protocols, options)) : (this._autoPong = options.autoPong, this._closeTimeout = options.closeTimeout, this._isServer = !0);
1679
+ }
1680
+ /**
1681
+ * For historical reasons, the custom "nodebuffer" type is used by the default
1682
+ * instead of "blob".
1683
+ *
1684
+ * @type {String}
1685
+ */
1686
+ get binaryType() {
1687
+ return this._binaryType;
1688
+ }
1689
+ set binaryType(type) {
1690
+ BINARY_TYPES.includes(type) && (this._binaryType = type, this._receiver && (this._receiver._binaryType = type));
1691
+ }
1692
+ /**
1693
+ * @type {Number}
1694
+ */
1695
+ get bufferedAmount() {
1696
+ return this._socket ? this._socket._writableState.length + this._sender._bufferedBytes : this._bufferedAmount;
1697
+ }
1698
+ /**
1699
+ * @type {String}
1700
+ */
1701
+ get extensions() {
1702
+ return Object.keys(this._extensions).join();
1703
+ }
1704
+ /**
1705
+ * @type {Boolean}
1706
+ */
1707
+ get isPaused() {
1708
+ return this._paused;
1709
+ }
1710
+ /**
1711
+ * @type {Function}
1712
+ */
1713
+ /* istanbul ignore next */
1714
+ get onclose() {
1715
+ return null;
1716
+ }
1717
+ /**
1718
+ * @type {Function}
1719
+ */
1720
+ /* istanbul ignore next */
1721
+ get onerror() {
1722
+ return null;
1723
+ }
1724
+ /**
1725
+ * @type {Function}
1726
+ */
1727
+ /* istanbul ignore next */
1728
+ get onopen() {
1729
+ return null;
1730
+ }
1731
+ /**
1732
+ * @type {Function}
1733
+ */
1734
+ /* istanbul ignore next */
1735
+ get onmessage() {
1736
+ return null;
1737
+ }
1738
+ /**
1739
+ * @type {String}
1740
+ */
1741
+ get protocol() {
1742
+ return this._protocol;
1743
+ }
1744
+ /**
1745
+ * @type {Number}
1746
+ */
1747
+ get readyState() {
1748
+ return this._readyState;
1749
+ }
1750
+ /**
1751
+ * @type {String}
1752
+ */
1753
+ get url() {
1754
+ return this._url;
1755
+ }
1756
+ /**
1757
+ * Set up the socket and the internal resources.
1758
+ *
1759
+ * @param {Duplex} socket The network socket between the server and client
1760
+ * @param {Buffer} head The first packet of the upgraded stream
1761
+ * @param {Object} options Options object
1762
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
1763
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
1764
+ * multiple times in the same tick
1765
+ * @param {Function} [options.generateMask] The function used to generate the
1766
+ * masking key
1767
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
1768
+ * buffered data chunks
1769
+ * @param {Number} [options.maxFragments=0] The maximum number of message
1770
+ * fragments
1771
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
1772
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
1773
+ * not to skip UTF-8 validation for text and close messages
1774
+ * @private
1775
+ */
1776
+ setSocket(socket, head, options) {
1777
+ let receiver = new Receiver({
1778
+ allowSynchronousEvents: options.allowSynchronousEvents,
1779
+ binaryType: this.binaryType,
1780
+ extensions: this._extensions,
1781
+ isServer: this._isServer,
1782
+ maxBufferedChunks: options.maxBufferedChunks,
1783
+ maxFragments: options.maxFragments,
1784
+ maxPayload: options.maxPayload,
1785
+ skipUTF8Validation: options.skipUTF8Validation
1786
+ }), sender = new Sender(socket, this._extensions, options.generateMask);
1787
+ this._receiver = receiver, this._sender = sender, this._socket = socket, receiver[kWebSocket] = this, sender[kWebSocket] = this, socket[kWebSocket] = this, receiver.on("conclude", receiverOnConclude), receiver.on("drain", receiverOnDrain), receiver.on("error", receiverOnError), receiver.on("message", receiverOnMessage), receiver.on("ping", receiverOnPing), receiver.on("pong", receiverOnPong), sender.onerror = senderOnError, socket.setTimeout && socket.setTimeout(0), socket.setNoDelay && socket.setNoDelay(), head.length > 0 && socket.unshift(head), socket.on("close", socketOnClose), socket.on("data", socketOnData), socket.on("end", socketOnEnd), socket.on("error", socketOnError), this._readyState = _WebSocket.OPEN, this.emit("open");
1788
+ }
1789
+ /**
1790
+ * Emit the `'close'` event.
1791
+ *
1792
+ * @private
1793
+ */
1794
+ emitClose() {
1795
+ if (!this._socket) {
1796
+ this._readyState = _WebSocket.CLOSED, this.emit("close", this._closeCode, this._closeMessage);
1797
+ return;
1798
+ }
1799
+ this._extensions[PerMessageDeflate.extensionName] && this._extensions[PerMessageDeflate.extensionName].cleanup(), this._receiver.removeAllListeners(), this._readyState = _WebSocket.CLOSED, this.emit("close", this._closeCode, this._closeMessage);
1800
+ }
1801
+ /**
1802
+ * Start a closing handshake.
1803
+ *
1804
+ * +----------+ +-----------+ +----------+
1805
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
1806
+ * | +----------+ +-----------+ +----------+ |
1807
+ * +----------+ +-----------+ |
1808
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
1809
+ * +----------+ +-----------+ |
1810
+ * | | | +---+ |
1811
+ * +------------------------+-->|fin| - - - -
1812
+ * | +---+ | +---+
1813
+ * - - - - -|fin|<---------------------+
1814
+ * +---+
1815
+ *
1816
+ * @param {Number} [code] Status code explaining why the connection is closing
1817
+ * @param {(String|Buffer)} [data] The reason why the connection is
1818
+ * closing
1819
+ * @public
1820
+ */
1821
+ close(code, data) {
1822
+ if (this.readyState !== _WebSocket.CLOSED) {
1823
+ if (this.readyState === _WebSocket.CONNECTING) {
1824
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
1825
+ return;
1826
+ }
1827
+ if (this.readyState === _WebSocket.CLOSING) {
1828
+ this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted) && this._socket.end();
1829
+ return;
1830
+ }
1831
+ this._readyState = _WebSocket.CLOSING, this._sender.close(code, data, !this._isServer, (err) => {
1832
+ err || (this._closeFrameSent = !0, (this._closeFrameReceived || this._receiver._writableState.errorEmitted) && this._socket.end());
1833
+ }), setCloseTimer(this);
1834
+ }
1835
+ }
1836
+ /**
1837
+ * Pause the socket.
1838
+ *
1839
+ * @public
1840
+ */
1841
+ pause() {
1842
+ this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED || (this._paused = !0, this._socket.pause());
1843
+ }
1844
+ /**
1845
+ * Send a ping.
1846
+ *
1847
+ * @param {*} [data] The data to send
1848
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
1849
+ * @param {Function} [cb] Callback which is executed when the ping is sent
1850
+ * @public
1851
+ */
1852
+ ping(data, mask, cb) {
1853
+ if (this.readyState === _WebSocket.CONNECTING)
1854
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1855
+ if (typeof data == "function" ? (cb = data, data = mask = void 0) : typeof mask == "function" && (cb = mask, mask = void 0), typeof data == "number" && (data = data.toString()), this.readyState !== _WebSocket.OPEN) {
1856
+ sendAfterClose(this, data, cb);
1857
+ return;
1858
+ }
1859
+ mask === void 0 && (mask = !this._isServer), this._sender.ping(data || EMPTY_BUFFER, mask, cb);
1860
+ }
1861
+ /**
1862
+ * Send a pong.
1863
+ *
1864
+ * @param {*} [data] The data to send
1865
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
1866
+ * @param {Function} [cb] Callback which is executed when the pong is sent
1867
+ * @public
1868
+ */
1869
+ pong(data, mask, cb) {
1870
+ if (this.readyState === _WebSocket.CONNECTING)
1871
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1872
+ if (typeof data == "function" ? (cb = data, data = mask = void 0) : typeof mask == "function" && (cb = mask, mask = void 0), typeof data == "number" && (data = data.toString()), this.readyState !== _WebSocket.OPEN) {
1873
+ sendAfterClose(this, data, cb);
1874
+ return;
1875
+ }
1876
+ mask === void 0 && (mask = !this._isServer), this._sender.pong(data || EMPTY_BUFFER, mask, cb);
1877
+ }
1878
+ /**
1879
+ * Resume the socket.
1880
+ *
1881
+ * @public
1882
+ */
1883
+ resume() {
1884
+ this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED || (this._paused = !1, this._receiver._writableState.needDrain || this._socket.resume());
1885
+ }
1886
+ /**
1887
+ * Send a data message.
1888
+ *
1889
+ * @param {*} data The message to send
1890
+ * @param {Object} [options] Options object
1891
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
1892
+ * text
1893
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
1894
+ * `data`
1895
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
1896
+ * last one
1897
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
1898
+ * @param {Function} [cb] Callback which is executed when data is written out
1899
+ * @public
1900
+ */
1901
+ send(data, options, cb) {
1902
+ if (this.readyState === _WebSocket.CONNECTING)
1903
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1904
+ if (typeof options == "function" && (cb = options, options = {}), typeof data == "number" && (data = data.toString()), this.readyState !== _WebSocket.OPEN) {
1905
+ sendAfterClose(this, data, cb);
1906
+ return;
1907
+ }
1908
+ let opts = {
1909
+ binary: typeof data != "string",
1910
+ mask: !this._isServer,
1911
+ compress: !0,
1912
+ fin: !0,
1913
+ ...options
1914
+ };
1915
+ this._extensions[PerMessageDeflate.extensionName] || (opts.compress = !1), this._sender.send(data || EMPTY_BUFFER, opts, cb);
1916
+ }
1917
+ /**
1918
+ * Forcibly close the connection.
1919
+ *
1920
+ * @public
1921
+ */
1922
+ terminate() {
1923
+ if (this.readyState !== _WebSocket.CLOSED) {
1924
+ if (this.readyState === _WebSocket.CONNECTING) {
1925
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
1926
+ return;
1927
+ }
1928
+ this._socket && (this._readyState = _WebSocket.CLOSING, this._socket.destroy());
1929
+ }
1930
+ }
1931
+ };
1932
+ Object.defineProperty(WebSocket, "CONNECTING", {
1933
+ enumerable: !0,
1934
+ value: readyStates.indexOf("CONNECTING")
1935
+ });
1936
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
1937
+ enumerable: !0,
1938
+ value: readyStates.indexOf("CONNECTING")
1939
+ });
1940
+ Object.defineProperty(WebSocket, "OPEN", {
1941
+ enumerable: !0,
1942
+ value: readyStates.indexOf("OPEN")
1943
+ });
1944
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
1945
+ enumerable: !0,
1946
+ value: readyStates.indexOf("OPEN")
1947
+ });
1948
+ Object.defineProperty(WebSocket, "CLOSING", {
1949
+ enumerable: !0,
1950
+ value: readyStates.indexOf("CLOSING")
1951
+ });
1952
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
1953
+ enumerable: !0,
1954
+ value: readyStates.indexOf("CLOSING")
1955
+ });
1956
+ Object.defineProperty(WebSocket, "CLOSED", {
1957
+ enumerable: !0,
1958
+ value: readyStates.indexOf("CLOSED")
1959
+ });
1960
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
1961
+ enumerable: !0,
1962
+ value: readyStates.indexOf("CLOSED")
1963
+ });
1964
+ [
1965
+ "binaryType",
1966
+ "bufferedAmount",
1967
+ "extensions",
1968
+ "isPaused",
1969
+ "protocol",
1970
+ "readyState",
1971
+ "url"
1972
+ ].forEach((property) => {
1973
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: !0 });
1974
+ });
1975
+ ["open", "error", "close", "message"].forEach((method) => {
1976
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
1977
+ enumerable: !0,
1978
+ get() {
1979
+ for (let listener of this.listeners(method))
1980
+ if (listener[kForOnEventAttribute]) return listener[kListener];
1981
+ return null;
1982
+ },
1983
+ set(handler) {
1984
+ for (let listener of this.listeners(method))
1985
+ if (listener[kForOnEventAttribute]) {
1986
+ this.removeListener(method, listener);
1987
+ break;
1988
+ }
1989
+ typeof handler == "function" && this.addEventListener(method, handler, {
1990
+ [kForOnEventAttribute]: !0
1991
+ });
1992
+ }
1993
+ });
1994
+ });
1995
+ WebSocket.prototype.addEventListener = addEventListener;
1996
+ WebSocket.prototype.removeEventListener = removeEventListener;
1997
+ module.exports = WebSocket;
1998
+ function initAsClient(websocket, address, protocols, options) {
1999
+ let opts = {
2000
+ allowSynchronousEvents: !0,
2001
+ autoPong: !0,
2002
+ closeTimeout: CLOSE_TIMEOUT,
2003
+ protocolVersion: protocolVersions[1],
2004
+ maxBufferedChunks: 262144,
2005
+ maxFragments: 16384,
2006
+ maxPayload: 104857600,
2007
+ skipUTF8Validation: !1,
2008
+ perMessageDeflate: !0,
2009
+ followRedirects: !1,
2010
+ maxRedirects: 10,
2011
+ ...options,
2012
+ socketPath: void 0,
2013
+ hostname: void 0,
2014
+ protocol: void 0,
2015
+ timeout: void 0,
2016
+ method: "GET",
2017
+ host: void 0,
2018
+ path: void 0,
2019
+ port: void 0
2020
+ };
2021
+ if (websocket._autoPong = opts.autoPong, websocket._closeTimeout = opts.closeTimeout, !protocolVersions.includes(opts.protocolVersion))
2022
+ throw new RangeError(
2023
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2024
+ );
2025
+ let parsedUrl;
2026
+ if (address instanceof URL)
2027
+ parsedUrl = address;
2028
+ else
2029
+ try {
2030
+ parsedUrl = new URL(address);
2031
+ } catch {
2032
+ throw new SyntaxError(`Invalid URL: ${address}`);
2033
+ }
2034
+ parsedUrl.protocol === "http:" ? parsedUrl.protocol = "ws:" : parsedUrl.protocol === "https:" && (parsedUrl.protocol = "wss:"), websocket._url = parsedUrl.href;
2035
+ let isSecure = parsedUrl.protocol === "wss:", isIpcUrl = parsedUrl.protocol === "ws+unix:", invalidUrlMessage;
2036
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl ? invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"` : isIpcUrl && !parsedUrl.pathname ? invalidUrlMessage = "The URL's pathname is empty" : parsedUrl.hash && (invalidUrlMessage = "The URL contains a fragment identifier"), invalidUrlMessage) {
2037
+ let err = new SyntaxError(invalidUrlMessage);
2038
+ if (websocket._redirects === 0)
2039
+ throw err;
2040
+ emitErrorAndClose(websocket, err);
2041
+ return;
2042
+ }
2043
+ let defaultPort = isSecure ? 443 : 80, key = randomBytes(16).toString("base64"), request = isSecure ? https.request : http.request, protocolSet = /* @__PURE__ */ new Set(), perMessageDeflate;
2044
+ if (opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect), opts.defaultPort = opts.defaultPort || defaultPort, opts.port = parsedUrl.port || defaultPort, opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname, opts.headers = {
2045
+ ...opts.headers,
2046
+ "Sec-WebSocket-Version": opts.protocolVersion,
2047
+ "Sec-WebSocket-Key": key,
2048
+ Connection: "Upgrade",
2049
+ Upgrade: "websocket"
2050
+ }, opts.path = parsedUrl.pathname + parsedUrl.search, opts.timeout = opts.handshakeTimeout, opts.perMessageDeflate && (perMessageDeflate = new PerMessageDeflate({
2051
+ ...opts.perMessageDeflate,
2052
+ isServer: !1,
2053
+ maxPayload: opts.maxPayload
2054
+ }), opts.headers["Sec-WebSocket-Extensions"] = format({
2055
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2056
+ })), protocols.length) {
2057
+ for (let protocol of protocols) {
2058
+ if (typeof protocol != "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol))
2059
+ throw new SyntaxError(
2060
+ "An invalid or duplicated subprotocol was specified"
2061
+ );
2062
+ protocolSet.add(protocol);
2063
+ }
2064
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2065
+ }
2066
+ if (opts.origin && (opts.protocolVersion < 13 ? opts.headers["Sec-WebSocket-Origin"] = opts.origin : opts.headers.Origin = opts.origin), (parsedUrl.username || parsedUrl.password) && (opts.auth = `${parsedUrl.username}:${parsedUrl.password}`), isIpcUrl) {
2067
+ let parts = opts.path.split(":");
2068
+ opts.socketPath = parts[0], opts.path = parts[1];
2069
+ }
2070
+ let req;
2071
+ if (opts.followRedirects) {
2072
+ if (websocket._redirects === 0) {
2073
+ websocket._originalIpc = isIpcUrl, websocket._originalSecure = isSecure, websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2074
+ let headers = options && options.headers;
2075
+ if (options = { ...options, headers: {} }, headers)
2076
+ for (let [key2, value] of Object.entries(headers))
2077
+ options.headers[key2.toLowerCase()] = value;
2078
+ } else if (websocket.listenerCount("redirect") === 0) {
2079
+ let isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : !1 : websocket._originalIpc ? !1 : parsedUrl.host === websocket._originalHostOrSocketPath;
2080
+ (!isSameHost || websocket._originalSecure && !isSecure) && (delete opts.headers.authorization, delete opts.headers.cookie, isSameHost || delete opts.headers.host, opts.auth = void 0);
2081
+ }
2082
+ opts.auth && !options.headers.authorization && (options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64")), req = websocket._req = request(opts), websocket._redirects && websocket.emit("redirect", websocket.url, req);
2083
+ } else
2084
+ req = websocket._req = request(opts);
2085
+ opts.timeout && req.on("timeout", () => {
2086
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2087
+ }), req.on("error", (err) => {
2088
+ req === null || req[kAborted] || (req = websocket._req = null, emitErrorAndClose(websocket, err));
2089
+ }), req.on("response", (res) => {
2090
+ let location = res.headers.location, statusCode = res.statusCode;
2091
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2092
+ if (++websocket._redirects > opts.maxRedirects) {
2093
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2094
+ return;
2095
+ }
2096
+ req.abort();
2097
+ let addr;
2098
+ try {
2099
+ addr = new URL(location, address);
2100
+ } catch {
2101
+ let err = new SyntaxError(`Invalid URL: ${location}`);
2102
+ emitErrorAndClose(websocket, err);
2103
+ return;
2104
+ }
2105
+ initAsClient(websocket, addr, protocols, options);
2106
+ } else websocket.emit("unexpected-response", req, res) || abortHandshake(
2107
+ websocket,
2108
+ req,
2109
+ `Unexpected server response: ${res.statusCode}`
2110
+ );
2111
+ }), req.on("upgrade", (res, socket, head) => {
2112
+ if (websocket.emit("upgrade", res), websocket.readyState !== WebSocket.CONNECTING) return;
2113
+ req = websocket._req = null;
2114
+ let upgrade = res.headers.upgrade;
2115
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2116
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2117
+ return;
2118
+ }
2119
+ let digest = createHash("sha1").update(key + GUID).digest("base64");
2120
+ if (res.headers["sec-websocket-accept"] !== digest) {
2121
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2122
+ return;
2123
+ }
2124
+ let serverProt = res.headers["sec-websocket-protocol"], protError;
2125
+ if (serverProt !== void 0 ? protocolSet.size ? protocolSet.has(serverProt) || (protError = "Server sent an invalid subprotocol") : protError = "Server sent a subprotocol but none was requested" : protocolSet.size && (protError = "Server sent no subprotocol"), protError) {
2126
+ abortHandshake(websocket, socket, protError);
2127
+ return;
2128
+ }
2129
+ serverProt && (websocket._protocol = serverProt);
2130
+ let secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2131
+ if (secWebSocketExtensions !== void 0) {
2132
+ if (!perMessageDeflate) {
2133
+ abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
2134
+ return;
2135
+ }
2136
+ let extensions;
2137
+ try {
2138
+ extensions = parse(secWebSocketExtensions);
2139
+ } catch {
2140
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2141
+ return;
2142
+ }
2143
+ let extensionNames = Object.keys(extensions);
2144
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2145
+ abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
2146
+ return;
2147
+ }
2148
+ try {
2149
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2150
+ } catch {
2151
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2152
+ return;
2153
+ }
2154
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2155
+ }
2156
+ websocket.setSocket(socket, head, {
2157
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2158
+ generateMask: opts.generateMask,
2159
+ maxBufferedChunks: opts.maxBufferedChunks,
2160
+ maxFragments: opts.maxFragments,
2161
+ maxPayload: opts.maxPayload,
2162
+ skipUTF8Validation: opts.skipUTF8Validation
2163
+ });
2164
+ }), opts.finishRequest ? opts.finishRequest(req, websocket) : req.end();
2165
+ }
2166
+ function emitErrorAndClose(websocket, err) {
2167
+ websocket._readyState = WebSocket.CLOSING, websocket._errorEmitted = !0, websocket.emit("error", err), websocket.emitClose();
2168
+ }
2169
+ function netConnect(options) {
2170
+ return options.path = options.socketPath, net.connect(options);
2171
+ }
2172
+ function tlsConnect(options) {
2173
+ return options.path = void 0, !options.servername && options.servername !== "" && (options.servername = net.isIP(options.host) ? "" : options.host), tls.connect(options);
2174
+ }
2175
+ function abortHandshake(websocket, stream, message) {
2176
+ websocket._readyState = WebSocket.CLOSING;
2177
+ let err = new Error(message);
2178
+ Error.captureStackTrace(err, abortHandshake), stream.setHeader ? (stream[kAborted] = !0, stream.abort(), stream.socket && !stream.socket.destroyed && stream.socket.destroy(), process.nextTick(emitErrorAndClose, websocket, err)) : (stream.destroy(err), stream.once("error", websocket.emit.bind(websocket, "error")), stream.once("close", websocket.emitClose.bind(websocket)));
2179
+ }
2180
+ function sendAfterClose(websocket, data, cb) {
2181
+ if (data) {
2182
+ let length = isBlob(data) ? data.size : toBuffer(data).length;
2183
+ websocket._socket ? websocket._sender._bufferedBytes += length : websocket._bufferedAmount += length;
2184
+ }
2185
+ if (cb) {
2186
+ let err = new Error(
2187
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
2188
+ );
2189
+ process.nextTick(cb, err);
2190
+ }
2191
+ }
2192
+ function receiverOnConclude(code, reason) {
2193
+ let websocket = this[kWebSocket];
2194
+ websocket._closeFrameReceived = !0, websocket._closeMessage = reason, websocket._closeCode = code, websocket._socket[kWebSocket] !== void 0 && (websocket._socket.removeListener("data", socketOnData), process.nextTick(resume, websocket._socket), code === 1005 ? websocket.close() : websocket.close(code, reason));
2195
+ }
2196
+ function receiverOnDrain() {
2197
+ let websocket = this[kWebSocket];
2198
+ websocket.isPaused || websocket._socket.resume();
2199
+ }
2200
+ function receiverOnError(err) {
2201
+ let websocket = this[kWebSocket];
2202
+ websocket._socket[kWebSocket] !== void 0 && (websocket._socket.removeListener("data", socketOnData), process.nextTick(resume, websocket._socket), websocket.close(err[kStatusCode])), websocket._errorEmitted || (websocket._errorEmitted = !0, websocket.emit("error", err));
2203
+ }
2204
+ function receiverOnFinish() {
2205
+ this[kWebSocket].emitClose();
2206
+ }
2207
+ function receiverOnMessage(data, isBinary) {
2208
+ this[kWebSocket].emit("message", data, isBinary);
2209
+ }
2210
+ function receiverOnPing(data) {
2211
+ let websocket = this[kWebSocket];
2212
+ websocket._autoPong && websocket.pong(data, !this._isServer, NOOP), websocket.emit("ping", data);
2213
+ }
2214
+ function receiverOnPong(data) {
2215
+ this[kWebSocket].emit("pong", data);
2216
+ }
2217
+ function resume(stream) {
2218
+ stream.resume();
2219
+ }
2220
+ function senderOnError(err) {
2221
+ let websocket = this[kWebSocket];
2222
+ websocket.readyState !== WebSocket.CLOSED && (websocket.readyState === WebSocket.OPEN && (websocket._readyState = WebSocket.CLOSING, setCloseTimer(websocket)), this._socket.end(), websocket._errorEmitted || (websocket._errorEmitted = !0, websocket.emit("error", err)));
2223
+ }
2224
+ function setCloseTimer(websocket) {
2225
+ websocket._closeTimer = setTimeout(
2226
+ websocket._socket.destroy.bind(websocket._socket),
2227
+ websocket._closeTimeout
2228
+ );
2229
+ }
2230
+ function socketOnClose() {
2231
+ let websocket = this[kWebSocket];
2232
+ if (this.removeListener("close", socketOnClose), this.removeListener("data", socketOnData), this.removeListener("end", socketOnEnd), websocket._readyState = WebSocket.CLOSING, !this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
2233
+ let chunk = this.read(this._readableState.length);
2234
+ websocket._receiver.write(chunk);
2235
+ }
2236
+ websocket._receiver.end(), this[kWebSocket] = void 0, clearTimeout(websocket._closeTimer), websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ? websocket.emitClose() : (websocket._receiver.on("error", receiverOnFinish), websocket._receiver.on("finish", receiverOnFinish));
2237
+ }
2238
+ function socketOnData(chunk) {
2239
+ this[kWebSocket]._receiver.write(chunk) || this.pause();
2240
+ }
2241
+ function socketOnEnd() {
2242
+ let websocket = this[kWebSocket];
2243
+ websocket._readyState = WebSocket.CLOSING, websocket._receiver.end(), this.end();
2244
+ }
2245
+ function socketOnError() {
2246
+ let websocket = this[kWebSocket];
2247
+ this.removeListener("error", socketOnError), this.on("error", NOOP), websocket && (websocket._readyState = WebSocket.CLOSING, this.destroy());
2248
+ }
2249
+ }
2250
+ });
2251
+
2252
+ // node_modules/ws/lib/stream.js
2253
+ var require_stream = __commonJS({
2254
+ "node_modules/ws/lib/stream.js"(exports, module) {
2255
+ "use strict";
2256
+ var WebSocket = require_websocket(), { Duplex } = __require("stream");
2257
+ function emitClose(stream) {
2258
+ stream.emit("close");
2259
+ }
2260
+ function duplexOnEnd() {
2261
+ !this.destroyed && this._writableState.finished && this.destroy();
2262
+ }
2263
+ function duplexOnError(err) {
2264
+ this.removeListener("error", duplexOnError), this.destroy(), this.listenerCount("error") === 0 && this.emit("error", err);
2265
+ }
2266
+ function createWebSocketStream(ws, options) {
2267
+ let terminateOnDestroy = !0, duplex = new Duplex({
2268
+ ...options,
2269
+ autoDestroy: !1,
2270
+ emitClose: !1,
2271
+ objectMode: !1,
2272
+ writableObjectMode: !1
2273
+ });
2274
+ return ws.on("message", function(msg, isBinary) {
2275
+ let data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
2276
+ duplex.push(data) || ws.pause();
2277
+ }), ws.once("error", function(err) {
2278
+ duplex.destroyed || (terminateOnDestroy = !1, duplex.destroy(err));
2279
+ }), ws.once("close", function() {
2280
+ duplex.destroyed || duplex.push(null);
2281
+ }), duplex._destroy = function(err, callback) {
2282
+ if (ws.readyState === ws.CLOSED) {
2283
+ callback(err), process.nextTick(emitClose, duplex);
2284
+ return;
2285
+ }
2286
+ let called = !1;
2287
+ ws.once("error", function(err2) {
2288
+ called = !0, callback(err2);
2289
+ }), ws.once("close", function() {
2290
+ called || callback(err), process.nextTick(emitClose, duplex);
2291
+ }), terminateOnDestroy && ws.terminate();
2292
+ }, duplex._final = function(callback) {
2293
+ if (ws.readyState === ws.CONNECTING) {
2294
+ ws.once("open", function() {
2295
+ duplex._final(callback);
2296
+ });
2297
+ return;
2298
+ }
2299
+ ws._socket !== null && (ws._socket._writableState.finished ? (callback(), duplex._readableState.endEmitted && duplex.destroy()) : (ws._socket.once("finish", function() {
2300
+ callback();
2301
+ }), ws.close()));
2302
+ }, duplex._read = function() {
2303
+ ws.isPaused && ws.resume();
2304
+ }, duplex._write = function(chunk, encoding, callback) {
2305
+ if (ws.readyState === ws.CONNECTING) {
2306
+ ws.once("open", function() {
2307
+ duplex._write(chunk, encoding, callback);
2308
+ });
2309
+ return;
2310
+ }
2311
+ ws.send(chunk, callback);
2312
+ }, duplex.on("end", duplexOnEnd), duplex.on("error", duplexOnError), duplex;
2313
+ }
2314
+ module.exports = createWebSocketStream;
2315
+ }
2316
+ });
2317
+
2318
+ // node_modules/ws/lib/subprotocol.js
2319
+ var require_subprotocol = __commonJS({
2320
+ "node_modules/ws/lib/subprotocol.js"(exports, module) {
2321
+ "use strict";
2322
+ var { tokenChars } = require_validation();
2323
+ function parse(header) {
2324
+ let protocols = /* @__PURE__ */ new Set(), start = -1, end = -1, i = 0;
2325
+ for (i; i < header.length; i++) {
2326
+ let code = header.charCodeAt(i);
2327
+ if (end === -1 && tokenChars[code] === 1)
2328
+ start === -1 && (start = i);
2329
+ else if (i !== 0 && (code === 32 || code === 9))
2330
+ end === -1 && start !== -1 && (end = i);
2331
+ else if (code === 44) {
2332
+ if (start === -1)
2333
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2334
+ end === -1 && (end = i);
2335
+ let protocol2 = header.slice(start, end);
2336
+ if (protocols.has(protocol2))
2337
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
2338
+ protocols.add(protocol2), start = end = -1;
2339
+ } else
2340
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2341
+ }
2342
+ if (start === -1 || end !== -1)
2343
+ throw new SyntaxError("Unexpected end of input");
2344
+ let protocol = header.slice(start, i);
2345
+ if (protocols.has(protocol))
2346
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
2347
+ return protocols.add(protocol), protocols;
2348
+ }
2349
+ module.exports = { parse };
2350
+ }
2351
+ });
2352
+
2353
+ // node_modules/ws/lib/websocket-server.js
2354
+ var require_websocket_server = __commonJS({
2355
+ "node_modules/ws/lib/websocket-server.js"(exports, module) {
2356
+ "use strict";
2357
+ var EventEmitter = __require("events"), http = __require("http"), { Duplex } = __require("stream"), { createHash } = __require("crypto"), extension = require_extension(), PerMessageDeflate = require_permessage_deflate(), subprotocol = require_subprotocol(), WebSocket = require_websocket(), { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants(), keyRegex = /^[+/0-9A-Za-z]{22}==$/, RUNNING = 0, CLOSING = 1, CLOSED = 2, WebSocketServer = class extends EventEmitter {
2358
+ /**
2359
+ * Create a `WebSocketServer` instance.
2360
+ *
2361
+ * @param {Object} options Configuration options
2362
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
2363
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2364
+ * multiple times in the same tick
2365
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
2366
+ * automatically send a pong in response to a ping
2367
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
2368
+ * pending connections
2369
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
2370
+ * track clients
2371
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
2372
+ * wait for the closing handshake to finish after `websocket.close()` is
2373
+ * called
2374
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
2375
+ * @param {String} [options.host] The hostname where to bind the server
2376
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
2377
+ * buffered data chunks
2378
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
2379
+ * fragments
2380
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
2381
+ * size
2382
+ * @param {Boolean} [options.noServer=false] Enable no server mode
2383
+ * @param {String} [options.path] Accept only connections matching this path
2384
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
2385
+ * permessage-deflate
2386
+ * @param {Number} [options.port] The port where to bind the server
2387
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
2388
+ * server to use
2389
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2390
+ * not to skip UTF-8 validation for text and close messages
2391
+ * @param {Function} [options.verifyClient] A hook to reject connections
2392
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
2393
+ * class to use. It must be the `WebSocket` class or class that extends it
2394
+ * @param {Function} [callback] A listener for the `listening` event
2395
+ */
2396
+ constructor(options, callback) {
2397
+ if (super(), options = {
2398
+ allowSynchronousEvents: !0,
2399
+ autoPong: !0,
2400
+ maxBufferedChunks: 256 * 1024,
2401
+ maxFragments: 16 * 1024,
2402
+ maxPayload: 100 * 1024 * 1024,
2403
+ skipUTF8Validation: !1,
2404
+ perMessageDeflate: !1,
2405
+ handleProtocols: null,
2406
+ clientTracking: !0,
2407
+ closeTimeout: CLOSE_TIMEOUT,
2408
+ verifyClient: null,
2409
+ noServer: !1,
2410
+ backlog: null,
2411
+ // use default (511 as implemented in net.js)
2412
+ server: null,
2413
+ host: null,
2414
+ path: null,
2415
+ port: null,
2416
+ WebSocket,
2417
+ ...options
2418
+ }, options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer)
2419
+ throw new TypeError(
2420
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
2421
+ );
2422
+ if (options.port != null ? (this._server = http.createServer((req, res) => {
2423
+ let body = http.STATUS_CODES[426];
2424
+ res.writeHead(426, {
2425
+ "Content-Length": body.length,
2426
+ "Content-Type": "text/plain"
2427
+ }), res.end(body);
2428
+ }), this._server.listen(
2429
+ options.port,
2430
+ options.host,
2431
+ options.backlog,
2432
+ callback
2433
+ )) : options.server && (this._server = options.server), this._server) {
2434
+ let emitConnection = this.emit.bind(this, "connection");
2435
+ this._removeListeners = addListeners(this._server, {
2436
+ listening: this.emit.bind(this, "listening"),
2437
+ error: this.emit.bind(this, "error"),
2438
+ upgrade: (req, socket, head) => {
2439
+ this.handleUpgrade(req, socket, head, emitConnection);
2440
+ }
2441
+ });
2442
+ }
2443
+ options.perMessageDeflate === !0 && (options.perMessageDeflate = {}), options.clientTracking && (this.clients = /* @__PURE__ */ new Set(), this._shouldEmitClose = !1), this.options = options, this._state = RUNNING;
2444
+ }
2445
+ /**
2446
+ * Returns the bound address, the address family name, and port of the server
2447
+ * as reported by the operating system if listening on an IP socket.
2448
+ * If the server is listening on a pipe or UNIX domain socket, the name is
2449
+ * returned as a string.
2450
+ *
2451
+ * @return {(Object|String|null)} The address of the server
2452
+ * @public
2453
+ */
2454
+ address() {
2455
+ if (this.options.noServer)
2456
+ throw new Error('The server is operating in "noServer" mode');
2457
+ return this._server ? this._server.address() : null;
2458
+ }
2459
+ /**
2460
+ * Stop the server from accepting new connections and emit the `'close'` event
2461
+ * when all existing connections are closed.
2462
+ *
2463
+ * @param {Function} [cb] A one-time listener for the `'close'` event
2464
+ * @public
2465
+ */
2466
+ close(cb) {
2467
+ if (this._state === CLOSED) {
2468
+ cb && this.once("close", () => {
2469
+ cb(new Error("The server is not running"));
2470
+ }), process.nextTick(emitClose, this);
2471
+ return;
2472
+ }
2473
+ if (cb && this.once("close", cb), this._state !== CLOSING)
2474
+ if (this._state = CLOSING, this.options.noServer || this.options.server)
2475
+ this._server && (this._removeListeners(), this._removeListeners = this._server = null), this.clients ? this.clients.size ? this._shouldEmitClose = !0 : process.nextTick(emitClose, this) : process.nextTick(emitClose, this);
2476
+ else {
2477
+ let server = this._server;
2478
+ this._removeListeners(), this._removeListeners = this._server = null, server.close(() => {
2479
+ emitClose(this);
2480
+ });
2481
+ }
2482
+ }
2483
+ /**
2484
+ * See if a given request should be handled by this server instance.
2485
+ *
2486
+ * @param {http.IncomingMessage} req Request object to inspect
2487
+ * @return {Boolean} `true` if the request is valid, else `false`
2488
+ * @public
2489
+ */
2490
+ shouldHandle(req) {
2491
+ if (this.options.path) {
2492
+ let index = req.url.indexOf("?");
2493
+ if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return !1;
2494
+ }
2495
+ return !0;
2496
+ }
2497
+ /**
2498
+ * Handle a HTTP Upgrade request.
2499
+ *
2500
+ * @param {http.IncomingMessage} req The request object
2501
+ * @param {Duplex} socket The network socket between the server and client
2502
+ * @param {Buffer} head The first packet of the upgraded stream
2503
+ * @param {Function} cb Callback
2504
+ * @public
2505
+ */
2506
+ handleUpgrade(req, socket, head, cb) {
2507
+ socket.on("error", socketOnError);
2508
+ let key = req.headers["sec-websocket-key"], upgrade = req.headers.upgrade, version = +req.headers["sec-websocket-version"];
2509
+ if (req.method !== "GET") {
2510
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
2511
+ return;
2512
+ }
2513
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2514
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
2515
+ return;
2516
+ }
2517
+ if (key === void 0 || !keyRegex.test(key)) {
2518
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
2519
+ return;
2520
+ }
2521
+ if (version !== 13 && version !== 8) {
2522
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", {
2523
+ "Sec-WebSocket-Version": "13, 8"
2524
+ });
2525
+ return;
2526
+ }
2527
+ if (!this.shouldHandle(req)) {
2528
+ abortHandshake(socket, 400);
2529
+ return;
2530
+ }
2531
+ let secWebSocketProtocol = req.headers["sec-websocket-protocol"], protocols = /* @__PURE__ */ new Set();
2532
+ if (secWebSocketProtocol !== void 0)
2533
+ try {
2534
+ protocols = subprotocol.parse(secWebSocketProtocol);
2535
+ } catch {
2536
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
2537
+ return;
2538
+ }
2539
+ let secWebSocketExtensions = req.headers["sec-websocket-extensions"], extensions = {};
2540
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
2541
+ let perMessageDeflate = new PerMessageDeflate({
2542
+ ...this.options.perMessageDeflate,
2543
+ isServer: !0,
2544
+ maxPayload: this.options.maxPayload
2545
+ });
2546
+ try {
2547
+ let offers = extension.parse(secWebSocketExtensions);
2548
+ offers[PerMessageDeflate.extensionName] && (perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]), extensions[PerMessageDeflate.extensionName] = perMessageDeflate);
2549
+ } catch {
2550
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
2551
+ return;
2552
+ }
2553
+ }
2554
+ if (this.options.verifyClient) {
2555
+ let info = {
2556
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
2557
+ secure: !!(req.socket.authorized || req.socket.encrypted),
2558
+ req
2559
+ };
2560
+ if (this.options.verifyClient.length === 2) {
2561
+ this.options.verifyClient(info, (verified, code, message, headers) => {
2562
+ if (!verified)
2563
+ return abortHandshake(socket, code || 401, message, headers);
2564
+ this.completeUpgrade(
2565
+ extensions,
2566
+ key,
2567
+ protocols,
2568
+ req,
2569
+ socket,
2570
+ head,
2571
+ cb
2572
+ );
2573
+ });
2574
+ return;
2575
+ }
2576
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
2577
+ }
2578
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
2579
+ }
2580
+ /**
2581
+ * Upgrade the connection to WebSocket.
2582
+ *
2583
+ * @param {Object} extensions The accepted extensions
2584
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
2585
+ * @param {Set} protocols The subprotocols
2586
+ * @param {http.IncomingMessage} req The request object
2587
+ * @param {Duplex} socket The network socket between the server and client
2588
+ * @param {Buffer} head The first packet of the upgraded stream
2589
+ * @param {Function} cb Callback
2590
+ * @throws {Error} If called more than once with the same socket
2591
+ * @private
2592
+ */
2593
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
2594
+ if (!socket.readable || !socket.writable) return socket.destroy();
2595
+ if (socket[kWebSocket])
2596
+ throw new Error(
2597
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
2598
+ );
2599
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
2600
+ let headers = [
2601
+ "HTTP/1.1 101 Switching Protocols",
2602
+ "Upgrade: websocket",
2603
+ "Connection: Upgrade",
2604
+ `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
2605
+ ], ws = new this.options.WebSocket(null, void 0, this.options);
2606
+ if (protocols.size) {
2607
+ let protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
2608
+ protocol && (headers.push(`Sec-WebSocket-Protocol: ${protocol}`), ws._protocol = protocol);
2609
+ }
2610
+ if (extensions[PerMessageDeflate.extensionName]) {
2611
+ let params = extensions[PerMessageDeflate.extensionName].params, value = extension.format({
2612
+ [PerMessageDeflate.extensionName]: [params]
2613
+ });
2614
+ headers.push(`Sec-WebSocket-Extensions: ${value}`), ws._extensions = extensions;
2615
+ }
2616
+ this.emit("headers", headers, req), socket.write(headers.concat(`\r
2617
+ `).join(`\r
2618
+ `)), socket.removeListener("error", socketOnError), ws.setSocket(socket, head, {
2619
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
2620
+ maxBufferedChunks: this.options.maxBufferedChunks,
2621
+ maxFragments: this.options.maxFragments,
2622
+ maxPayload: this.options.maxPayload,
2623
+ skipUTF8Validation: this.options.skipUTF8Validation
2624
+ }), this.clients && (this.clients.add(ws), ws.on("close", () => {
2625
+ this.clients.delete(ws), this._shouldEmitClose && !this.clients.size && process.nextTick(emitClose, this);
2626
+ })), cb(ws, req);
2627
+ }
2628
+ };
2629
+ module.exports = WebSocketServer;
2630
+ function addListeners(server, map) {
2631
+ for (let event of Object.keys(map)) server.on(event, map[event]);
2632
+ return function() {
2633
+ for (let event of Object.keys(map))
2634
+ server.removeListener(event, map[event]);
2635
+ };
2636
+ }
2637
+ function emitClose(server) {
2638
+ server._state = CLOSED, server.emit("close");
2639
+ }
2640
+ function socketOnError() {
2641
+ this.destroy();
2642
+ }
2643
+ function abortHandshake(socket, code, message, headers) {
2644
+ message = message || http.STATUS_CODES[code], headers = {
2645
+ Connection: "close",
2646
+ "Content-Type": "text/html",
2647
+ "Content-Length": Buffer.byteLength(message),
2648
+ ...headers
2649
+ }, socket.once("finish", socket.destroy), socket.end(
2650
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
2651
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r
2652
+ `) + `\r
2653
+ \r
2654
+ ` + message
2655
+ );
2656
+ }
2657
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
2658
+ if (server.listenerCount("wsClientError")) {
2659
+ let err = new Error(message);
2660
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError), server.emit("wsClientError", err, socket, req);
2661
+ } else
2662
+ abortHandshake(socket, code, message, headers);
2663
+ }
2664
+ }
2665
+ });
2666
+
2667
+ export {
2668
+ require_permessage_deflate,
2669
+ require_receiver,
2670
+ require_sender,
2671
+ require_extension,
2672
+ require_websocket,
2673
+ require_stream,
2674
+ require_subprotocol,
2675
+ require_websocket_server
2676
+ };