vanshi-sdk 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4386 @@
1
+ var VanshiSdk = (() => {
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/sdk/browser.ts
21
+ var browser_exports = {};
22
+ __export(browser_exports, {
23
+ VanshiSdk: () => sdk_default
24
+ });
25
+
26
+ // node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/commons.js
27
+ var PACKET_TYPES = /* @__PURE__ */ Object.create(null);
28
+ PACKET_TYPES["open"] = "0";
29
+ PACKET_TYPES["close"] = "1";
30
+ PACKET_TYPES["ping"] = "2";
31
+ PACKET_TYPES["pong"] = "3";
32
+ PACKET_TYPES["message"] = "4";
33
+ PACKET_TYPES["upgrade"] = "5";
34
+ PACKET_TYPES["noop"] = "6";
35
+ var PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
36
+ Object.keys(PACKET_TYPES).forEach((key) => {
37
+ PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
38
+ });
39
+ var ERROR_PACKET = { type: "error", data: "parser error" };
40
+
41
+ // node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/encodePacket.browser.js
42
+ var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
43
+ var withNativeArrayBuffer = typeof ArrayBuffer === "function";
44
+ var isView = (obj) => {
45
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
46
+ };
47
+ var encodePacket = ({ type, data }, supportsBinary, callback) => {
48
+ if (withNativeBlob && data instanceof Blob) {
49
+ if (supportsBinary) {
50
+ return callback(data);
51
+ } else {
52
+ return encodeBlobAsBase64(data, callback);
53
+ }
54
+ } else if (withNativeArrayBuffer && (data instanceof ArrayBuffer || isView(data))) {
55
+ if (supportsBinary) {
56
+ return callback(data);
57
+ } else {
58
+ return encodeBlobAsBase64(new Blob([data]), callback);
59
+ }
60
+ }
61
+ return callback(PACKET_TYPES[type] + (data || ""));
62
+ };
63
+ var encodeBlobAsBase64 = (data, callback) => {
64
+ const fileReader = new FileReader();
65
+ fileReader.onload = function() {
66
+ const content = fileReader.result.split(",")[1];
67
+ callback("b" + (content || ""));
68
+ };
69
+ return fileReader.readAsDataURL(data);
70
+ };
71
+ function toArray(data) {
72
+ if (data instanceof Uint8Array) {
73
+ return data;
74
+ } else if (data instanceof ArrayBuffer) {
75
+ return new Uint8Array(data);
76
+ } else {
77
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
78
+ }
79
+ }
80
+ var TEXT_ENCODER;
81
+ function encodePacketToBinary(packet, callback) {
82
+ if (withNativeBlob && packet.data instanceof Blob) {
83
+ return packet.data.arrayBuffer().then(toArray).then(callback);
84
+ } else if (withNativeArrayBuffer && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
85
+ return callback(toArray(packet.data));
86
+ }
87
+ encodePacket(packet, false, (encoded) => {
88
+ if (!TEXT_ENCODER) {
89
+ TEXT_ENCODER = new TextEncoder();
90
+ }
91
+ callback(TEXT_ENCODER.encode(encoded));
92
+ });
93
+ }
94
+
95
+ // node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js
96
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
97
+ var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
98
+ for (let i = 0; i < chars.length; i++) {
99
+ lookup[chars.charCodeAt(i)] = i;
100
+ }
101
+ var decode = (base64) => {
102
+ let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
103
+ if (base64[base64.length - 1] === "=") {
104
+ bufferLength--;
105
+ if (base64[base64.length - 2] === "=") {
106
+ bufferLength--;
107
+ }
108
+ }
109
+ const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
110
+ for (i = 0; i < len; i += 4) {
111
+ encoded1 = lookup[base64.charCodeAt(i)];
112
+ encoded2 = lookup[base64.charCodeAt(i + 1)];
113
+ encoded3 = lookup[base64.charCodeAt(i + 2)];
114
+ encoded4 = lookup[base64.charCodeAt(i + 3)];
115
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
116
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
117
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
118
+ }
119
+ return arraybuffer;
120
+ };
121
+
122
+ // node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/decodePacket.browser.js
123
+ var withNativeArrayBuffer2 = typeof ArrayBuffer === "function";
124
+ var decodePacket = (encodedPacket, binaryType) => {
125
+ if (typeof encodedPacket !== "string") {
126
+ return {
127
+ type: "message",
128
+ data: mapBinary(encodedPacket, binaryType)
129
+ };
130
+ }
131
+ const type = encodedPacket.charAt(0);
132
+ if (type === "b") {
133
+ return {
134
+ type: "message",
135
+ data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
136
+ };
137
+ }
138
+ const packetType = PACKET_TYPES_REVERSE[type];
139
+ if (!packetType) {
140
+ return ERROR_PACKET;
141
+ }
142
+ return encodedPacket.length > 1 ? {
143
+ type: PACKET_TYPES_REVERSE[type],
144
+ data: encodedPacket.substring(1)
145
+ } : {
146
+ type: PACKET_TYPES_REVERSE[type]
147
+ };
148
+ };
149
+ var decodeBase64Packet = (data, binaryType) => {
150
+ if (withNativeArrayBuffer2) {
151
+ const decoded = decode(data);
152
+ return mapBinary(decoded, binaryType);
153
+ } else {
154
+ return { base64: true, data };
155
+ }
156
+ };
157
+ var mapBinary = (data, binaryType) => {
158
+ switch (binaryType) {
159
+ case "blob":
160
+ if (data instanceof Blob) {
161
+ return data;
162
+ } else {
163
+ return new Blob([data]);
164
+ }
165
+ case "arraybuffer":
166
+ default:
167
+ if (data instanceof ArrayBuffer) {
168
+ return data;
169
+ } else {
170
+ return data.buffer;
171
+ }
172
+ }
173
+ };
174
+
175
+ // node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/index.js
176
+ var SEPARATOR = String.fromCharCode(30);
177
+ var encodePayload = (packets, callback) => {
178
+ const length = packets.length;
179
+ const encodedPackets = new Array(length);
180
+ let count = 0;
181
+ packets.forEach((packet, i) => {
182
+ encodePacket(packet, false, (encodedPacket) => {
183
+ encodedPackets[i] = encodedPacket;
184
+ if (++count === length) {
185
+ callback(encodedPackets.join(SEPARATOR));
186
+ }
187
+ });
188
+ });
189
+ };
190
+ var decodePayload = (encodedPayload, binaryType) => {
191
+ const encodedPackets = encodedPayload.split(SEPARATOR);
192
+ const packets = [];
193
+ for (let i = 0; i < encodedPackets.length; i++) {
194
+ const decodedPacket = decodePacket(encodedPackets[i], binaryType);
195
+ packets.push(decodedPacket);
196
+ if (decodedPacket.type === "error") {
197
+ break;
198
+ }
199
+ }
200
+ return packets;
201
+ };
202
+ function createPacketEncoderStream() {
203
+ return new TransformStream({
204
+ transform(packet, controller) {
205
+ encodePacketToBinary(packet, (encodedPacket) => {
206
+ const payloadLength = encodedPacket.length;
207
+ let header;
208
+ if (payloadLength < 126) {
209
+ header = new Uint8Array(1);
210
+ new DataView(header.buffer).setUint8(0, payloadLength);
211
+ } else if (payloadLength < 65536) {
212
+ header = new Uint8Array(3);
213
+ const view = new DataView(header.buffer);
214
+ view.setUint8(0, 126);
215
+ view.setUint16(1, payloadLength);
216
+ } else {
217
+ header = new Uint8Array(9);
218
+ const view = new DataView(header.buffer);
219
+ view.setUint8(0, 127);
220
+ view.setBigUint64(1, BigInt(payloadLength));
221
+ }
222
+ if (packet.data && typeof packet.data !== "string") {
223
+ header[0] |= 128;
224
+ }
225
+ controller.enqueue(header);
226
+ controller.enqueue(encodedPacket);
227
+ });
228
+ }
229
+ });
230
+ }
231
+ var TEXT_DECODER;
232
+ function totalLength(chunks) {
233
+ return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
234
+ }
235
+ function concatChunks(chunks, size) {
236
+ if (chunks[0].length === size) {
237
+ return chunks.shift();
238
+ }
239
+ const buffer = new Uint8Array(size);
240
+ let j = 0;
241
+ for (let i = 0; i < size; i++) {
242
+ buffer[i] = chunks[0][j++];
243
+ if (j === chunks[0].length) {
244
+ chunks.shift();
245
+ j = 0;
246
+ }
247
+ }
248
+ if (chunks.length && j < chunks[0].length) {
249
+ chunks[0] = chunks[0].slice(j);
250
+ }
251
+ return buffer;
252
+ }
253
+ function createPacketDecoderStream(maxPayload, binaryType) {
254
+ if (!TEXT_DECODER) {
255
+ TEXT_DECODER = new TextDecoder();
256
+ }
257
+ const chunks = [];
258
+ let state = 0;
259
+ let expectedLength = -1;
260
+ let isBinary2 = false;
261
+ return new TransformStream({
262
+ transform(chunk, controller) {
263
+ chunks.push(chunk);
264
+ while (true) {
265
+ if (state === 0) {
266
+ if (totalLength(chunks) < 1) {
267
+ break;
268
+ }
269
+ const header = concatChunks(chunks, 1);
270
+ isBinary2 = (header[0] & 128) === 128;
271
+ expectedLength = header[0] & 127;
272
+ if (expectedLength < 126) {
273
+ state = 3;
274
+ } else if (expectedLength === 126) {
275
+ state = 1;
276
+ } else {
277
+ state = 2;
278
+ }
279
+ } else if (state === 1) {
280
+ if (totalLength(chunks) < 2) {
281
+ break;
282
+ }
283
+ const headerArray = concatChunks(chunks, 2);
284
+ expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
285
+ state = 3;
286
+ } else if (state === 2) {
287
+ if (totalLength(chunks) < 8) {
288
+ break;
289
+ }
290
+ const headerArray = concatChunks(chunks, 8);
291
+ const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
292
+ const n = view.getUint32(0);
293
+ if (n > Math.pow(2, 53 - 32) - 1) {
294
+ controller.enqueue(ERROR_PACKET);
295
+ break;
296
+ }
297
+ expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
298
+ state = 3;
299
+ } else {
300
+ if (totalLength(chunks) < expectedLength) {
301
+ break;
302
+ }
303
+ const data = concatChunks(chunks, expectedLength);
304
+ controller.enqueue(decodePacket(isBinary2 ? data : TEXT_DECODER.decode(data), binaryType));
305
+ state = 0;
306
+ }
307
+ if (expectedLength === 0 || expectedLength > maxPayload) {
308
+ controller.enqueue(ERROR_PACKET);
309
+ break;
310
+ }
311
+ }
312
+ }
313
+ });
314
+ }
315
+ var protocol = 4;
316
+
317
+ // node_modules/.pnpm/@socket.io+component-emitter@3.1.2/node_modules/@socket.io/component-emitter/lib/esm/index.js
318
+ function Emitter(obj) {
319
+ if (obj)
320
+ return mixin(obj);
321
+ }
322
+ function mixin(obj) {
323
+ for (var key in Emitter.prototype) {
324
+ obj[key] = Emitter.prototype[key];
325
+ }
326
+ return obj;
327
+ }
328
+ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
329
+ this._callbacks = this._callbacks || {};
330
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
331
+ return this;
332
+ };
333
+ Emitter.prototype.once = function(event, fn) {
334
+ function on3() {
335
+ this.off(event, on3);
336
+ fn.apply(this, arguments);
337
+ }
338
+ on3.fn = fn;
339
+ this.on(event, on3);
340
+ return this;
341
+ };
342
+ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
343
+ this._callbacks = this._callbacks || {};
344
+ if (0 == arguments.length) {
345
+ this._callbacks = {};
346
+ return this;
347
+ }
348
+ var callbacks = this._callbacks["$" + event];
349
+ if (!callbacks)
350
+ return this;
351
+ if (1 == arguments.length) {
352
+ delete this._callbacks["$" + event];
353
+ return this;
354
+ }
355
+ var cb;
356
+ for (var i = 0; i < callbacks.length; i++) {
357
+ cb = callbacks[i];
358
+ if (cb === fn || cb.fn === fn) {
359
+ callbacks.splice(i, 1);
360
+ break;
361
+ }
362
+ }
363
+ if (callbacks.length === 0) {
364
+ delete this._callbacks["$" + event];
365
+ }
366
+ return this;
367
+ };
368
+ Emitter.prototype.emit = function(event) {
369
+ this._callbacks = this._callbacks || {};
370
+ var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
371
+ for (var i = 1; i < arguments.length; i++) {
372
+ args[i - 1] = arguments[i];
373
+ }
374
+ if (callbacks) {
375
+ callbacks = callbacks.slice(0);
376
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
377
+ callbacks[i].apply(this, args);
378
+ }
379
+ }
380
+ return this;
381
+ };
382
+ Emitter.prototype.emitReserved = Emitter.prototype.emit;
383
+ Emitter.prototype.listeners = function(event) {
384
+ this._callbacks = this._callbacks || {};
385
+ return this._callbacks["$" + event] || [];
386
+ };
387
+ Emitter.prototype.hasListeners = function(event) {
388
+ return !!this.listeners(event).length;
389
+ };
390
+
391
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/globals.js
392
+ var nextTick = (() => {
393
+ const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
394
+ if (isPromiseAvailable) {
395
+ return (cb) => Promise.resolve().then(cb);
396
+ } else {
397
+ return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
398
+ }
399
+ })();
400
+ var globalThisShim = (() => {
401
+ if (typeof self !== "undefined") {
402
+ return self;
403
+ } else if (typeof window !== "undefined") {
404
+ return window;
405
+ } else {
406
+ return Function("return this")();
407
+ }
408
+ })();
409
+ var defaultBinaryType = "arraybuffer";
410
+ function createCookieJar() {
411
+ }
412
+
413
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/util.js
414
+ function pick(obj, ...attr) {
415
+ return attr.reduce((acc, k) => {
416
+ if (obj.hasOwnProperty(k)) {
417
+ acc[k] = obj[k];
418
+ }
419
+ return acc;
420
+ }, {});
421
+ }
422
+ var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
423
+ var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
424
+ function installTimerFunctions(obj, opts) {
425
+ if (opts.useNativeTimers) {
426
+ obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
427
+ obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
428
+ } else {
429
+ obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
430
+ obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
431
+ }
432
+ }
433
+ var BASE64_OVERHEAD = 1.33;
434
+ function byteLength(obj) {
435
+ if (typeof obj === "string") {
436
+ return utf8Length(obj);
437
+ }
438
+ return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
439
+ }
440
+ function utf8Length(str) {
441
+ let c = 0, length = 0;
442
+ for (let i = 0, l = str.length; i < l; i++) {
443
+ c = str.charCodeAt(i);
444
+ if (c < 128) {
445
+ length += 1;
446
+ } else if (c < 2048) {
447
+ length += 2;
448
+ } else if (c < 55296 || c >= 57344) {
449
+ length += 3;
450
+ } else {
451
+ i++;
452
+ length += 4;
453
+ }
454
+ }
455
+ return length;
456
+ }
457
+ function randomString() {
458
+ return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
459
+ }
460
+
461
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/contrib/parseqs.js
462
+ function encode(obj) {
463
+ let str = "";
464
+ for (let i in obj) {
465
+ if (obj.hasOwnProperty(i)) {
466
+ if (str.length)
467
+ str += "&";
468
+ str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
469
+ }
470
+ }
471
+ return str;
472
+ }
473
+ function decode2(qs) {
474
+ let qry = {};
475
+ let pairs = qs.split("&");
476
+ for (let i = 0, l = pairs.length; i < l; i++) {
477
+ let pair = pairs[i].split("=");
478
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
479
+ }
480
+ return qry;
481
+ }
482
+
483
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transport.js
484
+ var TransportError = class extends Error {
485
+ constructor(reason, description, context) {
486
+ super(reason);
487
+ this.description = description;
488
+ this.context = context;
489
+ this.type = "TransportError";
490
+ }
491
+ };
492
+ var Transport = class extends Emitter {
493
+ /**
494
+ * Transport abstract constructor.
495
+ *
496
+ * @param {Object} opts - options
497
+ * @protected
498
+ */
499
+ constructor(opts) {
500
+ super();
501
+ this.writable = false;
502
+ installTimerFunctions(this, opts);
503
+ this.opts = opts;
504
+ this.query = opts.query;
505
+ this.socket = opts.socket;
506
+ this.supportsBinary = !opts.forceBase64;
507
+ }
508
+ /**
509
+ * Emits an error.
510
+ *
511
+ * @param {String} reason
512
+ * @param description
513
+ * @param context - the error context
514
+ * @return {Transport} for chaining
515
+ * @protected
516
+ */
517
+ onError(reason, description, context) {
518
+ super.emitReserved("error", new TransportError(reason, description, context));
519
+ return this;
520
+ }
521
+ /**
522
+ * Opens the transport.
523
+ */
524
+ open() {
525
+ this.readyState = "opening";
526
+ this.doOpen();
527
+ return this;
528
+ }
529
+ /**
530
+ * Closes the transport.
531
+ */
532
+ close() {
533
+ if (this.readyState === "opening" || this.readyState === "open") {
534
+ this.doClose();
535
+ this.onClose();
536
+ }
537
+ return this;
538
+ }
539
+ /**
540
+ * Sends multiple packets.
541
+ *
542
+ * @param {Array} packets
543
+ */
544
+ send(packets) {
545
+ if (this.readyState === "open") {
546
+ this.write(packets);
547
+ } else {
548
+ }
549
+ }
550
+ /**
551
+ * Called upon open
552
+ *
553
+ * @protected
554
+ */
555
+ onOpen() {
556
+ this.readyState = "open";
557
+ this.writable = true;
558
+ super.emitReserved("open");
559
+ }
560
+ /**
561
+ * Called with data.
562
+ *
563
+ * @param {String} data
564
+ * @protected
565
+ */
566
+ onData(data) {
567
+ const packet = decodePacket(data, this.socket.binaryType);
568
+ this.onPacket(packet);
569
+ }
570
+ /**
571
+ * Called with a decoded packet.
572
+ *
573
+ * @protected
574
+ */
575
+ onPacket(packet) {
576
+ super.emitReserved("packet", packet);
577
+ }
578
+ /**
579
+ * Called upon close.
580
+ *
581
+ * @protected
582
+ */
583
+ onClose(details) {
584
+ this.readyState = "closed";
585
+ super.emitReserved("close", details);
586
+ }
587
+ /**
588
+ * Pauses the transport, in order not to lose packets during an upgrade.
589
+ *
590
+ * @param onPause
591
+ */
592
+ pause(onPause) {
593
+ }
594
+ createUri(schema, query = {}) {
595
+ return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
596
+ }
597
+ _hostname() {
598
+ const hostname = this.opts.hostname;
599
+ return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
600
+ }
601
+ _port() {
602
+ if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) {
603
+ return ":" + this.opts.port;
604
+ } else {
605
+ return "";
606
+ }
607
+ }
608
+ _query(query) {
609
+ const encodedQuery = encode(query);
610
+ return encodedQuery.length ? "?" + encodedQuery : "";
611
+ }
612
+ };
613
+
614
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/polling.js
615
+ var Polling = class extends Transport {
616
+ constructor() {
617
+ super(...arguments);
618
+ this._polling = false;
619
+ }
620
+ get name() {
621
+ return "polling";
622
+ }
623
+ /**
624
+ * Opens the socket (triggers polling). We write a PING message to determine
625
+ * when the transport is open.
626
+ *
627
+ * @protected
628
+ */
629
+ doOpen() {
630
+ this._poll();
631
+ }
632
+ /**
633
+ * Pauses polling.
634
+ *
635
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
636
+ * @package
637
+ */
638
+ pause(onPause) {
639
+ this.readyState = "pausing";
640
+ const pause = () => {
641
+ this.readyState = "paused";
642
+ onPause();
643
+ };
644
+ if (this._polling || !this.writable) {
645
+ let total = 0;
646
+ if (this._polling) {
647
+ total++;
648
+ this.once("pollComplete", function() {
649
+ --total || pause();
650
+ });
651
+ }
652
+ if (!this.writable) {
653
+ total++;
654
+ this.once("drain", function() {
655
+ --total || pause();
656
+ });
657
+ }
658
+ } else {
659
+ pause();
660
+ }
661
+ }
662
+ /**
663
+ * Starts polling cycle.
664
+ *
665
+ * @private
666
+ */
667
+ _poll() {
668
+ this._polling = true;
669
+ this.doPoll();
670
+ this.emitReserved("poll");
671
+ }
672
+ /**
673
+ * Overloads onData to detect payloads.
674
+ *
675
+ * @protected
676
+ */
677
+ onData(data) {
678
+ const callback = (packet) => {
679
+ if ("opening" === this.readyState && packet.type === "open") {
680
+ this.onOpen();
681
+ }
682
+ if ("close" === packet.type) {
683
+ this.onClose({ description: "transport closed by the server" });
684
+ return false;
685
+ }
686
+ this.onPacket(packet);
687
+ };
688
+ decodePayload(data, this.socket.binaryType).forEach(callback);
689
+ if ("closed" !== this.readyState) {
690
+ this._polling = false;
691
+ this.emitReserved("pollComplete");
692
+ if ("open" === this.readyState) {
693
+ this._poll();
694
+ } else {
695
+ }
696
+ }
697
+ }
698
+ /**
699
+ * For polling, send a close packet.
700
+ *
701
+ * @protected
702
+ */
703
+ doClose() {
704
+ const close = () => {
705
+ this.write([{ type: "close" }]);
706
+ };
707
+ if ("open" === this.readyState) {
708
+ close();
709
+ } else {
710
+ this.once("open", close);
711
+ }
712
+ }
713
+ /**
714
+ * Writes a packets payload.
715
+ *
716
+ * @param {Array} packets - data packets
717
+ * @protected
718
+ */
719
+ write(packets) {
720
+ this.writable = false;
721
+ encodePayload(packets, (data) => {
722
+ this.doWrite(data, () => {
723
+ this.writable = true;
724
+ this.emitReserved("drain");
725
+ });
726
+ });
727
+ }
728
+ /**
729
+ * Generates uri for connection.
730
+ *
731
+ * @private
732
+ */
733
+ uri() {
734
+ const schema = this.opts.secure ? "https" : "http";
735
+ const query = this.query || {};
736
+ if (false !== this.opts.timestampRequests) {
737
+ query[this.opts.timestampParam] = randomString();
738
+ }
739
+ if (!this.supportsBinary && !query.sid) {
740
+ query.b64 = 1;
741
+ }
742
+ return this.createUri(schema, query);
743
+ }
744
+ };
745
+
746
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/contrib/has-cors.js
747
+ var value = false;
748
+ try {
749
+ value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
750
+ } catch (err) {
751
+ }
752
+ var hasCORS = value;
753
+
754
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/polling-xhr.js
755
+ function empty() {
756
+ }
757
+ var BaseXHR = class extends Polling {
758
+ /**
759
+ * XHR Polling constructor.
760
+ *
761
+ * @param {Object} opts
762
+ * @package
763
+ */
764
+ constructor(opts) {
765
+ super(opts);
766
+ if (typeof location !== "undefined") {
767
+ const isSSL = "https:" === location.protocol;
768
+ let port = location.port;
769
+ if (!port) {
770
+ port = isSSL ? "443" : "80";
771
+ }
772
+ this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
773
+ }
774
+ }
775
+ /**
776
+ * Sends data.
777
+ *
778
+ * @param {String} data to send.
779
+ * @param {Function} called upon flush.
780
+ * @private
781
+ */
782
+ doWrite(data, fn) {
783
+ const req = this.request({
784
+ method: "POST",
785
+ data
786
+ });
787
+ req.on("success", fn);
788
+ req.on("error", (xhrStatus, context) => {
789
+ this.onError("xhr post error", xhrStatus, context);
790
+ });
791
+ }
792
+ /**
793
+ * Starts a poll cycle.
794
+ *
795
+ * @private
796
+ */
797
+ doPoll() {
798
+ const req = this.request();
799
+ req.on("data", this.onData.bind(this));
800
+ req.on("error", (xhrStatus, context) => {
801
+ this.onError("xhr poll error", xhrStatus, context);
802
+ });
803
+ this.pollXhr = req;
804
+ }
805
+ };
806
+ var Request = class extends Emitter {
807
+ /**
808
+ * Request constructor
809
+ *
810
+ * @param {Object} options
811
+ * @package
812
+ */
813
+ constructor(createRequest, uri, opts) {
814
+ super();
815
+ this.createRequest = createRequest;
816
+ installTimerFunctions(this, opts);
817
+ this._opts = opts;
818
+ this._method = opts.method || "GET";
819
+ this._uri = uri;
820
+ this._data = void 0 !== opts.data ? opts.data : null;
821
+ this._create();
822
+ }
823
+ /**
824
+ * Creates the XHR object and sends the request.
825
+ *
826
+ * @private
827
+ */
828
+ _create() {
829
+ var _a;
830
+ const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
831
+ opts.xdomain = !!this._opts.xd;
832
+ const xhr = this._xhr = this.createRequest(opts);
833
+ try {
834
+ xhr.open(this._method, this._uri, true);
835
+ try {
836
+ if (this._opts.extraHeaders) {
837
+ xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
838
+ for (let i in this._opts.extraHeaders) {
839
+ if (this._opts.extraHeaders.hasOwnProperty(i)) {
840
+ xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
841
+ }
842
+ }
843
+ }
844
+ } catch (e) {
845
+ }
846
+ if ("POST" === this._method) {
847
+ try {
848
+ xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
849
+ } catch (e) {
850
+ }
851
+ }
852
+ try {
853
+ xhr.setRequestHeader("Accept", "*/*");
854
+ } catch (e) {
855
+ }
856
+ (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
857
+ if ("withCredentials" in xhr) {
858
+ xhr.withCredentials = this._opts.withCredentials;
859
+ }
860
+ if (this._opts.requestTimeout) {
861
+ xhr.timeout = this._opts.requestTimeout;
862
+ }
863
+ xhr.onreadystatechange = () => {
864
+ var _a2;
865
+ if (xhr.readyState === 3) {
866
+ (_a2 = this._opts.cookieJar) === null || _a2 === void 0 ? void 0 : _a2.parseCookies(
867
+ // @ts-ignore
868
+ xhr.getResponseHeader("set-cookie")
869
+ );
870
+ }
871
+ if (4 !== xhr.readyState)
872
+ return;
873
+ if (200 === xhr.status || 1223 === xhr.status) {
874
+ this._onLoad();
875
+ } else {
876
+ this.setTimeoutFn(() => {
877
+ this._onError(typeof xhr.status === "number" ? xhr.status : 0);
878
+ }, 0);
879
+ }
880
+ };
881
+ xhr.send(this._data);
882
+ } catch (e) {
883
+ this.setTimeoutFn(() => {
884
+ this._onError(e);
885
+ }, 0);
886
+ return;
887
+ }
888
+ if (typeof document !== "undefined") {
889
+ this._index = Request.requestsCount++;
890
+ Request.requests[this._index] = this;
891
+ }
892
+ }
893
+ /**
894
+ * Called upon error.
895
+ *
896
+ * @private
897
+ */
898
+ _onError(err) {
899
+ this.emitReserved("error", err, this._xhr);
900
+ this._cleanup(true);
901
+ }
902
+ /**
903
+ * Cleans up house.
904
+ *
905
+ * @private
906
+ */
907
+ _cleanup(fromError) {
908
+ if ("undefined" === typeof this._xhr || null === this._xhr) {
909
+ return;
910
+ }
911
+ this._xhr.onreadystatechange = empty;
912
+ if (fromError) {
913
+ try {
914
+ this._xhr.abort();
915
+ } catch (e) {
916
+ }
917
+ }
918
+ if (typeof document !== "undefined") {
919
+ delete Request.requests[this._index];
920
+ }
921
+ this._xhr = null;
922
+ }
923
+ /**
924
+ * Called upon load.
925
+ *
926
+ * @private
927
+ */
928
+ _onLoad() {
929
+ const data = this._xhr.responseText;
930
+ if (data !== null) {
931
+ this.emitReserved("data", data);
932
+ this.emitReserved("success");
933
+ this._cleanup();
934
+ }
935
+ }
936
+ /**
937
+ * Aborts the request.
938
+ *
939
+ * @package
940
+ */
941
+ abort() {
942
+ this._cleanup();
943
+ }
944
+ };
945
+ Request.requestsCount = 0;
946
+ Request.requests = {};
947
+ if (typeof document !== "undefined") {
948
+ if (typeof attachEvent === "function") {
949
+ attachEvent("onunload", unloadHandler);
950
+ } else if (typeof addEventListener === "function") {
951
+ const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
952
+ addEventListener(terminationEvent, unloadHandler, false);
953
+ }
954
+ }
955
+ function unloadHandler() {
956
+ for (let i in Request.requests) {
957
+ if (Request.requests.hasOwnProperty(i)) {
958
+ Request.requests[i].abort();
959
+ }
960
+ }
961
+ }
962
+ var hasXHR2 = function() {
963
+ const xhr = newRequest({
964
+ xdomain: false
965
+ });
966
+ return xhr && xhr.responseType !== null;
967
+ }();
968
+ var XHR = class extends BaseXHR {
969
+ constructor(opts) {
970
+ super(opts);
971
+ const forceBase64 = opts && opts.forceBase64;
972
+ this.supportsBinary = hasXHR2 && !forceBase64;
973
+ }
974
+ request(opts = {}) {
975
+ Object.assign(opts, { xd: this.xd }, this.opts);
976
+ return new Request(newRequest, this.uri(), opts);
977
+ }
978
+ };
979
+ function newRequest(opts) {
980
+ const xdomain = opts.xdomain;
981
+ try {
982
+ if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
983
+ return new XMLHttpRequest();
984
+ }
985
+ } catch (e) {
986
+ }
987
+ if (!xdomain) {
988
+ try {
989
+ return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
990
+ } catch (e) {
991
+ }
992
+ }
993
+ }
994
+
995
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/websocket.js
996
+ var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
997
+ var BaseWS = class extends Transport {
998
+ get name() {
999
+ return "websocket";
1000
+ }
1001
+ doOpen() {
1002
+ const uri = this.uri();
1003
+ const protocols = this.opts.protocols;
1004
+ const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
1005
+ if (this.opts.extraHeaders) {
1006
+ opts.headers = this.opts.extraHeaders;
1007
+ }
1008
+ try {
1009
+ this.ws = this.createSocket(uri, protocols, opts);
1010
+ } catch (err) {
1011
+ return this.emitReserved("error", err);
1012
+ }
1013
+ this.ws.binaryType = this.socket.binaryType;
1014
+ this.addEventListeners();
1015
+ }
1016
+ /**
1017
+ * Adds event listeners to the socket
1018
+ *
1019
+ * @private
1020
+ */
1021
+ addEventListeners() {
1022
+ this.ws.onopen = () => {
1023
+ if (this.opts.autoUnref) {
1024
+ this.ws._socket.unref();
1025
+ }
1026
+ this.onOpen();
1027
+ };
1028
+ this.ws.onclose = (closeEvent) => this.onClose({
1029
+ description: "websocket connection closed",
1030
+ context: closeEvent
1031
+ });
1032
+ this.ws.onmessage = (ev) => this.onData(ev.data);
1033
+ this.ws.onerror = (e) => this.onError("websocket error", e);
1034
+ }
1035
+ write(packets) {
1036
+ this.writable = false;
1037
+ for (let i = 0; i < packets.length; i++) {
1038
+ const packet = packets[i];
1039
+ const lastPacket = i === packets.length - 1;
1040
+ encodePacket(packet, this.supportsBinary, (data) => {
1041
+ try {
1042
+ this.doWrite(packet, data);
1043
+ } catch (e) {
1044
+ }
1045
+ if (lastPacket) {
1046
+ nextTick(() => {
1047
+ this.writable = true;
1048
+ this.emitReserved("drain");
1049
+ }, this.setTimeoutFn);
1050
+ }
1051
+ });
1052
+ }
1053
+ }
1054
+ doClose() {
1055
+ if (typeof this.ws !== "undefined") {
1056
+ this.ws.onerror = () => {
1057
+ };
1058
+ this.ws.close();
1059
+ this.ws = null;
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Generates uri for connection.
1064
+ *
1065
+ * @private
1066
+ */
1067
+ uri() {
1068
+ const schema = this.opts.secure ? "wss" : "ws";
1069
+ const query = this.query || {};
1070
+ if (this.opts.timestampRequests) {
1071
+ query[this.opts.timestampParam] = randomString();
1072
+ }
1073
+ if (!this.supportsBinary) {
1074
+ query.b64 = 1;
1075
+ }
1076
+ return this.createUri(schema, query);
1077
+ }
1078
+ };
1079
+ var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
1080
+ var WS = class extends BaseWS {
1081
+ createSocket(uri, protocols, opts) {
1082
+ return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
1083
+ }
1084
+ doWrite(_packet, data) {
1085
+ this.ws.send(data);
1086
+ }
1087
+ };
1088
+
1089
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/webtransport.js
1090
+ var WT = class extends Transport {
1091
+ get name() {
1092
+ return "webtransport";
1093
+ }
1094
+ doOpen() {
1095
+ try {
1096
+ this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
1097
+ } catch (err) {
1098
+ return this.emitReserved("error", err);
1099
+ }
1100
+ this._transport.closed.then(() => {
1101
+ this.onClose();
1102
+ }).catch((err) => {
1103
+ this.onError("webtransport error", err);
1104
+ });
1105
+ this._transport.ready.then(() => {
1106
+ this._transport.createBidirectionalStream().then((stream) => {
1107
+ const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
1108
+ const reader = stream.readable.pipeThrough(decoderStream).getReader();
1109
+ const encoderStream = createPacketEncoderStream();
1110
+ encoderStream.readable.pipeTo(stream.writable);
1111
+ this._writer = encoderStream.writable.getWriter();
1112
+ const read = () => {
1113
+ reader.read().then(({ done, value: value2 }) => {
1114
+ if (done) {
1115
+ return;
1116
+ }
1117
+ this.onPacket(value2);
1118
+ read();
1119
+ }).catch((err) => {
1120
+ });
1121
+ };
1122
+ read();
1123
+ const packet = { type: "open" };
1124
+ if (this.query.sid) {
1125
+ packet.data = `{"sid":"${this.query.sid}"}`;
1126
+ }
1127
+ this._writer.write(packet).then(() => this.onOpen());
1128
+ });
1129
+ });
1130
+ }
1131
+ write(packets) {
1132
+ this.writable = false;
1133
+ for (let i = 0; i < packets.length; i++) {
1134
+ const packet = packets[i];
1135
+ const lastPacket = i === packets.length - 1;
1136
+ this._writer.write(packet).then(() => {
1137
+ if (lastPacket) {
1138
+ nextTick(() => {
1139
+ this.writable = true;
1140
+ this.emitReserved("drain");
1141
+ }, this.setTimeoutFn);
1142
+ }
1143
+ });
1144
+ }
1145
+ }
1146
+ doClose() {
1147
+ var _a;
1148
+ (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
1149
+ }
1150
+ };
1151
+
1152
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/index.js
1153
+ var transports = {
1154
+ websocket: WS,
1155
+ webtransport: WT,
1156
+ polling: XHR
1157
+ };
1158
+
1159
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/contrib/parseuri.js
1160
+ var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
1161
+ var parts = [
1162
+ "source",
1163
+ "protocol",
1164
+ "authority",
1165
+ "userInfo",
1166
+ "user",
1167
+ "password",
1168
+ "host",
1169
+ "port",
1170
+ "relative",
1171
+ "path",
1172
+ "directory",
1173
+ "file",
1174
+ "query",
1175
+ "anchor"
1176
+ ];
1177
+ function parse(str) {
1178
+ if (str.length > 8e3) {
1179
+ throw "URI too long";
1180
+ }
1181
+ const src = str, b = str.indexOf("["), e = str.indexOf("]");
1182
+ if (b != -1 && e != -1) {
1183
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ";") + str.substring(e, str.length);
1184
+ }
1185
+ let m = re.exec(str || ""), uri = {}, i = 14;
1186
+ while (i--) {
1187
+ uri[parts[i]] = m[i] || "";
1188
+ }
1189
+ if (b != -1 && e != -1) {
1190
+ uri.source = src;
1191
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
1192
+ uri.authority = uri.authority.replace("[", "").replace("]", "").replace(/;/g, ":");
1193
+ uri.ipv6uri = true;
1194
+ }
1195
+ uri.pathNames = pathNames(uri, uri["path"]);
1196
+ uri.queryKey = queryKey(uri, uri["query"]);
1197
+ return uri;
1198
+ }
1199
+ function pathNames(obj, path) {
1200
+ const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
1201
+ if (path.slice(0, 1) == "/" || path.length === 0) {
1202
+ names.splice(0, 1);
1203
+ }
1204
+ if (path.slice(-1) == "/") {
1205
+ names.splice(names.length - 1, 1);
1206
+ }
1207
+ return names;
1208
+ }
1209
+ function queryKey(uri, query) {
1210
+ const data = {};
1211
+ query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function($0, $1, $2) {
1212
+ if ($1) {
1213
+ data[$1] = $2;
1214
+ }
1215
+ });
1216
+ return data;
1217
+ }
1218
+
1219
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/socket.js
1220
+ var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
1221
+ var OFFLINE_EVENT_LISTENERS = [];
1222
+ if (withEventListeners) {
1223
+ addEventListener("offline", () => {
1224
+ OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
1225
+ }, false);
1226
+ }
1227
+ var SocketWithoutUpgrade = class extends Emitter {
1228
+ /**
1229
+ * Socket constructor.
1230
+ *
1231
+ * @param {String|Object} uri - uri or options
1232
+ * @param {Object} opts - options
1233
+ */
1234
+ constructor(uri, opts) {
1235
+ super();
1236
+ this.binaryType = defaultBinaryType;
1237
+ this.writeBuffer = [];
1238
+ this._prevBufferLen = 0;
1239
+ this._pingInterval = -1;
1240
+ this._pingTimeout = -1;
1241
+ this._maxPayload = -1;
1242
+ this._pingTimeoutTime = Infinity;
1243
+ if (uri && "object" === typeof uri) {
1244
+ opts = uri;
1245
+ uri = null;
1246
+ }
1247
+ if (uri) {
1248
+ const parsedUri = parse(uri);
1249
+ opts.hostname = parsedUri.host;
1250
+ opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
1251
+ opts.port = parsedUri.port;
1252
+ if (parsedUri.query)
1253
+ opts.query = parsedUri.query;
1254
+ } else if (opts.host) {
1255
+ opts.hostname = parse(opts.host).host;
1256
+ }
1257
+ installTimerFunctions(this, opts);
1258
+ this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
1259
+ if (opts.hostname && !opts.port) {
1260
+ opts.port = this.secure ? "443" : "80";
1261
+ }
1262
+ this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
1263
+ this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
1264
+ this.transports = [];
1265
+ this._transportsByName = {};
1266
+ opts.transports.forEach((t) => {
1267
+ const transportName = t.prototype.name;
1268
+ this.transports.push(transportName);
1269
+ this._transportsByName[transportName] = t;
1270
+ });
1271
+ this.opts = Object.assign({
1272
+ path: "/engine.io",
1273
+ agent: false,
1274
+ withCredentials: false,
1275
+ upgrade: true,
1276
+ timestampParam: "t",
1277
+ rememberUpgrade: false,
1278
+ addTrailingSlash: true,
1279
+ rejectUnauthorized: true,
1280
+ perMessageDeflate: {
1281
+ threshold: 1024
1282
+ },
1283
+ transportOptions: {},
1284
+ closeOnBeforeunload: false
1285
+ }, opts);
1286
+ this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
1287
+ if (typeof this.opts.query === "string") {
1288
+ this.opts.query = decode2(this.opts.query);
1289
+ }
1290
+ if (withEventListeners) {
1291
+ if (this.opts.closeOnBeforeunload) {
1292
+ this._beforeunloadEventListener = () => {
1293
+ if (this.transport) {
1294
+ this.transport.removeAllListeners();
1295
+ this.transport.close();
1296
+ }
1297
+ };
1298
+ addEventListener("beforeunload", this._beforeunloadEventListener, false);
1299
+ }
1300
+ if (this.hostname !== "localhost") {
1301
+ this._offlineEventListener = () => {
1302
+ this._onClose("transport close", {
1303
+ description: "network connection lost"
1304
+ });
1305
+ };
1306
+ OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
1307
+ }
1308
+ }
1309
+ if (this.opts.withCredentials) {
1310
+ this._cookieJar = createCookieJar();
1311
+ }
1312
+ this._open();
1313
+ }
1314
+ /**
1315
+ * Creates transport of the given type.
1316
+ *
1317
+ * @param {String} name - transport name
1318
+ * @return {Transport}
1319
+ * @private
1320
+ */
1321
+ createTransport(name) {
1322
+ const query = Object.assign({}, this.opts.query);
1323
+ query.EIO = protocol;
1324
+ query.transport = name;
1325
+ if (this.id)
1326
+ query.sid = this.id;
1327
+ const opts = Object.assign({}, this.opts, {
1328
+ query,
1329
+ socket: this,
1330
+ hostname: this.hostname,
1331
+ secure: this.secure,
1332
+ port: this.port
1333
+ }, this.opts.transportOptions[name]);
1334
+ return new this._transportsByName[name](opts);
1335
+ }
1336
+ /**
1337
+ * Initializes transport to use and starts probe.
1338
+ *
1339
+ * @private
1340
+ */
1341
+ _open() {
1342
+ if (this.transports.length === 0) {
1343
+ this.setTimeoutFn(() => {
1344
+ this.emitReserved("error", "No transports available");
1345
+ }, 0);
1346
+ return;
1347
+ }
1348
+ const transportName = this.opts.rememberUpgrade && SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
1349
+ this.readyState = "opening";
1350
+ const transport = this.createTransport(transportName);
1351
+ transport.open();
1352
+ this.setTransport(transport);
1353
+ }
1354
+ /**
1355
+ * Sets the current transport. Disables the existing one (if any).
1356
+ *
1357
+ * @private
1358
+ */
1359
+ setTransport(transport) {
1360
+ if (this.transport) {
1361
+ this.transport.removeAllListeners();
1362
+ }
1363
+ this.transport = transport;
1364
+ transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (reason) => this._onClose("transport close", reason));
1365
+ }
1366
+ /**
1367
+ * Called when connection is deemed open.
1368
+ *
1369
+ * @private
1370
+ */
1371
+ onOpen() {
1372
+ this.readyState = "open";
1373
+ SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
1374
+ this.emitReserved("open");
1375
+ this.flush();
1376
+ }
1377
+ /**
1378
+ * Handles a packet.
1379
+ *
1380
+ * @private
1381
+ */
1382
+ _onPacket(packet) {
1383
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
1384
+ this.emitReserved("packet", packet);
1385
+ this.emitReserved("heartbeat");
1386
+ switch (packet.type) {
1387
+ case "open":
1388
+ this.onHandshake(JSON.parse(packet.data));
1389
+ break;
1390
+ case "ping":
1391
+ this._sendPacket("pong");
1392
+ this.emitReserved("ping");
1393
+ this.emitReserved("pong");
1394
+ this._resetPingTimeout();
1395
+ break;
1396
+ case "error":
1397
+ const err = new Error("server error");
1398
+ err.code = packet.data;
1399
+ this._onError(err);
1400
+ break;
1401
+ case "message":
1402
+ this.emitReserved("data", packet.data);
1403
+ this.emitReserved("message", packet.data);
1404
+ break;
1405
+ }
1406
+ } else {
1407
+ }
1408
+ }
1409
+ /**
1410
+ * Called upon handshake completion.
1411
+ *
1412
+ * @param {Object} data - handshake obj
1413
+ * @private
1414
+ */
1415
+ onHandshake(data) {
1416
+ this.emitReserved("handshake", data);
1417
+ this.id = data.sid;
1418
+ this.transport.query.sid = data.sid;
1419
+ this._pingInterval = data.pingInterval;
1420
+ this._pingTimeout = data.pingTimeout;
1421
+ this._maxPayload = data.maxPayload;
1422
+ this.onOpen();
1423
+ if ("closed" === this.readyState)
1424
+ return;
1425
+ this._resetPingTimeout();
1426
+ }
1427
+ /**
1428
+ * Sets and resets ping timeout timer based on server pings.
1429
+ *
1430
+ * @private
1431
+ */
1432
+ _resetPingTimeout() {
1433
+ this.clearTimeoutFn(this._pingTimeoutTimer);
1434
+ const delay = this._pingInterval + this._pingTimeout;
1435
+ this._pingTimeoutTime = Date.now() + delay;
1436
+ this._pingTimeoutTimer = this.setTimeoutFn(() => {
1437
+ this._onClose("ping timeout");
1438
+ }, delay);
1439
+ if (this.opts.autoUnref) {
1440
+ this._pingTimeoutTimer.unref();
1441
+ }
1442
+ }
1443
+ /**
1444
+ * Called on `drain` event
1445
+ *
1446
+ * @private
1447
+ */
1448
+ _onDrain() {
1449
+ this.writeBuffer.splice(0, this._prevBufferLen);
1450
+ this._prevBufferLen = 0;
1451
+ if (0 === this.writeBuffer.length) {
1452
+ this.emitReserved("drain");
1453
+ } else {
1454
+ this.flush();
1455
+ }
1456
+ }
1457
+ /**
1458
+ * Flush write buffers.
1459
+ *
1460
+ * @private
1461
+ */
1462
+ flush() {
1463
+ if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
1464
+ const packets = this._getWritablePackets();
1465
+ this.transport.send(packets);
1466
+ this._prevBufferLen = packets.length;
1467
+ this.emitReserved("flush");
1468
+ }
1469
+ }
1470
+ /**
1471
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
1472
+ * long-polling)
1473
+ *
1474
+ * @private
1475
+ */
1476
+ _getWritablePackets() {
1477
+ const shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
1478
+ if (!shouldCheckPayloadSize) {
1479
+ return this.writeBuffer;
1480
+ }
1481
+ let payloadSize = 1;
1482
+ for (let i = 0; i < this.writeBuffer.length; i++) {
1483
+ const data = this.writeBuffer[i].data;
1484
+ if (data) {
1485
+ payloadSize += byteLength(data);
1486
+ }
1487
+ if (i > 0 && payloadSize > this._maxPayload) {
1488
+ return this.writeBuffer.slice(0, i);
1489
+ }
1490
+ payloadSize += 2;
1491
+ }
1492
+ return this.writeBuffer;
1493
+ }
1494
+ /**
1495
+ * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
1496
+ *
1497
+ * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
1498
+ * `write()` method then the message would not be buffered by the Socket.IO client.
1499
+ *
1500
+ * @return {boolean}
1501
+ * @private
1502
+ */
1503
+ /* private */
1504
+ _hasPingExpired() {
1505
+ if (!this._pingTimeoutTime)
1506
+ return true;
1507
+ const hasExpired = Date.now() > this._pingTimeoutTime;
1508
+ if (hasExpired) {
1509
+ this._pingTimeoutTime = 0;
1510
+ nextTick(() => {
1511
+ this._onClose("ping timeout");
1512
+ }, this.setTimeoutFn);
1513
+ }
1514
+ return hasExpired;
1515
+ }
1516
+ /**
1517
+ * Sends a message.
1518
+ *
1519
+ * @param {String} msg - message.
1520
+ * @param {Object} options.
1521
+ * @param {Function} fn - callback function.
1522
+ * @return {Socket} for chaining.
1523
+ */
1524
+ write(msg, options, fn) {
1525
+ this._sendPacket("message", msg, options, fn);
1526
+ return this;
1527
+ }
1528
+ /**
1529
+ * Sends a message. Alias of {@link Socket#write}.
1530
+ *
1531
+ * @param {String} msg - message.
1532
+ * @param {Object} options.
1533
+ * @param {Function} fn - callback function.
1534
+ * @return {Socket} for chaining.
1535
+ */
1536
+ send(msg, options, fn) {
1537
+ this._sendPacket("message", msg, options, fn);
1538
+ return this;
1539
+ }
1540
+ /**
1541
+ * Sends a packet.
1542
+ *
1543
+ * @param {String} type: packet type.
1544
+ * @param {String} data.
1545
+ * @param {Object} options.
1546
+ * @param {Function} fn - callback function.
1547
+ * @private
1548
+ */
1549
+ _sendPacket(type, data, options, fn) {
1550
+ if ("function" === typeof data) {
1551
+ fn = data;
1552
+ data = void 0;
1553
+ }
1554
+ if ("function" === typeof options) {
1555
+ fn = options;
1556
+ options = null;
1557
+ }
1558
+ if ("closing" === this.readyState || "closed" === this.readyState) {
1559
+ return;
1560
+ }
1561
+ options = options || {};
1562
+ options.compress = false !== options.compress;
1563
+ const packet = {
1564
+ type,
1565
+ data,
1566
+ options
1567
+ };
1568
+ this.emitReserved("packetCreate", packet);
1569
+ this.writeBuffer.push(packet);
1570
+ if (fn)
1571
+ this.once("flush", fn);
1572
+ this.flush();
1573
+ }
1574
+ /**
1575
+ * Closes the connection.
1576
+ */
1577
+ close() {
1578
+ const close = () => {
1579
+ this._onClose("forced close");
1580
+ this.transport.close();
1581
+ };
1582
+ const cleanupAndClose = () => {
1583
+ this.off("upgrade", cleanupAndClose);
1584
+ this.off("upgradeError", cleanupAndClose);
1585
+ close();
1586
+ };
1587
+ const waitForUpgrade = () => {
1588
+ this.once("upgrade", cleanupAndClose);
1589
+ this.once("upgradeError", cleanupAndClose);
1590
+ };
1591
+ if ("opening" === this.readyState || "open" === this.readyState) {
1592
+ this.readyState = "closing";
1593
+ if (this.writeBuffer.length) {
1594
+ this.once("drain", () => {
1595
+ if (this.upgrading) {
1596
+ waitForUpgrade();
1597
+ } else {
1598
+ close();
1599
+ }
1600
+ });
1601
+ } else if (this.upgrading) {
1602
+ waitForUpgrade();
1603
+ } else {
1604
+ close();
1605
+ }
1606
+ }
1607
+ return this;
1608
+ }
1609
+ /**
1610
+ * Called upon transport error
1611
+ *
1612
+ * @private
1613
+ */
1614
+ _onError(err) {
1615
+ SocketWithoutUpgrade.priorWebsocketSuccess = false;
1616
+ if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
1617
+ this.transports.shift();
1618
+ return this._open();
1619
+ }
1620
+ this.emitReserved("error", err);
1621
+ this._onClose("transport error", err);
1622
+ }
1623
+ /**
1624
+ * Called upon transport close.
1625
+ *
1626
+ * @private
1627
+ */
1628
+ _onClose(reason, description) {
1629
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
1630
+ this.clearTimeoutFn(this._pingTimeoutTimer);
1631
+ this.transport.removeAllListeners("close");
1632
+ this.transport.close();
1633
+ this.transport.removeAllListeners();
1634
+ if (withEventListeners) {
1635
+ if (this._beforeunloadEventListener) {
1636
+ removeEventListener("beforeunload", this._beforeunloadEventListener, false);
1637
+ }
1638
+ if (this._offlineEventListener) {
1639
+ const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
1640
+ if (i !== -1) {
1641
+ OFFLINE_EVENT_LISTENERS.splice(i, 1);
1642
+ }
1643
+ }
1644
+ }
1645
+ this.readyState = "closed";
1646
+ this.id = null;
1647
+ this.emitReserved("close", reason, description);
1648
+ this.writeBuffer = [];
1649
+ this._prevBufferLen = 0;
1650
+ }
1651
+ }
1652
+ };
1653
+ SocketWithoutUpgrade.protocol = protocol;
1654
+ var SocketWithUpgrade = class extends SocketWithoutUpgrade {
1655
+ constructor() {
1656
+ super(...arguments);
1657
+ this._upgrades = [];
1658
+ }
1659
+ onOpen() {
1660
+ super.onOpen();
1661
+ if ("open" === this.readyState && this.opts.upgrade) {
1662
+ for (let i = 0; i < this._upgrades.length; i++) {
1663
+ this._probe(this._upgrades[i]);
1664
+ }
1665
+ }
1666
+ }
1667
+ /**
1668
+ * Probes a transport.
1669
+ *
1670
+ * @param {String} name - transport name
1671
+ * @private
1672
+ */
1673
+ _probe(name) {
1674
+ let transport = this.createTransport(name);
1675
+ let failed = false;
1676
+ SocketWithoutUpgrade.priorWebsocketSuccess = false;
1677
+ const onTransportOpen = () => {
1678
+ if (failed)
1679
+ return;
1680
+ transport.send([{ type: "ping", data: "probe" }]);
1681
+ transport.once("packet", (msg) => {
1682
+ if (failed)
1683
+ return;
1684
+ if ("pong" === msg.type && "probe" === msg.data) {
1685
+ this.upgrading = true;
1686
+ this.emitReserved("upgrading", transport);
1687
+ if (!transport)
1688
+ return;
1689
+ SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
1690
+ this.transport.pause(() => {
1691
+ if (failed)
1692
+ return;
1693
+ if ("closed" === this.readyState)
1694
+ return;
1695
+ cleanup();
1696
+ this.setTransport(transport);
1697
+ transport.send([{ type: "upgrade" }]);
1698
+ this.emitReserved("upgrade", transport);
1699
+ transport = null;
1700
+ this.upgrading = false;
1701
+ this.flush();
1702
+ });
1703
+ } else {
1704
+ const err = new Error("probe error");
1705
+ err.transport = transport.name;
1706
+ this.emitReserved("upgradeError", err);
1707
+ }
1708
+ });
1709
+ };
1710
+ function freezeTransport() {
1711
+ if (failed)
1712
+ return;
1713
+ failed = true;
1714
+ cleanup();
1715
+ transport.close();
1716
+ transport = null;
1717
+ }
1718
+ const onerror = (err) => {
1719
+ const error = new Error("probe error: " + err);
1720
+ error.transport = transport.name;
1721
+ freezeTransport();
1722
+ this.emitReserved("upgradeError", error);
1723
+ };
1724
+ function onTransportClose() {
1725
+ onerror("transport closed");
1726
+ }
1727
+ function onclose() {
1728
+ onerror("socket closed");
1729
+ }
1730
+ function onupgrade(to) {
1731
+ if (transport && to.name !== transport.name) {
1732
+ freezeTransport();
1733
+ }
1734
+ }
1735
+ const cleanup = () => {
1736
+ transport.removeListener("open", onTransportOpen);
1737
+ transport.removeListener("error", onerror);
1738
+ transport.removeListener("close", onTransportClose);
1739
+ this.off("close", onclose);
1740
+ this.off("upgrading", onupgrade);
1741
+ };
1742
+ transport.once("open", onTransportOpen);
1743
+ transport.once("error", onerror);
1744
+ transport.once("close", onTransportClose);
1745
+ this.once("close", onclose);
1746
+ this.once("upgrading", onupgrade);
1747
+ if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
1748
+ this.setTimeoutFn(() => {
1749
+ if (!failed) {
1750
+ transport.open();
1751
+ }
1752
+ }, 200);
1753
+ } else {
1754
+ transport.open();
1755
+ }
1756
+ }
1757
+ onHandshake(data) {
1758
+ this._upgrades = this._filterUpgrades(data.upgrades);
1759
+ super.onHandshake(data);
1760
+ }
1761
+ /**
1762
+ * Filters upgrades, returning only those matching client transports.
1763
+ *
1764
+ * @param {Array} upgrades - server upgrades
1765
+ * @private
1766
+ */
1767
+ _filterUpgrades(upgrades) {
1768
+ const filteredUpgrades = [];
1769
+ for (let i = 0; i < upgrades.length; i++) {
1770
+ if (~this.transports.indexOf(upgrades[i]))
1771
+ filteredUpgrades.push(upgrades[i]);
1772
+ }
1773
+ return filteredUpgrades;
1774
+ }
1775
+ };
1776
+ var Socket = class extends SocketWithUpgrade {
1777
+ constructor(uri, opts = {}) {
1778
+ const o = typeof uri === "object" ? uri : opts;
1779
+ if (!o.transports || o.transports && typeof o.transports[0] === "string") {
1780
+ o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map((transportName) => transports[transportName]).filter((t) => !!t);
1781
+ }
1782
+ super(uri, o);
1783
+ }
1784
+ };
1785
+
1786
+ // node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/index.js
1787
+ var protocol2 = Socket.protocol;
1788
+
1789
+ // node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/url.js
1790
+ function url(uri, path = "", loc) {
1791
+ let obj = uri;
1792
+ loc = loc || typeof location !== "undefined" && location;
1793
+ if (null == uri)
1794
+ uri = loc.protocol + "//" + loc.host;
1795
+ if (typeof uri === "string") {
1796
+ if ("/" === uri.charAt(0)) {
1797
+ if ("/" === uri.charAt(1)) {
1798
+ uri = loc.protocol + uri;
1799
+ } else {
1800
+ uri = loc.host + uri;
1801
+ }
1802
+ }
1803
+ if (!/^(https?|wss?):\/\//.test(uri)) {
1804
+ if ("undefined" !== typeof loc) {
1805
+ uri = loc.protocol + "//" + uri;
1806
+ } else {
1807
+ uri = "https://" + uri;
1808
+ }
1809
+ }
1810
+ obj = parse(uri);
1811
+ }
1812
+ if (!obj.port) {
1813
+ if (/^(http|ws)$/.test(obj.protocol)) {
1814
+ obj.port = "80";
1815
+ } else if (/^(http|ws)s$/.test(obj.protocol)) {
1816
+ obj.port = "443";
1817
+ }
1818
+ }
1819
+ obj.path = obj.path || "/";
1820
+ const ipv6 = obj.host.indexOf(":") !== -1;
1821
+ const host = ipv6 ? "[" + obj.host + "]" : obj.host;
1822
+ obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
1823
+ obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
1824
+ return obj;
1825
+ }
1826
+
1827
+ // node_modules/.pnpm/socket.io-parser@4.2.6/node_modules/socket.io-parser/build/esm/index.js
1828
+ var esm_exports = {};
1829
+ __export(esm_exports, {
1830
+ Decoder: () => Decoder,
1831
+ Encoder: () => Encoder,
1832
+ PacketType: () => PacketType,
1833
+ isPacketValid: () => isPacketValid,
1834
+ protocol: () => protocol3
1835
+ });
1836
+
1837
+ // node_modules/.pnpm/socket.io-parser@4.2.6/node_modules/socket.io-parser/build/esm/is-binary.js
1838
+ var withNativeArrayBuffer3 = typeof ArrayBuffer === "function";
1839
+ var isView2 = (obj) => {
1840
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
1841
+ };
1842
+ var toString = Object.prototype.toString;
1843
+ var withNativeBlob2 = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
1844
+ var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
1845
+ function isBinary(obj) {
1846
+ return withNativeArrayBuffer3 && (obj instanceof ArrayBuffer || isView2(obj)) || withNativeBlob2 && obj instanceof Blob || withNativeFile && obj instanceof File;
1847
+ }
1848
+ function hasBinary(obj, toJSON) {
1849
+ if (!obj || typeof obj !== "object") {
1850
+ return false;
1851
+ }
1852
+ if (Array.isArray(obj)) {
1853
+ for (let i = 0, l = obj.length; i < l; i++) {
1854
+ if (hasBinary(obj[i])) {
1855
+ return true;
1856
+ }
1857
+ }
1858
+ return false;
1859
+ }
1860
+ if (isBinary(obj)) {
1861
+ return true;
1862
+ }
1863
+ if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
1864
+ return hasBinary(obj.toJSON(), true);
1865
+ }
1866
+ for (const key in obj) {
1867
+ if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
1868
+ return true;
1869
+ }
1870
+ }
1871
+ return false;
1872
+ }
1873
+
1874
+ // node_modules/.pnpm/socket.io-parser@4.2.6/node_modules/socket.io-parser/build/esm/binary.js
1875
+ function deconstructPacket(packet) {
1876
+ const buffers = [];
1877
+ const packetData = packet.data;
1878
+ const pack = packet;
1879
+ pack.data = _deconstructPacket(packetData, buffers);
1880
+ pack.attachments = buffers.length;
1881
+ return { packet: pack, buffers };
1882
+ }
1883
+ function _deconstructPacket(data, buffers) {
1884
+ if (!data)
1885
+ return data;
1886
+ if (isBinary(data)) {
1887
+ const placeholder = { _placeholder: true, num: buffers.length };
1888
+ buffers.push(data);
1889
+ return placeholder;
1890
+ } else if (Array.isArray(data)) {
1891
+ const newData = new Array(data.length);
1892
+ for (let i = 0; i < data.length; i++) {
1893
+ newData[i] = _deconstructPacket(data[i], buffers);
1894
+ }
1895
+ return newData;
1896
+ } else if (typeof data === "object" && !(data instanceof Date)) {
1897
+ const newData = {};
1898
+ for (const key in data) {
1899
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
1900
+ newData[key] = _deconstructPacket(data[key], buffers);
1901
+ }
1902
+ }
1903
+ return newData;
1904
+ }
1905
+ return data;
1906
+ }
1907
+ function reconstructPacket(packet, buffers) {
1908
+ packet.data = _reconstructPacket(packet.data, buffers);
1909
+ delete packet.attachments;
1910
+ return packet;
1911
+ }
1912
+ function _reconstructPacket(data, buffers) {
1913
+ if (!data)
1914
+ return data;
1915
+ if (data && data._placeholder === true) {
1916
+ const isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
1917
+ if (isIndexValid) {
1918
+ return buffers[data.num];
1919
+ } else {
1920
+ throw new Error("illegal attachments");
1921
+ }
1922
+ } else if (Array.isArray(data)) {
1923
+ for (let i = 0; i < data.length; i++) {
1924
+ data[i] = _reconstructPacket(data[i], buffers);
1925
+ }
1926
+ } else if (typeof data === "object") {
1927
+ for (const key in data) {
1928
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
1929
+ data[key] = _reconstructPacket(data[key], buffers);
1930
+ }
1931
+ }
1932
+ }
1933
+ return data;
1934
+ }
1935
+
1936
+ // node_modules/.pnpm/socket.io-parser@4.2.6/node_modules/socket.io-parser/build/esm/index.js
1937
+ var RESERVED_EVENTS = [
1938
+ "connect",
1939
+ // used on the client side
1940
+ "connect_error",
1941
+ // used on the client side
1942
+ "disconnect",
1943
+ // used on both sides
1944
+ "disconnecting",
1945
+ // used on the server side
1946
+ "newListener",
1947
+ // used by the Node.js EventEmitter
1948
+ "removeListener"
1949
+ // used by the Node.js EventEmitter
1950
+ ];
1951
+ var protocol3 = 5;
1952
+ var PacketType;
1953
+ (function(PacketType2) {
1954
+ PacketType2[PacketType2["CONNECT"] = 0] = "CONNECT";
1955
+ PacketType2[PacketType2["DISCONNECT"] = 1] = "DISCONNECT";
1956
+ PacketType2[PacketType2["EVENT"] = 2] = "EVENT";
1957
+ PacketType2[PacketType2["ACK"] = 3] = "ACK";
1958
+ PacketType2[PacketType2["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
1959
+ PacketType2[PacketType2["BINARY_EVENT"] = 5] = "BINARY_EVENT";
1960
+ PacketType2[PacketType2["BINARY_ACK"] = 6] = "BINARY_ACK";
1961
+ })(PacketType || (PacketType = {}));
1962
+ var Encoder = class {
1963
+ /**
1964
+ * Encoder constructor
1965
+ *
1966
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
1967
+ */
1968
+ constructor(replacer) {
1969
+ this.replacer = replacer;
1970
+ }
1971
+ /**
1972
+ * Encode a packet as a single string if non-binary, or as a
1973
+ * buffer sequence, depending on packet type.
1974
+ *
1975
+ * @param {Object} obj - packet object
1976
+ */
1977
+ encode(obj) {
1978
+ if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
1979
+ if (hasBinary(obj)) {
1980
+ return this.encodeAsBinary({
1981
+ type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
1982
+ nsp: obj.nsp,
1983
+ data: obj.data,
1984
+ id: obj.id
1985
+ });
1986
+ }
1987
+ }
1988
+ return [this.encodeAsString(obj)];
1989
+ }
1990
+ /**
1991
+ * Encode packet as string.
1992
+ */
1993
+ encodeAsString(obj) {
1994
+ let str = "" + obj.type;
1995
+ if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
1996
+ str += obj.attachments + "-";
1997
+ }
1998
+ if (obj.nsp && "/" !== obj.nsp) {
1999
+ str += obj.nsp + ",";
2000
+ }
2001
+ if (null != obj.id) {
2002
+ str += obj.id;
2003
+ }
2004
+ if (null != obj.data) {
2005
+ str += JSON.stringify(obj.data, this.replacer);
2006
+ }
2007
+ return str;
2008
+ }
2009
+ /**
2010
+ * Encode packet as 'buffer sequence' by removing blobs, and
2011
+ * deconstructing packet into object with placeholders and
2012
+ * a list of buffers.
2013
+ */
2014
+ encodeAsBinary(obj) {
2015
+ const deconstruction = deconstructPacket(obj);
2016
+ const pack = this.encodeAsString(deconstruction.packet);
2017
+ const buffers = deconstruction.buffers;
2018
+ buffers.unshift(pack);
2019
+ return buffers;
2020
+ }
2021
+ };
2022
+ var Decoder = class extends Emitter {
2023
+ /**
2024
+ * Decoder constructor
2025
+ */
2026
+ constructor(opts) {
2027
+ super();
2028
+ this.opts = Object.assign({
2029
+ reviver: void 0,
2030
+ maxAttachments: 10
2031
+ }, typeof opts === "function" ? { reviver: opts } : opts);
2032
+ }
2033
+ /**
2034
+ * Decodes an encoded packet string into packet JSON.
2035
+ *
2036
+ * @param {String} obj - encoded packet
2037
+ */
2038
+ add(obj) {
2039
+ let packet;
2040
+ if (typeof obj === "string") {
2041
+ if (this.reconstructor) {
2042
+ throw new Error("got plaintext data when reconstructing a packet");
2043
+ }
2044
+ packet = this.decodeString(obj);
2045
+ const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
2046
+ if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
2047
+ packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
2048
+ this.reconstructor = new BinaryReconstructor(packet);
2049
+ if (packet.attachments === 0) {
2050
+ super.emitReserved("decoded", packet);
2051
+ }
2052
+ } else {
2053
+ super.emitReserved("decoded", packet);
2054
+ }
2055
+ } else if (isBinary(obj) || obj.base64) {
2056
+ if (!this.reconstructor) {
2057
+ throw new Error("got binary data when not reconstructing a packet");
2058
+ } else {
2059
+ packet = this.reconstructor.takeBinaryData(obj);
2060
+ if (packet) {
2061
+ this.reconstructor = null;
2062
+ super.emitReserved("decoded", packet);
2063
+ }
2064
+ }
2065
+ } else {
2066
+ throw new Error("Unknown type: " + obj);
2067
+ }
2068
+ }
2069
+ /**
2070
+ * Decode a packet String (JSON data)
2071
+ *
2072
+ * @param {String} str
2073
+ * @return {Object} packet
2074
+ */
2075
+ decodeString(str) {
2076
+ let i = 0;
2077
+ const p = {
2078
+ type: Number(str.charAt(0))
2079
+ };
2080
+ if (PacketType[p.type] === void 0) {
2081
+ throw new Error("unknown packet type " + p.type);
2082
+ }
2083
+ if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
2084
+ const start = i + 1;
2085
+ while (str.charAt(++i) !== "-" && i != str.length) {
2086
+ }
2087
+ const buf = str.substring(start, i);
2088
+ if (buf != Number(buf) || str.charAt(i) !== "-") {
2089
+ throw new Error("Illegal attachments");
2090
+ }
2091
+ const n = Number(buf);
2092
+ if (!isInteger(n) || n < 0) {
2093
+ throw new Error("Illegal attachments");
2094
+ } else if (n > this.opts.maxAttachments) {
2095
+ throw new Error("too many attachments");
2096
+ }
2097
+ p.attachments = n;
2098
+ }
2099
+ if ("/" === str.charAt(i + 1)) {
2100
+ const start = i + 1;
2101
+ while (++i) {
2102
+ const c = str.charAt(i);
2103
+ if ("," === c)
2104
+ break;
2105
+ if (i === str.length)
2106
+ break;
2107
+ }
2108
+ p.nsp = str.substring(start, i);
2109
+ } else {
2110
+ p.nsp = "/";
2111
+ }
2112
+ const next = str.charAt(i + 1);
2113
+ if ("" !== next && Number(next) == next) {
2114
+ const start = i + 1;
2115
+ while (++i) {
2116
+ const c = str.charAt(i);
2117
+ if (null == c || Number(c) != c) {
2118
+ --i;
2119
+ break;
2120
+ }
2121
+ if (i === str.length)
2122
+ break;
2123
+ }
2124
+ p.id = Number(str.substring(start, i + 1));
2125
+ }
2126
+ if (str.charAt(++i)) {
2127
+ const payload = this.tryParse(str.substr(i));
2128
+ if (Decoder.isPayloadValid(p.type, payload)) {
2129
+ p.data = payload;
2130
+ } else {
2131
+ throw new Error("invalid payload");
2132
+ }
2133
+ }
2134
+ return p;
2135
+ }
2136
+ tryParse(str) {
2137
+ try {
2138
+ return JSON.parse(str, this.opts.reviver);
2139
+ } catch (e) {
2140
+ return false;
2141
+ }
2142
+ }
2143
+ static isPayloadValid(type, payload) {
2144
+ switch (type) {
2145
+ case PacketType.CONNECT:
2146
+ return isObject(payload);
2147
+ case PacketType.DISCONNECT:
2148
+ return payload === void 0;
2149
+ case PacketType.CONNECT_ERROR:
2150
+ return typeof payload === "string" || isObject(payload);
2151
+ case PacketType.EVENT:
2152
+ case PacketType.BINARY_EVENT:
2153
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
2154
+ case PacketType.ACK:
2155
+ case PacketType.BINARY_ACK:
2156
+ return Array.isArray(payload);
2157
+ }
2158
+ }
2159
+ /**
2160
+ * Deallocates a parser's resources
2161
+ */
2162
+ destroy() {
2163
+ if (this.reconstructor) {
2164
+ this.reconstructor.finishedReconstruction();
2165
+ this.reconstructor = null;
2166
+ }
2167
+ }
2168
+ };
2169
+ var BinaryReconstructor = class {
2170
+ constructor(packet) {
2171
+ this.packet = packet;
2172
+ this.buffers = [];
2173
+ this.reconPack = packet;
2174
+ }
2175
+ /**
2176
+ * Method to be called when binary data received from connection
2177
+ * after a BINARY_EVENT packet.
2178
+ *
2179
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
2180
+ * @return {null | Object} returns null if more binary data is expected or
2181
+ * a reconstructed packet object if all buffers have been received.
2182
+ */
2183
+ takeBinaryData(binData) {
2184
+ this.buffers.push(binData);
2185
+ if (this.buffers.length === this.reconPack.attachments) {
2186
+ const packet = reconstructPacket(this.reconPack, this.buffers);
2187
+ this.finishedReconstruction();
2188
+ return packet;
2189
+ }
2190
+ return null;
2191
+ }
2192
+ /**
2193
+ * Cleans up binary packet reconstruction variables.
2194
+ */
2195
+ finishedReconstruction() {
2196
+ this.reconPack = null;
2197
+ this.buffers = [];
2198
+ }
2199
+ };
2200
+ function isNamespaceValid(nsp) {
2201
+ return typeof nsp === "string";
2202
+ }
2203
+ var isInteger = Number.isInteger || function(value2) {
2204
+ return typeof value2 === "number" && isFinite(value2) && Math.floor(value2) === value2;
2205
+ };
2206
+ function isAckIdValid(id) {
2207
+ return id === void 0 || isInteger(id);
2208
+ }
2209
+ function isObject(value2) {
2210
+ return Object.prototype.toString.call(value2) === "[object Object]";
2211
+ }
2212
+ function isDataValid(type, payload) {
2213
+ switch (type) {
2214
+ case PacketType.CONNECT:
2215
+ return payload === void 0 || isObject(payload);
2216
+ case PacketType.DISCONNECT:
2217
+ return payload === void 0;
2218
+ case PacketType.EVENT:
2219
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
2220
+ case PacketType.ACK:
2221
+ return Array.isArray(payload);
2222
+ case PacketType.CONNECT_ERROR:
2223
+ return typeof payload === "string" || isObject(payload);
2224
+ default:
2225
+ return false;
2226
+ }
2227
+ }
2228
+ function isPacketValid(packet) {
2229
+ return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
2230
+ }
2231
+
2232
+ // node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/on.js
2233
+ function on(obj, ev, fn) {
2234
+ obj.on(ev, fn);
2235
+ return function subDestroy() {
2236
+ obj.off(ev, fn);
2237
+ };
2238
+ }
2239
+
2240
+ // node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/socket.js
2241
+ var RESERVED_EVENTS2 = Object.freeze({
2242
+ connect: 1,
2243
+ connect_error: 1,
2244
+ disconnect: 1,
2245
+ disconnecting: 1,
2246
+ // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
2247
+ newListener: 1,
2248
+ removeListener: 1
2249
+ });
2250
+ var Socket2 = class extends Emitter {
2251
+ /**
2252
+ * `Socket` constructor.
2253
+ */
2254
+ constructor(io, nsp, opts) {
2255
+ super();
2256
+ this.connected = false;
2257
+ this.recovered = false;
2258
+ this.receiveBuffer = [];
2259
+ this.sendBuffer = [];
2260
+ this._queue = [];
2261
+ this._queueSeq = 0;
2262
+ this.ids = 0;
2263
+ this.acks = {};
2264
+ this.flags = {};
2265
+ this.io = io;
2266
+ this.nsp = nsp;
2267
+ if (opts && opts.auth) {
2268
+ this.auth = opts.auth;
2269
+ }
2270
+ this._opts = Object.assign({}, opts);
2271
+ if (this.io._autoConnect)
2272
+ this.open();
2273
+ }
2274
+ /**
2275
+ * Whether the socket is currently disconnected
2276
+ *
2277
+ * @example
2278
+ * const socket = io();
2279
+ *
2280
+ * socket.on("connect", () => {
2281
+ * console.log(socket.disconnected); // false
2282
+ * });
2283
+ *
2284
+ * socket.on("disconnect", () => {
2285
+ * console.log(socket.disconnected); // true
2286
+ * });
2287
+ */
2288
+ get disconnected() {
2289
+ return !this.connected;
2290
+ }
2291
+ /**
2292
+ * Subscribe to open, close and packet events
2293
+ *
2294
+ * @private
2295
+ */
2296
+ subEvents() {
2297
+ if (this.subs)
2298
+ return;
2299
+ const io = this.io;
2300
+ this.subs = [
2301
+ on(io, "open", this.onopen.bind(this)),
2302
+ on(io, "packet", this.onpacket.bind(this)),
2303
+ on(io, "error", this.onerror.bind(this)),
2304
+ on(io, "close", this.onclose.bind(this))
2305
+ ];
2306
+ }
2307
+ /**
2308
+ * Whether the Socket will try to reconnect when its Manager connects or reconnects.
2309
+ *
2310
+ * @example
2311
+ * const socket = io();
2312
+ *
2313
+ * console.log(socket.active); // true
2314
+ *
2315
+ * socket.on("disconnect", (reason) => {
2316
+ * if (reason === "io server disconnect") {
2317
+ * // the disconnection was initiated by the server, you need to manually reconnect
2318
+ * console.log(socket.active); // false
2319
+ * }
2320
+ * // else the socket will automatically try to reconnect
2321
+ * console.log(socket.active); // true
2322
+ * });
2323
+ */
2324
+ get active() {
2325
+ return !!this.subs;
2326
+ }
2327
+ /**
2328
+ * "Opens" the socket.
2329
+ *
2330
+ * @example
2331
+ * const socket = io({
2332
+ * autoConnect: false
2333
+ * });
2334
+ *
2335
+ * socket.connect();
2336
+ */
2337
+ connect() {
2338
+ if (this.connected)
2339
+ return this;
2340
+ this.subEvents();
2341
+ if (!this.io["_reconnecting"])
2342
+ this.io.open();
2343
+ if ("open" === this.io._readyState)
2344
+ this.onopen();
2345
+ return this;
2346
+ }
2347
+ /**
2348
+ * Alias for {@link connect()}.
2349
+ */
2350
+ open() {
2351
+ return this.connect();
2352
+ }
2353
+ /**
2354
+ * Sends a `message` event.
2355
+ *
2356
+ * This method mimics the WebSocket.send() method.
2357
+ *
2358
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
2359
+ *
2360
+ * @example
2361
+ * socket.send("hello");
2362
+ *
2363
+ * // this is equivalent to
2364
+ * socket.emit("message", "hello");
2365
+ *
2366
+ * @return self
2367
+ */
2368
+ send(...args) {
2369
+ args.unshift("message");
2370
+ this.emit.apply(this, args);
2371
+ return this;
2372
+ }
2373
+ /**
2374
+ * Override `emit`.
2375
+ * If the event is in `events`, it's emitted normally.
2376
+ *
2377
+ * @example
2378
+ * socket.emit("hello", "world");
2379
+ *
2380
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
2381
+ * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
2382
+ *
2383
+ * // with an acknowledgement from the server
2384
+ * socket.emit("hello", "world", (val) => {
2385
+ * // ...
2386
+ * });
2387
+ *
2388
+ * @return self
2389
+ */
2390
+ emit(ev, ...args) {
2391
+ var _a, _b, _c;
2392
+ if (RESERVED_EVENTS2.hasOwnProperty(ev)) {
2393
+ throw new Error('"' + ev.toString() + '" is a reserved event name');
2394
+ }
2395
+ args.unshift(ev);
2396
+ if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
2397
+ this._addToQueue(args);
2398
+ return this;
2399
+ }
2400
+ const packet = {
2401
+ type: PacketType.EVENT,
2402
+ data: args
2403
+ };
2404
+ packet.options = {};
2405
+ packet.options.compress = this.flags.compress !== false;
2406
+ if ("function" === typeof args[args.length - 1]) {
2407
+ const id = this.ids++;
2408
+ const ack = args.pop();
2409
+ this._registerAckCallback(id, ack);
2410
+ packet.id = id;
2411
+ }
2412
+ const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
2413
+ const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
2414
+ const discardPacket = this.flags.volatile && !isTransportWritable;
2415
+ if (discardPacket) {
2416
+ } else if (isConnected) {
2417
+ this.notifyOutgoingListeners(packet);
2418
+ this.packet(packet);
2419
+ } else {
2420
+ this.sendBuffer.push(packet);
2421
+ }
2422
+ this.flags = {};
2423
+ return this;
2424
+ }
2425
+ /**
2426
+ * @private
2427
+ */
2428
+ _registerAckCallback(id, ack) {
2429
+ var _a;
2430
+ const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
2431
+ if (timeout === void 0) {
2432
+ this.acks[id] = ack;
2433
+ return;
2434
+ }
2435
+ const timer = this.io.setTimeoutFn(() => {
2436
+ delete this.acks[id];
2437
+ for (let i = 0; i < this.sendBuffer.length; i++) {
2438
+ if (this.sendBuffer[i].id === id) {
2439
+ this.sendBuffer.splice(i, 1);
2440
+ }
2441
+ }
2442
+ ack.call(this, new Error("operation has timed out"));
2443
+ }, timeout);
2444
+ const fn = (...args) => {
2445
+ this.io.clearTimeoutFn(timer);
2446
+ ack.apply(this, args);
2447
+ };
2448
+ fn.withError = true;
2449
+ this.acks[id] = fn;
2450
+ }
2451
+ /**
2452
+ * Emits an event and waits for an acknowledgement
2453
+ *
2454
+ * @example
2455
+ * // without timeout
2456
+ * const response = await socket.emitWithAck("hello", "world");
2457
+ *
2458
+ * // with a specific timeout
2459
+ * try {
2460
+ * const response = await socket.timeout(1000).emitWithAck("hello", "world");
2461
+ * } catch (err) {
2462
+ * // the server did not acknowledge the event in the given delay
2463
+ * }
2464
+ *
2465
+ * @return a Promise that will be fulfilled when the server acknowledges the event
2466
+ */
2467
+ emitWithAck(ev, ...args) {
2468
+ return new Promise((resolve, reject) => {
2469
+ const fn = (arg1, arg2) => {
2470
+ return arg1 ? reject(arg1) : resolve(arg2);
2471
+ };
2472
+ fn.withError = true;
2473
+ args.push(fn);
2474
+ this.emit(ev, ...args);
2475
+ });
2476
+ }
2477
+ /**
2478
+ * Add the packet to the queue.
2479
+ * @param args
2480
+ * @private
2481
+ */
2482
+ _addToQueue(args) {
2483
+ let ack;
2484
+ if (typeof args[args.length - 1] === "function") {
2485
+ ack = args.pop();
2486
+ }
2487
+ const packet = {
2488
+ id: this._queueSeq++,
2489
+ tryCount: 0,
2490
+ pending: false,
2491
+ args,
2492
+ flags: Object.assign({ fromQueue: true }, this.flags)
2493
+ };
2494
+ args.push((err, ...responseArgs) => {
2495
+ if (packet !== this._queue[0]) {
2496
+ }
2497
+ const hasError = err !== null;
2498
+ if (hasError) {
2499
+ if (packet.tryCount > this._opts.retries) {
2500
+ this._queue.shift();
2501
+ if (ack) {
2502
+ ack(err);
2503
+ }
2504
+ }
2505
+ } else {
2506
+ this._queue.shift();
2507
+ if (ack) {
2508
+ ack(null, ...responseArgs);
2509
+ }
2510
+ }
2511
+ packet.pending = false;
2512
+ return this._drainQueue();
2513
+ });
2514
+ this._queue.push(packet);
2515
+ this._drainQueue();
2516
+ }
2517
+ /**
2518
+ * Send the first packet of the queue, and wait for an acknowledgement from the server.
2519
+ * @param force - whether to resend a packet that has not been acknowledged yet
2520
+ *
2521
+ * @private
2522
+ */
2523
+ _drainQueue(force = false) {
2524
+ if (!this.connected || this._queue.length === 0) {
2525
+ return;
2526
+ }
2527
+ const packet = this._queue[0];
2528
+ if (packet.pending && !force) {
2529
+ return;
2530
+ }
2531
+ packet.pending = true;
2532
+ packet.tryCount++;
2533
+ this.flags = packet.flags;
2534
+ this.emit.apply(this, packet.args);
2535
+ }
2536
+ /**
2537
+ * Sends a packet.
2538
+ *
2539
+ * @param packet
2540
+ * @private
2541
+ */
2542
+ packet(packet) {
2543
+ packet.nsp = this.nsp;
2544
+ this.io._packet(packet);
2545
+ }
2546
+ /**
2547
+ * Called upon engine `open`.
2548
+ *
2549
+ * @private
2550
+ */
2551
+ onopen() {
2552
+ if (typeof this.auth == "function") {
2553
+ this.auth((data) => {
2554
+ this._sendConnectPacket(data);
2555
+ });
2556
+ } else {
2557
+ this._sendConnectPacket(this.auth);
2558
+ }
2559
+ }
2560
+ /**
2561
+ * Sends a CONNECT packet to initiate the Socket.IO session.
2562
+ *
2563
+ * @param data
2564
+ * @private
2565
+ */
2566
+ _sendConnectPacket(data) {
2567
+ this.packet({
2568
+ type: PacketType.CONNECT,
2569
+ data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data) : data
2570
+ });
2571
+ }
2572
+ /**
2573
+ * Called upon engine or manager `error`.
2574
+ *
2575
+ * @param err
2576
+ * @private
2577
+ */
2578
+ onerror(err) {
2579
+ if (!this.connected) {
2580
+ this.emitReserved("connect_error", err);
2581
+ }
2582
+ }
2583
+ /**
2584
+ * Called upon engine `close`.
2585
+ *
2586
+ * @param reason
2587
+ * @param description
2588
+ * @private
2589
+ */
2590
+ onclose(reason, description) {
2591
+ this.connected = false;
2592
+ delete this.id;
2593
+ this.emitReserved("disconnect", reason, description);
2594
+ this._clearAcks();
2595
+ }
2596
+ /**
2597
+ * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
2598
+ * the server.
2599
+ *
2600
+ * @private
2601
+ */
2602
+ _clearAcks() {
2603
+ Object.keys(this.acks).forEach((id) => {
2604
+ const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
2605
+ if (!isBuffered) {
2606
+ const ack = this.acks[id];
2607
+ delete this.acks[id];
2608
+ if (ack.withError) {
2609
+ ack.call(this, new Error("socket has been disconnected"));
2610
+ }
2611
+ }
2612
+ });
2613
+ }
2614
+ /**
2615
+ * Called with socket packet.
2616
+ *
2617
+ * @param packet
2618
+ * @private
2619
+ */
2620
+ onpacket(packet) {
2621
+ const sameNamespace = packet.nsp === this.nsp;
2622
+ if (!sameNamespace)
2623
+ return;
2624
+ switch (packet.type) {
2625
+ case PacketType.CONNECT:
2626
+ if (packet.data && packet.data.sid) {
2627
+ this.onconnect(packet.data.sid, packet.data.pid);
2628
+ } else {
2629
+ this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
2630
+ }
2631
+ break;
2632
+ case PacketType.EVENT:
2633
+ case PacketType.BINARY_EVENT:
2634
+ this.onevent(packet);
2635
+ break;
2636
+ case PacketType.ACK:
2637
+ case PacketType.BINARY_ACK:
2638
+ this.onack(packet);
2639
+ break;
2640
+ case PacketType.DISCONNECT:
2641
+ this.ondisconnect();
2642
+ break;
2643
+ case PacketType.CONNECT_ERROR:
2644
+ this.destroy();
2645
+ const err = new Error(packet.data.message);
2646
+ err.data = packet.data.data;
2647
+ this.emitReserved("connect_error", err);
2648
+ break;
2649
+ }
2650
+ }
2651
+ /**
2652
+ * Called upon a server event.
2653
+ *
2654
+ * @param packet
2655
+ * @private
2656
+ */
2657
+ onevent(packet) {
2658
+ const args = packet.data || [];
2659
+ if (null != packet.id) {
2660
+ args.push(this.ack(packet.id));
2661
+ }
2662
+ if (this.connected) {
2663
+ this.emitEvent(args);
2664
+ } else {
2665
+ this.receiveBuffer.push(Object.freeze(args));
2666
+ }
2667
+ }
2668
+ emitEvent(args) {
2669
+ if (this._anyListeners && this._anyListeners.length) {
2670
+ const listeners = this._anyListeners.slice();
2671
+ for (const listener of listeners) {
2672
+ listener.apply(this, args);
2673
+ }
2674
+ }
2675
+ super.emit.apply(this, args);
2676
+ if (this._pid && args.length && typeof args[args.length - 1] === "string") {
2677
+ this._lastOffset = args[args.length - 1];
2678
+ }
2679
+ }
2680
+ /**
2681
+ * Produces an ack callback to emit with an event.
2682
+ *
2683
+ * @private
2684
+ */
2685
+ ack(id) {
2686
+ const self2 = this;
2687
+ let sent = false;
2688
+ return function(...args) {
2689
+ if (sent)
2690
+ return;
2691
+ sent = true;
2692
+ self2.packet({
2693
+ type: PacketType.ACK,
2694
+ id,
2695
+ data: args
2696
+ });
2697
+ };
2698
+ }
2699
+ /**
2700
+ * Called upon a server acknowledgement.
2701
+ *
2702
+ * @param packet
2703
+ * @private
2704
+ */
2705
+ onack(packet) {
2706
+ const ack = this.acks[packet.id];
2707
+ if (typeof ack !== "function") {
2708
+ return;
2709
+ }
2710
+ delete this.acks[packet.id];
2711
+ if (ack.withError) {
2712
+ packet.data.unshift(null);
2713
+ }
2714
+ ack.apply(this, packet.data);
2715
+ }
2716
+ /**
2717
+ * Called upon server connect.
2718
+ *
2719
+ * @private
2720
+ */
2721
+ onconnect(id, pid) {
2722
+ this.id = id;
2723
+ this.recovered = pid && this._pid === pid;
2724
+ this._pid = pid;
2725
+ this.connected = true;
2726
+ this.emitBuffered();
2727
+ this._drainQueue(true);
2728
+ this.emitReserved("connect");
2729
+ }
2730
+ /**
2731
+ * Emit buffered events (received and emitted).
2732
+ *
2733
+ * @private
2734
+ */
2735
+ emitBuffered() {
2736
+ this.receiveBuffer.forEach((args) => this.emitEvent(args));
2737
+ this.receiveBuffer = [];
2738
+ this.sendBuffer.forEach((packet) => {
2739
+ this.notifyOutgoingListeners(packet);
2740
+ this.packet(packet);
2741
+ });
2742
+ this.sendBuffer = [];
2743
+ }
2744
+ /**
2745
+ * Called upon server disconnect.
2746
+ *
2747
+ * @private
2748
+ */
2749
+ ondisconnect() {
2750
+ this.destroy();
2751
+ this.onclose("io server disconnect");
2752
+ }
2753
+ /**
2754
+ * Called upon forced client/server side disconnections,
2755
+ * this method ensures the manager stops tracking us and
2756
+ * that reconnections don't get triggered for this.
2757
+ *
2758
+ * @private
2759
+ */
2760
+ destroy() {
2761
+ if (this.subs) {
2762
+ this.subs.forEach((subDestroy) => subDestroy());
2763
+ this.subs = void 0;
2764
+ }
2765
+ this.io["_destroy"](this);
2766
+ }
2767
+ /**
2768
+ * Disconnects the socket manually. In that case, the socket will not try to reconnect.
2769
+ *
2770
+ * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
2771
+ *
2772
+ * @example
2773
+ * const socket = io();
2774
+ *
2775
+ * socket.on("disconnect", (reason) => {
2776
+ * // console.log(reason); prints "io client disconnect"
2777
+ * });
2778
+ *
2779
+ * socket.disconnect();
2780
+ *
2781
+ * @return self
2782
+ */
2783
+ disconnect() {
2784
+ if (this.connected) {
2785
+ this.packet({ type: PacketType.DISCONNECT });
2786
+ }
2787
+ this.destroy();
2788
+ if (this.connected) {
2789
+ this.onclose("io client disconnect");
2790
+ }
2791
+ return this;
2792
+ }
2793
+ /**
2794
+ * Alias for {@link disconnect()}.
2795
+ *
2796
+ * @return self
2797
+ */
2798
+ close() {
2799
+ return this.disconnect();
2800
+ }
2801
+ /**
2802
+ * Sets the compress flag.
2803
+ *
2804
+ * @example
2805
+ * socket.compress(false).emit("hello");
2806
+ *
2807
+ * @param compress - if `true`, compresses the sending data
2808
+ * @return self
2809
+ */
2810
+ compress(compress) {
2811
+ this.flags.compress = compress;
2812
+ return this;
2813
+ }
2814
+ /**
2815
+ * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
2816
+ * ready to send messages.
2817
+ *
2818
+ * @example
2819
+ * socket.volatile.emit("hello"); // the server may or may not receive it
2820
+ *
2821
+ * @returns self
2822
+ */
2823
+ get volatile() {
2824
+ this.flags.volatile = true;
2825
+ return this;
2826
+ }
2827
+ /**
2828
+ * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
2829
+ * given number of milliseconds have elapsed without an acknowledgement from the server:
2830
+ *
2831
+ * @example
2832
+ * socket.timeout(5000).emit("my-event", (err) => {
2833
+ * if (err) {
2834
+ * // the server did not acknowledge the event in the given delay
2835
+ * }
2836
+ * });
2837
+ *
2838
+ * @returns self
2839
+ */
2840
+ timeout(timeout) {
2841
+ this.flags.timeout = timeout;
2842
+ return this;
2843
+ }
2844
+ /**
2845
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2846
+ * callback.
2847
+ *
2848
+ * @example
2849
+ * socket.onAny((event, ...args) => {
2850
+ * console.log(`got ${event}`);
2851
+ * });
2852
+ *
2853
+ * @param listener
2854
+ */
2855
+ onAny(listener) {
2856
+ this._anyListeners = this._anyListeners || [];
2857
+ this._anyListeners.push(listener);
2858
+ return this;
2859
+ }
2860
+ /**
2861
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2862
+ * callback. The listener is added to the beginning of the listeners array.
2863
+ *
2864
+ * @example
2865
+ * socket.prependAny((event, ...args) => {
2866
+ * console.log(`got event ${event}`);
2867
+ * });
2868
+ *
2869
+ * @param listener
2870
+ */
2871
+ prependAny(listener) {
2872
+ this._anyListeners = this._anyListeners || [];
2873
+ this._anyListeners.unshift(listener);
2874
+ return this;
2875
+ }
2876
+ /**
2877
+ * Removes the listener that will be fired when any event is emitted.
2878
+ *
2879
+ * @example
2880
+ * const catchAllListener = (event, ...args) => {
2881
+ * console.log(`got event ${event}`);
2882
+ * }
2883
+ *
2884
+ * socket.onAny(catchAllListener);
2885
+ *
2886
+ * // remove a specific listener
2887
+ * socket.offAny(catchAllListener);
2888
+ *
2889
+ * // or remove all listeners
2890
+ * socket.offAny();
2891
+ *
2892
+ * @param listener
2893
+ */
2894
+ offAny(listener) {
2895
+ if (!this._anyListeners) {
2896
+ return this;
2897
+ }
2898
+ if (listener) {
2899
+ const listeners = this._anyListeners;
2900
+ for (let i = 0; i < listeners.length; i++) {
2901
+ if (listener === listeners[i]) {
2902
+ listeners.splice(i, 1);
2903
+ return this;
2904
+ }
2905
+ }
2906
+ } else {
2907
+ this._anyListeners = [];
2908
+ }
2909
+ return this;
2910
+ }
2911
+ /**
2912
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
2913
+ * e.g. to remove listeners.
2914
+ */
2915
+ listenersAny() {
2916
+ return this._anyListeners || [];
2917
+ }
2918
+ /**
2919
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2920
+ * callback.
2921
+ *
2922
+ * Note: acknowledgements sent to the server are not included.
2923
+ *
2924
+ * @example
2925
+ * socket.onAnyOutgoing((event, ...args) => {
2926
+ * console.log(`sent event ${event}`);
2927
+ * });
2928
+ *
2929
+ * @param listener
2930
+ */
2931
+ onAnyOutgoing(listener) {
2932
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
2933
+ this._anyOutgoingListeners.push(listener);
2934
+ return this;
2935
+ }
2936
+ /**
2937
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2938
+ * callback. The listener is added to the beginning of the listeners array.
2939
+ *
2940
+ * Note: acknowledgements sent to the server are not included.
2941
+ *
2942
+ * @example
2943
+ * socket.prependAnyOutgoing((event, ...args) => {
2944
+ * console.log(`sent event ${event}`);
2945
+ * });
2946
+ *
2947
+ * @param listener
2948
+ */
2949
+ prependAnyOutgoing(listener) {
2950
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
2951
+ this._anyOutgoingListeners.unshift(listener);
2952
+ return this;
2953
+ }
2954
+ /**
2955
+ * Removes the listener that will be fired when any event is emitted.
2956
+ *
2957
+ * @example
2958
+ * const catchAllListener = (event, ...args) => {
2959
+ * console.log(`sent event ${event}`);
2960
+ * }
2961
+ *
2962
+ * socket.onAnyOutgoing(catchAllListener);
2963
+ *
2964
+ * // remove a specific listener
2965
+ * socket.offAnyOutgoing(catchAllListener);
2966
+ *
2967
+ * // or remove all listeners
2968
+ * socket.offAnyOutgoing();
2969
+ *
2970
+ * @param [listener] - the catch-all listener (optional)
2971
+ */
2972
+ offAnyOutgoing(listener) {
2973
+ if (!this._anyOutgoingListeners) {
2974
+ return this;
2975
+ }
2976
+ if (listener) {
2977
+ const listeners = this._anyOutgoingListeners;
2978
+ for (let i = 0; i < listeners.length; i++) {
2979
+ if (listener === listeners[i]) {
2980
+ listeners.splice(i, 1);
2981
+ return this;
2982
+ }
2983
+ }
2984
+ } else {
2985
+ this._anyOutgoingListeners = [];
2986
+ }
2987
+ return this;
2988
+ }
2989
+ /**
2990
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
2991
+ * e.g. to remove listeners.
2992
+ */
2993
+ listenersAnyOutgoing() {
2994
+ return this._anyOutgoingListeners || [];
2995
+ }
2996
+ /**
2997
+ * Notify the listeners for each packet sent
2998
+ *
2999
+ * @param packet
3000
+ *
3001
+ * @private
3002
+ */
3003
+ notifyOutgoingListeners(packet) {
3004
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
3005
+ const listeners = this._anyOutgoingListeners.slice();
3006
+ for (const listener of listeners) {
3007
+ listener.apply(this, packet.data);
3008
+ }
3009
+ }
3010
+ }
3011
+ };
3012
+
3013
+ // node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/contrib/backo2.js
3014
+ function Backoff(opts) {
3015
+ opts = opts || {};
3016
+ this.ms = opts.min || 100;
3017
+ this.max = opts.max || 1e4;
3018
+ this.factor = opts.factor || 2;
3019
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
3020
+ this.attempts = 0;
3021
+ }
3022
+ Backoff.prototype.duration = function() {
3023
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
3024
+ if (this.jitter) {
3025
+ var rand = Math.random();
3026
+ var deviation = Math.floor(rand * this.jitter * ms);
3027
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
3028
+ }
3029
+ return Math.min(ms, this.max) | 0;
3030
+ };
3031
+ Backoff.prototype.reset = function() {
3032
+ this.attempts = 0;
3033
+ };
3034
+ Backoff.prototype.setMin = function(min) {
3035
+ this.ms = min;
3036
+ };
3037
+ Backoff.prototype.setMax = function(max) {
3038
+ this.max = max;
3039
+ };
3040
+ Backoff.prototype.setJitter = function(jitter) {
3041
+ this.jitter = jitter;
3042
+ };
3043
+
3044
+ // node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/manager.js
3045
+ var Manager = class extends Emitter {
3046
+ constructor(uri, opts) {
3047
+ var _a;
3048
+ super();
3049
+ this.nsps = {};
3050
+ this.subs = [];
3051
+ if (uri && "object" === typeof uri) {
3052
+ opts = uri;
3053
+ uri = void 0;
3054
+ }
3055
+ opts = opts || {};
3056
+ opts.path = opts.path || "/socket.io";
3057
+ this.opts = opts;
3058
+ installTimerFunctions(this, opts);
3059
+ this.reconnection(opts.reconnection !== false);
3060
+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
3061
+ this.reconnectionDelay(opts.reconnectionDelay || 1e3);
3062
+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
3063
+ this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
3064
+ this.backoff = new Backoff({
3065
+ min: this.reconnectionDelay(),
3066
+ max: this.reconnectionDelayMax(),
3067
+ jitter: this.randomizationFactor()
3068
+ });
3069
+ this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
3070
+ this._readyState = "closed";
3071
+ this.uri = uri;
3072
+ const _parser = opts.parser || esm_exports;
3073
+ this.encoder = new _parser.Encoder();
3074
+ this.decoder = new _parser.Decoder();
3075
+ this._autoConnect = opts.autoConnect !== false;
3076
+ if (this._autoConnect)
3077
+ this.open();
3078
+ }
3079
+ reconnection(v) {
3080
+ if (!arguments.length)
3081
+ return this._reconnection;
3082
+ this._reconnection = !!v;
3083
+ if (!v) {
3084
+ this.skipReconnect = true;
3085
+ }
3086
+ return this;
3087
+ }
3088
+ reconnectionAttempts(v) {
3089
+ if (v === void 0)
3090
+ return this._reconnectionAttempts;
3091
+ this._reconnectionAttempts = v;
3092
+ return this;
3093
+ }
3094
+ reconnectionDelay(v) {
3095
+ var _a;
3096
+ if (v === void 0)
3097
+ return this._reconnectionDelay;
3098
+ this._reconnectionDelay = v;
3099
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
3100
+ return this;
3101
+ }
3102
+ randomizationFactor(v) {
3103
+ var _a;
3104
+ if (v === void 0)
3105
+ return this._randomizationFactor;
3106
+ this._randomizationFactor = v;
3107
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
3108
+ return this;
3109
+ }
3110
+ reconnectionDelayMax(v) {
3111
+ var _a;
3112
+ if (v === void 0)
3113
+ return this._reconnectionDelayMax;
3114
+ this._reconnectionDelayMax = v;
3115
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
3116
+ return this;
3117
+ }
3118
+ timeout(v) {
3119
+ if (!arguments.length)
3120
+ return this._timeout;
3121
+ this._timeout = v;
3122
+ return this;
3123
+ }
3124
+ /**
3125
+ * Starts trying to reconnect if reconnection is enabled and we have not
3126
+ * started reconnecting yet
3127
+ *
3128
+ * @private
3129
+ */
3130
+ maybeReconnectOnOpen() {
3131
+ if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
3132
+ this.reconnect();
3133
+ }
3134
+ }
3135
+ /**
3136
+ * Sets the current transport `socket`.
3137
+ *
3138
+ * @param {Function} fn - optional, callback
3139
+ * @return self
3140
+ * @public
3141
+ */
3142
+ open(fn) {
3143
+ if (~this._readyState.indexOf("open"))
3144
+ return this;
3145
+ this.engine = new Socket(this.uri, this.opts);
3146
+ const socket = this.engine;
3147
+ const self2 = this;
3148
+ this._readyState = "opening";
3149
+ this.skipReconnect = false;
3150
+ const openSubDestroy = on(socket, "open", function() {
3151
+ self2.onopen();
3152
+ fn && fn();
3153
+ });
3154
+ const onError = (err) => {
3155
+ this.cleanup();
3156
+ this._readyState = "closed";
3157
+ this.emitReserved("error", err);
3158
+ if (fn) {
3159
+ fn(err);
3160
+ } else {
3161
+ this.maybeReconnectOnOpen();
3162
+ }
3163
+ };
3164
+ const errorSub = on(socket, "error", onError);
3165
+ if (false !== this._timeout) {
3166
+ const timeout = this._timeout;
3167
+ const timer = this.setTimeoutFn(() => {
3168
+ openSubDestroy();
3169
+ onError(new Error("timeout"));
3170
+ socket.close();
3171
+ }, timeout);
3172
+ if (this.opts.autoUnref) {
3173
+ timer.unref();
3174
+ }
3175
+ this.subs.push(() => {
3176
+ this.clearTimeoutFn(timer);
3177
+ });
3178
+ }
3179
+ this.subs.push(openSubDestroy);
3180
+ this.subs.push(errorSub);
3181
+ return this;
3182
+ }
3183
+ /**
3184
+ * Alias for open()
3185
+ *
3186
+ * @return self
3187
+ * @public
3188
+ */
3189
+ connect(fn) {
3190
+ return this.open(fn);
3191
+ }
3192
+ /**
3193
+ * Called upon transport open.
3194
+ *
3195
+ * @private
3196
+ */
3197
+ onopen() {
3198
+ this.cleanup();
3199
+ this._readyState = "open";
3200
+ this.emitReserved("open");
3201
+ const socket = this.engine;
3202
+ this.subs.push(
3203
+ on(socket, "ping", this.onping.bind(this)),
3204
+ on(socket, "data", this.ondata.bind(this)),
3205
+ on(socket, "error", this.onerror.bind(this)),
3206
+ on(socket, "close", this.onclose.bind(this)),
3207
+ // @ts-ignore
3208
+ on(this.decoder, "decoded", this.ondecoded.bind(this))
3209
+ );
3210
+ }
3211
+ /**
3212
+ * Called upon a ping.
3213
+ *
3214
+ * @private
3215
+ */
3216
+ onping() {
3217
+ this.emitReserved("ping");
3218
+ }
3219
+ /**
3220
+ * Called with data.
3221
+ *
3222
+ * @private
3223
+ */
3224
+ ondata(data) {
3225
+ try {
3226
+ this.decoder.add(data);
3227
+ } catch (e) {
3228
+ this.onclose("parse error", e);
3229
+ }
3230
+ }
3231
+ /**
3232
+ * Called when parser fully decodes a packet.
3233
+ *
3234
+ * @private
3235
+ */
3236
+ ondecoded(packet) {
3237
+ nextTick(() => {
3238
+ this.emitReserved("packet", packet);
3239
+ }, this.setTimeoutFn);
3240
+ }
3241
+ /**
3242
+ * Called upon socket error.
3243
+ *
3244
+ * @private
3245
+ */
3246
+ onerror(err) {
3247
+ this.emitReserved("error", err);
3248
+ }
3249
+ /**
3250
+ * Creates a new socket for the given `nsp`.
3251
+ *
3252
+ * @return {Socket}
3253
+ * @public
3254
+ */
3255
+ socket(nsp, opts) {
3256
+ let socket = this.nsps[nsp];
3257
+ if (!socket) {
3258
+ socket = new Socket2(this, nsp, opts);
3259
+ this.nsps[nsp] = socket;
3260
+ } else if (this._autoConnect && !socket.active) {
3261
+ socket.connect();
3262
+ }
3263
+ return socket;
3264
+ }
3265
+ /**
3266
+ * Called upon a socket close.
3267
+ *
3268
+ * @param socket
3269
+ * @private
3270
+ */
3271
+ _destroy(socket) {
3272
+ const nsps = Object.keys(this.nsps);
3273
+ for (const nsp of nsps) {
3274
+ const socket2 = this.nsps[nsp];
3275
+ if (socket2.active) {
3276
+ return;
3277
+ }
3278
+ }
3279
+ this._close();
3280
+ }
3281
+ /**
3282
+ * Writes a packet.
3283
+ *
3284
+ * @param packet
3285
+ * @private
3286
+ */
3287
+ _packet(packet) {
3288
+ const encodedPackets = this.encoder.encode(packet);
3289
+ for (let i = 0; i < encodedPackets.length; i++) {
3290
+ this.engine.write(encodedPackets[i], packet.options);
3291
+ }
3292
+ }
3293
+ /**
3294
+ * Clean up transport subscriptions and packet buffer.
3295
+ *
3296
+ * @private
3297
+ */
3298
+ cleanup() {
3299
+ this.subs.forEach((subDestroy) => subDestroy());
3300
+ this.subs.length = 0;
3301
+ this.decoder.destroy();
3302
+ }
3303
+ /**
3304
+ * Close the current socket.
3305
+ *
3306
+ * @private
3307
+ */
3308
+ _close() {
3309
+ this.skipReconnect = true;
3310
+ this._reconnecting = false;
3311
+ this.onclose("forced close");
3312
+ }
3313
+ /**
3314
+ * Alias for close()
3315
+ *
3316
+ * @private
3317
+ */
3318
+ disconnect() {
3319
+ return this._close();
3320
+ }
3321
+ /**
3322
+ * Called when:
3323
+ *
3324
+ * - the low-level engine is closed
3325
+ * - the parser encountered a badly formatted packet
3326
+ * - all sockets are disconnected
3327
+ *
3328
+ * @private
3329
+ */
3330
+ onclose(reason, description) {
3331
+ var _a;
3332
+ this.cleanup();
3333
+ (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
3334
+ this.backoff.reset();
3335
+ this._readyState = "closed";
3336
+ this.emitReserved("close", reason, description);
3337
+ if (this._reconnection && !this.skipReconnect) {
3338
+ this.reconnect();
3339
+ }
3340
+ }
3341
+ /**
3342
+ * Attempt a reconnection.
3343
+ *
3344
+ * @private
3345
+ */
3346
+ reconnect() {
3347
+ if (this._reconnecting || this.skipReconnect)
3348
+ return this;
3349
+ const self2 = this;
3350
+ if (this.backoff.attempts >= this._reconnectionAttempts) {
3351
+ this.backoff.reset();
3352
+ this.emitReserved("reconnect_failed");
3353
+ this._reconnecting = false;
3354
+ } else {
3355
+ const delay = this.backoff.duration();
3356
+ this._reconnecting = true;
3357
+ const timer = this.setTimeoutFn(() => {
3358
+ if (self2.skipReconnect)
3359
+ return;
3360
+ this.emitReserved("reconnect_attempt", self2.backoff.attempts);
3361
+ if (self2.skipReconnect)
3362
+ return;
3363
+ self2.open((err) => {
3364
+ if (err) {
3365
+ self2._reconnecting = false;
3366
+ self2.reconnect();
3367
+ this.emitReserved("reconnect_error", err);
3368
+ } else {
3369
+ self2.onreconnect();
3370
+ }
3371
+ });
3372
+ }, delay);
3373
+ if (this.opts.autoUnref) {
3374
+ timer.unref();
3375
+ }
3376
+ this.subs.push(() => {
3377
+ this.clearTimeoutFn(timer);
3378
+ });
3379
+ }
3380
+ }
3381
+ /**
3382
+ * Called upon successful reconnect.
3383
+ *
3384
+ * @private
3385
+ */
3386
+ onreconnect() {
3387
+ const attempt = this.backoff.attempts;
3388
+ this._reconnecting = false;
3389
+ this.backoff.reset();
3390
+ this.emitReserved("reconnect", attempt);
3391
+ }
3392
+ };
3393
+
3394
+ // node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/index.js
3395
+ var cache = {};
3396
+ function lookup2(uri, opts) {
3397
+ if (typeof uri === "object") {
3398
+ opts = uri;
3399
+ uri = void 0;
3400
+ }
3401
+ opts = opts || {};
3402
+ const parsed = url(uri, opts.path || "/socket.io");
3403
+ const source = parsed.source;
3404
+ const id = parsed.id;
3405
+ const path = parsed.path;
3406
+ const sameNamespace = cache[id] && path in cache[id]["nsps"];
3407
+ const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
3408
+ let io;
3409
+ if (newConnection) {
3410
+ io = new Manager(source, opts);
3411
+ } else {
3412
+ if (!cache[id]) {
3413
+ cache[id] = new Manager(source, opts);
3414
+ }
3415
+ io = cache[id];
3416
+ }
3417
+ if (parsed.query && !opts.query) {
3418
+ opts.query = parsed.queryKey;
3419
+ }
3420
+ return io.socket(parsed.path, opts);
3421
+ }
3422
+ Object.assign(lookup2, {
3423
+ Manager,
3424
+ Socket: Socket2,
3425
+ io: lookup2,
3426
+ connect: lookup2
3427
+ });
3428
+
3429
+ // src/sdk/runtime.ts
3430
+ var SDK_TOKEN_KEY = "VanshiSdk_Token";
3431
+ var SDK_LOGIN_KEY = "VanshiSdk_isLogin";
3432
+ function getBrowserStorage() {
3433
+ if (typeof localStorage === "undefined") {
3434
+ return void 0;
3435
+ }
3436
+ return localStorage;
3437
+ }
3438
+ var SdkRuntimeError = class extends Error {
3439
+ constructor(result) {
3440
+ super(result.message || `SDK request failed${result.code !== void 0 ? `: ${String(result.code)}` : ""}`);
3441
+ this.name = "SdkRuntimeError";
3442
+ this.code = result.code;
3443
+ this.data = result.data;
3444
+ this.raw = result.raw;
3445
+ this.parsed = result.parsed;
3446
+ }
3447
+ };
3448
+ function parseJsonSafely(value2) {
3449
+ if (value2 == null) {
3450
+ return void 0;
3451
+ }
3452
+ if (typeof value2 !== "string") {
3453
+ return value2;
3454
+ }
3455
+ try {
3456
+ return JSON.parse(value2);
3457
+ } catch {
3458
+ return void 0;
3459
+ }
3460
+ }
3461
+ function isSuccessCode(code) {
3462
+ return code === 0 || code === "0" || code === true;
3463
+ }
3464
+ function toSdkEnvelope(response) {
3465
+ if (response && typeof response === "object") {
3466
+ return response;
3467
+ }
3468
+ return {};
3469
+ }
3470
+ function unwrapSdkData(response) {
3471
+ const result = unwrapSdkDetailedData(response);
3472
+ if (!result.success) {
3473
+ throw new SdkRuntimeError(result);
3474
+ }
3475
+ return result.data;
3476
+ }
3477
+ function unwrapSdkResponse(response) {
3478
+ const envelope = toSdkEnvelope(response);
3479
+ const parsed = parseJsonSafely(envelope.data);
3480
+ if (parsed && typeof parsed === "object" && "code" in parsed) {
3481
+ return parsed;
3482
+ }
3483
+ return {
3484
+ code: envelope.code,
3485
+ message: envelope.message,
3486
+ data: parsed !== void 0 ? parsed : envelope.data
3487
+ };
3488
+ }
3489
+ function unwrapSdkDetailedData(response) {
3490
+ const envelope = toSdkEnvelope(response);
3491
+ const parsed = parseJsonSafely(envelope.data);
3492
+ if (parsed && typeof parsed === "object" && "code" in parsed) {
3493
+ const success = isSuccessCode(parsed.code);
3494
+ return {
3495
+ success,
3496
+ code: parsed.code,
3497
+ message: parsed.message || envelope.message,
3498
+ data: parsed.data,
3499
+ raw: response,
3500
+ parsed
3501
+ };
3502
+ }
3503
+ if (envelope.code !== void 0 || envelope.message !== void 0) {
3504
+ return {
3505
+ success: isSuccessCode(envelope.code),
3506
+ code: envelope.code,
3507
+ message: envelope.message,
3508
+ data: parsed !== void 0 ? parsed : envelope.data,
3509
+ raw: response,
3510
+ parsed
3511
+ };
3512
+ }
3513
+ return {
3514
+ success: true,
3515
+ data: parsed !== void 0 ? parsed : envelope.data,
3516
+ raw: response,
3517
+ parsed
3518
+ };
3519
+ }
3520
+ function getStoredToken() {
3521
+ return getBrowserStorage()?.getItem(SDK_TOKEN_KEY) || "";
3522
+ }
3523
+ function setSdkSession(token) {
3524
+ const storage = getBrowserStorage();
3525
+ if (!storage) {
3526
+ return;
3527
+ }
3528
+ storage.setItem(SDK_TOKEN_KEY, token);
3529
+ storage.setItem(SDK_LOGIN_KEY, "true");
3530
+ }
3531
+ function clearSdkSession() {
3532
+ const storage = getBrowserStorage();
3533
+ if (!storage) {
3534
+ return;
3535
+ }
3536
+ storage.removeItem(SDK_TOKEN_KEY);
3537
+ storage.removeItem(SDK_LOGIN_KEY);
3538
+ }
3539
+ function getSocketUrl() {
3540
+ const globalUrl = typeof window !== "undefined" ? window.__VANSHI_SOCKET_URL : void 0;
3541
+ return globalUrl || "wss://ws-vanshi-chat-sdk.xchatclub.com";
3542
+ }
3543
+ function getUploadUrl() {
3544
+ const globalHttpUrl = typeof window !== "undefined" ? window.__VANSHI_HTTP_URL : void 0;
3545
+ return globalHttpUrl || "https://vanshi-chat-api.xchatclub.com/api/files/sdkUpload";
3546
+ }
3547
+
3548
+ // src/sdk/session.ts
3549
+ var reconnectLoginHandler = null;
3550
+ function registerReconnectLoginHandler(handler) {
3551
+ reconnectLoginHandler = handler;
3552
+ }
3553
+ async function restoreSessionAfterReconnect() {
3554
+ if (!reconnectLoginHandler) {
3555
+ return false;
3556
+ }
3557
+ const token = getStoredToken();
3558
+ if (!token) {
3559
+ return false;
3560
+ }
3561
+ try {
3562
+ return await reconnectLoginHandler(token);
3563
+ } catch {
3564
+ return false;
3565
+ }
3566
+ }
3567
+ function clearSessionState() {
3568
+ clearSdkSession();
3569
+ }
3570
+
3571
+ // src/plugins/socketio/client.ts
3572
+ function parseSocketConnectErrorPayload(value2) {
3573
+ if (!value2) {
3574
+ return void 0;
3575
+ }
3576
+ if (typeof value2 === "string") {
3577
+ try {
3578
+ const parsed = JSON.parse(value2);
3579
+ if (parsed && typeof parsed === "object") {
3580
+ return parsed;
3581
+ }
3582
+ } catch {
3583
+ return void 0;
3584
+ }
3585
+ }
3586
+ if (typeof value2 === "object") {
3587
+ return value2;
3588
+ }
3589
+ return void 0;
3590
+ }
3591
+ function normalizeSocketConnectError(error) {
3592
+ const rawMessage = error && typeof error === "object" && "message" in error ? error.message : void 0;
3593
+ const rawData = error && typeof error === "object" && "data" in error ? error.data : void 0;
3594
+ const payload = parseSocketConnectErrorPayload(rawData) || parseSocketConnectErrorPayload(rawMessage);
3595
+ const normalized = new Error(
3596
+ payload?.message || (typeof rawMessage === "string" ? rawMessage : "") || "socket connect failed"
3597
+ );
3598
+ normalized.name = "SocketConnectError";
3599
+ normalized.code = payload?.code;
3600
+ normalized.data = payload;
3601
+ normalized.requestId = payload?.requestId;
3602
+ normalized.raw = error;
3603
+ return normalized;
3604
+ }
3605
+ var SocketClient = class {
3606
+ constructor() {
3607
+ this.pending = /* @__PURE__ */ new Map();
3608
+ this.emitQueue = [];
3609
+ this.connectPromise = null;
3610
+ this.url = "";
3611
+ this.handleResponse = (res) => {
3612
+ const entry = this.pending.get(res.id);
3613
+ if (!entry)
3614
+ return;
3615
+ clearTimeout(entry.timer);
3616
+ this.pending.delete(res.id);
3617
+ res.error ? entry.reject(res.error) : entry.resolve(res.payload);
3618
+ };
3619
+ }
3620
+ connect(url2, auth, opts = {}) {
3621
+ if (this.connectPromise)
3622
+ return this.connectPromise;
3623
+ if (this.isConnected())
3624
+ return Promise.resolve();
3625
+ if (this.socket) {
3626
+ try {
3627
+ this.socket.off();
3628
+ this.socket.io.off();
3629
+ this.socket = void 0;
3630
+ } catch {
3631
+ }
3632
+ }
3633
+ if (this.isConnected())
3634
+ return Promise.resolve();
3635
+ const { baseUrl, namespace } = this.parseUrl(url2);
3636
+ this.url = url2;
3637
+ const ioOpts = {
3638
+ ...opts,
3639
+ transports: ["websocket"],
3640
+ // 🔥 只保留 websocket,不会多条连接
3641
+ query: { namespace },
3642
+ forceNew: true,
3643
+ reconnection: true,
3644
+ reconnectionAttempts: 9999,
3645
+ reconnectionDelay: 1e4,
3646
+ timeout: 15e3
3647
+ };
3648
+ this.connectPromise = new Promise((resolve, reject) => {
3649
+ const socket = lookup2(`${baseUrl}/im/user`, ioOpts);
3650
+ this.socket = socket;
3651
+ console.log("[SocketClient] \u65B0\u8FDE\u63A5\u521B\u5EFA\uFF1A", `${baseUrl}/im/user`);
3652
+ const handleConnect = () => {
3653
+ socket.off("connect_error", handleError);
3654
+ socket.on("api:response", this.handleResponse);
3655
+ this.processEmitQueue();
3656
+ resolve();
3657
+ };
3658
+ const handleError = (err) => {
3659
+ const normalizedError = normalizeSocketConnectError(err);
3660
+ console.error("[SocketClient] \u8FDE\u63A5\u5931\u8D25\uFF1A:", normalizedError);
3661
+ socket.off("connect", handleConnect);
3662
+ reject(normalizedError);
3663
+ };
3664
+ socket.once("connect", handleConnect);
3665
+ socket.once("connect_error", handleError);
3666
+ socket.on("disconnect", (reason) => {
3667
+ this.cleanupAllPending("disconnected: " + reason);
3668
+ this.connectPromise = null;
3669
+ });
3670
+ socket.io.off("reconnect");
3671
+ socket.io.on("reconnect", async () => {
3672
+ console.log("[SocketClient] \u91CD\u8FDE\u6210\u529F \u2192 \u7B49\u5F85 socket \u5B8C\u5168\u5C31\u7EEA", this.socket?.connected);
3673
+ await new Promise(
3674
+ (resolveReconnect) => setTimeout(resolveReconnect, 200)
3675
+ );
3676
+ if (!this.isConnected() || !this.socket) {
3677
+ console.log("[SocketClient] socket \u672A\u5C31\u7EEA\uFF0C\u8DF3\u8FC7\u767B\u5F55");
3678
+ return;
3679
+ }
3680
+ try {
3681
+ console.log("[SocketClient] \u5F00\u59CB\u81EA\u52A8\u767B\u5F55 \u2705");
3682
+ const res = await restoreSessionAfterReconnect();
3683
+ if (res) {
3684
+ this.processEmitQueue();
3685
+ } else {
3686
+ clearSessionState();
3687
+ }
3688
+ } catch (err) {
3689
+ console.error("[SocketClient] \u81EA\u52A8\u767B\u5F55\u5931\u8D25", err);
3690
+ clearSessionState();
3691
+ }
3692
+ });
3693
+ });
3694
+ this.connectPromise.finally(() => {
3695
+ this.connectPromise = null;
3696
+ });
3697
+ return this.connectPromise;
3698
+ }
3699
+ disconnect() {
3700
+ if (!this.socket)
3701
+ return;
3702
+ try {
3703
+ this.socket.off("api:response", this.handleResponse);
3704
+ this.socket.io.off("reconnect");
3705
+ this.socket.disconnect();
3706
+ } catch {
3707
+ }
3708
+ this.socket = void 0;
3709
+ this.cleanupAllPending("client disconnected");
3710
+ }
3711
+ emitWithAck(event, payload, timeoutMs = 1e4) {
3712
+ if (this.isConnected()) {
3713
+ return this.createEmitPromise(event, payload, timeoutMs);
3714
+ }
3715
+ if (this.connectPromise) {
3716
+ return new Promise((resolve, reject) => {
3717
+ this.emitQueue.push({ event, payload, timeoutMs, resolve, reject });
3718
+ });
3719
+ }
3720
+ return Promise.reject(new Error("socket not initialized"));
3721
+ }
3722
+ request(path, payload, timeoutMs = 1e4) {
3723
+ if (!this.socket) {
3724
+ return Promise.reject(new Error("socket not initialized"));
3725
+ }
3726
+ const id = this.generateId();
3727
+ const envelope = { id, path, payload };
3728
+ return new Promise((resolve, reject) => {
3729
+ const timer = setTimeout(() => {
3730
+ this.pending.delete(id);
3731
+ reject(new Error("request timeout"));
3732
+ }, timeoutMs);
3733
+ this.pending.set(id, { resolve, reject, timer });
3734
+ try {
3735
+ this.socket.emit("api:request", envelope);
3736
+ } catch (err) {
3737
+ clearTimeout(timer);
3738
+ this.pending.delete(id);
3739
+ reject(err);
3740
+ }
3741
+ });
3742
+ }
3743
+ on(event, handler) {
3744
+ this.socket?.on(event, handler);
3745
+ }
3746
+ off(event, handler) {
3747
+ if (!this.socket)
3748
+ return;
3749
+ handler ? this.socket.off(event, handler) : this.socket.off(event);
3750
+ }
3751
+ isConnected() {
3752
+ return !!this.socket?.connected;
3753
+ }
3754
+ parseUrl(url2) {
3755
+ let baseUrl = url2;
3756
+ let namespace = "/im/user";
3757
+ try {
3758
+ const urlObj = new URL(url2);
3759
+ const queryNs = urlObj.searchParams.get("namespace");
3760
+ if (queryNs)
3761
+ namespace = queryNs;
3762
+ baseUrl = urlObj.origin + urlObj.pathname.replace(/\/$/, "");
3763
+ } catch {
3764
+ console.warn("[Socket] URL parse failed:", url2);
3765
+ }
3766
+ return { baseUrl, namespace };
3767
+ }
3768
+ generateId() {
3769
+ return Date.now().toString(36) + Math.random().toString(36).slice(2, 9);
3770
+ }
3771
+ createEmitPromise(event, payload, timeoutMs) {
3772
+ return new Promise((resolve, reject) => {
3773
+ let timedOut = false;
3774
+ const timer = setTimeout(() => {
3775
+ timedOut = true;
3776
+ reject(new Error("ack timeout"));
3777
+ }, timeoutMs);
3778
+ try {
3779
+ this.socket.emit(event, payload, (response) => {
3780
+ if (timedOut)
3781
+ return;
3782
+ clearTimeout(timer);
3783
+ if (response?.code !== void 0) {
3784
+ isSuccessCode(response.code) ? resolve(response) : reject(new Error(response.message || `code=${response.code}`));
3785
+ } else {
3786
+ resolve(response);
3787
+ }
3788
+ });
3789
+ } catch (err) {
3790
+ clearTimeout(timer);
3791
+ reject(err);
3792
+ }
3793
+ });
3794
+ }
3795
+ processEmitQueue() {
3796
+ if (!this.isConnected())
3797
+ return;
3798
+ while (this.emitQueue.length) {
3799
+ const item = this.emitQueue.shift();
3800
+ this.createEmitPromise(item.event, item.payload, item.timeoutMs).then(item.resolve).catch(item.reject);
3801
+ }
3802
+ }
3803
+ cleanupAllPending(reason) {
3804
+ for (const [, entry] of this.pending) {
3805
+ clearTimeout(entry.timer);
3806
+ entry.reject(new Error(reason));
3807
+ }
3808
+ this.pending.clear();
3809
+ for (const item of this.emitQueue) {
3810
+ item.reject(new Error(reason));
3811
+ }
3812
+ this.emitQueue = [];
3813
+ }
3814
+ };
3815
+ var socketClient = new SocketClient();
3816
+ var client_default = socketClient;
3817
+
3818
+ // src/plugins/request/index.ts
3819
+ async function request(config) {
3820
+ if (!config || !config.path) {
3821
+ return Promise.reject(new Error("invalid request config"));
3822
+ }
3823
+ const path = config.path;
3824
+ const isSdkApi = path.startsWith("/sdk/") || path.startsWith("sdk/");
3825
+ if (isSdkApi) {
3826
+ const eventName = path.replace(/^\/?sdk\//, "");
3827
+ const timeoutMs2 = typeof config.timeoutMs === "number" ? config.timeoutMs : 1e4;
3828
+ if (!client_default.isConnected()) {
3829
+ return Promise.reject(new Error("socket not connected"));
3830
+ }
3831
+ try {
3832
+ const res = await client_default.emitWithAck(
3833
+ eventName,
3834
+ config.data,
3835
+ timeoutMs2
3836
+ );
3837
+ if (res && typeof res === "object" && typeof res.code === "number") {
3838
+ return res;
3839
+ }
3840
+ return { code: 0, message: "", data: res };
3841
+ } catch (err) {
3842
+ return Promise.reject(err);
3843
+ }
3844
+ }
3845
+ if (!client_default.isConnected()) {
3846
+ return Promise.reject(new Error("socket not connected"));
3847
+ }
3848
+ const timeoutMs = typeof config.timeoutMs === "number" ? config.timeoutMs : 1e4;
3849
+ return client_default.request(config.path, config.data, timeoutMs);
3850
+ }
3851
+
3852
+ // src/apis/SdkQueryConversationPostApi.ts
3853
+ var postSdkQueryConversationApiRequest = (data) => {
3854
+ return request({
3855
+ path: "/sdk/queryConversation",
3856
+ method: "POST",
3857
+ data
3858
+ });
3859
+ };
3860
+
3861
+ // src/apis/SdkDeleteAllConversationsPostApi.ts
3862
+ var postSdkDeleteAllConversationsApiRequest = (data) => {
3863
+ return request({
3864
+ path: "/sdk/deleteAllConversations",
3865
+ method: "POST",
3866
+ data
3867
+ });
3868
+ };
3869
+
3870
+ // src/apis/SdkDeleteConversationPostApi.ts
3871
+ var postSdkDeleteConversationApiRequest = (data) => {
3872
+ return request({
3873
+ path: "/sdk/deleteConversation",
3874
+ method: "POST",
3875
+ data
3876
+ });
3877
+ };
3878
+
3879
+ // src/apis/SdkClearConversationTotalUnreadMessageCountPostApi.ts
3880
+ var postSdkClearConversationTotalUnreadMessageCountApiRequest = (data) => {
3881
+ return request({
3882
+ path: "/sdk/clearConversationTotalUnreadMessageCount",
3883
+ method: "POST",
3884
+ data
3885
+ });
3886
+ };
3887
+
3888
+ // src/apis/SdkClearConversationUnreadMessageCountPostApi.ts
3889
+ var postSdkClearConversationUnreadMessageCountApiRequest = (data) => {
3890
+ return request({
3891
+ path: "/sdk/clearConversationUnreadMessageCount",
3892
+ method: "POST",
3893
+ data
3894
+ });
3895
+ };
3896
+
3897
+ // src/sdk/conversation.ts
3898
+ async function queryConversation(payload) {
3899
+ const response = await postSdkQueryConversationApiRequest(payload);
3900
+ return unwrapSdkData(response) ?? [];
3901
+ }
3902
+ async function deleteAllConversations() {
3903
+ const response = await postSdkDeleteAllConversationsApiRequest(
3904
+ { config: true }
3905
+ );
3906
+ return unwrapSdkResponse(response);
3907
+ }
3908
+ async function deleteConversation(payload) {
3909
+ const response = await postSdkDeleteConversationApiRequest(payload);
3910
+ return unwrapSdkResponse(response);
3911
+ }
3912
+ async function clearConversationTotalUnreadMessageCount() {
3913
+ const response = await postSdkClearConversationTotalUnreadMessageCountApiRequest(
3914
+ {}
3915
+ );
3916
+ return unwrapSdkResponse(response);
3917
+ }
3918
+ async function clearConversationUnreadMessageCount(conversationID, conversationType) {
3919
+ const response = await postSdkClearConversationUnreadMessageCountApiRequest(
3920
+ {
3921
+ conversationID,
3922
+ conversationType: String(conversationType)
3923
+ }
3924
+ );
3925
+ return unwrapSdkResponse(response);
3926
+ }
3927
+
3928
+ // src/sdk/initSocket.ts
3929
+ async function initSocket() {
3930
+ const baseUrl = getSocketUrl();
3931
+ if (!client_default.isConnected()) {
3932
+ await client_default.connect(baseUrl);
3933
+ }
3934
+ }
3935
+ function isSocketConnected() {
3936
+ return client_default.isConnected();
3937
+ }
3938
+ function on2(event, handler) {
3939
+ client_default.on(event, handler);
3940
+ }
3941
+ function off(event, handler) {
3942
+ client_default.off(event, handler);
3943
+ }
3944
+
3945
+ // src/apis/SdkLoginPostApi.ts
3946
+ var postSdkLoginApiRequest = (data) => {
3947
+ return request({
3948
+ path: "/sdk/login",
3949
+ method: "POST",
3950
+ data
3951
+ });
3952
+ };
3953
+ var postSdkLogoutApiRequest = (data) => {
3954
+ return request({
3955
+ path: "/sdk/logout",
3956
+ method: "POST",
3957
+ data
3958
+ });
3959
+ };
3960
+
3961
+ // src/sdk/loginCore.ts
3962
+ async function performLogin(payload, { requestLogin, setSession = setSdkSession, clearSession = clearSdkSession }) {
3963
+ try {
3964
+ const resp = await requestLogin(payload);
3965
+ if (unwrapSdkData(resp)) {
3966
+ setSession(payload.token);
3967
+ return true;
3968
+ }
3969
+ } catch (error) {
3970
+ clearSession();
3971
+ throw error;
3972
+ }
3973
+ clearSession();
3974
+ return false;
3975
+ }
3976
+
3977
+ // src/sdk/login.ts
3978
+ async function login(payload) {
3979
+ return performLogin(payload, {
3980
+ requestLogin: postSdkLoginApiRequest
3981
+ });
3982
+ }
3983
+ registerReconnectLoginHandler((token) => login({ token }));
3984
+ async function logout(disconnect = true) {
3985
+ let success = false;
3986
+ try {
3987
+ const resp = await postSdkLogoutApiRequest(
3988
+ {}
3989
+ );
3990
+ let res = JSON.parse(resp);
3991
+ const result = unwrapSdkData(res);
3992
+ success = Boolean(result) || isSuccessCode(res.code);
3993
+ } catch {
3994
+ success = false;
3995
+ } finally {
3996
+ clearSdkSession();
3997
+ }
3998
+ return success;
3999
+ }
4000
+
4001
+ // src/apis/SdkSendMessagePostApi.ts
4002
+ var postSdkSendMessageApiRequest = (data) => {
4003
+ return request({
4004
+ path: "/sdk/sendMessage",
4005
+ method: "POST",
4006
+ data
4007
+ });
4008
+ };
4009
+
4010
+ // src/apis/SdkSendMediaMessagePostApi.ts
4011
+ var postSdkSendMediaMessageApiRequest = (data) => {
4012
+ return request({
4013
+ path: "/sdk/sendMediaMessage",
4014
+ method: "POST",
4015
+ data
4016
+ });
4017
+ };
4018
+
4019
+ // src/apis/SdkQueryHistoryMessagePostApi.ts
4020
+ var postSdkQueryHistoryMessageApiRequest = (data) => {
4021
+ return request({
4022
+ path: "/sdk/queryHistoryMessage",
4023
+ method: "POST",
4024
+ data
4025
+ });
4026
+ };
4027
+
4028
+ // src/apis/SdkDeleteAllConversationMessagesPostApi.ts
4029
+ var postSdkDeleteAllConversationMessagesApiRequest = (data) => {
4030
+ return request({
4031
+ path: "/sdk/deleteAllConversationMessages",
4032
+ method: "POST",
4033
+ data
4034
+ });
4035
+ };
4036
+
4037
+ // src/apis/SdkDeleteMessagesPostApi.ts
4038
+ var postSdkDeleteMessagesApiRequest = (data) => {
4039
+ return request({
4040
+ path: "/sdk/deleteMessages",
4041
+ method: "POST",
4042
+ data
4043
+ });
4044
+ };
4045
+
4046
+ // src/apis/SdkRevokeMessagePostApi.ts
4047
+ var postSdkRevokeMessageApiRequest = (data) => {
4048
+ return request({
4049
+ path: "/sdk/revokeMessage",
4050
+ method: "POST",
4051
+ data
4052
+ });
4053
+ };
4054
+
4055
+ // helper/index.ts
4056
+ function isSameUid(id, uid) {
4057
+ return id?.toString() === uid?.toString();
4058
+ }
4059
+ var getVideoDurationAndFirstFrame = (file) => {
4060
+ return new Promise((resolve, reject) => {
4061
+ const video = document.createElement("video");
4062
+ const canvas = document.createElement("canvas");
4063
+ const ctx = canvas.getContext("2d");
4064
+ let duration = 0;
4065
+ let videoWidth = 0;
4066
+ let videoHeight = 0;
4067
+ video.preload = "metadata";
4068
+ video.muted = true;
4069
+ video.playsInline = true;
4070
+ video.autoplay = true;
4071
+ video.onloadedmetadata = () => {
4072
+ canvas.width = video.videoWidth || 640;
4073
+ canvas.height = video.videoHeight || 360;
4074
+ window.URL.revokeObjectURL(video.src);
4075
+ duration = video?.duration;
4076
+ videoWidth = video.videoWidth || 640;
4077
+ videoHeight = video.videoHeight || 360;
4078
+ };
4079
+ video.oncanplay = () => {
4080
+ video.oncanplay = null;
4081
+ video.pause();
4082
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
4083
+ canvas.toBlob(
4084
+ (blob) => {
4085
+ if (!blob) {
4086
+ reject(new Error("\u622A\u53D6\u7B2C\u4E00\u5E27\u5931\u8D25"));
4087
+ return;
4088
+ }
4089
+ const firstFrameFile = new File(
4090
+ [blob],
4091
+ `video_first_frame_${Date.now()}.jpg`,
4092
+ { type: "image/jpeg" }
4093
+ );
4094
+ URL.revokeObjectURL(video.src);
4095
+ video.src = "";
4096
+ canvas.width = 0;
4097
+ canvas.height = 0;
4098
+ resolve({
4099
+ duration,
4100
+ firstFrameFile,
4101
+ // 这就是你要的文件流
4102
+ videoWidth,
4103
+ videoHeight
4104
+ });
4105
+ },
4106
+ "image/jpeg",
4107
+ 0.9
4108
+ // 图片质量 0-1
4109
+ );
4110
+ };
4111
+ video.onerror = () => {
4112
+ URL.revokeObjectURL(video.src);
4113
+ reject(new Error("\u89C6\u9891\u6587\u4EF6\u635F\u574F\u6216\u683C\u5F0F\u4E0D\u652F\u6301"));
4114
+ };
4115
+ video.src = URL.createObjectURL(file);
4116
+ });
4117
+ };
4118
+ function getAudioDuration(file) {
4119
+ return new Promise((resolve, reject) => {
4120
+ const audio = document.createElement("audio");
4121
+ audio.preload = "metadata";
4122
+ audio.onloadedmetadata = () => {
4123
+ const duration = audio.duration;
4124
+ URL.revokeObjectURL(audio.src);
4125
+ resolve(duration);
4126
+ };
4127
+ audio.onerror = () => {
4128
+ URL.revokeObjectURL(audio.src);
4129
+ reject(new Error("\u97F3\u9891\u6587\u4EF6\u65E0\u6CD5\u8BFB\u53D6\u6216\u683C\u5F0F\u4E0D\u652F\u6301"));
4130
+ };
4131
+ audio.src = URL.createObjectURL(file);
4132
+ });
4133
+ }
4134
+
4135
+ // src/apis/SdkDeleteAllMessagePostApi.ts
4136
+ var postSdkDeleteAllMessageApiRequest = (data) => {
4137
+ return request({
4138
+ path: "/sdk/deleteAllMessage",
4139
+ method: "POST",
4140
+ data
4141
+ });
4142
+ };
4143
+
4144
+ // src/sdk/message.ts
4145
+ async function getImageSize(file) {
4146
+ return new Promise((resolve, reject) => {
4147
+ const url2 = URL.createObjectURL(file);
4148
+ const img = new Image();
4149
+ img.onload = () => {
4150
+ resolve({
4151
+ width: img.naturalWidth,
4152
+ height: img.naturalHeight
4153
+ });
4154
+ URL.revokeObjectURL(url2);
4155
+ };
4156
+ img.onerror = () => {
4157
+ URL.revokeObjectURL(url2);
4158
+ reject(new Error("\u56FE\u7247\u6587\u4EF6\u65E0\u6CD5\u8BFB\u53D6\u6216\u683C\u5F0F\u4E0D\u652F\u6301"));
4159
+ };
4160
+ img.src = url2;
4161
+ });
4162
+ }
4163
+ async function uploadSdkFile(file) {
4164
+ const formData = new FormData();
4165
+ formData.append("file", file);
4166
+ const response = await fetch(getUploadUrl(), {
4167
+ method: "POST",
4168
+ headers: {
4169
+ Authorization: getStoredToken()
4170
+ },
4171
+ body: formData
4172
+ });
4173
+ if (!response.ok) {
4174
+ throw new Error(`file upload failed: ${response.status}`);
4175
+ }
4176
+ const payload = await response.json();
4177
+ if (payload.Code !== 0 && payload.Code !== "0") {
4178
+ throw new Error(payload.Message || "file upload failed");
4179
+ }
4180
+ if (!payload.Result) {
4181
+ throw new Error("file upload result is empty");
4182
+ }
4183
+ return payload.Result;
4184
+ }
4185
+ async function enrichMediaMessage(message) {
4186
+ const file = message.file;
4187
+ if (!file) {
4188
+ throw new Error("media message file is required");
4189
+ }
4190
+ const enrichedMessage = {
4191
+ ...message,
4192
+ fileName: file.name || message.fileName || "",
4193
+ fileSize: String(file.size)
4194
+ };
4195
+ if (isSameUid(message.type, "11" /* Image */)) {
4196
+ const { width, height } = await getImageSize(file);
4197
+ enrichedMessage.thumbnailWidth = String(width);
4198
+ enrichedMessage.thumbnailHeight = String(height);
4199
+ } else if (isSameUid(message.type, "13" /* Audio */)) {
4200
+ const duration = await getAudioDuration(file);
4201
+ enrichedMessage.duration = String(duration);
4202
+ } else if (isSameUid(message.type, "14" /* Video */)) {
4203
+ const res = await getVideoDurationAndFirstFrame(file);
4204
+ enrichedMessage.duration = String(res.duration);
4205
+ enrichedMessage.thumbnailWidth = String(res.videoWidth);
4206
+ enrichedMessage.thumbnailHeight = String(res.videoHeight);
4207
+ enrichedMessage.thumbnailDownloadUrl = await uploadSdkFile(res.firstFrameFile);
4208
+ }
4209
+ const fileDownloadUrl = await uploadSdkFile(file);
4210
+ enrichedMessage.fileDownloadUrl = fileDownloadUrl;
4211
+ if (isSameUid(message.type, "11" /* Image */)) {
4212
+ enrichedMessage.thumbnailDownloadUrl = fileDownloadUrl;
4213
+ }
4214
+ delete enrichedMessage.file;
4215
+ return enrichedMessage;
4216
+ }
4217
+ async function sendMessage(payload) {
4218
+ const response = await postSdkSendMessageApiRequest(payload);
4219
+ return unwrapSdkData(response);
4220
+ }
4221
+ async function sendMediaMessage(payload) {
4222
+ const response = await postSdkSendMediaMessageApiRequest({
4223
+ ...payload,
4224
+ message: await enrichMediaMessage(payload.message)
4225
+ });
4226
+ return unwrapSdkData(response);
4227
+ }
4228
+ async function queryHistoryMessage(payload) {
4229
+ const response = await postSdkQueryHistoryMessageApiRequest(payload);
4230
+ return unwrapSdkData(response);
4231
+ }
4232
+ async function deleteAllConversationMessages() {
4233
+ const response = await postSdkDeleteAllConversationMessagesApiRequest(
4234
+ {
4235
+ config: {
4236
+ isAlsoDeleteServerMessage: true
4237
+ // 是否同时删除服务器消息,默认为 false
4238
+ }
4239
+ }
4240
+ );
4241
+ return unwrapSdkResponse(response);
4242
+ }
4243
+ async function deleteMessages(conversationID, conversationType, messageList) {
4244
+ const response = await postSdkDeleteMessagesApiRequest({
4245
+ conversationID: Number(conversationID),
4246
+ conversationType: conversationType.toString(),
4247
+ messageList: messageList.map((msg) => ({
4248
+ messageID: msg.messageID,
4249
+ type: Number(msg.type)
4250
+ }))
4251
+ });
4252
+ return unwrapSdkResponse(response);
4253
+ }
4254
+ async function revokeMessage(message, config) {
4255
+ const response = await postSdkRevokeMessageApiRequest({ message, config });
4256
+ return unwrapSdkResponse(response);
4257
+ }
4258
+ async function deleteAllMessage(conversationID, conversationType) {
4259
+ const response = await postSdkDeleteAllMessageApiRequest({
4260
+ conversationID: Number(conversationID),
4261
+ conversationType: conversationType.toString()
4262
+ });
4263
+ return unwrapSdkResponse(response);
4264
+ }
4265
+
4266
+ // src/apis/SdkQueryGroupMessageReceiptReadMemberListPostApi.ts
4267
+ var postSdkQueryGroupMessageReceiptReadMemberListApiRequest = (data) => {
4268
+ return request({
4269
+ path: "/sdk/queryGroupMessageReceiptReadMemberList",
4270
+ method: "POST",
4271
+ data
4272
+ });
4273
+ };
4274
+
4275
+ // src/apis/SdkQueryGroupMessageReceiptUnreadMemberListPostApi.ts
4276
+ var postSdkQueryGroupMessageReceiptUnreadMemberListApiRequest = (data) => {
4277
+ return request({
4278
+ path: "/sdk/queryGroupMessageReceiptUnreadMemberList",
4279
+ method: "POST",
4280
+ data
4281
+ });
4282
+ };
4283
+
4284
+ // src/apis/SdkQueryMessageReceiptsInfoPostApi.ts
4285
+ var postSdkQueryMessageReceiptsInfoApiRequest = (data) => {
4286
+ return request({
4287
+ path: "/sdk/queryMessageReceiptsInfo",
4288
+ method: "POST",
4289
+ data
4290
+ });
4291
+ };
4292
+
4293
+ // src/apis/SdkSendMessageReceiptsReadPostApi.ts
4294
+ var postSdkSendMessageReceiptsReadApiRequest = (data) => {
4295
+ return request({
4296
+ path: "/sdk/sendMessageReceiptsRead",
4297
+ method: "POST",
4298
+ data
4299
+ });
4300
+ };
4301
+
4302
+ // src/sdk/messageReceipts.ts
4303
+ async function sendMessageReceiptsRead(conversationID, conversationType, messageList) {
4304
+ const response = await postSdkSendMessageReceiptsReadApiRequest({
4305
+ conversationID,
4306
+ conversationType: conversationType.toString(),
4307
+ messageList
4308
+ });
4309
+ return unwrapSdkResponse(response);
4310
+ }
4311
+ async function queryMessageReceiptsInfo(conversationID, conversationType, messageList) {
4312
+ const response = await postSdkQueryMessageReceiptsInfoApiRequest({
4313
+ conversationID: Number(conversationID),
4314
+ conversationType: conversationType.toString(),
4315
+ messageList
4316
+ });
4317
+ return unwrapSdkResponse(response);
4318
+ }
4319
+ async function queryGroupMessageReceiptUnreadMemberList(groupID, config, message) {
4320
+ const response = await postSdkQueryGroupMessageReceiptUnreadMemberListApiRequest({
4321
+ groupID,
4322
+ config,
4323
+ message
4324
+ });
4325
+ return unwrapSdkResponse(response);
4326
+ }
4327
+ async function queryGroupMessageReceiptReadMemberList(groupID, config, message) {
4328
+ const response = await postSdkQueryGroupMessageReceiptReadMemberListApiRequest({
4329
+ groupID,
4330
+ config,
4331
+ message
4332
+ });
4333
+ return unwrapSdkResponse(response);
4334
+ }
4335
+
4336
+ // src/sdk/index.ts
4337
+ var VanshiSdk = {
4338
+ // 创建 ws 实例
4339
+ create: initSocket,
4340
+ // 退出 SDK 登录并断开 ws 连接
4341
+ logout,
4342
+ // 判断当前 ws 是否连接
4343
+ isConnected: isSocketConnected,
4344
+ // 监听推送事件
4345
+ on: on2,
4346
+ // 解除推送事件监听
4347
+ off,
4348
+ // 登录 SDK
4349
+ login,
4350
+ // 查询会话列表
4351
+ queryConversation,
4352
+ // 删除全部会话列表
4353
+ deleteAllConversations,
4354
+ // 删除单个会话
4355
+ deleteConversation,
4356
+ // 清除全部会话未读数
4357
+ clearConversationTotalUnreadMessageCount,
4358
+ // 清除单个会话未读数
4359
+ clearConversationUnreadMessageCount,
4360
+ // 查询历史消息
4361
+ queryHistoryMessage,
4362
+ // 发送文本消息
4363
+ sendMessage,
4364
+ // 发送媒体消息
4365
+ sendMediaMessage,
4366
+ // 删除全部会话消息
4367
+ deleteAllConversationMessages,
4368
+ // 删除指定消息
4369
+ deleteMessages,
4370
+ // 删除当前会话全部消息
4371
+ deleteAllMessage,
4372
+ // 撤回消息
4373
+ revokeMessage,
4374
+ // 发送已读回执
4375
+ sendMessageReceiptsRead,
4376
+ // 查询一批消息回执信息
4377
+ queryMessageReceiptsInfo,
4378
+ // 查询群消息未读成员列表。
4379
+ queryGroupMessageReceiptUnreadMemberList,
4380
+ // 查询群消息已读成员列表。
4381
+ queryGroupMessageReceiptReadMemberList
4382
+ };
4383
+ var sdk_default = VanshiSdk;
4384
+ return __toCommonJS(browser_exports);
4385
+ })();
4386
+ VanshiSdk = VanshiSdk.VanshiSdk;