@danidoble/webserial 4.5.0-alpha.4 → 4.5.0-alpha.5

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.
Files changed (39) hide show
  1. package/dist/boardroid.cjs +1 -0
  2. package/dist/boardroid.js +766 -0
  3. package/dist/devices-2YN3FSHn.js +67 -0
  4. package/dist/devices-CcYKrJpP.cjs +1 -0
  5. package/dist/hopper.cjs +2 -0
  6. package/dist/hopper.js +254 -0
  7. package/dist/jofemar.cjs +1 -0
  8. package/dist/jofemar.js +1199 -0
  9. package/dist/jsd.cjs +1 -0
  10. package/dist/jsd.js +2530 -0
  11. package/dist/kernel-BhNOFt2M.js +774 -0
  12. package/dist/kernel-c6KuKgQ5.cjs +1 -0
  13. package/dist/kernel.cjs +1 -0
  14. package/dist/kernel.js +8 -0
  15. package/dist/locker.cjs +1 -0
  16. package/dist/locker.js +155 -0
  17. package/dist/pinpad.cjs +19 -0
  18. package/dist/pinpad.js +5455 -0
  19. package/dist/pinpax.cjs +4 -0
  20. package/dist/pinpax.js +408 -0
  21. package/dist/relay-DP8PLsDP.js +1340 -0
  22. package/dist/relay-E3NCcSjS.cjs +3 -0
  23. package/dist/relay.cjs +1 -0
  24. package/dist/relay.js +42 -0
  25. package/dist/types/lib/serial/boardroid.d.ts.map +1 -1
  26. package/dist/types/lib/serial/jofemar.d.ts.map +1 -1
  27. package/dist/types/lib/serial/jsd.d.ts.map +1 -1
  28. package/dist/types/lib/serial/kernel.d.ts.map +1 -1
  29. package/dist/types/lib/serial/locker.d.ts.map +1 -1
  30. package/dist/types/lib/serial/pinpad.d.ts.map +1 -1
  31. package/dist/types/lib/serial/pinpax.d.ts.map +1 -1
  32. package/dist/types/lib/serial/relay.d.ts.map +1 -1
  33. package/dist/types/lib/utils/devices.d.ts +18 -18
  34. package/dist/types/lib/utils/devices.d.ts.map +1 -1
  35. package/dist/webserial-core-CrutKvJa.cjs +4 -0
  36. package/dist/webserial-core-WmZ6i1ql.js +3524 -0
  37. package/dist/webserial.cjs +1 -0
  38. package/dist/webserial.js +36 -0
  39. package/package.json +1 -1
@@ -0,0 +1,3524 @@
1
+ const m = /* @__PURE__ */ Object.create(null);
2
+ m.open = "0";
3
+ m.close = "1";
4
+ m.ping = "2";
5
+ m.pong = "3";
6
+ m.message = "4";
7
+ m.upgrade = "5";
8
+ m.noop = "6";
9
+ const S = /* @__PURE__ */ Object.create(null);
10
+ Object.keys(m).forEach((n) => {
11
+ S[m[n]] = n;
12
+ });
13
+ const q = { type: "error", data: "parser error" }, te = typeof Blob == "function" || typeof Blob < "u" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]", se = typeof ArrayBuffer == "function", ne = (n) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(n) : n && n.buffer instanceof ArrayBuffer, H = ({ type: n, data: e }, t, s) => te && e instanceof Blob ? t ? s(e) : J(e, s) : se && (e instanceof ArrayBuffer || ne(e)) ? t ? s(e) : J(new Blob([e]), s) : s(m[n] + (e || "")), J = (n, e) => {
14
+ const t = new FileReader();
15
+ return t.onload = function() {
16
+ const s = t.result.split(",")[1];
17
+ e("b" + (s || ""));
18
+ }, t.readAsDataURL(n);
19
+ };
20
+ function j(n) {
21
+ return n instanceof Uint8Array ? n : n instanceof ArrayBuffer ? new Uint8Array(n) : new Uint8Array(n.buffer, n.byteOffset, n.byteLength);
22
+ }
23
+ let P;
24
+ function de(n, e) {
25
+ if (te && n.data instanceof Blob)
26
+ return n.data.arrayBuffer().then(j).then(e);
27
+ if (se && (n.data instanceof ArrayBuffer || ne(n.data)))
28
+ return e(j(n.data));
29
+ H(n, !1, (t) => {
30
+ P || (P = new TextEncoder()), e(P.encode(t));
31
+ });
32
+ }
33
+ const Q = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", C = typeof Uint8Array > "u" ? [] : new Uint8Array(256);
34
+ for (let n = 0; n < Q.length; n++)
35
+ C[Q.charCodeAt(n)] = n;
36
+ const ye = (n) => {
37
+ let e = n.length * 0.75, t = n.length, s, i = 0, r, o, c, l;
38
+ n[n.length - 1] === "=" && (e--, n[n.length - 2] === "=" && e--);
39
+ const f = new ArrayBuffer(e), _ = new Uint8Array(f);
40
+ for (s = 0; s < t; s += 4)
41
+ r = C[n.charCodeAt(s)], o = C[n.charCodeAt(s + 1)], c = C[n.charCodeAt(s + 2)], l = C[n.charCodeAt(s + 3)], _[i++] = r << 2 | o >> 4, _[i++] = (o & 15) << 4 | c >> 2, _[i++] = (c & 3) << 6 | l & 63;
42
+ return f;
43
+ }, ge = typeof ArrayBuffer == "function", W = (n, e) => {
44
+ if (typeof n != "string")
45
+ return {
46
+ type: "message",
47
+ data: ie(n, e)
48
+ };
49
+ const t = n.charAt(0);
50
+ return t === "b" ? {
51
+ type: "message",
52
+ data: me(n.substring(1), e)
53
+ } : S[t] ? n.length > 1 ? {
54
+ type: S[t],
55
+ data: n.substring(1)
56
+ } : {
57
+ type: S[t]
58
+ } : q;
59
+ }, me = (n, e) => {
60
+ if (ge) {
61
+ const t = ye(n);
62
+ return ie(t, e);
63
+ } else
64
+ return { base64: !0, data: n };
65
+ }, ie = (n, e) => e === "blob" ? n instanceof Blob ? n : new Blob([n]) : n instanceof ArrayBuffer ? n : n.buffer, re = "", we = (n, e) => {
66
+ const t = n.length, s = new Array(t);
67
+ let i = 0;
68
+ n.forEach((r, o) => {
69
+ H(r, !1, (c) => {
70
+ s[o] = c, ++i === t && e(s.join(re));
71
+ });
72
+ });
73
+ }, be = (n, e) => {
74
+ const t = n.split(re), s = [];
75
+ for (let i = 0; i < t.length; i++) {
76
+ const r = W(t[i], e);
77
+ if (s.push(r), r.type === "error")
78
+ break;
79
+ }
80
+ return s;
81
+ };
82
+ function ve() {
83
+ return new TransformStream({
84
+ transform(n, e) {
85
+ de(n, (t) => {
86
+ const s = t.length;
87
+ let i;
88
+ if (s < 126)
89
+ i = new Uint8Array(1), new DataView(i.buffer).setUint8(0, s);
90
+ else if (s < 65536) {
91
+ i = new Uint8Array(3);
92
+ const r = new DataView(i.buffer);
93
+ r.setUint8(0, 126), r.setUint16(1, s);
94
+ } else {
95
+ i = new Uint8Array(9);
96
+ const r = new DataView(i.buffer);
97
+ r.setUint8(0, 127), r.setBigUint64(1, BigInt(s));
98
+ }
99
+ n.data && typeof n.data != "string" && (i[0] |= 128), e.enqueue(i), e.enqueue(t);
100
+ });
101
+ }
102
+ });
103
+ }
104
+ let N;
105
+ function T(n) {
106
+ return n.reduce((e, t) => e + t.length, 0);
107
+ }
108
+ function A(n, e) {
109
+ if (n[0].length === e)
110
+ return n.shift();
111
+ const t = new Uint8Array(e);
112
+ let s = 0;
113
+ for (let i = 0; i < e; i++)
114
+ t[i] = n[0][s++], s === n[0].length && (n.shift(), s = 0);
115
+ return n.length && s < n[0].length && (n[0] = n[0].slice(s)), t;
116
+ }
117
+ function Ee(n, e) {
118
+ N || (N = new TextDecoder());
119
+ const t = [];
120
+ let s = 0, i = -1, r = !1;
121
+ return new TransformStream({
122
+ transform(o, c) {
123
+ for (t.push(o); ; ) {
124
+ if (s === 0) {
125
+ if (T(t) < 1)
126
+ break;
127
+ const l = A(t, 1);
128
+ r = (l[0] & 128) === 128, i = l[0] & 127, i < 126 ? s = 3 : i === 126 ? s = 1 : s = 2;
129
+ } else if (s === 1) {
130
+ if (T(t) < 2)
131
+ break;
132
+ const l = A(t, 2);
133
+ i = new DataView(l.buffer, l.byteOffset, l.length).getUint16(0), s = 3;
134
+ } else if (s === 2) {
135
+ if (T(t) < 8)
136
+ break;
137
+ const l = A(t, 8), f = new DataView(l.buffer, l.byteOffset, l.length), _ = f.getUint32(0);
138
+ if (_ > Math.pow(2, 21) - 1) {
139
+ c.enqueue(q);
140
+ break;
141
+ }
142
+ i = _ * Math.pow(2, 32) + f.getUint32(4), s = 3;
143
+ } else {
144
+ if (T(t) < i)
145
+ break;
146
+ const l = A(t, i);
147
+ c.enqueue(W(r ? l : N.decode(l), e)), s = 0;
148
+ }
149
+ if (i === 0 || i > n) {
150
+ c.enqueue(q);
151
+ break;
152
+ }
153
+ }
154
+ }
155
+ });
156
+ }
157
+ const oe = 4;
158
+ function u(n) {
159
+ if (n) return ke(n);
160
+ }
161
+ function ke(n) {
162
+ for (var e in u.prototype)
163
+ n[e] = u.prototype[e];
164
+ return n;
165
+ }
166
+ u.prototype.on = u.prototype.addEventListener = function(n, e) {
167
+ return this._callbacks = this._callbacks || {}, (this._callbacks["$" + n] = this._callbacks["$" + n] || []).push(e), this;
168
+ };
169
+ u.prototype.once = function(n, e) {
170
+ function t() {
171
+ this.off(n, t), e.apply(this, arguments);
172
+ }
173
+ return t.fn = e, this.on(n, t), this;
174
+ };
175
+ u.prototype.off = u.prototype.removeListener = u.prototype.removeAllListeners = u.prototype.removeEventListener = function(n, e) {
176
+ if (this._callbacks = this._callbacks || {}, arguments.length == 0)
177
+ return this._callbacks = {}, this;
178
+ var t = this._callbacks["$" + n];
179
+ if (!t) return this;
180
+ if (arguments.length == 1)
181
+ return delete this._callbacks["$" + n], this;
182
+ for (var s, i = 0; i < t.length; i++)
183
+ if (s = t[i], s === e || s.fn === e) {
184
+ t.splice(i, 1);
185
+ break;
186
+ }
187
+ return t.length === 0 && delete this._callbacks["$" + n], this;
188
+ };
189
+ u.prototype.emit = function(n) {
190
+ this._callbacks = this._callbacks || {};
191
+ for (var e = new Array(arguments.length - 1), t = this._callbacks["$" + n], s = 1; s < arguments.length; s++)
192
+ e[s - 1] = arguments[s];
193
+ if (t) {
194
+ t = t.slice(0);
195
+ for (var s = 0, i = t.length; s < i; ++s)
196
+ t[s].apply(this, e);
197
+ }
198
+ return this;
199
+ };
200
+ u.prototype.emitReserved = u.prototype.emit;
201
+ u.prototype.listeners = function(n) {
202
+ return this._callbacks = this._callbacks || {}, this._callbacks["$" + n] || [];
203
+ };
204
+ u.prototype.hasListeners = function(n) {
205
+ return !!this.listeners(n).length;
206
+ };
207
+ const O = typeof Promise == "function" && typeof Promise.resolve == "function" ? (e) => Promise.resolve().then(e) : (e, t) => t(e, 0), d = typeof self < "u" ? self : typeof window < "u" ? window : Function("return this")(), Ce = "arraybuffer";
208
+ function ae(n, ...e) {
209
+ return e.reduce((t, s) => (n.hasOwnProperty(s) && (t[s] = n[s]), t), {});
210
+ }
211
+ const Te = d.setTimeout, Ae = d.clearTimeout;
212
+ function L(n, e) {
213
+ e.useNativeTimers ? (n.setTimeoutFn = Te.bind(d), n.clearTimeoutFn = Ae.bind(d)) : (n.setTimeoutFn = d.setTimeout.bind(d), n.clearTimeoutFn = d.clearTimeout.bind(d));
214
+ }
215
+ const Se = 1.33;
216
+ function xe(n) {
217
+ return typeof n == "string" ? Re(n) : Math.ceil((n.byteLength || n.size) * Se);
218
+ }
219
+ function Re(n) {
220
+ let e = 0, t = 0;
221
+ for (let s = 0, i = n.length; s < i; s++)
222
+ e = n.charCodeAt(s), e < 128 ? t += 1 : e < 2048 ? t += 2 : e < 55296 || e >= 57344 ? t += 3 : (s++, t += 4);
223
+ return t;
224
+ }
225
+ function ce() {
226
+ return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
227
+ }
228
+ function Be(n) {
229
+ let e = "";
230
+ for (let t in n)
231
+ n.hasOwnProperty(t) && (e.length && (e += "&"), e += encodeURIComponent(t) + "=" + encodeURIComponent(n[t]));
232
+ return e;
233
+ }
234
+ function Oe(n) {
235
+ let e = {}, t = n.split("&");
236
+ for (let s = 0, i = t.length; s < i; s++) {
237
+ let r = t[s].split("=");
238
+ e[decodeURIComponent(r[0])] = decodeURIComponent(r[1]);
239
+ }
240
+ return e;
241
+ }
242
+ class Le extends Error {
243
+ constructor(e, t, s) {
244
+ super(e), this.description = t, this.context = s, this.type = "TransportError";
245
+ }
246
+ }
247
+ class K extends u {
248
+ /**
249
+ * Transport abstract constructor.
250
+ *
251
+ * @param {Object} opts - options
252
+ * @protected
253
+ */
254
+ constructor(e) {
255
+ super(), this.writable = !1, L(this, e), this.opts = e, this.query = e.query, this.socket = e.socket, this.supportsBinary = !e.forceBase64;
256
+ }
257
+ /**
258
+ * Emits an error.
259
+ *
260
+ * @param {String} reason
261
+ * @param description
262
+ * @param context - the error context
263
+ * @return {Transport} for chaining
264
+ * @protected
265
+ */
266
+ onError(e, t, s) {
267
+ return super.emitReserved("error", new Le(e, t, s)), this;
268
+ }
269
+ /**
270
+ * Opens the transport.
271
+ */
272
+ open() {
273
+ return this.readyState = "opening", this.doOpen(), this;
274
+ }
275
+ /**
276
+ * Closes the transport.
277
+ */
278
+ close() {
279
+ return (this.readyState === "opening" || this.readyState === "open") && (this.doClose(), this.onClose()), this;
280
+ }
281
+ /**
282
+ * Sends multiple packets.
283
+ *
284
+ * @param {Array} packets
285
+ */
286
+ send(e) {
287
+ this.readyState === "open" && this.write(e);
288
+ }
289
+ /**
290
+ * Called upon open
291
+ *
292
+ * @protected
293
+ */
294
+ onOpen() {
295
+ this.readyState = "open", this.writable = !0, super.emitReserved("open");
296
+ }
297
+ /**
298
+ * Called with data.
299
+ *
300
+ * @param {String} data
301
+ * @protected
302
+ */
303
+ onData(e) {
304
+ const t = W(e, this.socket.binaryType);
305
+ this.onPacket(t);
306
+ }
307
+ /**
308
+ * Called with a decoded packet.
309
+ *
310
+ * @protected
311
+ */
312
+ onPacket(e) {
313
+ super.emitReserved("packet", e);
314
+ }
315
+ /**
316
+ * Called upon close.
317
+ *
318
+ * @protected
319
+ */
320
+ onClose(e) {
321
+ this.readyState = "closed", super.emitReserved("close", e);
322
+ }
323
+ /**
324
+ * Pauses the transport, in order not to lose packets during an upgrade.
325
+ *
326
+ * @param onPause
327
+ */
328
+ pause(e) {
329
+ }
330
+ createUri(e, t = {}) {
331
+ return e + "://" + this._hostname() + this._port() + this.opts.path + this._query(t);
332
+ }
333
+ _hostname() {
334
+ const e = this.opts.hostname;
335
+ return e.indexOf(":") === -1 ? e : "[" + e + "]";
336
+ }
337
+ _port() {
338
+ return this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80) ? ":" + this.opts.port : "";
339
+ }
340
+ _query(e) {
341
+ const t = Be(e);
342
+ return t.length ? "?" + t : "";
343
+ }
344
+ }
345
+ class Pe extends K {
346
+ constructor() {
347
+ super(...arguments), this._polling = !1;
348
+ }
349
+ get name() {
350
+ return "polling";
351
+ }
352
+ /**
353
+ * Opens the socket (triggers polling). We write a PING message to determine
354
+ * when the transport is open.
355
+ *
356
+ * @protected
357
+ */
358
+ doOpen() {
359
+ this._poll();
360
+ }
361
+ /**
362
+ * Pauses polling.
363
+ *
364
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
365
+ * @package
366
+ */
367
+ pause(e) {
368
+ this.readyState = "pausing";
369
+ const t = () => {
370
+ this.readyState = "paused", e();
371
+ };
372
+ if (this._polling || !this.writable) {
373
+ let s = 0;
374
+ this._polling && (s++, this.once("pollComplete", function() {
375
+ --s || t();
376
+ })), this.writable || (s++, this.once("drain", function() {
377
+ --s || t();
378
+ }));
379
+ } else
380
+ t();
381
+ }
382
+ /**
383
+ * Starts polling cycle.
384
+ *
385
+ * @private
386
+ */
387
+ _poll() {
388
+ this._polling = !0, this.doPoll(), this.emitReserved("poll");
389
+ }
390
+ /**
391
+ * Overloads onData to detect payloads.
392
+ *
393
+ * @protected
394
+ */
395
+ onData(e) {
396
+ const t = (s) => {
397
+ if (this.readyState === "opening" && s.type === "open" && this.onOpen(), s.type === "close")
398
+ return this.onClose({ description: "transport closed by the server" }), !1;
399
+ this.onPacket(s);
400
+ };
401
+ be(e, this.socket.binaryType).forEach(t), this.readyState !== "closed" && (this._polling = !1, this.emitReserved("pollComplete"), this.readyState === "open" && this._poll());
402
+ }
403
+ /**
404
+ * For polling, send a close packet.
405
+ *
406
+ * @protected
407
+ */
408
+ doClose() {
409
+ const e = () => {
410
+ this.write([{ type: "close" }]);
411
+ };
412
+ this.readyState === "open" ? e() : this.once("open", e);
413
+ }
414
+ /**
415
+ * Writes a packets payload.
416
+ *
417
+ * @param {Array} packets - data packets
418
+ * @protected
419
+ */
420
+ write(e) {
421
+ this.writable = !1, we(e, (t) => {
422
+ this.doWrite(t, () => {
423
+ this.writable = !0, this.emitReserved("drain");
424
+ });
425
+ });
426
+ }
427
+ /**
428
+ * Generates uri for connection.
429
+ *
430
+ * @private
431
+ */
432
+ uri() {
433
+ const e = this.opts.secure ? "https" : "http", t = this.query || {};
434
+ return this.opts.timestampRequests !== !1 && (t[this.opts.timestampParam] = ce()), !this.supportsBinary && !t.sid && (t.b64 = 1), this.createUri(e, t);
435
+ }
436
+ }
437
+ let le = !1;
438
+ try {
439
+ le = typeof XMLHttpRequest < "u" && "withCredentials" in new XMLHttpRequest();
440
+ } catch {
441
+ }
442
+ const Ne = le;
443
+ function Ie() {
444
+ }
445
+ class De extends Pe {
446
+ /**
447
+ * XHR Polling constructor.
448
+ *
449
+ * @param {Object} opts
450
+ * @package
451
+ */
452
+ constructor(e) {
453
+ if (super(e), typeof location < "u") {
454
+ const t = location.protocol === "https:";
455
+ let s = location.port;
456
+ s || (s = t ? "443" : "80"), this.xd = typeof location < "u" && e.hostname !== location.hostname || s !== e.port;
457
+ }
458
+ }
459
+ /**
460
+ * Sends data.
461
+ *
462
+ * @param {String} data to send.
463
+ * @param {Function} called upon flush.
464
+ * @private
465
+ */
466
+ doWrite(e, t) {
467
+ const s = this.request({
468
+ method: "POST",
469
+ data: e
470
+ });
471
+ s.on("success", t), s.on("error", (i, r) => {
472
+ this.onError("xhr post error", i, r);
473
+ });
474
+ }
475
+ /**
476
+ * Starts a poll cycle.
477
+ *
478
+ * @private
479
+ */
480
+ doPoll() {
481
+ const e = this.request();
482
+ e.on("data", this.onData.bind(this)), e.on("error", (t, s) => {
483
+ this.onError("xhr poll error", t, s);
484
+ }), this.pollXhr = e;
485
+ }
486
+ }
487
+ class g extends u {
488
+ /**
489
+ * Request constructor
490
+ *
491
+ * @param {Object} options
492
+ * @package
493
+ */
494
+ constructor(e, t, s) {
495
+ super(), this.createRequest = e, L(this, s), this._opts = s, this._method = s.method || "GET", this._uri = t, this._data = s.data !== void 0 ? s.data : null, this._create();
496
+ }
497
+ /**
498
+ * Creates the XHR object and sends the request.
499
+ *
500
+ * @private
501
+ */
502
+ _create() {
503
+ var e;
504
+ const t = ae(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
505
+ t.xdomain = !!this._opts.xd;
506
+ const s = this._xhr = this.createRequest(t);
507
+ try {
508
+ s.open(this._method, this._uri, !0);
509
+ try {
510
+ if (this._opts.extraHeaders) {
511
+ s.setDisableHeaderCheck && s.setDisableHeaderCheck(!0);
512
+ for (let i in this._opts.extraHeaders)
513
+ this._opts.extraHeaders.hasOwnProperty(i) && s.setRequestHeader(i, this._opts.extraHeaders[i]);
514
+ }
515
+ } catch {
516
+ }
517
+ if (this._method === "POST")
518
+ try {
519
+ s.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
520
+ } catch {
521
+ }
522
+ try {
523
+ s.setRequestHeader("Accept", "*/*");
524
+ } catch {
525
+ }
526
+ (e = this._opts.cookieJar) === null || e === void 0 || e.addCookies(s), "withCredentials" in s && (s.withCredentials = this._opts.withCredentials), this._opts.requestTimeout && (s.timeout = this._opts.requestTimeout), s.onreadystatechange = () => {
527
+ var i;
528
+ s.readyState === 3 && ((i = this._opts.cookieJar) === null || i === void 0 || i.parseCookies(
529
+ // @ts-ignore
530
+ s.getResponseHeader("set-cookie")
531
+ )), s.readyState === 4 && (s.status === 200 || s.status === 1223 ? this._onLoad() : this.setTimeoutFn(() => {
532
+ this._onError(typeof s.status == "number" ? s.status : 0);
533
+ }, 0));
534
+ }, s.send(this._data);
535
+ } catch (i) {
536
+ this.setTimeoutFn(() => {
537
+ this._onError(i);
538
+ }, 0);
539
+ return;
540
+ }
541
+ typeof document < "u" && (this._index = g.requestsCount++, g.requests[this._index] = this);
542
+ }
543
+ /**
544
+ * Called upon error.
545
+ *
546
+ * @private
547
+ */
548
+ _onError(e) {
549
+ this.emitReserved("error", e, this._xhr), this._cleanup(!0);
550
+ }
551
+ /**
552
+ * Cleans up house.
553
+ *
554
+ * @private
555
+ */
556
+ _cleanup(e) {
557
+ if (!(typeof this._xhr > "u" || this._xhr === null)) {
558
+ if (this._xhr.onreadystatechange = Ie, e)
559
+ try {
560
+ this._xhr.abort();
561
+ } catch {
562
+ }
563
+ typeof document < "u" && delete g.requests[this._index], this._xhr = null;
564
+ }
565
+ }
566
+ /**
567
+ * Called upon load.
568
+ *
569
+ * @private
570
+ */
571
+ _onLoad() {
572
+ const e = this._xhr.responseText;
573
+ e !== null && (this.emitReserved("data", e), this.emitReserved("success"), this._cleanup());
574
+ }
575
+ /**
576
+ * Aborts the request.
577
+ *
578
+ * @package
579
+ */
580
+ abort() {
581
+ this._cleanup();
582
+ }
583
+ }
584
+ g.requestsCount = 0;
585
+ g.requests = {};
586
+ if (typeof document < "u") {
587
+ if (typeof attachEvent == "function")
588
+ attachEvent("onunload", X);
589
+ else if (typeof addEventListener == "function") {
590
+ const n = "onpagehide" in d ? "pagehide" : "unload";
591
+ addEventListener(n, X, !1);
592
+ }
593
+ }
594
+ function X() {
595
+ for (let n in g.requests)
596
+ g.requests.hasOwnProperty(n) && g.requests[n].abort();
597
+ }
598
+ const qe = (function() {
599
+ const n = he({
600
+ xdomain: !1
601
+ });
602
+ return n && n.responseType !== null;
603
+ })();
604
+ class Ue extends De {
605
+ constructor(e) {
606
+ super(e);
607
+ const t = e && e.forceBase64;
608
+ this.supportsBinary = qe && !t;
609
+ }
610
+ request(e = {}) {
611
+ return Object.assign(e, { xd: this.xd }, this.opts), new g(he, this.uri(), e);
612
+ }
613
+ }
614
+ function he(n) {
615
+ const e = n.xdomain;
616
+ try {
617
+ if (typeof XMLHttpRequest < "u" && (!e || Ne))
618
+ return new XMLHttpRequest();
619
+ } catch {
620
+ }
621
+ if (!e)
622
+ try {
623
+ return new d[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
624
+ } catch {
625
+ }
626
+ }
627
+ const _e = typeof navigator < "u" && typeof navigator.product == "string" && navigator.product.toLowerCase() === "reactnative";
628
+ class Me extends K {
629
+ get name() {
630
+ return "websocket";
631
+ }
632
+ doOpen() {
633
+ const e = this.uri(), t = this.opts.protocols, s = _e ? {} : ae(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
634
+ this.opts.extraHeaders && (s.headers = this.opts.extraHeaders);
635
+ try {
636
+ this.ws = this.createSocket(e, t, s);
637
+ } catch (i) {
638
+ return this.emitReserved("error", i);
639
+ }
640
+ this.ws.binaryType = this.socket.binaryType, this.addEventListeners();
641
+ }
642
+ /**
643
+ * Adds event listeners to the socket
644
+ *
645
+ * @private
646
+ */
647
+ addEventListeners() {
648
+ this.ws.onopen = () => {
649
+ this.opts.autoUnref && this.ws._socket.unref(), this.onOpen();
650
+ }, this.ws.onclose = (e) => this.onClose({
651
+ description: "websocket connection closed",
652
+ context: e
653
+ }), this.ws.onmessage = (e) => this.onData(e.data), this.ws.onerror = (e) => this.onError("websocket error", e);
654
+ }
655
+ write(e) {
656
+ this.writable = !1;
657
+ for (let t = 0; t < e.length; t++) {
658
+ const s = e[t], i = t === e.length - 1;
659
+ H(s, this.supportsBinary, (r) => {
660
+ try {
661
+ this.doWrite(s, r);
662
+ } catch {
663
+ }
664
+ i && O(() => {
665
+ this.writable = !0, this.emitReserved("drain");
666
+ }, this.setTimeoutFn);
667
+ });
668
+ }
669
+ }
670
+ doClose() {
671
+ typeof this.ws < "u" && (this.ws.onerror = () => {
672
+ }, this.ws.close(), this.ws = null);
673
+ }
674
+ /**
675
+ * Generates uri for connection.
676
+ *
677
+ * @private
678
+ */
679
+ uri() {
680
+ const e = this.opts.secure ? "wss" : "ws", t = this.query || {};
681
+ return this.opts.timestampRequests && (t[this.opts.timestampParam] = ce()), this.supportsBinary || (t.b64 = 1), this.createUri(e, t);
682
+ }
683
+ }
684
+ const I = d.WebSocket || d.MozWebSocket;
685
+ class Fe extends Me {
686
+ createSocket(e, t, s) {
687
+ return _e ? new I(e, t, s) : t ? new I(e, t) : new I(e);
688
+ }
689
+ doWrite(e, t) {
690
+ this.ws.send(t);
691
+ }
692
+ }
693
+ class $e extends K {
694
+ get name() {
695
+ return "webtransport";
696
+ }
697
+ doOpen() {
698
+ try {
699
+ this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
700
+ } catch (e) {
701
+ return this.emitReserved("error", e);
702
+ }
703
+ this._transport.closed.then(() => {
704
+ this.onClose();
705
+ }).catch((e) => {
706
+ this.onError("webtransport error", e);
707
+ }), this._transport.ready.then(() => {
708
+ this._transport.createBidirectionalStream().then((e) => {
709
+ const t = Ee(Number.MAX_SAFE_INTEGER, this.socket.binaryType), s = e.readable.pipeThrough(t).getReader(), i = ve();
710
+ i.readable.pipeTo(e.writable), this._writer = i.writable.getWriter();
711
+ const r = () => {
712
+ s.read().then(({ done: c, value: l }) => {
713
+ c || (this.onPacket(l), r());
714
+ }).catch((c) => {
715
+ });
716
+ };
717
+ r();
718
+ const o = { type: "open" };
719
+ this.query.sid && (o.data = `{"sid":"${this.query.sid}"}`), this._writer.write(o).then(() => this.onOpen());
720
+ });
721
+ });
722
+ }
723
+ write(e) {
724
+ this.writable = !1;
725
+ for (let t = 0; t < e.length; t++) {
726
+ const s = e[t], i = t === e.length - 1;
727
+ this._writer.write(s).then(() => {
728
+ i && O(() => {
729
+ this.writable = !0, this.emitReserved("drain");
730
+ }, this.setTimeoutFn);
731
+ });
732
+ }
733
+ }
734
+ doClose() {
735
+ var e;
736
+ (e = this._transport) === null || e === void 0 || e.close();
737
+ }
738
+ }
739
+ const Ve = {
740
+ websocket: Fe,
741
+ webtransport: $e,
742
+ polling: Ue
743
+ }, He = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/, We = [
744
+ "source",
745
+ "protocol",
746
+ "authority",
747
+ "userInfo",
748
+ "user",
749
+ "password",
750
+ "host",
751
+ "port",
752
+ "relative",
753
+ "path",
754
+ "directory",
755
+ "file",
756
+ "query",
757
+ "anchor"
758
+ ];
759
+ function U(n) {
760
+ if (n.length > 8e3)
761
+ throw "URI too long";
762
+ const e = n, t = n.indexOf("["), s = n.indexOf("]");
763
+ t != -1 && s != -1 && (n = n.substring(0, t) + n.substring(t, s).replace(/:/g, ";") + n.substring(s, n.length));
764
+ let i = He.exec(n || ""), r = {}, o = 14;
765
+ for (; o--; )
766
+ r[We[o]] = i[o] || "";
767
+ return t != -1 && s != -1 && (r.source = e, r.host = r.host.substring(1, r.host.length - 1).replace(/;/g, ":"), r.authority = r.authority.replace("[", "").replace("]", "").replace(/;/g, ":"), r.ipv6uri = !0), r.pathNames = Ke(r, r.path), r.queryKey = ze(r, r.query), r;
768
+ }
769
+ function Ke(n, e) {
770
+ const t = /\/{2,9}/g, s = e.replace(t, "/").split("/");
771
+ return (e.slice(0, 1) == "/" || e.length === 0) && s.splice(0, 1), e.slice(-1) == "/" && s.splice(s.length - 1, 1), s;
772
+ }
773
+ function ze(n, e) {
774
+ const t = {};
775
+ return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function(s, i, r) {
776
+ i && (t[i] = r);
777
+ }), t;
778
+ }
779
+ const M = typeof addEventListener == "function" && typeof removeEventListener == "function", x = [];
780
+ M && addEventListener("offline", () => {
781
+ x.forEach((n) => n());
782
+ }, !1);
783
+ class b extends u {
784
+ /**
785
+ * Socket constructor.
786
+ *
787
+ * @param {String|Object} uri - uri or options
788
+ * @param {Object} opts - options
789
+ */
790
+ constructor(e, t) {
791
+ if (super(), this.binaryType = Ce, this.writeBuffer = [], this._prevBufferLen = 0, this._pingInterval = -1, this._pingTimeout = -1, this._maxPayload = -1, this._pingTimeoutTime = 1 / 0, e && typeof e == "object" && (t = e, e = null), e) {
792
+ const s = U(e);
793
+ t.hostname = s.host, t.secure = s.protocol === "https" || s.protocol === "wss", t.port = s.port, s.query && (t.query = s.query);
794
+ } else t.host && (t.hostname = U(t.host).host);
795
+ L(this, t), this.secure = t.secure != null ? t.secure : typeof location < "u" && location.protocol === "https:", t.hostname && !t.port && (t.port = this.secure ? "443" : "80"), this.hostname = t.hostname || (typeof location < "u" ? location.hostname : "localhost"), this.port = t.port || (typeof location < "u" && location.port ? location.port : this.secure ? "443" : "80"), this.transports = [], this._transportsByName = {}, t.transports.forEach((s) => {
796
+ const i = s.prototype.name;
797
+ this.transports.push(i), this._transportsByName[i] = s;
798
+ }), this.opts = Object.assign({
799
+ path: "/engine.io",
800
+ agent: !1,
801
+ withCredentials: !1,
802
+ upgrade: !0,
803
+ timestampParam: "t",
804
+ rememberUpgrade: !1,
805
+ addTrailingSlash: !0,
806
+ rejectUnauthorized: !0,
807
+ perMessageDeflate: {
808
+ threshold: 1024
809
+ },
810
+ transportOptions: {},
811
+ closeOnBeforeunload: !1
812
+ }, t), this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : ""), typeof this.opts.query == "string" && (this.opts.query = Oe(this.opts.query)), M && (this.opts.closeOnBeforeunload && (this._beforeunloadEventListener = () => {
813
+ this.transport && (this.transport.removeAllListeners(), this.transport.close());
814
+ }, addEventListener("beforeunload", this._beforeunloadEventListener, !1)), this.hostname !== "localhost" && (this._offlineEventListener = () => {
815
+ this._onClose("transport close", {
816
+ description: "network connection lost"
817
+ });
818
+ }, x.push(this._offlineEventListener))), this.opts.withCredentials && (this._cookieJar = void 0), this._open();
819
+ }
820
+ /**
821
+ * Creates transport of the given type.
822
+ *
823
+ * @param {String} name - transport name
824
+ * @return {Transport}
825
+ * @private
826
+ */
827
+ createTransport(e) {
828
+ const t = Object.assign({}, this.opts.query);
829
+ t.EIO = oe, t.transport = e, this.id && (t.sid = this.id);
830
+ const s = Object.assign({}, this.opts, {
831
+ query: t,
832
+ socket: this,
833
+ hostname: this.hostname,
834
+ secure: this.secure,
835
+ port: this.port
836
+ }, this.opts.transportOptions[e]);
837
+ return new this._transportsByName[e](s);
838
+ }
839
+ /**
840
+ * Initializes transport to use and starts probe.
841
+ *
842
+ * @private
843
+ */
844
+ _open() {
845
+ if (this.transports.length === 0) {
846
+ this.setTimeoutFn(() => {
847
+ this.emitReserved("error", "No transports available");
848
+ }, 0);
849
+ return;
850
+ }
851
+ const e = this.opts.rememberUpgrade && b.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
852
+ this.readyState = "opening";
853
+ const t = this.createTransport(e);
854
+ t.open(), this.setTransport(t);
855
+ }
856
+ /**
857
+ * Sets the current transport. Disables the existing one (if any).
858
+ *
859
+ * @private
860
+ */
861
+ setTransport(e) {
862
+ this.transport && this.transport.removeAllListeners(), this.transport = e, e.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (t) => this._onClose("transport close", t));
863
+ }
864
+ /**
865
+ * Called when connection is deemed open.
866
+ *
867
+ * @private
868
+ */
869
+ onOpen() {
870
+ this.readyState = "open", b.priorWebsocketSuccess = this.transport.name === "websocket", this.emitReserved("open"), this.flush();
871
+ }
872
+ /**
873
+ * Handles a packet.
874
+ *
875
+ * @private
876
+ */
877
+ _onPacket(e) {
878
+ if (this.readyState === "opening" || this.readyState === "open" || this.readyState === "closing")
879
+ switch (this.emitReserved("packet", e), this.emitReserved("heartbeat"), e.type) {
880
+ case "open":
881
+ this.onHandshake(JSON.parse(e.data));
882
+ break;
883
+ case "ping":
884
+ this._sendPacket("pong"), this.emitReserved("ping"), this.emitReserved("pong"), this._resetPingTimeout();
885
+ break;
886
+ case "error":
887
+ const t = new Error("server error");
888
+ t.code = e.data, this._onError(t);
889
+ break;
890
+ case "message":
891
+ this.emitReserved("data", e.data), this.emitReserved("message", e.data);
892
+ break;
893
+ }
894
+ }
895
+ /**
896
+ * Called upon handshake completion.
897
+ *
898
+ * @param {Object} data - handshake obj
899
+ * @private
900
+ */
901
+ onHandshake(e) {
902
+ this.emitReserved("handshake", e), this.id = e.sid, this.transport.query.sid = e.sid, this._pingInterval = e.pingInterval, this._pingTimeout = e.pingTimeout, this._maxPayload = e.maxPayload, this.onOpen(), this.readyState !== "closed" && this._resetPingTimeout();
903
+ }
904
+ /**
905
+ * Sets and resets ping timeout timer based on server pings.
906
+ *
907
+ * @private
908
+ */
909
+ _resetPingTimeout() {
910
+ this.clearTimeoutFn(this._pingTimeoutTimer);
911
+ const e = this._pingInterval + this._pingTimeout;
912
+ this._pingTimeoutTime = Date.now() + e, this._pingTimeoutTimer = this.setTimeoutFn(() => {
913
+ this._onClose("ping timeout");
914
+ }, e), this.opts.autoUnref && this._pingTimeoutTimer.unref();
915
+ }
916
+ /**
917
+ * Called on `drain` event
918
+ *
919
+ * @private
920
+ */
921
+ _onDrain() {
922
+ this.writeBuffer.splice(0, this._prevBufferLen), this._prevBufferLen = 0, this.writeBuffer.length === 0 ? this.emitReserved("drain") : this.flush();
923
+ }
924
+ /**
925
+ * Flush write buffers.
926
+ *
927
+ * @private
928
+ */
929
+ flush() {
930
+ if (this.readyState !== "closed" && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
931
+ const e = this._getWritablePackets();
932
+ this.transport.send(e), this._prevBufferLen = e.length, this.emitReserved("flush");
933
+ }
934
+ }
935
+ /**
936
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
937
+ * long-polling)
938
+ *
939
+ * @private
940
+ */
941
+ _getWritablePackets() {
942
+ if (!(this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1))
943
+ return this.writeBuffer;
944
+ let t = 1;
945
+ for (let s = 0; s < this.writeBuffer.length; s++) {
946
+ const i = this.writeBuffer[s].data;
947
+ if (i && (t += xe(i)), s > 0 && t > this._maxPayload)
948
+ return this.writeBuffer.slice(0, s);
949
+ t += 2;
950
+ }
951
+ return this.writeBuffer;
952
+ }
953
+ /**
954
+ * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
955
+ *
956
+ * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
957
+ * `write()` method then the message would not be buffered by the Socket.IO client.
958
+ *
959
+ * @return {boolean}
960
+ * @private
961
+ */
962
+ /* private */
963
+ _hasPingExpired() {
964
+ if (!this._pingTimeoutTime)
965
+ return !0;
966
+ const e = Date.now() > this._pingTimeoutTime;
967
+ return e && (this._pingTimeoutTime = 0, O(() => {
968
+ this._onClose("ping timeout");
969
+ }, this.setTimeoutFn)), e;
970
+ }
971
+ /**
972
+ * Sends a message.
973
+ *
974
+ * @param {String} msg - message.
975
+ * @param {Object} options.
976
+ * @param {Function} fn - callback function.
977
+ * @return {Socket} for chaining.
978
+ */
979
+ write(e, t, s) {
980
+ return this._sendPacket("message", e, t, s), this;
981
+ }
982
+ /**
983
+ * Sends a message. Alias of {@link Socket#write}.
984
+ *
985
+ * @param {String} msg - message.
986
+ * @param {Object} options.
987
+ * @param {Function} fn - callback function.
988
+ * @return {Socket} for chaining.
989
+ */
990
+ send(e, t, s) {
991
+ return this._sendPacket("message", e, t, s), this;
992
+ }
993
+ /**
994
+ * Sends a packet.
995
+ *
996
+ * @param {String} type: packet type.
997
+ * @param {String} data.
998
+ * @param {Object} options.
999
+ * @param {Function} fn - callback function.
1000
+ * @private
1001
+ */
1002
+ _sendPacket(e, t, s, i) {
1003
+ if (typeof t == "function" && (i = t, t = void 0), typeof s == "function" && (i = s, s = null), this.readyState === "closing" || this.readyState === "closed")
1004
+ return;
1005
+ s = s || {}, s.compress = s.compress !== !1;
1006
+ const r = {
1007
+ type: e,
1008
+ data: t,
1009
+ options: s
1010
+ };
1011
+ this.emitReserved("packetCreate", r), this.writeBuffer.push(r), i && this.once("flush", i), this.flush();
1012
+ }
1013
+ /**
1014
+ * Closes the connection.
1015
+ */
1016
+ close() {
1017
+ const e = () => {
1018
+ this._onClose("forced close"), this.transport.close();
1019
+ }, t = () => {
1020
+ this.off("upgrade", t), this.off("upgradeError", t), e();
1021
+ }, s = () => {
1022
+ this.once("upgrade", t), this.once("upgradeError", t);
1023
+ };
1024
+ return (this.readyState === "opening" || this.readyState === "open") && (this.readyState = "closing", this.writeBuffer.length ? this.once("drain", () => {
1025
+ this.upgrading ? s() : e();
1026
+ }) : this.upgrading ? s() : e()), this;
1027
+ }
1028
+ /**
1029
+ * Called upon transport error
1030
+ *
1031
+ * @private
1032
+ */
1033
+ _onError(e) {
1034
+ if (b.priorWebsocketSuccess = !1, this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening")
1035
+ return this.transports.shift(), this._open();
1036
+ this.emitReserved("error", e), this._onClose("transport error", e);
1037
+ }
1038
+ /**
1039
+ * Called upon transport close.
1040
+ *
1041
+ * @private
1042
+ */
1043
+ _onClose(e, t) {
1044
+ if (this.readyState === "opening" || this.readyState === "open" || this.readyState === "closing") {
1045
+ if (this.clearTimeoutFn(this._pingTimeoutTimer), this.transport.removeAllListeners("close"), this.transport.close(), this.transport.removeAllListeners(), M && (this._beforeunloadEventListener && removeEventListener("beforeunload", this._beforeunloadEventListener, !1), this._offlineEventListener)) {
1046
+ const s = x.indexOf(this._offlineEventListener);
1047
+ s !== -1 && x.splice(s, 1);
1048
+ }
1049
+ this.readyState = "closed", this.id = null, this.emitReserved("close", e, t), this.writeBuffer = [], this._prevBufferLen = 0;
1050
+ }
1051
+ }
1052
+ }
1053
+ b.protocol = oe;
1054
+ class Ye extends b {
1055
+ constructor() {
1056
+ super(...arguments), this._upgrades = [];
1057
+ }
1058
+ onOpen() {
1059
+ if (super.onOpen(), this.readyState === "open" && this.opts.upgrade)
1060
+ for (let e = 0; e < this._upgrades.length; e++)
1061
+ this._probe(this._upgrades[e]);
1062
+ }
1063
+ /**
1064
+ * Probes a transport.
1065
+ *
1066
+ * @param {String} name - transport name
1067
+ * @private
1068
+ */
1069
+ _probe(e) {
1070
+ let t = this.createTransport(e), s = !1;
1071
+ b.priorWebsocketSuccess = !1;
1072
+ const i = () => {
1073
+ s || (t.send([{ type: "ping", data: "probe" }]), t.once("packet", (p) => {
1074
+ if (!s)
1075
+ if (p.type === "pong" && p.data === "probe") {
1076
+ if (this.upgrading = !0, this.emitReserved("upgrading", t), !t)
1077
+ return;
1078
+ b.priorWebsocketSuccess = t.name === "websocket", this.transport.pause(() => {
1079
+ s || this.readyState !== "closed" && (_(), this.setTransport(t), t.send([{ type: "upgrade" }]), this.emitReserved("upgrade", t), t = null, this.upgrading = !1, this.flush());
1080
+ });
1081
+ } else {
1082
+ const E = new Error("probe error");
1083
+ E.transport = t.name, this.emitReserved("upgradeError", E);
1084
+ }
1085
+ }));
1086
+ };
1087
+ function r() {
1088
+ s || (s = !0, _(), t.close(), t = null);
1089
+ }
1090
+ const o = (p) => {
1091
+ const E = new Error("probe error: " + p);
1092
+ E.transport = t.name, r(), this.emitReserved("upgradeError", E);
1093
+ };
1094
+ function c() {
1095
+ o("transport closed");
1096
+ }
1097
+ function l() {
1098
+ o("socket closed");
1099
+ }
1100
+ function f(p) {
1101
+ t && p.name !== t.name && r();
1102
+ }
1103
+ const _ = () => {
1104
+ t.removeListener("open", i), t.removeListener("error", o), t.removeListener("close", c), this.off("close", l), this.off("upgrading", f);
1105
+ };
1106
+ t.once("open", i), t.once("error", o), t.once("close", c), this.once("close", l), this.once("upgrading", f), this._upgrades.indexOf("webtransport") !== -1 && e !== "webtransport" ? this.setTimeoutFn(() => {
1107
+ s || t.open();
1108
+ }, 200) : t.open();
1109
+ }
1110
+ onHandshake(e) {
1111
+ this._upgrades = this._filterUpgrades(e.upgrades), super.onHandshake(e);
1112
+ }
1113
+ /**
1114
+ * Filters upgrades, returning only those matching client transports.
1115
+ *
1116
+ * @param {Array} upgrades - server upgrades
1117
+ * @private
1118
+ */
1119
+ _filterUpgrades(e) {
1120
+ const t = [];
1121
+ for (let s = 0; s < e.length; s++)
1122
+ ~this.transports.indexOf(e[s]) && t.push(e[s]);
1123
+ return t;
1124
+ }
1125
+ }
1126
+ let Je = class extends Ye {
1127
+ constructor(e, t = {}) {
1128
+ const s = typeof e == "object" ? e : t;
1129
+ (!s.transports || s.transports && typeof s.transports[0] == "string") && (s.transports = (s.transports || ["polling", "websocket", "webtransport"]).map((i) => Ve[i]).filter((i) => !!i)), super(e, s);
1130
+ }
1131
+ };
1132
+ function je(n, e = "", t) {
1133
+ let s = n;
1134
+ t = t || typeof location < "u" && location, n == null && (n = t.protocol + "//" + t.host), typeof n == "string" && (n.charAt(0) === "/" && (n.charAt(1) === "/" ? n = t.protocol + n : n = t.host + n), /^(https?|wss?):\/\//.test(n) || (typeof t < "u" ? n = t.protocol + "//" + n : n = "https://" + n), s = U(n)), s.port || (/^(http|ws)$/.test(s.protocol) ? s.port = "80" : /^(http|ws)s$/.test(s.protocol) && (s.port = "443")), s.path = s.path || "/";
1135
+ const r = s.host.indexOf(":") !== -1 ? "[" + s.host + "]" : s.host;
1136
+ return s.id = s.protocol + "://" + r + ":" + s.port + e, s.href = s.protocol + "://" + r + (t && t.port === s.port ? "" : ":" + s.port), s;
1137
+ }
1138
+ const Qe = typeof ArrayBuffer == "function", Xe = (n) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(n) : n.buffer instanceof ArrayBuffer, ue = Object.prototype.toString, Ge = typeof Blob == "function" || typeof Blob < "u" && ue.call(Blob) === "[object BlobConstructor]", Ze = typeof File == "function" || typeof File < "u" && ue.call(File) === "[object FileConstructor]";
1139
+ function z(n) {
1140
+ return Qe && (n instanceof ArrayBuffer || Xe(n)) || Ge && n instanceof Blob || Ze && n instanceof File;
1141
+ }
1142
+ function R(n, e) {
1143
+ if (!n || typeof n != "object")
1144
+ return !1;
1145
+ if (Array.isArray(n)) {
1146
+ for (let t = 0, s = n.length; t < s; t++)
1147
+ if (R(n[t]))
1148
+ return !0;
1149
+ return !1;
1150
+ }
1151
+ if (z(n))
1152
+ return !0;
1153
+ if (n.toJSON && typeof n.toJSON == "function" && arguments.length === 1)
1154
+ return R(n.toJSON(), !0);
1155
+ for (const t in n)
1156
+ if (Object.prototype.hasOwnProperty.call(n, t) && R(n[t]))
1157
+ return !0;
1158
+ return !1;
1159
+ }
1160
+ function et(n) {
1161
+ const e = [], t = n.data, s = n;
1162
+ return s.data = F(t, e), s.attachments = e.length, { packet: s, buffers: e };
1163
+ }
1164
+ function F(n, e) {
1165
+ if (!n)
1166
+ return n;
1167
+ if (z(n)) {
1168
+ const t = { _placeholder: !0, num: e.length };
1169
+ return e.push(n), t;
1170
+ } else if (Array.isArray(n)) {
1171
+ const t = new Array(n.length);
1172
+ for (let s = 0; s < n.length; s++)
1173
+ t[s] = F(n[s], e);
1174
+ return t;
1175
+ } else if (typeof n == "object" && !(n instanceof Date)) {
1176
+ const t = {};
1177
+ for (const s in n)
1178
+ Object.prototype.hasOwnProperty.call(n, s) && (t[s] = F(n[s], e));
1179
+ return t;
1180
+ }
1181
+ return n;
1182
+ }
1183
+ function tt(n, e) {
1184
+ return n.data = $(n.data, e), delete n.attachments, n;
1185
+ }
1186
+ function $(n, e) {
1187
+ if (!n)
1188
+ return n;
1189
+ if (n && n._placeholder === !0) {
1190
+ if (typeof n.num == "number" && n.num >= 0 && n.num < e.length)
1191
+ return e[n.num];
1192
+ throw new Error("illegal attachments");
1193
+ } else if (Array.isArray(n))
1194
+ for (let t = 0; t < n.length; t++)
1195
+ n[t] = $(n[t], e);
1196
+ else if (typeof n == "object")
1197
+ for (const t in n)
1198
+ Object.prototype.hasOwnProperty.call(n, t) && (n[t] = $(n[t], e));
1199
+ return n;
1200
+ }
1201
+ const st = [
1202
+ "connect",
1203
+ // used on the client side
1204
+ "connect_error",
1205
+ // used on the client side
1206
+ "disconnect",
1207
+ // used on both sides
1208
+ "disconnecting",
1209
+ // used on the server side
1210
+ "newListener",
1211
+ // used by the Node.js EventEmitter
1212
+ "removeListener"
1213
+ // used by the Node.js EventEmitter
1214
+ ];
1215
+ var h;
1216
+ (function(n) {
1217
+ n[n.CONNECT = 0] = "CONNECT", n[n.DISCONNECT = 1] = "DISCONNECT", n[n.EVENT = 2] = "EVENT", n[n.ACK = 3] = "ACK", n[n.CONNECT_ERROR = 4] = "CONNECT_ERROR", n[n.BINARY_EVENT = 5] = "BINARY_EVENT", n[n.BINARY_ACK = 6] = "BINARY_ACK";
1218
+ })(h || (h = {}));
1219
+ class nt {
1220
+ /**
1221
+ * Encoder constructor
1222
+ *
1223
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
1224
+ */
1225
+ constructor(e) {
1226
+ this.replacer = e;
1227
+ }
1228
+ /**
1229
+ * Encode a packet as a single string if non-binary, or as a
1230
+ * buffer sequence, depending on packet type.
1231
+ *
1232
+ * @param {Object} obj - packet object
1233
+ */
1234
+ encode(e) {
1235
+ return (e.type === h.EVENT || e.type === h.ACK) && R(e) ? this.encodeAsBinary({
1236
+ type: e.type === h.EVENT ? h.BINARY_EVENT : h.BINARY_ACK,
1237
+ nsp: e.nsp,
1238
+ data: e.data,
1239
+ id: e.id
1240
+ }) : [this.encodeAsString(e)];
1241
+ }
1242
+ /**
1243
+ * Encode packet as string.
1244
+ */
1245
+ encodeAsString(e) {
1246
+ let t = "" + e.type;
1247
+ return (e.type === h.BINARY_EVENT || e.type === h.BINARY_ACK) && (t += e.attachments + "-"), e.nsp && e.nsp !== "/" && (t += e.nsp + ","), e.id != null && (t += e.id), e.data != null && (t += JSON.stringify(e.data, this.replacer)), t;
1248
+ }
1249
+ /**
1250
+ * Encode packet as 'buffer sequence' by removing blobs, and
1251
+ * deconstructing packet into object with placeholders and
1252
+ * a list of buffers.
1253
+ */
1254
+ encodeAsBinary(e) {
1255
+ const t = et(e), s = this.encodeAsString(t.packet), i = t.buffers;
1256
+ return i.unshift(s), i;
1257
+ }
1258
+ }
1259
+ class Y extends u {
1260
+ /**
1261
+ * Decoder constructor
1262
+ */
1263
+ constructor(e) {
1264
+ super(), this.opts = Object.assign({
1265
+ reviver: void 0,
1266
+ maxAttachments: 10
1267
+ }, typeof e == "function" ? { reviver: e } : e);
1268
+ }
1269
+ /**
1270
+ * Decodes an encoded packet string into packet JSON.
1271
+ *
1272
+ * @param {String} obj - encoded packet
1273
+ */
1274
+ add(e) {
1275
+ let t;
1276
+ if (typeof e == "string") {
1277
+ if (this.reconstructor)
1278
+ throw new Error("got plaintext data when reconstructing a packet");
1279
+ t = this.decodeString(e);
1280
+ const s = t.type === h.BINARY_EVENT;
1281
+ s || t.type === h.BINARY_ACK ? (t.type = s ? h.EVENT : h.ACK, this.reconstructor = new it(t), t.attachments === 0 && super.emitReserved("decoded", t)) : super.emitReserved("decoded", t);
1282
+ } else if (z(e) || e.base64)
1283
+ if (this.reconstructor)
1284
+ t = this.reconstructor.takeBinaryData(e), t && (this.reconstructor = null, super.emitReserved("decoded", t));
1285
+ else
1286
+ throw new Error("got binary data when not reconstructing a packet");
1287
+ else
1288
+ throw new Error("Unknown type: " + e);
1289
+ }
1290
+ /**
1291
+ * Decode a packet String (JSON data)
1292
+ *
1293
+ * @param {String} str
1294
+ * @return {Object} packet
1295
+ */
1296
+ decodeString(e) {
1297
+ let t = 0;
1298
+ const s = {
1299
+ type: Number(e.charAt(0))
1300
+ };
1301
+ if (h[s.type] === void 0)
1302
+ throw new Error("unknown packet type " + s.type);
1303
+ if (s.type === h.BINARY_EVENT || s.type === h.BINARY_ACK) {
1304
+ const r = t + 1;
1305
+ for (; e.charAt(++t) !== "-" && t != e.length; )
1306
+ ;
1307
+ const o = e.substring(r, t);
1308
+ if (o != Number(o) || e.charAt(t) !== "-")
1309
+ throw new Error("Illegal attachments");
1310
+ const c = Number(o);
1311
+ if (!rt(c) || c < 0)
1312
+ throw new Error("Illegal attachments");
1313
+ if (c > this.opts.maxAttachments)
1314
+ throw new Error("too many attachments");
1315
+ s.attachments = c;
1316
+ }
1317
+ if (e.charAt(t + 1) === "/") {
1318
+ const r = t + 1;
1319
+ for (; ++t && !(e.charAt(t) === "," || t === e.length); )
1320
+ ;
1321
+ s.nsp = e.substring(r, t);
1322
+ } else
1323
+ s.nsp = "/";
1324
+ const i = e.charAt(t + 1);
1325
+ if (i !== "" && Number(i) == i) {
1326
+ const r = t + 1;
1327
+ for (; ++t; ) {
1328
+ const o = e.charAt(t);
1329
+ if (o == null || Number(o) != o) {
1330
+ --t;
1331
+ break;
1332
+ }
1333
+ if (t === e.length)
1334
+ break;
1335
+ }
1336
+ s.id = Number(e.substring(r, t + 1));
1337
+ }
1338
+ if (e.charAt(++t)) {
1339
+ const r = this.tryParse(e.substr(t));
1340
+ if (Y.isPayloadValid(s.type, r))
1341
+ s.data = r;
1342
+ else
1343
+ throw new Error("invalid payload");
1344
+ }
1345
+ return s;
1346
+ }
1347
+ tryParse(e) {
1348
+ try {
1349
+ return JSON.parse(e, this.opts.reviver);
1350
+ } catch {
1351
+ return !1;
1352
+ }
1353
+ }
1354
+ static isPayloadValid(e, t) {
1355
+ switch (e) {
1356
+ case h.CONNECT:
1357
+ return G(t);
1358
+ case h.DISCONNECT:
1359
+ return t === void 0;
1360
+ case h.CONNECT_ERROR:
1361
+ return typeof t == "string" || G(t);
1362
+ case h.EVENT:
1363
+ case h.BINARY_EVENT:
1364
+ return Array.isArray(t) && (typeof t[0] == "number" || typeof t[0] == "string" && st.indexOf(t[0]) === -1);
1365
+ case h.ACK:
1366
+ case h.BINARY_ACK:
1367
+ return Array.isArray(t);
1368
+ }
1369
+ }
1370
+ /**
1371
+ * Deallocates a parser's resources
1372
+ */
1373
+ destroy() {
1374
+ this.reconstructor && (this.reconstructor.finishedReconstruction(), this.reconstructor = null);
1375
+ }
1376
+ }
1377
+ class it {
1378
+ constructor(e) {
1379
+ this.packet = e, this.buffers = [], this.reconPack = e;
1380
+ }
1381
+ /**
1382
+ * Method to be called when binary data received from connection
1383
+ * after a BINARY_EVENT packet.
1384
+ *
1385
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
1386
+ * @return {null | Object} returns null if more binary data is expected or
1387
+ * a reconstructed packet object if all buffers have been received.
1388
+ */
1389
+ takeBinaryData(e) {
1390
+ if (this.buffers.push(e), this.buffers.length === this.reconPack.attachments) {
1391
+ const t = tt(this.reconPack, this.buffers);
1392
+ return this.finishedReconstruction(), t;
1393
+ }
1394
+ return null;
1395
+ }
1396
+ /**
1397
+ * Cleans up binary packet reconstruction variables.
1398
+ */
1399
+ finishedReconstruction() {
1400
+ this.reconPack = null, this.buffers = [];
1401
+ }
1402
+ }
1403
+ const rt = Number.isInteger || function(n) {
1404
+ return typeof n == "number" && isFinite(n) && Math.floor(n) === n;
1405
+ };
1406
+ function G(n) {
1407
+ return Object.prototype.toString.call(n) === "[object Object]";
1408
+ }
1409
+ const ot = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1410
+ __proto__: null,
1411
+ Decoder: Y,
1412
+ Encoder: nt,
1413
+ get PacketType() {
1414
+ return h;
1415
+ }
1416
+ }, Symbol.toStringTag, { value: "Module" }));
1417
+ function y(n, e, t) {
1418
+ return n.on(e, t), function() {
1419
+ n.off(e, t);
1420
+ };
1421
+ }
1422
+ const at = Object.freeze({
1423
+ connect: 1,
1424
+ connect_error: 1,
1425
+ disconnect: 1,
1426
+ disconnecting: 1,
1427
+ // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
1428
+ newListener: 1,
1429
+ removeListener: 1
1430
+ });
1431
+ class fe extends u {
1432
+ /**
1433
+ * `Socket` constructor.
1434
+ */
1435
+ constructor(e, t, s) {
1436
+ super(), this.connected = !1, this.recovered = !1, this.receiveBuffer = [], this.sendBuffer = [], this._queue = [], this._queueSeq = 0, this.ids = 0, this.acks = {}, this.flags = {}, this.io = e, this.nsp = t, s && s.auth && (this.auth = s.auth), this._opts = Object.assign({}, s), this.io._autoConnect && this.open();
1437
+ }
1438
+ /**
1439
+ * Whether the socket is currently disconnected
1440
+ *
1441
+ * @example
1442
+ * const socket = io();
1443
+ *
1444
+ * socket.on("connect", () => {
1445
+ * console.log(socket.disconnected); // false
1446
+ * });
1447
+ *
1448
+ * socket.on("disconnect", () => {
1449
+ * console.log(socket.disconnected); // true
1450
+ * });
1451
+ */
1452
+ get disconnected() {
1453
+ return !this.connected;
1454
+ }
1455
+ /**
1456
+ * Subscribe to open, close and packet events
1457
+ *
1458
+ * @private
1459
+ */
1460
+ subEvents() {
1461
+ if (this.subs)
1462
+ return;
1463
+ const e = this.io;
1464
+ this.subs = [
1465
+ y(e, "open", this.onopen.bind(this)),
1466
+ y(e, "packet", this.onpacket.bind(this)),
1467
+ y(e, "error", this.onerror.bind(this)),
1468
+ y(e, "close", this.onclose.bind(this))
1469
+ ];
1470
+ }
1471
+ /**
1472
+ * Whether the Socket will try to reconnect when its Manager connects or reconnects.
1473
+ *
1474
+ * @example
1475
+ * const socket = io();
1476
+ *
1477
+ * console.log(socket.active); // true
1478
+ *
1479
+ * socket.on("disconnect", (reason) => {
1480
+ * if (reason === "io server disconnect") {
1481
+ * // the disconnection was initiated by the server, you need to manually reconnect
1482
+ * console.log(socket.active); // false
1483
+ * }
1484
+ * // else the socket will automatically try to reconnect
1485
+ * console.log(socket.active); // true
1486
+ * });
1487
+ */
1488
+ get active() {
1489
+ return !!this.subs;
1490
+ }
1491
+ /**
1492
+ * "Opens" the socket.
1493
+ *
1494
+ * @example
1495
+ * const socket = io({
1496
+ * autoConnect: false
1497
+ * });
1498
+ *
1499
+ * socket.connect();
1500
+ */
1501
+ connect() {
1502
+ return this.connected ? this : (this.subEvents(), this.io._reconnecting || this.io.open(), this.io._readyState === "open" && this.onopen(), this);
1503
+ }
1504
+ /**
1505
+ * Alias for {@link connect()}.
1506
+ */
1507
+ open() {
1508
+ return this.connect();
1509
+ }
1510
+ /**
1511
+ * Sends a `message` event.
1512
+ *
1513
+ * This method mimics the WebSocket.send() method.
1514
+ *
1515
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
1516
+ *
1517
+ * @example
1518
+ * socket.send("hello");
1519
+ *
1520
+ * // this is equivalent to
1521
+ * socket.emit("message", "hello");
1522
+ *
1523
+ * @return self
1524
+ */
1525
+ send(...e) {
1526
+ return e.unshift("message"), this.emit.apply(this, e), this;
1527
+ }
1528
+ /**
1529
+ * Override `emit`.
1530
+ * If the event is in `events`, it's emitted normally.
1531
+ *
1532
+ * @example
1533
+ * socket.emit("hello", "world");
1534
+ *
1535
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
1536
+ * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
1537
+ *
1538
+ * // with an acknowledgement from the server
1539
+ * socket.emit("hello", "world", (val) => {
1540
+ * // ...
1541
+ * });
1542
+ *
1543
+ * @return self
1544
+ */
1545
+ emit(e, ...t) {
1546
+ var s, i, r;
1547
+ if (at.hasOwnProperty(e))
1548
+ throw new Error('"' + e.toString() + '" is a reserved event name');
1549
+ if (t.unshift(e), this._opts.retries && !this.flags.fromQueue && !this.flags.volatile)
1550
+ return this._addToQueue(t), this;
1551
+ const o = {
1552
+ type: h.EVENT,
1553
+ data: t
1554
+ };
1555
+ if (o.options = {}, o.options.compress = this.flags.compress !== !1, typeof t[t.length - 1] == "function") {
1556
+ const _ = this.ids++, p = t.pop();
1557
+ this._registerAckCallback(_, p), o.id = _;
1558
+ }
1559
+ const c = (i = (s = this.io.engine) === null || s === void 0 ? void 0 : s.transport) === null || i === void 0 ? void 0 : i.writable, l = this.connected && !(!((r = this.io.engine) === null || r === void 0) && r._hasPingExpired());
1560
+ return this.flags.volatile && !c || (l ? (this.notifyOutgoingListeners(o), this.packet(o)) : this.sendBuffer.push(o)), this.flags = {}, this;
1561
+ }
1562
+ /**
1563
+ * @private
1564
+ */
1565
+ _registerAckCallback(e, t) {
1566
+ var s;
1567
+ const i = (s = this.flags.timeout) !== null && s !== void 0 ? s : this._opts.ackTimeout;
1568
+ if (i === void 0) {
1569
+ this.acks[e] = t;
1570
+ return;
1571
+ }
1572
+ const r = this.io.setTimeoutFn(() => {
1573
+ delete this.acks[e];
1574
+ for (let c = 0; c < this.sendBuffer.length; c++)
1575
+ this.sendBuffer[c].id === e && this.sendBuffer.splice(c, 1);
1576
+ t.call(this, new Error("operation has timed out"));
1577
+ }, i), o = (...c) => {
1578
+ this.io.clearTimeoutFn(r), t.apply(this, c);
1579
+ };
1580
+ o.withError = !0, this.acks[e] = o;
1581
+ }
1582
+ /**
1583
+ * Emits an event and waits for an acknowledgement
1584
+ *
1585
+ * @example
1586
+ * // without timeout
1587
+ * const response = await socket.emitWithAck("hello", "world");
1588
+ *
1589
+ * // with a specific timeout
1590
+ * try {
1591
+ * const response = await socket.timeout(1000).emitWithAck("hello", "world");
1592
+ * } catch (err) {
1593
+ * // the server did not acknowledge the event in the given delay
1594
+ * }
1595
+ *
1596
+ * @return a Promise that will be fulfilled when the server acknowledges the event
1597
+ */
1598
+ emitWithAck(e, ...t) {
1599
+ return new Promise((s, i) => {
1600
+ const r = (o, c) => o ? i(o) : s(c);
1601
+ r.withError = !0, t.push(r), this.emit(e, ...t);
1602
+ });
1603
+ }
1604
+ /**
1605
+ * Add the packet to the queue.
1606
+ * @param args
1607
+ * @private
1608
+ */
1609
+ _addToQueue(e) {
1610
+ let t;
1611
+ typeof e[e.length - 1] == "function" && (t = e.pop());
1612
+ const s = {
1613
+ id: this._queueSeq++,
1614
+ tryCount: 0,
1615
+ pending: !1,
1616
+ args: e,
1617
+ flags: Object.assign({ fromQueue: !0 }, this.flags)
1618
+ };
1619
+ e.push((i, ...r) => (this._queue[0], i !== null ? s.tryCount > this._opts.retries && (this._queue.shift(), t && t(i)) : (this._queue.shift(), t && t(null, ...r)), s.pending = !1, this._drainQueue())), this._queue.push(s), this._drainQueue();
1620
+ }
1621
+ /**
1622
+ * Send the first packet of the queue, and wait for an acknowledgement from the server.
1623
+ * @param force - whether to resend a packet that has not been acknowledged yet
1624
+ *
1625
+ * @private
1626
+ */
1627
+ _drainQueue(e = !1) {
1628
+ if (!this.connected || this._queue.length === 0)
1629
+ return;
1630
+ const t = this._queue[0];
1631
+ t.pending && !e || (t.pending = !0, t.tryCount++, this.flags = t.flags, this.emit.apply(this, t.args));
1632
+ }
1633
+ /**
1634
+ * Sends a packet.
1635
+ *
1636
+ * @param packet
1637
+ * @private
1638
+ */
1639
+ packet(e) {
1640
+ e.nsp = this.nsp, this.io._packet(e);
1641
+ }
1642
+ /**
1643
+ * Called upon engine `open`.
1644
+ *
1645
+ * @private
1646
+ */
1647
+ onopen() {
1648
+ typeof this.auth == "function" ? this.auth((e) => {
1649
+ this._sendConnectPacket(e);
1650
+ }) : this._sendConnectPacket(this.auth);
1651
+ }
1652
+ /**
1653
+ * Sends a CONNECT packet to initiate the Socket.IO session.
1654
+ *
1655
+ * @param data
1656
+ * @private
1657
+ */
1658
+ _sendConnectPacket(e) {
1659
+ this.packet({
1660
+ type: h.CONNECT,
1661
+ data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, e) : e
1662
+ });
1663
+ }
1664
+ /**
1665
+ * Called upon engine or manager `error`.
1666
+ *
1667
+ * @param err
1668
+ * @private
1669
+ */
1670
+ onerror(e) {
1671
+ this.connected || this.emitReserved("connect_error", e);
1672
+ }
1673
+ /**
1674
+ * Called upon engine `close`.
1675
+ *
1676
+ * @param reason
1677
+ * @param description
1678
+ * @private
1679
+ */
1680
+ onclose(e, t) {
1681
+ this.connected = !1, delete this.id, this.emitReserved("disconnect", e, t), this._clearAcks();
1682
+ }
1683
+ /**
1684
+ * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
1685
+ * the server.
1686
+ *
1687
+ * @private
1688
+ */
1689
+ _clearAcks() {
1690
+ Object.keys(this.acks).forEach((e) => {
1691
+ if (!this.sendBuffer.some((s) => String(s.id) === e)) {
1692
+ const s = this.acks[e];
1693
+ delete this.acks[e], s.withError && s.call(this, new Error("socket has been disconnected"));
1694
+ }
1695
+ });
1696
+ }
1697
+ /**
1698
+ * Called with socket packet.
1699
+ *
1700
+ * @param packet
1701
+ * @private
1702
+ */
1703
+ onpacket(e) {
1704
+ if (e.nsp === this.nsp)
1705
+ switch (e.type) {
1706
+ case h.CONNECT:
1707
+ e.data && e.data.sid ? this.onconnect(e.data.sid, e.data.pid) : 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/)"));
1708
+ break;
1709
+ case h.EVENT:
1710
+ case h.BINARY_EVENT:
1711
+ this.onevent(e);
1712
+ break;
1713
+ case h.ACK:
1714
+ case h.BINARY_ACK:
1715
+ this.onack(e);
1716
+ break;
1717
+ case h.DISCONNECT:
1718
+ this.ondisconnect();
1719
+ break;
1720
+ case h.CONNECT_ERROR:
1721
+ this.destroy();
1722
+ const s = new Error(e.data.message);
1723
+ s.data = e.data.data, this.emitReserved("connect_error", s);
1724
+ break;
1725
+ }
1726
+ }
1727
+ /**
1728
+ * Called upon a server event.
1729
+ *
1730
+ * @param packet
1731
+ * @private
1732
+ */
1733
+ onevent(e) {
1734
+ const t = e.data || [];
1735
+ e.id != null && t.push(this.ack(e.id)), this.connected ? this.emitEvent(t) : this.receiveBuffer.push(Object.freeze(t));
1736
+ }
1737
+ emitEvent(e) {
1738
+ if (this._anyListeners && this._anyListeners.length) {
1739
+ const t = this._anyListeners.slice();
1740
+ for (const s of t)
1741
+ s.apply(this, e);
1742
+ }
1743
+ super.emit.apply(this, e), this._pid && e.length && typeof e[e.length - 1] == "string" && (this._lastOffset = e[e.length - 1]);
1744
+ }
1745
+ /**
1746
+ * Produces an ack callback to emit with an event.
1747
+ *
1748
+ * @private
1749
+ */
1750
+ ack(e) {
1751
+ const t = this;
1752
+ let s = !1;
1753
+ return function(...i) {
1754
+ s || (s = !0, t.packet({
1755
+ type: h.ACK,
1756
+ id: e,
1757
+ data: i
1758
+ }));
1759
+ };
1760
+ }
1761
+ /**
1762
+ * Called upon a server acknowledgement.
1763
+ *
1764
+ * @param packet
1765
+ * @private
1766
+ */
1767
+ onack(e) {
1768
+ const t = this.acks[e.id];
1769
+ typeof t == "function" && (delete this.acks[e.id], t.withError && e.data.unshift(null), t.apply(this, e.data));
1770
+ }
1771
+ /**
1772
+ * Called upon server connect.
1773
+ *
1774
+ * @private
1775
+ */
1776
+ onconnect(e, t) {
1777
+ this.id = e, this.recovered = t && this._pid === t, this._pid = t, this.connected = !0, this.emitBuffered(), this._drainQueue(!0), this.emitReserved("connect");
1778
+ }
1779
+ /**
1780
+ * Emit buffered events (received and emitted).
1781
+ *
1782
+ * @private
1783
+ */
1784
+ emitBuffered() {
1785
+ this.receiveBuffer.forEach((e) => this.emitEvent(e)), this.receiveBuffer = [], this.sendBuffer.forEach((e) => {
1786
+ this.notifyOutgoingListeners(e), this.packet(e);
1787
+ }), this.sendBuffer = [];
1788
+ }
1789
+ /**
1790
+ * Called upon server disconnect.
1791
+ *
1792
+ * @private
1793
+ */
1794
+ ondisconnect() {
1795
+ this.destroy(), this.onclose("io server disconnect");
1796
+ }
1797
+ /**
1798
+ * Called upon forced client/server side disconnections,
1799
+ * this method ensures the manager stops tracking us and
1800
+ * that reconnections don't get triggered for this.
1801
+ *
1802
+ * @private
1803
+ */
1804
+ destroy() {
1805
+ this.subs && (this.subs.forEach((e) => e()), this.subs = void 0), this.io._destroy(this);
1806
+ }
1807
+ /**
1808
+ * Disconnects the socket manually. In that case, the socket will not try to reconnect.
1809
+ *
1810
+ * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
1811
+ *
1812
+ * @example
1813
+ * const socket = io();
1814
+ *
1815
+ * socket.on("disconnect", (reason) => {
1816
+ * // console.log(reason); prints "io client disconnect"
1817
+ * });
1818
+ *
1819
+ * socket.disconnect();
1820
+ *
1821
+ * @return self
1822
+ */
1823
+ disconnect() {
1824
+ return this.connected && this.packet({ type: h.DISCONNECT }), this.destroy(), this.connected && this.onclose("io client disconnect"), this;
1825
+ }
1826
+ /**
1827
+ * Alias for {@link disconnect()}.
1828
+ *
1829
+ * @return self
1830
+ */
1831
+ close() {
1832
+ return this.disconnect();
1833
+ }
1834
+ /**
1835
+ * Sets the compress flag.
1836
+ *
1837
+ * @example
1838
+ * socket.compress(false).emit("hello");
1839
+ *
1840
+ * @param compress - if `true`, compresses the sending data
1841
+ * @return self
1842
+ */
1843
+ compress(e) {
1844
+ return this.flags.compress = e, this;
1845
+ }
1846
+ /**
1847
+ * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
1848
+ * ready to send messages.
1849
+ *
1850
+ * @example
1851
+ * socket.volatile.emit("hello"); // the server may or may not receive it
1852
+ *
1853
+ * @returns self
1854
+ */
1855
+ get volatile() {
1856
+ return this.flags.volatile = !0, this;
1857
+ }
1858
+ /**
1859
+ * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
1860
+ * given number of milliseconds have elapsed without an acknowledgement from the server:
1861
+ *
1862
+ * @example
1863
+ * socket.timeout(5000).emit("my-event", (err) => {
1864
+ * if (err) {
1865
+ * // the server did not acknowledge the event in the given delay
1866
+ * }
1867
+ * });
1868
+ *
1869
+ * @returns self
1870
+ */
1871
+ timeout(e) {
1872
+ return this.flags.timeout = e, this;
1873
+ }
1874
+ /**
1875
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
1876
+ * callback.
1877
+ *
1878
+ * @example
1879
+ * socket.onAny((event, ...args) => {
1880
+ * console.log(`got ${event}`);
1881
+ * });
1882
+ *
1883
+ * @param listener
1884
+ */
1885
+ onAny(e) {
1886
+ return this._anyListeners = this._anyListeners || [], this._anyListeners.push(e), this;
1887
+ }
1888
+ /**
1889
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
1890
+ * callback. The listener is added to the beginning of the listeners array.
1891
+ *
1892
+ * @example
1893
+ * socket.prependAny((event, ...args) => {
1894
+ * console.log(`got event ${event}`);
1895
+ * });
1896
+ *
1897
+ * @param listener
1898
+ */
1899
+ prependAny(e) {
1900
+ return this._anyListeners = this._anyListeners || [], this._anyListeners.unshift(e), this;
1901
+ }
1902
+ /**
1903
+ * Removes the listener that will be fired when any event is emitted.
1904
+ *
1905
+ * @example
1906
+ * const catchAllListener = (event, ...args) => {
1907
+ * console.log(`got event ${event}`);
1908
+ * }
1909
+ *
1910
+ * socket.onAny(catchAllListener);
1911
+ *
1912
+ * // remove a specific listener
1913
+ * socket.offAny(catchAllListener);
1914
+ *
1915
+ * // or remove all listeners
1916
+ * socket.offAny();
1917
+ *
1918
+ * @param listener
1919
+ */
1920
+ offAny(e) {
1921
+ if (!this._anyListeners)
1922
+ return this;
1923
+ if (e) {
1924
+ const t = this._anyListeners;
1925
+ for (let s = 0; s < t.length; s++)
1926
+ if (e === t[s])
1927
+ return t.splice(s, 1), this;
1928
+ } else
1929
+ this._anyListeners = [];
1930
+ return this;
1931
+ }
1932
+ /**
1933
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
1934
+ * e.g. to remove listeners.
1935
+ */
1936
+ listenersAny() {
1937
+ return this._anyListeners || [];
1938
+ }
1939
+ /**
1940
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
1941
+ * callback.
1942
+ *
1943
+ * Note: acknowledgements sent to the server are not included.
1944
+ *
1945
+ * @example
1946
+ * socket.onAnyOutgoing((event, ...args) => {
1947
+ * console.log(`sent event ${event}`);
1948
+ * });
1949
+ *
1950
+ * @param listener
1951
+ */
1952
+ onAnyOutgoing(e) {
1953
+ return this._anyOutgoingListeners = this._anyOutgoingListeners || [], this._anyOutgoingListeners.push(e), this;
1954
+ }
1955
+ /**
1956
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
1957
+ * callback. The listener is added to the beginning of the listeners array.
1958
+ *
1959
+ * Note: acknowledgements sent to the server are not included.
1960
+ *
1961
+ * @example
1962
+ * socket.prependAnyOutgoing((event, ...args) => {
1963
+ * console.log(`sent event ${event}`);
1964
+ * });
1965
+ *
1966
+ * @param listener
1967
+ */
1968
+ prependAnyOutgoing(e) {
1969
+ return this._anyOutgoingListeners = this._anyOutgoingListeners || [], this._anyOutgoingListeners.unshift(e), this;
1970
+ }
1971
+ /**
1972
+ * Removes the listener that will be fired when any event is emitted.
1973
+ *
1974
+ * @example
1975
+ * const catchAllListener = (event, ...args) => {
1976
+ * console.log(`sent event ${event}`);
1977
+ * }
1978
+ *
1979
+ * socket.onAnyOutgoing(catchAllListener);
1980
+ *
1981
+ * // remove a specific listener
1982
+ * socket.offAnyOutgoing(catchAllListener);
1983
+ *
1984
+ * // or remove all listeners
1985
+ * socket.offAnyOutgoing();
1986
+ *
1987
+ * @param [listener] - the catch-all listener (optional)
1988
+ */
1989
+ offAnyOutgoing(e) {
1990
+ if (!this._anyOutgoingListeners)
1991
+ return this;
1992
+ if (e) {
1993
+ const t = this._anyOutgoingListeners;
1994
+ for (let s = 0; s < t.length; s++)
1995
+ if (e === t[s])
1996
+ return t.splice(s, 1), this;
1997
+ } else
1998
+ this._anyOutgoingListeners = [];
1999
+ return this;
2000
+ }
2001
+ /**
2002
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
2003
+ * e.g. to remove listeners.
2004
+ */
2005
+ listenersAnyOutgoing() {
2006
+ return this._anyOutgoingListeners || [];
2007
+ }
2008
+ /**
2009
+ * Notify the listeners for each packet sent
2010
+ *
2011
+ * @param packet
2012
+ *
2013
+ * @private
2014
+ */
2015
+ notifyOutgoingListeners(e) {
2016
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
2017
+ const t = this._anyOutgoingListeners.slice();
2018
+ for (const s of t)
2019
+ s.apply(this, e.data);
2020
+ }
2021
+ }
2022
+ }
2023
+ function v(n) {
2024
+ n = n || {}, this.ms = n.min || 100, this.max = n.max || 1e4, this.factor = n.factor || 2, this.jitter = n.jitter > 0 && n.jitter <= 1 ? n.jitter : 0, this.attempts = 0;
2025
+ }
2026
+ v.prototype.duration = function() {
2027
+ var n = this.ms * Math.pow(this.factor, this.attempts++);
2028
+ if (this.jitter) {
2029
+ var e = Math.random(), t = Math.floor(e * this.jitter * n);
2030
+ n = (Math.floor(e * 10) & 1) == 0 ? n - t : n + t;
2031
+ }
2032
+ return Math.min(n, this.max) | 0;
2033
+ };
2034
+ v.prototype.reset = function() {
2035
+ this.attempts = 0;
2036
+ };
2037
+ v.prototype.setMin = function(n) {
2038
+ this.ms = n;
2039
+ };
2040
+ v.prototype.setMax = function(n) {
2041
+ this.max = n;
2042
+ };
2043
+ v.prototype.setJitter = function(n) {
2044
+ this.jitter = n;
2045
+ };
2046
+ class V extends u {
2047
+ constructor(e, t) {
2048
+ var s;
2049
+ super(), this.nsps = {}, this.subs = [], e && typeof e == "object" && (t = e, e = void 0), t = t || {}, t.path = t.path || "/socket.io", this.opts = t, L(this, t), this.reconnection(t.reconnection !== !1), this.reconnectionAttempts(t.reconnectionAttempts || 1 / 0), this.reconnectionDelay(t.reconnectionDelay || 1e3), this.reconnectionDelayMax(t.reconnectionDelayMax || 5e3), this.randomizationFactor((s = t.randomizationFactor) !== null && s !== void 0 ? s : 0.5), this.backoff = new v({
2050
+ min: this.reconnectionDelay(),
2051
+ max: this.reconnectionDelayMax(),
2052
+ jitter: this.randomizationFactor()
2053
+ }), this.timeout(t.timeout == null ? 2e4 : t.timeout), this._readyState = "closed", this.uri = e;
2054
+ const i = t.parser || ot;
2055
+ this.encoder = new i.Encoder(), this.decoder = new i.Decoder(), this._autoConnect = t.autoConnect !== !1, this._autoConnect && this.open();
2056
+ }
2057
+ reconnection(e) {
2058
+ return arguments.length ? (this._reconnection = !!e, e || (this.skipReconnect = !0), this) : this._reconnection;
2059
+ }
2060
+ reconnectionAttempts(e) {
2061
+ return e === void 0 ? this._reconnectionAttempts : (this._reconnectionAttempts = e, this);
2062
+ }
2063
+ reconnectionDelay(e) {
2064
+ var t;
2065
+ return e === void 0 ? this._reconnectionDelay : (this._reconnectionDelay = e, (t = this.backoff) === null || t === void 0 || t.setMin(e), this);
2066
+ }
2067
+ randomizationFactor(e) {
2068
+ var t;
2069
+ return e === void 0 ? this._randomizationFactor : (this._randomizationFactor = e, (t = this.backoff) === null || t === void 0 || t.setJitter(e), this);
2070
+ }
2071
+ reconnectionDelayMax(e) {
2072
+ var t;
2073
+ return e === void 0 ? this._reconnectionDelayMax : (this._reconnectionDelayMax = e, (t = this.backoff) === null || t === void 0 || t.setMax(e), this);
2074
+ }
2075
+ timeout(e) {
2076
+ return arguments.length ? (this._timeout = e, this) : this._timeout;
2077
+ }
2078
+ /**
2079
+ * Starts trying to reconnect if reconnection is enabled and we have not
2080
+ * started reconnecting yet
2081
+ *
2082
+ * @private
2083
+ */
2084
+ maybeReconnectOnOpen() {
2085
+ !this._reconnecting && this._reconnection && this.backoff.attempts === 0 && this.reconnect();
2086
+ }
2087
+ /**
2088
+ * Sets the current transport `socket`.
2089
+ *
2090
+ * @param {Function} fn - optional, callback
2091
+ * @return self
2092
+ * @public
2093
+ */
2094
+ open(e) {
2095
+ if (~this._readyState.indexOf("open"))
2096
+ return this;
2097
+ this.engine = new Je(this.uri, this.opts);
2098
+ const t = this.engine, s = this;
2099
+ this._readyState = "opening", this.skipReconnect = !1;
2100
+ const i = y(t, "open", function() {
2101
+ s.onopen(), e && e();
2102
+ }), r = (c) => {
2103
+ this.cleanup(), this._readyState = "closed", this.emitReserved("error", c), e ? e(c) : this.maybeReconnectOnOpen();
2104
+ }, o = y(t, "error", r);
2105
+ if (this._timeout !== !1) {
2106
+ const c = this._timeout, l = this.setTimeoutFn(() => {
2107
+ i(), r(new Error("timeout")), t.close();
2108
+ }, c);
2109
+ this.opts.autoUnref && l.unref(), this.subs.push(() => {
2110
+ this.clearTimeoutFn(l);
2111
+ });
2112
+ }
2113
+ return this.subs.push(i), this.subs.push(o), this;
2114
+ }
2115
+ /**
2116
+ * Alias for open()
2117
+ *
2118
+ * @return self
2119
+ * @public
2120
+ */
2121
+ connect(e) {
2122
+ return this.open(e);
2123
+ }
2124
+ /**
2125
+ * Called upon transport open.
2126
+ *
2127
+ * @private
2128
+ */
2129
+ onopen() {
2130
+ this.cleanup(), this._readyState = "open", this.emitReserved("open");
2131
+ const e = this.engine;
2132
+ this.subs.push(
2133
+ y(e, "ping", this.onping.bind(this)),
2134
+ y(e, "data", this.ondata.bind(this)),
2135
+ y(e, "error", this.onerror.bind(this)),
2136
+ y(e, "close", this.onclose.bind(this)),
2137
+ // @ts-ignore
2138
+ y(this.decoder, "decoded", this.ondecoded.bind(this))
2139
+ );
2140
+ }
2141
+ /**
2142
+ * Called upon a ping.
2143
+ *
2144
+ * @private
2145
+ */
2146
+ onping() {
2147
+ this.emitReserved("ping");
2148
+ }
2149
+ /**
2150
+ * Called with data.
2151
+ *
2152
+ * @private
2153
+ */
2154
+ ondata(e) {
2155
+ try {
2156
+ this.decoder.add(e);
2157
+ } catch (t) {
2158
+ this.onclose("parse error", t);
2159
+ }
2160
+ }
2161
+ /**
2162
+ * Called when parser fully decodes a packet.
2163
+ *
2164
+ * @private
2165
+ */
2166
+ ondecoded(e) {
2167
+ O(() => {
2168
+ this.emitReserved("packet", e);
2169
+ }, this.setTimeoutFn);
2170
+ }
2171
+ /**
2172
+ * Called upon socket error.
2173
+ *
2174
+ * @private
2175
+ */
2176
+ onerror(e) {
2177
+ this.emitReserved("error", e);
2178
+ }
2179
+ /**
2180
+ * Creates a new socket for the given `nsp`.
2181
+ *
2182
+ * @return {Socket}
2183
+ * @public
2184
+ */
2185
+ socket(e, t) {
2186
+ let s = this.nsps[e];
2187
+ return s ? this._autoConnect && !s.active && s.connect() : (s = new fe(this, e, t), this.nsps[e] = s), s;
2188
+ }
2189
+ /**
2190
+ * Called upon a socket close.
2191
+ *
2192
+ * @param socket
2193
+ * @private
2194
+ */
2195
+ _destroy(e) {
2196
+ const t = Object.keys(this.nsps);
2197
+ for (const s of t)
2198
+ if (this.nsps[s].active)
2199
+ return;
2200
+ this._close();
2201
+ }
2202
+ /**
2203
+ * Writes a packet.
2204
+ *
2205
+ * @param packet
2206
+ * @private
2207
+ */
2208
+ _packet(e) {
2209
+ const t = this.encoder.encode(e);
2210
+ for (let s = 0; s < t.length; s++)
2211
+ this.engine.write(t[s], e.options);
2212
+ }
2213
+ /**
2214
+ * Clean up transport subscriptions and packet buffer.
2215
+ *
2216
+ * @private
2217
+ */
2218
+ cleanup() {
2219
+ this.subs.forEach((e) => e()), this.subs.length = 0, this.decoder.destroy();
2220
+ }
2221
+ /**
2222
+ * Close the current socket.
2223
+ *
2224
+ * @private
2225
+ */
2226
+ _close() {
2227
+ this.skipReconnect = !0, this._reconnecting = !1, this.onclose("forced close");
2228
+ }
2229
+ /**
2230
+ * Alias for close()
2231
+ *
2232
+ * @private
2233
+ */
2234
+ disconnect() {
2235
+ return this._close();
2236
+ }
2237
+ /**
2238
+ * Called when:
2239
+ *
2240
+ * - the low-level engine is closed
2241
+ * - the parser encountered a badly formatted packet
2242
+ * - all sockets are disconnected
2243
+ *
2244
+ * @private
2245
+ */
2246
+ onclose(e, t) {
2247
+ var s;
2248
+ this.cleanup(), (s = this.engine) === null || s === void 0 || s.close(), this.backoff.reset(), this._readyState = "closed", this.emitReserved("close", e, t), this._reconnection && !this.skipReconnect && this.reconnect();
2249
+ }
2250
+ /**
2251
+ * Attempt a reconnection.
2252
+ *
2253
+ * @private
2254
+ */
2255
+ reconnect() {
2256
+ if (this._reconnecting || this.skipReconnect)
2257
+ return this;
2258
+ const e = this;
2259
+ if (this.backoff.attempts >= this._reconnectionAttempts)
2260
+ this.backoff.reset(), this.emitReserved("reconnect_failed"), this._reconnecting = !1;
2261
+ else {
2262
+ const t = this.backoff.duration();
2263
+ this._reconnecting = !0;
2264
+ const s = this.setTimeoutFn(() => {
2265
+ e.skipReconnect || (this.emitReserved("reconnect_attempt", e.backoff.attempts), !e.skipReconnect && e.open((i) => {
2266
+ i ? (e._reconnecting = !1, e.reconnect(), this.emitReserved("reconnect_error", i)) : e.onreconnect();
2267
+ }));
2268
+ }, t);
2269
+ this.opts.autoUnref && s.unref(), this.subs.push(() => {
2270
+ this.clearTimeoutFn(s);
2271
+ });
2272
+ }
2273
+ }
2274
+ /**
2275
+ * Called upon successful reconnect.
2276
+ *
2277
+ * @private
2278
+ */
2279
+ onreconnect() {
2280
+ const e = this.backoff.attempts;
2281
+ this._reconnecting = !1, this.backoff.reset(), this.emitReserved("reconnect", e);
2282
+ }
2283
+ }
2284
+ const k = {};
2285
+ function B(n, e) {
2286
+ typeof n == "object" && (e = n, n = void 0), e = e || {};
2287
+ const t = je(n, e.path || "/socket.io"), s = t.source, i = t.id, r = t.path, o = k[i] && r in k[i].nsps, c = e.forceNew || e["force new connection"] || e.multiplex === !1 || o;
2288
+ let l;
2289
+ return c ? l = new V(s, e) : (k[i] || (k[i] = new V(s, e)), l = k[i]), t.query && !e.query && (e.query = t.queryKey), l.socket(t.path, e);
2290
+ }
2291
+ Object.assign(B, {
2292
+ Manager: V,
2293
+ Socket: fe,
2294
+ io: B,
2295
+ connect: B
2296
+ });
2297
+ class Z extends CustomEvent {
2298
+ constructor(e, t) {
2299
+ super(e, t);
2300
+ }
2301
+ }
2302
+ class pe extends EventTarget {
2303
+ __listeners__ = {
2304
+ debug: !1
2305
+ };
2306
+ __debug__ = !1;
2307
+ __listenersCallbacks__ = [];
2308
+ /**
2309
+ * Dispatches an event with the specified type and data
2310
+ * @param type - The event type to dispatch
2311
+ * @param data - Optional data to attach to the event
2312
+ * @example
2313
+ * ```typescript
2314
+ * dispatcher.dispatch('connected', { port: 'COM3' });
2315
+ * ```
2316
+ */
2317
+ dispatch(e, t = null) {
2318
+ const s = new Z(e, { detail: t });
2319
+ this.dispatchEvent(s), this.__debug__ && this.dispatchEvent(new Z("debug", { detail: { type: e, data: t } }));
2320
+ }
2321
+ /**
2322
+ * Dispatches an event asynchronously after a specified delay
2323
+ * @param type - The event type to dispatch
2324
+ * @param data - Optional data to attach to the event
2325
+ * @param ms - Delay in milliseconds (default: 100)
2326
+ * @example
2327
+ * ```typescript
2328
+ * dispatcher.dispatchAsync('timeout', { reason: 'no response' }, 500);
2329
+ * ```
2330
+ */
2331
+ dispatchAsync(e, t = null, s = 100) {
2332
+ const i = this;
2333
+ setTimeout(() => {
2334
+ i.dispatch(e, t);
2335
+ }, s);
2336
+ }
2337
+ /**
2338
+ * Registers an event listener for the specified event type
2339
+ * @param type - The event type to listen to
2340
+ * @param callback - The callback function to execute when the event is triggered
2341
+ * @example
2342
+ * ```typescript
2343
+ * dispatcher.on('connected', (event) => {
2344
+ * console.log('Device connected', event.detail);
2345
+ * });
2346
+ * ```
2347
+ */
2348
+ on(e, t) {
2349
+ typeof this.__listeners__[e] < "u" && !this.__listeners__[e] && (this.__listeners__[e] = !0), this.__listenersCallbacks__.push({ key: e, callback: t }), this.addEventListener(e, t);
2350
+ }
2351
+ /**
2352
+ * Removes an event listener for the specified event type
2353
+ * @param type - The event type to stop listening to
2354
+ * @param callback - The callback function to remove
2355
+ * @example
2356
+ * ```typescript
2357
+ * const handler = (event) => console.log(event.detail);
2358
+ * dispatcher.on('data', handler);
2359
+ * dispatcher.off('data', handler);
2360
+ * ```
2361
+ */
2362
+ off(e, t) {
2363
+ this.__listenersCallbacks__ = this.__listenersCallbacks__.filter((s) => !(s.key === e && s.callback === t)), this.removeEventListener(e, t);
2364
+ }
2365
+ /**
2366
+ * Registers an available listener type for tracking
2367
+ * @param type - The event type to register
2368
+ * @internal
2369
+ */
2370
+ serialRegisterAvailableListener(e) {
2371
+ this.__listeners__[e] || (this.__listeners__[e] = !1);
2372
+ }
2373
+ /**
2374
+ * Gets the list of all available listeners and their state
2375
+ * @returns Array of listener objects with type and listening status
2376
+ * @example
2377
+ * ```typescript
2378
+ * const listeners = dispatcher.availableListeners;
2379
+ * console.log(listeners); // [{ type: 'connected', listening: true }, ...]
2380
+ * ```
2381
+ */
2382
+ get availableListeners() {
2383
+ return Object.keys(this.__listeners__).sort().map((e) => ({
2384
+ type: e,
2385
+ listening: this.__listeners__[e]
2386
+ }));
2387
+ }
2388
+ /**
2389
+ * Removes all event listeners except internal ones (like queue listeners)
2390
+ * Resets all listener states to false
2391
+ * @example
2392
+ * ```typescript
2393
+ * dispatcher.removeAllListeners();
2394
+ * ```
2395
+ */
2396
+ removeAllListeners() {
2397
+ for (const e of this.__listenersCallbacks__)
2398
+ ["internal:queue"].includes(e.key) || (this.__listenersCallbacks__ = this.__listenersCallbacks__.filter((t) => !(t.key === e.key && t.callback === e.callback)), this.removeEventListener(e.key, e.callback));
2399
+ for (const e of Object.keys(this.__listeners__))
2400
+ this.__listeners__[e] = !1;
2401
+ }
2402
+ }
2403
+ class a extends pe {
2404
+ static instance;
2405
+ static devices = {};
2406
+ constructor() {
2407
+ super(), ["change"].forEach((e) => {
2408
+ this.serialRegisterAvailableListener(e);
2409
+ });
2410
+ }
2411
+ static $dispatchChange(e = null) {
2412
+ e && e.$checkAndDispatchConnection(), a.instance.dispatch("change", { devices: a.devices, dispatcher: e });
2413
+ }
2414
+ static typeError(e) {
2415
+ const t = new Error();
2416
+ throw t.message = `Type ${e} is not supported`, t.name = "DeviceTypeError", t;
2417
+ }
2418
+ /**
2419
+ * Registers a new device type in the registry
2420
+ * @param type - The type name of the device (e.g., 'arduino', 'esp32')
2421
+ * @internal
2422
+ */
2423
+ static registerType(e) {
2424
+ typeof a.devices[e] > "u" && (a.devices = { ...a.devices, [e]: {} });
2425
+ }
2426
+ /**
2427
+ * Adds a device to the registry
2428
+ * @param device - The Core device instance to add
2429
+ * @returns The index of the device in its type registry
2430
+ * @throws {Error} If device with the same ID already exists
2431
+ * @example
2432
+ * ```typescript
2433
+ * const arduino = new Arduino();
2434
+ * Devices.add(arduino);
2435
+ * ```
2436
+ */
2437
+ static add(e) {
2438
+ const t = e.typeDevice;
2439
+ typeof a.devices[t] > "u" && a.registerType(t);
2440
+ const s = e.uuid;
2441
+ if (typeof a.devices[t] > "u" && a.typeError(t), a.devices[t][s])
2442
+ throw new Error(`Device with id ${s} already exists`);
2443
+ return a.devices[t][s] = e, a.$dispatchChange(e), Object.keys(a.devices[t]).indexOf(s);
2444
+ }
2445
+ /**
2446
+ * Gets a specific device by type and UUID
2447
+ * @param type - The device type
2448
+ * @param id - The device UUID
2449
+ * @returns The device instance
2450
+ * @throws {Error} If the device type is not supported
2451
+ * @example
2452
+ * ```typescript
2453
+ * const device = Devices.get('arduino', 'uuid-123');
2454
+ * ```
2455
+ */
2456
+ static get(e, t) {
2457
+ return typeof a.devices[e] > "u" && a.registerType(e), typeof a.devices[e] > "u" && a.typeError(e), a.devices[e][t];
2458
+ }
2459
+ static getAll(e = null) {
2460
+ return e === null ? a.devices : (typeof a.devices[e] > "u" && a.typeError(e), a.devices[e]);
2461
+ }
2462
+ static getList() {
2463
+ return Object.values(a.devices).map((e) => Object.values(e)).flat();
2464
+ }
2465
+ static getByNumber(e, t) {
2466
+ return typeof a.devices[e] > "u" && a.typeError(e), Object.values(a.devices[e]).find((s) => s.deviceNumber === t) ?? null;
2467
+ }
2468
+ static getCustom(e, t = 1) {
2469
+ return typeof a.devices[e] > "u" && a.typeError(e), Object.values(a.devices[e]).find((s) => s.deviceNumber === t) ?? null;
2470
+ }
2471
+ static async connectToAll() {
2472
+ const e = a.getList();
2473
+ for (const t of e)
2474
+ t.isConnected || await t.connect().catch(console.warn);
2475
+ return Promise.resolve(a.areAllConnected());
2476
+ }
2477
+ static async disconnectAll() {
2478
+ const e = a.getList();
2479
+ for (const t of e)
2480
+ t.isDisconnected || await t.disconnect().catch(console.warn);
2481
+ return Promise.resolve(a.areAllDisconnected());
2482
+ }
2483
+ static async areAllConnected() {
2484
+ const e = a.getList();
2485
+ for (const t of e)
2486
+ if (!t.isConnected) return Promise.resolve(!1);
2487
+ return Promise.resolve(!0);
2488
+ }
2489
+ static async areAllDisconnected() {
2490
+ const e = a.getList();
2491
+ for (const t of e)
2492
+ if (!t.isDisconnected) return Promise.resolve(!1);
2493
+ return Promise.resolve(!0);
2494
+ }
2495
+ static async getAllConnected() {
2496
+ const e = a.getList();
2497
+ return Promise.resolve(e.filter((t) => t.isConnected));
2498
+ }
2499
+ static async getAllDisconnected() {
2500
+ const e = a.getList();
2501
+ return Promise.resolve(e.filter((t) => t.isDisconnected));
2502
+ }
2503
+ }
2504
+ a.instance || (a.instance = new a());
2505
+ function ee(n = 100) {
2506
+ return new Promise(
2507
+ (e) => setTimeout(() => e(), n)
2508
+ );
2509
+ }
2510
+ class ct {
2511
+ #n = "http://localhost:3001";
2512
+ #t = {
2513
+ transports: ["websocket"]
2514
+ };
2515
+ #e = null;
2516
+ #i = !1;
2517
+ #o = !1;
2518
+ #s;
2519
+ constructor(e, t) {
2520
+ e && (this.#n = e), t && (this.#t = { ...this.#t, ...t }), this.#s = {
2521
+ onResponse: this.onResponse.bind(this),
2522
+ onDisconnect: () => {
2523
+ this.#i = !1, window.dispatchEvent(new Event("serial:socket:disconnected"));
2524
+ },
2525
+ onConnect: () => {
2526
+ this.#i = !0, window.dispatchEvent(new Event("serial:socket:connected"));
2527
+ },
2528
+ onConnectError: (s) => {
2529
+ console.debug("Socket connection error", s), this.#i = !1, window.dispatchEvent(new Event("serial:socket:disconnected"));
2530
+ }
2531
+ };
2532
+ }
2533
+ set uri(e) {
2534
+ const t = new URL(e);
2535
+ if (!["http:", "https:", "ws:", "wss:"].includes(t.protocol))
2536
+ throw new Error("URI must start with http://, https://, ws://, or wss://");
2537
+ this.#n = e;
2538
+ }
2539
+ get uri() {
2540
+ return this.#n;
2541
+ }
2542
+ set options(e) {
2543
+ if (typeof e != "object")
2544
+ throw new Error("Options must be an object");
2545
+ this.#t = e;
2546
+ }
2547
+ get options() {
2548
+ return this.#t;
2549
+ }
2550
+ get socketId() {
2551
+ return this.#e && this.#e.id ? this.#e.id : null;
2552
+ }
2553
+ configure(e, t) {
2554
+ if (this.#o)
2555
+ throw new Error("Cannot configure socket after it has been initialized. Call configure() before prepare().");
2556
+ e && (this.uri = e), t && (this.#t = { ...this.#t, ...t });
2557
+ }
2558
+ disconnect() {
2559
+ this.#e && (this.#e.off("response", this.#s.onResponse), this.#e.off("disconnect", this.#s.onDisconnect), this.#e.off("connect", this.#s.onConnect), this.#e.off("connect_error", this.#s.onConnectError), this.#e.disconnect(), this.#e = null, this.#o = !1), this.#i = !1;
2560
+ }
2561
+ prepare() {
2562
+ this.#i || this.#o || (this.#e = B(this.#n, this.#t), this.#o = !0, this.#e.on("disconnect", this.#s.onDisconnect), this.#e.on("response", this.#s.onResponse), this.#e.on("connect", this.#s.onConnect), this.#e.on("connect_error", this.#s.onConnectError));
2563
+ }
2564
+ connectDevice(e) {
2565
+ if (!this.#e)
2566
+ throw new Error("Socket not connected. Call prepare() first.");
2567
+ this.#e.emit("connectDevice", { config: e });
2568
+ }
2569
+ disconnectDevice(e) {
2570
+ if (!this.#e)
2571
+ throw new Error("Socket not connected. Call prepare() first.");
2572
+ this.#e.emit("disconnectDevice", { config: e });
2573
+ }
2574
+ disconnectAllDevices() {
2575
+ if (!this.#e)
2576
+ throw new Error("Socket not connected. Call prepare() first.");
2577
+ this.#e.emit("disconnectAll");
2578
+ }
2579
+ write(e) {
2580
+ if (!this.#e)
2581
+ throw new Error("Socket not connected. Call prepare() first.");
2582
+ this.#e.emit("cmd", e);
2583
+ }
2584
+ onResponse(e) {
2585
+ let t = a.get(e.name, e.uuid);
2586
+ t || (t = a.getByNumber(e.name, e.deviceNumber)), t && t.socketResponse(e);
2587
+ }
2588
+ isConnected() {
2589
+ return this.#i;
2590
+ }
2591
+ isDisconnected() {
2592
+ return !this.#i;
2593
+ }
2594
+ }
2595
+ const w = new ct(), D = {
2596
+ baudRate: 9600,
2597
+ dataBits: 8,
2598
+ stopBits: 1,
2599
+ parity: "none",
2600
+ bufferSize: 32768,
2601
+ flowControl: "none"
2602
+ };
2603
+ class ht extends pe {
2604
+ __internal__ = {
2605
+ bypassSerialBytesConnection: !1,
2606
+ auto_response: !1,
2607
+ device_number: 1,
2608
+ aux_port_connector: 0,
2609
+ last_error: {
2610
+ message: null,
2611
+ action: null,
2612
+ code: null,
2613
+ no_code: 0
2614
+ },
2615
+ serial: {
2616
+ transformStream: !1,
2617
+ socket: !1,
2618
+ portInfo: {
2619
+ path: null,
2620
+ vendorId: null,
2621
+ productId: null,
2622
+ parser: {
2623
+ name: "inter-byte-timeout",
2624
+ interval: 50
2625
+ }
2626
+ },
2627
+ aux_connecting: "idle",
2628
+ connecting: !1,
2629
+ connected: !1,
2630
+ port: null,
2631
+ last_action: null,
2632
+ response: {
2633
+ length: null,
2634
+ buffer: new Uint8Array([]),
2635
+ as: "uint8",
2636
+ replacer: /[\n\r]+/g,
2637
+ limiter: null,
2638
+ prefixLimiter: !1,
2639
+ sufixLimiter: !0,
2640
+ delimited: !1
2641
+ },
2642
+ reader: null,
2643
+ input_done: null,
2644
+ output_done: null,
2645
+ input_stream: null,
2646
+ output_stream: null,
2647
+ keep_reading: !0,
2648
+ time_until_send_bytes: void 0,
2649
+ delay_first_connection: 200,
2650
+ bytes_connection: null,
2651
+ filters: [],
2652
+ config_port: D,
2653
+ queue: [],
2654
+ running_queue: !1,
2655
+ auto_response: null,
2656
+ free_timeout_ms: 50,
2657
+ // In previous versions 400 was used
2658
+ useRTSCTS: !1,
2659
+ // Use RTS/CTS flow control
2660
+ pipeAbortController: null,
2661
+ pipeDone: null,
2662
+ pumpReader: null
2663
+ },
2664
+ device: {
2665
+ type: "unknown",
2666
+ id: window.crypto.randomUUID(),
2667
+ listen_on_port: null
2668
+ },
2669
+ time: {
2670
+ response_connection: 500,
2671
+ response_engines: 2e3,
2672
+ response_general: 2e3
2673
+ },
2674
+ timeout: {
2675
+ until_response: 0
2676
+ },
2677
+ interval: {
2678
+ reconnection: 0
2679
+ }
2680
+ };
2681
+ #n = null;
2682
+ constructor({
2683
+ filters: e = null,
2684
+ config_port: t = D,
2685
+ no_device: s = 1,
2686
+ device_listen_on_channel: i = 1,
2687
+ bypassSerialBytesConnection: r = !1,
2688
+ socket: o = !1,
2689
+ transformStream: c = !1
2690
+ } = {
2691
+ filters: null,
2692
+ config_port: D,
2693
+ no_device: 1,
2694
+ device_listen_on_channel: 1,
2695
+ bypassSerialBytesConnection: !1,
2696
+ socket: !1,
2697
+ transformStream: !1
2698
+ }) {
2699
+ if (super(), !("serial" in navigator))
2700
+ throw new Error("Web Serial not supported");
2701
+ if (e && (this.serialFilters = e), t && (this.serialConfigPort = t), r && (this.__internal__.bypassSerialBytesConnection = r), s && this.#v(s), i && ["number", "string"].includes(typeof i) && (this.listenOnChannel = i), this.__internal__.serial.socket = o, typeof c == "function")
2702
+ this.__internal__.serial.transformStream = c;
2703
+ else if (c) {
2704
+ const l = c;
2705
+ this.__internal__.serial.transformStream = () => l;
2706
+ } else
2707
+ this.__internal__.serial.transformStream = !1;
2708
+ this.#g(), this.#m();
2709
+ }
2710
+ set listenOnChannel(e) {
2711
+ if (typeof e == "string" && (e = parseInt(e)), isNaN(e) || e < 1 || e > 255)
2712
+ throw new Error("Invalid port number");
2713
+ this.__internal__.device.listen_on_port = e, !this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e));
2714
+ }
2715
+ get lastAction() {
2716
+ return this.__internal__.serial.last_action;
2717
+ }
2718
+ get listenOnChannel() {
2719
+ return this.__internal__.device.listen_on_port ?? 1;
2720
+ }
2721
+ set serialFilters(e) {
2722
+ if (this.isConnected) throw new Error("Cannot change serial filters while connected");
2723
+ this.__internal__.serial.filters = e;
2724
+ }
2725
+ get serialFilters() {
2726
+ return this.__internal__.serial.filters;
2727
+ }
2728
+ set serialConfigPort(e) {
2729
+ if (this.isConnected) throw new Error("Cannot change serial filters while connected");
2730
+ this.__internal__.serial.config_port = e;
2731
+ }
2732
+ get serialConfigPort() {
2733
+ return this.__internal__.serial.config_port;
2734
+ }
2735
+ get useRTSCTS() {
2736
+ return this.__internal__.serial.useRTSCTS;
2737
+ }
2738
+ set useRTSCTS(e) {
2739
+ this.__internal__.serial.useRTSCTS = e;
2740
+ }
2741
+ get isConnected() {
2742
+ const e = this.__internal__.serial.connected, t = this.#t(this.__internal__.serial.port);
2743
+ return e && !t && this.#e({ error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
2744
+ }
2745
+ get isConnecting() {
2746
+ return this.__internal__.serial.connecting;
2747
+ }
2748
+ get isDisconnected() {
2749
+ const e = this.__internal__.serial.connected, t = this.#t(this.__internal__.serial.port);
2750
+ return !e && t && (this.dispatch("serial:connected"), this.#a(!1), a.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
2751
+ }
2752
+ get deviceNumber() {
2753
+ return this.__internal__.device_number;
2754
+ }
2755
+ get uuid() {
2756
+ return this.__internal__.device.id;
2757
+ }
2758
+ get typeDevice() {
2759
+ return this.__internal__.device.type;
2760
+ }
2761
+ get queue() {
2762
+ return this.__internal__.serial.queue;
2763
+ }
2764
+ get responseDelimited() {
2765
+ return this.__internal__.serial.response.delimited;
2766
+ }
2767
+ set responseDelimited(e) {
2768
+ if (typeof e != "boolean")
2769
+ throw new Error("responseDelimited must be a boolean");
2770
+ this.__internal__.serial.response.delimited = e;
2771
+ }
2772
+ get responsePrefixLimited() {
2773
+ return this.__internal__.serial.response.prefixLimiter;
2774
+ }
2775
+ set responsePrefixLimited(e) {
2776
+ if (typeof e != "boolean")
2777
+ throw new Error("responsePrefixLimited must be a boolean");
2778
+ this.__internal__.serial.response.prefixLimiter = e;
2779
+ }
2780
+ get responseSufixLimited() {
2781
+ return this.__internal__.serial.response.sufixLimiter;
2782
+ }
2783
+ set responseSufixLimited(e) {
2784
+ if (typeof e != "boolean")
2785
+ throw new Error("responseSufixLimited must be a boolean");
2786
+ this.__internal__.serial.response.sufixLimiter = e;
2787
+ }
2788
+ get responseLimiter() {
2789
+ return this.__internal__.serial.response.limiter;
2790
+ }
2791
+ set responseLimiter(e) {
2792
+ if (typeof e != "string" && !(e instanceof RegExp))
2793
+ throw new Error("responseLimiter must be a string or a RegExp");
2794
+ this.__internal__.serial.response.limiter = e;
2795
+ }
2796
+ get fixedBytesMessage() {
2797
+ return this.__internal__.serial.response.length;
2798
+ }
2799
+ set fixedBytesMessage(e) {
2800
+ if (e !== null && (typeof e != "number" || e < 1))
2801
+ throw new Error("Invalid length for fixed bytes message");
2802
+ this.__internal__.serial.response.length = e;
2803
+ }
2804
+ get timeoutBeforeResponseBytes() {
2805
+ return this.__internal__.serial.free_timeout_ms || 50;
2806
+ }
2807
+ set timeoutBeforeResponseBytes(e) {
2808
+ if (e !== void 0 && (typeof e != "number" || e < 1))
2809
+ throw new Error("Invalid timeout for response bytes");
2810
+ this.__internal__.serial.free_timeout_ms = e ?? 50;
2811
+ }
2812
+ get bypassSerialBytesConnection() {
2813
+ return this.__internal__.bypassSerialBytesConnection;
2814
+ }
2815
+ set bypassSerialBytesConnection(e) {
2816
+ if (typeof e != "boolean")
2817
+ throw new Error("bypassSerialBytesConnection must be a boolean");
2818
+ this.__internal__.bypassSerialBytesConnection = e;
2819
+ }
2820
+ get useSocket() {
2821
+ return this.__internal__.serial.socket;
2822
+ }
2823
+ get connectionBytes() {
2824
+ const e = this.__internal__.serial.bytes_connection;
2825
+ return e instanceof Uint8Array ? e : typeof e == "string" ? this.stringArrayToUint8Array(this.parseStringToBytes(e, "")) : Array.isArray(e) && typeof e[0] == "string" ? this.stringArrayToUint8Array(e) : Array.isArray(e) && typeof e[0] == "number" ? new Uint8Array(e) : new Uint8Array([]);
2826
+ }
2827
+ set portPath(e) {
2828
+ if (this.isConnected) throw new Error("Cannot change port path while connected");
2829
+ if (typeof e != "string" && e !== null)
2830
+ throw new TypeError("vendorId must be string or null");
2831
+ this.__internal__.serial.portInfo.path = e;
2832
+ }
2833
+ get portPath() {
2834
+ return this.__internal__.serial.portInfo.path;
2835
+ }
2836
+ set portVendorId(e) {
2837
+ if (this.isConnected) throw new Error("Cannot change port vendorId while connected");
2838
+ if (typeof e == "number" && typeof e != "string" && e !== null)
2839
+ throw new TypeError("vendorId must be a number, string or null");
2840
+ this.__internal__.serial.portInfo.vendorId = e;
2841
+ }
2842
+ get portVendorId() {
2843
+ return this.__internal__.serial.portInfo.vendorId;
2844
+ }
2845
+ set portProductId(e) {
2846
+ if (this.isConnected) throw new Error("Cannot change port productId while connected");
2847
+ if (typeof e == "number" && typeof e != "string" && e !== null)
2848
+ throw new TypeError("productId must be a number, string or null");
2849
+ this.__internal__.serial.portInfo.productId = e;
2850
+ }
2851
+ get portProductId() {
2852
+ return this.__internal__.serial.portInfo.productId;
2853
+ }
2854
+ set socketPortParser(e) {
2855
+ if (["byte-length", "inter-byte-timeout"].includes(e))
2856
+ throw new TypeError("socketPortParser must be a string, either 'byte-length' or 'inter-byte-timeout'");
2857
+ this.__internal__.serial.portInfo.parser.name = e;
2858
+ }
2859
+ get socketPortParser() {
2860
+ return this.__internal__.serial.portInfo.parser.name;
2861
+ }
2862
+ set socketPortParserInterval(e) {
2863
+ if (typeof e != "number" || e < 1)
2864
+ throw new TypeError("Interval must be a positive number");
2865
+ this.__internal__.serial.portInfo.parser.interval = e;
2866
+ }
2867
+ get socketPortParserInterval() {
2868
+ return this.__internal__.serial.portInfo.parser.interval || 50;
2869
+ }
2870
+ set socketPortParserLength(e) {
2871
+ if (typeof e != "number" || e < 1)
2872
+ throw new TypeError("Length must be a positive number or null");
2873
+ this.__internal__.serial.portInfo.parser.length = e;
2874
+ }
2875
+ get socketPortParserLength() {
2876
+ return this.__internal__.serial.portInfo.parser.length || 14;
2877
+ }
2878
+ get parserForSocket() {
2879
+ return this.socketPortParser === "byte-length" ? {
2880
+ name: this.socketPortParser,
2881
+ length: this.socketPortParserLength
2882
+ } : {
2883
+ name: this.socketPortParser,
2884
+ interval: this.socketPortParserInterval
2885
+ };
2886
+ }
2887
+ get configDeviceSocket() {
2888
+ return {
2889
+ uuid: this.uuid,
2890
+ name: this.typeDevice,
2891
+ deviceNumber: this.deviceNumber,
2892
+ connectionBytes: Array.from(this.connectionBytes),
2893
+ config: {
2894
+ baudRate: this.__internal__.serial.config_port.baudRate,
2895
+ dataBits: this.__internal__.serial.config_port.dataBits,
2896
+ stopBits: this.__internal__.serial.config_port.stopBits,
2897
+ parity: this.__internal__.serial.config_port.parity,
2898
+ bufferSize: this.__internal__.serial.config_port.bufferSize,
2899
+ flowControl: this.__internal__.serial.config_port.flowControl
2900
+ },
2901
+ info: {
2902
+ vendorId: this.portVendorId,
2903
+ // vendor ID or null for auto-detect
2904
+ productId: this.portProductId,
2905
+ // product ID or null for auto-detect
2906
+ portName: this.portPath
2907
+ // COM3, /dev/ttyUSB0, etc. null for auto-detect
2908
+ },
2909
+ response: {
2910
+ automatic: this.__internal__.auto_response,
2911
+ // true to auto-respond to commands this only for devices that doesn't respond nothing
2912
+ autoResponse: this.__internal__.serial.auto_response,
2913
+ // null or data to respond automatically, ie. [0x02, 0x06, 0xdd, 0xdd, 0xf0, 0xcf, 0x03] for relay
2914
+ parser: this.parserForSocket,
2915
+ timeout: {
2916
+ general: this.__internal__.time.response_general,
2917
+ engines: this.__internal__.time.response_engines,
2918
+ connection: this.__internal__.time.response_connection
2919
+ }
2920
+ }
2921
+ };
2922
+ }
2923
+ #t(e) {
2924
+ return this.useSocket ? this.__internal__.serial.connected && w.isConnected() : !!(e && e.readable && e.writable);
2925
+ }
2926
+ async timeout(e, t) {
2927
+ this.__internal__.last_error.message = "Operation response timed out.", this.__internal__.last_error.action = t, this.__internal__.last_error.code = e, this.__internal__.timeout.until_response && (clearTimeout(this.__internal__.timeout.until_response), this.__internal__.timeout.until_response = 0), t === "connect" ? (this.__internal__.serial.connected = !1, this.dispatch("serial:reconnect", {}), a.$dispatchChange(this)) : t === "connection:start" && (await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector += 1, a.$dispatchChange(this), await this.serialConnect()), this.__internal__.serial.queue.length > 0 && this.dispatch("internal:queue", {}), this.dispatch("serial:timeout", {
2928
+ ...this.__internal__.last_error,
2929
+ bytes: e,
2930
+ action: t
2931
+ });
2932
+ }
2933
+ async disconnect(e = null) {
2934
+ await this.serialDisconnect(), this.#e(e);
2935
+ }
2936
+ #e(e = null) {
2937
+ this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), a.$dispatchChange(this);
2938
+ }
2939
+ #i(e) {
2940
+ this.__internal__.serial.aux_connecting = e.detail.active ? "connecting" : "finished";
2941
+ }
2942
+ socketResponse(e) {
2943
+ const t = this.__internal__.serial.connected;
2944
+ if (e.type === "disconnect" || e.type === "error" && e.data === "DISCONNECTED" ? this.__internal__.serial.connected = !1 : e.type === "success" && (this.__internal__.serial.connected = !0), a.$dispatchChange(this), !t && this.__internal__.serial.connected && (this.dispatch("serial:connected"), this.#a(!1)), e.type === "success")
2945
+ this.#r(new Uint8Array(e.data));
2946
+ else if (e.type === "error") {
2947
+ const s = new Error("The port is closed or is not readable/writable");
2948
+ this.serialErrors(s);
2949
+ } else e.type === "timeout" && this.timeout(e.data.bytes ?? [], this.lastAction || "unknown");
2950
+ this.__internal__.serial.last_action = null;
2951
+ }
2952
+ async connect() {
2953
+ return this.isConnected ? !0 : (this.__internal__.serial.aux_connecting = "idle", new Promise((e, t) => {
2954
+ this.#n || (this.#n = this.#i.bind(this)), this.on("internal:connecting", this.#n);
2955
+ const s = setInterval(() => {
2956
+ this.__internal__.serial.aux_connecting === "finished" ? (clearInterval(s), this.__internal__.serial.aux_connecting = "idle", this.#n !== null && this.off("internal:connecting", this.#n), this.isConnected ? e(!0) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`)) : this.__internal__.serial.aux_connecting === "connecting" && (this.__internal__.serial.aux_connecting = "idle", this.dispatch("internal:connecting", { active: !0 }), this.dispatch("serial:connecting", { active: !0 }));
2957
+ }, 100);
2958
+ this.serialConnect();
2959
+ }));
2960
+ }
2961
+ async serialDisconnect() {
2962
+ try {
2963
+ if (this.useSocket)
2964
+ w.isConnected() && w.disconnectDevice(this.configDeviceSocket);
2965
+ else {
2966
+ this.__internal__.serial.keep_reading = !1;
2967
+ const e = this.__internal__.serial.reader;
2968
+ e && await e.cancel().catch(() => {
2969
+ }), this.__internal__.serial.pumpReader && await this.__internal__.serial.pumpReader.cancel().catch(() => {
2970
+ }), this.__internal__.serial.pipeDone && (await this.__internal__.serial.pipeDone.catch(() => {
2971
+ }), this.__internal__.serial.pipeDone = null), this.__internal__.serial.input_done && await this.__internal__.serial.input_done.catch(() => {
2972
+ });
2973
+ const t = this.__internal__.serial.output_stream;
2974
+ if (t) {
2975
+ const s = t.getWriter();
2976
+ await s.close().catch(() => {
2977
+ }), s.releaseLock(), this.__internal__.serial.output_done && await this.__internal__.serial.output_done.catch(() => {
2978
+ });
2979
+ }
2980
+ this.__internal__.serial.port && await this.__internal__.serial.port.close().catch(() => {
2981
+ });
2982
+ }
2983
+ } catch (e) {
2984
+ console.error(e), this.serialErrors(e);
2985
+ } finally {
2986
+ this.__internal__.serial.reader = null, this.__internal__.serial.input_done = null, this.__internal__.serial.output_stream = null, this.__internal__.serial.output_done = null, this.__internal__.serial.connected = !1, this.__internal__.serial.port = null, a.$dispatchChange(this);
2987
+ }
2988
+ }
2989
+ async #o(e) {
2990
+ if (w.isDisconnected())
2991
+ throw this.#e({ error: "Socket is disconnected." }), new Error("The socket is disconnected");
2992
+ if (this.isDisconnected)
2993
+ throw this.#e({ error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
2994
+ const t = this.validateBytes(e);
2995
+ w.write({ config: this.configDeviceSocket, bytes: Array.from(t) });
2996
+ }
2997
+ async #s(e) {
2998
+ if (this.useSocket) {
2999
+ await this.#o(e);
3000
+ return;
3001
+ }
3002
+ const t = this.__internal__.serial.port;
3003
+ if (!t || t && (!t.readable || !t.writable))
3004
+ throw this.#e({ error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
3005
+ const s = this.validateBytes(e);
3006
+ if (this.useRTSCTS && await this.#c(t, 5e3), t.writable === null) return;
3007
+ const i = t.writable.getWriter();
3008
+ await i.write(s), i.releaseLock();
3009
+ }
3010
+ async #c(e, t = 5e3) {
3011
+ const s = Date.now();
3012
+ for (; ; ) {
3013
+ if (Date.now() - s > t)
3014
+ throw new Error("Timeout waiting for clearToSend signal");
3015
+ const { clearToSend: i } = await e.getSignals();
3016
+ if (i) return;
3017
+ await ee(100);
3018
+ }
3019
+ }
3020
+ #r(e = new Uint8Array([]), t = !1) {
3021
+ if (e && e.length > 0) {
3022
+ const s = this.__internal__.serial.connected;
3023
+ if (this.__internal__.serial.connected = this.#t(this.__internal__.serial.port), a.$dispatchChange(this), !s && this.__internal__.serial.connected && (this.dispatch("serial:connected"), this.#a(!1)), this.__internal__.interval.reconnection && (clearInterval(this.__internal__.interval.reconnection), this.__internal__.interval.reconnection = 0), this.__internal__.timeout.until_response && (clearTimeout(this.__internal__.timeout.until_response), this.__internal__.timeout.until_response = 0), this.__internal__.serial.response.as === "hex")
3024
+ t ? this.serialCorruptMessage(this.parseUint8ToHex(e)) : this.serialMessage(this.parseUint8ToHex(e));
3025
+ else if (this.__internal__.serial.response.as === "uint8")
3026
+ t ? this.serialCorruptMessage(e) : this.serialMessage(e);
3027
+ else if (this.__internal__.serial.response.as === "string") {
3028
+ const i = this.parseUint8ArrayToString(e);
3029
+ if (this.__internal__.serial.response.limiter !== null) {
3030
+ const r = i.split(this.__internal__.serial.response.limiter);
3031
+ for (const o in r)
3032
+ r[o] && (t ? this.serialCorruptMessage(r[o]) : this.serialMessage(r[o]));
3033
+ } else
3034
+ t ? this.serialCorruptMessage(i) : this.serialMessage(i);
3035
+ } else {
3036
+ const i = this.stringToArrayBuffer(this.parseUint8ArrayToString(e));
3037
+ t ? this.serialCorruptMessage(i) : this.serialMessage(i);
3038
+ }
3039
+ }
3040
+ if (this.__internal__.serial.queue.length === 0) {
3041
+ this.__internal__.serial.running_queue = !1;
3042
+ return;
3043
+ }
3044
+ this.dispatch("internal:queue", {});
3045
+ }
3046
+ getResponseAsArrayBuffer() {
3047
+ this.__internal__.serial.response.as = "arraybuffer";
3048
+ }
3049
+ getResponseAsArrayHex() {
3050
+ this.__internal__.serial.response.as = "hex";
3051
+ }
3052
+ getResponseAsUint8Array() {
3053
+ this.__internal__.serial.response.as = "uint8";
3054
+ }
3055
+ getResponseAsString() {
3056
+ this.__internal__.serial.response.as = "string";
3057
+ }
3058
+ async #l() {
3059
+ const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
3060
+ return e.length === 0 ? t : t.filter((s) => {
3061
+ const i = s.getInfo();
3062
+ return e.some((r) => i.usbProductId === r.usbProductId && i.usbVendorId === r.usbVendorId);
3063
+ }).filter((s) => !this.#t(s));
3064
+ }
3065
+ async serialPortsSaved(e) {
3066
+ const t = this.serialFilters;
3067
+ if (this.__internal__.aux_port_connector < e.length) {
3068
+ const s = this.__internal__.aux_port_connector;
3069
+ this.__internal__.serial.port = e[s];
3070
+ } else
3071
+ this.__internal__.aux_port_connector = 0, this.__internal__.serial.port = await navigator.serial.requestPort({
3072
+ filters: t
3073
+ });
3074
+ if (!this.__internal__.serial.port)
3075
+ throw new Error("Select another port please");
3076
+ }
3077
+ serialErrors(e) {
3078
+ const t = e.toString().toLowerCase();
3079
+ switch (!0) {
3080
+ case t.includes("must be handling a user gesture to show a permission request"):
3081
+ case t.includes("the port is closed."):
3082
+ case t.includes("the port is closed or is not writable"):
3083
+ case t.includes("the port is closed or is not readable"):
3084
+ case t.includes("the port is closed or is not readable/writable"):
3085
+ case t.includes("select another port please"):
3086
+ case t.includes("no port selected by the user"):
3087
+ case t.includes(
3088
+ "this readable stream reader has been released and cannot be used to cancel its previous owner stream"
3089
+ ):
3090
+ this.dispatch("serial:need-permission", {}), a.$dispatchChange(this);
3091
+ break;
3092
+ case t.includes("the port is already open."):
3093
+ case t.includes("failed to open serial port"):
3094
+ this.serialDisconnect().then(async () => {
3095
+ this.__internal__.aux_port_connector += 1, await this.serialConnect();
3096
+ });
3097
+ break;
3098
+ case t.includes("cannot read properties of undefined (reading 'writable')"):
3099
+ case t.includes("cannot read properties of null (reading 'writable')"):
3100
+ case t.includes("cannot read property 'writable' of null"):
3101
+ case t.includes("cannot read property 'writable' of undefined"):
3102
+ this.serialDisconnect().then(async () => {
3103
+ await this.serialConnect();
3104
+ });
3105
+ break;
3106
+ case t.includes("'close' on 'serialport': a call to close() is already in progress."):
3107
+ break;
3108
+ case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):
3109
+ break;
3110
+ case t.includes("the port is already closed."):
3111
+ break;
3112
+ case t.includes("the device has been lost"):
3113
+ this.dispatch("serial:lost", {}), a.$dispatchChange(this);
3114
+ break;
3115
+ case t.includes("navigator.serial is undefined"):
3116
+ this.dispatch("serial:unsupported", {});
3117
+ break;
3118
+ default:
3119
+ console.error(e);
3120
+ break;
3121
+ }
3122
+ this.dispatch("serial:error", e);
3123
+ }
3124
+ #h(e) {
3125
+ if (e) {
3126
+ const t = this.__internal__.serial.response.buffer, s = new Uint8Array(t.length + e.byteLength);
3127
+ s.set(t, 0), s.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = s;
3128
+ }
3129
+ }
3130
+ async #_() {
3131
+ this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), this.__internal__.serial.response.buffer && this.#r(this.__internal__.serial.response.buffer), this.__internal__.serial.response.buffer = new Uint8Array(0);
3132
+ }
3133
+ async #u() {
3134
+ this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
3135
+ this.__internal__.serial.response.buffer && this.#r(this.__internal__.serial.response.buffer), this.__internal__.serial.response.buffer = new Uint8Array(0);
3136
+ }, this.__internal__.serial.free_timeout_ms || 50);
3137
+ }
3138
+ async #f() {
3139
+ const e = this.__internal__.serial.response.length;
3140
+ let t = this.__internal__.serial.response.buffer;
3141
+ if (this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), !(e === null || !t || t.length === 0)) {
3142
+ for (; t.length >= e; ) {
3143
+ const s = t.slice(0, e);
3144
+ this.#r(s), t = t.slice(e);
3145
+ }
3146
+ this.__internal__.serial.response.buffer = t, t.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
3147
+ this.#r(this.__internal__.serial.response.buffer, !0);
3148
+ }, this.__internal__.serial.free_timeout_ms || 50));
3149
+ }
3150
+ }
3151
+ async #p() {
3152
+ const {
3153
+ limiter: e,
3154
+ prefixLimiter: t = !1,
3155
+ sufixLimiter: s = !0
3156
+ } = this.__internal__.serial.response;
3157
+ if (!e)
3158
+ throw new Error("No limiter defined for delimited serial response");
3159
+ const i = this.__internal__.serial.response.buffer;
3160
+ if (!e || !i || i.length === 0) return;
3161
+ this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0);
3162
+ let r = new TextDecoder().decode(i);
3163
+ const o = [];
3164
+ if (typeof e == "string") {
3165
+ let l;
3166
+ if (t && s)
3167
+ l = new RegExp(`${e}([^${e}]+)${e}`, "g");
3168
+ else if (t)
3169
+ l = new RegExp(`${e}([^${e}]*)`, "g");
3170
+ else if (s)
3171
+ l = new RegExp(`([^${e}]+)${e}`, "g");
3172
+ else
3173
+ return;
3174
+ let f, _ = 0;
3175
+ for (; (f = l.exec(r)) !== null; )
3176
+ o.push(new TextEncoder().encode(f[1])), _ = l.lastIndex;
3177
+ r = r.slice(_);
3178
+ } else if (e instanceof RegExp) {
3179
+ let l, f = 0;
3180
+ if (t && s) {
3181
+ const _ = new RegExp(`${e.source}(.*?)${e.source}`, "g");
3182
+ for (; (l = _.exec(r)) !== null; )
3183
+ o.push(new TextEncoder().encode(l[1])), f = _.lastIndex;
3184
+ } else if (s)
3185
+ for (; (l = e.exec(r)) !== null; ) {
3186
+ const _ = l.index, p = r.slice(f, _);
3187
+ o.push(new TextEncoder().encode(p)), f = e.lastIndex;
3188
+ }
3189
+ else if (t) {
3190
+ const _ = r.split(e);
3191
+ _.shift();
3192
+ for (const p of _)
3193
+ o.push(new TextEncoder().encode(p));
3194
+ r = "";
3195
+ }
3196
+ r = r.slice(f);
3197
+ }
3198
+ for (const l of o)
3199
+ this.#r(l);
3200
+ const c = new TextEncoder().encode(r);
3201
+ this.__internal__.serial.response.buffer = c, c.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
3202
+ this.#r(this.__internal__.serial.response.buffer, !0), this.__internal__.serial.response.buffer = new Uint8Array(0);
3203
+ }, this.__internal__.serial.free_timeout_ms ?? 50));
3204
+ }
3205
+ async #d() {
3206
+ const e = this.__internal__.serial.port;
3207
+ if (!e || !e.readable) throw new Error("Port is not readable");
3208
+ const t = this.__internal__.serial.transformStream;
3209
+ let s;
3210
+ if (t) {
3211
+ const i = t(), r = e.readable.getReader();
3212
+ this.__internal__.serial.pumpReader = r;
3213
+ const o = i.writable.getWriter();
3214
+ this.__internal__.serial.pipeDone = (async () => {
3215
+ try {
3216
+ for (; ; ) {
3217
+ const { value: c, done: l } = await r.read();
3218
+ if (l) break;
3219
+ await o.write(c);
3220
+ }
3221
+ } catch {
3222
+ } finally {
3223
+ try {
3224
+ r.releaseLock();
3225
+ } catch {
3226
+ }
3227
+ try {
3228
+ o.releaseLock();
3229
+ } catch {
3230
+ }
3231
+ this.__internal__.serial.pumpReader = null;
3232
+ }
3233
+ })(), s = i.readable.getReader();
3234
+ } else
3235
+ s = e.readable.getReader();
3236
+ this.__internal__.serial.reader = s;
3237
+ try {
3238
+ for (; this.__internal__.serial.keep_reading; ) {
3239
+ const { value: i, done: r } = await s.read();
3240
+ if (r) break;
3241
+ this.#h(i), t ? await this.#_() : this.__internal__.serial.response.delimited ? await this.#p() : this.__internal__.serial.response.length === null ? await this.#u() : await this.#f();
3242
+ }
3243
+ } catch (i) {
3244
+ this.serialErrors(i);
3245
+ } finally {
3246
+ s.releaseLock(), this.__internal__.serial.reader = null, this.__internal__.serial.keep_reading = !0;
3247
+ }
3248
+ }
3249
+ #a(e) {
3250
+ e !== this.__internal__.serial.connecting && (this.__internal__.serial.connecting = e, this.dispatch("serial:connecting", { active: e }), this.dispatch("internal:connecting", { active: e }));
3251
+ }
3252
+ async serialConnect() {
3253
+ try {
3254
+ if (this.#a(!0), this.useSocket) {
3255
+ if (w.prepare(), this.__internal__.serial.last_action = "connect", this.__internal__.timeout.until_response = setTimeout(async () => {
3256
+ await this.timeout(this.__internal__.serial.bytes_connection ?? [], "connection:start");
3257
+ }, this.__internal__.time.response_connection), w.isDisconnected())
3258
+ return;
3259
+ w.connectDevice(this.configDeviceSocket), this.dispatch("serial:sent", {
3260
+ action: "connect",
3261
+ bytes: this.__internal__.serial.bytes_connection
3262
+ });
3263
+ } else {
3264
+ const e = await this.#l();
3265
+ if (e.length > 0)
3266
+ await this.serialPortsSaved(e);
3267
+ else {
3268
+ const i = this.serialFilters;
3269
+ this.__internal__.serial.port = await navigator.serial.requestPort({
3270
+ filters: i
3271
+ });
3272
+ }
3273
+ const t = this.__internal__.serial.port;
3274
+ if (!t)
3275
+ throw new Error("No port selected by the user");
3276
+ await t.open(this.serialConfigPort);
3277
+ const s = this;
3278
+ t.onconnect = (i) => {
3279
+ s.dispatch("serial:connected", i), s.#a(!1), a.$dispatchChange(this), s.__internal__.serial.queue.length > 0 ? s.dispatch("internal:queue", {}) : s.__internal__.serial.running_queue = !1;
3280
+ }, t.ondisconnect = async () => {
3281
+ await s.disconnect();
3282
+ }, await ee(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
3283
+ await s.timeout(s.__internal__.serial.bytes_connection ?? [], "connection:start");
3284
+ }, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await this.#s(this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
3285
+ action: "connect",
3286
+ bytes: this.__internal__.serial.bytes_connection
3287
+ }), this.__internal__.auto_response && this.#r(this.__internal__.serial.auto_response), this.__internal__.serial.input_done = this.#d(), await this.__internal__.serial.input_done;
3288
+ }
3289
+ } catch (e) {
3290
+ this.#a(!1), this.serialErrors(e);
3291
+ }
3292
+ }
3293
+ async #y() {
3294
+ return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
3295
+ }
3296
+ async serialForget() {
3297
+ return await this.#y();
3298
+ }
3299
+ decToHex(e) {
3300
+ return typeof e == "string" && (e = parseInt(e, 10)), e.toString(16);
3301
+ }
3302
+ hexToDec(e) {
3303
+ return parseInt(e, 16);
3304
+ }
3305
+ hexMaker(e = "00", t = 2) {
3306
+ return e.toString().padStart(t, "0").toLowerCase();
3307
+ }
3308
+ add0x(e) {
3309
+ const t = [];
3310
+ return e.forEach((s, i) => {
3311
+ t[i] = "0x" + s;
3312
+ }), t;
3313
+ }
3314
+ bytesToHex(e) {
3315
+ return this.add0x(Array.from(e, (t) => this.hexMaker(t)));
3316
+ }
3317
+ #g() {
3318
+ [
3319
+ "serial:connected",
3320
+ "serial:connecting",
3321
+ "serial:reconnect",
3322
+ "serial:timeout",
3323
+ "serial:disconnected",
3324
+ "serial:sent",
3325
+ "serial:soft-reload",
3326
+ "serial:message",
3327
+ "serial:corrupt-message",
3328
+ "unknown",
3329
+ "serial:need-permission",
3330
+ "serial:lost",
3331
+ "serial:unsupported",
3332
+ "serial:error",
3333
+ "debug"
3334
+ ].forEach((e) => {
3335
+ this.serialRegisterAvailableListener(e);
3336
+ });
3337
+ }
3338
+ #m() {
3339
+ const e = this;
3340
+ this.on("internal:queue", async () => {
3341
+ await e.#b();
3342
+ });
3343
+ const t = () => {
3344
+ e.isConnected && e.#e({ error: "Socket disconnected." });
3345
+ }, s = () => {
3346
+ e.isDisconnected && !e.isConnecting && e.serialConnect().catch(() => {
3347
+ });
3348
+ };
3349
+ this.useSocket && (window.addEventListener("serial:socket:disconnected", t), window.addEventListener("serial:socket:connected", s)), this.#w();
3350
+ }
3351
+ #w() {
3352
+ const e = this;
3353
+ navigator.serial.addEventListener("connect", async () => {
3354
+ e.isDisconnected && await e.serialConnect().catch(() => {
3355
+ });
3356
+ });
3357
+ }
3358
+ async #b() {
3359
+ if (this.useSocket && w.isDisconnected())
3360
+ return;
3361
+ if (!this.#t(this.__internal__.serial.port)) {
3362
+ this.#e({ error: "Port is closed, not readable or writable." }), await this.serialConnect();
3363
+ return;
3364
+ }
3365
+ if (this.__internal__.timeout.until_response) return;
3366
+ if (this.__internal__.serial.queue.length === 0) {
3367
+ this.__internal__.serial.running_queue = !1;
3368
+ return;
3369
+ }
3370
+ this.__internal__.serial.running_queue = !0;
3371
+ const e = this.__internal__.serial.queue[0];
3372
+ let t = this.__internal__.time.response_general;
3373
+ if (e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
3374
+ await this.timeout(e.bytes, e.action);
3375
+ }, t), this.__internal__.serial.last_action = e.action ?? "unknown", await this.#s(e.bytes), this.dispatch("serial:sent", {
3376
+ action: e.action,
3377
+ bytes: e.bytes
3378
+ }), this.__internal__.auto_response) {
3379
+ let i = new Uint8Array(0);
3380
+ try {
3381
+ i = this.validateBytes(this.__internal__.serial.auto_response);
3382
+ } catch (r) {
3383
+ this.serialErrors(r);
3384
+ }
3385
+ this.#r(i);
3386
+ }
3387
+ const s = [...this.__internal__.serial.queue];
3388
+ this.__internal__.serial.queue = s.splice(1), this.__internal__.serial.queue.length > 0 && (this.__internal__.serial.running_queue = !0);
3389
+ }
3390
+ validateBytes(e) {
3391
+ let t = new Uint8Array(0);
3392
+ if (e instanceof Uint8Array)
3393
+ t = e;
3394
+ else if (typeof e == "string")
3395
+ t = this.parseStringToTextEncoder(e);
3396
+ else if (Array.isArray(e) && typeof e[0] == "string")
3397
+ t = this.stringArrayToUint8Array(e);
3398
+ else if (Array.isArray(e) && typeof e[0] == "number")
3399
+ t = new Uint8Array(e);
3400
+ else
3401
+ throw new Error("Invalid data type");
3402
+ return t;
3403
+ }
3404
+ async appendToQueue(e, t) {
3405
+ const s = this.validateBytes(e);
3406
+ if (["connect", "connection:start"].includes(t)) {
3407
+ if (this.__internal__.serial.connected) return;
3408
+ await this.serialConnect();
3409
+ return;
3410
+ }
3411
+ this.__internal__.serial.queue.push({ bytes: s, action: t }), this.dispatch("internal:queue", {});
3412
+ }
3413
+ #v(e = 1) {
3414
+ this.__internal__.device_number = e, !this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e));
3415
+ }
3416
+ serialSetConnectionConstant(e = 1) {
3417
+ if (this.__internal__.bypassSerialBytesConnection) return this.__internal__.serial.bytes_connection;
3418
+ throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`);
3419
+ }
3420
+ serialMessage(e) {
3421
+ throw console.log(e), this.dispatch("serial:message", { code: e }), new Error("Method not implemented 'serialMessage'");
3422
+ }
3423
+ serialCorruptMessage(e) {
3424
+ throw console.log(e), this.dispatch("serial:corrupt-message", { code: e }), new Error("Method not implemented 'serialCorruptMessage'");
3425
+ }
3426
+ #E() {
3427
+ this.__internal__.last_error = {
3428
+ message: null,
3429
+ action: null,
3430
+ code: null,
3431
+ no_code: 0
3432
+ };
3433
+ }
3434
+ clearSerialQueue() {
3435
+ this.__internal__.serial.queue = [];
3436
+ }
3437
+ sumHex(e) {
3438
+ let t = 0;
3439
+ return e.forEach((s) => {
3440
+ t += parseInt(s, 16);
3441
+ }), t.toString(16);
3442
+ }
3443
+ toString() {
3444
+ return JSON.stringify({
3445
+ __class: this.typeDevice,
3446
+ device_number: this.deviceNumber,
3447
+ uuid: this.uuid,
3448
+ connected: this.isConnected,
3449
+ connection: this.__internal__.serial.bytes_connection
3450
+ });
3451
+ }
3452
+ softReload() {
3453
+ this.#E(), this.dispatch("serial:soft-reload", {});
3454
+ }
3455
+ async sendConnect() {
3456
+ if (!this.__internal__.serial.bytes_connection)
3457
+ throw new Error("No connection bytes defined");
3458
+ await this.appendToQueue(this.__internal__.serial.bytes_connection, "connect");
3459
+ }
3460
+ async sendCustomCode({ code: e = [] } = { code: [] }) {
3461
+ if (!e)
3462
+ throw new Error("No data to send");
3463
+ this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.validateBytes(e)), await this.appendToQueue(e, "custom");
3464
+ }
3465
+ stringToArrayHex(e) {
3466
+ return Array.from(e).map((t) => t.charCodeAt(0).toString(16));
3467
+ }
3468
+ stringToArrayBuffer(e, t = `
3469
+ `) {
3470
+ return this.parseStringToTextEncoder(e, t).buffer;
3471
+ }
3472
+ parseStringToTextEncoder(e = "", t = `
3473
+ `) {
3474
+ const s = new TextEncoder();
3475
+ return e += t, s.encode(e);
3476
+ }
3477
+ parseStringToBytes(e = "", t = `
3478
+ `) {
3479
+ const s = this.parseStringToTextEncoder(e, t);
3480
+ return Array.from(s).map((i) => i.toString(16));
3481
+ }
3482
+ parseUint8ToHex(e) {
3483
+ return Array.from(e).map((t) => t.toString(16).padStart(2, "0").toLowerCase());
3484
+ }
3485
+ parseHexToUint8(e) {
3486
+ return new Uint8Array(e.map((t) => parseInt(t, 16)));
3487
+ }
3488
+ stringArrayToUint8Array(e) {
3489
+ const t = [];
3490
+ return typeof e == "string" ? this.parseStringToTextEncoder(e).buffer : (e.forEach((s) => {
3491
+ const i = s.replace("0x", "");
3492
+ t.push(parseInt(i, 16));
3493
+ }), new Uint8Array(t));
3494
+ }
3495
+ parseUint8ArrayToString(e) {
3496
+ let t = new Uint8Array(0);
3497
+ e instanceof Uint8Array ? t = e : t = this.stringArrayToUint8Array(e), e = this.parseUint8ToHex(t);
3498
+ const s = e.map((i) => parseInt(i, 16));
3499
+ return this.__internal__.serial.response.replacer ? String.fromCharCode(...s).replace(this.__internal__.serial.response.replacer, "") : String.fromCharCode(...s);
3500
+ }
3501
+ hexToAscii(e) {
3502
+ const t = e.toString();
3503
+ let s = "";
3504
+ for (let i = 0; i < t.length; i += 2)
3505
+ s += String.fromCharCode(parseInt(t.substring(i, 2), 16));
3506
+ return s;
3507
+ }
3508
+ asciiToHex(e) {
3509
+ const t = [];
3510
+ for (let s = 0, i = e.length; s < i; s++) {
3511
+ const r = Number(e.charCodeAt(s)).toString(16);
3512
+ t.push(r);
3513
+ }
3514
+ return t.join("");
3515
+ }
3516
+ $checkAndDispatchConnection() {
3517
+ return this.isConnected;
3518
+ }
3519
+ }
3520
+ export {
3521
+ w as h,
3522
+ a as s,
3523
+ ht as v
3524
+ };