@blinkdotnew/sdk 2.5.1 → 2.6.1

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.js CHANGED
@@ -1,3726 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
3
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
4
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
5
  }) : x)(function(x) {
7
- if (typeof require !== "undefined")
8
- return require.apply(this, arguments);
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
9
7
  throw Error('Dynamic require of "' + x + '" is not supported');
10
8
  });
11
- var __commonJS = (cb, mod) => function __require2() {
12
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
- };
14
-
15
- // ../../../node_modules/ws/lib/constants.js
16
- var require_constants = __commonJS({
17
- "../../../node_modules/ws/lib/constants.js"(exports$1, module) {
18
- var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
19
- var hasBlob = typeof Blob !== "undefined";
20
- if (hasBlob)
21
- BINARY_TYPES.push("blob");
22
- module.exports = {
23
- BINARY_TYPES,
24
- CLOSE_TIMEOUT: 3e4,
25
- EMPTY_BUFFER: Buffer.alloc(0),
26
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
27
- hasBlob,
28
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
29
- kListener: Symbol("kListener"),
30
- kStatusCode: Symbol("status-code"),
31
- kWebSocket: Symbol("websocket"),
32
- NOOP: () => {
33
- }
34
- };
35
- }
36
- });
37
-
38
- // ../../../node_modules/ws/lib/buffer-util.js
39
- var require_buffer_util = __commonJS({
40
- "../../../node_modules/ws/lib/buffer-util.js"(exports$1, module) {
41
- var { EMPTY_BUFFER } = require_constants();
42
- var FastBuffer = Buffer[Symbol.species];
43
- function concat(list, totalLength) {
44
- if (list.length === 0)
45
- return EMPTY_BUFFER;
46
- if (list.length === 1)
47
- return list[0];
48
- const target = Buffer.allocUnsafe(totalLength);
49
- let offset = 0;
50
- for (let i = 0; i < list.length; i++) {
51
- const buf = list[i];
52
- target.set(buf, offset);
53
- offset += buf.length;
54
- }
55
- if (offset < totalLength) {
56
- return new FastBuffer(target.buffer, target.byteOffset, offset);
57
- }
58
- return target;
59
- }
60
- function _mask(source, mask, output, offset, length) {
61
- for (let i = 0; i < length; i++) {
62
- output[offset + i] = source[i] ^ mask[i & 3];
63
- }
64
- }
65
- function _unmask(buffer, mask) {
66
- for (let i = 0; i < buffer.length; i++) {
67
- buffer[i] ^= mask[i & 3];
68
- }
69
- }
70
- function toArrayBuffer(buf) {
71
- if (buf.length === buf.buffer.byteLength) {
72
- return buf.buffer;
73
- }
74
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
75
- }
76
- function toBuffer(data) {
77
- toBuffer.readOnly = true;
78
- if (Buffer.isBuffer(data))
79
- return data;
80
- let buf;
81
- if (data instanceof ArrayBuffer) {
82
- buf = new FastBuffer(data);
83
- } else if (ArrayBuffer.isView(data)) {
84
- buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
85
- } else {
86
- buf = Buffer.from(data);
87
- toBuffer.readOnly = false;
88
- }
89
- return buf;
90
- }
91
- module.exports = {
92
- concat,
93
- mask: _mask,
94
- toArrayBuffer,
95
- toBuffer,
96
- unmask: _unmask
97
- };
98
- if (!process.env.WS_NO_BUFFER_UTIL) {
99
- try {
100
- const bufferUtil = __require("bufferutil");
101
- module.exports.mask = function(source, mask, output, offset, length) {
102
- if (length < 48)
103
- _mask(source, mask, output, offset, length);
104
- else
105
- bufferUtil.mask(source, mask, output, offset, length);
106
- };
107
- module.exports.unmask = function(buffer, mask) {
108
- if (buffer.length < 32)
109
- _unmask(buffer, mask);
110
- else
111
- bufferUtil.unmask(buffer, mask);
112
- };
113
- } catch (e) {
114
- }
115
- }
116
- }
117
- });
118
-
119
- // ../../../node_modules/ws/lib/limiter.js
120
- var require_limiter = __commonJS({
121
- "../../../node_modules/ws/lib/limiter.js"(exports$1, module) {
122
- var kDone = Symbol("kDone");
123
- var kRun = Symbol("kRun");
124
- var Limiter = class {
125
- /**
126
- * Creates a new `Limiter`.
127
- *
128
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
129
- * to run concurrently
130
- */
131
- constructor(concurrency) {
132
- this[kDone] = () => {
133
- this.pending--;
134
- this[kRun]();
135
- };
136
- this.concurrency = concurrency || Infinity;
137
- this.jobs = [];
138
- this.pending = 0;
139
- }
140
- /**
141
- * Adds a job to the queue.
142
- *
143
- * @param {Function} job The job to run
144
- * @public
145
- */
146
- add(job) {
147
- this.jobs.push(job);
148
- this[kRun]();
149
- }
150
- /**
151
- * Removes a job from the queue and runs it if possible.
152
- *
153
- * @private
154
- */
155
- [kRun]() {
156
- if (this.pending === this.concurrency)
157
- return;
158
- if (this.jobs.length) {
159
- const job = this.jobs.shift();
160
- this.pending++;
161
- job(this[kDone]);
162
- }
163
- }
164
- };
165
- module.exports = Limiter;
166
- }
167
- });
168
-
169
- // ../../../node_modules/ws/lib/permessage-deflate.js
170
- var require_permessage_deflate = __commonJS({
171
- "../../../node_modules/ws/lib/permessage-deflate.js"(exports$1, module) {
172
- var zlib = __require("zlib");
173
- var bufferUtil = require_buffer_util();
174
- var Limiter = require_limiter();
175
- var { kStatusCode } = require_constants();
176
- var FastBuffer = Buffer[Symbol.species];
177
- var TRAILER = Buffer.from([0, 0, 255, 255]);
178
- var kPerMessageDeflate = Symbol("permessage-deflate");
179
- var kTotalLength = Symbol("total-length");
180
- var kCallback = Symbol("callback");
181
- var kBuffers = Symbol("buffers");
182
- var kError = Symbol("error");
183
- var zlibLimiter;
184
- var PerMessageDeflate = class {
185
- /**
186
- * Creates a PerMessageDeflate instance.
187
- *
188
- * @param {Object} [options] Configuration options
189
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
190
- * for, or request, a custom client window size
191
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
192
- * acknowledge disabling of client context takeover
193
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
194
- * calls to zlib
195
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
196
- * use of a custom server window size
197
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
198
- * disabling of server context takeover
199
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
200
- * messages should not be compressed if context takeover is disabled
201
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
202
- * deflate
203
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
204
- * inflate
205
- * @param {Boolean} [isServer=false] Create the instance in either server or
206
- * client mode
207
- * @param {Number} [maxPayload=0] The maximum allowed message length
208
- */
209
- constructor(options, isServer2, maxPayload) {
210
- this._maxPayload = maxPayload | 0;
211
- this._options = options || {};
212
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
213
- this._isServer = !!isServer2;
214
- this._deflate = null;
215
- this._inflate = null;
216
- this.params = null;
217
- if (!zlibLimiter) {
218
- const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
219
- zlibLimiter = new Limiter(concurrency);
220
- }
221
- }
222
- /**
223
- * @type {String}
224
- */
225
- static get extensionName() {
226
- return "permessage-deflate";
227
- }
228
- /**
229
- * Create an extension negotiation offer.
230
- *
231
- * @return {Object} Extension parameters
232
- * @public
233
- */
234
- offer() {
235
- const params = {};
236
- if (this._options.serverNoContextTakeover) {
237
- params.server_no_context_takeover = true;
238
- }
239
- if (this._options.clientNoContextTakeover) {
240
- params.client_no_context_takeover = true;
241
- }
242
- if (this._options.serverMaxWindowBits) {
243
- params.server_max_window_bits = this._options.serverMaxWindowBits;
244
- }
245
- if (this._options.clientMaxWindowBits) {
246
- params.client_max_window_bits = this._options.clientMaxWindowBits;
247
- } else if (this._options.clientMaxWindowBits == null) {
248
- params.client_max_window_bits = true;
249
- }
250
- return params;
251
- }
252
- /**
253
- * Accept an extension negotiation offer/response.
254
- *
255
- * @param {Array} configurations The extension negotiation offers/reponse
256
- * @return {Object} Accepted configuration
257
- * @public
258
- */
259
- accept(configurations) {
260
- configurations = this.normalizeParams(configurations);
261
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
262
- return this.params;
263
- }
264
- /**
265
- * Releases all resources used by the extension.
266
- *
267
- * @public
268
- */
269
- cleanup() {
270
- if (this._inflate) {
271
- this._inflate.close();
272
- this._inflate = null;
273
- }
274
- if (this._deflate) {
275
- const callback = this._deflate[kCallback];
276
- this._deflate.close();
277
- this._deflate = null;
278
- if (callback) {
279
- callback(
280
- new Error(
281
- "The deflate stream was closed while data was being processed"
282
- )
283
- );
284
- }
285
- }
286
- }
287
- /**
288
- * Accept an extension negotiation offer.
289
- *
290
- * @param {Array} offers The extension negotiation offers
291
- * @return {Object} Accepted configuration
292
- * @private
293
- */
294
- acceptAsServer(offers) {
295
- const opts = this._options;
296
- const accepted = offers.find((params) => {
297
- 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) {
298
- return false;
299
- }
300
- return true;
301
- });
302
- if (!accepted) {
303
- throw new Error("None of the extension offers can be accepted");
304
- }
305
- if (opts.serverNoContextTakeover) {
306
- accepted.server_no_context_takeover = true;
307
- }
308
- if (opts.clientNoContextTakeover) {
309
- accepted.client_no_context_takeover = true;
310
- }
311
- if (typeof opts.serverMaxWindowBits === "number") {
312
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
313
- }
314
- if (typeof opts.clientMaxWindowBits === "number") {
315
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
316
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
317
- delete accepted.client_max_window_bits;
318
- }
319
- return accepted;
320
- }
321
- /**
322
- * Accept the extension negotiation response.
323
- *
324
- * @param {Array} response The extension negotiation response
325
- * @return {Object} Accepted configuration
326
- * @private
327
- */
328
- acceptAsClient(response) {
329
- const params = response[0];
330
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
331
- throw new Error('Unexpected parameter "client_no_context_takeover"');
332
- }
333
- if (!params.client_max_window_bits) {
334
- if (typeof this._options.clientMaxWindowBits === "number") {
335
- params.client_max_window_bits = this._options.clientMaxWindowBits;
336
- }
337
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
338
- throw new Error(
339
- 'Unexpected or invalid parameter "client_max_window_bits"'
340
- );
341
- }
342
- return params;
343
- }
344
- /**
345
- * Normalize parameters.
346
- *
347
- * @param {Array} configurations The extension negotiation offers/reponse
348
- * @return {Array} The offers/response with normalized parameters
349
- * @private
350
- */
351
- normalizeParams(configurations) {
352
- configurations.forEach((params) => {
353
- Object.keys(params).forEach((key) => {
354
- let value = params[key];
355
- if (value.length > 1) {
356
- throw new Error(`Parameter "${key}" must have only a single value`);
357
- }
358
- value = value[0];
359
- if (key === "client_max_window_bits") {
360
- if (value !== true) {
361
- const num = +value;
362
- if (!Number.isInteger(num) || num < 8 || num > 15) {
363
- throw new TypeError(
364
- `Invalid value for parameter "${key}": ${value}`
365
- );
366
- }
367
- value = num;
368
- } else if (!this._isServer) {
369
- throw new TypeError(
370
- `Invalid value for parameter "${key}": ${value}`
371
- );
372
- }
373
- } else if (key === "server_max_window_bits") {
374
- const num = +value;
375
- if (!Number.isInteger(num) || num < 8 || num > 15) {
376
- throw new TypeError(
377
- `Invalid value for parameter "${key}": ${value}`
378
- );
379
- }
380
- value = num;
381
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
382
- if (value !== true) {
383
- throw new TypeError(
384
- `Invalid value for parameter "${key}": ${value}`
385
- );
386
- }
387
- } else {
388
- throw new Error(`Unknown parameter "${key}"`);
389
- }
390
- params[key] = value;
391
- });
392
- });
393
- return configurations;
394
- }
395
- /**
396
- * Decompress data. Concurrency limited.
397
- *
398
- * @param {Buffer} data Compressed data
399
- * @param {Boolean} fin Specifies whether or not this is the last fragment
400
- * @param {Function} callback Callback
401
- * @public
402
- */
403
- decompress(data, fin, callback) {
404
- zlibLimiter.add((done) => {
405
- this._decompress(data, fin, (err, result) => {
406
- done();
407
- callback(err, result);
408
- });
409
- });
410
- }
411
- /**
412
- * Compress data. Concurrency limited.
413
- *
414
- * @param {(Buffer|String)} data Data to compress
415
- * @param {Boolean} fin Specifies whether or not this is the last fragment
416
- * @param {Function} callback Callback
417
- * @public
418
- */
419
- compress(data, fin, callback) {
420
- zlibLimiter.add((done) => {
421
- this._compress(data, fin, (err, result) => {
422
- done();
423
- callback(err, result);
424
- });
425
- });
426
- }
427
- /**
428
- * Decompress data.
429
- *
430
- * @param {Buffer} data Compressed data
431
- * @param {Boolean} fin Specifies whether or not this is the last fragment
432
- * @param {Function} callback Callback
433
- * @private
434
- */
435
- _decompress(data, fin, callback) {
436
- const endpoint = this._isServer ? "client" : "server";
437
- if (!this._inflate) {
438
- const key = `${endpoint}_max_window_bits`;
439
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
440
- this._inflate = zlib.createInflateRaw({
441
- ...this._options.zlibInflateOptions,
442
- windowBits
443
- });
444
- this._inflate[kPerMessageDeflate] = this;
445
- this._inflate[kTotalLength] = 0;
446
- this._inflate[kBuffers] = [];
447
- this._inflate.on("error", inflateOnError);
448
- this._inflate.on("data", inflateOnData);
449
- }
450
- this._inflate[kCallback] = callback;
451
- this._inflate.write(data);
452
- if (fin)
453
- this._inflate.write(TRAILER);
454
- this._inflate.flush(() => {
455
- const err = this._inflate[kError];
456
- if (err) {
457
- this._inflate.close();
458
- this._inflate = null;
459
- callback(err);
460
- return;
461
- }
462
- const data2 = bufferUtil.concat(
463
- this._inflate[kBuffers],
464
- this._inflate[kTotalLength]
465
- );
466
- if (this._inflate._readableState.endEmitted) {
467
- this._inflate.close();
468
- this._inflate = null;
469
- } else {
470
- this._inflate[kTotalLength] = 0;
471
- this._inflate[kBuffers] = [];
472
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
473
- this._inflate.reset();
474
- }
475
- }
476
- callback(null, data2);
477
- });
478
- }
479
- /**
480
- * Compress data.
481
- *
482
- * @param {(Buffer|String)} data Data to compress
483
- * @param {Boolean} fin Specifies whether or not this is the last fragment
484
- * @param {Function} callback Callback
485
- * @private
486
- */
487
- _compress(data, fin, callback) {
488
- const endpoint = this._isServer ? "server" : "client";
489
- if (!this._deflate) {
490
- const key = `${endpoint}_max_window_bits`;
491
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
492
- this._deflate = zlib.createDeflateRaw({
493
- ...this._options.zlibDeflateOptions,
494
- windowBits
495
- });
496
- this._deflate[kTotalLength] = 0;
497
- this._deflate[kBuffers] = [];
498
- this._deflate.on("data", deflateOnData);
499
- }
500
- this._deflate[kCallback] = callback;
501
- this._deflate.write(data);
502
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
503
- if (!this._deflate) {
504
- return;
505
- }
506
- let data2 = bufferUtil.concat(
507
- this._deflate[kBuffers],
508
- this._deflate[kTotalLength]
509
- );
510
- if (fin) {
511
- data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
512
- }
513
- this._deflate[kCallback] = null;
514
- this._deflate[kTotalLength] = 0;
515
- this._deflate[kBuffers] = [];
516
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
517
- this._deflate.reset();
518
- }
519
- callback(null, data2);
520
- });
521
- }
522
- };
523
- module.exports = PerMessageDeflate;
524
- function deflateOnData(chunk) {
525
- this[kBuffers].push(chunk);
526
- this[kTotalLength] += chunk.length;
527
- }
528
- function inflateOnData(chunk) {
529
- this[kTotalLength] += chunk.length;
530
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
531
- this[kBuffers].push(chunk);
532
- return;
533
- }
534
- this[kError] = new RangeError("Max payload size exceeded");
535
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
536
- this[kError][kStatusCode] = 1009;
537
- this.removeListener("data", inflateOnData);
538
- this.reset();
539
- }
540
- function inflateOnError(err) {
541
- this[kPerMessageDeflate]._inflate = null;
542
- if (this[kError]) {
543
- this[kCallback](this[kError]);
544
- return;
545
- }
546
- err[kStatusCode] = 1007;
547
- this[kCallback](err);
548
- }
549
- }
550
- });
551
-
552
- // ../../../node_modules/ws/lib/validation.js
553
- var require_validation = __commonJS({
554
- "../../../node_modules/ws/lib/validation.js"(exports$1, module) {
555
- var { isUtf8 } = __require("buffer");
556
- var { hasBlob } = require_constants();
557
- var tokenChars = [
558
- 0,
559
- 0,
560
- 0,
561
- 0,
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 - 15
575
- 0,
576
- 0,
577
- 0,
578
- 0,
579
- 0,
580
- 0,
581
- 0,
582
- 0,
583
- 0,
584
- 0,
585
- 0,
586
- 0,
587
- 0,
588
- 0,
589
- 0,
590
- 0,
591
- // 16 - 31
592
- 0,
593
- 1,
594
- 0,
595
- 1,
596
- 1,
597
- 1,
598
- 1,
599
- 1,
600
- 0,
601
- 0,
602
- 1,
603
- 1,
604
- 0,
605
- 1,
606
- 1,
607
- 0,
608
- // 32 - 47
609
- 1,
610
- 1,
611
- 1,
612
- 1,
613
- 1,
614
- 1,
615
- 1,
616
- 1,
617
- 1,
618
- 1,
619
- 0,
620
- 0,
621
- 0,
622
- 0,
623
- 0,
624
- 0,
625
- // 48 - 63
626
- 0,
627
- 1,
628
- 1,
629
- 1,
630
- 1,
631
- 1,
632
- 1,
633
- 1,
634
- 1,
635
- 1,
636
- 1,
637
- 1,
638
- 1,
639
- 1,
640
- 1,
641
- 1,
642
- // 64 - 79
643
- 1,
644
- 1,
645
- 1,
646
- 1,
647
- 1,
648
- 1,
649
- 1,
650
- 1,
651
- 1,
652
- 1,
653
- 1,
654
- 0,
655
- 0,
656
- 0,
657
- 1,
658
- 1,
659
- // 80 - 95
660
- 1,
661
- 1,
662
- 1,
663
- 1,
664
- 1,
665
- 1,
666
- 1,
667
- 1,
668
- 1,
669
- 1,
670
- 1,
671
- 1,
672
- 1,
673
- 1,
674
- 1,
675
- 1,
676
- // 96 - 111
677
- 1,
678
- 1,
679
- 1,
680
- 1,
681
- 1,
682
- 1,
683
- 1,
684
- 1,
685
- 1,
686
- 1,
687
- 1,
688
- 0,
689
- 1,
690
- 0,
691
- 1,
692
- 0
693
- // 112 - 127
694
- ];
695
- function isValidStatusCode(code) {
696
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
697
- }
698
- function _isValidUTF8(buf) {
699
- const len = buf.length;
700
- let i = 0;
701
- while (i < len) {
702
- if ((buf[i] & 128) === 0) {
703
- i++;
704
- } else if ((buf[i] & 224) === 192) {
705
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
706
- return false;
707
- }
708
- i += 2;
709
- } else if ((buf[i] & 240) === 224) {
710
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
711
- buf[i] === 237 && (buf[i + 1] & 224) === 160) {
712
- return false;
713
- }
714
- i += 3;
715
- } else if ((buf[i] & 248) === 240) {
716
- 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
717
- buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
718
- return false;
719
- }
720
- i += 4;
721
- } else {
722
- return false;
723
- }
724
- }
725
- return true;
726
- }
727
- function isBlob(value) {
728
- 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");
729
- }
730
- module.exports = {
731
- isBlob,
732
- isValidStatusCode,
733
- isValidUTF8: _isValidUTF8,
734
- tokenChars
735
- };
736
- if (isUtf8) {
737
- module.exports.isValidUTF8 = function(buf) {
738
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
739
- };
740
- } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
741
- try {
742
- const isValidUTF8 = __require("utf-8-validate");
743
- module.exports.isValidUTF8 = function(buf) {
744
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
745
- };
746
- } catch (e) {
747
- }
748
- }
749
- }
750
- });
751
-
752
- // ../../../node_modules/ws/lib/receiver.js
753
- var require_receiver = __commonJS({
754
- "../../../node_modules/ws/lib/receiver.js"(exports$1, module) {
755
- var { Writable } = __require("stream");
756
- var PerMessageDeflate = require_permessage_deflate();
757
- var {
758
- BINARY_TYPES,
759
- EMPTY_BUFFER,
760
- kStatusCode,
761
- kWebSocket
762
- } = require_constants();
763
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
764
- var { isValidStatusCode, isValidUTF8 } = require_validation();
765
- var FastBuffer = Buffer[Symbol.species];
766
- var GET_INFO = 0;
767
- var GET_PAYLOAD_LENGTH_16 = 1;
768
- var GET_PAYLOAD_LENGTH_64 = 2;
769
- var GET_MASK = 3;
770
- var GET_DATA = 4;
771
- var INFLATING = 5;
772
- var DEFER_EVENT = 6;
773
- var Receiver = class extends Writable {
774
- /**
775
- * Creates a Receiver instance.
776
- *
777
- * @param {Object} [options] Options object
778
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
779
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
780
- * multiple times in the same tick
781
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
782
- * @param {Object} [options.extensions] An object containing the negotiated
783
- * extensions
784
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
785
- * client or server mode
786
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
787
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
788
- * not to skip UTF-8 validation for text and close messages
789
- */
790
- constructor(options = {}) {
791
- super();
792
- this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
793
- this._binaryType = options.binaryType || BINARY_TYPES[0];
794
- this._extensions = options.extensions || {};
795
- this._isServer = !!options.isServer;
796
- this._maxPayload = options.maxPayload | 0;
797
- this._skipUTF8Validation = !!options.skipUTF8Validation;
798
- this[kWebSocket] = void 0;
799
- this._bufferedBytes = 0;
800
- this._buffers = [];
801
- this._compressed = false;
802
- this._payloadLength = 0;
803
- this._mask = void 0;
804
- this._fragmented = 0;
805
- this._masked = false;
806
- this._fin = false;
807
- this._opcode = 0;
808
- this._totalPayloadLength = 0;
809
- this._messageLength = 0;
810
- this._fragments = [];
811
- this._errored = false;
812
- this._loop = false;
813
- this._state = GET_INFO;
814
- }
815
- /**
816
- * Implements `Writable.prototype._write()`.
817
- *
818
- * @param {Buffer} chunk The chunk of data to write
819
- * @param {String} encoding The character encoding of `chunk`
820
- * @param {Function} cb Callback
821
- * @private
822
- */
823
- _write(chunk, encoding, cb) {
824
- if (this._opcode === 8 && this._state == GET_INFO)
825
- return cb();
826
- this._bufferedBytes += chunk.length;
827
- this._buffers.push(chunk);
828
- this.startLoop(cb);
829
- }
830
- /**
831
- * Consumes `n` bytes from the buffered data.
832
- *
833
- * @param {Number} n The number of bytes to consume
834
- * @return {Buffer} The consumed bytes
835
- * @private
836
- */
837
- consume(n) {
838
- this._bufferedBytes -= n;
839
- if (n === this._buffers[0].length)
840
- return this._buffers.shift();
841
- if (n < this._buffers[0].length) {
842
- const buf = this._buffers[0];
843
- this._buffers[0] = new FastBuffer(
844
- buf.buffer,
845
- buf.byteOffset + n,
846
- buf.length - n
847
- );
848
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
849
- }
850
- const dst = Buffer.allocUnsafe(n);
851
- do {
852
- const buf = this._buffers[0];
853
- const offset = dst.length - n;
854
- if (n >= buf.length) {
855
- dst.set(this._buffers.shift(), offset);
856
- } else {
857
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
858
- this._buffers[0] = new FastBuffer(
859
- buf.buffer,
860
- buf.byteOffset + n,
861
- buf.length - n
862
- );
863
- }
864
- n -= buf.length;
865
- } while (n > 0);
866
- return dst;
867
- }
868
- /**
869
- * Starts the parsing loop.
870
- *
871
- * @param {Function} cb Callback
872
- * @private
873
- */
874
- startLoop(cb) {
875
- this._loop = true;
876
- do {
877
- switch (this._state) {
878
- case GET_INFO:
879
- this.getInfo(cb);
880
- break;
881
- case GET_PAYLOAD_LENGTH_16:
882
- this.getPayloadLength16(cb);
883
- break;
884
- case GET_PAYLOAD_LENGTH_64:
885
- this.getPayloadLength64(cb);
886
- break;
887
- case GET_MASK:
888
- this.getMask();
889
- break;
890
- case GET_DATA:
891
- this.getData(cb);
892
- break;
893
- case INFLATING:
894
- case DEFER_EVENT:
895
- this._loop = false;
896
- return;
897
- }
898
- } while (this._loop);
899
- if (!this._errored)
900
- cb();
901
- }
902
- /**
903
- * Reads the first two bytes of a frame.
904
- *
905
- * @param {Function} cb Callback
906
- * @private
907
- */
908
- getInfo(cb) {
909
- if (this._bufferedBytes < 2) {
910
- this._loop = false;
911
- return;
912
- }
913
- const buf = this.consume(2);
914
- if ((buf[0] & 48) !== 0) {
915
- const error = this.createError(
916
- RangeError,
917
- "RSV2 and RSV3 must be clear",
918
- true,
919
- 1002,
920
- "WS_ERR_UNEXPECTED_RSV_2_3"
921
- );
922
- cb(error);
923
- return;
924
- }
925
- const compressed = (buf[0] & 64) === 64;
926
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
927
- const error = this.createError(
928
- RangeError,
929
- "RSV1 must be clear",
930
- true,
931
- 1002,
932
- "WS_ERR_UNEXPECTED_RSV_1"
933
- );
934
- cb(error);
935
- return;
936
- }
937
- this._fin = (buf[0] & 128) === 128;
938
- this._opcode = buf[0] & 15;
939
- this._payloadLength = buf[1] & 127;
940
- if (this._opcode === 0) {
941
- if (compressed) {
942
- const error = this.createError(
943
- RangeError,
944
- "RSV1 must be clear",
945
- true,
946
- 1002,
947
- "WS_ERR_UNEXPECTED_RSV_1"
948
- );
949
- cb(error);
950
- return;
951
- }
952
- if (!this._fragmented) {
953
- const error = this.createError(
954
- RangeError,
955
- "invalid opcode 0",
956
- true,
957
- 1002,
958
- "WS_ERR_INVALID_OPCODE"
959
- );
960
- cb(error);
961
- return;
962
- }
963
- this._opcode = this._fragmented;
964
- } else if (this._opcode === 1 || this._opcode === 2) {
965
- if (this._fragmented) {
966
- const error = this.createError(
967
- RangeError,
968
- `invalid opcode ${this._opcode}`,
969
- true,
970
- 1002,
971
- "WS_ERR_INVALID_OPCODE"
972
- );
973
- cb(error);
974
- return;
975
- }
976
- this._compressed = compressed;
977
- } else if (this._opcode > 7 && this._opcode < 11) {
978
- if (!this._fin) {
979
- const error = this.createError(
980
- RangeError,
981
- "FIN must be set",
982
- true,
983
- 1002,
984
- "WS_ERR_EXPECTED_FIN"
985
- );
986
- cb(error);
987
- return;
988
- }
989
- if (compressed) {
990
- const error = this.createError(
991
- RangeError,
992
- "RSV1 must be clear",
993
- true,
994
- 1002,
995
- "WS_ERR_UNEXPECTED_RSV_1"
996
- );
997
- cb(error);
998
- return;
999
- }
1000
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1001
- const error = this.createError(
1002
- RangeError,
1003
- `invalid payload length ${this._payloadLength}`,
1004
- true,
1005
- 1002,
1006
- "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1007
- );
1008
- cb(error);
1009
- return;
1010
- }
1011
- } else {
1012
- const error = this.createError(
1013
- RangeError,
1014
- `invalid opcode ${this._opcode}`,
1015
- true,
1016
- 1002,
1017
- "WS_ERR_INVALID_OPCODE"
1018
- );
1019
- cb(error);
1020
- return;
1021
- }
1022
- if (!this._fin && !this._fragmented)
1023
- this._fragmented = this._opcode;
1024
- this._masked = (buf[1] & 128) === 128;
1025
- if (this._isServer) {
1026
- if (!this._masked) {
1027
- const error = this.createError(
1028
- RangeError,
1029
- "MASK must be set",
1030
- true,
1031
- 1002,
1032
- "WS_ERR_EXPECTED_MASK"
1033
- );
1034
- cb(error);
1035
- return;
1036
- }
1037
- } else if (this._masked) {
1038
- const error = this.createError(
1039
- RangeError,
1040
- "MASK must be clear",
1041
- true,
1042
- 1002,
1043
- "WS_ERR_UNEXPECTED_MASK"
1044
- );
1045
- cb(error);
1046
- return;
1047
- }
1048
- if (this._payloadLength === 126)
1049
- this._state = GET_PAYLOAD_LENGTH_16;
1050
- else if (this._payloadLength === 127)
1051
- this._state = GET_PAYLOAD_LENGTH_64;
1052
- else
1053
- this.haveLength(cb);
1054
- }
1055
- /**
1056
- * Gets extended payload length (7+16).
1057
- *
1058
- * @param {Function} cb Callback
1059
- * @private
1060
- */
1061
- getPayloadLength16(cb) {
1062
- if (this._bufferedBytes < 2) {
1063
- this._loop = false;
1064
- return;
1065
- }
1066
- this._payloadLength = this.consume(2).readUInt16BE(0);
1067
- this.haveLength(cb);
1068
- }
1069
- /**
1070
- * Gets extended payload length (7+64).
1071
- *
1072
- * @param {Function} cb Callback
1073
- * @private
1074
- */
1075
- getPayloadLength64(cb) {
1076
- if (this._bufferedBytes < 8) {
1077
- this._loop = false;
1078
- return;
1079
- }
1080
- const buf = this.consume(8);
1081
- const num = buf.readUInt32BE(0);
1082
- if (num > Math.pow(2, 53 - 32) - 1) {
1083
- const error = this.createError(
1084
- RangeError,
1085
- "Unsupported WebSocket frame: payload length > 2^53 - 1",
1086
- false,
1087
- 1009,
1088
- "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1089
- );
1090
- cb(error);
1091
- return;
1092
- }
1093
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1094
- this.haveLength(cb);
1095
- }
1096
- /**
1097
- * Payload length has been read.
1098
- *
1099
- * @param {Function} cb Callback
1100
- * @private
1101
- */
1102
- haveLength(cb) {
1103
- if (this._payloadLength && this._opcode < 8) {
1104
- this._totalPayloadLength += this._payloadLength;
1105
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1106
- const error = this.createError(
1107
- RangeError,
1108
- "Max payload size exceeded",
1109
- false,
1110
- 1009,
1111
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1112
- );
1113
- cb(error);
1114
- return;
1115
- }
1116
- }
1117
- if (this._masked)
1118
- this._state = GET_MASK;
1119
- else
1120
- this._state = GET_DATA;
1121
- }
1122
- /**
1123
- * Reads mask bytes.
1124
- *
1125
- * @private
1126
- */
1127
- getMask() {
1128
- if (this._bufferedBytes < 4) {
1129
- this._loop = false;
1130
- return;
1131
- }
1132
- this._mask = this.consume(4);
1133
- this._state = GET_DATA;
1134
- }
1135
- /**
1136
- * Reads data bytes.
1137
- *
1138
- * @param {Function} cb Callback
1139
- * @private
1140
- */
1141
- getData(cb) {
1142
- let data = EMPTY_BUFFER;
1143
- if (this._payloadLength) {
1144
- if (this._bufferedBytes < this._payloadLength) {
1145
- this._loop = false;
1146
- return;
1147
- }
1148
- data = this.consume(this._payloadLength);
1149
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1150
- unmask(data, this._mask);
1151
- }
1152
- }
1153
- if (this._opcode > 7) {
1154
- this.controlMessage(data, cb);
1155
- return;
1156
- }
1157
- if (this._compressed) {
1158
- this._state = INFLATING;
1159
- this.decompress(data, cb);
1160
- return;
1161
- }
1162
- if (data.length) {
1163
- this._messageLength = this._totalPayloadLength;
1164
- this._fragments.push(data);
1165
- }
1166
- this.dataMessage(cb);
1167
- }
1168
- /**
1169
- * Decompresses data.
1170
- *
1171
- * @param {Buffer} data Compressed data
1172
- * @param {Function} cb Callback
1173
- * @private
1174
- */
1175
- decompress(data, cb) {
1176
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1177
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1178
- if (err)
1179
- return cb(err);
1180
- if (buf.length) {
1181
- this._messageLength += buf.length;
1182
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1183
- const error = this.createError(
1184
- RangeError,
1185
- "Max payload size exceeded",
1186
- false,
1187
- 1009,
1188
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1189
- );
1190
- cb(error);
1191
- return;
1192
- }
1193
- this._fragments.push(buf);
1194
- }
1195
- this.dataMessage(cb);
1196
- if (this._state === GET_INFO)
1197
- this.startLoop(cb);
1198
- });
1199
- }
1200
- /**
1201
- * Handles a data message.
1202
- *
1203
- * @param {Function} cb Callback
1204
- * @private
1205
- */
1206
- dataMessage(cb) {
1207
- if (!this._fin) {
1208
- this._state = GET_INFO;
1209
- return;
1210
- }
1211
- const messageLength = this._messageLength;
1212
- const fragments = this._fragments;
1213
- this._totalPayloadLength = 0;
1214
- this._messageLength = 0;
1215
- this._fragmented = 0;
1216
- this._fragments = [];
1217
- if (this._opcode === 2) {
1218
- let data;
1219
- if (this._binaryType === "nodebuffer") {
1220
- data = concat(fragments, messageLength);
1221
- } else if (this._binaryType === "arraybuffer") {
1222
- data = toArrayBuffer(concat(fragments, messageLength));
1223
- } else if (this._binaryType === "blob") {
1224
- data = new Blob(fragments);
1225
- } else {
1226
- data = fragments;
1227
- }
1228
- if (this._allowSynchronousEvents) {
1229
- this.emit("message", data, true);
1230
- this._state = GET_INFO;
1231
- } else {
1232
- this._state = DEFER_EVENT;
1233
- setImmediate(() => {
1234
- this.emit("message", data, true);
1235
- this._state = GET_INFO;
1236
- this.startLoop(cb);
1237
- });
1238
- }
1239
- } else {
1240
- const buf = concat(fragments, messageLength);
1241
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1242
- const error = this.createError(
1243
- Error,
1244
- "invalid UTF-8 sequence",
1245
- true,
1246
- 1007,
1247
- "WS_ERR_INVALID_UTF8"
1248
- );
1249
- cb(error);
1250
- return;
1251
- }
1252
- if (this._state === INFLATING || this._allowSynchronousEvents) {
1253
- this.emit("message", buf, false);
1254
- this._state = GET_INFO;
1255
- } else {
1256
- this._state = DEFER_EVENT;
1257
- setImmediate(() => {
1258
- this.emit("message", buf, false);
1259
- this._state = GET_INFO;
1260
- this.startLoop(cb);
1261
- });
1262
- }
1263
- }
1264
- }
1265
- /**
1266
- * Handles a control message.
1267
- *
1268
- * @param {Buffer} data Data to handle
1269
- * @return {(Error|RangeError|undefined)} A possible error
1270
- * @private
1271
- */
1272
- controlMessage(data, cb) {
1273
- if (this._opcode === 8) {
1274
- if (data.length === 0) {
1275
- this._loop = false;
1276
- this.emit("conclude", 1005, EMPTY_BUFFER);
1277
- this.end();
1278
- } else {
1279
- const code = data.readUInt16BE(0);
1280
- if (!isValidStatusCode(code)) {
1281
- const error = this.createError(
1282
- RangeError,
1283
- `invalid status code ${code}`,
1284
- true,
1285
- 1002,
1286
- "WS_ERR_INVALID_CLOSE_CODE"
1287
- );
1288
- cb(error);
1289
- return;
1290
- }
1291
- const buf = new FastBuffer(
1292
- data.buffer,
1293
- data.byteOffset + 2,
1294
- data.length - 2
1295
- );
1296
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1297
- const error = this.createError(
1298
- Error,
1299
- "invalid UTF-8 sequence",
1300
- true,
1301
- 1007,
1302
- "WS_ERR_INVALID_UTF8"
1303
- );
1304
- cb(error);
1305
- return;
1306
- }
1307
- this._loop = false;
1308
- this.emit("conclude", code, buf);
1309
- this.end();
1310
- }
1311
- this._state = GET_INFO;
1312
- return;
1313
- }
1314
- if (this._allowSynchronousEvents) {
1315
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1316
- this._state = GET_INFO;
1317
- } else {
1318
- this._state = DEFER_EVENT;
1319
- setImmediate(() => {
1320
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1321
- this._state = GET_INFO;
1322
- this.startLoop(cb);
1323
- });
1324
- }
1325
- }
1326
- /**
1327
- * Builds an error object.
1328
- *
1329
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1330
- * @param {String} message The error message
1331
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1332
- * `message`
1333
- * @param {Number} statusCode The status code
1334
- * @param {String} errorCode The exposed error code
1335
- * @return {(Error|RangeError)} The error
1336
- * @private
1337
- */
1338
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1339
- this._loop = false;
1340
- this._errored = true;
1341
- const err = new ErrorCtor(
1342
- prefix ? `Invalid WebSocket frame: ${message}` : message
1343
- );
1344
- Error.captureStackTrace(err, this.createError);
1345
- err.code = errorCode;
1346
- err[kStatusCode] = statusCode;
1347
- return err;
1348
- }
1349
- };
1350
- module.exports = Receiver;
1351
- }
1352
- });
1353
-
1354
- // ../../../node_modules/ws/lib/sender.js
1355
- var require_sender = __commonJS({
1356
- "../../../node_modules/ws/lib/sender.js"(exports$1, module) {
1357
- var { Duplex } = __require("stream");
1358
- var { randomFillSync } = __require("crypto");
1359
- var PerMessageDeflate = require_permessage_deflate();
1360
- var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1361
- var { isBlob, isValidStatusCode } = require_validation();
1362
- var { mask: applyMask, toBuffer } = require_buffer_util();
1363
- var kByteLength = Symbol("kByteLength");
1364
- var maskBuffer = Buffer.alloc(4);
1365
- var RANDOM_POOL_SIZE = 8 * 1024;
1366
- var randomPool;
1367
- var randomPoolPointer = RANDOM_POOL_SIZE;
1368
- var DEFAULT = 0;
1369
- var DEFLATING = 1;
1370
- var GET_BLOB_DATA = 2;
1371
- var Sender = class _Sender {
1372
- /**
1373
- * Creates a Sender instance.
1374
- *
1375
- * @param {Duplex} socket The connection socket
1376
- * @param {Object} [extensions] An object containing the negotiated extensions
1377
- * @param {Function} [generateMask] The function used to generate the masking
1378
- * key
1379
- */
1380
- constructor(socket, extensions, generateMask) {
1381
- this._extensions = extensions || {};
1382
- if (generateMask) {
1383
- this._generateMask = generateMask;
1384
- this._maskBuffer = Buffer.alloc(4);
1385
- }
1386
- this._socket = socket;
1387
- this._firstFragment = true;
1388
- this._compress = false;
1389
- this._bufferedBytes = 0;
1390
- this._queue = [];
1391
- this._state = DEFAULT;
1392
- this.onerror = NOOP;
1393
- this[kWebSocket] = void 0;
1394
- }
1395
- /**
1396
- * Frames a piece of data according to the HyBi WebSocket protocol.
1397
- *
1398
- * @param {(Buffer|String)} data The data to frame
1399
- * @param {Object} options Options object
1400
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1401
- * FIN bit
1402
- * @param {Function} [options.generateMask] The function used to generate the
1403
- * masking key
1404
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1405
- * `data`
1406
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1407
- * key
1408
- * @param {Number} options.opcode The opcode
1409
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1410
- * modified
1411
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1412
- * RSV1 bit
1413
- * @return {(Buffer|String)[]} The framed data
1414
- * @public
1415
- */
1416
- static frame(data, options) {
1417
- let mask;
1418
- let merge = false;
1419
- let offset = 2;
1420
- let skipMasking = false;
1421
- if (options.mask) {
1422
- mask = options.maskBuffer || maskBuffer;
1423
- if (options.generateMask) {
1424
- options.generateMask(mask);
1425
- } else {
1426
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
1427
- if (randomPool === void 0) {
1428
- randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1429
- }
1430
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1431
- randomPoolPointer = 0;
1432
- }
1433
- mask[0] = randomPool[randomPoolPointer++];
1434
- mask[1] = randomPool[randomPoolPointer++];
1435
- mask[2] = randomPool[randomPoolPointer++];
1436
- mask[3] = randomPool[randomPoolPointer++];
1437
- }
1438
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1439
- offset = 6;
1440
- }
1441
- let dataLength;
1442
- if (typeof data === "string") {
1443
- if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1444
- dataLength = options[kByteLength];
1445
- } else {
1446
- data = Buffer.from(data);
1447
- dataLength = data.length;
1448
- }
1449
- } else {
1450
- dataLength = data.length;
1451
- merge = options.mask && options.readOnly && !skipMasking;
1452
- }
1453
- let payloadLength = dataLength;
1454
- if (dataLength >= 65536) {
1455
- offset += 8;
1456
- payloadLength = 127;
1457
- } else if (dataLength > 125) {
1458
- offset += 2;
1459
- payloadLength = 126;
1460
- }
1461
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1462
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
1463
- if (options.rsv1)
1464
- target[0] |= 64;
1465
- target[1] = payloadLength;
1466
- if (payloadLength === 126) {
1467
- target.writeUInt16BE(dataLength, 2);
1468
- } else if (payloadLength === 127) {
1469
- target[2] = target[3] = 0;
1470
- target.writeUIntBE(dataLength, 4, 6);
1471
- }
1472
- if (!options.mask)
1473
- return [target, data];
1474
- target[1] |= 128;
1475
- target[offset - 4] = mask[0];
1476
- target[offset - 3] = mask[1];
1477
- target[offset - 2] = mask[2];
1478
- target[offset - 1] = mask[3];
1479
- if (skipMasking)
1480
- return [target, data];
1481
- if (merge) {
1482
- applyMask(data, mask, target, offset, dataLength);
1483
- return [target];
1484
- }
1485
- applyMask(data, mask, data, 0, dataLength);
1486
- return [target, data];
1487
- }
1488
- /**
1489
- * Sends a close message to the other peer.
1490
- *
1491
- * @param {Number} [code] The status code component of the body
1492
- * @param {(String|Buffer)} [data] The message component of the body
1493
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1494
- * @param {Function} [cb] Callback
1495
- * @public
1496
- */
1497
- close(code, data, mask, cb) {
1498
- let buf;
1499
- if (code === void 0) {
1500
- buf = EMPTY_BUFFER;
1501
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1502
- throw new TypeError("First argument must be a valid error code number");
1503
- } else if (data === void 0 || !data.length) {
1504
- buf = Buffer.allocUnsafe(2);
1505
- buf.writeUInt16BE(code, 0);
1506
- } else {
1507
- const length = Buffer.byteLength(data);
1508
- if (length > 123) {
1509
- throw new RangeError("The message must not be greater than 123 bytes");
1510
- }
1511
- buf = Buffer.allocUnsafe(2 + length);
1512
- buf.writeUInt16BE(code, 0);
1513
- if (typeof data === "string") {
1514
- buf.write(data, 2);
1515
- } else {
1516
- buf.set(data, 2);
1517
- }
1518
- }
1519
- const options = {
1520
- [kByteLength]: buf.length,
1521
- fin: true,
1522
- generateMask: this._generateMask,
1523
- mask,
1524
- maskBuffer: this._maskBuffer,
1525
- opcode: 8,
1526
- readOnly: false,
1527
- rsv1: false
1528
- };
1529
- if (this._state !== DEFAULT) {
1530
- this.enqueue([this.dispatch, buf, false, options, cb]);
1531
- } else {
1532
- this.sendFrame(_Sender.frame(buf, options), cb);
1533
- }
1534
- }
1535
- /**
1536
- * Sends a ping message to the other peer.
1537
- *
1538
- * @param {*} data The message to send
1539
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1540
- * @param {Function} [cb] Callback
1541
- * @public
1542
- */
1543
- ping(data, mask, cb) {
1544
- let byteLength;
1545
- let readOnly;
1546
- if (typeof data === "string") {
1547
- byteLength = Buffer.byteLength(data);
1548
- readOnly = false;
1549
- } else if (isBlob(data)) {
1550
- byteLength = data.size;
1551
- readOnly = false;
1552
- } else {
1553
- data = toBuffer(data);
1554
- byteLength = data.length;
1555
- readOnly = toBuffer.readOnly;
1556
- }
1557
- if (byteLength > 125) {
1558
- throw new RangeError("The data size must not be greater than 125 bytes");
1559
- }
1560
- const options = {
1561
- [kByteLength]: byteLength,
1562
- fin: true,
1563
- generateMask: this._generateMask,
1564
- mask,
1565
- maskBuffer: this._maskBuffer,
1566
- opcode: 9,
1567
- readOnly,
1568
- rsv1: false
1569
- };
1570
- if (isBlob(data)) {
1571
- if (this._state !== DEFAULT) {
1572
- this.enqueue([this.getBlobData, data, false, options, cb]);
1573
- } else {
1574
- this.getBlobData(data, false, options, cb);
1575
- }
1576
- } else if (this._state !== DEFAULT) {
1577
- this.enqueue([this.dispatch, data, false, options, cb]);
1578
- } else {
1579
- this.sendFrame(_Sender.frame(data, options), cb);
1580
- }
1581
- }
1582
- /**
1583
- * Sends a pong message to the other peer.
1584
- *
1585
- * @param {*} data The message to send
1586
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1587
- * @param {Function} [cb] Callback
1588
- * @public
1589
- */
1590
- pong(data, mask, cb) {
1591
- let byteLength;
1592
- let readOnly;
1593
- if (typeof data === "string") {
1594
- byteLength = Buffer.byteLength(data);
1595
- readOnly = false;
1596
- } else if (isBlob(data)) {
1597
- byteLength = data.size;
1598
- readOnly = false;
1599
- } else {
1600
- data = toBuffer(data);
1601
- byteLength = data.length;
1602
- readOnly = toBuffer.readOnly;
1603
- }
1604
- if (byteLength > 125) {
1605
- throw new RangeError("The data size must not be greater than 125 bytes");
1606
- }
1607
- const options = {
1608
- [kByteLength]: byteLength,
1609
- fin: true,
1610
- generateMask: this._generateMask,
1611
- mask,
1612
- maskBuffer: this._maskBuffer,
1613
- opcode: 10,
1614
- readOnly,
1615
- rsv1: false
1616
- };
1617
- if (isBlob(data)) {
1618
- if (this._state !== DEFAULT) {
1619
- this.enqueue([this.getBlobData, data, false, options, cb]);
1620
- } else {
1621
- this.getBlobData(data, false, options, cb);
1622
- }
1623
- } else if (this._state !== DEFAULT) {
1624
- this.enqueue([this.dispatch, data, false, options, cb]);
1625
- } else {
1626
- this.sendFrame(_Sender.frame(data, options), cb);
1627
- }
1628
- }
1629
- /**
1630
- * Sends a data message to the other peer.
1631
- *
1632
- * @param {*} data The message to send
1633
- * @param {Object} options Options object
1634
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1635
- * or text
1636
- * @param {Boolean} [options.compress=false] Specifies whether or not to
1637
- * compress `data`
1638
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1639
- * last one
1640
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1641
- * `data`
1642
- * @param {Function} [cb] Callback
1643
- * @public
1644
- */
1645
- send(data, options, cb) {
1646
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1647
- let opcode = options.binary ? 2 : 1;
1648
- let rsv1 = options.compress;
1649
- let byteLength;
1650
- let readOnly;
1651
- if (typeof data === "string") {
1652
- byteLength = Buffer.byteLength(data);
1653
- readOnly = false;
1654
- } else if (isBlob(data)) {
1655
- byteLength = data.size;
1656
- readOnly = false;
1657
- } else {
1658
- data = toBuffer(data);
1659
- byteLength = data.length;
1660
- readOnly = toBuffer.readOnly;
1661
- }
1662
- if (this._firstFragment) {
1663
- this._firstFragment = false;
1664
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1665
- rsv1 = byteLength >= perMessageDeflate._threshold;
1666
- }
1667
- this._compress = rsv1;
1668
- } else {
1669
- rsv1 = false;
1670
- opcode = 0;
1671
- }
1672
- if (options.fin)
1673
- this._firstFragment = true;
1674
- const opts = {
1675
- [kByteLength]: byteLength,
1676
- fin: options.fin,
1677
- generateMask: this._generateMask,
1678
- mask: options.mask,
1679
- maskBuffer: this._maskBuffer,
1680
- opcode,
1681
- readOnly,
1682
- rsv1
1683
- };
1684
- if (isBlob(data)) {
1685
- if (this._state !== DEFAULT) {
1686
- this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1687
- } else {
1688
- this.getBlobData(data, this._compress, opts, cb);
1689
- }
1690
- } else if (this._state !== DEFAULT) {
1691
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1692
- } else {
1693
- this.dispatch(data, this._compress, opts, cb);
1694
- }
1695
- }
1696
- /**
1697
- * Gets the contents of a blob as binary data.
1698
- *
1699
- * @param {Blob} blob The blob
1700
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1701
- * the data
1702
- * @param {Object} options Options object
1703
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1704
- * FIN bit
1705
- * @param {Function} [options.generateMask] The function used to generate the
1706
- * masking key
1707
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1708
- * `data`
1709
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1710
- * key
1711
- * @param {Number} options.opcode The opcode
1712
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1713
- * modified
1714
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1715
- * RSV1 bit
1716
- * @param {Function} [cb] Callback
1717
- * @private
1718
- */
1719
- getBlobData(blob, compress, options, cb) {
1720
- this._bufferedBytes += options[kByteLength];
1721
- this._state = GET_BLOB_DATA;
1722
- blob.arrayBuffer().then((arrayBuffer) => {
1723
- if (this._socket.destroyed) {
1724
- const err = new Error(
1725
- "The socket was closed while the blob was being read"
1726
- );
1727
- process.nextTick(callCallbacks, this, err, cb);
1728
- return;
1729
- }
1730
- this._bufferedBytes -= options[kByteLength];
1731
- const data = toBuffer(arrayBuffer);
1732
- if (!compress) {
1733
- this._state = DEFAULT;
1734
- this.sendFrame(_Sender.frame(data, options), cb);
1735
- this.dequeue();
1736
- } else {
1737
- this.dispatch(data, compress, options, cb);
1738
- }
1739
- }).catch((err) => {
1740
- process.nextTick(onError, this, err, cb);
1741
- });
1742
- }
1743
- /**
1744
- * Dispatches a message.
1745
- *
1746
- * @param {(Buffer|String)} data The message to send
1747
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1748
- * `data`
1749
- * @param {Object} options Options object
1750
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1751
- * FIN bit
1752
- * @param {Function} [options.generateMask] The function used to generate the
1753
- * masking key
1754
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1755
- * `data`
1756
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1757
- * key
1758
- * @param {Number} options.opcode The opcode
1759
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1760
- * modified
1761
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1762
- * RSV1 bit
1763
- * @param {Function} [cb] Callback
1764
- * @private
1765
- */
1766
- dispatch(data, compress, options, cb) {
1767
- if (!compress) {
1768
- this.sendFrame(_Sender.frame(data, options), cb);
1769
- return;
1770
- }
1771
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1772
- this._bufferedBytes += options[kByteLength];
1773
- this._state = DEFLATING;
1774
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1775
- if (this._socket.destroyed) {
1776
- const err = new Error(
1777
- "The socket was closed while data was being compressed"
1778
- );
1779
- callCallbacks(this, err, cb);
1780
- return;
1781
- }
1782
- this._bufferedBytes -= options[kByteLength];
1783
- this._state = DEFAULT;
1784
- options.readOnly = false;
1785
- this.sendFrame(_Sender.frame(buf, options), cb);
1786
- this.dequeue();
1787
- });
1788
- }
1789
- /**
1790
- * Executes queued send operations.
1791
- *
1792
- * @private
1793
- */
1794
- dequeue() {
1795
- while (this._state === DEFAULT && this._queue.length) {
1796
- const params = this._queue.shift();
1797
- this._bufferedBytes -= params[3][kByteLength];
1798
- Reflect.apply(params[0], this, params.slice(1));
1799
- }
1800
- }
1801
- /**
1802
- * Enqueues a send operation.
1803
- *
1804
- * @param {Array} params Send operation parameters.
1805
- * @private
1806
- */
1807
- enqueue(params) {
1808
- this._bufferedBytes += params[3][kByteLength];
1809
- this._queue.push(params);
1810
- }
1811
- /**
1812
- * Sends a frame.
1813
- *
1814
- * @param {(Buffer | String)[]} list The frame to send
1815
- * @param {Function} [cb] Callback
1816
- * @private
1817
- */
1818
- sendFrame(list, cb) {
1819
- if (list.length === 2) {
1820
- this._socket.cork();
1821
- this._socket.write(list[0]);
1822
- this._socket.write(list[1], cb);
1823
- this._socket.uncork();
1824
- } else {
1825
- this._socket.write(list[0], cb);
1826
- }
1827
- }
1828
- };
1829
- module.exports = Sender;
1830
- function callCallbacks(sender, err, cb) {
1831
- if (typeof cb === "function")
1832
- cb(err);
1833
- for (let i = 0; i < sender._queue.length; i++) {
1834
- const params = sender._queue[i];
1835
- const callback = params[params.length - 1];
1836
- if (typeof callback === "function")
1837
- callback(err);
1838
- }
1839
- }
1840
- function onError(sender, err, cb) {
1841
- callCallbacks(sender, err, cb);
1842
- sender.onerror(err);
1843
- }
1844
- }
1845
- });
1846
-
1847
- // ../../../node_modules/ws/lib/event-target.js
1848
- var require_event_target = __commonJS({
1849
- "../../../node_modules/ws/lib/event-target.js"(exports$1, module) {
1850
- var { kForOnEventAttribute, kListener } = require_constants();
1851
- var kCode = Symbol("kCode");
1852
- var kData = Symbol("kData");
1853
- var kError = Symbol("kError");
1854
- var kMessage = Symbol("kMessage");
1855
- var kReason = Symbol("kReason");
1856
- var kTarget = Symbol("kTarget");
1857
- var kType = Symbol("kType");
1858
- var kWasClean = Symbol("kWasClean");
1859
- var Event = class {
1860
- /**
1861
- * Create a new `Event`.
1862
- *
1863
- * @param {String} type The name of the event
1864
- * @throws {TypeError} If the `type` argument is not specified
1865
- */
1866
- constructor(type) {
1867
- this[kTarget] = null;
1868
- this[kType] = type;
1869
- }
1870
- /**
1871
- * @type {*}
1872
- */
1873
- get target() {
1874
- return this[kTarget];
1875
- }
1876
- /**
1877
- * @type {String}
1878
- */
1879
- get type() {
1880
- return this[kType];
1881
- }
1882
- };
1883
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
1884
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
1885
- var CloseEvent = class extends Event {
1886
- /**
1887
- * Create a new `CloseEvent`.
1888
- *
1889
- * @param {String} type The name of the event
1890
- * @param {Object} [options] A dictionary object that allows for setting
1891
- * attributes via object members of the same name
1892
- * @param {Number} [options.code=0] The status code explaining why the
1893
- * connection was closed
1894
- * @param {String} [options.reason=''] A human-readable string explaining why
1895
- * the connection was closed
1896
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1897
- * connection was cleanly closed
1898
- */
1899
- constructor(type, options = {}) {
1900
- super(type);
1901
- this[kCode] = options.code === void 0 ? 0 : options.code;
1902
- this[kReason] = options.reason === void 0 ? "" : options.reason;
1903
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1904
- }
1905
- /**
1906
- * @type {Number}
1907
- */
1908
- get code() {
1909
- return this[kCode];
1910
- }
1911
- /**
1912
- * @type {String}
1913
- */
1914
- get reason() {
1915
- return this[kReason];
1916
- }
1917
- /**
1918
- * @type {Boolean}
1919
- */
1920
- get wasClean() {
1921
- return this[kWasClean];
1922
- }
1923
- };
1924
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1925
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1926
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1927
- var ErrorEvent = class extends Event {
1928
- /**
1929
- * Create a new `ErrorEvent`.
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.error=null] The error that generated this event
1935
- * @param {String} [options.message=''] The error message
1936
- */
1937
- constructor(type, options = {}) {
1938
- super(type);
1939
- this[kError] = options.error === void 0 ? null : options.error;
1940
- this[kMessage] = options.message === void 0 ? "" : options.message;
1941
- }
1942
- /**
1943
- * @type {*}
1944
- */
1945
- get error() {
1946
- return this[kError];
1947
- }
1948
- /**
1949
- * @type {String}
1950
- */
1951
- get message() {
1952
- return this[kMessage];
1953
- }
1954
- };
1955
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1956
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1957
- var MessageEvent = class extends Event {
1958
- /**
1959
- * Create a new `MessageEvent`.
1960
- *
1961
- * @param {String} type The name of the event
1962
- * @param {Object} [options] A dictionary object that allows for setting
1963
- * attributes via object members of the same name
1964
- * @param {*} [options.data=null] The message content
1965
- */
1966
- constructor(type, options = {}) {
1967
- super(type);
1968
- this[kData] = options.data === void 0 ? null : options.data;
1969
- }
1970
- /**
1971
- * @type {*}
1972
- */
1973
- get data() {
1974
- return this[kData];
1975
- }
1976
- };
1977
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1978
- var EventTarget = {
1979
- /**
1980
- * Register an event listener.
1981
- *
1982
- * @param {String} type A string representing the event type to listen for
1983
- * @param {(Function|Object)} handler The listener to add
1984
- * @param {Object} [options] An options object specifies characteristics about
1985
- * the event listener
1986
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1987
- * listener should be invoked at most once after being added. If `true`,
1988
- * the listener would be automatically removed when invoked.
1989
- * @public
1990
- */
1991
- addEventListener(type, handler, options = {}) {
1992
- for (const listener of this.listeners(type)) {
1993
- if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1994
- return;
1995
- }
1996
- }
1997
- let wrapper;
1998
- if (type === "message") {
1999
- wrapper = function onMessage(data, isBinary) {
2000
- const event = new MessageEvent("message", {
2001
- data: isBinary ? data : data.toString()
2002
- });
2003
- event[kTarget] = this;
2004
- callListener(handler, this, event);
2005
- };
2006
- } else if (type === "close") {
2007
- wrapper = function onClose(code, message) {
2008
- const event = new CloseEvent("close", {
2009
- code,
2010
- reason: message.toString(),
2011
- wasClean: this._closeFrameReceived && this._closeFrameSent
2012
- });
2013
- event[kTarget] = this;
2014
- callListener(handler, this, event);
2015
- };
2016
- } else if (type === "error") {
2017
- wrapper = function onError(error) {
2018
- const event = new ErrorEvent("error", {
2019
- error,
2020
- message: error.message
2021
- });
2022
- event[kTarget] = this;
2023
- callListener(handler, this, event);
2024
- };
2025
- } else if (type === "open") {
2026
- wrapper = function onOpen() {
2027
- const event = new Event("open");
2028
- event[kTarget] = this;
2029
- callListener(handler, this, event);
2030
- };
2031
- } else {
2032
- return;
2033
- }
2034
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2035
- wrapper[kListener] = handler;
2036
- if (options.once) {
2037
- this.once(type, wrapper);
2038
- } else {
2039
- this.on(type, wrapper);
2040
- }
2041
- },
2042
- /**
2043
- * Remove an event listener.
2044
- *
2045
- * @param {String} type A string representing the event type to remove
2046
- * @param {(Function|Object)} handler The listener to remove
2047
- * @public
2048
- */
2049
- removeEventListener(type, handler) {
2050
- for (const listener of this.listeners(type)) {
2051
- if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2052
- this.removeListener(type, listener);
2053
- break;
2054
- }
2055
- }
2056
- }
2057
- };
2058
- module.exports = {
2059
- CloseEvent,
2060
- ErrorEvent,
2061
- Event,
2062
- EventTarget,
2063
- MessageEvent
2064
- };
2065
- function callListener(listener, thisArg, event) {
2066
- if (typeof listener === "object" && listener.handleEvent) {
2067
- listener.handleEvent.call(listener, event);
2068
- } else {
2069
- listener.call(thisArg, event);
2070
- }
2071
- }
2072
- }
2073
- });
2074
-
2075
- // ../../../node_modules/ws/lib/extension.js
2076
- var require_extension = __commonJS({
2077
- "../../../node_modules/ws/lib/extension.js"(exports$1, module) {
2078
- var { tokenChars } = require_validation();
2079
- function push(dest, name, elem) {
2080
- if (dest[name] === void 0)
2081
- dest[name] = [elem];
2082
- else
2083
- dest[name].push(elem);
2084
- }
2085
- function parse(header) {
2086
- const offers = /* @__PURE__ */ Object.create(null);
2087
- let params = /* @__PURE__ */ Object.create(null);
2088
- let mustUnescape = false;
2089
- let isEscaping = false;
2090
- let inQuotes = false;
2091
- let extensionName;
2092
- let paramName;
2093
- let start = -1;
2094
- let code = -1;
2095
- let end = -1;
2096
- let i = 0;
2097
- for (; i < header.length; i++) {
2098
- code = header.charCodeAt(i);
2099
- if (extensionName === void 0) {
2100
- if (end === -1 && tokenChars[code] === 1) {
2101
- if (start === -1)
2102
- start = i;
2103
- } else if (i !== 0 && (code === 32 || code === 9)) {
2104
- if (end === -1 && start !== -1)
2105
- end = i;
2106
- } else if (code === 59 || code === 44) {
2107
- if (start === -1) {
2108
- throw new SyntaxError(`Unexpected character at index ${i}`);
2109
- }
2110
- if (end === -1)
2111
- end = i;
2112
- const name = header.slice(start, end);
2113
- if (code === 44) {
2114
- push(offers, name, params);
2115
- params = /* @__PURE__ */ Object.create(null);
2116
- } else {
2117
- extensionName = name;
2118
- }
2119
- start = end = -1;
2120
- } else {
2121
- throw new SyntaxError(`Unexpected character at index ${i}`);
2122
- }
2123
- } else if (paramName === void 0) {
2124
- if (end === -1 && tokenChars[code] === 1) {
2125
- if (start === -1)
2126
- start = i;
2127
- } else if (code === 32 || code === 9) {
2128
- if (end === -1 && start !== -1)
2129
- end = i;
2130
- } else if (code === 59 || code === 44) {
2131
- if (start === -1) {
2132
- throw new SyntaxError(`Unexpected character at index ${i}`);
2133
- }
2134
- if (end === -1)
2135
- end = i;
2136
- push(params, header.slice(start, end), true);
2137
- if (code === 44) {
2138
- push(offers, extensionName, params);
2139
- params = /* @__PURE__ */ Object.create(null);
2140
- extensionName = void 0;
2141
- }
2142
- start = end = -1;
2143
- } else if (code === 61 && start !== -1 && end === -1) {
2144
- paramName = header.slice(start, i);
2145
- start = end = -1;
2146
- } else {
2147
- throw new SyntaxError(`Unexpected character at index ${i}`);
2148
- }
2149
- } else {
2150
- if (isEscaping) {
2151
- if (tokenChars[code] !== 1) {
2152
- throw new SyntaxError(`Unexpected character at index ${i}`);
2153
- }
2154
- if (start === -1)
2155
- start = i;
2156
- else if (!mustUnescape)
2157
- mustUnescape = true;
2158
- isEscaping = false;
2159
- } else if (inQuotes) {
2160
- if (tokenChars[code] === 1) {
2161
- if (start === -1)
2162
- start = i;
2163
- } else if (code === 34 && start !== -1) {
2164
- inQuotes = false;
2165
- end = i;
2166
- } else if (code === 92) {
2167
- isEscaping = true;
2168
- } else {
2169
- throw new SyntaxError(`Unexpected character at index ${i}`);
2170
- }
2171
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2172
- inQuotes = true;
2173
- } else if (end === -1 && tokenChars[code] === 1) {
2174
- if (start === -1)
2175
- start = i;
2176
- } else if (start !== -1 && (code === 32 || code === 9)) {
2177
- if (end === -1)
2178
- end = i;
2179
- } else if (code === 59 || code === 44) {
2180
- if (start === -1) {
2181
- throw new SyntaxError(`Unexpected character at index ${i}`);
2182
- }
2183
- if (end === -1)
2184
- end = i;
2185
- let value = header.slice(start, end);
2186
- if (mustUnescape) {
2187
- value = value.replace(/\\/g, "");
2188
- mustUnescape = false;
2189
- }
2190
- push(params, paramName, value);
2191
- if (code === 44) {
2192
- push(offers, extensionName, params);
2193
- params = /* @__PURE__ */ Object.create(null);
2194
- extensionName = void 0;
2195
- }
2196
- paramName = void 0;
2197
- start = end = -1;
2198
- } else {
2199
- throw new SyntaxError(`Unexpected character at index ${i}`);
2200
- }
2201
- }
2202
- }
2203
- if (start === -1 || inQuotes || code === 32 || code === 9) {
2204
- throw new SyntaxError("Unexpected end of input");
2205
- }
2206
- if (end === -1)
2207
- end = i;
2208
- const token = header.slice(start, end);
2209
- if (extensionName === void 0) {
2210
- push(offers, token, params);
2211
- } else {
2212
- if (paramName === void 0) {
2213
- push(params, token, true);
2214
- } else if (mustUnescape) {
2215
- push(params, paramName, token.replace(/\\/g, ""));
2216
- } else {
2217
- push(params, paramName, token);
2218
- }
2219
- push(offers, extensionName, params);
2220
- }
2221
- return offers;
2222
- }
2223
- function format(extensions) {
2224
- return Object.keys(extensions).map((extension) => {
2225
- let configurations = extensions[extension];
2226
- if (!Array.isArray(configurations))
2227
- configurations = [configurations];
2228
- return configurations.map((params) => {
2229
- return [extension].concat(
2230
- Object.keys(params).map((k) => {
2231
- let values = params[k];
2232
- if (!Array.isArray(values))
2233
- values = [values];
2234
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2235
- })
2236
- ).join("; ");
2237
- }).join(", ");
2238
- }).join(", ");
2239
- }
2240
- module.exports = { format, parse };
2241
- }
2242
- });
2243
-
2244
- // ../../../node_modules/ws/lib/websocket.js
2245
- var require_websocket = __commonJS({
2246
- "../../../node_modules/ws/lib/websocket.js"(exports$1, module) {
2247
- var EventEmitter = __require("events");
2248
- var https = __require("https");
2249
- var http = __require("http");
2250
- var net = __require("net");
2251
- var tls = __require("tls");
2252
- var { randomBytes, createHash } = __require("crypto");
2253
- var { Duplex, Readable } = __require("stream");
2254
- var { URL: URL2 } = __require("url");
2255
- var PerMessageDeflate = require_permessage_deflate();
2256
- var Receiver = require_receiver();
2257
- var Sender = require_sender();
2258
- var { isBlob } = require_validation();
2259
- var {
2260
- BINARY_TYPES,
2261
- CLOSE_TIMEOUT,
2262
- EMPTY_BUFFER,
2263
- GUID,
2264
- kForOnEventAttribute,
2265
- kListener,
2266
- kStatusCode,
2267
- kWebSocket,
2268
- NOOP
2269
- } = require_constants();
2270
- var {
2271
- EventTarget: { addEventListener, removeEventListener }
2272
- } = require_event_target();
2273
- var { format, parse } = require_extension();
2274
- var { toBuffer } = require_buffer_util();
2275
- var kAborted = Symbol("kAborted");
2276
- var protocolVersions = [8, 13];
2277
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2278
- var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2279
- var WebSocket2 = class _WebSocket extends EventEmitter {
2280
- /**
2281
- * Create a new `WebSocket`.
2282
- *
2283
- * @param {(String|URL)} address The URL to which to connect
2284
- * @param {(String|String[])} [protocols] The subprotocols
2285
- * @param {Object} [options] Connection options
2286
- */
2287
- constructor(address, protocols, options) {
2288
- super();
2289
- this._binaryType = BINARY_TYPES[0];
2290
- this._closeCode = 1006;
2291
- this._closeFrameReceived = false;
2292
- this._closeFrameSent = false;
2293
- this._closeMessage = EMPTY_BUFFER;
2294
- this._closeTimer = null;
2295
- this._errorEmitted = false;
2296
- this._extensions = {};
2297
- this._paused = false;
2298
- this._protocol = "";
2299
- this._readyState = _WebSocket.CONNECTING;
2300
- this._receiver = null;
2301
- this._sender = null;
2302
- this._socket = null;
2303
- if (address !== null) {
2304
- this._bufferedAmount = 0;
2305
- this._isServer = false;
2306
- this._redirects = 0;
2307
- if (protocols === void 0) {
2308
- protocols = [];
2309
- } else if (!Array.isArray(protocols)) {
2310
- if (typeof protocols === "object" && protocols !== null) {
2311
- options = protocols;
2312
- protocols = [];
2313
- } else {
2314
- protocols = [protocols];
2315
- }
2316
- }
2317
- initAsClient(this, address, protocols, options);
2318
- } else {
2319
- this._autoPong = options.autoPong;
2320
- this._closeTimeout = options.closeTimeout;
2321
- this._isServer = true;
2322
- }
2323
- }
2324
- /**
2325
- * For historical reasons, the custom "nodebuffer" type is used by the default
2326
- * instead of "blob".
2327
- *
2328
- * @type {String}
2329
- */
2330
- get binaryType() {
2331
- return this._binaryType;
2332
- }
2333
- set binaryType(type) {
2334
- if (!BINARY_TYPES.includes(type))
2335
- return;
2336
- this._binaryType = type;
2337
- if (this._receiver)
2338
- this._receiver._binaryType = type;
2339
- }
2340
- /**
2341
- * @type {Number}
2342
- */
2343
- get bufferedAmount() {
2344
- if (!this._socket)
2345
- return this._bufferedAmount;
2346
- return this._socket._writableState.length + this._sender._bufferedBytes;
2347
- }
2348
- /**
2349
- * @type {String}
2350
- */
2351
- get extensions() {
2352
- return Object.keys(this._extensions).join();
2353
- }
2354
- /**
2355
- * @type {Boolean}
2356
- */
2357
- get isPaused() {
2358
- return this._paused;
2359
- }
2360
- /**
2361
- * @type {Function}
2362
- */
2363
- /* istanbul ignore next */
2364
- get onclose() {
2365
- return null;
2366
- }
2367
- /**
2368
- * @type {Function}
2369
- */
2370
- /* istanbul ignore next */
2371
- get onerror() {
2372
- return null;
2373
- }
2374
- /**
2375
- * @type {Function}
2376
- */
2377
- /* istanbul ignore next */
2378
- get onopen() {
2379
- return null;
2380
- }
2381
- /**
2382
- * @type {Function}
2383
- */
2384
- /* istanbul ignore next */
2385
- get onmessage() {
2386
- return null;
2387
- }
2388
- /**
2389
- * @type {String}
2390
- */
2391
- get protocol() {
2392
- return this._protocol;
2393
- }
2394
- /**
2395
- * @type {Number}
2396
- */
2397
- get readyState() {
2398
- return this._readyState;
2399
- }
2400
- /**
2401
- * @type {String}
2402
- */
2403
- get url() {
2404
- return this._url;
2405
- }
2406
- /**
2407
- * Set up the socket and the internal resources.
2408
- *
2409
- * @param {Duplex} socket The network socket between the server and client
2410
- * @param {Buffer} head The first packet of the upgraded stream
2411
- * @param {Object} options Options object
2412
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2413
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2414
- * multiple times in the same tick
2415
- * @param {Function} [options.generateMask] The function used to generate the
2416
- * masking key
2417
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
2418
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2419
- * not to skip UTF-8 validation for text and close messages
2420
- * @private
2421
- */
2422
- setSocket(socket, head, options) {
2423
- const receiver = new Receiver({
2424
- allowSynchronousEvents: options.allowSynchronousEvents,
2425
- binaryType: this.binaryType,
2426
- extensions: this._extensions,
2427
- isServer: this._isServer,
2428
- maxPayload: options.maxPayload,
2429
- skipUTF8Validation: options.skipUTF8Validation
2430
- });
2431
- const sender = new Sender(socket, this._extensions, options.generateMask);
2432
- this._receiver = receiver;
2433
- this._sender = sender;
2434
- this._socket = socket;
2435
- receiver[kWebSocket] = this;
2436
- sender[kWebSocket] = this;
2437
- socket[kWebSocket] = this;
2438
- receiver.on("conclude", receiverOnConclude);
2439
- receiver.on("drain", receiverOnDrain);
2440
- receiver.on("error", receiverOnError);
2441
- receiver.on("message", receiverOnMessage);
2442
- receiver.on("ping", receiverOnPing);
2443
- receiver.on("pong", receiverOnPong);
2444
- sender.onerror = senderOnError;
2445
- if (socket.setTimeout)
2446
- socket.setTimeout(0);
2447
- if (socket.setNoDelay)
2448
- socket.setNoDelay();
2449
- if (head.length > 0)
2450
- socket.unshift(head);
2451
- socket.on("close", socketOnClose);
2452
- socket.on("data", socketOnData);
2453
- socket.on("end", socketOnEnd);
2454
- socket.on("error", socketOnError);
2455
- this._readyState = _WebSocket.OPEN;
2456
- this.emit("open");
2457
- }
2458
- /**
2459
- * Emit the `'close'` event.
2460
- *
2461
- * @private
2462
- */
2463
- emitClose() {
2464
- if (!this._socket) {
2465
- this._readyState = _WebSocket.CLOSED;
2466
- this.emit("close", this._closeCode, this._closeMessage);
2467
- return;
2468
- }
2469
- if (this._extensions[PerMessageDeflate.extensionName]) {
2470
- this._extensions[PerMessageDeflate.extensionName].cleanup();
2471
- }
2472
- this._receiver.removeAllListeners();
2473
- this._readyState = _WebSocket.CLOSED;
2474
- this.emit("close", this._closeCode, this._closeMessage);
2475
- }
2476
- /**
2477
- * Start a closing handshake.
2478
- *
2479
- * +----------+ +-----------+ +----------+
2480
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2481
- * | +----------+ +-----------+ +----------+ |
2482
- * +----------+ +-----------+ |
2483
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2484
- * +----------+ +-----------+ |
2485
- * | | | +---+ |
2486
- * +------------------------+-->|fin| - - - -
2487
- * | +---+ | +---+
2488
- * - - - - -|fin|<---------------------+
2489
- * +---+
2490
- *
2491
- * @param {Number} [code] Status code explaining why the connection is closing
2492
- * @param {(String|Buffer)} [data] The reason why the connection is
2493
- * closing
2494
- * @public
2495
- */
2496
- close(code, data) {
2497
- if (this.readyState === _WebSocket.CLOSED)
2498
- return;
2499
- if (this.readyState === _WebSocket.CONNECTING) {
2500
- const msg = "WebSocket was closed before the connection was established";
2501
- abortHandshake(this, this._req, msg);
2502
- return;
2503
- }
2504
- if (this.readyState === _WebSocket.CLOSING) {
2505
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2506
- this._socket.end();
2507
- }
2508
- return;
2509
- }
2510
- this._readyState = _WebSocket.CLOSING;
2511
- this._sender.close(code, data, !this._isServer, (err) => {
2512
- if (err)
2513
- return;
2514
- this._closeFrameSent = true;
2515
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2516
- this._socket.end();
2517
- }
2518
- });
2519
- setCloseTimer(this);
2520
- }
2521
- /**
2522
- * Pause the socket.
2523
- *
2524
- * @public
2525
- */
2526
- pause() {
2527
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2528
- return;
2529
- }
2530
- this._paused = true;
2531
- this._socket.pause();
2532
- }
2533
- /**
2534
- * Send a ping.
2535
- *
2536
- * @param {*} [data] The data to send
2537
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2538
- * @param {Function} [cb] Callback which is executed when the ping is sent
2539
- * @public
2540
- */
2541
- ping(data, mask, cb) {
2542
- if (this.readyState === _WebSocket.CONNECTING) {
2543
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2544
- }
2545
- if (typeof data === "function") {
2546
- cb = data;
2547
- data = mask = void 0;
2548
- } else if (typeof mask === "function") {
2549
- cb = mask;
2550
- mask = void 0;
2551
- }
2552
- if (typeof data === "number")
2553
- data = data.toString();
2554
- if (this.readyState !== _WebSocket.OPEN) {
2555
- sendAfterClose(this, data, cb);
2556
- return;
2557
- }
2558
- if (mask === void 0)
2559
- mask = !this._isServer;
2560
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2561
- }
2562
- /**
2563
- * Send a pong.
2564
- *
2565
- * @param {*} [data] The data to send
2566
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2567
- * @param {Function} [cb] Callback which is executed when the pong is sent
2568
- * @public
2569
- */
2570
- pong(data, mask, cb) {
2571
- if (this.readyState === _WebSocket.CONNECTING) {
2572
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2573
- }
2574
- if (typeof data === "function") {
2575
- cb = data;
2576
- data = mask = void 0;
2577
- } else if (typeof mask === "function") {
2578
- cb = mask;
2579
- mask = void 0;
2580
- }
2581
- if (typeof data === "number")
2582
- data = data.toString();
2583
- if (this.readyState !== _WebSocket.OPEN) {
2584
- sendAfterClose(this, data, cb);
2585
- return;
2586
- }
2587
- if (mask === void 0)
2588
- mask = !this._isServer;
2589
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2590
- }
2591
- /**
2592
- * Resume the socket.
2593
- *
2594
- * @public
2595
- */
2596
- resume() {
2597
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2598
- return;
2599
- }
2600
- this._paused = false;
2601
- if (!this._receiver._writableState.needDrain)
2602
- this._socket.resume();
2603
- }
2604
- /**
2605
- * Send a data message.
2606
- *
2607
- * @param {*} data The message to send
2608
- * @param {Object} [options] Options object
2609
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2610
- * text
2611
- * @param {Boolean} [options.compress] Specifies whether or not to compress
2612
- * `data`
2613
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2614
- * last one
2615
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2616
- * @param {Function} [cb] Callback which is executed when data is written out
2617
- * @public
2618
- */
2619
- send(data, options, cb) {
2620
- if (this.readyState === _WebSocket.CONNECTING) {
2621
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2622
- }
2623
- if (typeof options === "function") {
2624
- cb = options;
2625
- options = {};
2626
- }
2627
- if (typeof data === "number")
2628
- data = data.toString();
2629
- if (this.readyState !== _WebSocket.OPEN) {
2630
- sendAfterClose(this, data, cb);
2631
- return;
2632
- }
2633
- const opts = {
2634
- binary: typeof data !== "string",
2635
- mask: !this._isServer,
2636
- compress: true,
2637
- fin: true,
2638
- ...options
2639
- };
2640
- if (!this._extensions[PerMessageDeflate.extensionName]) {
2641
- opts.compress = false;
2642
- }
2643
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2644
- }
2645
- /**
2646
- * Forcibly close the connection.
2647
- *
2648
- * @public
2649
- */
2650
- terminate() {
2651
- if (this.readyState === _WebSocket.CLOSED)
2652
- return;
2653
- if (this.readyState === _WebSocket.CONNECTING) {
2654
- const msg = "WebSocket was closed before the connection was established";
2655
- abortHandshake(this, this._req, msg);
2656
- return;
2657
- }
2658
- if (this._socket) {
2659
- this._readyState = _WebSocket.CLOSING;
2660
- this._socket.destroy();
2661
- }
2662
- }
2663
- };
2664
- Object.defineProperty(WebSocket2, "CONNECTING", {
2665
- enumerable: true,
2666
- value: readyStates.indexOf("CONNECTING")
2667
- });
2668
- Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2669
- enumerable: true,
2670
- value: readyStates.indexOf("CONNECTING")
2671
- });
2672
- Object.defineProperty(WebSocket2, "OPEN", {
2673
- enumerable: true,
2674
- value: readyStates.indexOf("OPEN")
2675
- });
2676
- Object.defineProperty(WebSocket2.prototype, "OPEN", {
2677
- enumerable: true,
2678
- value: readyStates.indexOf("OPEN")
2679
- });
2680
- Object.defineProperty(WebSocket2, "CLOSING", {
2681
- enumerable: true,
2682
- value: readyStates.indexOf("CLOSING")
2683
- });
2684
- Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2685
- enumerable: true,
2686
- value: readyStates.indexOf("CLOSING")
2687
- });
2688
- Object.defineProperty(WebSocket2, "CLOSED", {
2689
- enumerable: true,
2690
- value: readyStates.indexOf("CLOSED")
2691
- });
2692
- Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2693
- enumerable: true,
2694
- value: readyStates.indexOf("CLOSED")
2695
- });
2696
- [
2697
- "binaryType",
2698
- "bufferedAmount",
2699
- "extensions",
2700
- "isPaused",
2701
- "protocol",
2702
- "readyState",
2703
- "url"
2704
- ].forEach((property) => {
2705
- Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2706
- });
2707
- ["open", "error", "close", "message"].forEach((method) => {
2708
- Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2709
- enumerable: true,
2710
- get() {
2711
- for (const listener of this.listeners(method)) {
2712
- if (listener[kForOnEventAttribute])
2713
- return listener[kListener];
2714
- }
2715
- return null;
2716
- },
2717
- set(handler) {
2718
- for (const listener of this.listeners(method)) {
2719
- if (listener[kForOnEventAttribute]) {
2720
- this.removeListener(method, listener);
2721
- break;
2722
- }
2723
- }
2724
- if (typeof handler !== "function")
2725
- return;
2726
- this.addEventListener(method, handler, {
2727
- [kForOnEventAttribute]: true
2728
- });
2729
- }
2730
- });
2731
- });
2732
- WebSocket2.prototype.addEventListener = addEventListener;
2733
- WebSocket2.prototype.removeEventListener = removeEventListener;
2734
- module.exports = WebSocket2;
2735
- function initAsClient(websocket, address, protocols, options) {
2736
- const opts = {
2737
- allowSynchronousEvents: true,
2738
- autoPong: true,
2739
- closeTimeout: CLOSE_TIMEOUT,
2740
- protocolVersion: protocolVersions[1],
2741
- maxPayload: 100 * 1024 * 1024,
2742
- skipUTF8Validation: false,
2743
- perMessageDeflate: true,
2744
- followRedirects: false,
2745
- maxRedirects: 10,
2746
- ...options,
2747
- socketPath: void 0,
2748
- hostname: void 0,
2749
- protocol: void 0,
2750
- timeout: void 0,
2751
- method: "GET",
2752
- host: void 0,
2753
- path: void 0,
2754
- port: void 0
2755
- };
2756
- websocket._autoPong = opts.autoPong;
2757
- websocket._closeTimeout = opts.closeTimeout;
2758
- if (!protocolVersions.includes(opts.protocolVersion)) {
2759
- throw new RangeError(
2760
- `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2761
- );
2762
- }
2763
- let parsedUrl;
2764
- if (address instanceof URL2) {
2765
- parsedUrl = address;
2766
- } else {
2767
- try {
2768
- parsedUrl = new URL2(address);
2769
- } catch (e) {
2770
- throw new SyntaxError(`Invalid URL: ${address}`);
2771
- }
2772
- }
2773
- if (parsedUrl.protocol === "http:") {
2774
- parsedUrl.protocol = "ws:";
2775
- } else if (parsedUrl.protocol === "https:") {
2776
- parsedUrl.protocol = "wss:";
2777
- }
2778
- websocket._url = parsedUrl.href;
2779
- const isSecure = parsedUrl.protocol === "wss:";
2780
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2781
- let invalidUrlMessage;
2782
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2783
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2784
- } else if (isIpcUrl && !parsedUrl.pathname) {
2785
- invalidUrlMessage = "The URL's pathname is empty";
2786
- } else if (parsedUrl.hash) {
2787
- invalidUrlMessage = "The URL contains a fragment identifier";
2788
- }
2789
- if (invalidUrlMessage) {
2790
- const err = new SyntaxError(invalidUrlMessage);
2791
- if (websocket._redirects === 0) {
2792
- throw err;
2793
- } else {
2794
- emitErrorAndClose(websocket, err);
2795
- return;
2796
- }
2797
- }
2798
- const defaultPort = isSecure ? 443 : 80;
2799
- const key = randomBytes(16).toString("base64");
2800
- const request = isSecure ? https.request : http.request;
2801
- const protocolSet = /* @__PURE__ */ new Set();
2802
- let perMessageDeflate;
2803
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2804
- opts.defaultPort = opts.defaultPort || defaultPort;
2805
- opts.port = parsedUrl.port || defaultPort;
2806
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2807
- opts.headers = {
2808
- ...opts.headers,
2809
- "Sec-WebSocket-Version": opts.protocolVersion,
2810
- "Sec-WebSocket-Key": key,
2811
- Connection: "Upgrade",
2812
- Upgrade: "websocket"
2813
- };
2814
- opts.path = parsedUrl.pathname + parsedUrl.search;
2815
- opts.timeout = opts.handshakeTimeout;
2816
- if (opts.perMessageDeflate) {
2817
- perMessageDeflate = new PerMessageDeflate(
2818
- opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2819
- false,
2820
- opts.maxPayload
2821
- );
2822
- opts.headers["Sec-WebSocket-Extensions"] = format({
2823
- [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2824
- });
2825
- }
2826
- if (protocols.length) {
2827
- for (const protocol of protocols) {
2828
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2829
- throw new SyntaxError(
2830
- "An invalid or duplicated subprotocol was specified"
2831
- );
2832
- }
2833
- protocolSet.add(protocol);
2834
- }
2835
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2836
- }
2837
- if (opts.origin) {
2838
- if (opts.protocolVersion < 13) {
2839
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2840
- } else {
2841
- opts.headers.Origin = opts.origin;
2842
- }
2843
- }
2844
- if (parsedUrl.username || parsedUrl.password) {
2845
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2846
- }
2847
- if (isIpcUrl) {
2848
- const parts = opts.path.split(":");
2849
- opts.socketPath = parts[0];
2850
- opts.path = parts[1];
2851
- }
2852
- let req;
2853
- if (opts.followRedirects) {
2854
- if (websocket._redirects === 0) {
2855
- websocket._originalIpc = isIpcUrl;
2856
- websocket._originalSecure = isSecure;
2857
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2858
- const headers = options && options.headers;
2859
- options = { ...options, headers: {} };
2860
- if (headers) {
2861
- for (const [key2, value] of Object.entries(headers)) {
2862
- options.headers[key2.toLowerCase()] = value;
2863
- }
2864
- }
2865
- } else if (websocket.listenerCount("redirect") === 0) {
2866
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2867
- if (!isSameHost || websocket._originalSecure && !isSecure) {
2868
- delete opts.headers.authorization;
2869
- delete opts.headers.cookie;
2870
- if (!isSameHost)
2871
- delete opts.headers.host;
2872
- opts.auth = void 0;
2873
- }
2874
- }
2875
- if (opts.auth && !options.headers.authorization) {
2876
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2877
- }
2878
- req = websocket._req = request(opts);
2879
- if (websocket._redirects) {
2880
- websocket.emit("redirect", websocket.url, req);
2881
- }
2882
- } else {
2883
- req = websocket._req = request(opts);
2884
- }
2885
- if (opts.timeout) {
2886
- req.on("timeout", () => {
2887
- abortHandshake(websocket, req, "Opening handshake has timed out");
2888
- });
2889
- }
2890
- req.on("error", (err) => {
2891
- if (req === null || req[kAborted])
2892
- return;
2893
- req = websocket._req = null;
2894
- emitErrorAndClose(websocket, err);
2895
- });
2896
- req.on("response", (res) => {
2897
- const location = res.headers.location;
2898
- const statusCode = res.statusCode;
2899
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2900
- if (++websocket._redirects > opts.maxRedirects) {
2901
- abortHandshake(websocket, req, "Maximum redirects exceeded");
2902
- return;
2903
- }
2904
- req.abort();
2905
- let addr;
2906
- try {
2907
- addr = new URL2(location, address);
2908
- } catch (e) {
2909
- const err = new SyntaxError(`Invalid URL: ${location}`);
2910
- emitErrorAndClose(websocket, err);
2911
- return;
2912
- }
2913
- initAsClient(websocket, addr, protocols, options);
2914
- } else if (!websocket.emit("unexpected-response", req, res)) {
2915
- abortHandshake(
2916
- websocket,
2917
- req,
2918
- `Unexpected server response: ${res.statusCode}`
2919
- );
2920
- }
2921
- });
2922
- req.on("upgrade", (res, socket, head) => {
2923
- websocket.emit("upgrade", res);
2924
- if (websocket.readyState !== WebSocket2.CONNECTING)
2925
- return;
2926
- req = websocket._req = null;
2927
- const upgrade = res.headers.upgrade;
2928
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2929
- abortHandshake(websocket, socket, "Invalid Upgrade header");
2930
- return;
2931
- }
2932
- const digest = createHash("sha1").update(key + GUID).digest("base64");
2933
- if (res.headers["sec-websocket-accept"] !== digest) {
2934
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2935
- return;
2936
- }
2937
- const serverProt = res.headers["sec-websocket-protocol"];
2938
- let protError;
2939
- if (serverProt !== void 0) {
2940
- if (!protocolSet.size) {
2941
- protError = "Server sent a subprotocol but none was requested";
2942
- } else if (!protocolSet.has(serverProt)) {
2943
- protError = "Server sent an invalid subprotocol";
2944
- }
2945
- } else if (protocolSet.size) {
2946
- protError = "Server sent no subprotocol";
2947
- }
2948
- if (protError) {
2949
- abortHandshake(websocket, socket, protError);
2950
- return;
2951
- }
2952
- if (serverProt)
2953
- websocket._protocol = serverProt;
2954
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2955
- if (secWebSocketExtensions !== void 0) {
2956
- if (!perMessageDeflate) {
2957
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2958
- abortHandshake(websocket, socket, message);
2959
- return;
2960
- }
2961
- let extensions;
2962
- try {
2963
- extensions = parse(secWebSocketExtensions);
2964
- } catch (err) {
2965
- const message = "Invalid Sec-WebSocket-Extensions header";
2966
- abortHandshake(websocket, socket, message);
2967
- return;
2968
- }
2969
- const extensionNames = Object.keys(extensions);
2970
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2971
- const message = "Server indicated an extension that was not requested";
2972
- abortHandshake(websocket, socket, message);
2973
- return;
2974
- }
2975
- try {
2976
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2977
- } catch (err) {
2978
- const message = "Invalid Sec-WebSocket-Extensions header";
2979
- abortHandshake(websocket, socket, message);
2980
- return;
2981
- }
2982
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2983
- }
2984
- websocket.setSocket(socket, head, {
2985
- allowSynchronousEvents: opts.allowSynchronousEvents,
2986
- generateMask: opts.generateMask,
2987
- maxPayload: opts.maxPayload,
2988
- skipUTF8Validation: opts.skipUTF8Validation
2989
- });
2990
- });
2991
- if (opts.finishRequest) {
2992
- opts.finishRequest(req, websocket);
2993
- } else {
2994
- req.end();
2995
- }
2996
- }
2997
- function emitErrorAndClose(websocket, err) {
2998
- websocket._readyState = WebSocket2.CLOSING;
2999
- websocket._errorEmitted = true;
3000
- websocket.emit("error", err);
3001
- websocket.emitClose();
3002
- }
3003
- function netConnect(options) {
3004
- options.path = options.socketPath;
3005
- return net.connect(options);
3006
- }
3007
- function tlsConnect(options) {
3008
- options.path = void 0;
3009
- if (!options.servername && options.servername !== "") {
3010
- options.servername = net.isIP(options.host) ? "" : options.host;
3011
- }
3012
- return tls.connect(options);
3013
- }
3014
- function abortHandshake(websocket, stream, message) {
3015
- websocket._readyState = WebSocket2.CLOSING;
3016
- const err = new Error(message);
3017
- Error.captureStackTrace(err, abortHandshake);
3018
- if (stream.setHeader) {
3019
- stream[kAborted] = true;
3020
- stream.abort();
3021
- if (stream.socket && !stream.socket.destroyed) {
3022
- stream.socket.destroy();
3023
- }
3024
- process.nextTick(emitErrorAndClose, websocket, err);
3025
- } else {
3026
- stream.destroy(err);
3027
- stream.once("error", websocket.emit.bind(websocket, "error"));
3028
- stream.once("close", websocket.emitClose.bind(websocket));
3029
- }
3030
- }
3031
- function sendAfterClose(websocket, data, cb) {
3032
- if (data) {
3033
- const length = isBlob(data) ? data.size : toBuffer(data).length;
3034
- if (websocket._socket)
3035
- websocket._sender._bufferedBytes += length;
3036
- else
3037
- websocket._bufferedAmount += length;
3038
- }
3039
- if (cb) {
3040
- const err = new Error(
3041
- `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3042
- );
3043
- process.nextTick(cb, err);
3044
- }
3045
- }
3046
- function receiverOnConclude(code, reason) {
3047
- const websocket = this[kWebSocket];
3048
- websocket._closeFrameReceived = true;
3049
- websocket._closeMessage = reason;
3050
- websocket._closeCode = code;
3051
- if (websocket._socket[kWebSocket] === void 0)
3052
- return;
3053
- websocket._socket.removeListener("data", socketOnData);
3054
- process.nextTick(resume, websocket._socket);
3055
- if (code === 1005)
3056
- websocket.close();
3057
- else
3058
- websocket.close(code, reason);
3059
- }
3060
- function receiverOnDrain() {
3061
- const websocket = this[kWebSocket];
3062
- if (!websocket.isPaused)
3063
- websocket._socket.resume();
3064
- }
3065
- function receiverOnError(err) {
3066
- const websocket = this[kWebSocket];
3067
- if (websocket._socket[kWebSocket] !== void 0) {
3068
- websocket._socket.removeListener("data", socketOnData);
3069
- process.nextTick(resume, websocket._socket);
3070
- websocket.close(err[kStatusCode]);
3071
- }
3072
- if (!websocket._errorEmitted) {
3073
- websocket._errorEmitted = true;
3074
- websocket.emit("error", err);
3075
- }
3076
- }
3077
- function receiverOnFinish() {
3078
- this[kWebSocket].emitClose();
3079
- }
3080
- function receiverOnMessage(data, isBinary) {
3081
- this[kWebSocket].emit("message", data, isBinary);
3082
- }
3083
- function receiverOnPing(data) {
3084
- const websocket = this[kWebSocket];
3085
- if (websocket._autoPong)
3086
- websocket.pong(data, !this._isServer, NOOP);
3087
- websocket.emit("ping", data);
3088
- }
3089
- function receiverOnPong(data) {
3090
- this[kWebSocket].emit("pong", data);
3091
- }
3092
- function resume(stream) {
3093
- stream.resume();
3094
- }
3095
- function senderOnError(err) {
3096
- const websocket = this[kWebSocket];
3097
- if (websocket.readyState === WebSocket2.CLOSED)
3098
- return;
3099
- if (websocket.readyState === WebSocket2.OPEN) {
3100
- websocket._readyState = WebSocket2.CLOSING;
3101
- setCloseTimer(websocket);
3102
- }
3103
- this._socket.end();
3104
- if (!websocket._errorEmitted) {
3105
- websocket._errorEmitted = true;
3106
- websocket.emit("error", err);
3107
- }
3108
- }
3109
- function setCloseTimer(websocket) {
3110
- websocket._closeTimer = setTimeout(
3111
- websocket._socket.destroy.bind(websocket._socket),
3112
- websocket._closeTimeout
3113
- );
3114
- }
3115
- function socketOnClose() {
3116
- const websocket = this[kWebSocket];
3117
- this.removeListener("close", socketOnClose);
3118
- this.removeListener("data", socketOnData);
3119
- this.removeListener("end", socketOnEnd);
3120
- websocket._readyState = WebSocket2.CLOSING;
3121
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3122
- const chunk = this.read(this._readableState.length);
3123
- websocket._receiver.write(chunk);
3124
- }
3125
- websocket._receiver.end();
3126
- this[kWebSocket] = void 0;
3127
- clearTimeout(websocket._closeTimer);
3128
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3129
- websocket.emitClose();
3130
- } else {
3131
- websocket._receiver.on("error", receiverOnFinish);
3132
- websocket._receiver.on("finish", receiverOnFinish);
3133
- }
3134
- }
3135
- function socketOnData(chunk) {
3136
- if (!this[kWebSocket]._receiver.write(chunk)) {
3137
- this.pause();
3138
- }
3139
- }
3140
- function socketOnEnd() {
3141
- const websocket = this[kWebSocket];
3142
- websocket._readyState = WebSocket2.CLOSING;
3143
- websocket._receiver.end();
3144
- this.end();
3145
- }
3146
- function socketOnError() {
3147
- const websocket = this[kWebSocket];
3148
- this.removeListener("error", socketOnError);
3149
- this.on("error", NOOP);
3150
- if (websocket) {
3151
- websocket._readyState = WebSocket2.CLOSING;
3152
- this.destroy();
3153
- }
3154
- }
3155
- }
3156
- });
3157
-
3158
- // ../../../node_modules/ws/lib/stream.js
3159
- var require_stream = __commonJS({
3160
- "../../../node_modules/ws/lib/stream.js"(exports$1, module) {
3161
- require_websocket();
3162
- var { Duplex } = __require("stream");
3163
- function emitClose(stream) {
3164
- stream.emit("close");
3165
- }
3166
- function duplexOnEnd() {
3167
- if (!this.destroyed && this._writableState.finished) {
3168
- this.destroy();
3169
- }
3170
- }
3171
- function duplexOnError(err) {
3172
- this.removeListener("error", duplexOnError);
3173
- this.destroy();
3174
- if (this.listenerCount("error") === 0) {
3175
- this.emit("error", err);
3176
- }
3177
- }
3178
- function createWebSocketStream(ws, options) {
3179
- let terminateOnDestroy = true;
3180
- const duplex = new Duplex({
3181
- ...options,
3182
- autoDestroy: false,
3183
- emitClose: false,
3184
- objectMode: false,
3185
- writableObjectMode: false
3186
- });
3187
- ws.on("message", function message(msg, isBinary) {
3188
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3189
- if (!duplex.push(data))
3190
- ws.pause();
3191
- });
3192
- ws.once("error", function error(err) {
3193
- if (duplex.destroyed)
3194
- return;
3195
- terminateOnDestroy = false;
3196
- duplex.destroy(err);
3197
- });
3198
- ws.once("close", function close() {
3199
- if (duplex.destroyed)
3200
- return;
3201
- duplex.push(null);
3202
- });
3203
- duplex._destroy = function(err, callback) {
3204
- if (ws.readyState === ws.CLOSED) {
3205
- callback(err);
3206
- process.nextTick(emitClose, duplex);
3207
- return;
3208
- }
3209
- let called = false;
3210
- ws.once("error", function error(err2) {
3211
- called = true;
3212
- callback(err2);
3213
- });
3214
- ws.once("close", function close() {
3215
- if (!called)
3216
- callback(err);
3217
- process.nextTick(emitClose, duplex);
3218
- });
3219
- if (terminateOnDestroy)
3220
- ws.terminate();
3221
- };
3222
- duplex._final = function(callback) {
3223
- if (ws.readyState === ws.CONNECTING) {
3224
- ws.once("open", function open() {
3225
- duplex._final(callback);
3226
- });
3227
- return;
3228
- }
3229
- if (ws._socket === null)
3230
- return;
3231
- if (ws._socket._writableState.finished) {
3232
- callback();
3233
- if (duplex._readableState.endEmitted)
3234
- duplex.destroy();
3235
- } else {
3236
- ws._socket.once("finish", function finish() {
3237
- callback();
3238
- });
3239
- ws.close();
3240
- }
3241
- };
3242
- duplex._read = function() {
3243
- if (ws.isPaused)
3244
- ws.resume();
3245
- };
3246
- duplex._write = function(chunk, encoding, callback) {
3247
- if (ws.readyState === ws.CONNECTING) {
3248
- ws.once("open", function open() {
3249
- duplex._write(chunk, encoding, callback);
3250
- });
3251
- return;
3252
- }
3253
- ws.send(chunk, callback);
3254
- };
3255
- duplex.on("end", duplexOnEnd);
3256
- duplex.on("error", duplexOnError);
3257
- return duplex;
3258
- }
3259
- module.exports = createWebSocketStream;
3260
- }
3261
- });
3262
-
3263
- // ../../../node_modules/ws/lib/subprotocol.js
3264
- var require_subprotocol = __commonJS({
3265
- "../../../node_modules/ws/lib/subprotocol.js"(exports$1, module) {
3266
- var { tokenChars } = require_validation();
3267
- function parse(header) {
3268
- const protocols = /* @__PURE__ */ new Set();
3269
- let start = -1;
3270
- let end = -1;
3271
- let i = 0;
3272
- for (i; i < header.length; i++) {
3273
- const code = header.charCodeAt(i);
3274
- if (end === -1 && tokenChars[code] === 1) {
3275
- if (start === -1)
3276
- start = i;
3277
- } else if (i !== 0 && (code === 32 || code === 9)) {
3278
- if (end === -1 && start !== -1)
3279
- end = i;
3280
- } else if (code === 44) {
3281
- if (start === -1) {
3282
- throw new SyntaxError(`Unexpected character at index ${i}`);
3283
- }
3284
- if (end === -1)
3285
- end = i;
3286
- const protocol2 = header.slice(start, end);
3287
- if (protocols.has(protocol2)) {
3288
- throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3289
- }
3290
- protocols.add(protocol2);
3291
- start = end = -1;
3292
- } else {
3293
- throw new SyntaxError(`Unexpected character at index ${i}`);
3294
- }
3295
- }
3296
- if (start === -1 || end !== -1) {
3297
- throw new SyntaxError("Unexpected end of input");
3298
- }
3299
- const protocol = header.slice(start, i);
3300
- if (protocols.has(protocol)) {
3301
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3302
- }
3303
- protocols.add(protocol);
3304
- return protocols;
3305
- }
3306
- module.exports = { parse };
3307
- }
3308
- });
3309
-
3310
- // ../../../node_modules/ws/lib/websocket-server.js
3311
- var require_websocket_server = __commonJS({
3312
- "../../../node_modules/ws/lib/websocket-server.js"(exports$1, module) {
3313
- var EventEmitter = __require("events");
3314
- var http = __require("http");
3315
- var { Duplex } = __require("stream");
3316
- var { createHash } = __require("crypto");
3317
- var extension = require_extension();
3318
- var PerMessageDeflate = require_permessage_deflate();
3319
- var subprotocol = require_subprotocol();
3320
- var WebSocket2 = require_websocket();
3321
- var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3322
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3323
- var RUNNING = 0;
3324
- var CLOSING = 1;
3325
- var CLOSED = 2;
3326
- var WebSocketServer = class extends EventEmitter {
3327
- /**
3328
- * Create a `WebSocketServer` instance.
3329
- *
3330
- * @param {Object} options Configuration options
3331
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3332
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3333
- * multiple times in the same tick
3334
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3335
- * automatically send a pong in response to a ping
3336
- * @param {Number} [options.backlog=511] The maximum length of the queue of
3337
- * pending connections
3338
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3339
- * track clients
3340
- * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3341
- * wait for the closing handshake to finish after `websocket.close()` is
3342
- * called
3343
- * @param {Function} [options.handleProtocols] A hook to handle protocols
3344
- * @param {String} [options.host] The hostname where to bind the server
3345
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3346
- * size
3347
- * @param {Boolean} [options.noServer=false] Enable no server mode
3348
- * @param {String} [options.path] Accept only connections matching this path
3349
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3350
- * permessage-deflate
3351
- * @param {Number} [options.port] The port where to bind the server
3352
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3353
- * server to use
3354
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3355
- * not to skip UTF-8 validation for text and close messages
3356
- * @param {Function} [options.verifyClient] A hook to reject connections
3357
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3358
- * class to use. It must be the `WebSocket` class or class that extends it
3359
- * @param {Function} [callback] A listener for the `listening` event
3360
- */
3361
- constructor(options, callback) {
3362
- super();
3363
- options = {
3364
- allowSynchronousEvents: true,
3365
- autoPong: true,
3366
- maxPayload: 100 * 1024 * 1024,
3367
- skipUTF8Validation: false,
3368
- perMessageDeflate: false,
3369
- handleProtocols: null,
3370
- clientTracking: true,
3371
- closeTimeout: CLOSE_TIMEOUT,
3372
- verifyClient: null,
3373
- noServer: false,
3374
- backlog: null,
3375
- // use default (511 as implemented in net.js)
3376
- server: null,
3377
- host: null,
3378
- path: null,
3379
- port: null,
3380
- WebSocket: WebSocket2,
3381
- ...options
3382
- };
3383
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3384
- throw new TypeError(
3385
- 'One and only one of the "port", "server", or "noServer" options must be specified'
3386
- );
3387
- }
3388
- if (options.port != null) {
3389
- this._server = http.createServer((req, res) => {
3390
- const body = http.STATUS_CODES[426];
3391
- res.writeHead(426, {
3392
- "Content-Length": body.length,
3393
- "Content-Type": "text/plain"
3394
- });
3395
- res.end(body);
3396
- });
3397
- this._server.listen(
3398
- options.port,
3399
- options.host,
3400
- options.backlog,
3401
- callback
3402
- );
3403
- } else if (options.server) {
3404
- this._server = options.server;
3405
- }
3406
- if (this._server) {
3407
- const emitConnection = this.emit.bind(this, "connection");
3408
- this._removeListeners = addListeners(this._server, {
3409
- listening: this.emit.bind(this, "listening"),
3410
- error: this.emit.bind(this, "error"),
3411
- upgrade: (req, socket, head) => {
3412
- this.handleUpgrade(req, socket, head, emitConnection);
3413
- }
3414
- });
3415
- }
3416
- if (options.perMessageDeflate === true)
3417
- options.perMessageDeflate = {};
3418
- if (options.clientTracking) {
3419
- this.clients = /* @__PURE__ */ new Set();
3420
- this._shouldEmitClose = false;
3421
- }
3422
- this.options = options;
3423
- this._state = RUNNING;
3424
- }
3425
- /**
3426
- * Returns the bound address, the address family name, and port of the server
3427
- * as reported by the operating system if listening on an IP socket.
3428
- * If the server is listening on a pipe or UNIX domain socket, the name is
3429
- * returned as a string.
3430
- *
3431
- * @return {(Object|String|null)} The address of the server
3432
- * @public
3433
- */
3434
- address() {
3435
- if (this.options.noServer) {
3436
- throw new Error('The server is operating in "noServer" mode');
3437
- }
3438
- if (!this._server)
3439
- return null;
3440
- return this._server.address();
3441
- }
3442
- /**
3443
- * Stop the server from accepting new connections and emit the `'close'` event
3444
- * when all existing connections are closed.
3445
- *
3446
- * @param {Function} [cb] A one-time listener for the `'close'` event
3447
- * @public
3448
- */
3449
- close(cb) {
3450
- if (this._state === CLOSED) {
3451
- if (cb) {
3452
- this.once("close", () => {
3453
- cb(new Error("The server is not running"));
3454
- });
3455
- }
3456
- process.nextTick(emitClose, this);
3457
- return;
3458
- }
3459
- if (cb)
3460
- this.once("close", cb);
3461
- if (this._state === CLOSING)
3462
- return;
3463
- this._state = CLOSING;
3464
- if (this.options.noServer || this.options.server) {
3465
- if (this._server) {
3466
- this._removeListeners();
3467
- this._removeListeners = this._server = null;
3468
- }
3469
- if (this.clients) {
3470
- if (!this.clients.size) {
3471
- process.nextTick(emitClose, this);
3472
- } else {
3473
- this._shouldEmitClose = true;
3474
- }
3475
- } else {
3476
- process.nextTick(emitClose, this);
3477
- }
3478
- } else {
3479
- const server = this._server;
3480
- this._removeListeners();
3481
- this._removeListeners = this._server = null;
3482
- server.close(() => {
3483
- emitClose(this);
3484
- });
3485
- }
3486
- }
3487
- /**
3488
- * See if a given request should be handled by this server instance.
3489
- *
3490
- * @param {http.IncomingMessage} req Request object to inspect
3491
- * @return {Boolean} `true` if the request is valid, else `false`
3492
- * @public
3493
- */
3494
- shouldHandle(req) {
3495
- if (this.options.path) {
3496
- const index = req.url.indexOf("?");
3497
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3498
- if (pathname !== this.options.path)
3499
- return false;
3500
- }
3501
- return true;
3502
- }
3503
- /**
3504
- * Handle a HTTP Upgrade request.
3505
- *
3506
- * @param {http.IncomingMessage} req The request object
3507
- * @param {Duplex} socket The network socket between the server and client
3508
- * @param {Buffer} head The first packet of the upgraded stream
3509
- * @param {Function} cb Callback
3510
- * @public
3511
- */
3512
- handleUpgrade(req, socket, head, cb) {
3513
- socket.on("error", socketOnError);
3514
- const key = req.headers["sec-websocket-key"];
3515
- const upgrade = req.headers.upgrade;
3516
- const version = +req.headers["sec-websocket-version"];
3517
- if (req.method !== "GET") {
3518
- const message = "Invalid HTTP method";
3519
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3520
- return;
3521
- }
3522
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3523
- const message = "Invalid Upgrade header";
3524
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3525
- return;
3526
- }
3527
- if (key === void 0 || !keyRegex.test(key)) {
3528
- const message = "Missing or invalid Sec-WebSocket-Key header";
3529
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3530
- return;
3531
- }
3532
- if (version !== 13 && version !== 8) {
3533
- const message = "Missing or invalid Sec-WebSocket-Version header";
3534
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3535
- "Sec-WebSocket-Version": "13, 8"
3536
- });
3537
- return;
3538
- }
3539
- if (!this.shouldHandle(req)) {
3540
- abortHandshake(socket, 400);
3541
- return;
3542
- }
3543
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3544
- let protocols = /* @__PURE__ */ new Set();
3545
- if (secWebSocketProtocol !== void 0) {
3546
- try {
3547
- protocols = subprotocol.parse(secWebSocketProtocol);
3548
- } catch (err) {
3549
- const message = "Invalid Sec-WebSocket-Protocol header";
3550
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3551
- return;
3552
- }
3553
- }
3554
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3555
- const extensions = {};
3556
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3557
- const perMessageDeflate = new PerMessageDeflate(
3558
- this.options.perMessageDeflate,
3559
- true,
3560
- this.options.maxPayload
3561
- );
3562
- try {
3563
- const offers = extension.parse(secWebSocketExtensions);
3564
- if (offers[PerMessageDeflate.extensionName]) {
3565
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3566
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3567
- }
3568
- } catch (err) {
3569
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3570
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3571
- return;
3572
- }
3573
- }
3574
- if (this.options.verifyClient) {
3575
- const info = {
3576
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3577
- secure: !!(req.socket.authorized || req.socket.encrypted),
3578
- req
3579
- };
3580
- if (this.options.verifyClient.length === 2) {
3581
- this.options.verifyClient(info, (verified, code, message, headers) => {
3582
- if (!verified) {
3583
- return abortHandshake(socket, code || 401, message, headers);
3584
- }
3585
- this.completeUpgrade(
3586
- extensions,
3587
- key,
3588
- protocols,
3589
- req,
3590
- socket,
3591
- head,
3592
- cb
3593
- );
3594
- });
3595
- return;
3596
- }
3597
- if (!this.options.verifyClient(info))
3598
- return abortHandshake(socket, 401);
3599
- }
3600
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3601
- }
3602
- /**
3603
- * Upgrade the connection to WebSocket.
3604
- *
3605
- * @param {Object} extensions The accepted extensions
3606
- * @param {String} key The value of the `Sec-WebSocket-Key` header
3607
- * @param {Set} protocols The subprotocols
3608
- * @param {http.IncomingMessage} req The request object
3609
- * @param {Duplex} socket The network socket between the server and client
3610
- * @param {Buffer} head The first packet of the upgraded stream
3611
- * @param {Function} cb Callback
3612
- * @throws {Error} If called more than once with the same socket
3613
- * @private
3614
- */
3615
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3616
- if (!socket.readable || !socket.writable)
3617
- return socket.destroy();
3618
- if (socket[kWebSocket]) {
3619
- throw new Error(
3620
- "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3621
- );
3622
- }
3623
- if (this._state > RUNNING)
3624
- return abortHandshake(socket, 503);
3625
- const digest = createHash("sha1").update(key + GUID).digest("base64");
3626
- const headers = [
3627
- "HTTP/1.1 101 Switching Protocols",
3628
- "Upgrade: websocket",
3629
- "Connection: Upgrade",
3630
- `Sec-WebSocket-Accept: ${digest}`
3631
- ];
3632
- const ws = new this.options.WebSocket(null, void 0, this.options);
3633
- if (protocols.size) {
3634
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3635
- if (protocol) {
3636
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3637
- ws._protocol = protocol;
3638
- }
3639
- }
3640
- if (extensions[PerMessageDeflate.extensionName]) {
3641
- const params = extensions[PerMessageDeflate.extensionName].params;
3642
- const value = extension.format({
3643
- [PerMessageDeflate.extensionName]: [params]
3644
- });
3645
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
3646
- ws._extensions = extensions;
3647
- }
3648
- this.emit("headers", headers, req);
3649
- socket.write(headers.concat("\r\n").join("\r\n"));
3650
- socket.removeListener("error", socketOnError);
3651
- ws.setSocket(socket, head, {
3652
- allowSynchronousEvents: this.options.allowSynchronousEvents,
3653
- maxPayload: this.options.maxPayload,
3654
- skipUTF8Validation: this.options.skipUTF8Validation
3655
- });
3656
- if (this.clients) {
3657
- this.clients.add(ws);
3658
- ws.on("close", () => {
3659
- this.clients.delete(ws);
3660
- if (this._shouldEmitClose && !this.clients.size) {
3661
- process.nextTick(emitClose, this);
3662
- }
3663
- });
3664
- }
3665
- cb(ws, req);
3666
- }
3667
- };
3668
- module.exports = WebSocketServer;
3669
- function addListeners(server, map) {
3670
- for (const event of Object.keys(map))
3671
- server.on(event, map[event]);
3672
- return function removeListeners() {
3673
- for (const event of Object.keys(map)) {
3674
- server.removeListener(event, map[event]);
3675
- }
3676
- };
3677
- }
3678
- function emitClose(server) {
3679
- server._state = CLOSED;
3680
- server.emit("close");
3681
- }
3682
- function socketOnError() {
3683
- this.destroy();
3684
- }
3685
- function abortHandshake(socket, code, message, headers) {
3686
- message = message || http.STATUS_CODES[code];
3687
- headers = {
3688
- Connection: "close",
3689
- "Content-Type": "text/html",
3690
- "Content-Length": Buffer.byteLength(message),
3691
- ...headers
3692
- };
3693
- socket.once("finish", socket.destroy);
3694
- socket.end(
3695
- `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3696
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3697
- );
3698
- }
3699
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3700
- if (server.listenerCount("wsClientError")) {
3701
- const err = new Error(message);
3702
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3703
- server.emit("wsClientError", err, socket, req);
3704
- } else {
3705
- abortHandshake(socket, code, message, headers);
3706
- }
3707
- }
3708
- }
3709
- });
3710
-
3711
- // ../../../node_modules/ws/index.js
3712
- var require_ws = __commonJS({
3713
- "../../../node_modules/ws/index.js"(exports$1, module) {
3714
- var WebSocket2 = require_websocket();
3715
- WebSocket2.createWebSocketStream = require_stream();
3716
- WebSocket2.Server = require_websocket_server();
3717
- WebSocket2.Receiver = require_receiver();
3718
- WebSocket2.Sender = require_sender();
3719
- WebSocket2.WebSocket = WebSocket2;
3720
- WebSocket2.WebSocketServer = WebSocket2.Server;
3721
- module.exports = WebSocket2;
3722
- }
3723
- });
3724
9
 
3725
10
  // ../core/src/platform.ts
3726
11
  function detectPlatform() {
@@ -3753,8 +38,7 @@ var isServer = isNode || isDeno;
3753
38
  var WebStorageAdapter = class {
3754
39
  getItem(key) {
3755
40
  try {
3756
- if (typeof localStorage === "undefined")
3757
- return null;
41
+ if (typeof localStorage === "undefined") return null;
3758
42
  return localStorage.getItem(key);
3759
43
  } catch (error) {
3760
44
  console.warn("Failed to get item from localStorage:", error);
@@ -3763,8 +47,7 @@ var WebStorageAdapter = class {
3763
47
  }
3764
48
  setItem(key, value) {
3765
49
  try {
3766
- if (typeof localStorage === "undefined")
3767
- return;
50
+ if (typeof localStorage === "undefined") return;
3768
51
  localStorage.setItem(key, value);
3769
52
  } catch (error) {
3770
53
  console.warn("Failed to set item in localStorage:", error);
@@ -3772,8 +55,7 @@ var WebStorageAdapter = class {
3772
55
  }
3773
56
  removeItem(key) {
3774
57
  try {
3775
- if (typeof localStorage === "undefined")
3776
- return;
58
+ if (typeof localStorage === "undefined") return;
3777
59
  localStorage.removeItem(key);
3778
60
  } catch (error) {
3779
61
  console.warn("Failed to remove item from localStorage:", error);
@@ -3781,8 +63,7 @@ var WebStorageAdapter = class {
3781
63
  }
3782
64
  clear() {
3783
65
  try {
3784
- if (typeof localStorage === "undefined")
3785
- return;
66
+ if (typeof localStorage === "undefined") return;
3786
67
  localStorage.clear();
3787
68
  } catch (error) {
3788
69
  console.warn("Failed to clear localStorage:", error);
@@ -3956,8 +237,7 @@ function camelToSnake(str) {
3956
237
  return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
3957
238
  }
3958
239
  function convertFilterKeysToSnakeCase(condition) {
3959
- if (!condition)
3960
- return condition;
240
+ if (!condition) return condition;
3961
241
  if ("AND" in condition) {
3962
242
  return {
3963
243
  AND: condition.AND?.map(convertFilterKeysToSnakeCase)
@@ -3976,8 +256,7 @@ function convertFilterKeysToSnakeCase(condition) {
3976
256
  return converted;
3977
257
  }
3978
258
  function buildFilterQuery(condition) {
3979
- if (!condition)
3980
- return "";
259
+ if (!condition) return "";
3981
260
  if ("AND" in condition) {
3982
261
  const andConditions = condition.AND?.map(buildFilterQuery).filter(Boolean) || [];
3983
262
  return andConditions.length > 0 ? `and=(${andConditions.join(",")})` : "";
@@ -3988,13 +267,11 @@ function buildFilterQuery(condition) {
3988
267
  }
3989
268
  const params = [];
3990
269
  for (const [field, value] of Object.entries(condition)) {
3991
- if (value === void 0 || value === null)
3992
- continue;
270
+ if (value === void 0 || value === null) continue;
3993
271
  if (typeof value === "object" && !Array.isArray(value)) {
3994
272
  for (const [operator, operatorValue] of Object.entries(value)) {
3995
273
  const param = buildOperatorQuery(field, operator, operatorValue);
3996
- if (param)
3997
- params.push(param);
274
+ if (param) params.push(param);
3998
275
  }
3999
276
  } else {
4000
277
  params.push(`${field}=eq.${encodeQueryValue(value)}`);
@@ -4041,40 +318,33 @@ function buildOperatorQuery(field, operator, value) {
4041
318
  }
4042
319
  }
4043
320
  function encodeQueryValue(value) {
4044
- if (value === null)
4045
- return "null";
321
+ if (value === null) return "null";
4046
322
  if (typeof value === "boolean") {
4047
323
  return value ? "1" : "0";
4048
324
  }
4049
- if (typeof value === "number")
4050
- return value.toString();
325
+ if (typeof value === "number") return value.toString();
4051
326
  return String(value);
4052
327
  }
4053
328
  function collectFilterParams(condition, params) {
4054
- if (!condition)
4055
- return;
329
+ if (!condition) return;
4056
330
  if ("AND" in condition) {
4057
331
  const andConditions = condition.AND?.map(buildFilterQuery).filter(Boolean) || [];
4058
- if (andConditions.length > 0)
4059
- params["and"] = `(${andConditions.join(",")})`;
332
+ if (andConditions.length > 0) params["and"] = `(${andConditions.join(",")})`;
4060
333
  return;
4061
334
  }
4062
335
  if ("OR" in condition) {
4063
336
  const orConditions = condition.OR?.map(buildFilterQuery).filter(Boolean) || [];
4064
- if (orConditions.length > 0)
4065
- params["or"] = `(${orConditions.join(",")})`;
337
+ if (orConditions.length > 0) params["or"] = `(${orConditions.join(",")})`;
4066
338
  return;
4067
339
  }
4068
340
  for (const [field, value] of Object.entries(condition)) {
4069
- if (value === void 0 || value === null)
4070
- continue;
341
+ if (value === void 0 || value === null) continue;
4071
342
  if (typeof value === "object" && !Array.isArray(value)) {
4072
343
  for (const [operator, operatorValue] of Object.entries(value)) {
4073
344
  const param = buildOperatorQuery(field, operator, operatorValue);
4074
345
  if (param) {
4075
346
  const eqIdx = param.indexOf("=");
4076
- if (eqIdx !== -1)
4077
- params[param.slice(0, eqIdx)] = param.slice(eqIdx + 1);
347
+ if (eqIdx !== -1) params[param.slice(0, eqIdx)] = param.slice(eqIdx + 1);
4078
348
  }
4079
349
  }
4080
350
  } else {
@@ -4121,12 +391,9 @@ function snakeToCamel(str) {
4121
391
  return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
4122
392
  }
4123
393
  function convertKeysToSnakeCase(obj) {
4124
- if (obj === null || obj === void 0)
4125
- return obj;
4126
- if (typeof obj !== "object")
4127
- return obj;
4128
- if (Array.isArray(obj))
4129
- return obj.map(convertKeysToSnakeCase);
394
+ if (obj === null || obj === void 0) return obj;
395
+ if (typeof obj !== "object") return obj;
396
+ if (Array.isArray(obj)) return obj.map(convertKeysToSnakeCase);
4130
397
  const converted = {};
4131
398
  for (const [key, value] of Object.entries(obj)) {
4132
399
  const snakeKey = camelToSnake2(key);
@@ -4135,12 +402,9 @@ function convertKeysToSnakeCase(obj) {
4135
402
  return converted;
4136
403
  }
4137
404
  function convertKeysToCamelCase(obj) {
4138
- if (obj === null || obj === void 0)
4139
- return obj;
4140
- if (typeof obj !== "object")
4141
- return obj;
4142
- if (Array.isArray(obj))
4143
- return obj.map(convertKeysToCamelCase);
405
+ if (obj === null || obj === void 0) return obj;
406
+ if (typeof obj !== "object") return obj;
407
+ if (Array.isArray(obj)) return obj.map(convertKeysToCamelCase);
4144
408
  const converted = {};
4145
409
  for (const [key, value] of Object.entries(obj)) {
4146
410
  const camelKey = snakeToCamel(key);
@@ -4157,22 +421,31 @@ var HttpClient = class {
4157
421
  // Permanent, non-expiring key (like Stripe's sk_live_...)
4158
422
  getToken;
4159
423
  getValidToken;
4160
- constructor(config, getToken, getValidToken) {
424
+ forceRefreshToken;
425
+ constructor(config, getToken, getValidToken, forceRefreshToken) {
4161
426
  this.projectId = config.projectId;
4162
427
  this.publishableKey = config.publishableKey;
4163
428
  this.secretKey = config.secretKey || config.serviceToken;
4164
429
  this.getToken = getToken;
4165
430
  this.getValidToken = getValidToken;
431
+ this.forceRefreshToken = forceRefreshToken;
432
+ }
433
+ /**
434
+ * Whether a 401 on this request is worth recovering from by forcing a
435
+ * user-token refresh and retrying once.
436
+ *
437
+ * Only meaningful for user-JWT auth: server-side `secretKey` 401s are real
438
+ * authorization failures a refresh cannot fix, and publishable-key requests
439
+ * carry no user token to refresh.
440
+ */
441
+ canAttemptTokenRefresh(token) {
442
+ return !!this.forceRefreshToken && !this.secretKey && !!token;
4166
443
  }
4167
444
  shouldAttachPublishableKey(path, method) {
4168
- if (method !== "GET" && method !== "POST")
4169
- return false;
4170
- if (path.includes("/api/analytics/"))
4171
- return true;
4172
- if (path.includes("/api/storage/"))
4173
- return true;
4174
- if (path.includes("/api/db/") && path.includes("/rest/v1/"))
4175
- return method === "GET";
445
+ if (method !== "GET" && method !== "POST") return false;
446
+ if (path.includes("/api/analytics/")) return true;
447
+ if (path.includes("/api/storage/")) return true;
448
+ if (path.includes("/api/db/") && path.includes("/rest/v1/")) return method === "GET";
4176
449
  return false;
4177
450
  }
4178
451
  shouldSkipSecretKey(url) {
@@ -4197,28 +470,37 @@ var HttpClient = class {
4197
470
  */
4198
471
  async request(path, options = {}) {
4199
472
  const url = this.buildUrl(path, options.searchParams);
4200
- const token = this.getValidToken ? await this.getValidToken() : this.getToken();
4201
473
  const method = options.method || "GET";
4202
- const headers = {
4203
- "Content-Type": "application/json",
4204
- ...options.headers
4205
- };
4206
- const auth = this.getAuthorizationHeader(url, token);
4207
- if (auth) {
4208
- headers.Authorization = auth;
4209
- } else if (this.publishableKey && !headers["x-blink-publishable-key"] && this.shouldAttachPublishableKey(path, method)) {
4210
- headers["x-blink-publishable-key"] = this.publishableKey;
4211
- }
4212
- const requestInit = {
4213
- method,
4214
- headers,
4215
- signal: options.signal
474
+ const sendRequest = (token) => {
475
+ const headers = {
476
+ "Content-Type": "application/json",
477
+ ...options.headers
478
+ };
479
+ const auth = this.getAuthorizationHeader(url, token);
480
+ if (auth) {
481
+ headers.Authorization = auth;
482
+ } else if (this.publishableKey && !headers["x-blink-publishable-key"] && this.shouldAttachPublishableKey(path, method)) {
483
+ headers["x-blink-publishable-key"] = this.publishableKey;
484
+ }
485
+ const requestInit = {
486
+ method,
487
+ headers,
488
+ signal: options.signal
489
+ };
490
+ if (options.body && method !== "GET") {
491
+ requestInit.body = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
492
+ }
493
+ return fetch(url, requestInit);
4216
494
  };
4217
- if (options.body && method !== "GET") {
4218
- requestInit.body = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
4219
- }
4220
495
  try {
4221
- const response = await fetch(url, requestInit);
496
+ const token = this.getValidToken ? await this.getValidToken() : this.getToken();
497
+ let response = await sendRequest(token);
498
+ if (response.status === 401 && this.canAttemptTokenRefresh(token)) {
499
+ const refreshedToken = await this.forceRefreshToken();
500
+ if (refreshedToken) {
501
+ response = await sendRequest(refreshedToken);
502
+ }
503
+ }
4222
504
  if (!response.ok) {
4223
505
  await this.handleErrorResponse(response);
4224
506
  }
@@ -4376,7 +658,6 @@ var HttpClient = class {
4376
658
  */
4377
659
  async uploadFile(path, file, filePath, options = {}) {
4378
660
  const url = this.buildUrl(path);
4379
- const token = this.getValidToken ? await this.getValidToken() : this.getToken();
4380
661
  const formData = new FormData();
4381
662
  if (file instanceof File) {
4382
663
  formData.append("file", file);
@@ -4390,41 +671,57 @@ var HttpClient = class {
4390
671
  throw new BlinkValidationError("Unsupported file type");
4391
672
  }
4392
673
  formData.append("path", filePath);
4393
- const headers = {};
4394
- const auth = this.getAuthorizationHeader(url, token);
4395
- if (auth) {
4396
- headers.Authorization = auth;
4397
- } else if (this.publishableKey && path.includes("/api/storage/") && !headers["x-blink-publishable-key"]) {
4398
- headers["x-blink-publishable-key"] = this.publishableKey;
4399
- }
4400
- try {
4401
- if (typeof XMLHttpRequest !== "undefined" && options.onProgress) {
4402
- return this.uploadWithProgress(url, formData, headers, options.onProgress);
4403
- }
4404
- const response = await fetch(url, {
4405
- method: "POST",
4406
- headers,
4407
- body: formData
4408
- });
4409
- if (!response.ok) {
4410
- await this.handleErrorResponse(response);
674
+ const attempt = async (allowRetry) => {
675
+ const token = this.getValidToken ? await this.getValidToken() : this.getToken();
676
+ const headers = {};
677
+ const auth = this.getAuthorizationHeader(url, token);
678
+ if (auth) {
679
+ headers.Authorization = auth;
680
+ } else if (this.publishableKey && path.includes("/api/storage/") && !headers["x-blink-publishable-key"]) {
681
+ headers["x-blink-publishable-key"] = this.publishableKey;
4411
682
  }
4412
- const data = await this.parseResponse(response);
4413
- return {
4414
- data,
4415
- status: response.status,
4416
- headers: response.headers
4417
- };
4418
- } catch (error) {
4419
- if (error instanceof BlinkError) {
4420
- throw error;
683
+ try {
684
+ if (typeof XMLHttpRequest !== "undefined" && options.onProgress) {
685
+ return await this.uploadWithProgress(url, formData, headers, options.onProgress);
686
+ }
687
+ const response = await fetch(url, {
688
+ method: "POST",
689
+ headers,
690
+ body: formData
691
+ });
692
+ if (response.status === 401 && allowRetry && this.canAttemptTokenRefresh(token)) {
693
+ const refreshedToken = await this.forceRefreshToken();
694
+ if (refreshedToken) {
695
+ return attempt(false);
696
+ }
697
+ }
698
+ if (!response.ok) {
699
+ await this.handleErrorResponse(response);
700
+ }
701
+ const data = await this.parseResponse(response);
702
+ return {
703
+ data,
704
+ status: response.status,
705
+ headers: response.headers
706
+ };
707
+ } catch (error) {
708
+ if (allowRetry && error instanceof BlinkAuthError && this.canAttemptTokenRefresh(token)) {
709
+ const refreshedToken = await this.forceRefreshToken();
710
+ if (refreshedToken) {
711
+ return attempt(false);
712
+ }
713
+ }
714
+ if (error instanceof BlinkError) {
715
+ throw error;
716
+ }
717
+ throw new BlinkNetworkError(
718
+ `File upload failed: ${error instanceof Error ? error.message : "Unknown error"}`,
719
+ 0,
720
+ { originalError: error }
721
+ );
4421
722
  }
4422
- throw new BlinkNetworkError(
4423
- `File upload failed: ${error instanceof Error ? error.message : "Unknown error"}`,
4424
- 0,
4425
- { originalError: error }
4426
- );
4427
- }
723
+ };
724
+ return attempt(true);
4428
725
  }
4429
726
  /**
4430
727
  * Upload with progress tracking using XMLHttpRequest
@@ -4505,8 +802,7 @@ var HttpClient = class {
4505
802
  "Content-Type": "application/json"
4506
803
  };
4507
804
  const auth = this.getAuthorizationHeader(url, token);
4508
- if (auth)
4509
- headers.Authorization = auth;
805
+ if (auth) headers.Authorization = auth;
4510
806
  const body = {
4511
807
  prompt,
4512
808
  stream: true,
@@ -4560,8 +856,7 @@ var HttpClient = class {
4560
856
  "Content-Type": "application/json"
4561
857
  };
4562
858
  const auth = this.getAuthorizationHeader(url, token);
4563
- if (auth)
4564
- headers.Authorization = auth;
859
+ if (auth) headers.Authorization = auth;
4565
860
  const body = {
4566
861
  prompt,
4567
862
  stream: true,
@@ -4588,8 +883,7 @@ var HttpClient = class {
4588
883
  try {
4589
884
  while (true) {
4590
885
  const { done, value } = await reader.read();
4591
- if (done)
4592
- break;
886
+ if (done) break;
4593
887
  const chunk = decoder.decode(value, { stream: true });
4594
888
  buffer += chunk;
4595
889
  try {
@@ -4700,8 +994,7 @@ var HttpClient = class {
4700
994
  "Content-Type": "application/json"
4701
995
  };
4702
996
  const auth = this.getAuthorizationHeader(url, token);
4703
- if (auth)
4704
- headers.Authorization = auth;
997
+ if (auth) headers.Authorization = auth;
4705
998
  const response = await fetch(url, {
4706
999
  method: "POST",
4707
1000
  headers,
@@ -4724,8 +1017,7 @@ var HttpClient = class {
4724
1017
  "Content-Type": "application/json"
4725
1018
  };
4726
1019
  const auth = this.getAuthorizationHeader(url, token);
4727
- if (auth)
4728
- headers.Authorization = auth;
1020
+ if (auth) headers.Authorization = auth;
4729
1021
  const response = await fetch(url, {
4730
1022
  method: "POST",
4731
1023
  headers,
@@ -4893,19 +1185,16 @@ var HttpClient = class {
4893
1185
  try {
4894
1186
  while (true) {
4895
1187
  const { done, value } = await reader.read();
4896
- if (done)
4897
- break;
1188
+ if (done) break;
4898
1189
  buffer += decoder.decode(value, { stream: true });
4899
1190
  const lines = buffer.split("\n");
4900
1191
  buffer = lines.pop() || "";
4901
1192
  for (const line of lines) {
4902
- if (!line.trim())
4903
- continue;
1193
+ if (!line.trim()) continue;
4904
1194
  if (line === "[DONE]") {
4905
1195
  continue;
4906
1196
  }
4907
- if (!line.startsWith("data: "))
4908
- continue;
1197
+ if (!line.startsWith("data: ")) continue;
4909
1198
  try {
4910
1199
  const jsonStr = line.slice(6);
4911
1200
  const part = JSON.parse(jsonStr);
@@ -4915,13 +1204,11 @@ var HttpClient = class {
4915
1204
  case "text-delta":
4916
1205
  if (part.delta) {
4917
1206
  finalResult.text += part.delta;
4918
- if (onChunk)
4919
- onChunk(part.delta);
1207
+ if (onChunk) onChunk(part.delta);
4920
1208
  }
4921
1209
  if (part.textDelta) {
4922
1210
  finalResult.text += part.textDelta;
4923
- if (onChunk)
4924
- onChunk(part.textDelta);
1211
+ if (onChunk) onChunk(part.textDelta);
4925
1212
  }
4926
1213
  break;
4927
1214
  case "text-end":
@@ -4956,15 +1243,13 @@ var HttpClient = class {
4956
1243
  case "finish":
4957
1244
  finalResult.finishReason = part.finishReason;
4958
1245
  finalResult.usage = part.usage;
4959
- if (part.response)
4960
- finalResult.response = part.response;
1246
+ if (part.response) finalResult.response = part.response;
4961
1247
  break;
4962
1248
  case "error":
4963
1249
  finalResult.error = part.error;
4964
1250
  throw new Error(part.error);
4965
1251
  case "data":
4966
- if (!finalResult.customData)
4967
- finalResult.customData = [];
1252
+ if (!finalResult.customData) finalResult.customData = [];
4968
1253
  finalResult.customData.push(part.value);
4969
1254
  break;
4970
1255
  }
@@ -4993,8 +1278,7 @@ function isReactNative2() {
4993
1278
  return typeof navigator !== "undefined" && navigator.product === "ReactNative";
4994
1279
  }
4995
1280
  function getWindowLocation() {
4996
- if (!hasWindow())
4997
- return null;
1281
+ if (!hasWindow()) return null;
4998
1282
  try {
4999
1283
  return window.location;
5000
1284
  } catch {
@@ -5003,8 +1287,7 @@ function getWindowLocation() {
5003
1287
  }
5004
1288
  function getLocationHref() {
5005
1289
  const loc = getWindowLocation();
5006
- if (!loc)
5007
- return null;
1290
+ if (!loc) return null;
5008
1291
  try {
5009
1292
  return loc.href;
5010
1293
  } catch {
@@ -5013,8 +1296,7 @@ function getLocationHref() {
5013
1296
  }
5014
1297
  function getLocationOrigin() {
5015
1298
  const loc = getWindowLocation();
5016
- if (!loc)
5017
- return null;
1299
+ if (!loc) return null;
5018
1300
  try {
5019
1301
  return loc.origin;
5020
1302
  } catch {
@@ -5023,8 +1305,7 @@ function getLocationOrigin() {
5023
1305
  }
5024
1306
  function getLocationHostname() {
5025
1307
  const loc = getWindowLocation();
5026
- if (!loc)
5027
- return null;
1308
+ if (!loc) return null;
5028
1309
  try {
5029
1310
  return loc.hostname;
5030
1311
  } catch {
@@ -5033,8 +1314,7 @@ function getLocationHostname() {
5033
1314
  }
5034
1315
  function getLocationPathname() {
5035
1316
  const loc = getWindowLocation();
5036
- if (!loc)
5037
- return null;
1317
+ if (!loc) return null;
5038
1318
  try {
5039
1319
  return loc.pathname;
5040
1320
  } catch {
@@ -5043,8 +1323,7 @@ function getLocationPathname() {
5043
1323
  }
5044
1324
  function getLocationSearch() {
5045
1325
  const loc = getWindowLocation();
5046
- if (!loc)
5047
- return null;
1326
+ if (!loc) return null;
5048
1327
  try {
5049
1328
  return loc.search;
5050
1329
  } catch {
@@ -5053,8 +1332,7 @@ function getLocationSearch() {
5053
1332
  }
5054
1333
  function getLocationHash() {
5055
1334
  const loc = getWindowLocation();
5056
- if (!loc)
5057
- return null;
1335
+ if (!loc) return null;
5058
1336
  try {
5059
1337
  return loc.hash;
5060
1338
  } catch {
@@ -5063,8 +1341,7 @@ function getLocationHash() {
5063
1341
  }
5064
1342
  function getLocationProtocol() {
5065
1343
  const loc = getWindowLocation();
5066
- if (!loc)
5067
- return null;
1344
+ if (!loc) return null;
5068
1345
  try {
5069
1346
  return loc.protocol;
5070
1347
  } catch {
@@ -5073,8 +1350,7 @@ function getLocationProtocol() {
5073
1350
  }
5074
1351
  function getLocationHost() {
5075
1352
  const loc = getWindowLocation();
5076
- if (!loc)
5077
- return null;
1353
+ if (!loc) return null;
5078
1354
  try {
5079
1355
  return loc.host;
5080
1356
  } catch {
@@ -5082,20 +1358,17 @@ function getLocationHost() {
5082
1358
  }
5083
1359
  }
5084
1360
  function constructFullUrl() {
5085
- if (!hasWindow())
5086
- return null;
1361
+ if (!hasWindow()) return null;
5087
1362
  const protocol = getLocationProtocol();
5088
1363
  const host = getLocationHost();
5089
1364
  const pathname = getLocationPathname();
5090
1365
  const search = getLocationSearch();
5091
1366
  const hash = getLocationHash();
5092
- if (!protocol || !host)
5093
- return null;
1367
+ if (!protocol || !host) return null;
5094
1368
  return `${protocol}//${host}${pathname || ""}${search || ""}${hash || ""}`;
5095
1369
  }
5096
1370
  function getDocumentReferrer() {
5097
- if (!hasDocument())
5098
- return null;
1371
+ if (!hasDocument()) return null;
5099
1372
  try {
5100
1373
  return document.referrer || null;
5101
1374
  } catch {
@@ -5103,8 +1376,7 @@ function getDocumentReferrer() {
5103
1376
  }
5104
1377
  }
5105
1378
  function getWindowInnerWidth() {
5106
- if (!hasWindow())
5107
- return null;
1379
+ if (!hasWindow()) return null;
5108
1380
  try {
5109
1381
  return window.innerWidth;
5110
1382
  } catch {
@@ -5112,8 +1384,7 @@ function getWindowInnerWidth() {
5112
1384
  }
5113
1385
  }
5114
1386
  function isIframe() {
5115
- if (!hasWindow())
5116
- return false;
1387
+ if (!hasWindow()) return false;
5117
1388
  try {
5118
1389
  return window.self !== window.top;
5119
1390
  } catch {
@@ -5121,8 +1392,7 @@ function isIframe() {
5121
1392
  }
5122
1393
  }
5123
1394
  function getSessionStorage() {
5124
- if (!hasWindow())
5125
- return null;
1395
+ if (!hasWindow()) return null;
5126
1396
  try {
5127
1397
  return window.sessionStorage;
5128
1398
  } catch {
@@ -5143,6 +1413,7 @@ var BlinkAuth = class {
5143
1413
  initializationPromise = null;
5144
1414
  isInitialized = false;
5145
1415
  storage;
1416
+ refreshPromise = null;
5146
1417
  constructor(config) {
5147
1418
  this.config = config;
5148
1419
  if (!config.projectId) {
@@ -5201,8 +1472,7 @@ var BlinkAuth = class {
5201
1472
  * Wait for authentication initialization to complete
5202
1473
  */
5203
1474
  async waitForInitialization() {
5204
- if (this.isInitialized)
5205
- return;
1475
+ if (this.isInitialized) return;
5206
1476
  if (this.initializationPromise) {
5207
1477
  await this.initializationPromise;
5208
1478
  }
@@ -5211,8 +1481,7 @@ var BlinkAuth = class {
5211
1481
  * Setup listener for tokens from parent window
5212
1482
  */
5213
1483
  setupParentWindowListener() {
5214
- if (!isWeb || !this.isIframe || !hasWindow())
5215
- return;
1484
+ if (!isWeb || !this.isIframe || !hasWindow()) return;
5216
1485
  window.addEventListener("message", (event) => {
5217
1486
  if (event.origin !== "https://blink.new" && event.origin !== "http://localhost:3000" && event.origin !== "http://localhost:3001") {
5218
1487
  return;
@@ -5921,26 +2190,21 @@ var BlinkAuth = class {
5921
2190
  let closedIntervalId;
5922
2191
  let cleanedUp = false;
5923
2192
  const cleanup = () => {
5924
- if (cleanedUp)
5925
- return;
2193
+ if (cleanedUp) return;
5926
2194
  cleanedUp = true;
5927
2195
  clearTimeout(timeoutId);
5928
- if (closedIntervalId)
5929
- clearInterval(closedIntervalId);
2196
+ if (closedIntervalId) clearInterval(closedIntervalId);
5930
2197
  window.removeEventListener("message", messageListener);
5931
2198
  };
5932
2199
  const messageListener = (event) => {
5933
2200
  let allowed = false;
5934
2201
  try {
5935
2202
  const authOrigin = new URL(this.authUrl).origin;
5936
- if (event.origin === authOrigin)
5937
- allowed = true;
2203
+ if (event.origin === authOrigin) allowed = true;
5938
2204
  } catch {
5939
2205
  }
5940
- if (event.origin === "http://localhost:3000" || event.origin === "http://localhost:3001")
5941
- allowed = true;
5942
- if (!allowed)
5943
- return;
2206
+ if (event.origin === "http://localhost:3000" || event.origin === "http://localhost:3001") allowed = true;
2207
+ if (!allowed) return;
5944
2208
  if (event.data?.type === "BLINK_AUTH_TOKENS") {
5945
2209
  const { access_token, refresh_token, token_type, expires_in, refresh_expires_in, projectId, state: returnedState } = event.data;
5946
2210
  try {
@@ -6382,27 +2646,21 @@ var BlinkAuth = class {
6382
2646
  }
6383
2647
  const visited = /* @__PURE__ */ new Set();
6384
2648
  const hasPermissionInRole = (roleName) => {
6385
- if (visited.has(roleName))
6386
- return false;
2649
+ if (visited.has(roleName)) return false;
6387
2650
  visited.add(roleName);
6388
2651
  const rc = roles[roleName];
6389
- if (!rc)
6390
- return false;
6391
- if (rc.permissions.includes("*"))
6392
- return true;
2652
+ if (!rc) return false;
2653
+ if (rc.permissions.includes("*")) return true;
6393
2654
  const fullPermission2 = resource ? `${permission}.${resource}` : permission;
6394
- if (rc.permissions.includes(fullPermission2) || rc.permissions.includes(permission))
6395
- return true;
2655
+ if (rc.permissions.includes(fullPermission2) || rc.permissions.includes(permission)) return true;
6396
2656
  if (rc.inherit) {
6397
2657
  for (const parent of rc.inherit) {
6398
- if (hasPermissionInRole(parent))
6399
- return true;
2658
+ if (hasPermissionInRole(parent)) return true;
6400
2659
  }
6401
2660
  }
6402
2661
  return false;
6403
2662
  };
6404
- if (hasPermissionInRole(user.role))
6405
- return true;
2663
+ if (hasPermissionInRole(user.role)) return true;
6406
2664
  return false;
6407
2665
  }
6408
2666
  /**
@@ -6603,10 +2861,35 @@ var BlinkAuth = class {
6603
2861
  * Refresh access token using refresh token
6604
2862
  */
6605
2863
  async refreshToken() {
2864
+ if (this.refreshPromise) {
2865
+ return this.refreshPromise;
2866
+ }
6606
2867
  const refreshToken = this.authState.tokens?.refresh_token;
6607
2868
  if (!refreshToken) {
6608
2869
  return false;
6609
2870
  }
2871
+ this.refreshPromise = this.performTokenRefresh(refreshToken);
2872
+ try {
2873
+ return await this.refreshPromise;
2874
+ } finally {
2875
+ this.refreshPromise = null;
2876
+ }
2877
+ }
2878
+ /**
2879
+ * Force a server-side token refresh and return the resulting access token.
2880
+ *
2881
+ * Used by the HTTP client to recover from a 401 even when the client-side
2882
+ * expiry heuristics believe the access token is still valid (clock skew, a
2883
+ * restored session with a stale `issued_at`, or a refresh race). Delegates to
2884
+ * {@link refreshToken} so it shares the single-flight guard.
2885
+ *
2886
+ * @returns The new access token, or null if refresh was not possible.
2887
+ */
2888
+ async forceRefreshAccessToken() {
2889
+ const refreshed = await this.refreshToken();
2890
+ return refreshed ? this.authState.tokens?.access_token || null : null;
2891
+ }
2892
+ async performTokenRefresh(refreshToken) {
6610
2893
  try {
6611
2894
  const response = await fetch(`${this.authUrl}/api/auth/refresh`, {
6612
2895
  method: "POST",
@@ -6841,8 +3124,7 @@ var BlinkAuth = class {
6841
3124
  }
6842
3125
  extractTokensFromUrl() {
6843
3126
  const search = getLocationSearch();
6844
- if (!search)
6845
- return null;
3127
+ if (!search) return null;
6846
3128
  const params = new URLSearchParams(search);
6847
3129
  const accessToken = params.get("access_token");
6848
3130
  const refreshToken = params.get("refresh_token");
@@ -6875,8 +3157,7 @@ var BlinkAuth = class {
6875
3157
  }
6876
3158
  clearUrlTokens() {
6877
3159
  const href = getLocationHref();
6878
- if (!href || !hasWindowLocation())
6879
- return;
3160
+ if (!href || !hasWindowLocation()) return;
6880
3161
  const url = new URL(href);
6881
3162
  url.searchParams.delete("access_token");
6882
3163
  url.searchParams.delete("refresh_token");
@@ -6941,8 +3222,7 @@ var BlinkAuth = class {
6941
3222
  */
6942
3223
  extractMagicTokenFromUrl() {
6943
3224
  const search = getLocationSearch();
6944
- if (!search)
6945
- return null;
3225
+ if (!search) return null;
6946
3226
  const params = new URLSearchParams(search);
6947
3227
  return params.get("magic_token") || params.get("token");
6948
3228
  }
@@ -6999,8 +3279,7 @@ var BlinkAuth = class {
6999
3279
  * Setup cross-tab authentication synchronization
7000
3280
  */
7001
3281
  setupCrossTabSync() {
7002
- if (!isWeb || !hasWindow())
7003
- return;
3282
+ if (!isWeb || !hasWindow()) return;
7004
3283
  window.addEventListener("storage", (e) => {
7005
3284
  if (e.key === this.getStorageKey("tokens")) {
7006
3285
  const newTokens = e.newValue ? JSON.parse(e.newValue) : null;
@@ -9046,7 +5325,7 @@ var getWebSocketClass = () => {
9046
5325
  return WebSocket;
9047
5326
  }
9048
5327
  try {
9049
- const WS = require_ws();
5328
+ const WS = __require("ws");
9050
5329
  return WS;
9051
5330
  } catch (error) {
9052
5331
  throw new BlinkRealtimeError('WebSocket is not available. Install "ws" package for Node.js environments.');
@@ -9371,8 +5650,7 @@ var RealtimeConnection = class {
9371
5650
  });
9372
5651
  }
9373
5652
  flushMessageQueue() {
9374
- if (!this.websocket || this.websocket.readyState !== 1)
9375
- return;
5653
+ if (!this.websocket || this.websocket.readyState !== 1) return;
9376
5654
  const queue = [...this.messageQueue];
9377
5655
  this.messageQueue = [];
9378
5656
  queue.forEach((q) => {
@@ -9415,8 +5693,7 @@ var RealtimeConnection = class {
9415
5693
  const delay = baseDelay + jitter;
9416
5694
  console.log(`\u{1F504} Scheduling reconnect attempt ${this.reconnectAttempts} in ${Math.round(delay)}ms`);
9417
5695
  this.reconnectTimer = globalThis.setTimeout(async () => {
9418
- if (this.channels.size === 0)
9419
- return;
5696
+ if (this.channels.size === 0) return;
9420
5697
  try {
9421
5698
  await this.connectWebSocket();
9422
5699
  await this.resubscribeAllChannels();
@@ -9642,44 +5919,129 @@ var BlinkNotificationsImpl = class {
9642
5919
  /**
9643
5920
  * Sends an email using the Blink Notifications API.
9644
5921
  *
5922
+ * If the project has a verified custom email domain (Settings → Email),
5923
+ * the message is sent via that domain through AWS SES. Otherwise it
5924
+ * goes through the default Blink sending infrastructure on a project
5925
+ * subdomain (`noreply@{projectId}.blink-email.com`).
5926
+ *
9645
5927
  * @param params - An object containing the details for the email.
9646
5928
  * - `to`: The recipient's email address or an array of addresses.
9647
5929
  * - `subject`: The subject line of the email.
9648
5930
  * - `html`: The HTML body of the email. For best results across all email
9649
- * clients (like Gmail, Outlook), use inline CSS and table-based layouts.
5931
+ * clients (like Gmail, Outlook), use inline CSS and table-based
5932
+ * layouts.
9650
5933
  * - `text`: A plain-text version of the email body (optional).
9651
- * - `from`: A custom sender name (e.g., "Acme Inc"). The email address will
9652
- * be auto-generated by the project (e.g., "noreply@project.blink-email.com").
5934
+ * - `from`: Pick which sender to use (optional).
5935
+ * Two shapes are accepted — the server disambiguates by
5936
+ * whether the value contains an `@`:
5937
+ * • **Full address** like `"support@mail.acme.com"` (any
5938
+ * string with `@`) — sends from that specific verified
5939
+ * sender. The address must be added in Settings → Email
5940
+ * first; unverified addresses are rejected (HTTP 403,
5941
+ * `UNVERIFIED_SENDER`).
5942
+ * • **Display name** like `"Acme Support"` (no `@`) —
5943
+ * keeps the project's default sender address, only
5944
+ * overrides the visible name in the recipient's inbox.
5945
+ * So a display name MUST NOT contain `@`, or the server
5946
+ * treats it as an address and 403s if unverified.
5947
+ * Omit to use the project's default sender (same one auth
5948
+ * flows like password reset use).
9653
5949
  * - `replyTo`: An email address for recipients to reply to (optional).
9654
5950
  * - `cc`: A CC recipient's email address or an array of addresses (optional).
9655
5951
  * - `bcc`: A BCC recipient's email address or an array of addresses (optional).
9656
- * - `attachments`: An array of objects for files to attach, each with a `url`.
9657
- * The file at the URL will be fetched and attached by the server.
5952
+ * - `attachments`: An array of `SendEmailAttachment` objects. Each
5953
+ * REQUIRES `filename`, `url`, AND `type` (the MIME
5954
+ * type — e.g. `'image/png'`, `'application/pdf'`).
5955
+ * Missing any of the three returns a 400. The file at
5956
+ * the URL is fetched server-side and attached.
9658
5957
  *
9659
- * @example
5958
+ * **Interaction with `from`:** AWS SES can't carry
5959
+ * attachments in the simple body type we use, so any
5960
+ * request with `attachments` is delivered through the
5961
+ * fallback transport instead of the project's verified
5962
+ * SES domain. The `from` field is still honored in the
5963
+ * From header — i.e. recipients of an attachment email
5964
+ * still see `support@mail.acme.com` if you passed that —
5965
+ * but the signing/sending domain in the headers will be
5966
+ * the Blink subdomain. Gmail may render a small "via
5967
+ * blink-email.com" annotation on these messages, and
5968
+ * SPF/DKIM won't align to your verified domain.
5969
+ * Attachment-free sends are not affected.
5970
+ *
5971
+ * @example Basic transactional send — uses the project's default sender.
9660
5972
  * ```ts
9661
- * // Send a simple email
9662
- * const { success, messageId } = await blink.notifications.email({
5973
+ * await blink.notifications.email({
9663
5974
  * to: 'customer@example.com',
9664
- * subject: 'Your order has shipped!',
9665
- * html: '<h1>Order Confirmation</h1><p>Your order #12345 is on its way.</p>'
5975
+ * subject: 'Your order has shipped',
5976
+ * html: '<h1>Order Confirmation</h1><p>Your order #12345 is on its way.</p>',
9666
5977
  * });
5978
+ * ```
9667
5979
  *
9668
- * // Send an email with attachments and a custom from name
9669
- * const { success } = await blink.notifications.email({
9670
- * to: ['team@example.com', 'manager@example.com'],
9671
- * subject: 'New Invoice',
9672
- * from: 'Blink Invoicing',
9673
- * html: '<p>Please find the invoice attached.</p>',
9674
- * attachments: [
9675
- * { url: 'https://example.com/invoice.pdf', filename: 'invoice.pdf' }
9676
- * ]
5980
+ * @example Send from a specific verified sender (set up in Settings → Email).
5981
+ * ```ts
5982
+ * await blink.notifications.email({
5983
+ * to: 'customer@example.com',
5984
+ * from: 'support@mail.acme.com',
5985
+ * replyTo: 'support@mail.acme.com',
5986
+ * subject: 'Re: your ticket #2891',
5987
+ * html: '<p>Hi! Following up on your support request…</p>',
5988
+ * });
5989
+ *
5990
+ * await blink.notifications.email({
5991
+ * to: 'customer@example.com',
5992
+ * from: 'billing@mail.acme.com',
5993
+ * subject: 'Your invoice for May',
5994
+ * html: '<p>Your monthly invoice is ready.</p>',
5995
+ * });
5996
+ * ```
5997
+ *
5998
+ * @example Display-name override on top of the default sender.
5999
+ * ```ts
6000
+ * await blink.notifications.email({
6001
+ * to: 'customer@example.com',
6002
+ * from: 'Acme Receipts', // not an email — display name only
6003
+ * subject: 'Payment received',
6004
+ * html: '<p>Thanks for your payment.</p>',
6005
+ * });
6006
+ * ```
6007
+ *
6008
+ * @example Cron-driven digest from a dedicated sender.
6009
+ * ```ts
6010
+ * await blink.notifications.email({
6011
+ * to: user.email,
6012
+ * from: 'digest@mail.acme.com',
6013
+ * subject: 'Your weekly Acme summary',
6014
+ * html: renderDigestHtml(user),
9677
6015
  * });
9678
6016
  * ```
9679
6017
  *
9680
- * @returns A promise that resolves with an object containing the status of the email send.
9681
- * - `success`: A boolean indicating if the email was sent successfully.
6018
+ * @returns A promise that resolves with an object containing:
6019
+ * - `success`: Whether the email was accepted for delivery.
9682
6020
  * - `messageId`: The unique ID of the message from the email provider.
6021
+ *
6022
+ * @throws {BlinkNotificationsError} On any send failure. The thrown error's
6023
+ * `.code` is always `'NOTIFICATIONS_ERROR'` (the SDK-level category).
6024
+ * Inspect `.status` and `.details` for the specific server reason:
6025
+ *
6026
+ * - `err.status === 403 && err.details?.code === 'UNVERIFIED_SENDER'` —
6027
+ * the `from` address you passed is not a verified sender for this
6028
+ * project. Add it in Settings → Email or pick one of the project's
6029
+ * existing verified addresses.
6030
+ *
6031
+ * Example:
6032
+ * ```ts
6033
+ * try {
6034
+ * await blink.notifications.email({ to, subject, html, from: 'foo@x.com' });
6035
+ * } catch (err) {
6036
+ * if (err instanceof BlinkNotificationsError &&
6037
+ * err.status === 403 &&
6038
+ * (err.details as { code?: string })?.code === 'UNVERIFIED_SENDER') {
6039
+ * // surface a friendly "this sender isn't set up yet" message
6040
+ * } else {
6041
+ * throw err;
6042
+ * }
6043
+ * }
6044
+ * ```
9683
6045
  */
9684
6046
  async email(params) {
9685
6047
  try {
@@ -9695,8 +6057,18 @@ var BlinkNotificationsImpl = class {
9695
6057
  if (error instanceof BlinkNotificationsError) {
9696
6058
  throw error;
9697
6059
  }
9698
- const errorMessage = error.response?.data?.error?.message || error.message || "An unknown error occurred";
9699
- throw new BlinkNotificationsError(`Failed to send email: ${errorMessage}`, error.response?.status, error.response?.data?.error);
6060
+ const status = error.status ?? error.response?.status;
6061
+ let details = error.details;
6062
+ if (!details && error.response?.data) {
6063
+ const d = error.response.data;
6064
+ details = d?.code ? { code: d.code, message: d.message ?? d.error } : d;
6065
+ }
6066
+ const errorMessage = details?.message ?? error.message ?? "An unknown error occurred";
6067
+ throw new BlinkNotificationsError(
6068
+ `Failed to send email: ${errorMessage}`,
6069
+ status,
6070
+ details
6071
+ );
9700
6072
  }
9701
6073
  }
9702
6074
  };
@@ -9935,8 +6307,7 @@ var BlinkAnalyticsImpl = class {
9935
6307
  }
9936
6308
  }
9937
6309
  setupRouteChangeListener() {
9938
- if (!isWeb)
9939
- return;
6310
+ if (!isWeb) return;
9940
6311
  if (!window.__blinkAnalyticsSetup) {
9941
6312
  const originalPushState = history.pushState;
9942
6313
  const originalReplaceState = history.replaceState;
@@ -9970,8 +6341,7 @@ var BlinkAnalyticsImpl = class {
9970
6341
  window.__blinkAnalyticsInstances?.add(this);
9971
6342
  }
9972
6343
  setupUnloadListener() {
9973
- if (!isWeb || !hasWindow())
9974
- return;
6344
+ if (!isWeb || !hasWindow()) return;
9975
6345
  window.addEventListener("pagehide", () => {
9976
6346
  this.flush();
9977
6347
  });
@@ -9980,8 +6350,7 @@ var BlinkAnalyticsImpl = class {
9980
6350
  });
9981
6351
  }
9982
6352
  captureUTMParams() {
9983
- if (!isWeb)
9984
- return;
6353
+ if (!isWeb) return;
9985
6354
  const search = getLocationSearch();
9986
6355
  if (!search) {
9987
6356
  this.utmParams = {};
@@ -10028,21 +6397,14 @@ var BlinkAnalyticsImpl = class {
10028
6397
  const utmMedium = this.utmParams.utm_medium;
10029
6398
  this.utmParams.utm_source;
10030
6399
  if (utmMedium) {
10031
- if (utmMedium === "cpc" || utmMedium === "ppc")
10032
- return "Paid Search";
10033
- if (utmMedium === "email")
10034
- return "Email";
10035
- if (utmMedium === "social")
10036
- return "Social";
10037
- if (utmMedium === "referral")
10038
- return "Referral";
10039
- if (utmMedium === "display")
10040
- return "Display";
10041
- if (utmMedium === "affiliate")
10042
- return "Affiliate";
10043
- }
10044
- if (!referrer)
10045
- return "Direct";
6400
+ if (utmMedium === "cpc" || utmMedium === "ppc") return "Paid Search";
6401
+ if (utmMedium === "email") return "Email";
6402
+ if (utmMedium === "social") return "Social";
6403
+ if (utmMedium === "referral") return "Referral";
6404
+ if (utmMedium === "display") return "Display";
6405
+ if (utmMedium === "affiliate") return "Affiliate";
6406
+ }
6407
+ if (!referrer) return "Direct";
10046
6408
  try {
10047
6409
  const referrerUrl = new URL(referrer);
10048
6410
  const referrerDomain = referrerUrl.hostname.toLowerCase();
@@ -10173,10 +6535,8 @@ function convertDocument(api) {
10173
6535
  }
10174
6536
  function convertPartialDocument(api, options) {
10175
6537
  let sourceType = "text";
10176
- if (options.url)
10177
- sourceType = "url";
10178
- if (options.file)
10179
- sourceType = "file";
6538
+ if (options.url) sourceType = "url";
6539
+ if (options.file) sourceType = "file";
10180
6540
  return {
10181
6541
  id: api.id || "",
10182
6542
  collectionId: api.collection_id || options.collectionId || "",
@@ -10351,10 +6711,8 @@ var BlinkRAGImpl = class {
10351
6711
  */
10352
6712
  async listDocuments(options) {
10353
6713
  const params = {};
10354
- if (options?.collectionId)
10355
- params.collection_id = options.collectionId;
10356
- if (options?.status)
10357
- params.status = options.status;
6714
+ if (options?.collectionId) params.collection_id = options.collectionId;
6715
+ if (options?.status) params.status = options.status;
10358
6716
  const queryString = Object.keys(params).length > 0 ? `?${new URLSearchParams(params).toString()}` : "";
10359
6717
  const response = await this.httpClient.get(
10360
6718
  this.url(`/documents${queryString}`)
@@ -10558,19 +6916,15 @@ var BlinkQueueImpl = class {
10558
6916
  `${this.basePath}/enqueue`,
10559
6917
  { taskName, payload, options }
10560
6918
  ).then((res) => res.data).catch((err) => {
10561
- if (err?.status === 402)
10562
- throw new BlinkQueueCreditError();
6919
+ if (err?.status === 402) throw new BlinkQueueCreditError();
10563
6920
  throw err;
10564
6921
  });
10565
6922
  }
10566
6923
  async list(filter) {
10567
6924
  const params = {};
10568
- if (filter?.status)
10569
- params.status = filter.status;
10570
- if (filter?.queue)
10571
- params.queue = filter.queue;
10572
- if (filter?.limit)
10573
- params.limit = String(filter.limit);
6925
+ if (filter?.status) params.status = filter.status;
6926
+ if (filter?.queue) params.queue = filter.queue;
6927
+ if (filter?.limit) params.limit = String(filter.limit);
10574
6928
  const res = await this.httpClient.get(`${this.basePath}/tasks`, params);
10575
6929
  return res.data.tasks;
10576
6930
  }
@@ -10665,7 +7019,8 @@ var BlinkClientImpl = class {
10665
7019
  this._httpClient = new HttpClient(
10666
7020
  config,
10667
7021
  () => this.auth.getToken(),
10668
- () => this.auth.getValidToken()
7022
+ () => this.auth.getValidToken(),
7023
+ () => this.auth.forceRefreshAccessToken()
10669
7024
  );
10670
7025
  this.db = new BlinkDatabase(this._httpClient);
10671
7026
  this.storage = new BlinkStorageImpl(this._httpClient);
@@ -10768,5 +7123,5 @@ exports.storageTools = storageTools;
10768
7123
  exports.storageUpload = storageUpload;
10769
7124
  exports.webSearch = webSearch;
10770
7125
  exports.writeFile = writeFile;
10771
- //# sourceMappingURL=out.js.map
7126
+ //# sourceMappingURL=index.js.map
10772
7127
  //# sourceMappingURL=index.js.map