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

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