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