agents 0.1.4 → 0.1.6

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