webserial-core 1.1.0 → 1.1.2

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