@blinkdotnew/dev-sdk 2.3.1 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2582 +1,9 @@
1
- var __getOwnPropNames = Object.getOwnPropertyNames;
2
1
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
2
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
3
  }) : x)(function(x) {
5
4
  if (typeof require !== "undefined") return require.apply(this, arguments);
6
5
  throw Error('Dynamic require of "' + x + '" is not supported');
7
6
  });
8
- var __commonJS = (cb, mod) => function __require2() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
11
-
12
- // ../../node_modules/async-limiter/index.js
13
- var require_async_limiter = __commonJS({
14
- "../../node_modules/async-limiter/index.js"(exports, module) {
15
- function Queue(options) {
16
- if (!(this instanceof Queue)) {
17
- return new Queue(options);
18
- }
19
- options = options || {};
20
- this.concurrency = options.concurrency || Infinity;
21
- this.pending = 0;
22
- this.jobs = [];
23
- this.cbs = [];
24
- this._done = done.bind(this);
25
- }
26
- var arrayAddMethods = [
27
- "push",
28
- "unshift",
29
- "splice"
30
- ];
31
- arrayAddMethods.forEach(function(method) {
32
- Queue.prototype[method] = function() {
33
- var methodResult = Array.prototype[method].apply(this.jobs, arguments);
34
- this._run();
35
- return methodResult;
36
- };
37
- });
38
- Object.defineProperty(Queue.prototype, "length", {
39
- get: function() {
40
- return this.pending + this.jobs.length;
41
- }
42
- });
43
- Queue.prototype._run = function() {
44
- if (this.pending === this.concurrency) {
45
- return;
46
- }
47
- if (this.jobs.length) {
48
- var job = this.jobs.shift();
49
- this.pending++;
50
- job(this._done);
51
- this._run();
52
- }
53
- if (this.pending === 0) {
54
- while (this.cbs.length !== 0) {
55
- var cb = this.cbs.pop();
56
- process.nextTick(cb);
57
- }
58
- }
59
- };
60
- Queue.prototype.onDone = function(cb) {
61
- if (typeof cb === "function") {
62
- this.cbs.push(cb);
63
- this._run();
64
- }
65
- };
66
- function done() {
67
- this.pending--;
68
- this._run();
69
- }
70
- module.exports = Queue;
71
- }
72
- });
73
-
74
- // ../../node_modules/ws/lib/constants.js
75
- var require_constants = __commonJS({
76
- "../../node_modules/ws/lib/constants.js"(exports, module) {
77
- module.exports = {
78
- BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
79
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
80
- kStatusCode: Symbol("status-code"),
81
- kWebSocket: Symbol("websocket"),
82
- EMPTY_BUFFER: Buffer.alloc(0),
83
- NOOP: () => {
84
- }
85
- };
86
- }
87
- });
88
-
89
- // ../../node_modules/ws/lib/buffer-util.js
90
- var require_buffer_util = __commonJS({
91
- "../../node_modules/ws/lib/buffer-util.js"(exports, module) {
92
- var { EMPTY_BUFFER } = require_constants();
93
- function concat(list, totalLength) {
94
- if (list.length === 0) return EMPTY_BUFFER;
95
- if (list.length === 1) return list[0];
96
- const target = Buffer.allocUnsafe(totalLength);
97
- var offset = 0;
98
- for (var i = 0; i < list.length; i++) {
99
- const buf = list[i];
100
- buf.copy(target, offset);
101
- offset += buf.length;
102
- }
103
- return target;
104
- }
105
- function _mask(source, mask, output, offset, length) {
106
- for (var i = 0; i < length; i++) {
107
- output[offset + i] = source[i] ^ mask[i & 3];
108
- }
109
- }
110
- function _unmask(buffer, mask) {
111
- const length = buffer.length;
112
- for (var i = 0; i < length; i++) {
113
- buffer[i] ^= mask[i & 3];
114
- }
115
- }
116
- function toArrayBuffer(buf) {
117
- if (buf.byteLength === buf.buffer.byteLength) {
118
- return buf.buffer;
119
- }
120
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
121
- }
122
- function toBuffer(data) {
123
- toBuffer.readOnly = true;
124
- if (Buffer.isBuffer(data)) return data;
125
- var buf;
126
- if (data instanceof ArrayBuffer) {
127
- buf = Buffer.from(data);
128
- } else if (ArrayBuffer.isView(data)) {
129
- buf = viewToBuffer(data);
130
- } else {
131
- buf = Buffer.from(data);
132
- toBuffer.readOnly = false;
133
- }
134
- return buf;
135
- }
136
- function viewToBuffer(view) {
137
- const buf = Buffer.from(view.buffer);
138
- if (view.byteLength !== view.buffer.byteLength) {
139
- return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);
140
- }
141
- return buf;
142
- }
143
- try {
144
- const bufferUtil = __require("bufferutil");
145
- const bu = bufferUtil.BufferUtil || bufferUtil;
146
- module.exports = {
147
- concat,
148
- mask(source, mask, output, offset, length) {
149
- if (length < 48) _mask(source, mask, output, offset, length);
150
- else bu.mask(source, mask, output, offset, length);
151
- },
152
- toArrayBuffer,
153
- toBuffer,
154
- unmask(buffer, mask) {
155
- if (buffer.length < 32) _unmask(buffer, mask);
156
- else bu.unmask(buffer, mask);
157
- }
158
- };
159
- } catch (e) {
160
- module.exports = {
161
- concat,
162
- mask: _mask,
163
- toArrayBuffer,
164
- toBuffer,
165
- unmask: _unmask
166
- };
167
- }
168
- }
169
- });
170
-
171
- // ../../node_modules/ws/lib/permessage-deflate.js
172
- var require_permessage_deflate = __commonJS({
173
- "../../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
174
- var Limiter = require_async_limiter();
175
- var zlib = __require("zlib");
176
- var bufferUtil = require_buffer_util();
177
- var { kStatusCode, NOOP } = require_constants();
178
- var TRAILER = Buffer.from([0, 0, 255, 255]);
179
- var EMPTY_BLOCK = Buffer.from([0]);
180
- var kPerMessageDeflate = Symbol("permessage-deflate");
181
- var kTotalLength = Symbol("total-length");
182
- var kCallback = Symbol("callback");
183
- var kBuffers = Symbol("buffers");
184
- var kError = Symbol("error");
185
- var zlibLimiter;
186
- var PerMessageDeflate = class {
187
- /**
188
- * Creates a PerMessageDeflate instance.
189
- *
190
- * @param {Object} options Configuration options
191
- * @param {Boolean} options.serverNoContextTakeover Request/accept disabling
192
- * of server context takeover
193
- * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge
194
- * disabling of client context takeover
195
- * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the
196
- * use of a custom server window size
197
- * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support
198
- * for, or request, a custom client window size
199
- * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate
200
- * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate
201
- * @param {Number} options.threshold Size (in bytes) below which messages
202
- * should not be compressed
203
- * @param {Number} options.concurrencyLimit The number of concurrent calls to
204
- * zlib
205
- * @param {Boolean} isServer Create the instance in either server or client
206
- * mode
207
- * @param {Number} maxPayload 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
- this._deflate.close();
276
- this._deflate = null;
277
- }
278
- }
279
- /**
280
- * Accept an extension negotiation offer.
281
- *
282
- * @param {Array} offers The extension negotiation offers
283
- * @return {Object} Accepted configuration
284
- * @private
285
- */
286
- acceptAsServer(offers) {
287
- const opts = this._options;
288
- const accepted = offers.find((params) => {
289
- 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) {
290
- return false;
291
- }
292
- return true;
293
- });
294
- if (!accepted) {
295
- throw new Error("None of the extension offers can be accepted");
296
- }
297
- if (opts.serverNoContextTakeover) {
298
- accepted.server_no_context_takeover = true;
299
- }
300
- if (opts.clientNoContextTakeover) {
301
- accepted.client_no_context_takeover = true;
302
- }
303
- if (typeof opts.serverMaxWindowBits === "number") {
304
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
305
- }
306
- if (typeof opts.clientMaxWindowBits === "number") {
307
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
308
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
309
- delete accepted.client_max_window_bits;
310
- }
311
- return accepted;
312
- }
313
- /**
314
- * Accept the extension negotiation response.
315
- *
316
- * @param {Array} response The extension negotiation response
317
- * @return {Object} Accepted configuration
318
- * @private
319
- */
320
- acceptAsClient(response) {
321
- const params = response[0];
322
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
323
- throw new Error('Unexpected parameter "client_no_context_takeover"');
324
- }
325
- if (!params.client_max_window_bits) {
326
- if (typeof this._options.clientMaxWindowBits === "number") {
327
- params.client_max_window_bits = this._options.clientMaxWindowBits;
328
- }
329
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
330
- throw new Error(
331
- 'Unexpected or invalid parameter "client_max_window_bits"'
332
- );
333
- }
334
- return params;
335
- }
336
- /**
337
- * Normalize parameters.
338
- *
339
- * @param {Array} configurations The extension negotiation offers/reponse
340
- * @return {Array} The offers/response with normalized parameters
341
- * @private
342
- */
343
- normalizeParams(configurations) {
344
- configurations.forEach((params) => {
345
- Object.keys(params).forEach((key) => {
346
- var value = params[key];
347
- if (value.length > 1) {
348
- throw new Error(`Parameter "${key}" must have only a single value`);
349
- }
350
- value = value[0];
351
- if (key === "client_max_window_bits") {
352
- if (value !== true) {
353
- const num = +value;
354
- if (!Number.isInteger(num) || num < 8 || num > 15) {
355
- throw new TypeError(
356
- `Invalid value for parameter "${key}": ${value}`
357
- );
358
- }
359
- value = num;
360
- } else if (!this._isServer) {
361
- throw new TypeError(
362
- `Invalid value for parameter "${key}": ${value}`
363
- );
364
- }
365
- } else if (key === "server_max_window_bits") {
366
- const num = +value;
367
- if (!Number.isInteger(num) || num < 8 || num > 15) {
368
- throw new TypeError(
369
- `Invalid value for parameter "${key}": ${value}`
370
- );
371
- }
372
- value = num;
373
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
374
- if (value !== true) {
375
- throw new TypeError(
376
- `Invalid value for parameter "${key}": ${value}`
377
- );
378
- }
379
- } else {
380
- throw new Error(`Unknown parameter "${key}"`);
381
- }
382
- params[key] = value;
383
- });
384
- });
385
- return configurations;
386
- }
387
- /**
388
- * Decompress data. Concurrency limited by async-limiter.
389
- *
390
- * @param {Buffer} data Compressed data
391
- * @param {Boolean} fin Specifies whether or not this is the last fragment
392
- * @param {Function} callback Callback
393
- * @public
394
- */
395
- decompress(data, fin, callback) {
396
- zlibLimiter.push((done) => {
397
- this._decompress(data, fin, (err, result) => {
398
- done();
399
- callback(err, result);
400
- });
401
- });
402
- }
403
- /**
404
- * Compress data. Concurrency limited by async-limiter.
405
- *
406
- * @param {Buffer} data Data to compress
407
- * @param {Boolean} fin Specifies whether or not this is the last fragment
408
- * @param {Function} callback Callback
409
- * @public
410
- */
411
- compress(data, fin, callback) {
412
- zlibLimiter.push((done) => {
413
- this._compress(data, fin, (err, result) => {
414
- done();
415
- callback(err, result);
416
- });
417
- });
418
- }
419
- /**
420
- * Decompress data.
421
- *
422
- * @param {Buffer} data Compressed data
423
- * @param {Boolean} fin Specifies whether or not this is the last fragment
424
- * @param {Function} callback Callback
425
- * @private
426
- */
427
- _decompress(data, fin, callback) {
428
- const endpoint = this._isServer ? "client" : "server";
429
- if (!this._inflate) {
430
- const key = `${endpoint}_max_window_bits`;
431
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
432
- this._inflate = zlib.createInflateRaw(
433
- Object.assign({}, this._options.zlibInflateOptions, { windowBits })
434
- );
435
- this._inflate[kPerMessageDeflate] = this;
436
- this._inflate[kTotalLength] = 0;
437
- this._inflate[kBuffers] = [];
438
- this._inflate.on("error", inflateOnError);
439
- this._inflate.on("data", inflateOnData);
440
- }
441
- this._inflate[kCallback] = callback;
442
- this._inflate.write(data);
443
- if (fin) this._inflate.write(TRAILER);
444
- this._inflate.flush(() => {
445
- const err = this._inflate[kError];
446
- if (err) {
447
- this._inflate.close();
448
- this._inflate = null;
449
- callback(err);
450
- return;
451
- }
452
- const data2 = bufferUtil.concat(
453
- this._inflate[kBuffers],
454
- this._inflate[kTotalLength]
455
- );
456
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
457
- this._inflate.close();
458
- this._inflate = null;
459
- } else {
460
- this._inflate[kTotalLength] = 0;
461
- this._inflate[kBuffers] = [];
462
- }
463
- callback(null, data2);
464
- });
465
- }
466
- /**
467
- * Compress data.
468
- *
469
- * @param {Buffer} data Data to compress
470
- * @param {Boolean} fin Specifies whether or not this is the last fragment
471
- * @param {Function} callback Callback
472
- * @private
473
- */
474
- _compress(data, fin, callback) {
475
- if (!data || data.length === 0) {
476
- process.nextTick(callback, null, EMPTY_BLOCK);
477
- return;
478
- }
479
- const endpoint = this._isServer ? "server" : "client";
480
- if (!this._deflate) {
481
- const key = `${endpoint}_max_window_bits`;
482
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
483
- this._deflate = zlib.createDeflateRaw(
484
- Object.assign({}, this._options.zlibDeflateOptions, { windowBits })
485
- );
486
- this._deflate[kTotalLength] = 0;
487
- this._deflate[kBuffers] = [];
488
- this._deflate.on("error", NOOP);
489
- this._deflate.on("data", deflateOnData);
490
- }
491
- this._deflate.write(data);
492
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
493
- if (!this._deflate) {
494
- return;
495
- }
496
- var data2 = bufferUtil.concat(
497
- this._deflate[kBuffers],
498
- this._deflate[kTotalLength]
499
- );
500
- if (fin) data2 = data2.slice(0, data2.length - 4);
501
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
502
- this._deflate.close();
503
- this._deflate = null;
504
- } else {
505
- this._deflate[kTotalLength] = 0;
506
- this._deflate[kBuffers] = [];
507
- }
508
- callback(null, data2);
509
- });
510
- }
511
- };
512
- module.exports = PerMessageDeflate;
513
- function deflateOnData(chunk) {
514
- this[kBuffers].push(chunk);
515
- this[kTotalLength] += chunk.length;
516
- }
517
- function inflateOnData(chunk) {
518
- this[kTotalLength] += chunk.length;
519
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
520
- this[kBuffers].push(chunk);
521
- return;
522
- }
523
- this[kError] = new RangeError("Max payload size exceeded");
524
- this[kError][kStatusCode] = 1009;
525
- this.removeListener("data", inflateOnData);
526
- this.reset();
527
- }
528
- function inflateOnError(err) {
529
- this[kPerMessageDeflate]._inflate = null;
530
- err[kStatusCode] = 1007;
531
- this[kCallback](err);
532
- }
533
- }
534
- });
535
-
536
- // ../../node_modules/ws/lib/event-target.js
537
- var require_event_target = __commonJS({
538
- "../../node_modules/ws/lib/event-target.js"(exports, module) {
539
- var Event = class {
540
- /**
541
- * Create a new `Event`.
542
- *
543
- * @param {String} type The name of the event
544
- * @param {Object} target A reference to the target to which the event was dispatched
545
- */
546
- constructor(type, target) {
547
- this.target = target;
548
- this.type = type;
549
- }
550
- };
551
- var MessageEvent = class extends Event {
552
- /**
553
- * Create a new `MessageEvent`.
554
- *
555
- * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data
556
- * @param {WebSocket} target A reference to the target to which the event was dispatched
557
- */
558
- constructor(data, target) {
559
- super("message", target);
560
- this.data = data;
561
- }
562
- };
563
- var CloseEvent = class extends Event {
564
- /**
565
- * Create a new `CloseEvent`.
566
- *
567
- * @param {Number} code The status code explaining why the connection is being closed
568
- * @param {String} reason A human-readable string explaining why the connection is closing
569
- * @param {WebSocket} target A reference to the target to which the event was dispatched
570
- */
571
- constructor(code, reason, target) {
572
- super("close", target);
573
- this.wasClean = target._closeFrameReceived && target._closeFrameSent;
574
- this.reason = reason;
575
- this.code = code;
576
- }
577
- };
578
- var OpenEvent = class extends Event {
579
- /**
580
- * Create a new `OpenEvent`.
581
- *
582
- * @param {WebSocket} target A reference to the target to which the event was dispatched
583
- */
584
- constructor(target) {
585
- super("open", target);
586
- }
587
- };
588
- var ErrorEvent = class extends Event {
589
- /**
590
- * Create a new `ErrorEvent`.
591
- *
592
- * @param {Object} error The error that generated this event
593
- * @param {WebSocket} target A reference to the target to which the event was dispatched
594
- */
595
- constructor(error, target) {
596
- super("error", target);
597
- this.message = error.message;
598
- this.error = error;
599
- }
600
- };
601
- var EventTarget = {
602
- /**
603
- * Register an event listener.
604
- *
605
- * @param {String} method A string representing the event type to listen for
606
- * @param {Function} listener The listener to add
607
- * @public
608
- */
609
- addEventListener(method, listener) {
610
- if (typeof listener !== "function") return;
611
- function onMessage(data) {
612
- listener.call(this, new MessageEvent(data, this));
613
- }
614
- function onClose(code, message) {
615
- listener.call(this, new CloseEvent(code, message, this));
616
- }
617
- function onError(error) {
618
- listener.call(this, new ErrorEvent(error, this));
619
- }
620
- function onOpen() {
621
- listener.call(this, new OpenEvent(this));
622
- }
623
- if (method === "message") {
624
- onMessage._listener = listener;
625
- this.on(method, onMessage);
626
- } else if (method === "close") {
627
- onClose._listener = listener;
628
- this.on(method, onClose);
629
- } else if (method === "error") {
630
- onError._listener = listener;
631
- this.on(method, onError);
632
- } else if (method === "open") {
633
- onOpen._listener = listener;
634
- this.on(method, onOpen);
635
- } else {
636
- this.on(method, listener);
637
- }
638
- },
639
- /**
640
- * Remove an event listener.
641
- *
642
- * @param {String} method A string representing the event type to remove
643
- * @param {Function} listener The listener to remove
644
- * @public
645
- */
646
- removeEventListener(method, listener) {
647
- const listeners = this.listeners(method);
648
- for (var i = 0; i < listeners.length; i++) {
649
- if (listeners[i] === listener || listeners[i]._listener === listener) {
650
- this.removeListener(method, listeners[i]);
651
- }
652
- }
653
- }
654
- };
655
- module.exports = EventTarget;
656
- }
657
- });
658
-
659
- // ../../node_modules/ws/lib/extension.js
660
- var require_extension = __commonJS({
661
- "../../node_modules/ws/lib/extension.js"(exports, module) {
662
- var tokenChars = [
663
- 0,
664
- 0,
665
- 0,
666
- 0,
667
- 0,
668
- 0,
669
- 0,
670
- 0,
671
- 0,
672
- 0,
673
- 0,
674
- 0,
675
- 0,
676
- 0,
677
- 0,
678
- 0,
679
- // 0 - 15
680
- 0,
681
- 0,
682
- 0,
683
- 0,
684
- 0,
685
- 0,
686
- 0,
687
- 0,
688
- 0,
689
- 0,
690
- 0,
691
- 0,
692
- 0,
693
- 0,
694
- 0,
695
- 0,
696
- // 16 - 31
697
- 0,
698
- 1,
699
- 0,
700
- 1,
701
- 1,
702
- 1,
703
- 1,
704
- 1,
705
- 0,
706
- 0,
707
- 1,
708
- 1,
709
- 0,
710
- 1,
711
- 1,
712
- 0,
713
- // 32 - 47
714
- 1,
715
- 1,
716
- 1,
717
- 1,
718
- 1,
719
- 1,
720
- 1,
721
- 1,
722
- 1,
723
- 1,
724
- 0,
725
- 0,
726
- 0,
727
- 0,
728
- 0,
729
- 0,
730
- // 48 - 63
731
- 0,
732
- 1,
733
- 1,
734
- 1,
735
- 1,
736
- 1,
737
- 1,
738
- 1,
739
- 1,
740
- 1,
741
- 1,
742
- 1,
743
- 1,
744
- 1,
745
- 1,
746
- 1,
747
- // 64 - 79
748
- 1,
749
- 1,
750
- 1,
751
- 1,
752
- 1,
753
- 1,
754
- 1,
755
- 1,
756
- 1,
757
- 1,
758
- 1,
759
- 0,
760
- 0,
761
- 0,
762
- 1,
763
- 1,
764
- // 80 - 95
765
- 1,
766
- 1,
767
- 1,
768
- 1,
769
- 1,
770
- 1,
771
- 1,
772
- 1,
773
- 1,
774
- 1,
775
- 1,
776
- 1,
777
- 1,
778
- 1,
779
- 1,
780
- 1,
781
- // 96 - 111
782
- 1,
783
- 1,
784
- 1,
785
- 1,
786
- 1,
787
- 1,
788
- 1,
789
- 1,
790
- 1,
791
- 1,
792
- 1,
793
- 0,
794
- 1,
795
- 0,
796
- 1,
797
- 0
798
- // 112 - 127
799
- ];
800
- function push(dest, name, elem) {
801
- if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem);
802
- else dest[name] = [elem];
803
- }
804
- function parse(header) {
805
- const offers = {};
806
- if (header === void 0 || header === "") return offers;
807
- var params = {};
808
- var mustUnescape = false;
809
- var isEscaping = false;
810
- var inQuotes = false;
811
- var extensionName;
812
- var paramName;
813
- var start = -1;
814
- var end = -1;
815
- for (var i = 0; i < header.length; i++) {
816
- const code = header.charCodeAt(i);
817
- if (extensionName === void 0) {
818
- if (end === -1 && tokenChars[code] === 1) {
819
- if (start === -1) start = i;
820
- } else if (code === 32 || code === 9) {
821
- if (end === -1 && start !== -1) end = i;
822
- } else if (code === 59 || code === 44) {
823
- if (start === -1) {
824
- throw new SyntaxError(`Unexpected character at index ${i}`);
825
- }
826
- if (end === -1) end = i;
827
- const name = header.slice(start, end);
828
- if (code === 44) {
829
- push(offers, name, params);
830
- params = {};
831
- } else {
832
- extensionName = name;
833
- }
834
- start = end = -1;
835
- } else {
836
- throw new SyntaxError(`Unexpected character at index ${i}`);
837
- }
838
- } else if (paramName === void 0) {
839
- if (end === -1 && tokenChars[code] === 1) {
840
- if (start === -1) start = i;
841
- } else if (code === 32 || code === 9) {
842
- if (end === -1 && start !== -1) end = i;
843
- } else if (code === 59 || code === 44) {
844
- if (start === -1) {
845
- throw new SyntaxError(`Unexpected character at index ${i}`);
846
- }
847
- if (end === -1) end = i;
848
- push(params, header.slice(start, end), true);
849
- if (code === 44) {
850
- push(offers, extensionName, params);
851
- params = {};
852
- extensionName = void 0;
853
- }
854
- start = end = -1;
855
- } else if (code === 61 && start !== -1 && end === -1) {
856
- paramName = header.slice(start, i);
857
- start = end = -1;
858
- } else {
859
- throw new SyntaxError(`Unexpected character at index ${i}`);
860
- }
861
- } else {
862
- if (isEscaping) {
863
- if (tokenChars[code] !== 1) {
864
- throw new SyntaxError(`Unexpected character at index ${i}`);
865
- }
866
- if (start === -1) start = i;
867
- else if (!mustUnescape) mustUnescape = true;
868
- isEscaping = false;
869
- } else if (inQuotes) {
870
- if (tokenChars[code] === 1) {
871
- if (start === -1) start = i;
872
- } else if (code === 34 && start !== -1) {
873
- inQuotes = false;
874
- end = i;
875
- } else if (code === 92) {
876
- isEscaping = true;
877
- } else {
878
- throw new SyntaxError(`Unexpected character at index ${i}`);
879
- }
880
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
881
- inQuotes = true;
882
- } else if (end === -1 && tokenChars[code] === 1) {
883
- if (start === -1) start = i;
884
- } else if (start !== -1 && (code === 32 || code === 9)) {
885
- if (end === -1) end = i;
886
- } else if (code === 59 || code === 44) {
887
- if (start === -1) {
888
- throw new SyntaxError(`Unexpected character at index ${i}`);
889
- }
890
- if (end === -1) end = i;
891
- var value = header.slice(start, end);
892
- if (mustUnescape) {
893
- value = value.replace(/\\/g, "");
894
- mustUnescape = false;
895
- }
896
- push(params, paramName, value);
897
- if (code === 44) {
898
- push(offers, extensionName, params);
899
- params = {};
900
- extensionName = void 0;
901
- }
902
- paramName = void 0;
903
- start = end = -1;
904
- } else {
905
- throw new SyntaxError(`Unexpected character at index ${i}`);
906
- }
907
- }
908
- }
909
- if (start === -1 || inQuotes) {
910
- throw new SyntaxError("Unexpected end of input");
911
- }
912
- if (end === -1) end = i;
913
- const token = header.slice(start, end);
914
- if (extensionName === void 0) {
915
- push(offers, token, {});
916
- } else {
917
- if (paramName === void 0) {
918
- push(params, token, true);
919
- } else if (mustUnescape) {
920
- push(params, paramName, token.replace(/\\/g, ""));
921
- } else {
922
- push(params, paramName, token);
923
- }
924
- push(offers, extensionName, params);
925
- }
926
- return offers;
927
- }
928
- function format(extensions) {
929
- return Object.keys(extensions).map((extension) => {
930
- var configurations = extensions[extension];
931
- if (!Array.isArray(configurations)) configurations = [configurations];
932
- return configurations.map((params) => {
933
- return [extension].concat(
934
- Object.keys(params).map((k) => {
935
- var values = params[k];
936
- if (!Array.isArray(values)) values = [values];
937
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
938
- })
939
- ).join("; ");
940
- }).join(", ");
941
- }).join(", ");
942
- }
943
- module.exports = { format, parse };
944
- }
945
- });
946
-
947
- // ../../node_modules/ws/lib/validation.js
948
- var require_validation = __commonJS({
949
- "../../node_modules/ws/lib/validation.js"(exports) {
950
- try {
951
- const isValidUTF8 = __require("utf-8-validate");
952
- exports.isValidUTF8 = typeof isValidUTF8 === "object" ? isValidUTF8.Validation.isValidUTF8 : isValidUTF8;
953
- } catch (e) {
954
- exports.isValidUTF8 = () => true;
955
- }
956
- exports.isValidStatusCode = (code) => {
957
- return code >= 1e3 && code <= 1013 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
958
- };
959
- }
960
- });
961
-
962
- // ../../node_modules/ws/lib/receiver.js
963
- var require_receiver = __commonJS({
964
- "../../node_modules/ws/lib/receiver.js"(exports, module) {
965
- var { Writable } = __require("stream");
966
- var PerMessageDeflate = require_permessage_deflate();
967
- var {
968
- BINARY_TYPES,
969
- EMPTY_BUFFER,
970
- kStatusCode,
971
- kWebSocket
972
- } = require_constants();
973
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
974
- var { isValidStatusCode, isValidUTF8 } = require_validation();
975
- var GET_INFO = 0;
976
- var GET_PAYLOAD_LENGTH_16 = 1;
977
- var GET_PAYLOAD_LENGTH_64 = 2;
978
- var GET_MASK = 3;
979
- var GET_DATA = 4;
980
- var INFLATING = 5;
981
- var Receiver = class extends Writable {
982
- /**
983
- * Creates a Receiver instance.
984
- *
985
- * @param {String} binaryType The type for binary data
986
- * @param {Object} extensions An object containing the negotiated extensions
987
- * @param {Number} maxPayload The maximum allowed message length
988
- */
989
- constructor(binaryType, extensions, maxPayload) {
990
- super();
991
- this._binaryType = binaryType || BINARY_TYPES[0];
992
- this[kWebSocket] = void 0;
993
- this._extensions = extensions || {};
994
- this._maxPayload = maxPayload | 0;
995
- this._bufferedBytes = 0;
996
- this._buffers = [];
997
- this._compressed = false;
998
- this._payloadLength = 0;
999
- this._mask = void 0;
1000
- this._fragmented = 0;
1001
- this._masked = false;
1002
- this._fin = false;
1003
- this._opcode = 0;
1004
- this._totalPayloadLength = 0;
1005
- this._messageLength = 0;
1006
- this._fragments = [];
1007
- this._state = GET_INFO;
1008
- this._loop = false;
1009
- }
1010
- /**
1011
- * Implements `Writable.prototype._write()`.
1012
- *
1013
- * @param {Buffer} chunk The chunk of data to write
1014
- * @param {String} encoding The character encoding of `chunk`
1015
- * @param {Function} cb Callback
1016
- */
1017
- _write(chunk, encoding, cb) {
1018
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
1019
- this._bufferedBytes += chunk.length;
1020
- this._buffers.push(chunk);
1021
- this.startLoop(cb);
1022
- }
1023
- /**
1024
- * Consumes `n` bytes from the buffered data.
1025
- *
1026
- * @param {Number} n The number of bytes to consume
1027
- * @return {Buffer} The consumed bytes
1028
- * @private
1029
- */
1030
- consume(n) {
1031
- this._bufferedBytes -= n;
1032
- if (n === this._buffers[0].length) return this._buffers.shift();
1033
- if (n < this._buffers[0].length) {
1034
- const buf = this._buffers[0];
1035
- this._buffers[0] = buf.slice(n);
1036
- return buf.slice(0, n);
1037
- }
1038
- const dst = Buffer.allocUnsafe(n);
1039
- do {
1040
- const buf = this._buffers[0];
1041
- if (n >= buf.length) {
1042
- this._buffers.shift().copy(dst, dst.length - n);
1043
- } else {
1044
- buf.copy(dst, dst.length - n, 0, n);
1045
- this._buffers[0] = buf.slice(n);
1046
- }
1047
- n -= buf.length;
1048
- } while (n > 0);
1049
- return dst;
1050
- }
1051
- /**
1052
- * Starts the parsing loop.
1053
- *
1054
- * @param {Function} cb Callback
1055
- * @private
1056
- */
1057
- startLoop(cb) {
1058
- var err;
1059
- this._loop = true;
1060
- do {
1061
- switch (this._state) {
1062
- case GET_INFO:
1063
- err = this.getInfo();
1064
- break;
1065
- case GET_PAYLOAD_LENGTH_16:
1066
- err = this.getPayloadLength16();
1067
- break;
1068
- case GET_PAYLOAD_LENGTH_64:
1069
- err = this.getPayloadLength64();
1070
- break;
1071
- case GET_MASK:
1072
- this.getMask();
1073
- break;
1074
- case GET_DATA:
1075
- err = this.getData(cb);
1076
- break;
1077
- default:
1078
- this._loop = false;
1079
- return;
1080
- }
1081
- } while (this._loop);
1082
- cb(err);
1083
- }
1084
- /**
1085
- * Reads the first two bytes of a frame.
1086
- *
1087
- * @return {(RangeError|undefined)} A possible error
1088
- * @private
1089
- */
1090
- getInfo() {
1091
- if (this._bufferedBytes < 2) {
1092
- this._loop = false;
1093
- return;
1094
- }
1095
- const buf = this.consume(2);
1096
- if ((buf[0] & 48) !== 0) {
1097
- this._loop = false;
1098
- return error(RangeError, "RSV2 and RSV3 must be clear", true, 1002);
1099
- }
1100
- const compressed = (buf[0] & 64) === 64;
1101
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1102
- this._loop = false;
1103
- return error(RangeError, "RSV1 must be clear", true, 1002);
1104
- }
1105
- this._fin = (buf[0] & 128) === 128;
1106
- this._opcode = buf[0] & 15;
1107
- this._payloadLength = buf[1] & 127;
1108
- if (this._opcode === 0) {
1109
- if (compressed) {
1110
- this._loop = false;
1111
- return error(RangeError, "RSV1 must be clear", true, 1002);
1112
- }
1113
- if (!this._fragmented) {
1114
- this._loop = false;
1115
- return error(RangeError, "invalid opcode 0", true, 1002);
1116
- }
1117
- this._opcode = this._fragmented;
1118
- } else if (this._opcode === 1 || this._opcode === 2) {
1119
- if (this._fragmented) {
1120
- this._loop = false;
1121
- return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
1122
- }
1123
- this._compressed = compressed;
1124
- } else if (this._opcode > 7 && this._opcode < 11) {
1125
- if (!this._fin) {
1126
- this._loop = false;
1127
- return error(RangeError, "FIN must be set", true, 1002);
1128
- }
1129
- if (compressed) {
1130
- this._loop = false;
1131
- return error(RangeError, "RSV1 must be clear", true, 1002);
1132
- }
1133
- if (this._payloadLength > 125) {
1134
- this._loop = false;
1135
- return error(
1136
- RangeError,
1137
- `invalid payload length ${this._payloadLength}`,
1138
- true,
1139
- 1002
1140
- );
1141
- }
1142
- } else {
1143
- this._loop = false;
1144
- return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
1145
- }
1146
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1147
- this._masked = (buf[1] & 128) === 128;
1148
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1149
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1150
- else return this.haveLength();
1151
- }
1152
- /**
1153
- * Gets extended payload length (7+16).
1154
- *
1155
- * @return {(RangeError|undefined)} A possible error
1156
- * @private
1157
- */
1158
- getPayloadLength16() {
1159
- if (this._bufferedBytes < 2) {
1160
- this._loop = false;
1161
- return;
1162
- }
1163
- this._payloadLength = this.consume(2).readUInt16BE(0);
1164
- return this.haveLength();
1165
- }
1166
- /**
1167
- * Gets extended payload length (7+64).
1168
- *
1169
- * @return {(RangeError|undefined)} A possible error
1170
- * @private
1171
- */
1172
- getPayloadLength64() {
1173
- if (this._bufferedBytes < 8) {
1174
- this._loop = false;
1175
- return;
1176
- }
1177
- const buf = this.consume(8);
1178
- const num = buf.readUInt32BE(0);
1179
- if (num > Math.pow(2, 53 - 32) - 1) {
1180
- this._loop = false;
1181
- return error(
1182
- RangeError,
1183
- "Unsupported WebSocket frame: payload length > 2^53 - 1",
1184
- false,
1185
- 1009
1186
- );
1187
- }
1188
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1189
- return this.haveLength();
1190
- }
1191
- /**
1192
- * Payload length has been read.
1193
- *
1194
- * @return {(RangeError|undefined)} A possible error
1195
- * @private
1196
- */
1197
- haveLength() {
1198
- if (this._payloadLength && this._opcode < 8) {
1199
- this._totalPayloadLength += this._payloadLength;
1200
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1201
- this._loop = false;
1202
- return error(RangeError, "Max payload size exceeded", false, 1009);
1203
- }
1204
- }
1205
- if (this._masked) this._state = GET_MASK;
1206
- else this._state = GET_DATA;
1207
- }
1208
- /**
1209
- * Reads mask bytes.
1210
- *
1211
- * @private
1212
- */
1213
- getMask() {
1214
- if (this._bufferedBytes < 4) {
1215
- this._loop = false;
1216
- return;
1217
- }
1218
- this._mask = this.consume(4);
1219
- this._state = GET_DATA;
1220
- }
1221
- /**
1222
- * Reads data bytes.
1223
- *
1224
- * @param {Function} cb Callback
1225
- * @return {(Error|RangeError|undefined)} A possible error
1226
- * @private
1227
- */
1228
- getData(cb) {
1229
- var data = EMPTY_BUFFER;
1230
- if (this._payloadLength) {
1231
- if (this._bufferedBytes < this._payloadLength) {
1232
- this._loop = false;
1233
- return;
1234
- }
1235
- data = this.consume(this._payloadLength);
1236
- if (this._masked) unmask(data, this._mask);
1237
- }
1238
- if (this._opcode > 7) return this.controlMessage(data);
1239
- if (this._compressed) {
1240
- this._state = INFLATING;
1241
- this.decompress(data, cb);
1242
- return;
1243
- }
1244
- if (data.length) {
1245
- this._messageLength = this._totalPayloadLength;
1246
- this._fragments.push(data);
1247
- }
1248
- return this.dataMessage();
1249
- }
1250
- /**
1251
- * Decompresses data.
1252
- *
1253
- * @param {Buffer} data Compressed data
1254
- * @param {Function} cb Callback
1255
- * @private
1256
- */
1257
- decompress(data, cb) {
1258
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1259
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1260
- if (err) return cb(err);
1261
- if (buf.length) {
1262
- this._messageLength += buf.length;
1263
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1264
- return cb(
1265
- error(RangeError, "Max payload size exceeded", false, 1009)
1266
- );
1267
- }
1268
- this._fragments.push(buf);
1269
- }
1270
- const er = this.dataMessage();
1271
- if (er) return cb(er);
1272
- this.startLoop(cb);
1273
- });
1274
- }
1275
- /**
1276
- * Handles a data message.
1277
- *
1278
- * @return {(Error|undefined)} A possible error
1279
- * @private
1280
- */
1281
- dataMessage() {
1282
- if (this._fin) {
1283
- const messageLength = this._messageLength;
1284
- const fragments = this._fragments;
1285
- this._totalPayloadLength = 0;
1286
- this._messageLength = 0;
1287
- this._fragmented = 0;
1288
- this._fragments = [];
1289
- if (this._opcode === 2) {
1290
- var data;
1291
- if (this._binaryType === "nodebuffer") {
1292
- data = concat(fragments, messageLength);
1293
- } else if (this._binaryType === "arraybuffer") {
1294
- data = toArrayBuffer(concat(fragments, messageLength));
1295
- } else {
1296
- data = fragments;
1297
- }
1298
- this.emit("message", data);
1299
- } else {
1300
- const buf = concat(fragments, messageLength);
1301
- if (!isValidUTF8(buf)) {
1302
- this._loop = false;
1303
- return error(Error, "invalid UTF-8 sequence", true, 1007);
1304
- }
1305
- this.emit("message", buf.toString());
1306
- }
1307
- }
1308
- this._state = GET_INFO;
1309
- }
1310
- /**
1311
- * Handles a control message.
1312
- *
1313
- * @param {Buffer} data Data to handle
1314
- * @return {(Error|RangeError|undefined)} A possible error
1315
- * @private
1316
- */
1317
- controlMessage(data) {
1318
- if (this._opcode === 8) {
1319
- this._loop = false;
1320
- if (data.length === 0) {
1321
- this.emit("conclude", 1005, "");
1322
- this.end();
1323
- } else if (data.length === 1) {
1324
- return error(RangeError, "invalid payload length 1", true, 1002);
1325
- } else {
1326
- const code = data.readUInt16BE(0);
1327
- if (!isValidStatusCode(code)) {
1328
- return error(RangeError, `invalid status code ${code}`, true, 1002);
1329
- }
1330
- const buf = data.slice(2);
1331
- if (!isValidUTF8(buf)) {
1332
- return error(Error, "invalid UTF-8 sequence", true, 1007);
1333
- }
1334
- this.emit("conclude", code, buf.toString());
1335
- this.end();
1336
- }
1337
- } else if (this._opcode === 9) {
1338
- this.emit("ping", data);
1339
- } else {
1340
- this.emit("pong", data);
1341
- }
1342
- this._state = GET_INFO;
1343
- }
1344
- };
1345
- module.exports = Receiver;
1346
- function error(ErrorCtor, message, prefix, statusCode) {
1347
- const err = new ErrorCtor(
1348
- prefix ? `Invalid WebSocket frame: ${message}` : message
1349
- );
1350
- Error.captureStackTrace(err, error);
1351
- err[kStatusCode] = statusCode;
1352
- return err;
1353
- }
1354
- }
1355
- });
1356
-
1357
- // ../../node_modules/ws/lib/sender.js
1358
- var require_sender = __commonJS({
1359
- "../../node_modules/ws/lib/sender.js"(exports, module) {
1360
- var { randomBytes } = __require("crypto");
1361
- var PerMessageDeflate = require_permessage_deflate();
1362
- var { EMPTY_BUFFER } = require_constants();
1363
- var { isValidStatusCode } = require_validation();
1364
- var { mask: applyMask, toBuffer } = require_buffer_util();
1365
- var Sender = class _Sender {
1366
- /**
1367
- * Creates a Sender instance.
1368
- *
1369
- * @param {net.Socket} socket The connection socket
1370
- * @param {Object} extensions An object containing the negotiated extensions
1371
- */
1372
- constructor(socket, extensions) {
1373
- this._extensions = extensions || {};
1374
- this._socket = socket;
1375
- this._firstFragment = true;
1376
- this._compress = false;
1377
- this._bufferedBytes = 0;
1378
- this._deflating = false;
1379
- this._queue = [];
1380
- }
1381
- /**
1382
- * Frames a piece of data according to the HyBi WebSocket protocol.
1383
- *
1384
- * @param {Buffer} data The data to frame
1385
- * @param {Object} options Options object
1386
- * @param {Number} options.opcode The opcode
1387
- * @param {Boolean} options.readOnly Specifies whether `data` can be modified
1388
- * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
1389
- * @param {Boolean} options.mask Specifies whether or not to mask `data`
1390
- * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
1391
- * @return {Buffer[]} The framed data as a list of `Buffer` instances
1392
- * @public
1393
- */
1394
- static frame(data, options) {
1395
- const merge = options.mask && options.readOnly;
1396
- var offset = options.mask ? 6 : 2;
1397
- var payloadLength = data.length;
1398
- if (data.length >= 65536) {
1399
- offset += 8;
1400
- payloadLength = 127;
1401
- } else if (data.length > 125) {
1402
- offset += 2;
1403
- payloadLength = 126;
1404
- }
1405
- const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
1406
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
1407
- if (options.rsv1) target[0] |= 64;
1408
- target[1] = payloadLength;
1409
- if (payloadLength === 126) {
1410
- target.writeUInt16BE(data.length, 2);
1411
- } else if (payloadLength === 127) {
1412
- target.writeUInt32BE(0, 2);
1413
- target.writeUInt32BE(data.length, 6);
1414
- }
1415
- if (!options.mask) return [target, data];
1416
- const mask = randomBytes(4);
1417
- target[1] |= 128;
1418
- target[offset - 4] = mask[0];
1419
- target[offset - 3] = mask[1];
1420
- target[offset - 2] = mask[2];
1421
- target[offset - 1] = mask[3];
1422
- if (merge) {
1423
- applyMask(data, mask, target, offset, data.length);
1424
- return [target];
1425
- }
1426
- applyMask(data, mask, data, 0, data.length);
1427
- return [target, data];
1428
- }
1429
- /**
1430
- * Sends a close message to the other peer.
1431
- *
1432
- * @param {(Number|undefined)} code The status code component of the body
1433
- * @param {String} data The message component of the body
1434
- * @param {Boolean} mask Specifies whether or not to mask the message
1435
- * @param {Function} cb Callback
1436
- * @public
1437
- */
1438
- close(code, data, mask, cb) {
1439
- var buf;
1440
- if (code === void 0) {
1441
- buf = EMPTY_BUFFER;
1442
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1443
- throw new TypeError("First argument must be a valid error code number");
1444
- } else if (data === void 0 || data === "") {
1445
- buf = Buffer.allocUnsafe(2);
1446
- buf.writeUInt16BE(code, 0);
1447
- } else {
1448
- buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));
1449
- buf.writeUInt16BE(code, 0);
1450
- buf.write(data, 2);
1451
- }
1452
- if (this._deflating) {
1453
- this.enqueue([this.doClose, buf, mask, cb]);
1454
- } else {
1455
- this.doClose(buf, mask, cb);
1456
- }
1457
- }
1458
- /**
1459
- * Frames and sends a close message.
1460
- *
1461
- * @param {Buffer} data The message to send
1462
- * @param {Boolean} mask Specifies whether or not to mask `data`
1463
- * @param {Function} cb Callback
1464
- * @private
1465
- */
1466
- doClose(data, mask, cb) {
1467
- this.sendFrame(
1468
- _Sender.frame(data, {
1469
- fin: true,
1470
- rsv1: false,
1471
- opcode: 8,
1472
- mask,
1473
- readOnly: false
1474
- }),
1475
- cb
1476
- );
1477
- }
1478
- /**
1479
- * Sends a ping message to the other peer.
1480
- *
1481
- * @param {*} data The message to send
1482
- * @param {Boolean} mask Specifies whether or not to mask `data`
1483
- * @param {Function} cb Callback
1484
- * @public
1485
- */
1486
- ping(data, mask, cb) {
1487
- const buf = toBuffer(data);
1488
- if (this._deflating) {
1489
- this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]);
1490
- } else {
1491
- this.doPing(buf, mask, toBuffer.readOnly, cb);
1492
- }
1493
- }
1494
- /**
1495
- * Frames and sends a ping message.
1496
- *
1497
- * @param {*} data The message to send
1498
- * @param {Boolean} mask Specifies whether or not to mask `data`
1499
- * @param {Boolean} readOnly Specifies whether `data` can be modified
1500
- * @param {Function} cb Callback
1501
- * @private
1502
- */
1503
- doPing(data, mask, readOnly, cb) {
1504
- this.sendFrame(
1505
- _Sender.frame(data, {
1506
- fin: true,
1507
- rsv1: false,
1508
- opcode: 9,
1509
- mask,
1510
- readOnly
1511
- }),
1512
- cb
1513
- );
1514
- }
1515
- /**
1516
- * Sends a pong message to the other peer.
1517
- *
1518
- * @param {*} data The message to send
1519
- * @param {Boolean} mask Specifies whether or not to mask `data`
1520
- * @param {Function} cb Callback
1521
- * @public
1522
- */
1523
- pong(data, mask, cb) {
1524
- const buf = toBuffer(data);
1525
- if (this._deflating) {
1526
- this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]);
1527
- } else {
1528
- this.doPong(buf, mask, toBuffer.readOnly, cb);
1529
- }
1530
- }
1531
- /**
1532
- * Frames and sends a pong message.
1533
- *
1534
- * @param {*} data The message to send
1535
- * @param {Boolean} mask Specifies whether or not to mask `data`
1536
- * @param {Boolean} readOnly Specifies whether `data` can be modified
1537
- * @param {Function} cb Callback
1538
- * @private
1539
- */
1540
- doPong(data, mask, readOnly, cb) {
1541
- this.sendFrame(
1542
- _Sender.frame(data, {
1543
- fin: true,
1544
- rsv1: false,
1545
- opcode: 10,
1546
- mask,
1547
- readOnly
1548
- }),
1549
- cb
1550
- );
1551
- }
1552
- /**
1553
- * Sends a data message to the other peer.
1554
- *
1555
- * @param {*} data The message to send
1556
- * @param {Object} options Options object
1557
- * @param {Boolean} options.compress Specifies whether or not to compress `data`
1558
- * @param {Boolean} options.binary Specifies whether `data` is binary or text
1559
- * @param {Boolean} options.fin Specifies whether the fragment is the last one
1560
- * @param {Boolean} options.mask Specifies whether or not to mask `data`
1561
- * @param {Function} cb Callback
1562
- * @public
1563
- */
1564
- send(data, options, cb) {
1565
- const buf = toBuffer(data);
1566
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1567
- var opcode = options.binary ? 2 : 1;
1568
- var rsv1 = options.compress;
1569
- if (this._firstFragment) {
1570
- this._firstFragment = false;
1571
- if (rsv1 && perMessageDeflate) {
1572
- rsv1 = buf.length >= perMessageDeflate._threshold;
1573
- }
1574
- this._compress = rsv1;
1575
- } else {
1576
- rsv1 = false;
1577
- opcode = 0;
1578
- }
1579
- if (options.fin) this._firstFragment = true;
1580
- if (perMessageDeflate) {
1581
- const opts = {
1582
- fin: options.fin,
1583
- rsv1,
1584
- opcode,
1585
- mask: options.mask,
1586
- readOnly: toBuffer.readOnly
1587
- };
1588
- if (this._deflating) {
1589
- this.enqueue([this.dispatch, buf, this._compress, opts, cb]);
1590
- } else {
1591
- this.dispatch(buf, this._compress, opts, cb);
1592
- }
1593
- } else {
1594
- this.sendFrame(
1595
- _Sender.frame(buf, {
1596
- fin: options.fin,
1597
- rsv1: false,
1598
- opcode,
1599
- mask: options.mask,
1600
- readOnly: toBuffer.readOnly
1601
- }),
1602
- cb
1603
- );
1604
- }
1605
- }
1606
- /**
1607
- * Dispatches a data message.
1608
- *
1609
- * @param {Buffer} data The message to send
1610
- * @param {Boolean} compress Specifies whether or not to compress `data`
1611
- * @param {Object} options Options object
1612
- * @param {Number} options.opcode The opcode
1613
- * @param {Boolean} options.readOnly Specifies whether `data` can be modified
1614
- * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
1615
- * @param {Boolean} options.mask Specifies whether or not to mask `data`
1616
- * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
1617
- * @param {Function} cb Callback
1618
- * @private
1619
- */
1620
- dispatch(data, compress, options, cb) {
1621
- if (!compress) {
1622
- this.sendFrame(_Sender.frame(data, options), cb);
1623
- return;
1624
- }
1625
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1626
- this._deflating = true;
1627
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1628
- this._deflating = false;
1629
- options.readOnly = false;
1630
- this.sendFrame(_Sender.frame(buf, options), cb);
1631
- this.dequeue();
1632
- });
1633
- }
1634
- /**
1635
- * Executes queued send operations.
1636
- *
1637
- * @private
1638
- */
1639
- dequeue() {
1640
- while (!this._deflating && this._queue.length) {
1641
- const params = this._queue.shift();
1642
- this._bufferedBytes -= params[1].length;
1643
- params[0].apply(this, params.slice(1));
1644
- }
1645
- }
1646
- /**
1647
- * Enqueues a send operation.
1648
- *
1649
- * @param {Array} params Send operation parameters.
1650
- * @private
1651
- */
1652
- enqueue(params) {
1653
- this._bufferedBytes += params[1].length;
1654
- this._queue.push(params);
1655
- }
1656
- /**
1657
- * Sends a frame.
1658
- *
1659
- * @param {Buffer[]} list The frame to send
1660
- * @param {Function} cb Callback
1661
- * @private
1662
- */
1663
- sendFrame(list, cb) {
1664
- if (list.length === 2) {
1665
- this._socket.cork();
1666
- this._socket.write(list[0]);
1667
- this._socket.write(list[1], cb);
1668
- this._socket.uncork();
1669
- } else {
1670
- this._socket.write(list[0], cb);
1671
- }
1672
- }
1673
- };
1674
- module.exports = Sender;
1675
- }
1676
- });
1677
-
1678
- // ../../node_modules/ws/lib/websocket.js
1679
- var require_websocket = __commonJS({
1680
- "../../node_modules/ws/lib/websocket.js"(exports, module) {
1681
- var EventEmitter = __require("events");
1682
- var crypto2 = __require("crypto");
1683
- var https = __require("https");
1684
- var http = __require("http");
1685
- var net = __require("net");
1686
- var tls = __require("tls");
1687
- var url = __require("url");
1688
- var PerMessageDeflate = require_permessage_deflate();
1689
- var EventTarget = require_event_target();
1690
- var extension = require_extension();
1691
- var Receiver = require_receiver();
1692
- var Sender = require_sender();
1693
- var {
1694
- BINARY_TYPES,
1695
- EMPTY_BUFFER,
1696
- GUID,
1697
- kStatusCode,
1698
- kWebSocket,
1699
- NOOP
1700
- } = require_constants();
1701
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
1702
- var protocolVersions = [8, 13];
1703
- var closeTimeout = 30 * 1e3;
1704
- var WebSocket2 = class _WebSocket extends EventEmitter {
1705
- /**
1706
- * Create a new `WebSocket`.
1707
- *
1708
- * @param {(String|url.Url|url.URL)} address The URL to which to connect
1709
- * @param {(String|String[])} protocols The subprotocols
1710
- * @param {Object} options Connection options
1711
- */
1712
- constructor(address, protocols, options) {
1713
- super();
1714
- this.readyState = _WebSocket.CONNECTING;
1715
- this.protocol = "";
1716
- this._binaryType = BINARY_TYPES[0];
1717
- this._closeFrameReceived = false;
1718
- this._closeFrameSent = false;
1719
- this._closeMessage = "";
1720
- this._closeTimer = null;
1721
- this._closeCode = 1006;
1722
- this._extensions = {};
1723
- this._receiver = null;
1724
- this._sender = null;
1725
- this._socket = null;
1726
- if (address !== null) {
1727
- this._isServer = false;
1728
- this._redirects = 0;
1729
- if (Array.isArray(protocols)) {
1730
- protocols = protocols.join(", ");
1731
- } else if (typeof protocols === "object" && protocols !== null) {
1732
- options = protocols;
1733
- protocols = void 0;
1734
- }
1735
- initAsClient(this, address, protocols, options);
1736
- } else {
1737
- this._isServer = true;
1738
- }
1739
- }
1740
- get CONNECTING() {
1741
- return _WebSocket.CONNECTING;
1742
- }
1743
- get CLOSING() {
1744
- return _WebSocket.CLOSING;
1745
- }
1746
- get CLOSED() {
1747
- return _WebSocket.CLOSED;
1748
- }
1749
- get OPEN() {
1750
- return _WebSocket.OPEN;
1751
- }
1752
- /**
1753
- * This deviates from the WHATWG interface since ws doesn't support the
1754
- * required default "blob" type (instead we define a custom "nodebuffer"
1755
- * type).
1756
- *
1757
- * @type {String}
1758
- */
1759
- get binaryType() {
1760
- return this._binaryType;
1761
- }
1762
- set binaryType(type) {
1763
- if (!BINARY_TYPES.includes(type)) return;
1764
- this._binaryType = type;
1765
- if (this._receiver) this._receiver._binaryType = type;
1766
- }
1767
- /**
1768
- * @type {Number}
1769
- */
1770
- get bufferedAmount() {
1771
- if (!this._socket) return 0;
1772
- return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;
1773
- }
1774
- /**
1775
- * @type {String}
1776
- */
1777
- get extensions() {
1778
- return Object.keys(this._extensions).join();
1779
- }
1780
- /**
1781
- * Set up the socket and the internal resources.
1782
- *
1783
- * @param {net.Socket} socket The network socket between the server and client
1784
- * @param {Buffer} head The first packet of the upgraded stream
1785
- * @param {Number} maxPayload The maximum allowed message size
1786
- * @private
1787
- */
1788
- setSocket(socket, head, maxPayload) {
1789
- const receiver = new Receiver(
1790
- this._binaryType,
1791
- this._extensions,
1792
- maxPayload
1793
- );
1794
- this._sender = new Sender(socket, this._extensions);
1795
- this._receiver = receiver;
1796
- this._socket = socket;
1797
- receiver[kWebSocket] = this;
1798
- socket[kWebSocket] = this;
1799
- receiver.on("conclude", receiverOnConclude);
1800
- receiver.on("drain", receiverOnDrain);
1801
- receiver.on("error", receiverOnError);
1802
- receiver.on("message", receiverOnMessage);
1803
- receiver.on("ping", receiverOnPing);
1804
- receiver.on("pong", receiverOnPong);
1805
- socket.setTimeout(0);
1806
- socket.setNoDelay();
1807
- if (head.length > 0) socket.unshift(head);
1808
- socket.on("close", socketOnClose);
1809
- socket.on("data", socketOnData);
1810
- socket.on("end", socketOnEnd);
1811
- socket.on("error", socketOnError);
1812
- this.readyState = _WebSocket.OPEN;
1813
- this.emit("open");
1814
- }
1815
- /**
1816
- * Emit the `'close'` event.
1817
- *
1818
- * @private
1819
- */
1820
- emitClose() {
1821
- this.readyState = _WebSocket.CLOSED;
1822
- if (!this._socket) {
1823
- this.emit("close", this._closeCode, this._closeMessage);
1824
- return;
1825
- }
1826
- if (this._extensions[PerMessageDeflate.extensionName]) {
1827
- this._extensions[PerMessageDeflate.extensionName].cleanup();
1828
- }
1829
- this._receiver.removeAllListeners();
1830
- this.emit("close", this._closeCode, this._closeMessage);
1831
- }
1832
- /**
1833
- * Start a closing handshake.
1834
- *
1835
- * +----------+ +-----------+ +----------+
1836
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
1837
- * | +----------+ +-----------+ +----------+ |
1838
- * +----------+ +-----------+ |
1839
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
1840
- * +----------+ +-----------+ |
1841
- * | | | +---+ |
1842
- * +------------------------+-->|fin| - - - -
1843
- * | +---+ | +---+
1844
- * - - - - -|fin|<---------------------+
1845
- * +---+
1846
- *
1847
- * @param {Number} code Status code explaining why the connection is closing
1848
- * @param {String} data A string explaining why the connection is closing
1849
- * @public
1850
- */
1851
- close(code, data) {
1852
- if (this.readyState === _WebSocket.CLOSED) return;
1853
- if (this.readyState === _WebSocket.CONNECTING) {
1854
- const msg = "WebSocket was closed before the connection was established";
1855
- return abortHandshake(this, this._req, msg);
1856
- }
1857
- if (this.readyState === _WebSocket.CLOSING) {
1858
- if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();
1859
- return;
1860
- }
1861
- this.readyState = _WebSocket.CLOSING;
1862
- this._sender.close(code, data, !this._isServer, (err) => {
1863
- if (err) return;
1864
- this._closeFrameSent = true;
1865
- if (this._closeFrameReceived) this._socket.end();
1866
- });
1867
- this._closeTimer = setTimeout(
1868
- this._socket.destroy.bind(this._socket),
1869
- closeTimeout
1870
- );
1871
- }
1872
- /**
1873
- * Send a ping.
1874
- *
1875
- * @param {*} data The data to send
1876
- * @param {Boolean} mask Indicates whether or not to mask `data`
1877
- * @param {Function} cb Callback which is executed when the ping is sent
1878
- * @public
1879
- */
1880
- ping(data, mask, cb) {
1881
- if (typeof data === "function") {
1882
- cb = data;
1883
- data = mask = void 0;
1884
- } else if (typeof mask === "function") {
1885
- cb = mask;
1886
- mask = void 0;
1887
- }
1888
- if (this.readyState !== _WebSocket.OPEN) {
1889
- const err = new Error(
1890
- `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1891
- );
1892
- if (cb) return cb(err);
1893
- throw err;
1894
- }
1895
- if (typeof data === "number") data = data.toString();
1896
- if (mask === void 0) mask = !this._isServer;
1897
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
1898
- }
1899
- /**
1900
- * Send a pong.
1901
- *
1902
- * @param {*} data The data to send
1903
- * @param {Boolean} mask Indicates whether or not to mask `data`
1904
- * @param {Function} cb Callback which is executed when the pong is sent
1905
- * @public
1906
- */
1907
- pong(data, mask, cb) {
1908
- if (typeof data === "function") {
1909
- cb = data;
1910
- data = mask = void 0;
1911
- } else if (typeof mask === "function") {
1912
- cb = mask;
1913
- mask = void 0;
1914
- }
1915
- if (this.readyState !== _WebSocket.OPEN) {
1916
- const err = new Error(
1917
- `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1918
- );
1919
- if (cb) return cb(err);
1920
- throw err;
1921
- }
1922
- if (typeof data === "number") data = data.toString();
1923
- if (mask === void 0) mask = !this._isServer;
1924
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
1925
- }
1926
- /**
1927
- * Send a data message.
1928
- *
1929
- * @param {*} data The message to send
1930
- * @param {Object} options Options object
1931
- * @param {Boolean} options.compress Specifies whether or not to compress `data`
1932
- * @param {Boolean} options.binary Specifies whether `data` is binary or text
1933
- * @param {Boolean} options.fin Specifies whether the fragment is the last one
1934
- * @param {Boolean} options.mask Specifies whether or not to mask `data`
1935
- * @param {Function} cb Callback which is executed when data is written out
1936
- * @public
1937
- */
1938
- send(data, options, cb) {
1939
- if (typeof options === "function") {
1940
- cb = options;
1941
- options = {};
1942
- }
1943
- if (this.readyState !== _WebSocket.OPEN) {
1944
- const err = new Error(
1945
- `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1946
- );
1947
- if (cb) return cb(err);
1948
- throw err;
1949
- }
1950
- if (typeof data === "number") data = data.toString();
1951
- const opts = Object.assign(
1952
- {
1953
- binary: typeof data !== "string",
1954
- mask: !this._isServer,
1955
- compress: true,
1956
- fin: true
1957
- },
1958
- options
1959
- );
1960
- if (!this._extensions[PerMessageDeflate.extensionName]) {
1961
- opts.compress = false;
1962
- }
1963
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
1964
- }
1965
- /**
1966
- * Forcibly close the connection.
1967
- *
1968
- * @public
1969
- */
1970
- terminate() {
1971
- if (this.readyState === _WebSocket.CLOSED) return;
1972
- if (this.readyState === _WebSocket.CONNECTING) {
1973
- const msg = "WebSocket was closed before the connection was established";
1974
- return abortHandshake(this, this._req, msg);
1975
- }
1976
- if (this._socket) {
1977
- this.readyState = _WebSocket.CLOSING;
1978
- this._socket.destroy();
1979
- }
1980
- }
1981
- };
1982
- readyStates.forEach((readyState, i) => {
1983
- WebSocket2[readyState] = i;
1984
- });
1985
- ["open", "error", "close", "message"].forEach((method) => {
1986
- Object.defineProperty(WebSocket2.prototype, `on${method}`, {
1987
- /**
1988
- * Return the listener of the event.
1989
- *
1990
- * @return {(Function|undefined)} The event listener or `undefined`
1991
- * @public
1992
- */
1993
- get() {
1994
- const listeners = this.listeners(method);
1995
- for (var i = 0; i < listeners.length; i++) {
1996
- if (listeners[i]._listener) return listeners[i]._listener;
1997
- }
1998
- return void 0;
1999
- },
2000
- /**
2001
- * Add a listener for the event.
2002
- *
2003
- * @param {Function} listener The listener to add
2004
- * @public
2005
- */
2006
- set(listener) {
2007
- const listeners = this.listeners(method);
2008
- for (var i = 0; i < listeners.length; i++) {
2009
- if (listeners[i]._listener) this.removeListener(method, listeners[i]);
2010
- }
2011
- this.addEventListener(method, listener);
2012
- }
2013
- });
2014
- });
2015
- WebSocket2.prototype.addEventListener = EventTarget.addEventListener;
2016
- WebSocket2.prototype.removeEventListener = EventTarget.removeEventListener;
2017
- module.exports = WebSocket2;
2018
- function initAsClient(websocket, address, protocols, options) {
2019
- const opts = Object.assign(
2020
- {
2021
- protocolVersion: protocolVersions[1],
2022
- maxPayload: 100 * 1024 * 1024,
2023
- perMessageDeflate: true,
2024
- followRedirects: false,
2025
- maxRedirects: 10
2026
- },
2027
- options,
2028
- {
2029
- createConnection: void 0,
2030
- socketPath: void 0,
2031
- hostname: void 0,
2032
- protocol: void 0,
2033
- timeout: void 0,
2034
- method: void 0,
2035
- auth: void 0,
2036
- host: void 0,
2037
- path: void 0,
2038
- port: void 0
2039
- }
2040
- );
2041
- if (!protocolVersions.includes(opts.protocolVersion)) {
2042
- throw new RangeError(
2043
- `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2044
- );
2045
- }
2046
- var parsedUrl;
2047
- if (typeof address === "object" && address.href !== void 0) {
2048
- parsedUrl = address;
2049
- websocket.url = address.href;
2050
- } else {
2051
- parsedUrl = url.URL ? new url.URL(address) : url.parse(address);
2052
- websocket.url = address;
2053
- }
2054
- const isUnixSocket = parsedUrl.protocol === "ws+unix:";
2055
- if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
2056
- throw new Error(`Invalid URL: ${websocket.url}`);
2057
- }
2058
- const isSecure = parsedUrl.protocol === "wss:" || parsedUrl.protocol === "https:";
2059
- const defaultPort = isSecure ? 443 : 80;
2060
- const key = crypto2.randomBytes(16).toString("base64");
2061
- const get = isSecure ? https.get : http.get;
2062
- const path = parsedUrl.search ? `${parsedUrl.pathname || "/"}${parsedUrl.search}` : parsedUrl.pathname || "/";
2063
- var perMessageDeflate;
2064
- opts.createConnection = isSecure ? tlsConnect : netConnect;
2065
- opts.defaultPort = opts.defaultPort || defaultPort;
2066
- opts.port = parsedUrl.port || defaultPort;
2067
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2068
- opts.headers = Object.assign(
2069
- {
2070
- "Sec-WebSocket-Version": opts.protocolVersion,
2071
- "Sec-WebSocket-Key": key,
2072
- Connection: "Upgrade",
2073
- Upgrade: "websocket"
2074
- },
2075
- opts.headers
2076
- );
2077
- opts.path = path;
2078
- opts.timeout = opts.handshakeTimeout;
2079
- if (opts.perMessageDeflate) {
2080
- perMessageDeflate = new PerMessageDeflate(
2081
- opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2082
- false,
2083
- opts.maxPayload
2084
- );
2085
- opts.headers["Sec-WebSocket-Extensions"] = extension.format({
2086
- [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2087
- });
2088
- }
2089
- if (protocols) {
2090
- opts.headers["Sec-WebSocket-Protocol"] = protocols;
2091
- }
2092
- if (opts.origin) {
2093
- if (opts.protocolVersion < 13) {
2094
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2095
- } else {
2096
- opts.headers.Origin = opts.origin;
2097
- }
2098
- }
2099
- if (parsedUrl.auth) {
2100
- opts.auth = parsedUrl.auth;
2101
- } else if (parsedUrl.username || parsedUrl.password) {
2102
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2103
- }
2104
- if (isUnixSocket) {
2105
- const parts = path.split(":");
2106
- opts.socketPath = parts[0];
2107
- opts.path = parts[1];
2108
- }
2109
- var req = websocket._req = get(opts);
2110
- if (opts.timeout) {
2111
- req.on("timeout", () => {
2112
- abortHandshake(websocket, req, "Opening handshake has timed out");
2113
- });
2114
- }
2115
- req.on("error", (err) => {
2116
- if (websocket._req.aborted) return;
2117
- req = websocket._req = null;
2118
- websocket.readyState = WebSocket2.CLOSING;
2119
- websocket.emit("error", err);
2120
- websocket.emitClose();
2121
- });
2122
- req.on("response", (res) => {
2123
- const location = res.headers.location;
2124
- const statusCode = res.statusCode;
2125
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2126
- if (++websocket._redirects > opts.maxRedirects) {
2127
- abortHandshake(websocket, req, "Maximum redirects exceeded");
2128
- return;
2129
- }
2130
- req.abort();
2131
- const addr = url.URL ? new url.URL(location, address) : url.resolve(address, location);
2132
- initAsClient(websocket, addr, protocols, options);
2133
- } else if (!websocket.emit("unexpected-response", req, res)) {
2134
- abortHandshake(
2135
- websocket,
2136
- req,
2137
- `Unexpected server response: ${res.statusCode}`
2138
- );
2139
- }
2140
- });
2141
- req.on("upgrade", (res, socket, head) => {
2142
- websocket.emit("upgrade", res);
2143
- if (websocket.readyState !== WebSocket2.CONNECTING) return;
2144
- req = websocket._req = null;
2145
- const digest = crypto2.createHash("sha1").update(key + GUID).digest("base64");
2146
- if (res.headers["sec-websocket-accept"] !== digest) {
2147
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2148
- return;
2149
- }
2150
- const serverProt = res.headers["sec-websocket-protocol"];
2151
- const protList = (protocols || "").split(/, */);
2152
- var protError;
2153
- if (!protocols && serverProt) {
2154
- protError = "Server sent a subprotocol but none was requested";
2155
- } else if (protocols && !serverProt) {
2156
- protError = "Server sent no subprotocol";
2157
- } else if (serverProt && !protList.includes(serverProt)) {
2158
- protError = "Server sent an invalid subprotocol";
2159
- }
2160
- if (protError) {
2161
- abortHandshake(websocket, socket, protError);
2162
- return;
2163
- }
2164
- if (serverProt) websocket.protocol = serverProt;
2165
- if (perMessageDeflate) {
2166
- try {
2167
- const extensions = extension.parse(
2168
- res.headers["sec-websocket-extensions"]
2169
- );
2170
- if (extensions[PerMessageDeflate.extensionName]) {
2171
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2172
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2173
- }
2174
- } catch (err) {
2175
- abortHandshake(
2176
- websocket,
2177
- socket,
2178
- "Invalid Sec-WebSocket-Extensions header"
2179
- );
2180
- return;
2181
- }
2182
- }
2183
- websocket.setSocket(socket, head, opts.maxPayload);
2184
- });
2185
- }
2186
- function netConnect(options) {
2187
- if (options.protocolVersion) options.path = options.socketPath;
2188
- return net.connect(options);
2189
- }
2190
- function tlsConnect(options) {
2191
- options.path = void 0;
2192
- options.servername = options.servername || options.host;
2193
- return tls.connect(options);
2194
- }
2195
- function abortHandshake(websocket, stream, message) {
2196
- websocket.readyState = WebSocket2.CLOSING;
2197
- const err = new Error(message);
2198
- Error.captureStackTrace(err, abortHandshake);
2199
- if (stream.setHeader) {
2200
- stream.abort();
2201
- stream.once("abort", websocket.emitClose.bind(websocket));
2202
- websocket.emit("error", err);
2203
- } else {
2204
- stream.destroy(err);
2205
- stream.once("error", websocket.emit.bind(websocket, "error"));
2206
- stream.once("close", websocket.emitClose.bind(websocket));
2207
- }
2208
- }
2209
- function receiverOnConclude(code, reason) {
2210
- const websocket = this[kWebSocket];
2211
- websocket._socket.removeListener("data", socketOnData);
2212
- websocket._socket.resume();
2213
- websocket._closeFrameReceived = true;
2214
- websocket._closeMessage = reason;
2215
- websocket._closeCode = code;
2216
- if (code === 1005) websocket.close();
2217
- else websocket.close(code, reason);
2218
- }
2219
- function receiverOnDrain() {
2220
- this[kWebSocket]._socket.resume();
2221
- }
2222
- function receiverOnError(err) {
2223
- const websocket = this[kWebSocket];
2224
- websocket._socket.removeListener("data", socketOnData);
2225
- websocket.readyState = WebSocket2.CLOSING;
2226
- websocket._closeCode = err[kStatusCode];
2227
- websocket.emit("error", err);
2228
- websocket._socket.destroy();
2229
- }
2230
- function receiverOnFinish() {
2231
- this[kWebSocket].emitClose();
2232
- }
2233
- function receiverOnMessage(data) {
2234
- this[kWebSocket].emit("message", data);
2235
- }
2236
- function receiverOnPing(data) {
2237
- const websocket = this[kWebSocket];
2238
- websocket.pong(data, !websocket._isServer, NOOP);
2239
- websocket.emit("ping", data);
2240
- }
2241
- function receiverOnPong(data) {
2242
- this[kWebSocket].emit("pong", data);
2243
- }
2244
- function socketOnClose() {
2245
- const websocket = this[kWebSocket];
2246
- this.removeListener("close", socketOnClose);
2247
- this.removeListener("end", socketOnEnd);
2248
- websocket.readyState = WebSocket2.CLOSING;
2249
- websocket._socket.read();
2250
- websocket._receiver.end();
2251
- this.removeListener("data", socketOnData);
2252
- this[kWebSocket] = void 0;
2253
- clearTimeout(websocket._closeTimer);
2254
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
2255
- websocket.emitClose();
2256
- } else {
2257
- websocket._receiver.on("error", receiverOnFinish);
2258
- websocket._receiver.on("finish", receiverOnFinish);
2259
- }
2260
- }
2261
- function socketOnData(chunk) {
2262
- if (!this[kWebSocket]._receiver.write(chunk)) {
2263
- this.pause();
2264
- }
2265
- }
2266
- function socketOnEnd() {
2267
- const websocket = this[kWebSocket];
2268
- websocket.readyState = WebSocket2.CLOSING;
2269
- websocket._receiver.end();
2270
- this.end();
2271
- }
2272
- function socketOnError() {
2273
- const websocket = this[kWebSocket];
2274
- this.removeListener("error", socketOnError);
2275
- this.on("error", NOOP);
2276
- websocket.readyState = WebSocket2.CLOSING;
2277
- this.destroy();
2278
- }
2279
- }
2280
- });
2281
-
2282
- // ../../node_modules/ws/lib/websocket-server.js
2283
- var require_websocket_server = __commonJS({
2284
- "../../node_modules/ws/lib/websocket-server.js"(exports, module) {
2285
- var EventEmitter = __require("events");
2286
- var crypto2 = __require("crypto");
2287
- var http = __require("http");
2288
- var PerMessageDeflate = require_permessage_deflate();
2289
- var extension = require_extension();
2290
- var WebSocket2 = require_websocket();
2291
- var { GUID } = require_constants();
2292
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
2293
- var WebSocketServer = class extends EventEmitter {
2294
- /**
2295
- * Create a `WebSocketServer` instance.
2296
- *
2297
- * @param {Object} options Configuration options
2298
- * @param {Number} options.backlog The maximum length of the queue of pending
2299
- * connections
2300
- * @param {Boolean} options.clientTracking Specifies whether or not to track
2301
- * clients
2302
- * @param {Function} options.handleProtocols An hook to handle protocols
2303
- * @param {String} options.host The hostname where to bind the server
2304
- * @param {Number} options.maxPayload The maximum allowed message size
2305
- * @param {Boolean} options.noServer Enable no server mode
2306
- * @param {String} options.path Accept only connections matching this path
2307
- * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable
2308
- * permessage-deflate
2309
- * @param {Number} options.port The port where to bind the server
2310
- * @param {http.Server} options.server A pre-created HTTP/S server to use
2311
- * @param {Function} options.verifyClient An hook to reject connections
2312
- * @param {Function} callback A listener for the `listening` event
2313
- */
2314
- constructor(options, callback) {
2315
- super();
2316
- options = Object.assign(
2317
- {
2318
- maxPayload: 100 * 1024 * 1024,
2319
- perMessageDeflate: false,
2320
- handleProtocols: null,
2321
- clientTracking: true,
2322
- verifyClient: null,
2323
- noServer: false,
2324
- backlog: null,
2325
- // use default (511 as implemented in net.js)
2326
- server: null,
2327
- host: null,
2328
- path: null,
2329
- port: null
2330
- },
2331
- options
2332
- );
2333
- if (options.port == null && !options.server && !options.noServer) {
2334
- throw new TypeError(
2335
- 'One of the "port", "server", or "noServer" options must be specified'
2336
- );
2337
- }
2338
- if (options.port != null) {
2339
- this._server = http.createServer((req, res) => {
2340
- const body = http.STATUS_CODES[426];
2341
- res.writeHead(426, {
2342
- "Content-Length": body.length,
2343
- "Content-Type": "text/plain"
2344
- });
2345
- res.end(body);
2346
- });
2347
- this._server.listen(
2348
- options.port,
2349
- options.host,
2350
- options.backlog,
2351
- callback
2352
- );
2353
- } else if (options.server) {
2354
- this._server = options.server;
2355
- }
2356
- if (this._server) {
2357
- this._removeListeners = addListeners(this._server, {
2358
- listening: this.emit.bind(this, "listening"),
2359
- error: this.emit.bind(this, "error"),
2360
- upgrade: (req, socket, head) => {
2361
- this.handleUpgrade(req, socket, head, (ws) => {
2362
- this.emit("connection", ws, req);
2363
- });
2364
- }
2365
- });
2366
- }
2367
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
2368
- if (options.clientTracking) this.clients = /* @__PURE__ */ new Set();
2369
- this.options = options;
2370
- }
2371
- /**
2372
- * Returns the bound address, the address family name, and port of the server
2373
- * as reported by the operating system if listening on an IP socket.
2374
- * If the server is listening on a pipe or UNIX domain socket, the name is
2375
- * returned as a string.
2376
- *
2377
- * @return {(Object|String|null)} The address of the server
2378
- * @public
2379
- */
2380
- address() {
2381
- if (this.options.noServer) {
2382
- throw new Error('The server is operating in "noServer" mode');
2383
- }
2384
- if (!this._server) return null;
2385
- return this._server.address();
2386
- }
2387
- /**
2388
- * Close the server.
2389
- *
2390
- * @param {Function} cb Callback
2391
- * @public
2392
- */
2393
- close(cb) {
2394
- if (cb) this.once("close", cb);
2395
- if (this.clients) {
2396
- for (const client of this.clients) client.terminate();
2397
- }
2398
- const server = this._server;
2399
- if (server) {
2400
- this._removeListeners();
2401
- this._removeListeners = this._server = null;
2402
- if (this.options.port != null) {
2403
- server.close(() => this.emit("close"));
2404
- return;
2405
- }
2406
- }
2407
- process.nextTick(emitClose, this);
2408
- }
2409
- /**
2410
- * See if a given request should be handled by this server instance.
2411
- *
2412
- * @param {http.IncomingMessage} req Request object to inspect
2413
- * @return {Boolean} `true` if the request is valid, else `false`
2414
- * @public
2415
- */
2416
- shouldHandle(req) {
2417
- if (this.options.path) {
2418
- const index = req.url.indexOf("?");
2419
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
2420
- if (pathname !== this.options.path) return false;
2421
- }
2422
- return true;
2423
- }
2424
- /**
2425
- * Handle a HTTP Upgrade request.
2426
- *
2427
- * @param {http.IncomingMessage} req The request object
2428
- * @param {net.Socket} socket The network socket between the server and client
2429
- * @param {Buffer} head The first packet of the upgraded stream
2430
- * @param {Function} cb Callback
2431
- * @public
2432
- */
2433
- handleUpgrade(req, socket, head, cb) {
2434
- socket.on("error", socketOnError);
2435
- const key = req.headers["sec-websocket-key"] !== void 0 ? req.headers["sec-websocket-key"].trim() : false;
2436
- const upgrade = req.headers.upgrade;
2437
- const version = +req.headers["sec-websocket-version"];
2438
- const extensions = {};
2439
- if (req.method !== "GET" || upgrade === void 0 || upgrade.toLowerCase() !== "websocket" || !key || !keyRegex.test(key) || version !== 8 && version !== 13 || !this.shouldHandle(req)) {
2440
- return abortHandshake(socket, 400);
2441
- }
2442
- if (this.options.perMessageDeflate) {
2443
- const perMessageDeflate = new PerMessageDeflate(
2444
- this.options.perMessageDeflate,
2445
- true,
2446
- this.options.maxPayload
2447
- );
2448
- try {
2449
- const offers = extension.parse(req.headers["sec-websocket-extensions"]);
2450
- if (offers[PerMessageDeflate.extensionName]) {
2451
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
2452
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2453
- }
2454
- } catch (err) {
2455
- return abortHandshake(socket, 400);
2456
- }
2457
- }
2458
- if (this.options.verifyClient) {
2459
- const info = {
2460
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
2461
- secure: !!(req.connection.authorized || req.connection.encrypted),
2462
- req
2463
- };
2464
- if (this.options.verifyClient.length === 2) {
2465
- this.options.verifyClient(info, (verified, code, message, headers) => {
2466
- if (!verified) {
2467
- return abortHandshake(socket, code || 401, message, headers);
2468
- }
2469
- this.completeUpgrade(key, extensions, req, socket, head, cb);
2470
- });
2471
- return;
2472
- }
2473
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
2474
- }
2475
- this.completeUpgrade(key, extensions, req, socket, head, cb);
2476
- }
2477
- /**
2478
- * Upgrade the connection to WebSocket.
2479
- *
2480
- * @param {String} key The value of the `Sec-WebSocket-Key` header
2481
- * @param {Object} extensions The accepted extensions
2482
- * @param {http.IncomingMessage} req The request object
2483
- * @param {net.Socket} socket The network socket between the server and client
2484
- * @param {Buffer} head The first packet of the upgraded stream
2485
- * @param {Function} cb Callback
2486
- * @private
2487
- */
2488
- completeUpgrade(key, extensions, req, socket, head, cb) {
2489
- if (!socket.readable || !socket.writable) return socket.destroy();
2490
- const digest = crypto2.createHash("sha1").update(key + GUID).digest("base64");
2491
- const headers = [
2492
- "HTTP/1.1 101 Switching Protocols",
2493
- "Upgrade: websocket",
2494
- "Connection: Upgrade",
2495
- `Sec-WebSocket-Accept: ${digest}`
2496
- ];
2497
- const ws = new WebSocket2(null);
2498
- var protocol = req.headers["sec-websocket-protocol"];
2499
- if (protocol) {
2500
- protocol = protocol.split(",").map(trim);
2501
- if (this.options.handleProtocols) {
2502
- protocol = this.options.handleProtocols(protocol, req);
2503
- } else {
2504
- protocol = protocol[0];
2505
- }
2506
- if (protocol) {
2507
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
2508
- ws.protocol = protocol;
2509
- }
2510
- }
2511
- if (extensions[PerMessageDeflate.extensionName]) {
2512
- const params = extensions[PerMessageDeflate.extensionName].params;
2513
- const value = extension.format({
2514
- [PerMessageDeflate.extensionName]: [params]
2515
- });
2516
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
2517
- ws._extensions = extensions;
2518
- }
2519
- this.emit("headers", headers, req);
2520
- socket.write(headers.concat("\r\n").join("\r\n"));
2521
- socket.removeListener("error", socketOnError);
2522
- ws.setSocket(socket, head, this.options.maxPayload);
2523
- if (this.clients) {
2524
- this.clients.add(ws);
2525
- ws.on("close", () => this.clients.delete(ws));
2526
- }
2527
- cb(ws);
2528
- }
2529
- };
2530
- module.exports = WebSocketServer;
2531
- function addListeners(server, map) {
2532
- for (const event of Object.keys(map)) server.on(event, map[event]);
2533
- return function removeListeners() {
2534
- for (const event of Object.keys(map)) {
2535
- server.removeListener(event, map[event]);
2536
- }
2537
- };
2538
- }
2539
- function emitClose(server) {
2540
- server.emit("close");
2541
- }
2542
- function socketOnError() {
2543
- this.destroy();
2544
- }
2545
- function abortHandshake(socket, code, message, headers) {
2546
- if (socket.writable) {
2547
- message = message || http.STATUS_CODES[code];
2548
- headers = Object.assign(
2549
- {
2550
- Connection: "close",
2551
- "Content-type": "text/html",
2552
- "Content-Length": Buffer.byteLength(message)
2553
- },
2554
- headers
2555
- );
2556
- socket.write(
2557
- `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
2558
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
2559
- );
2560
- }
2561
- socket.removeListener("error", socketOnError);
2562
- socket.destroy();
2563
- }
2564
- function trim(str) {
2565
- return str.trim();
2566
- }
2567
- }
2568
- });
2569
-
2570
- // ../../node_modules/ws/index.js
2571
- var require_ws = __commonJS({
2572
- "../../node_modules/ws/index.js"(exports, module) {
2573
- var WebSocket2 = require_websocket();
2574
- WebSocket2.Server = require_websocket_server();
2575
- WebSocket2.Receiver = require_receiver();
2576
- WebSocket2.Sender = require_sender();
2577
- module.exports = WebSocket2;
2578
- }
2579
- });
2580
7
 
2581
8
  // ../core/src/platform.ts
2582
9
  function detectPlatform() {
@@ -4574,10 +2001,22 @@ var BlinkAuth = class {
4574
2001
  }
4575
2002
  const { sessionId, authUrl } = await this.initiateMobileOAuth(provider, options);
4576
2003
  console.log("\u{1F510} Opening OAuth browser for", provider);
4577
- webBrowser.openAuthSessionAsync(authUrl).then((result) => {
4578
- console.log("\u{1F510} Browser closed with result:", result.type);
4579
- }).catch(() => {
4580
- });
2004
+ const browserPromise = webBrowser.openAuthSessionAsync(authUrl);
2005
+ const raceResult = await Promise.race([
2006
+ browserPromise.then((result) => ({ closed: true, result })).catch((err) => ({ closed: true, error: err })),
2007
+ new Promise(
2008
+ (resolve) => setTimeout(() => resolve({ closed: false }), 5e3)
2009
+ )
2010
+ ]);
2011
+ if (raceResult.closed) {
2012
+ if ("result" in raceResult) {
2013
+ console.log("\u{1F510} Browser closed with result:", raceResult.result.type);
2014
+ } else {
2015
+ console.log("\u{1F510} Browser closed with error");
2016
+ }
2017
+ } else {
2018
+ console.log("\u{1F510} Browser still open (new tab/stuck popup), starting to poll...");
2019
+ }
4581
2020
  const user = await this.pollMobileOAuthSession(sessionId, {
4582
2021
  maxAttempts: 120,
4583
2022
  // 60 seconds (give user time to complete auth)
@@ -7786,172 +5225,45 @@ var BlinkDataImpl = class {
7786
5225
  }
7787
5226
  };
7788
5227
 
7789
- // src/realtime.ts
5228
+ // src/realtime-connection.ts
7790
5229
  var getWebSocketClass = () => {
7791
5230
  if (typeof WebSocket !== "undefined") {
7792
5231
  return WebSocket;
7793
5232
  }
7794
5233
  try {
7795
- const WS = require_ws();
5234
+ const WS = __require("ws");
7796
5235
  return WS;
7797
5236
  } catch (error) {
7798
5237
  throw new BlinkRealtimeError('WebSocket is not available. Install "ws" package for Node.js environments.');
7799
5238
  }
7800
5239
  };
7801
- var BlinkRealtimeChannel = class {
7802
- constructor(channelName, httpClient, projectId) {
7803
- this.channelName = channelName;
5240
+ var RealtimeConnection = class {
5241
+ constructor(httpClient, projectId) {
7804
5242
  this.httpClient = httpClient;
7805
5243
  this.projectId = projectId;
7806
5244
  }
7807
- messageCallbacks = [];
7808
- presenceCallbacks = [];
7809
5245
  websocket = null;
7810
- isSubscribed = false;
7811
5246
  isConnected = false;
7812
5247
  isConnecting = false;
7813
5248
  reconnectTimer = null;
7814
5249
  heartbeatTimer = null;
7815
5250
  reconnectAttempts = 0;
7816
- // Message queuing for when socket is not ready
7817
- messageQueue = [];
7818
- pendingSubscription = null;
7819
- // Connection promise for awaiting readiness
7820
5251
  connectionPromise = null;
5252
+ // Channel management
5253
+ channels = /* @__PURE__ */ new Map();
5254
+ pendingSubscriptions = /* @__PURE__ */ new Map();
5255
+ // Message queue for when socket not ready
5256
+ messageQueue = [];
7821
5257
  /**
7822
- * Check if channel is ready for publishing
5258
+ * Check if connection is ready
7823
5259
  */
7824
5260
  isReady() {
7825
- return this.isConnected && this.isSubscribed;
7826
- }
7827
- async subscribe(options = {}) {
7828
- if (this.isSubscribed) {
7829
- return;
7830
- }
7831
- await this.ensureConnected();
7832
- return new Promise((resolve, reject) => {
7833
- if (this.pendingSubscription) {
7834
- clearTimeout(this.pendingSubscription.timeout);
7835
- this.pendingSubscription.reject(new BlinkRealtimeError("Subscription cancelled by new subscription request"));
7836
- }
7837
- const timeout = setTimeout(() => {
7838
- this.pendingSubscription = null;
7839
- reject(new BlinkRealtimeError("Subscription timeout - no acknowledgment from server"));
7840
- }, 1e4);
7841
- this.pendingSubscription = {
7842
- options,
7843
- resolve: () => {
7844
- clearTimeout(timeout);
7845
- this.pendingSubscription = null;
7846
- this.isSubscribed = true;
7847
- this.startHeartbeat();
7848
- resolve();
7849
- },
7850
- reject: (error) => {
7851
- clearTimeout(timeout);
7852
- this.pendingSubscription = null;
7853
- reject(error);
7854
- },
7855
- timeout
7856
- };
7857
- const subscribeMessage = {
7858
- type: "subscribe",
7859
- payload: {
7860
- channel: this.channelName,
7861
- userId: options.userId,
7862
- metadata: options.metadata
7863
- }
7864
- };
7865
- this.sendMessage(JSON.stringify(subscribeMessage)).catch((error) => {
7866
- if (this.pendingSubscription) {
7867
- this.pendingSubscription.reject(error);
7868
- }
7869
- });
7870
- });
7871
- }
7872
- async unsubscribe() {
7873
- if (!this.isSubscribed) {
7874
- return;
7875
- }
7876
- if (this.pendingSubscription) {
7877
- clearTimeout(this.pendingSubscription.timeout);
7878
- this.pendingSubscription.reject(new BlinkRealtimeError("Subscription cancelled by unsubscribe"));
7879
- this.pendingSubscription = null;
7880
- }
7881
- if (this.websocket && this.websocket.readyState === 1) {
7882
- const unsubscribeMessage = {
7883
- type: "unsubscribe",
7884
- payload: {
7885
- channel: this.channelName
7886
- }
7887
- };
7888
- this.websocket.send(JSON.stringify(unsubscribeMessage));
7889
- }
7890
- this.cleanup();
7891
- }
7892
- async publish(type, data, options = {}) {
7893
- await this.ensureConnected();
7894
- const publishMessage = {
7895
- type: "publish",
7896
- payload: {
7897
- channel: this.channelName,
7898
- type,
7899
- data,
7900
- userId: options.userId,
7901
- metadata: options.metadata
7902
- }
7903
- };
7904
- return this.sendMessage(JSON.stringify(publishMessage));
7905
- }
7906
- onMessage(callback) {
7907
- this.messageCallbacks.push(callback);
7908
- return () => {
7909
- const index = this.messageCallbacks.indexOf(callback);
7910
- if (index > -1) {
7911
- this.messageCallbacks.splice(index, 1);
7912
- }
7913
- };
7914
- }
7915
- onPresence(callback) {
7916
- this.presenceCallbacks.push(callback);
7917
- return () => {
7918
- const index = this.presenceCallbacks.indexOf(callback);
7919
- if (index > -1) {
7920
- this.presenceCallbacks.splice(index, 1);
7921
- }
7922
- };
7923
- }
7924
- async getPresence() {
7925
- try {
7926
- const response = await this.httpClient.realtimeGetPresence(this.projectId, this.channelName);
7927
- return response.data.users || [];
7928
- } catch (error) {
7929
- throw new BlinkRealtimeError(
7930
- `Failed to get presence for channel ${this.channelName}: ${error instanceof Error ? error.message : "Unknown error"}`
7931
- );
7932
- }
7933
- }
7934
- async getMessages(options = {}) {
7935
- try {
7936
- const response = await this.httpClient.realtimeGetMessages(this.projectId, {
7937
- channel: this.channelName,
7938
- limit: options.limit,
7939
- start: options.after || "-",
7940
- // after = start from this ID onwards, default to oldest
7941
- end: options.before || "+"
7942
- // before = end at this ID, default to newest
7943
- });
7944
- return response.data.messages || [];
7945
- } catch (error) {
7946
- throw new BlinkRealtimeError(
7947
- `Failed to get messages for channel ${this.channelName}: ${error instanceof Error ? error.message : "Unknown error"}`
7948
- );
7949
- }
5261
+ return this.isConnected && this.websocket?.readyState === 1;
7950
5262
  }
7951
5263
  /**
7952
- * Ensure WebSocket connection is established and ready
5264
+ * Ensure WebSocket connection is established
7953
5265
  */
7954
- async ensureConnected() {
5266
+ async connect() {
7955
5267
  if (this.isConnected && this.websocket?.readyState === 1) {
7956
5268
  return;
7957
5269
  }
@@ -7966,100 +5278,111 @@ var BlinkRealtimeChannel = class {
7966
5278
  }
7967
5279
  }
7968
5280
  /**
7969
- * Send a message, queuing if socket not ready
5281
+ * Join a channel (subscribe)
7970
5282
  */
7971
- sendMessage(message) {
7972
- return new Promise((resolve, reject) => {
7973
- let messageObj;
7974
- try {
7975
- messageObj = JSON.parse(message);
7976
- } catch (error) {
7977
- reject(new BlinkRealtimeError("Invalid message format"));
7978
- return;
7979
- }
5283
+ async joinChannel(channelName, handler, options = {}) {
5284
+ await this.connect();
5285
+ this.channels.set(channelName, { handler, options });
5286
+ return new Promise((resolve, reject) => {
7980
5287
  const timeout = setTimeout(() => {
7981
- const index = this.messageQueue.findIndex((q) => q.resolve === resolve);
7982
- if (index > -1) {
7983
- this.messageQueue.splice(index, 1);
7984
- }
7985
- reject(new BlinkRealtimeError("Message send timeout - no response from server"));
5288
+ this.pendingSubscriptions.delete(channelName);
5289
+ this.channels.delete(channelName);
5290
+ reject(new BlinkRealtimeError("Subscription timeout - no acknowledgment from server"));
7986
5291
  }, 1e4);
7987
- const queuedMessage = {
7988
- message,
7989
- resolve,
7990
- reject,
7991
- timeout
7992
- };
7993
- if (this.websocket && this.websocket.readyState === 1) {
7994
- if (messageObj.type === "publish") {
7995
- this.sendQueuedMessage(queuedMessage);
7996
- } else {
7997
- this.websocket.send(message);
7998
- clearTimeout(timeout);
7999
- resolve("sent");
5292
+ this.pendingSubscriptions.set(channelName, { resolve, reject, timeout });
5293
+ const subscribeMessage = {
5294
+ type: "subscribe",
5295
+ payload: {
5296
+ channel: channelName,
5297
+ userId: options.userId,
5298
+ metadata: options.metadata
8000
5299
  }
8001
- } else {
8002
- this.messageQueue.push(queuedMessage);
5300
+ };
5301
+ try {
5302
+ this.sendRaw(JSON.stringify(subscribeMessage));
5303
+ } catch (error) {
5304
+ clearTimeout(timeout);
5305
+ this.pendingSubscriptions.delete(channelName);
5306
+ this.channels.delete(channelName);
5307
+ reject(error);
8003
5308
  }
8004
5309
  });
8005
5310
  }
8006
5311
  /**
8007
- * Send a queued message and set up response handling
5312
+ * Leave a channel (unsubscribe)
8008
5313
  */
8009
- sendQueuedMessage(queuedMessage) {
8010
- const { message, resolve, reject, timeout } = queuedMessage;
8011
- const handleResponse = (event) => {
8012
- try {
8013
- const response = JSON.parse(event.data);
8014
- if (response.type === "published" && response.payload.channel === this.channelName) {
8015
- clearTimeout(timeout);
8016
- this.websocket.removeEventListener("message", handleResponse);
8017
- resolve(response.payload.messageId);
8018
- } else if (response.type === "error") {
8019
- clearTimeout(timeout);
8020
- this.websocket.removeEventListener("message", handleResponse);
8021
- reject(new BlinkRealtimeError(`Server error: ${response.payload.error}`));
8022
- }
8023
- } catch (err) {
5314
+ async leaveChannel(channelName) {
5315
+ this.channels.delete(channelName);
5316
+ const pending = this.pendingSubscriptions.get(channelName);
5317
+ if (pending) {
5318
+ clearTimeout(pending.timeout);
5319
+ pending.reject(new BlinkRealtimeError("Subscription cancelled"));
5320
+ this.pendingSubscriptions.delete(channelName);
5321
+ }
5322
+ if (this.websocket && this.websocket.readyState === 1) {
5323
+ const unsubscribeMessage = {
5324
+ type: "unsubscribe",
5325
+ payload: { channel: channelName }
5326
+ };
5327
+ this.websocket.send(JSON.stringify(unsubscribeMessage));
5328
+ }
5329
+ if (this.channels.size === 0) {
5330
+ this.disconnect();
5331
+ }
5332
+ }
5333
+ /**
5334
+ * Send a message to a channel
5335
+ */
5336
+ async send(channelName, type, data, options = {}) {
5337
+ await this.connect();
5338
+ const publishMessage = {
5339
+ type: "publish",
5340
+ payload: {
5341
+ channel: channelName,
5342
+ type,
5343
+ data,
5344
+ userId: options.userId,
5345
+ metadata: options.metadata
8024
5346
  }
8025
5347
  };
8026
- const originalTimeout = timeout;
8027
- const cleanupTimeout = setTimeout(() => {
8028
- if (this.websocket) {
8029
- this.websocket.removeEventListener("message", handleResponse);
8030
- }
8031
- reject(new BlinkRealtimeError("Message send timeout - no response from server"));
8032
- }, 1e4);
8033
- queuedMessage.timeout = cleanupTimeout;
8034
- clearTimeout(originalTimeout);
8035
- this.websocket.addEventListener("message", handleResponse);
8036
- this.websocket.send(message);
5348
+ return this.sendWithResponse(JSON.stringify(publishMessage), channelName);
8037
5349
  }
8038
5350
  /**
8039
- * Flush all queued messages when connection becomes ready
5351
+ * Disconnect and cleanup
8040
5352
  */
8041
- flushMessageQueue() {
8042
- if (!this.websocket || this.websocket.readyState !== 1) {
8043
- return;
5353
+ disconnect() {
5354
+ this.isConnected = false;
5355
+ this.isConnecting = false;
5356
+ if (this.heartbeatTimer) {
5357
+ clearInterval(this.heartbeatTimer);
5358
+ this.heartbeatTimer = null;
8044
5359
  }
8045
- const queue = [...this.messageQueue];
5360
+ if (this.reconnectTimer) {
5361
+ clearTimeout(this.reconnectTimer);
5362
+ this.reconnectTimer = null;
5363
+ }
5364
+ this.messageQueue.forEach((q) => {
5365
+ clearTimeout(q.timeout);
5366
+ q.reject(new BlinkRealtimeError("Connection closed"));
5367
+ });
8046
5368
  this.messageQueue = [];
8047
- queue.forEach((queuedMessage) => {
8048
- try {
8049
- const messageObj = JSON.parse(queuedMessage.message);
8050
- if (messageObj.type === "publish") {
8051
- this.sendQueuedMessage(queuedMessage);
8052
- } else {
8053
- this.websocket.send(queuedMessage.message);
8054
- clearTimeout(queuedMessage.timeout);
8055
- queuedMessage.resolve("sent");
8056
- }
8057
- } catch (error) {
8058
- clearTimeout(queuedMessage.timeout);
8059
- queuedMessage.reject(new BlinkRealtimeError("Invalid queued message format"));
8060
- }
5369
+ this.pendingSubscriptions.forEach((pending, channel) => {
5370
+ clearTimeout(pending.timeout);
5371
+ pending.reject(new BlinkRealtimeError("Connection closed"));
8061
5372
  });
5373
+ this.pendingSubscriptions.clear();
5374
+ if (this.websocket) {
5375
+ this.websocket.close();
5376
+ this.websocket = null;
5377
+ }
5378
+ }
5379
+ /**
5380
+ * Get count of active channels
5381
+ */
5382
+ getChannelCount() {
5383
+ return this.channels.size;
8062
5384
  }
5385
+ // Private methods
8063
5386
  async connectWebSocket() {
8064
5387
  if (this.websocket && this.websocket.readyState === 1) {
8065
5388
  this.isConnected = true;
@@ -8087,7 +5410,7 @@ var BlinkRealtimeChannel = class {
8087
5410
  const coreUrl = httpClient.coreUrl || "https://core.blink.new";
8088
5411
  const baseUrl = coreUrl.replace("https://", "wss://").replace("http://", "ws://");
8089
5412
  const wsUrl = `${baseUrl}?project_id=${this.projectId}`;
8090
- console.log(`\u{1F517} Attempting WebSocket connection to: ${wsUrl}`);
5413
+ console.log(`\u{1F517} Connecting to realtime: ${wsUrl}`);
8091
5414
  const WSClass = getWebSocketClass();
8092
5415
  this.websocket = new WSClass(wsUrl);
8093
5416
  if (!this.websocket) {
@@ -8100,13 +5423,14 @@ var BlinkRealtimeChannel = class {
8100
5423
  this.isConnecting = false;
8101
5424
  this.isConnected = true;
8102
5425
  this.reconnectAttempts = 0;
5426
+ this.startHeartbeat();
8103
5427
  this.flushMessageQueue();
8104
5428
  resolve();
8105
5429
  };
8106
5430
  this.websocket.onmessage = (event) => {
8107
5431
  try {
8108
5432
  const message = JSON.parse(event.data);
8109
- this.handleWebSocketMessage(message);
5433
+ this.handleMessage(message);
8110
5434
  } catch (error) {
8111
5435
  console.error("Failed to parse WebSocket message:", error);
8112
5436
  }
@@ -8115,19 +5439,11 @@ var BlinkRealtimeChannel = class {
8115
5439
  console.log(`\u{1F50C} Disconnected from realtime for project ${this.projectId}`);
8116
5440
  this.isConnecting = false;
8117
5441
  this.isConnected = false;
8118
- this.isSubscribed = false;
8119
5442
  this.rejectQueuedMessages(new BlinkRealtimeError("WebSocket connection closed"));
8120
- if (this.pendingSubscription) {
8121
- clearTimeout(this.pendingSubscription.timeout);
8122
- this.pendingSubscription.reject(new BlinkRealtimeError("Connection closed during subscription"));
8123
- this.pendingSubscription = null;
8124
- }
8125
5443
  this.scheduleReconnect();
8126
5444
  };
8127
5445
  this.websocket.onerror = (error) => {
8128
5446
  console.error("WebSocket error:", error);
8129
- console.error("WebSocket URL was:", wsUrl);
8130
- console.error("WebSocket readyState:", this.websocket?.readyState);
8131
5447
  this.isConnecting = false;
8132
5448
  this.isConnected = false;
8133
5449
  reject(new BlinkRealtimeError(`WebSocket connection failed to ${wsUrl}`));
@@ -8144,61 +5460,122 @@ var BlinkRealtimeChannel = class {
8144
5460
  }
8145
5461
  });
8146
5462
  }
8147
- /**
8148
- * Reject all queued messages with the given error
8149
- */
8150
- rejectQueuedMessages(error) {
8151
- const queue = [...this.messageQueue];
8152
- this.messageQueue = [];
8153
- queue.forEach((queuedMessage) => {
8154
- clearTimeout(queuedMessage.timeout);
8155
- queuedMessage.reject(error);
8156
- });
8157
- }
8158
- handleWebSocketMessage(message) {
5463
+ handleMessage(message) {
5464
+ const channelName = message.payload?.channel;
8159
5465
  switch (message.type) {
8160
- case "message":
8161
- this.messageCallbacks.forEach((callback) => {
8162
- try {
8163
- callback(message.payload);
8164
- } catch (error) {
8165
- console.error("Error in message callback:", error);
8166
- }
8167
- });
8168
- break;
8169
- case "presence":
8170
- this.presenceCallbacks.forEach((callback) => {
8171
- try {
8172
- const users = message.payload.data?.users || [];
8173
- callback(users);
8174
- } catch (error) {
8175
- console.error("Error in presence callback:", error);
8176
- }
8177
- });
5466
+ case "connected":
5467
+ console.log(`\u2705 WebSocket connected: ${message.payload?.socketId}`);
8178
5468
  break;
8179
5469
  case "subscribed":
8180
- console.log(`\u2705 Subscribed to channel: ${message.payload.channel}`);
8181
- if (this.pendingSubscription && message.payload.channel === this.channelName) {
8182
- this.pendingSubscription.resolve();
5470
+ console.log(`\u2705 Subscribed to channel: ${channelName}`);
5471
+ const pendingSub = this.pendingSubscriptions.get(channelName);
5472
+ if (pendingSub) {
5473
+ clearTimeout(pendingSub.timeout);
5474
+ pendingSub.resolve();
5475
+ this.pendingSubscriptions.delete(channelName);
5476
+ }
5477
+ const subHandler = this.channels.get(channelName);
5478
+ if (subHandler) {
5479
+ subHandler.handler.onSubscribed();
8183
5480
  }
8184
5481
  break;
8185
- case "unsubscribed":
8186
- console.log(`\u274C Unsubscribed from channel: ${message.payload.channel}`);
5482
+ case "message":
5483
+ const msgChannel = this.channels.get(message.payload?.channel);
5484
+ if (msgChannel) {
5485
+ msgChannel.handler.onMessage(message.payload);
5486
+ }
5487
+ break;
5488
+ case "presence":
5489
+ const presChannel = this.channels.get(message.payload?.channel);
5490
+ if (presChannel) {
5491
+ const users = message.payload?.data?.users || [];
5492
+ presChannel.handler.onPresence(users);
5493
+ }
8187
5494
  break;
8188
5495
  case "published":
8189
5496
  break;
8190
5497
  case "pong":
8191
5498
  break;
8192
5499
  case "error":
8193
- console.error("Realtime error:", message.payload.error);
8194
- if (this.pendingSubscription && message.payload.channel === this.channelName) {
8195
- this.pendingSubscription.reject(new BlinkRealtimeError(`Subscription error: ${message.payload.error}`));
5500
+ console.error("Realtime error:", message.payload?.error);
5501
+ const errChannel = this.channels.get(channelName);
5502
+ if (errChannel) {
5503
+ errChannel.handler.onError(message.payload?.error);
8196
5504
  }
5505
+ const pendingErr = this.pendingSubscriptions.get(channelName);
5506
+ if (pendingErr) {
5507
+ clearTimeout(pendingErr.timeout);
5508
+ pendingErr.reject(new BlinkRealtimeError(`Subscription error: ${message.payload?.error}`));
5509
+ this.pendingSubscriptions.delete(channelName);
5510
+ }
5511
+ break;
5512
+ case "unsubscribed":
5513
+ console.log(`\u274C Unsubscribed from channel: ${channelName}`);
8197
5514
  break;
8198
5515
  default:
8199
5516
  console.log("Unknown message type:", message.type);
8200
5517
  }
8201
5518
  }
5519
+ sendRaw(message) {
5520
+ if (this.websocket && this.websocket.readyState === 1) {
5521
+ this.websocket.send(message);
5522
+ } else {
5523
+ throw new BlinkRealtimeError("Cannot send message: WebSocket not connected");
5524
+ }
5525
+ }
5526
+ sendWithResponse(message, channelName) {
5527
+ return new Promise((resolve, reject) => {
5528
+ const timeout = setTimeout(() => {
5529
+ const index = this.messageQueue.findIndex((q) => q.resolve === resolve);
5530
+ if (index > -1) {
5531
+ this.messageQueue.splice(index, 1);
5532
+ }
5533
+ reject(new BlinkRealtimeError("Message send timeout - no response from server"));
5534
+ }, 1e4);
5535
+ if (this.websocket && this.websocket.readyState === 1) {
5536
+ const handleResponse = (event) => {
5537
+ try {
5538
+ const response = JSON.parse(event.data);
5539
+ if (response.type === "published" && response.payload.channel === channelName) {
5540
+ clearTimeout(timeout);
5541
+ this.websocket.removeEventListener("message", handleResponse);
5542
+ resolve(response.payload.messageId);
5543
+ } else if (response.type === "error") {
5544
+ clearTimeout(timeout);
5545
+ this.websocket.removeEventListener("message", handleResponse);
5546
+ reject(new BlinkRealtimeError(`Server error: ${response.payload.error}`));
5547
+ }
5548
+ } catch (err) {
5549
+ }
5550
+ };
5551
+ this.websocket.addEventListener("message", handleResponse);
5552
+ this.websocket.send(message);
5553
+ } else {
5554
+ this.messageQueue.push({ message, resolve, reject, timeout });
5555
+ }
5556
+ });
5557
+ }
5558
+ flushMessageQueue() {
5559
+ if (!this.websocket || this.websocket.readyState !== 1) return;
5560
+ const queue = [...this.messageQueue];
5561
+ this.messageQueue = [];
5562
+ queue.forEach((q) => {
5563
+ try {
5564
+ this.websocket.send(q.message);
5565
+ } catch (error) {
5566
+ clearTimeout(q.timeout);
5567
+ q.reject(new BlinkRealtimeError("Failed to send queued message"));
5568
+ }
5569
+ });
5570
+ }
5571
+ rejectQueuedMessages(error) {
5572
+ const queue = [...this.messageQueue];
5573
+ this.messageQueue = [];
5574
+ queue.forEach((q) => {
5575
+ clearTimeout(q.timeout);
5576
+ q.reject(error);
5577
+ });
5578
+ }
8202
5579
  startHeartbeat() {
8203
5580
  if (this.heartbeatTimer) {
8204
5581
  clearInterval(this.heartbeatTimer);
@@ -8213,7 +5590,7 @@ var BlinkRealtimeChannel = class {
8213
5590
  if (this.reconnectTimer) {
8214
5591
  clearTimeout(this.reconnectTimer);
8215
5592
  }
8216
- if (!this.isSubscribed && !this.pendingSubscription) {
5593
+ if (this.channels.size === 0) {
8217
5594
  return;
8218
5595
  }
8219
5596
  this.reconnectAttempts++;
@@ -8222,48 +5599,146 @@ var BlinkRealtimeChannel = class {
8222
5599
  const delay = baseDelay + jitter;
8223
5600
  console.log(`\u{1F504} Scheduling reconnect attempt ${this.reconnectAttempts} in ${Math.round(delay)}ms`);
8224
5601
  this.reconnectTimer = globalThis.setTimeout(async () => {
8225
- if (this.isSubscribed || this.pendingSubscription) {
8226
- try {
8227
- await this.connectWebSocket();
8228
- if (this.isSubscribed && this.websocket) {
8229
- const subscribeMessage = {
8230
- type: "subscribe",
8231
- payload: {
8232
- channel: this.channelName
8233
- }
8234
- };
8235
- this.websocket.send(JSON.stringify(subscribeMessage));
8236
- this.startHeartbeat();
5602
+ if (this.channels.size === 0) return;
5603
+ try {
5604
+ await this.connectWebSocket();
5605
+ await this.resubscribeAllChannels();
5606
+ } catch (error) {
5607
+ console.error("Reconnection failed:", error);
5608
+ this.scheduleReconnect();
5609
+ }
5610
+ }, delay);
5611
+ }
5612
+ async resubscribeAllChannels() {
5613
+ console.log(`\u{1F504} Resubscribing ${this.channels.size} channels...`);
5614
+ for (const [channelName, subscription] of this.channels) {
5615
+ try {
5616
+ const subscribeMessage = {
5617
+ type: "subscribe",
5618
+ payload: {
5619
+ channel: channelName,
5620
+ userId: subscription.options.userId,
5621
+ metadata: subscription.options.metadata
8237
5622
  }
8238
- } catch (error) {
8239
- console.error("Reconnection failed:", error);
8240
- this.scheduleReconnect();
5623
+ };
5624
+ if (this.websocket && this.websocket.readyState === 1) {
5625
+ this.websocket.send(JSON.stringify(subscribeMessage));
8241
5626
  }
5627
+ } catch (error) {
5628
+ console.error(`Failed to resubscribe to ${channelName}:`, error);
8242
5629
  }
8243
- }, delay);
5630
+ }
8244
5631
  }
8245
- cleanup() {
8246
- this.isSubscribed = false;
8247
- this.isConnected = false;
8248
- this.isConnecting = false;
8249
- if (this.pendingSubscription) {
8250
- clearTimeout(this.pendingSubscription.timeout);
8251
- this.pendingSubscription.reject(new BlinkRealtimeError("Channel cleanup"));
8252
- this.pendingSubscription = null;
5632
+ };
5633
+
5634
+ // src/realtime.ts
5635
+ var BlinkRealtimeChannel = class {
5636
+ constructor(channelName, connection, httpClient, projectId) {
5637
+ this.channelName = channelName;
5638
+ this.connection = connection;
5639
+ this.httpClient = httpClient;
5640
+ this.projectId = projectId;
5641
+ }
5642
+ messageCallbacks = [];
5643
+ presenceCallbacks = [];
5644
+ isSubscribed = false;
5645
+ subscribeOptions = {};
5646
+ /**
5647
+ * Check if channel is ready for publishing
5648
+ */
5649
+ isReady() {
5650
+ return this.isSubscribed && this.connection.isReady();
5651
+ }
5652
+ async subscribe(options = {}) {
5653
+ if (this.isSubscribed) {
5654
+ return;
8253
5655
  }
8254
- this.rejectQueuedMessages(new BlinkRealtimeError("Channel cleanup"));
8255
- if (this.heartbeatTimer) {
8256
- clearInterval(this.heartbeatTimer);
8257
- this.heartbeatTimer = null;
5656
+ this.subscribeOptions = options;
5657
+ const handler = {
5658
+ onMessage: (message) => {
5659
+ this.messageCallbacks.forEach((callback) => {
5660
+ try {
5661
+ callback(message);
5662
+ } catch (error) {
5663
+ console.error("Error in message callback:", error);
5664
+ }
5665
+ });
5666
+ },
5667
+ onPresence: (users) => {
5668
+ this.presenceCallbacks.forEach((callback) => {
5669
+ try {
5670
+ callback(users);
5671
+ } catch (error) {
5672
+ console.error("Error in presence callback:", error);
5673
+ }
5674
+ });
5675
+ },
5676
+ onSubscribed: () => {
5677
+ this.isSubscribed = true;
5678
+ },
5679
+ onError: (error) => {
5680
+ console.error(`Channel ${this.channelName} error:`, error);
5681
+ }
5682
+ };
5683
+ await this.connection.joinChannel(this.channelName, handler, options);
5684
+ this.isSubscribed = true;
5685
+ }
5686
+ async unsubscribe() {
5687
+ if (!this.isSubscribed) {
5688
+ return;
8258
5689
  }
8259
- if (this.reconnectTimer) {
8260
- clearTimeout(this.reconnectTimer);
8261
- this.reconnectTimer = null;
5690
+ await this.connection.leaveChannel(this.channelName);
5691
+ this.cleanup();
5692
+ }
5693
+ async publish(type, data, options = {}) {
5694
+ return this.connection.send(this.channelName, type, data, options);
5695
+ }
5696
+ onMessage(callback) {
5697
+ this.messageCallbacks.push(callback);
5698
+ return () => {
5699
+ const index = this.messageCallbacks.indexOf(callback);
5700
+ if (index > -1) {
5701
+ this.messageCallbacks.splice(index, 1);
5702
+ }
5703
+ };
5704
+ }
5705
+ onPresence(callback) {
5706
+ this.presenceCallbacks.push(callback);
5707
+ return () => {
5708
+ const index = this.presenceCallbacks.indexOf(callback);
5709
+ if (index > -1) {
5710
+ this.presenceCallbacks.splice(index, 1);
5711
+ }
5712
+ };
5713
+ }
5714
+ async getPresence() {
5715
+ try {
5716
+ const response = await this.httpClient.realtimeGetPresence(this.projectId, this.channelName);
5717
+ return response.data.users || [];
5718
+ } catch (error) {
5719
+ throw new BlinkRealtimeError(
5720
+ `Failed to get presence for channel ${this.channelName}: ${error instanceof Error ? error.message : "Unknown error"}`
5721
+ );
8262
5722
  }
8263
- if (this.websocket) {
8264
- this.websocket.close();
8265
- this.websocket = null;
5723
+ }
5724
+ async getMessages(options = {}) {
5725
+ try {
5726
+ const response = await this.httpClient.realtimeGetMessages(this.projectId, {
5727
+ channel: this.channelName,
5728
+ limit: options.limit,
5729
+ start: options.after || "-",
5730
+ end: options.before || "+"
5731
+ });
5732
+ return response.data.messages || [];
5733
+ } catch (error) {
5734
+ throw new BlinkRealtimeError(
5735
+ `Failed to get messages for channel ${this.channelName}: ${error instanceof Error ? error.message : "Unknown error"}`
5736
+ );
8266
5737
  }
5738
+ }
5739
+ cleanup() {
5740
+ this.isSubscribed = false;
5741
+ this.subscribeOptions = {};
8267
5742
  this.messageCallbacks = [];
8268
5743
  this.presenceCallbacks = [];
8269
5744
  }
@@ -8272,12 +5747,14 @@ var BlinkRealtimeImpl = class {
8272
5747
  constructor(httpClient, projectId) {
8273
5748
  this.httpClient = httpClient;
8274
5749
  this.projectId = projectId;
5750
+ this.connection = new RealtimeConnection(httpClient, projectId);
8275
5751
  }
5752
+ connection;
8276
5753
  channels = /* @__PURE__ */ new Map();
8277
5754
  handlers = {};
8278
5755
  channel(name) {
8279
5756
  if (!this.channels.has(name)) {
8280
- this.channels.set(name, new BlinkRealtimeChannel(name, this.httpClient, this.projectId));
5757
+ this.channels.set(name, new BlinkRealtimeChannel(name, this.connection, this.httpClient, this.projectId));
8281
5758
  }
8282
5759
  return this.channels.get(name);
8283
5760
  }
@@ -8326,6 +5803,18 @@ var BlinkRealtimeImpl = class {
8326
5803
  }
8327
5804
  };
8328
5805
  }
5806
+ /**
5807
+ * Get the number of active WebSocket connections (should always be 0 or 1)
5808
+ */
5809
+ getConnectionCount() {
5810
+ return this.connection.isReady() ? 1 : 0;
5811
+ }
5812
+ /**
5813
+ * Get the number of active channels
5814
+ */
5815
+ getChannelCount() {
5816
+ return this.connection.getChannelCount();
5817
+ }
8329
5818
  };
8330
5819
 
8331
5820
  // src/notifications.ts