@gradio/client 1.19.0 → 2.0.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3076 +0,0 @@
1
- import require$$0 from "stream";
2
- import require$$0$2 from "zlib";
3
- import require$$0$1 from "fs";
4
- import require$$1$1 from "path";
5
- import require$$2 from "os";
6
- import require$$0$3 from "buffer";
7
- import require$$3 from "net";
8
- import require$$4 from "tls";
9
- import require$$5 from "crypto";
10
- import require$$0$4 from "events";
11
- import require$$1$2 from "https";
12
- import require$$2$1 from "http";
13
- import require$$7 from "url";
14
- function getDefaultExportFromCjs(x) {
15
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
16
- }
17
- function getAugmentedNamespace(n) {
18
- if (n.__esModule) return n;
19
- var f = n.default;
20
- if (typeof f == "function") {
21
- var a = function a2() {
22
- if (this instanceof a2) {
23
- return Reflect.construct(f, arguments, this.constructor);
24
- }
25
- return f.apply(this, arguments);
26
- };
27
- a.prototype = f.prototype;
28
- } else a = {};
29
- Object.defineProperty(a, "__esModule", { value: true });
30
- Object.keys(n).forEach(function(k) {
31
- var d = Object.getOwnPropertyDescriptor(n, k);
32
- Object.defineProperty(a, k, d.get ? d : {
33
- enumerable: true,
34
- get: function() {
35
- return n[k];
36
- }
37
- });
38
- });
39
- return a;
40
- }
41
- const { Duplex } = require$$0;
42
- var bufferUtil$1 = { exports: {} };
43
- var constants = {
44
- BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
45
- EMPTY_BUFFER: Buffer.alloc(0),
46
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
47
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
48
- kListener: Symbol("kListener"),
49
- kStatusCode: Symbol("status-code"),
50
- kWebSocket: Symbol("websocket"),
51
- NOOP: () => {
52
- }
53
- };
54
- var bufferutil = { exports: {} };
55
- var nodeGypBuild$1 = { exports: {} };
56
- function commonjsRequire(path) {
57
- throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
58
- }
59
- var nodeGypBuild;
60
- var hasRequiredNodeGypBuild$1;
61
- function requireNodeGypBuild$1() {
62
- if (hasRequiredNodeGypBuild$1) return nodeGypBuild;
63
- hasRequiredNodeGypBuild$1 = 1;
64
- var fs = require$$0$1;
65
- var path = require$$1$1;
66
- var os = require$$2;
67
- var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : commonjsRequire;
68
- var vars = process.config && process.config.variables || {};
69
- var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
70
- var abi = process.versions.modules;
71
- var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
72
- var arch = process.env.npm_config_arch || os.arch();
73
- var platform = process.env.npm_config_platform || os.platform();
74
- var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc");
75
- var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
76
- var uv = (process.versions.uv || "").split(".")[0];
77
- nodeGypBuild = load;
78
- function load(dir) {
79
- return runtimeRequire(load.resolve(dir));
80
- }
81
- load.resolve = load.path = function(dir) {
82
- dir = path.resolve(dir || ".");
83
- try {
84
- var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
85
- if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
86
- } catch (err) {
87
- }
88
- if (!prebuildsOnly) {
89
- var release = getFirst(path.join(dir, "build/Release"), matchBuild);
90
- if (release) return release;
91
- var debug = getFirst(path.join(dir, "build/Debug"), matchBuild);
92
- if (debug) return debug;
93
- }
94
- var prebuild = resolve(dir);
95
- if (prebuild) return prebuild;
96
- var nearby = resolve(path.dirname(process.execPath));
97
- if (nearby) return nearby;
98
- var target = [
99
- "platform=" + platform,
100
- "arch=" + arch,
101
- "runtime=" + runtime,
102
- "abi=" + abi,
103
- "uv=" + uv,
104
- armv ? "armv=" + armv : "",
105
- "libc=" + libc,
106
- "node=" + process.versions.node,
107
- process.versions.electron ? "electron=" + process.versions.electron : "",
108
- typeof __webpack_require__ === "function" ? "webpack=true" : ""
109
- // eslint-disable-line
110
- ].filter(Boolean).join(" ");
111
- throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n");
112
- function resolve(dir2) {
113
- var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple);
114
- var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
115
- if (!tuple) return;
116
- var prebuilds = path.join(dir2, "prebuilds", tuple.name);
117
- var parsed = readdirSync(prebuilds).map(parseTags);
118
- var candidates = parsed.filter(matchTags(runtime, abi));
119
- var winner = candidates.sort(compareTags(runtime))[0];
120
- if (winner) return path.join(prebuilds, winner.file);
121
- }
122
- };
123
- function readdirSync(dir) {
124
- try {
125
- return fs.readdirSync(dir);
126
- } catch (err) {
127
- return [];
128
- }
129
- }
130
- function getFirst(dir, filter) {
131
- var files = readdirSync(dir).filter(filter);
132
- return files[0] && path.join(dir, files[0]);
133
- }
134
- function matchBuild(name) {
135
- return /\.node$/.test(name);
136
- }
137
- function parseTuple(name) {
138
- var arr = name.split("-");
139
- if (arr.length !== 2) return;
140
- var platform2 = arr[0];
141
- var architectures = arr[1].split("+");
142
- if (!platform2) return;
143
- if (!architectures.length) return;
144
- if (!architectures.every(Boolean)) return;
145
- return { name, platform: platform2, architectures };
146
- }
147
- function matchTuple(platform2, arch2) {
148
- return function(tuple) {
149
- if (tuple == null) return false;
150
- if (tuple.platform !== platform2) return false;
151
- return tuple.architectures.includes(arch2);
152
- };
153
- }
154
- function compareTuples(a, b) {
155
- return a.architectures.length - b.architectures.length;
156
- }
157
- function parseTags(file) {
158
- var arr = file.split(".");
159
- var extension2 = arr.pop();
160
- var tags = { file, specificity: 0 };
161
- if (extension2 !== "node") return;
162
- for (var i = 0; i < arr.length; i++) {
163
- var tag = arr[i];
164
- if (tag === "node" || tag === "electron" || tag === "node-webkit") {
165
- tags.runtime = tag;
166
- } else if (tag === "napi") {
167
- tags.napi = true;
168
- } else if (tag.slice(0, 3) === "abi") {
169
- tags.abi = tag.slice(3);
170
- } else if (tag.slice(0, 2) === "uv") {
171
- tags.uv = tag.slice(2);
172
- } else if (tag.slice(0, 4) === "armv") {
173
- tags.armv = tag.slice(4);
174
- } else if (tag === "glibc" || tag === "musl") {
175
- tags.libc = tag;
176
- } else {
177
- continue;
178
- }
179
- tags.specificity++;
180
- }
181
- return tags;
182
- }
183
- function matchTags(runtime2, abi2) {
184
- return function(tags) {
185
- if (tags == null) return false;
186
- if (tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
187
- if (tags.abi !== abi2 && !tags.napi) return false;
188
- if (tags.uv && tags.uv !== uv) return false;
189
- if (tags.armv && tags.armv !== armv) return false;
190
- if (tags.libc && tags.libc !== libc) return false;
191
- return true;
192
- };
193
- }
194
- function runtimeAgnostic(tags) {
195
- return tags.runtime === "node" && tags.napi;
196
- }
197
- function compareTags(runtime2) {
198
- return function(a, b) {
199
- if (a.runtime !== b.runtime) {
200
- return a.runtime === runtime2 ? -1 : 1;
201
- } else if (a.abi !== b.abi) {
202
- return a.abi ? -1 : 1;
203
- } else if (a.specificity !== b.specificity) {
204
- return a.specificity > b.specificity ? -1 : 1;
205
- } else {
206
- return 0;
207
- }
208
- };
209
- }
210
- function isNwjs() {
211
- return !!(process.versions && process.versions.nw);
212
- }
213
- function isElectron() {
214
- if (process.versions && process.versions.electron) return true;
215
- if (process.env.ELECTRON_RUN_AS_NODE) return true;
216
- return typeof window !== "undefined" && window.process && window.process.type === "renderer";
217
- }
218
- function isAlpine(platform2) {
219
- return platform2 === "linux" && fs.existsSync("/etc/alpine-release");
220
- }
221
- load.parseTags = parseTags;
222
- load.matchTags = matchTags;
223
- load.compareTags = compareTags;
224
- load.parseTuple = parseTuple;
225
- load.matchTuple = matchTuple;
226
- load.compareTuples = compareTuples;
227
- return nodeGypBuild;
228
- }
229
- var hasRequiredNodeGypBuild;
230
- function requireNodeGypBuild() {
231
- if (hasRequiredNodeGypBuild) return nodeGypBuild$1.exports;
232
- hasRequiredNodeGypBuild = 1;
233
- if (typeof process.addon === "function") {
234
- nodeGypBuild$1.exports = process.addon.bind(process);
235
- } else {
236
- nodeGypBuild$1.exports = requireNodeGypBuild$1();
237
- }
238
- return nodeGypBuild$1.exports;
239
- }
240
- var fallback;
241
- var hasRequiredFallback;
242
- function requireFallback() {
243
- if (hasRequiredFallback) return fallback;
244
- hasRequiredFallback = 1;
245
- const mask2 = (source, mask3, output, offset, length) => {
246
- for (var i = 0; i < length; i++) {
247
- output[offset + i] = source[i] ^ mask3[i & 3];
248
- }
249
- };
250
- const unmask2 = (buffer, mask3) => {
251
- const length = buffer.length;
252
- for (var i = 0; i < length; i++) {
253
- buffer[i] ^= mask3[i & 3];
254
- }
255
- };
256
- fallback = { mask: mask2, unmask: unmask2 };
257
- return fallback;
258
- }
259
- var hasRequiredBufferutil;
260
- function requireBufferutil() {
261
- if (hasRequiredBufferutil) return bufferutil.exports;
262
- hasRequiredBufferutil = 1;
263
- try {
264
- bufferutil.exports = requireNodeGypBuild()(__dirname);
265
- } catch (e) {
266
- bufferutil.exports = requireFallback();
267
- }
268
- return bufferutil.exports;
269
- }
270
- var unmask$1;
271
- var mask;
272
- const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
273
- const FastBuffer$2 = Buffer[Symbol.species];
274
- function concat$1(list, totalLength) {
275
- if (list.length === 0) return EMPTY_BUFFER$3;
276
- if (list.length === 1) return list[0];
277
- const target = Buffer.allocUnsafe(totalLength);
278
- let offset = 0;
279
- for (let i = 0; i < list.length; i++) {
280
- const buf = list[i];
281
- target.set(buf, offset);
282
- offset += buf.length;
283
- }
284
- if (offset < totalLength) {
285
- return new FastBuffer$2(target.buffer, target.byteOffset, offset);
286
- }
287
- return target;
288
- }
289
- function _mask(source, mask2, output, offset, length) {
290
- for (let i = 0; i < length; i++) {
291
- output[offset + i] = source[i] ^ mask2[i & 3];
292
- }
293
- }
294
- function _unmask(buffer, mask2) {
295
- for (let i = 0; i < buffer.length; i++) {
296
- buffer[i] ^= mask2[i & 3];
297
- }
298
- }
299
- function toArrayBuffer$1(buf) {
300
- if (buf.length === buf.buffer.byteLength) {
301
- return buf.buffer;
302
- }
303
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
304
- }
305
- function toBuffer$2(data) {
306
- toBuffer$2.readOnly = true;
307
- if (Buffer.isBuffer(data)) return data;
308
- let buf;
309
- if (data instanceof ArrayBuffer) {
310
- buf = new FastBuffer$2(data);
311
- } else if (ArrayBuffer.isView(data)) {
312
- buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength);
313
- } else {
314
- buf = Buffer.from(data);
315
- toBuffer$2.readOnly = false;
316
- }
317
- return buf;
318
- }
319
- bufferUtil$1.exports = {
320
- concat: concat$1,
321
- mask: _mask,
322
- toArrayBuffer: toArrayBuffer$1,
323
- toBuffer: toBuffer$2,
324
- unmask: _unmask
325
- };
326
- if (!process.env.WS_NO_BUFFER_UTIL) {
327
- try {
328
- const bufferUtil2 = requireBufferutil();
329
- mask = bufferUtil$1.exports.mask = function(source, mask2, output, offset, length) {
330
- if (length < 48) _mask(source, mask2, output, offset, length);
331
- else bufferUtil2.mask(source, mask2, output, offset, length);
332
- };
333
- unmask$1 = bufferUtil$1.exports.unmask = function(buffer, mask2) {
334
- if (buffer.length < 32) _unmask(buffer, mask2);
335
- else bufferUtil2.unmask(buffer, mask2);
336
- };
337
- } catch (e) {
338
- }
339
- }
340
- var bufferUtilExports = bufferUtil$1.exports;
341
- const kDone = Symbol("kDone");
342
- const kRun = Symbol("kRun");
343
- let Limiter$1 = class Limiter {
344
- /**
345
- * Creates a new `Limiter`.
346
- *
347
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
348
- * to run concurrently
349
- */
350
- constructor(concurrency) {
351
- this[kDone] = () => {
352
- this.pending--;
353
- this[kRun]();
354
- };
355
- this.concurrency = concurrency || Infinity;
356
- this.jobs = [];
357
- this.pending = 0;
358
- }
359
- /**
360
- * Adds a job to the queue.
361
- *
362
- * @param {Function} job The job to run
363
- * @public
364
- */
365
- add(job) {
366
- this.jobs.push(job);
367
- this[kRun]();
368
- }
369
- /**
370
- * Removes a job from the queue and runs it if possible.
371
- *
372
- * @private
373
- */
374
- [kRun]() {
375
- if (this.pending === this.concurrency) return;
376
- if (this.jobs.length) {
377
- const job = this.jobs.shift();
378
- this.pending++;
379
- job(this[kDone]);
380
- }
381
- }
382
- };
383
- var limiter = Limiter$1;
384
- const zlib = require$$0$2;
385
- const bufferUtil = bufferUtilExports;
386
- const Limiter2 = limiter;
387
- const { kStatusCode: kStatusCode$2 } = constants;
388
- const FastBuffer$1 = Buffer[Symbol.species];
389
- const TRAILER = Buffer.from([0, 0, 255, 255]);
390
- const kPerMessageDeflate = Symbol("permessage-deflate");
391
- const kTotalLength = Symbol("total-length");
392
- const kCallback = Symbol("callback");
393
- const kBuffers = Symbol("buffers");
394
- const kError$1 = Symbol("error");
395
- let zlibLimiter;
396
- let PerMessageDeflate$3 = class PerMessageDeflate {
397
- /**
398
- * Creates a PerMessageDeflate instance.
399
- *
400
- * @param {Object} [options] Configuration options
401
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
402
- * for, or request, a custom client window size
403
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
404
- * acknowledge disabling of client context takeover
405
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
406
- * calls to zlib
407
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
408
- * use of a custom server window size
409
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
410
- * disabling of server context takeover
411
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
412
- * messages should not be compressed if context takeover is disabled
413
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
414
- * deflate
415
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
416
- * inflate
417
- * @param {Boolean} [isServer=false] Create the instance in either server or
418
- * client mode
419
- * @param {Number} [maxPayload=0] The maximum allowed message length
420
- */
421
- constructor(options, isServer, maxPayload) {
422
- this._maxPayload = maxPayload | 0;
423
- this._options = options || {};
424
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
425
- this._isServer = !!isServer;
426
- this._deflate = null;
427
- this._inflate = null;
428
- this.params = null;
429
- if (!zlibLimiter) {
430
- const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
431
- zlibLimiter = new Limiter2(concurrency);
432
- }
433
- }
434
- /**
435
- * @type {String}
436
- */
437
- static get extensionName() {
438
- return "permessage-deflate";
439
- }
440
- /**
441
- * Create an extension negotiation offer.
442
- *
443
- * @return {Object} Extension parameters
444
- * @public
445
- */
446
- offer() {
447
- const params = {};
448
- if (this._options.serverNoContextTakeover) {
449
- params.server_no_context_takeover = true;
450
- }
451
- if (this._options.clientNoContextTakeover) {
452
- params.client_no_context_takeover = true;
453
- }
454
- if (this._options.serverMaxWindowBits) {
455
- params.server_max_window_bits = this._options.serverMaxWindowBits;
456
- }
457
- if (this._options.clientMaxWindowBits) {
458
- params.client_max_window_bits = this._options.clientMaxWindowBits;
459
- } else if (this._options.clientMaxWindowBits == null) {
460
- params.client_max_window_bits = true;
461
- }
462
- return params;
463
- }
464
- /**
465
- * Accept an extension negotiation offer/response.
466
- *
467
- * @param {Array} configurations The extension negotiation offers/reponse
468
- * @return {Object} Accepted configuration
469
- * @public
470
- */
471
- accept(configurations) {
472
- configurations = this.normalizeParams(configurations);
473
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
474
- return this.params;
475
- }
476
- /**
477
- * Releases all resources used by the extension.
478
- *
479
- * @public
480
- */
481
- cleanup() {
482
- if (this._inflate) {
483
- this._inflate.close();
484
- this._inflate = null;
485
- }
486
- if (this._deflate) {
487
- const callback = this._deflate[kCallback];
488
- this._deflate.close();
489
- this._deflate = null;
490
- if (callback) {
491
- callback(
492
- new Error(
493
- "The deflate stream was closed while data was being processed"
494
- )
495
- );
496
- }
497
- }
498
- }
499
- /**
500
- * Accept an extension negotiation offer.
501
- *
502
- * @param {Array} offers The extension negotiation offers
503
- * @return {Object} Accepted configuration
504
- * @private
505
- */
506
- acceptAsServer(offers) {
507
- const opts = this._options;
508
- const accepted = offers.find((params) => {
509
- 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) {
510
- return false;
511
- }
512
- return true;
513
- });
514
- if (!accepted) {
515
- throw new Error("None of the extension offers can be accepted");
516
- }
517
- if (opts.serverNoContextTakeover) {
518
- accepted.server_no_context_takeover = true;
519
- }
520
- if (opts.clientNoContextTakeover) {
521
- accepted.client_no_context_takeover = true;
522
- }
523
- if (typeof opts.serverMaxWindowBits === "number") {
524
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
525
- }
526
- if (typeof opts.clientMaxWindowBits === "number") {
527
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
528
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
529
- delete accepted.client_max_window_bits;
530
- }
531
- return accepted;
532
- }
533
- /**
534
- * Accept the extension negotiation response.
535
- *
536
- * @param {Array} response The extension negotiation response
537
- * @return {Object} Accepted configuration
538
- * @private
539
- */
540
- acceptAsClient(response) {
541
- const params = response[0];
542
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
543
- throw new Error('Unexpected parameter "client_no_context_takeover"');
544
- }
545
- if (!params.client_max_window_bits) {
546
- if (typeof this._options.clientMaxWindowBits === "number") {
547
- params.client_max_window_bits = this._options.clientMaxWindowBits;
548
- }
549
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
550
- throw new Error(
551
- 'Unexpected or invalid parameter "client_max_window_bits"'
552
- );
553
- }
554
- return params;
555
- }
556
- /**
557
- * Normalize parameters.
558
- *
559
- * @param {Array} configurations The extension negotiation offers/reponse
560
- * @return {Array} The offers/response with normalized parameters
561
- * @private
562
- */
563
- normalizeParams(configurations) {
564
- configurations.forEach((params) => {
565
- Object.keys(params).forEach((key) => {
566
- let value = params[key];
567
- if (value.length > 1) {
568
- throw new Error(`Parameter "${key}" must have only a single value`);
569
- }
570
- value = value[0];
571
- if (key === "client_max_window_bits") {
572
- if (value !== true) {
573
- const num = +value;
574
- if (!Number.isInteger(num) || num < 8 || num > 15) {
575
- throw new TypeError(
576
- `Invalid value for parameter "${key}": ${value}`
577
- );
578
- }
579
- value = num;
580
- } else if (!this._isServer) {
581
- throw new TypeError(
582
- `Invalid value for parameter "${key}": ${value}`
583
- );
584
- }
585
- } else if (key === "server_max_window_bits") {
586
- const num = +value;
587
- if (!Number.isInteger(num) || num < 8 || num > 15) {
588
- throw new TypeError(
589
- `Invalid value for parameter "${key}": ${value}`
590
- );
591
- }
592
- value = num;
593
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
594
- if (value !== true) {
595
- throw new TypeError(
596
- `Invalid value for parameter "${key}": ${value}`
597
- );
598
- }
599
- } else {
600
- throw new Error(`Unknown parameter "${key}"`);
601
- }
602
- params[key] = value;
603
- });
604
- });
605
- return configurations;
606
- }
607
- /**
608
- * Decompress data. Concurrency limited.
609
- *
610
- * @param {Buffer} data Compressed data
611
- * @param {Boolean} fin Specifies whether or not this is the last fragment
612
- * @param {Function} callback Callback
613
- * @public
614
- */
615
- decompress(data, fin, callback) {
616
- zlibLimiter.add((done) => {
617
- this._decompress(data, fin, (err, result) => {
618
- done();
619
- callback(err, result);
620
- });
621
- });
622
- }
623
- /**
624
- * Compress data. Concurrency limited.
625
- *
626
- * @param {(Buffer|String)} data Data to compress
627
- * @param {Boolean} fin Specifies whether or not this is the last fragment
628
- * @param {Function} callback Callback
629
- * @public
630
- */
631
- compress(data, fin, callback) {
632
- zlibLimiter.add((done) => {
633
- this._compress(data, fin, (err, result) => {
634
- done();
635
- callback(err, result);
636
- });
637
- });
638
- }
639
- /**
640
- * Decompress data.
641
- *
642
- * @param {Buffer} data Compressed data
643
- * @param {Boolean} fin Specifies whether or not this is the last fragment
644
- * @param {Function} callback Callback
645
- * @private
646
- */
647
- _decompress(data, fin, callback) {
648
- const endpoint = this._isServer ? "client" : "server";
649
- if (!this._inflate) {
650
- const key = `${endpoint}_max_window_bits`;
651
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
652
- this._inflate = zlib.createInflateRaw({
653
- ...this._options.zlibInflateOptions,
654
- windowBits
655
- });
656
- this._inflate[kPerMessageDeflate] = this;
657
- this._inflate[kTotalLength] = 0;
658
- this._inflate[kBuffers] = [];
659
- this._inflate.on("error", inflateOnError);
660
- this._inflate.on("data", inflateOnData);
661
- }
662
- this._inflate[kCallback] = callback;
663
- this._inflate.write(data);
664
- if (fin) this._inflate.write(TRAILER);
665
- this._inflate.flush(() => {
666
- const err = this._inflate[kError$1];
667
- if (err) {
668
- this._inflate.close();
669
- this._inflate = null;
670
- callback(err);
671
- return;
672
- }
673
- const data2 = bufferUtil.concat(
674
- this._inflate[kBuffers],
675
- this._inflate[kTotalLength]
676
- );
677
- if (this._inflate._readableState.endEmitted) {
678
- this._inflate.close();
679
- this._inflate = null;
680
- } else {
681
- this._inflate[kTotalLength] = 0;
682
- this._inflate[kBuffers] = [];
683
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
684
- this._inflate.reset();
685
- }
686
- }
687
- callback(null, data2);
688
- });
689
- }
690
- /**
691
- * Compress data.
692
- *
693
- * @param {(Buffer|String)} data Data to compress
694
- * @param {Boolean} fin Specifies whether or not this is the last fragment
695
- * @param {Function} callback Callback
696
- * @private
697
- */
698
- _compress(data, fin, callback) {
699
- const endpoint = this._isServer ? "server" : "client";
700
- if (!this._deflate) {
701
- const key = `${endpoint}_max_window_bits`;
702
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
703
- this._deflate = zlib.createDeflateRaw({
704
- ...this._options.zlibDeflateOptions,
705
- windowBits
706
- });
707
- this._deflate[kTotalLength] = 0;
708
- this._deflate[kBuffers] = [];
709
- this._deflate.on("data", deflateOnData);
710
- }
711
- this._deflate[kCallback] = callback;
712
- this._deflate.write(data);
713
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
714
- if (!this._deflate) {
715
- return;
716
- }
717
- let data2 = bufferUtil.concat(
718
- this._deflate[kBuffers],
719
- this._deflate[kTotalLength]
720
- );
721
- if (fin) {
722
- data2 = new FastBuffer$1(data2.buffer, data2.byteOffset, data2.length - 4);
723
- }
724
- this._deflate[kCallback] = null;
725
- this._deflate[kTotalLength] = 0;
726
- this._deflate[kBuffers] = [];
727
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
728
- this._deflate.reset();
729
- }
730
- callback(null, data2);
731
- });
732
- }
733
- };
734
- var permessageDeflate = PerMessageDeflate$3;
735
- function deflateOnData(chunk) {
736
- this[kBuffers].push(chunk);
737
- this[kTotalLength] += chunk.length;
738
- }
739
- function inflateOnData(chunk) {
740
- this[kTotalLength] += chunk.length;
741
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
742
- this[kBuffers].push(chunk);
743
- return;
744
- }
745
- this[kError$1] = new RangeError("Max payload size exceeded");
746
- this[kError$1].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
747
- this[kError$1][kStatusCode$2] = 1009;
748
- this.removeListener("data", inflateOnData);
749
- this.reset();
750
- }
751
- function inflateOnError(err) {
752
- this[kPerMessageDeflate]._inflate = null;
753
- err[kStatusCode$2] = 1007;
754
- this[kCallback](err);
755
- }
756
- var validation = { exports: {} };
757
- const __viteOptionalPeerDep_utf8Validate_ws = {};
758
- const __viteOptionalPeerDep_utf8Validate_ws$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
759
- __proto__: null,
760
- default: __viteOptionalPeerDep_utf8Validate_ws
761
- }, Symbol.toStringTag, { value: "Module" }));
762
- const require$$1 = /* @__PURE__ */ getAugmentedNamespace(__viteOptionalPeerDep_utf8Validate_ws$1);
763
- var isValidUTF8_1;
764
- const { isUtf8 } = require$$0$3;
765
- const tokenChars$2 = [
766
- 0,
767
- 0,
768
- 0,
769
- 0,
770
- 0,
771
- 0,
772
- 0,
773
- 0,
774
- 0,
775
- 0,
776
- 0,
777
- 0,
778
- 0,
779
- 0,
780
- 0,
781
- 0,
782
- // 0 - 15
783
- 0,
784
- 0,
785
- 0,
786
- 0,
787
- 0,
788
- 0,
789
- 0,
790
- 0,
791
- 0,
792
- 0,
793
- 0,
794
- 0,
795
- 0,
796
- 0,
797
- 0,
798
- 0,
799
- // 16 - 31
800
- 0,
801
- 1,
802
- 0,
803
- 1,
804
- 1,
805
- 1,
806
- 1,
807
- 1,
808
- 0,
809
- 0,
810
- 1,
811
- 1,
812
- 0,
813
- 1,
814
- 1,
815
- 0,
816
- // 32 - 47
817
- 1,
818
- 1,
819
- 1,
820
- 1,
821
- 1,
822
- 1,
823
- 1,
824
- 1,
825
- 1,
826
- 1,
827
- 0,
828
- 0,
829
- 0,
830
- 0,
831
- 0,
832
- 0,
833
- // 48 - 63
834
- 0,
835
- 1,
836
- 1,
837
- 1,
838
- 1,
839
- 1,
840
- 1,
841
- 1,
842
- 1,
843
- 1,
844
- 1,
845
- 1,
846
- 1,
847
- 1,
848
- 1,
849
- 1,
850
- // 64 - 79
851
- 1,
852
- 1,
853
- 1,
854
- 1,
855
- 1,
856
- 1,
857
- 1,
858
- 1,
859
- 1,
860
- 1,
861
- 1,
862
- 0,
863
- 0,
864
- 0,
865
- 1,
866
- 1,
867
- // 80 - 95
868
- 1,
869
- 1,
870
- 1,
871
- 1,
872
- 1,
873
- 1,
874
- 1,
875
- 1,
876
- 1,
877
- 1,
878
- 1,
879
- 1,
880
- 1,
881
- 1,
882
- 1,
883
- 1,
884
- // 96 - 111
885
- 1,
886
- 1,
887
- 1,
888
- 1,
889
- 1,
890
- 1,
891
- 1,
892
- 1,
893
- 1,
894
- 1,
895
- 1,
896
- 0,
897
- 1,
898
- 0,
899
- 1,
900
- 0
901
- // 112 - 127
902
- ];
903
- function isValidStatusCode$2(code) {
904
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
905
- }
906
- function _isValidUTF8(buf) {
907
- const len = buf.length;
908
- let i = 0;
909
- while (i < len) {
910
- if ((buf[i] & 128) === 0) {
911
- i++;
912
- } else if ((buf[i] & 224) === 192) {
913
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
914
- return false;
915
- }
916
- i += 2;
917
- } else if ((buf[i] & 240) === 224) {
918
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
919
- buf[i] === 237 && (buf[i + 1] & 224) === 160) {
920
- return false;
921
- }
922
- i += 3;
923
- } else if ((buf[i] & 248) === 240) {
924
- 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
925
- buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
926
- return false;
927
- }
928
- i += 4;
929
- } else {
930
- return false;
931
- }
932
- }
933
- return true;
934
- }
935
- validation.exports = {
936
- isValidStatusCode: isValidStatusCode$2,
937
- isValidUTF8: _isValidUTF8,
938
- tokenChars: tokenChars$2
939
- };
940
- if (isUtf8) {
941
- isValidUTF8_1 = validation.exports.isValidUTF8 = function(buf) {
942
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
943
- };
944
- } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
945
- try {
946
- const isValidUTF82 = require$$1;
947
- isValidUTF8_1 = validation.exports.isValidUTF8 = function(buf) {
948
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF82(buf);
949
- };
950
- } catch (e) {
951
- }
952
- }
953
- var validationExports = validation.exports;
954
- const { Writable } = require$$0;
955
- const PerMessageDeflate$2 = permessageDeflate;
956
- const {
957
- BINARY_TYPES: BINARY_TYPES$1,
958
- EMPTY_BUFFER: EMPTY_BUFFER$2,
959
- kStatusCode: kStatusCode$1,
960
- kWebSocket: kWebSocket$2
961
- } = constants;
962
- const { concat, toArrayBuffer, unmask } = bufferUtilExports;
963
- const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports;
964
- const FastBuffer = Buffer[Symbol.species];
965
- const GET_INFO = 0;
966
- const GET_PAYLOAD_LENGTH_16 = 1;
967
- const GET_PAYLOAD_LENGTH_64 = 2;
968
- const GET_MASK = 3;
969
- const GET_DATA = 4;
970
- const INFLATING = 5;
971
- let Receiver$1 = class Receiver extends Writable {
972
- /**
973
- * Creates a Receiver instance.
974
- *
975
- * @param {Object} [options] Options object
976
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
977
- * @param {Object} [options.extensions] An object containing the negotiated
978
- * extensions
979
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
980
- * client or server mode
981
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
982
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
983
- * not to skip UTF-8 validation for text and close messages
984
- */
985
- constructor(options = {}) {
986
- super();
987
- this._binaryType = options.binaryType || BINARY_TYPES$1[0];
988
- this._extensions = options.extensions || {};
989
- this._isServer = !!options.isServer;
990
- this._maxPayload = options.maxPayload | 0;
991
- this._skipUTF8Validation = !!options.skipUTF8Validation;
992
- this[kWebSocket$2] = void 0;
993
- this._bufferedBytes = 0;
994
- this._buffers = [];
995
- this._compressed = false;
996
- this._payloadLength = 0;
997
- this._mask = void 0;
998
- this._fragmented = 0;
999
- this._masked = false;
1000
- this._fin = false;
1001
- this._opcode = 0;
1002
- this._totalPayloadLength = 0;
1003
- this._messageLength = 0;
1004
- this._fragments = [];
1005
- this._state = GET_INFO;
1006
- this._loop = false;
1007
- }
1008
- /**
1009
- * Implements `Writable.prototype._write()`.
1010
- *
1011
- * @param {Buffer} chunk The chunk of data to write
1012
- * @param {String} encoding The character encoding of `chunk`
1013
- * @param {Function} cb Callback
1014
- * @private
1015
- */
1016
- _write(chunk, encoding, cb) {
1017
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
1018
- this._bufferedBytes += chunk.length;
1019
- this._buffers.push(chunk);
1020
- this.startLoop(cb);
1021
- }
1022
- /**
1023
- * Consumes `n` bytes from the buffered data.
1024
- *
1025
- * @param {Number} n The number of bytes to consume
1026
- * @return {Buffer} The consumed bytes
1027
- * @private
1028
- */
1029
- consume(n) {
1030
- this._bufferedBytes -= n;
1031
- if (n === this._buffers[0].length) return this._buffers.shift();
1032
- if (n < this._buffers[0].length) {
1033
- const buf = this._buffers[0];
1034
- this._buffers[0] = new FastBuffer(
1035
- buf.buffer,
1036
- buf.byteOffset + n,
1037
- buf.length - n
1038
- );
1039
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
1040
- }
1041
- const dst = Buffer.allocUnsafe(n);
1042
- do {
1043
- const buf = this._buffers[0];
1044
- const offset = dst.length - n;
1045
- if (n >= buf.length) {
1046
- dst.set(this._buffers.shift(), offset);
1047
- } else {
1048
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
1049
- this._buffers[0] = new FastBuffer(
1050
- buf.buffer,
1051
- buf.byteOffset + n,
1052
- buf.length - n
1053
- );
1054
- }
1055
- n -= buf.length;
1056
- } while (n > 0);
1057
- return dst;
1058
- }
1059
- /**
1060
- * Starts the parsing loop.
1061
- *
1062
- * @param {Function} cb Callback
1063
- * @private
1064
- */
1065
- startLoop(cb) {
1066
- let err;
1067
- this._loop = true;
1068
- do {
1069
- switch (this._state) {
1070
- case GET_INFO:
1071
- err = this.getInfo();
1072
- break;
1073
- case GET_PAYLOAD_LENGTH_16:
1074
- err = this.getPayloadLength16();
1075
- break;
1076
- case GET_PAYLOAD_LENGTH_64:
1077
- err = this.getPayloadLength64();
1078
- break;
1079
- case GET_MASK:
1080
- this.getMask();
1081
- break;
1082
- case GET_DATA:
1083
- err = this.getData(cb);
1084
- break;
1085
- default:
1086
- this._loop = false;
1087
- return;
1088
- }
1089
- } while (this._loop);
1090
- cb(err);
1091
- }
1092
- /**
1093
- * Reads the first two bytes of a frame.
1094
- *
1095
- * @return {(RangeError|undefined)} A possible error
1096
- * @private
1097
- */
1098
- getInfo() {
1099
- if (this._bufferedBytes < 2) {
1100
- this._loop = false;
1101
- return;
1102
- }
1103
- const buf = this.consume(2);
1104
- if ((buf[0] & 48) !== 0) {
1105
- this._loop = false;
1106
- return error(
1107
- RangeError,
1108
- "RSV2 and RSV3 must be clear",
1109
- true,
1110
- 1002,
1111
- "WS_ERR_UNEXPECTED_RSV_2_3"
1112
- );
1113
- }
1114
- const compressed = (buf[0] & 64) === 64;
1115
- if (compressed && !this._extensions[PerMessageDeflate$2.extensionName]) {
1116
- this._loop = false;
1117
- return error(
1118
- RangeError,
1119
- "RSV1 must be clear",
1120
- true,
1121
- 1002,
1122
- "WS_ERR_UNEXPECTED_RSV_1"
1123
- );
1124
- }
1125
- this._fin = (buf[0] & 128) === 128;
1126
- this._opcode = buf[0] & 15;
1127
- this._payloadLength = buf[1] & 127;
1128
- if (this._opcode === 0) {
1129
- if (compressed) {
1130
- this._loop = false;
1131
- return error(
1132
- RangeError,
1133
- "RSV1 must be clear",
1134
- true,
1135
- 1002,
1136
- "WS_ERR_UNEXPECTED_RSV_1"
1137
- );
1138
- }
1139
- if (!this._fragmented) {
1140
- this._loop = false;
1141
- return error(
1142
- RangeError,
1143
- "invalid opcode 0",
1144
- true,
1145
- 1002,
1146
- "WS_ERR_INVALID_OPCODE"
1147
- );
1148
- }
1149
- this._opcode = this._fragmented;
1150
- } else if (this._opcode === 1 || this._opcode === 2) {
1151
- if (this._fragmented) {
1152
- this._loop = false;
1153
- return error(
1154
- RangeError,
1155
- `invalid opcode ${this._opcode}`,
1156
- true,
1157
- 1002,
1158
- "WS_ERR_INVALID_OPCODE"
1159
- );
1160
- }
1161
- this._compressed = compressed;
1162
- } else if (this._opcode > 7 && this._opcode < 11) {
1163
- if (!this._fin) {
1164
- this._loop = false;
1165
- return error(
1166
- RangeError,
1167
- "FIN must be set",
1168
- true,
1169
- 1002,
1170
- "WS_ERR_EXPECTED_FIN"
1171
- );
1172
- }
1173
- if (compressed) {
1174
- this._loop = false;
1175
- return error(
1176
- RangeError,
1177
- "RSV1 must be clear",
1178
- true,
1179
- 1002,
1180
- "WS_ERR_UNEXPECTED_RSV_1"
1181
- );
1182
- }
1183
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1184
- this._loop = false;
1185
- return error(
1186
- RangeError,
1187
- `invalid payload length ${this._payloadLength}`,
1188
- true,
1189
- 1002,
1190
- "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1191
- );
1192
- }
1193
- } else {
1194
- this._loop = false;
1195
- return error(
1196
- RangeError,
1197
- `invalid opcode ${this._opcode}`,
1198
- true,
1199
- 1002,
1200
- "WS_ERR_INVALID_OPCODE"
1201
- );
1202
- }
1203
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1204
- this._masked = (buf[1] & 128) === 128;
1205
- if (this._isServer) {
1206
- if (!this._masked) {
1207
- this._loop = false;
1208
- return error(
1209
- RangeError,
1210
- "MASK must be set",
1211
- true,
1212
- 1002,
1213
- "WS_ERR_EXPECTED_MASK"
1214
- );
1215
- }
1216
- } else if (this._masked) {
1217
- this._loop = false;
1218
- return error(
1219
- RangeError,
1220
- "MASK must be clear",
1221
- true,
1222
- 1002,
1223
- "WS_ERR_UNEXPECTED_MASK"
1224
- );
1225
- }
1226
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1227
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1228
- else return this.haveLength();
1229
- }
1230
- /**
1231
- * Gets extended payload length (7+16).
1232
- *
1233
- * @return {(RangeError|undefined)} A possible error
1234
- * @private
1235
- */
1236
- getPayloadLength16() {
1237
- if (this._bufferedBytes < 2) {
1238
- this._loop = false;
1239
- return;
1240
- }
1241
- this._payloadLength = this.consume(2).readUInt16BE(0);
1242
- return this.haveLength();
1243
- }
1244
- /**
1245
- * Gets extended payload length (7+64).
1246
- *
1247
- * @return {(RangeError|undefined)} A possible error
1248
- * @private
1249
- */
1250
- getPayloadLength64() {
1251
- if (this._bufferedBytes < 8) {
1252
- this._loop = false;
1253
- return;
1254
- }
1255
- const buf = this.consume(8);
1256
- const num = buf.readUInt32BE(0);
1257
- if (num > Math.pow(2, 53 - 32) - 1) {
1258
- this._loop = false;
1259
- return error(
1260
- RangeError,
1261
- "Unsupported WebSocket frame: payload length > 2^53 - 1",
1262
- false,
1263
- 1009,
1264
- "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1265
- );
1266
- }
1267
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1268
- return this.haveLength();
1269
- }
1270
- /**
1271
- * Payload length has been read.
1272
- *
1273
- * @return {(RangeError|undefined)} A possible error
1274
- * @private
1275
- */
1276
- haveLength() {
1277
- if (this._payloadLength && this._opcode < 8) {
1278
- this._totalPayloadLength += this._payloadLength;
1279
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1280
- this._loop = false;
1281
- return error(
1282
- RangeError,
1283
- "Max payload size exceeded",
1284
- false,
1285
- 1009,
1286
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1287
- );
1288
- }
1289
- }
1290
- if (this._masked) this._state = GET_MASK;
1291
- else this._state = GET_DATA;
1292
- }
1293
- /**
1294
- * Reads mask bytes.
1295
- *
1296
- * @private
1297
- */
1298
- getMask() {
1299
- if (this._bufferedBytes < 4) {
1300
- this._loop = false;
1301
- return;
1302
- }
1303
- this._mask = this.consume(4);
1304
- this._state = GET_DATA;
1305
- }
1306
- /**
1307
- * Reads data bytes.
1308
- *
1309
- * @param {Function} cb Callback
1310
- * @return {(Error|RangeError|undefined)} A possible error
1311
- * @private
1312
- */
1313
- getData(cb) {
1314
- let data = EMPTY_BUFFER$2;
1315
- if (this._payloadLength) {
1316
- if (this._bufferedBytes < this._payloadLength) {
1317
- this._loop = false;
1318
- return;
1319
- }
1320
- data = this.consume(this._payloadLength);
1321
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1322
- unmask(data, this._mask);
1323
- }
1324
- }
1325
- if (this._opcode > 7) return this.controlMessage(data);
1326
- if (this._compressed) {
1327
- this._state = INFLATING;
1328
- this.decompress(data, cb);
1329
- return;
1330
- }
1331
- if (data.length) {
1332
- this._messageLength = this._totalPayloadLength;
1333
- this._fragments.push(data);
1334
- }
1335
- return this.dataMessage();
1336
- }
1337
- /**
1338
- * Decompresses data.
1339
- *
1340
- * @param {Buffer} data Compressed data
1341
- * @param {Function} cb Callback
1342
- * @private
1343
- */
1344
- decompress(data, cb) {
1345
- const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
1346
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1347
- if (err) return cb(err);
1348
- if (buf.length) {
1349
- this._messageLength += buf.length;
1350
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1351
- return cb(
1352
- error(
1353
- RangeError,
1354
- "Max payload size exceeded",
1355
- false,
1356
- 1009,
1357
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1358
- )
1359
- );
1360
- }
1361
- this._fragments.push(buf);
1362
- }
1363
- const er = this.dataMessage();
1364
- if (er) return cb(er);
1365
- this.startLoop(cb);
1366
- });
1367
- }
1368
- /**
1369
- * Handles a data message.
1370
- *
1371
- * @return {(Error|undefined)} A possible error
1372
- * @private
1373
- */
1374
- dataMessage() {
1375
- if (this._fin) {
1376
- const messageLength = this._messageLength;
1377
- const fragments = this._fragments;
1378
- this._totalPayloadLength = 0;
1379
- this._messageLength = 0;
1380
- this._fragmented = 0;
1381
- this._fragments = [];
1382
- if (this._opcode === 2) {
1383
- let data;
1384
- if (this._binaryType === "nodebuffer") {
1385
- data = concat(fragments, messageLength);
1386
- } else if (this._binaryType === "arraybuffer") {
1387
- data = toArrayBuffer(concat(fragments, messageLength));
1388
- } else {
1389
- data = fragments;
1390
- }
1391
- this.emit("message", data, true);
1392
- } else {
1393
- const buf = concat(fragments, messageLength);
1394
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1395
- this._loop = false;
1396
- return error(
1397
- Error,
1398
- "invalid UTF-8 sequence",
1399
- true,
1400
- 1007,
1401
- "WS_ERR_INVALID_UTF8"
1402
- );
1403
- }
1404
- this.emit("message", buf, false);
1405
- }
1406
- }
1407
- this._state = GET_INFO;
1408
- }
1409
- /**
1410
- * Handles a control message.
1411
- *
1412
- * @param {Buffer} data Data to handle
1413
- * @return {(Error|RangeError|undefined)} A possible error
1414
- * @private
1415
- */
1416
- controlMessage(data) {
1417
- if (this._opcode === 8) {
1418
- this._loop = false;
1419
- if (data.length === 0) {
1420
- this.emit("conclude", 1005, EMPTY_BUFFER$2);
1421
- this.end();
1422
- } else {
1423
- const code = data.readUInt16BE(0);
1424
- if (!isValidStatusCode$1(code)) {
1425
- return error(
1426
- RangeError,
1427
- `invalid status code ${code}`,
1428
- true,
1429
- 1002,
1430
- "WS_ERR_INVALID_CLOSE_CODE"
1431
- );
1432
- }
1433
- const buf = new FastBuffer(
1434
- data.buffer,
1435
- data.byteOffset + 2,
1436
- data.length - 2
1437
- );
1438
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1439
- return error(
1440
- Error,
1441
- "invalid UTF-8 sequence",
1442
- true,
1443
- 1007,
1444
- "WS_ERR_INVALID_UTF8"
1445
- );
1446
- }
1447
- this.emit("conclude", code, buf);
1448
- this.end();
1449
- }
1450
- } else if (this._opcode === 9) {
1451
- this.emit("ping", data);
1452
- } else {
1453
- this.emit("pong", data);
1454
- }
1455
- this._state = GET_INFO;
1456
- }
1457
- };
1458
- var receiver = Receiver$1;
1459
- function error(ErrorCtor, message, prefix, statusCode, errorCode) {
1460
- const err = new ErrorCtor(
1461
- prefix ? `Invalid WebSocket frame: ${message}` : message
1462
- );
1463
- Error.captureStackTrace(err, error);
1464
- err.code = errorCode;
1465
- err[kStatusCode$1] = statusCode;
1466
- return err;
1467
- }
1468
- const { randomFillSync } = require$$5;
1469
- const PerMessageDeflate$1 = permessageDeflate;
1470
- const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants;
1471
- const { isValidStatusCode } = validationExports;
1472
- const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports;
1473
- const kByteLength = Symbol("kByteLength");
1474
- const maskBuffer = Buffer.alloc(4);
1475
- let Sender$1 = class Sender {
1476
- /**
1477
- * Creates a Sender instance.
1478
- *
1479
- * @param {(net.Socket|tls.Socket)} socket The connection socket
1480
- * @param {Object} [extensions] An object containing the negotiated extensions
1481
- * @param {Function} [generateMask] The function used to generate the masking
1482
- * key
1483
- */
1484
- constructor(socket, extensions, generateMask) {
1485
- this._extensions = extensions || {};
1486
- if (generateMask) {
1487
- this._generateMask = generateMask;
1488
- this._maskBuffer = Buffer.alloc(4);
1489
- }
1490
- this._socket = socket;
1491
- this._firstFragment = true;
1492
- this._compress = false;
1493
- this._bufferedBytes = 0;
1494
- this._deflating = false;
1495
- this._queue = [];
1496
- }
1497
- /**
1498
- * Frames a piece of data according to the HyBi WebSocket protocol.
1499
- *
1500
- * @param {(Buffer|String)} data The data to frame
1501
- * @param {Object} options Options object
1502
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1503
- * FIN bit
1504
- * @param {Function} [options.generateMask] The function used to generate the
1505
- * masking key
1506
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1507
- * `data`
1508
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1509
- * key
1510
- * @param {Number} options.opcode The opcode
1511
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1512
- * modified
1513
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1514
- * RSV1 bit
1515
- * @return {(Buffer|String)[]} The framed data
1516
- * @public
1517
- */
1518
- static frame(data, options) {
1519
- let mask2;
1520
- let merge = false;
1521
- let offset = 2;
1522
- let skipMasking = false;
1523
- if (options.mask) {
1524
- mask2 = options.maskBuffer || maskBuffer;
1525
- if (options.generateMask) {
1526
- options.generateMask(mask2);
1527
- } else {
1528
- randomFillSync(mask2, 0, 4);
1529
- }
1530
- skipMasking = (mask2[0] | mask2[1] | mask2[2] | mask2[3]) === 0;
1531
- offset = 6;
1532
- }
1533
- let dataLength;
1534
- if (typeof data === "string") {
1535
- if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1536
- dataLength = options[kByteLength];
1537
- } else {
1538
- data = Buffer.from(data);
1539
- dataLength = data.length;
1540
- }
1541
- } else {
1542
- dataLength = data.length;
1543
- merge = options.mask && options.readOnly && !skipMasking;
1544
- }
1545
- let payloadLength = dataLength;
1546
- if (dataLength >= 65536) {
1547
- offset += 8;
1548
- payloadLength = 127;
1549
- } else if (dataLength > 125) {
1550
- offset += 2;
1551
- payloadLength = 126;
1552
- }
1553
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1554
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
1555
- if (options.rsv1) target[0] |= 64;
1556
- target[1] = payloadLength;
1557
- if (payloadLength === 126) {
1558
- target.writeUInt16BE(dataLength, 2);
1559
- } else if (payloadLength === 127) {
1560
- target[2] = target[3] = 0;
1561
- target.writeUIntBE(dataLength, 4, 6);
1562
- }
1563
- if (!options.mask) return [target, data];
1564
- target[1] |= 128;
1565
- target[offset - 4] = mask2[0];
1566
- target[offset - 3] = mask2[1];
1567
- target[offset - 2] = mask2[2];
1568
- target[offset - 1] = mask2[3];
1569
- if (skipMasking) return [target, data];
1570
- if (merge) {
1571
- applyMask(data, mask2, target, offset, dataLength);
1572
- return [target];
1573
- }
1574
- applyMask(data, mask2, data, 0, dataLength);
1575
- return [target, data];
1576
- }
1577
- /**
1578
- * Sends a close message to the other peer.
1579
- *
1580
- * @param {Number} [code] The status code component of the body
1581
- * @param {(String|Buffer)} [data] The message component of the body
1582
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1583
- * @param {Function} [cb] Callback
1584
- * @public
1585
- */
1586
- close(code, data, mask2, cb) {
1587
- let buf;
1588
- if (code === void 0) {
1589
- buf = EMPTY_BUFFER$1;
1590
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1591
- throw new TypeError("First argument must be a valid error code number");
1592
- } else if (data === void 0 || !data.length) {
1593
- buf = Buffer.allocUnsafe(2);
1594
- buf.writeUInt16BE(code, 0);
1595
- } else {
1596
- const length = Buffer.byteLength(data);
1597
- if (length > 123) {
1598
- throw new RangeError("The message must not be greater than 123 bytes");
1599
- }
1600
- buf = Buffer.allocUnsafe(2 + length);
1601
- buf.writeUInt16BE(code, 0);
1602
- if (typeof data === "string") {
1603
- buf.write(data, 2);
1604
- } else {
1605
- buf.set(data, 2);
1606
- }
1607
- }
1608
- const options = {
1609
- [kByteLength]: buf.length,
1610
- fin: true,
1611
- generateMask: this._generateMask,
1612
- mask: mask2,
1613
- maskBuffer: this._maskBuffer,
1614
- opcode: 8,
1615
- readOnly: false,
1616
- rsv1: false
1617
- };
1618
- if (this._deflating) {
1619
- this.enqueue([this.dispatch, buf, false, options, cb]);
1620
- } else {
1621
- this.sendFrame(Sender.frame(buf, options), cb);
1622
- }
1623
- }
1624
- /**
1625
- * Sends a ping message to the other peer.
1626
- *
1627
- * @param {*} data The message to send
1628
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1629
- * @param {Function} [cb] Callback
1630
- * @public
1631
- */
1632
- ping(data, mask2, cb) {
1633
- let byteLength;
1634
- let readOnly;
1635
- if (typeof data === "string") {
1636
- byteLength = Buffer.byteLength(data);
1637
- readOnly = false;
1638
- } else {
1639
- data = toBuffer$1(data);
1640
- byteLength = data.length;
1641
- readOnly = toBuffer$1.readOnly;
1642
- }
1643
- if (byteLength > 125) {
1644
- throw new RangeError("The data size must not be greater than 125 bytes");
1645
- }
1646
- const options = {
1647
- [kByteLength]: byteLength,
1648
- fin: true,
1649
- generateMask: this._generateMask,
1650
- mask: mask2,
1651
- maskBuffer: this._maskBuffer,
1652
- opcode: 9,
1653
- readOnly,
1654
- rsv1: false
1655
- };
1656
- if (this._deflating) {
1657
- this.enqueue([this.dispatch, data, false, options, cb]);
1658
- } else {
1659
- this.sendFrame(Sender.frame(data, options), cb);
1660
- }
1661
- }
1662
- /**
1663
- * Sends a pong message to the other peer.
1664
- *
1665
- * @param {*} data The message to send
1666
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1667
- * @param {Function} [cb] Callback
1668
- * @public
1669
- */
1670
- pong(data, mask2, cb) {
1671
- let byteLength;
1672
- let readOnly;
1673
- if (typeof data === "string") {
1674
- byteLength = Buffer.byteLength(data);
1675
- readOnly = false;
1676
- } else {
1677
- data = toBuffer$1(data);
1678
- byteLength = data.length;
1679
- readOnly = toBuffer$1.readOnly;
1680
- }
1681
- if (byteLength > 125) {
1682
- throw new RangeError("The data size must not be greater than 125 bytes");
1683
- }
1684
- const options = {
1685
- [kByteLength]: byteLength,
1686
- fin: true,
1687
- generateMask: this._generateMask,
1688
- mask: mask2,
1689
- maskBuffer: this._maskBuffer,
1690
- opcode: 10,
1691
- readOnly,
1692
- rsv1: false
1693
- };
1694
- if (this._deflating) {
1695
- this.enqueue([this.dispatch, data, false, options, cb]);
1696
- } else {
1697
- this.sendFrame(Sender.frame(data, options), cb);
1698
- }
1699
- }
1700
- /**
1701
- * Sends a data message to the other peer.
1702
- *
1703
- * @param {*} data The message to send
1704
- * @param {Object} options Options object
1705
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1706
- * or text
1707
- * @param {Boolean} [options.compress=false] Specifies whether or not to
1708
- * compress `data`
1709
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1710
- * last one
1711
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1712
- * `data`
1713
- * @param {Function} [cb] Callback
1714
- * @public
1715
- */
1716
- send(data, options, cb) {
1717
- const perMessageDeflate = this._extensions[PerMessageDeflate$1.extensionName];
1718
- let opcode = options.binary ? 2 : 1;
1719
- let rsv1 = options.compress;
1720
- let byteLength;
1721
- let readOnly;
1722
- if (typeof data === "string") {
1723
- byteLength = Buffer.byteLength(data);
1724
- readOnly = false;
1725
- } else {
1726
- data = toBuffer$1(data);
1727
- byteLength = data.length;
1728
- readOnly = toBuffer$1.readOnly;
1729
- }
1730
- if (this._firstFragment) {
1731
- this._firstFragment = false;
1732
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1733
- rsv1 = byteLength >= perMessageDeflate._threshold;
1734
- }
1735
- this._compress = rsv1;
1736
- } else {
1737
- rsv1 = false;
1738
- opcode = 0;
1739
- }
1740
- if (options.fin) this._firstFragment = true;
1741
- if (perMessageDeflate) {
1742
- const opts = {
1743
- [kByteLength]: byteLength,
1744
- fin: options.fin,
1745
- generateMask: this._generateMask,
1746
- mask: options.mask,
1747
- maskBuffer: this._maskBuffer,
1748
- opcode,
1749
- readOnly,
1750
- rsv1
1751
- };
1752
- if (this._deflating) {
1753
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1754
- } else {
1755
- this.dispatch(data, this._compress, opts, cb);
1756
- }
1757
- } else {
1758
- this.sendFrame(
1759
- Sender.frame(data, {
1760
- [kByteLength]: byteLength,
1761
- fin: options.fin,
1762
- generateMask: this._generateMask,
1763
- mask: options.mask,
1764
- maskBuffer: this._maskBuffer,
1765
- opcode,
1766
- readOnly,
1767
- rsv1: false
1768
- }),
1769
- cb
1770
- );
1771
- }
1772
- }
1773
- /**
1774
- * Dispatches a message.
1775
- *
1776
- * @param {(Buffer|String)} data The message to send
1777
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1778
- * `data`
1779
- * @param {Object} options Options object
1780
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1781
- * FIN bit
1782
- * @param {Function} [options.generateMask] The function used to generate the
1783
- * masking key
1784
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1785
- * `data`
1786
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1787
- * key
1788
- * @param {Number} options.opcode The opcode
1789
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1790
- * modified
1791
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1792
- * RSV1 bit
1793
- * @param {Function} [cb] Callback
1794
- * @private
1795
- */
1796
- dispatch(data, compress, options, cb) {
1797
- if (!compress) {
1798
- this.sendFrame(Sender.frame(data, options), cb);
1799
- return;
1800
- }
1801
- const perMessageDeflate = this._extensions[PerMessageDeflate$1.extensionName];
1802
- this._bufferedBytes += options[kByteLength];
1803
- this._deflating = true;
1804
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1805
- if (this._socket.destroyed) {
1806
- const err = new Error(
1807
- "The socket was closed while data was being compressed"
1808
- );
1809
- if (typeof cb === "function") cb(err);
1810
- for (let i = 0; i < this._queue.length; i++) {
1811
- const params = this._queue[i];
1812
- const callback = params[params.length - 1];
1813
- if (typeof callback === "function") callback(err);
1814
- }
1815
- return;
1816
- }
1817
- this._bufferedBytes -= options[kByteLength];
1818
- this._deflating = false;
1819
- options.readOnly = false;
1820
- this.sendFrame(Sender.frame(buf, options), cb);
1821
- this.dequeue();
1822
- });
1823
- }
1824
- /**
1825
- * Executes queued send operations.
1826
- *
1827
- * @private
1828
- */
1829
- dequeue() {
1830
- while (!this._deflating && this._queue.length) {
1831
- const params = this._queue.shift();
1832
- this._bufferedBytes -= params[3][kByteLength];
1833
- Reflect.apply(params[0], this, params.slice(1));
1834
- }
1835
- }
1836
- /**
1837
- * Enqueues a send operation.
1838
- *
1839
- * @param {Array} params Send operation parameters.
1840
- * @private
1841
- */
1842
- enqueue(params) {
1843
- this._bufferedBytes += params[3][kByteLength];
1844
- this._queue.push(params);
1845
- }
1846
- /**
1847
- * Sends a frame.
1848
- *
1849
- * @param {Buffer[]} list The frame to send
1850
- * @param {Function} [cb] Callback
1851
- * @private
1852
- */
1853
- sendFrame(list, cb) {
1854
- if (list.length === 2) {
1855
- this._socket.cork();
1856
- this._socket.write(list[0]);
1857
- this._socket.write(list[1], cb);
1858
- this._socket.uncork();
1859
- } else {
1860
- this._socket.write(list[0], cb);
1861
- }
1862
- }
1863
- };
1864
- var sender = Sender$1;
1865
- const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants;
1866
- const kCode = Symbol("kCode");
1867
- const kData = Symbol("kData");
1868
- const kError = Symbol("kError");
1869
- const kMessage = Symbol("kMessage");
1870
- const kReason = Symbol("kReason");
1871
- const kTarget = Symbol("kTarget");
1872
- const kType = Symbol("kType");
1873
- const kWasClean = Symbol("kWasClean");
1874
- class Event {
1875
- /**
1876
- * Create a new `Event`.
1877
- *
1878
- * @param {String} type The name of the event
1879
- * @throws {TypeError} If the `type` argument is not specified
1880
- */
1881
- constructor(type) {
1882
- this[kTarget] = null;
1883
- this[kType] = type;
1884
- }
1885
- /**
1886
- * @type {*}
1887
- */
1888
- get target() {
1889
- return this[kTarget];
1890
- }
1891
- /**
1892
- * @type {String}
1893
- */
1894
- get type() {
1895
- return this[kType];
1896
- }
1897
- }
1898
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
1899
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
1900
- class CloseEvent extends Event {
1901
- /**
1902
- * Create a new `CloseEvent`.
1903
- *
1904
- * @param {String} type The name of the event
1905
- * @param {Object} [options] A dictionary object that allows for setting
1906
- * attributes via object members of the same name
1907
- * @param {Number} [options.code=0] The status code explaining why the
1908
- * connection was closed
1909
- * @param {String} [options.reason=''] A human-readable string explaining why
1910
- * the connection was closed
1911
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1912
- * connection was cleanly closed
1913
- */
1914
- constructor(type, options = {}) {
1915
- super(type);
1916
- this[kCode] = options.code === void 0 ? 0 : options.code;
1917
- this[kReason] = options.reason === void 0 ? "" : options.reason;
1918
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1919
- }
1920
- /**
1921
- * @type {Number}
1922
- */
1923
- get code() {
1924
- return this[kCode];
1925
- }
1926
- /**
1927
- * @type {String}
1928
- */
1929
- get reason() {
1930
- return this[kReason];
1931
- }
1932
- /**
1933
- * @type {Boolean}
1934
- */
1935
- get wasClean() {
1936
- return this[kWasClean];
1937
- }
1938
- }
1939
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1940
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1941
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1942
- class ErrorEvent extends Event {
1943
- /**
1944
- * Create a new `ErrorEvent`.
1945
- *
1946
- * @param {String} type The name of the event
1947
- * @param {Object} [options] A dictionary object that allows for setting
1948
- * attributes via object members of the same name
1949
- * @param {*} [options.error=null] The error that generated this event
1950
- * @param {String} [options.message=''] The error message
1951
- */
1952
- constructor(type, options = {}) {
1953
- super(type);
1954
- this[kError] = options.error === void 0 ? null : options.error;
1955
- this[kMessage] = options.message === void 0 ? "" : options.message;
1956
- }
1957
- /**
1958
- * @type {*}
1959
- */
1960
- get error() {
1961
- return this[kError];
1962
- }
1963
- /**
1964
- * @type {String}
1965
- */
1966
- get message() {
1967
- return this[kMessage];
1968
- }
1969
- }
1970
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1971
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1972
- class MessageEvent extends Event {
1973
- /**
1974
- * Create a new `MessageEvent`.
1975
- *
1976
- * @param {String} type The name of the event
1977
- * @param {Object} [options] A dictionary object that allows for setting
1978
- * attributes via object members of the same name
1979
- * @param {*} [options.data=null] The message content
1980
- */
1981
- constructor(type, options = {}) {
1982
- super(type);
1983
- this[kData] = options.data === void 0 ? null : options.data;
1984
- }
1985
- /**
1986
- * @type {*}
1987
- */
1988
- get data() {
1989
- return this[kData];
1990
- }
1991
- }
1992
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1993
- const EventTarget = {
1994
- /**
1995
- * Register an event listener.
1996
- *
1997
- * @param {String} type A string representing the event type to listen for
1998
- * @param {(Function|Object)} handler The listener to add
1999
- * @param {Object} [options] An options object specifies characteristics about
2000
- * the event listener
2001
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2002
- * listener should be invoked at most once after being added. If `true`,
2003
- * the listener would be automatically removed when invoked.
2004
- * @public
2005
- */
2006
- addEventListener(type, handler, options = {}) {
2007
- for (const listener of this.listeners(type)) {
2008
- if (!options[kForOnEventAttribute$1] && listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) {
2009
- return;
2010
- }
2011
- }
2012
- let wrapper;
2013
- if (type === "message") {
2014
- wrapper = function onMessage(data, isBinary) {
2015
- const event = new MessageEvent("message", {
2016
- data: isBinary ? data : data.toString()
2017
- });
2018
- event[kTarget] = this;
2019
- callListener(handler, this, event);
2020
- };
2021
- } else if (type === "close") {
2022
- wrapper = function onClose(code, message) {
2023
- const event = new CloseEvent("close", {
2024
- code,
2025
- reason: message.toString(),
2026
- wasClean: this._closeFrameReceived && this._closeFrameSent
2027
- });
2028
- event[kTarget] = this;
2029
- callListener(handler, this, event);
2030
- };
2031
- } else if (type === "error") {
2032
- wrapper = function onError(error2) {
2033
- const event = new ErrorEvent("error", {
2034
- error: error2,
2035
- message: error2.message
2036
- });
2037
- event[kTarget] = this;
2038
- callListener(handler, this, event);
2039
- };
2040
- } else if (type === "open") {
2041
- wrapper = function onOpen() {
2042
- const event = new Event("open");
2043
- event[kTarget] = this;
2044
- callListener(handler, this, event);
2045
- };
2046
- } else {
2047
- return;
2048
- }
2049
- wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
2050
- wrapper[kListener$1] = handler;
2051
- if (options.once) {
2052
- this.once(type, wrapper);
2053
- } else {
2054
- this.on(type, wrapper);
2055
- }
2056
- },
2057
- /**
2058
- * Remove an event listener.
2059
- *
2060
- * @param {String} type A string representing the event type to remove
2061
- * @param {(Function|Object)} handler The listener to remove
2062
- * @public
2063
- */
2064
- removeEventListener(type, handler) {
2065
- for (const listener of this.listeners(type)) {
2066
- if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) {
2067
- this.removeListener(type, listener);
2068
- break;
2069
- }
2070
- }
2071
- }
2072
- };
2073
- var eventTarget = {
2074
- EventTarget
2075
- };
2076
- function callListener(listener, thisArg, event) {
2077
- if (typeof listener === "object" && listener.handleEvent) {
2078
- listener.handleEvent.call(listener, event);
2079
- } else {
2080
- listener.call(thisArg, event);
2081
- }
2082
- }
2083
- const { tokenChars: tokenChars$1 } = validationExports;
2084
- function push(dest, name, elem) {
2085
- if (dest[name] === void 0) dest[name] = [elem];
2086
- else dest[name].push(elem);
2087
- }
2088
- function parse$1(header) {
2089
- const offers = /* @__PURE__ */ Object.create(null);
2090
- let params = /* @__PURE__ */ Object.create(null);
2091
- let mustUnescape = false;
2092
- let isEscaping = false;
2093
- let inQuotes = false;
2094
- let extensionName;
2095
- let paramName;
2096
- let start = -1;
2097
- let code = -1;
2098
- let end = -1;
2099
- let i = 0;
2100
- for (; i < header.length; i++) {
2101
- code = header.charCodeAt(i);
2102
- if (extensionName === void 0) {
2103
- if (end === -1 && tokenChars$1[code] === 1) {
2104
- if (start === -1) start = i;
2105
- } else if (i !== 0 && (code === 32 || code === 9)) {
2106
- if (end === -1 && start !== -1) end = i;
2107
- } else if (code === 59 || code === 44) {
2108
- if (start === -1) {
2109
- throw new SyntaxError(`Unexpected character at index ${i}`);
2110
- }
2111
- if (end === -1) end = i;
2112
- const name = header.slice(start, end);
2113
- if (code === 44) {
2114
- push(offers, name, params);
2115
- params = /* @__PURE__ */ Object.create(null);
2116
- } else {
2117
- extensionName = name;
2118
- }
2119
- start = end = -1;
2120
- } else {
2121
- throw new SyntaxError(`Unexpected character at index ${i}`);
2122
- }
2123
- } else if (paramName === void 0) {
2124
- if (end === -1 && tokenChars$1[code] === 1) {
2125
- if (start === -1) start = i;
2126
- } else if (code === 32 || code === 9) {
2127
- if (end === -1 && start !== -1) end = i;
2128
- } else if (code === 59 || code === 44) {
2129
- if (start === -1) {
2130
- throw new SyntaxError(`Unexpected character at index ${i}`);
2131
- }
2132
- if (end === -1) end = i;
2133
- push(params, header.slice(start, end), true);
2134
- if (code === 44) {
2135
- push(offers, extensionName, params);
2136
- params = /* @__PURE__ */ Object.create(null);
2137
- extensionName = void 0;
2138
- }
2139
- start = end = -1;
2140
- } else if (code === 61 && start !== -1 && end === -1) {
2141
- paramName = header.slice(start, i);
2142
- start = end = -1;
2143
- } else {
2144
- throw new SyntaxError(`Unexpected character at index ${i}`);
2145
- }
2146
- } else {
2147
- if (isEscaping) {
2148
- if (tokenChars$1[code] !== 1) {
2149
- throw new SyntaxError(`Unexpected character at index ${i}`);
2150
- }
2151
- if (start === -1) start = i;
2152
- else if (!mustUnescape) mustUnescape = true;
2153
- isEscaping = false;
2154
- } else if (inQuotes) {
2155
- if (tokenChars$1[code] === 1) {
2156
- if (start === -1) start = i;
2157
- } else if (code === 34 && start !== -1) {
2158
- inQuotes = false;
2159
- end = i;
2160
- } else if (code === 92) {
2161
- isEscaping = true;
2162
- } else {
2163
- throw new SyntaxError(`Unexpected character at index ${i}`);
2164
- }
2165
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2166
- inQuotes = true;
2167
- } else if (end === -1 && tokenChars$1[code] === 1) {
2168
- if (start === -1) start = i;
2169
- } else if (start !== -1 && (code === 32 || code === 9)) {
2170
- if (end === -1) end = i;
2171
- } else if (code === 59 || code === 44) {
2172
- if (start === -1) {
2173
- throw new SyntaxError(`Unexpected character at index ${i}`);
2174
- }
2175
- if (end === -1) end = i;
2176
- let value = header.slice(start, end);
2177
- if (mustUnescape) {
2178
- value = value.replace(/\\/g, "");
2179
- mustUnescape = false;
2180
- }
2181
- push(params, paramName, value);
2182
- if (code === 44) {
2183
- push(offers, extensionName, params);
2184
- params = /* @__PURE__ */ Object.create(null);
2185
- extensionName = void 0;
2186
- }
2187
- paramName = void 0;
2188
- start = end = -1;
2189
- } else {
2190
- throw new SyntaxError(`Unexpected character at index ${i}`);
2191
- }
2192
- }
2193
- }
2194
- if (start === -1 || inQuotes || code === 32 || code === 9) {
2195
- throw new SyntaxError("Unexpected end of input");
2196
- }
2197
- if (end === -1) end = i;
2198
- const token = header.slice(start, end);
2199
- if (extensionName === void 0) {
2200
- push(offers, token, params);
2201
- } else {
2202
- if (paramName === void 0) {
2203
- push(params, token, true);
2204
- } else if (mustUnescape) {
2205
- push(params, paramName, token.replace(/\\/g, ""));
2206
- } else {
2207
- push(params, paramName, token);
2208
- }
2209
- push(offers, extensionName, params);
2210
- }
2211
- return offers;
2212
- }
2213
- function format$1(extensions) {
2214
- return Object.keys(extensions).map((extension2) => {
2215
- let configurations = extensions[extension2];
2216
- if (!Array.isArray(configurations)) configurations = [configurations];
2217
- return configurations.map((params) => {
2218
- return [extension2].concat(
2219
- Object.keys(params).map((k) => {
2220
- let values = params[k];
2221
- if (!Array.isArray(values)) values = [values];
2222
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2223
- })
2224
- ).join("; ");
2225
- }).join(", ");
2226
- }).join(", ");
2227
- }
2228
- var extension = { format: format$1, parse: parse$1 };
2229
- const EventEmitter = require$$0$4;
2230
- const https = require$$1$2;
2231
- const http = require$$2$1;
2232
- const net = require$$3;
2233
- const tls = require$$4;
2234
- const { randomBytes, createHash: createHash$1 } = require$$5;
2235
- const { Readable } = require$$0;
2236
- const { URL } = require$$7;
2237
- const PerMessageDeflate2 = permessageDeflate;
2238
- const Receiver2 = receiver;
2239
- const Sender2 = sender;
2240
- const {
2241
- BINARY_TYPES,
2242
- EMPTY_BUFFER,
2243
- GUID: GUID$1,
2244
- kForOnEventAttribute,
2245
- kListener,
2246
- kStatusCode,
2247
- kWebSocket: kWebSocket$1,
2248
- NOOP
2249
- } = constants;
2250
- const {
2251
- EventTarget: { addEventListener, removeEventListener }
2252
- } = eventTarget;
2253
- const { format, parse } = extension;
2254
- const { toBuffer } = bufferUtilExports;
2255
- const closeTimeout = 30 * 1e3;
2256
- const kAborted = Symbol("kAborted");
2257
- const protocolVersions = [8, 13];
2258
- const readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2259
- const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2260
- class WebSocket extends EventEmitter {
2261
- /**
2262
- * Create a new `WebSocket`.
2263
- *
2264
- * @param {(String|URL)} address The URL to which to connect
2265
- * @param {(String|String[])} [protocols] The subprotocols
2266
- * @param {Object} [options] Connection options
2267
- */
2268
- constructor(address, protocols, options) {
2269
- super();
2270
- this._binaryType = BINARY_TYPES[0];
2271
- this._closeCode = 1006;
2272
- this._closeFrameReceived = false;
2273
- this._closeFrameSent = false;
2274
- this._closeMessage = EMPTY_BUFFER;
2275
- this._closeTimer = null;
2276
- this._extensions = {};
2277
- this._paused = false;
2278
- this._protocol = "";
2279
- this._readyState = WebSocket.CONNECTING;
2280
- this._receiver = null;
2281
- this._sender = null;
2282
- this._socket = null;
2283
- if (address !== null) {
2284
- this._bufferedAmount = 0;
2285
- this._isServer = false;
2286
- this._redirects = 0;
2287
- if (protocols === void 0) {
2288
- protocols = [];
2289
- } else if (!Array.isArray(protocols)) {
2290
- if (typeof protocols === "object" && protocols !== null) {
2291
- options = protocols;
2292
- protocols = [];
2293
- } else {
2294
- protocols = [protocols];
2295
- }
2296
- }
2297
- initAsClient(this, address, protocols, options);
2298
- } else {
2299
- this._isServer = true;
2300
- }
2301
- }
2302
- /**
2303
- * This deviates from the WHATWG interface since ws doesn't support the
2304
- * required default "blob" type (instead we define a custom "nodebuffer"
2305
- * type).
2306
- *
2307
- * @type {String}
2308
- */
2309
- get binaryType() {
2310
- return this._binaryType;
2311
- }
2312
- set binaryType(type) {
2313
- if (!BINARY_TYPES.includes(type)) return;
2314
- this._binaryType = type;
2315
- if (this._receiver) this._receiver._binaryType = type;
2316
- }
2317
- /**
2318
- * @type {Number}
2319
- */
2320
- get bufferedAmount() {
2321
- if (!this._socket) return this._bufferedAmount;
2322
- return this._socket._writableState.length + this._sender._bufferedBytes;
2323
- }
2324
- /**
2325
- * @type {String}
2326
- */
2327
- get extensions() {
2328
- return Object.keys(this._extensions).join();
2329
- }
2330
- /**
2331
- * @type {Boolean}
2332
- */
2333
- get isPaused() {
2334
- return this._paused;
2335
- }
2336
- /**
2337
- * @type {Function}
2338
- */
2339
- /* istanbul ignore next */
2340
- get onclose() {
2341
- return null;
2342
- }
2343
- /**
2344
- * @type {Function}
2345
- */
2346
- /* istanbul ignore next */
2347
- get onerror() {
2348
- return null;
2349
- }
2350
- /**
2351
- * @type {Function}
2352
- */
2353
- /* istanbul ignore next */
2354
- get onopen() {
2355
- return null;
2356
- }
2357
- /**
2358
- * @type {Function}
2359
- */
2360
- /* istanbul ignore next */
2361
- get onmessage() {
2362
- return null;
2363
- }
2364
- /**
2365
- * @type {String}
2366
- */
2367
- get protocol() {
2368
- return this._protocol;
2369
- }
2370
- /**
2371
- * @type {Number}
2372
- */
2373
- get readyState() {
2374
- return this._readyState;
2375
- }
2376
- /**
2377
- * @type {String}
2378
- */
2379
- get url() {
2380
- return this._url;
2381
- }
2382
- /**
2383
- * Set up the socket and the internal resources.
2384
- *
2385
- * @param {(net.Socket|tls.Socket)} socket The network socket between the
2386
- * server and client
2387
- * @param {Buffer} head The first packet of the upgraded stream
2388
- * @param {Object} options Options object
2389
- * @param {Function} [options.generateMask] The function used to generate the
2390
- * masking key
2391
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
2392
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2393
- * not to skip UTF-8 validation for text and close messages
2394
- * @private
2395
- */
2396
- setSocket(socket, head, options) {
2397
- const receiver2 = new Receiver2({
2398
- binaryType: this.binaryType,
2399
- extensions: this._extensions,
2400
- isServer: this._isServer,
2401
- maxPayload: options.maxPayload,
2402
- skipUTF8Validation: options.skipUTF8Validation
2403
- });
2404
- this._sender = new Sender2(socket, this._extensions, options.generateMask);
2405
- this._receiver = receiver2;
2406
- this._socket = socket;
2407
- receiver2[kWebSocket$1] = this;
2408
- socket[kWebSocket$1] = this;
2409
- receiver2.on("conclude", receiverOnConclude);
2410
- receiver2.on("drain", receiverOnDrain);
2411
- receiver2.on("error", receiverOnError);
2412
- receiver2.on("message", receiverOnMessage);
2413
- receiver2.on("ping", receiverOnPing);
2414
- receiver2.on("pong", receiverOnPong);
2415
- socket.setTimeout(0);
2416
- socket.setNoDelay();
2417
- if (head.length > 0) socket.unshift(head);
2418
- socket.on("close", socketOnClose);
2419
- socket.on("data", socketOnData);
2420
- socket.on("end", socketOnEnd);
2421
- socket.on("error", socketOnError);
2422
- this._readyState = WebSocket.OPEN;
2423
- this.emit("open");
2424
- }
2425
- /**
2426
- * Emit the `'close'` event.
2427
- *
2428
- * @private
2429
- */
2430
- emitClose() {
2431
- if (!this._socket) {
2432
- this._readyState = WebSocket.CLOSED;
2433
- this.emit("close", this._closeCode, this._closeMessage);
2434
- return;
2435
- }
2436
- if (this._extensions[PerMessageDeflate2.extensionName]) {
2437
- this._extensions[PerMessageDeflate2.extensionName].cleanup();
2438
- }
2439
- this._receiver.removeAllListeners();
2440
- this._readyState = WebSocket.CLOSED;
2441
- this.emit("close", this._closeCode, this._closeMessage);
2442
- }
2443
- /**
2444
- * Start a closing handshake.
2445
- *
2446
- * +----------+ +-----------+ +----------+
2447
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2448
- * | +----------+ +-----------+ +----------+ |
2449
- * +----------+ +-----------+ |
2450
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2451
- * +----------+ +-----------+ |
2452
- * | | | +---+ |
2453
- * +------------------------+-->|fin| - - - -
2454
- * | +---+ | +---+
2455
- * - - - - -|fin|<---------------------+
2456
- * +---+
2457
- *
2458
- * @param {Number} [code] Status code explaining why the connection is closing
2459
- * @param {(String|Buffer)} [data] The reason why the connection is
2460
- * closing
2461
- * @public
2462
- */
2463
- close(code, data) {
2464
- if (this.readyState === WebSocket.CLOSED) return;
2465
- if (this.readyState === WebSocket.CONNECTING) {
2466
- const msg = "WebSocket was closed before the connection was established";
2467
- abortHandshake(this, this._req, msg);
2468
- return;
2469
- }
2470
- if (this.readyState === WebSocket.CLOSING) {
2471
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2472
- this._socket.end();
2473
- }
2474
- return;
2475
- }
2476
- this._readyState = WebSocket.CLOSING;
2477
- this._sender.close(code, data, !this._isServer, (err) => {
2478
- if (err) return;
2479
- this._closeFrameSent = true;
2480
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2481
- this._socket.end();
2482
- }
2483
- });
2484
- this._closeTimer = setTimeout(
2485
- this._socket.destroy.bind(this._socket),
2486
- closeTimeout
2487
- );
2488
- }
2489
- /**
2490
- * Pause the socket.
2491
- *
2492
- * @public
2493
- */
2494
- pause() {
2495
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
2496
- return;
2497
- }
2498
- this._paused = true;
2499
- this._socket.pause();
2500
- }
2501
- /**
2502
- * Send a ping.
2503
- *
2504
- * @param {*} [data] The data to send
2505
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2506
- * @param {Function} [cb] Callback which is executed when the ping is sent
2507
- * @public
2508
- */
2509
- ping(data, mask2, cb) {
2510
- if (this.readyState === WebSocket.CONNECTING) {
2511
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2512
- }
2513
- if (typeof data === "function") {
2514
- cb = data;
2515
- data = mask2 = void 0;
2516
- } else if (typeof mask2 === "function") {
2517
- cb = mask2;
2518
- mask2 = void 0;
2519
- }
2520
- if (typeof data === "number") data = data.toString();
2521
- if (this.readyState !== WebSocket.OPEN) {
2522
- sendAfterClose(this, data, cb);
2523
- return;
2524
- }
2525
- if (mask2 === void 0) mask2 = !this._isServer;
2526
- this._sender.ping(data || EMPTY_BUFFER, mask2, cb);
2527
- }
2528
- /**
2529
- * Send a pong.
2530
- *
2531
- * @param {*} [data] The data to send
2532
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2533
- * @param {Function} [cb] Callback which is executed when the pong is sent
2534
- * @public
2535
- */
2536
- pong(data, mask2, cb) {
2537
- if (this.readyState === WebSocket.CONNECTING) {
2538
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2539
- }
2540
- if (typeof data === "function") {
2541
- cb = data;
2542
- data = mask2 = void 0;
2543
- } else if (typeof mask2 === "function") {
2544
- cb = mask2;
2545
- mask2 = void 0;
2546
- }
2547
- if (typeof data === "number") data = data.toString();
2548
- if (this.readyState !== WebSocket.OPEN) {
2549
- sendAfterClose(this, data, cb);
2550
- return;
2551
- }
2552
- if (mask2 === void 0) mask2 = !this._isServer;
2553
- this._sender.pong(data || EMPTY_BUFFER, mask2, cb);
2554
- }
2555
- /**
2556
- * Resume the socket.
2557
- *
2558
- * @public
2559
- */
2560
- resume() {
2561
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
2562
- return;
2563
- }
2564
- this._paused = false;
2565
- if (!this._receiver._writableState.needDrain) this._socket.resume();
2566
- }
2567
- /**
2568
- * Send a data message.
2569
- *
2570
- * @param {*} data The message to send
2571
- * @param {Object} [options] Options object
2572
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2573
- * text
2574
- * @param {Boolean} [options.compress] Specifies whether or not to compress
2575
- * `data`
2576
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2577
- * last one
2578
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2579
- * @param {Function} [cb] Callback which is executed when data is written out
2580
- * @public
2581
- */
2582
- send(data, options, cb) {
2583
- if (this.readyState === WebSocket.CONNECTING) {
2584
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2585
- }
2586
- if (typeof options === "function") {
2587
- cb = options;
2588
- options = {};
2589
- }
2590
- if (typeof data === "number") data = data.toString();
2591
- if (this.readyState !== WebSocket.OPEN) {
2592
- sendAfterClose(this, data, cb);
2593
- return;
2594
- }
2595
- const opts = {
2596
- binary: typeof data !== "string",
2597
- mask: !this._isServer,
2598
- compress: true,
2599
- fin: true,
2600
- ...options
2601
- };
2602
- if (!this._extensions[PerMessageDeflate2.extensionName]) {
2603
- opts.compress = false;
2604
- }
2605
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2606
- }
2607
- /**
2608
- * Forcibly close the connection.
2609
- *
2610
- * @public
2611
- */
2612
- terminate() {
2613
- if (this.readyState === WebSocket.CLOSED) return;
2614
- if (this.readyState === WebSocket.CONNECTING) {
2615
- const msg = "WebSocket was closed before the connection was established";
2616
- abortHandshake(this, this._req, msg);
2617
- return;
2618
- }
2619
- if (this._socket) {
2620
- this._readyState = WebSocket.CLOSING;
2621
- this._socket.destroy();
2622
- }
2623
- }
2624
- }
2625
- Object.defineProperty(WebSocket, "CONNECTING", {
2626
- enumerable: true,
2627
- value: readyStates.indexOf("CONNECTING")
2628
- });
2629
- Object.defineProperty(WebSocket.prototype, "CONNECTING", {
2630
- enumerable: true,
2631
- value: readyStates.indexOf("CONNECTING")
2632
- });
2633
- Object.defineProperty(WebSocket, "OPEN", {
2634
- enumerable: true,
2635
- value: readyStates.indexOf("OPEN")
2636
- });
2637
- Object.defineProperty(WebSocket.prototype, "OPEN", {
2638
- enumerable: true,
2639
- value: readyStates.indexOf("OPEN")
2640
- });
2641
- Object.defineProperty(WebSocket, "CLOSING", {
2642
- enumerable: true,
2643
- value: readyStates.indexOf("CLOSING")
2644
- });
2645
- Object.defineProperty(WebSocket.prototype, "CLOSING", {
2646
- enumerable: true,
2647
- value: readyStates.indexOf("CLOSING")
2648
- });
2649
- Object.defineProperty(WebSocket, "CLOSED", {
2650
- enumerable: true,
2651
- value: readyStates.indexOf("CLOSED")
2652
- });
2653
- Object.defineProperty(WebSocket.prototype, "CLOSED", {
2654
- enumerable: true,
2655
- value: readyStates.indexOf("CLOSED")
2656
- });
2657
- [
2658
- "binaryType",
2659
- "bufferedAmount",
2660
- "extensions",
2661
- "isPaused",
2662
- "protocol",
2663
- "readyState",
2664
- "url"
2665
- ].forEach((property) => {
2666
- Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
2667
- });
2668
- ["open", "error", "close", "message"].forEach((method) => {
2669
- Object.defineProperty(WebSocket.prototype, `on${method}`, {
2670
- enumerable: true,
2671
- get() {
2672
- for (const listener of this.listeners(method)) {
2673
- if (listener[kForOnEventAttribute]) return listener[kListener];
2674
- }
2675
- return null;
2676
- },
2677
- set(handler) {
2678
- for (const listener of this.listeners(method)) {
2679
- if (listener[kForOnEventAttribute]) {
2680
- this.removeListener(method, listener);
2681
- break;
2682
- }
2683
- }
2684
- if (typeof handler !== "function") return;
2685
- this.addEventListener(method, handler, {
2686
- [kForOnEventAttribute]: true
2687
- });
2688
- }
2689
- });
2690
- });
2691
- WebSocket.prototype.addEventListener = addEventListener;
2692
- WebSocket.prototype.removeEventListener = removeEventListener;
2693
- var websocket = WebSocket;
2694
- function initAsClient(websocket2, address, protocols, options) {
2695
- const opts = {
2696
- protocolVersion: protocolVersions[1],
2697
- maxPayload: 100 * 1024 * 1024,
2698
- skipUTF8Validation: false,
2699
- perMessageDeflate: true,
2700
- followRedirects: false,
2701
- maxRedirects: 10,
2702
- ...options,
2703
- createConnection: void 0,
2704
- socketPath: void 0,
2705
- hostname: void 0,
2706
- protocol: void 0,
2707
- timeout: void 0,
2708
- method: "GET",
2709
- host: void 0,
2710
- path: void 0,
2711
- port: void 0
2712
- };
2713
- if (!protocolVersions.includes(opts.protocolVersion)) {
2714
- throw new RangeError(
2715
- `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2716
- );
2717
- }
2718
- let parsedUrl;
2719
- if (address instanceof URL) {
2720
- parsedUrl = address;
2721
- websocket2._url = address.href;
2722
- } else {
2723
- try {
2724
- parsedUrl = new URL(address);
2725
- } catch (e) {
2726
- throw new SyntaxError(`Invalid URL: ${address}`);
2727
- }
2728
- websocket2._url = address;
2729
- }
2730
- const isSecure = parsedUrl.protocol === "wss:";
2731
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2732
- let invalidUrlMessage;
2733
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2734
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", or "ws+unix:"`;
2735
- } else if (isIpcUrl && !parsedUrl.pathname) {
2736
- invalidUrlMessage = "The URL's pathname is empty";
2737
- } else if (parsedUrl.hash) {
2738
- invalidUrlMessage = "The URL contains a fragment identifier";
2739
- }
2740
- if (invalidUrlMessage) {
2741
- const err = new SyntaxError(invalidUrlMessage);
2742
- if (websocket2._redirects === 0) {
2743
- throw err;
2744
- } else {
2745
- emitErrorAndClose(websocket2, err);
2746
- return;
2747
- }
2748
- }
2749
- const defaultPort = isSecure ? 443 : 80;
2750
- const key = randomBytes(16).toString("base64");
2751
- const request = isSecure ? https.request : http.request;
2752
- const protocolSet = /* @__PURE__ */ new Set();
2753
- let perMessageDeflate;
2754
- opts.createConnection = isSecure ? tlsConnect : netConnect;
2755
- opts.defaultPort = opts.defaultPort || defaultPort;
2756
- opts.port = parsedUrl.port || defaultPort;
2757
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2758
- opts.headers = {
2759
- ...opts.headers,
2760
- "Sec-WebSocket-Version": opts.protocolVersion,
2761
- "Sec-WebSocket-Key": key,
2762
- Connection: "Upgrade",
2763
- Upgrade: "websocket"
2764
- };
2765
- opts.path = parsedUrl.pathname + parsedUrl.search;
2766
- opts.timeout = opts.handshakeTimeout;
2767
- if (opts.perMessageDeflate) {
2768
- perMessageDeflate = new PerMessageDeflate2(
2769
- opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2770
- false,
2771
- opts.maxPayload
2772
- );
2773
- opts.headers["Sec-WebSocket-Extensions"] = format({
2774
- [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2775
- });
2776
- }
2777
- if (protocols.length) {
2778
- for (const protocol of protocols) {
2779
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2780
- throw new SyntaxError(
2781
- "An invalid or duplicated subprotocol was specified"
2782
- );
2783
- }
2784
- protocolSet.add(protocol);
2785
- }
2786
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2787
- }
2788
- if (opts.origin) {
2789
- if (opts.protocolVersion < 13) {
2790
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2791
- } else {
2792
- opts.headers.Origin = opts.origin;
2793
- }
2794
- }
2795
- if (parsedUrl.username || parsedUrl.password) {
2796
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2797
- }
2798
- if (isIpcUrl) {
2799
- const parts = opts.path.split(":");
2800
- opts.socketPath = parts[0];
2801
- opts.path = parts[1];
2802
- }
2803
- let req;
2804
- if (opts.followRedirects) {
2805
- if (websocket2._redirects === 0) {
2806
- websocket2._originalIpc = isIpcUrl;
2807
- websocket2._originalSecure = isSecure;
2808
- websocket2._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2809
- const headers = options && options.headers;
2810
- options = { ...options, headers: {} };
2811
- if (headers) {
2812
- for (const [key2, value] of Object.entries(headers)) {
2813
- options.headers[key2.toLowerCase()] = value;
2814
- }
2815
- }
2816
- } else if (websocket2.listenerCount("redirect") === 0) {
2817
- const isSameHost = isIpcUrl ? websocket2._originalIpc ? opts.socketPath === websocket2._originalHostOrSocketPath : false : websocket2._originalIpc ? false : parsedUrl.host === websocket2._originalHostOrSocketPath;
2818
- if (!isSameHost || websocket2._originalSecure && !isSecure) {
2819
- delete opts.headers.authorization;
2820
- delete opts.headers.cookie;
2821
- if (!isSameHost) delete opts.headers.host;
2822
- opts.auth = void 0;
2823
- }
2824
- }
2825
- if (opts.auth && !options.headers.authorization) {
2826
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2827
- }
2828
- req = websocket2._req = request(opts);
2829
- if (websocket2._redirects) {
2830
- websocket2.emit("redirect", websocket2.url, req);
2831
- }
2832
- } else {
2833
- req = websocket2._req = request(opts);
2834
- }
2835
- if (opts.timeout) {
2836
- req.on("timeout", () => {
2837
- abortHandshake(websocket2, req, "Opening handshake has timed out");
2838
- });
2839
- }
2840
- req.on("error", (err) => {
2841
- if (req === null || req[kAborted]) return;
2842
- req = websocket2._req = null;
2843
- emitErrorAndClose(websocket2, err);
2844
- });
2845
- req.on("response", (res) => {
2846
- const location = res.headers.location;
2847
- const statusCode = res.statusCode;
2848
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2849
- if (++websocket2._redirects > opts.maxRedirects) {
2850
- abortHandshake(websocket2, req, "Maximum redirects exceeded");
2851
- return;
2852
- }
2853
- req.abort();
2854
- let addr;
2855
- try {
2856
- addr = new URL(location, address);
2857
- } catch (e) {
2858
- const err = new SyntaxError(`Invalid URL: ${location}`);
2859
- emitErrorAndClose(websocket2, err);
2860
- return;
2861
- }
2862
- initAsClient(websocket2, addr, protocols, options);
2863
- } else if (!websocket2.emit("unexpected-response", req, res)) {
2864
- abortHandshake(
2865
- websocket2,
2866
- req,
2867
- `Unexpected server response: ${res.statusCode}`
2868
- );
2869
- }
2870
- });
2871
- req.on("upgrade", (res, socket, head) => {
2872
- websocket2.emit("upgrade", res);
2873
- if (websocket2.readyState !== WebSocket.CONNECTING) return;
2874
- req = websocket2._req = null;
2875
- if (res.headers.upgrade.toLowerCase() !== "websocket") {
2876
- abortHandshake(websocket2, socket, "Invalid Upgrade header");
2877
- return;
2878
- }
2879
- const digest = createHash$1("sha1").update(key + GUID$1).digest("base64");
2880
- if (res.headers["sec-websocket-accept"] !== digest) {
2881
- abortHandshake(websocket2, socket, "Invalid Sec-WebSocket-Accept header");
2882
- return;
2883
- }
2884
- const serverProt = res.headers["sec-websocket-protocol"];
2885
- let protError;
2886
- if (serverProt !== void 0) {
2887
- if (!protocolSet.size) {
2888
- protError = "Server sent a subprotocol but none was requested";
2889
- } else if (!protocolSet.has(serverProt)) {
2890
- protError = "Server sent an invalid subprotocol";
2891
- }
2892
- } else if (protocolSet.size) {
2893
- protError = "Server sent no subprotocol";
2894
- }
2895
- if (protError) {
2896
- abortHandshake(websocket2, socket, protError);
2897
- return;
2898
- }
2899
- if (serverProt) websocket2._protocol = serverProt;
2900
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2901
- if (secWebSocketExtensions !== void 0) {
2902
- if (!perMessageDeflate) {
2903
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2904
- abortHandshake(websocket2, socket, message);
2905
- return;
2906
- }
2907
- let extensions;
2908
- try {
2909
- extensions = parse(secWebSocketExtensions);
2910
- } catch (err) {
2911
- const message = "Invalid Sec-WebSocket-Extensions header";
2912
- abortHandshake(websocket2, socket, message);
2913
- return;
2914
- }
2915
- const extensionNames = Object.keys(extensions);
2916
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2917
- const message = "Server indicated an extension that was not requested";
2918
- abortHandshake(websocket2, socket, message);
2919
- return;
2920
- }
2921
- try {
2922
- perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2923
- } catch (err) {
2924
- const message = "Invalid Sec-WebSocket-Extensions header";
2925
- abortHandshake(websocket2, socket, message);
2926
- return;
2927
- }
2928
- websocket2._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
2929
- }
2930
- websocket2.setSocket(socket, head, {
2931
- generateMask: opts.generateMask,
2932
- maxPayload: opts.maxPayload,
2933
- skipUTF8Validation: opts.skipUTF8Validation
2934
- });
2935
- });
2936
- if (opts.finishRequest) {
2937
- opts.finishRequest(req, websocket2);
2938
- } else {
2939
- req.end();
2940
- }
2941
- }
2942
- function emitErrorAndClose(websocket2, err) {
2943
- websocket2._readyState = WebSocket.CLOSING;
2944
- websocket2.emit("error", err);
2945
- websocket2.emitClose();
2946
- }
2947
- function netConnect(options) {
2948
- options.path = options.socketPath;
2949
- return net.connect(options);
2950
- }
2951
- function tlsConnect(options) {
2952
- options.path = void 0;
2953
- if (!options.servername && options.servername !== "") {
2954
- options.servername = net.isIP(options.host) ? "" : options.host;
2955
- }
2956
- return tls.connect(options);
2957
- }
2958
- function abortHandshake(websocket2, stream, message) {
2959
- websocket2._readyState = WebSocket.CLOSING;
2960
- const err = new Error(message);
2961
- Error.captureStackTrace(err, abortHandshake);
2962
- if (stream.setHeader) {
2963
- stream[kAborted] = true;
2964
- stream.abort();
2965
- if (stream.socket && !stream.socket.destroyed) {
2966
- stream.socket.destroy();
2967
- }
2968
- process.nextTick(emitErrorAndClose, websocket2, err);
2969
- } else {
2970
- stream.destroy(err);
2971
- stream.once("error", websocket2.emit.bind(websocket2, "error"));
2972
- stream.once("close", websocket2.emitClose.bind(websocket2));
2973
- }
2974
- }
2975
- function sendAfterClose(websocket2, data, cb) {
2976
- if (data) {
2977
- const length = toBuffer(data).length;
2978
- if (websocket2._socket) websocket2._sender._bufferedBytes += length;
2979
- else websocket2._bufferedAmount += length;
2980
- }
2981
- if (cb) {
2982
- const err = new Error(
2983
- `WebSocket is not open: readyState ${websocket2.readyState} (${readyStates[websocket2.readyState]})`
2984
- );
2985
- process.nextTick(cb, err);
2986
- }
2987
- }
2988
- function receiverOnConclude(code, reason) {
2989
- const websocket2 = this[kWebSocket$1];
2990
- websocket2._closeFrameReceived = true;
2991
- websocket2._closeMessage = reason;
2992
- websocket2._closeCode = code;
2993
- if (websocket2._socket[kWebSocket$1] === void 0) return;
2994
- websocket2._socket.removeListener("data", socketOnData);
2995
- process.nextTick(resume, websocket2._socket);
2996
- if (code === 1005) websocket2.close();
2997
- else websocket2.close(code, reason);
2998
- }
2999
- function receiverOnDrain() {
3000
- const websocket2 = this[kWebSocket$1];
3001
- if (!websocket2.isPaused) websocket2._socket.resume();
3002
- }
3003
- function receiverOnError(err) {
3004
- const websocket2 = this[kWebSocket$1];
3005
- if (websocket2._socket[kWebSocket$1] !== void 0) {
3006
- websocket2._socket.removeListener("data", socketOnData);
3007
- process.nextTick(resume, websocket2._socket);
3008
- websocket2.close(err[kStatusCode]);
3009
- }
3010
- websocket2.emit("error", err);
3011
- }
3012
- function receiverOnFinish() {
3013
- this[kWebSocket$1].emitClose();
3014
- }
3015
- function receiverOnMessage(data, isBinary) {
3016
- this[kWebSocket$1].emit("message", data, isBinary);
3017
- }
3018
- function receiverOnPing(data) {
3019
- const websocket2 = this[kWebSocket$1];
3020
- websocket2.pong(data, !websocket2._isServer, NOOP);
3021
- websocket2.emit("ping", data);
3022
- }
3023
- function receiverOnPong(data) {
3024
- this[kWebSocket$1].emit("pong", data);
3025
- }
3026
- function resume(stream) {
3027
- stream.resume();
3028
- }
3029
- function socketOnClose() {
3030
- const websocket2 = this[kWebSocket$1];
3031
- this.removeListener("close", socketOnClose);
3032
- this.removeListener("data", socketOnData);
3033
- this.removeListener("end", socketOnEnd);
3034
- websocket2._readyState = WebSocket.CLOSING;
3035
- let chunk;
3036
- if (!this._readableState.endEmitted && !websocket2._closeFrameReceived && !websocket2._receiver._writableState.errorEmitted && (chunk = websocket2._socket.read()) !== null) {
3037
- websocket2._receiver.write(chunk);
3038
- }
3039
- websocket2._receiver.end();
3040
- this[kWebSocket$1] = void 0;
3041
- clearTimeout(websocket2._closeTimer);
3042
- if (websocket2._receiver._writableState.finished || websocket2._receiver._writableState.errorEmitted) {
3043
- websocket2.emitClose();
3044
- } else {
3045
- websocket2._receiver.on("error", receiverOnFinish);
3046
- websocket2._receiver.on("finish", receiverOnFinish);
3047
- }
3048
- }
3049
- function socketOnData(chunk) {
3050
- if (!this[kWebSocket$1]._receiver.write(chunk)) {
3051
- this.pause();
3052
- }
3053
- }
3054
- function socketOnEnd() {
3055
- const websocket2 = this[kWebSocket$1];
3056
- websocket2._readyState = WebSocket.CLOSING;
3057
- websocket2._receiver.end();
3058
- this.end();
3059
- }
3060
- function socketOnError() {
3061
- const websocket2 = this[kWebSocket$1];
3062
- this.removeListener("error", socketOnError);
3063
- this.on("error", NOOP);
3064
- if (websocket2) {
3065
- websocket2._readyState = WebSocket.CLOSING;
3066
- this.destroy();
3067
- }
3068
- }
3069
- const WebSocket$1 = /* @__PURE__ */ getDefaultExportFromCjs(websocket);
3070
- const { tokenChars } = validationExports;
3071
- const { createHash } = require$$5;
3072
- const { GUID, kWebSocket } = constants;
3073
- export {
3074
- WebSocket$1 as WebSocket,
3075
- WebSocket$1 as default
3076
- };