@carboncode/cli 0.1.0

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