@blinkdotnew/dev-sdk 2.3.4-dev.1 → 2.3.10

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