webserial-core 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,59 +1,59 @@
1
1
  var N = Object.defineProperty;
2
- var b = (r) => {
3
- throw TypeError(r);
2
+ var m = (s) => {
3
+ throw TypeError(s);
4
4
  };
5
- var O = (r, i, e) => i in r ? N(r, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[i] = e;
6
- var h = (r, i, e) => O(r, typeof i != "symbol" ? i + "" : i, e), H = (r, i, e) => i.has(r) || b("Cannot " + e);
7
- var w = (r, i, e) => i.has(r) ? b("Cannot add the same private member more than once") : i instanceof WeakSet ? i.add(r) : i.set(r, e);
8
- var l = (r, i, e) => (H(r, i, "access private method"), e);
5
+ var O = (s, i, e) => i in s ? N(s, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[i] = e;
6
+ var d = (s, i, e) => O(s, typeof i != "symbol" ? i + "" : i, e), H = (s, i, e) => i.has(s) || m("Cannot " + e);
7
+ var v = (s, i, e) => i.has(s) ? m("Cannot add the same private member more than once") : i instanceof WeakSet ? i.add(s) : i.set(s, e);
8
+ var l = (s, i, e) => (H(s, i, "access private method"), e);
9
9
  const _ = [];
10
- for (let r = 0; r < 256; ++r)
11
- _.push((r + 256).toString(16).slice(1));
12
- function j(r, i = 0) {
13
- return (_[r[i + 0]] + _[r[i + 1]] + _[r[i + 2]] + _[r[i + 3]] + "-" + _[r[i + 4]] + _[r[i + 5]] + "-" + _[r[i + 6]] + _[r[i + 7]] + "-" + _[r[i + 8]] + _[r[i + 9]] + "-" + _[r[i + 10]] + _[r[i + 11]] + _[r[i + 12]] + _[r[i + 13]] + _[r[i + 14]] + _[r[i + 15]]).toLowerCase();
10
+ for (let s = 0; s < 256; ++s)
11
+ _.push((s + 256).toString(16).slice(1));
12
+ function j(s, i = 0) {
13
+ return (_[s[i + 0]] + _[s[i + 1]] + _[s[i + 2]] + _[s[i + 3]] + "-" + _[s[i + 4]] + _[s[i + 5]] + "-" + _[s[i + 6]] + _[s[i + 7]] + "-" + _[s[i + 8]] + _[s[i + 9]] + "-" + _[s[i + 10]] + _[s[i + 11]] + _[s[i + 12]] + _[s[i + 13]] + _[s[i + 14]] + _[s[i + 15]]).toLowerCase();
14
14
  }
15
- let p;
15
+ let g;
16
16
  const B = new Uint8Array(16);
17
17
  function F() {
18
- if (!p) {
18
+ if (!g) {
19
19
  if (typeof crypto > "u" || !crypto.getRandomValues)
20
20
  throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
21
- p = crypto.getRandomValues.bind(crypto);
21
+ g = crypto.getRandomValues.bind(crypto);
22
22
  }
23
- return p(B);
23
+ return g(B);
24
24
  }
25
- const $ = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), m = { randomUUID: $ };
26
- function V(r, i, e) {
25
+ const V = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), C = { randomUUID: V };
26
+ function W(s, i, e) {
27
27
  var n;
28
- if (m.randomUUID && !r)
29
- return m.randomUUID();
30
- r = r || {};
31
- const t = r.random ?? ((n = r.rng) == null ? void 0 : n.call(r)) ?? F();
28
+ if (C.randomUUID && !s)
29
+ return C.randomUUID();
30
+ s = s || {};
31
+ const t = s.random ?? ((n = s.rng) == null ? void 0 : n.call(s)) ?? F();
32
32
  if (t.length < 16)
33
33
  throw new Error("Random bytes length must be >= 16");
34
34
  return t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128, j(t);
35
35
  }
36
- class v extends CustomEvent {
36
+ class x extends CustomEvent {
37
37
  constructor(i, e) {
38
38
  super(i, e);
39
39
  }
40
40
  }
41
- class S extends EventTarget {
41
+ class A extends EventTarget {
42
42
  constructor() {
43
43
  super(...arguments);
44
- h(this, "__listeners__", {
44
+ d(this, "__listeners__", {
45
45
  debug: !1
46
46
  });
47
- h(this, "__debug__", !1);
47
+ d(this, "__debug__", !1);
48
48
  }
49
49
  dispatch(e, t = null) {
50
- const n = new v(e, { detail: t });
51
- this.dispatchEvent(n), this.__debug__ && this.dispatchEvent(new v("debug", { detail: { type: e, data: t } }));
50
+ const n = new x(e, { detail: t });
51
+ this.dispatchEvent(n), this.__debug__ && this.dispatchEvent(new x("debug", { detail: { type: e, data: t } }));
52
52
  }
53
53
  dispatchAsync(e, t = null, n = 100) {
54
- const s = this;
54
+ const a = this;
55
55
  setTimeout(() => {
56
- s.dispatch(e, t);
56
+ a.dispatch(e, t);
57
57
  }, n);
58
58
  }
59
59
  on(e, t) {
@@ -72,15 +72,58 @@ class S extends EventTarget {
72
72
  }));
73
73
  }
74
74
  }
75
- function x(r = 100) {
75
+ const o = class o extends A {
76
+ constructor() {
77
+ super(), ["change"].forEach((e) => {
78
+ this.serialRegisterAvailableListener(e);
79
+ });
80
+ }
81
+ static $dispatchChange(i = null) {
82
+ i && i.$checkAndDispatchConnection(), o.instance.dispatch("change", { devices: o.devices, dispatcher: i });
83
+ }
84
+ static typeError(i) {
85
+ const e = new Error();
86
+ throw e.message = `Type ${i} is not supported`, e.name = "DeviceTypeError", e;
87
+ }
88
+ static registerType(i) {
89
+ typeof o.devices[i] > "u" && (o.devices[i] = {});
90
+ }
91
+ static add(i) {
92
+ const e = i.typeDevice;
93
+ typeof o.devices[e] > "u" && (o.devices[e] = {});
94
+ const t = i.uuid;
95
+ if (typeof o.devices[e] > "u" && o.typeError(e), o.devices[e][t])
96
+ throw new Error(`Device with id ${t} already exists`);
97
+ return o.devices[e][t] = i, o.$dispatchChange(i), Object.keys(o.devices[e]).indexOf(t);
98
+ }
99
+ static get(i, e) {
100
+ return typeof o.devices[i] > "u" && (o.devices[i] = {}), typeof o.devices[i] > "u" && o.typeError(i), o.devices[i][e];
101
+ }
102
+ static getAll(i = null) {
103
+ return i === null ? o.devices : (typeof o.devices[i] > "u" && o.typeError(i), o.devices[i]);
104
+ }
105
+ static getList() {
106
+ return Object.values(o.devices).map((e) => Object.values(e)).flat();
107
+ }
108
+ static getByNumber(i, e) {
109
+ return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
110
+ }
111
+ static getCustom(i, e = 1) {
112
+ return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
113
+ }
114
+ };
115
+ d(o, "instance"), d(o, "devices", {});
116
+ let c = o;
117
+ c.instance || (c.instance = new c());
118
+ function S(s = 100) {
76
119
  return new Promise(
77
- (i) => setTimeout(() => i(), r)
120
+ (i) => setTimeout(() => i(), s)
78
121
  );
79
122
  }
80
- function W() {
123
+ function Q() {
81
124
  return "serial" in navigator;
82
125
  }
83
- const f = {
126
+ const b = {
84
127
  baudRate: 9600,
85
128
  dataBits: 8,
86
129
  stopBits: 1,
@@ -88,22 +131,22 @@ const f = {
88
131
  bufferSize: 32768,
89
132
  flowControl: "none"
90
133
  };
91
- var a, C, g, c, E, A, T, U, k, D, I, L, P, q, R, M;
92
- class z extends S {
134
+ var r, p, f, y, u, E, T, U, k, D, L, P, I, q, $, R, M;
135
+ class G extends A {
93
136
  constructor({
94
137
  filters: e = null,
95
- config_port: t = f,
138
+ config_port: t = b,
96
139
  no_device: n = 1,
97
- device_listen_on_channel: s = 1
140
+ device_listen_on_channel: a = 1
98
141
  } = {
99
142
  filters: null,
100
- config_port: f,
143
+ config_port: b,
101
144
  no_device: 1,
102
145
  device_listen_on_channel: 1
103
146
  }) {
104
147
  super();
105
- w(this, a);
106
- h(this, "__internal__", {
148
+ v(this, r);
149
+ d(this, "__internal__", {
107
150
  auto_response: !1,
108
151
  device_number: 1,
109
152
  aux_port_connector: 0,
@@ -132,12 +175,13 @@ class z extends S {
132
175
  delay_first_connection: 200,
133
176
  bytes_connection: null,
134
177
  filters: [],
135
- config_port: f,
136
- queue: []
178
+ config_port: b,
179
+ queue: [],
180
+ auto_response: ["DD", "DD"]
137
181
  },
138
182
  device: {
139
183
  type: "unknown",
140
- id: V(),
184
+ id: W(),
141
185
  listen_on_port: null
142
186
  },
143
187
  time: {
@@ -153,7 +197,7 @@ class z extends S {
153
197
  });
154
198
  if (!("serial" in navigator))
155
199
  throw new Error("Web Serial not supported");
156
- e && (this.serialFilters = e), t && (this.serialConfigPort = t), n && l(this, a, R).call(this, n), s && ["number", "string"].includes(typeof s) && (this.listenOnChannel = s), l(this, a, I).call(this), l(this, a, L).call(this);
200
+ e && (this.serialFilters = e), t && (this.serialConfigPort = t), n && l(this, r, R).call(this, n), a && ["number", "string"].includes(typeof a) && (this.listenOnChannel = a), l(this, r, P).call(this), l(this, r, I).call(this);
157
201
  }
158
202
  set listenOnChannel(e) {
159
203
  if (typeof e == "string" && (e = parseInt(e)), isNaN(e) || e < 1 || e > 255)
@@ -179,10 +223,12 @@ class z extends S {
179
223
  return this.__internal__.serial.config_port;
180
224
  }
181
225
  get isConnected() {
182
- return this.__internal__.serial.connected;
226
+ const e = this.__internal__.serial.connected, t = l(this, r, p).call(this, this.__internal__.serial.port);
227
+ return e && !t && l(this, r, f).call(this, { error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
183
228
  }
184
229
  get isDisconnected() {
185
- return !this.__internal__.serial.connected;
230
+ const e = this.__internal__.serial.connected, t = l(this, r, p).call(this, this.__internal__.serial.port);
231
+ return !e && t && (this.dispatch("serial:connected"), c.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
186
232
  }
187
233
  get deviceNumber() {
188
234
  return this.__internal__.device_number;
@@ -204,19 +250,19 @@ class z extends S {
204
250
  });
205
251
  }
206
252
  async disconnect(e = null) {
207
- await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e);
253
+ await this.serialDisconnect(), l(this, r, f).call(this, e);
208
254
  }
209
255
  async connect() {
210
256
  return new Promise((e, t) => {
211
- W() || t("Web Serial not supported"), setTimeout(async () => {
212
- await x(499), await this.serialConnect(), this.isConnected ? e(`${this.typeDevice} device ${this.deviceNumber} connected`) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`);
257
+ Q() || t("Web Serial not supported"), setTimeout(async () => {
258
+ await S(499), await this.serialConnect(), this.isConnected ? e(`${this.typeDevice} device ${this.deviceNumber} connected`) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`);
213
259
  }, 1);
214
260
  });
215
261
  }
216
262
  async serialDisconnect() {
217
263
  try {
218
264
  const e = this.__internal__.serial.reader, t = this.__internal__.serial.output_stream;
219
- e && (await e.cancel().catch((s) => this.serialErrors(s)), await this.__internal__.serial.input_done), t && (await t.getWriter().close(), await this.__internal__.serial.output_done), this.__internal__.serial.connected && this.__internal__.serial && this.__internal__.serial.port && await this.__internal__.serial.port.close();
265
+ e && (await e.cancel().catch((a) => this.serialErrors(a)), await this.__internal__.serial.input_done), t && (await t.getWriter().close(), await this.__internal__.serial.output_done), this.__internal__.serial.connected && this.__internal__.serial && this.__internal__.serial.port && await this.__internal__.serial.port.close();
220
266
  } catch (e) {
221
267
  this.serialErrors(e);
222
268
  } finally {
@@ -253,12 +299,14 @@ class z extends S {
253
299
  case t.includes("must be handling a user gesture to show a permission request"):
254
300
  case t.includes("the port is closed."):
255
301
  case t.includes("the port is closed or is not writable"):
302
+ case t.includes("the port is closed or is not readable"):
303
+ case t.includes("the port is closed or is not readable/writable"):
256
304
  case t.includes("select another port please"):
257
305
  case t.includes("no port selected by the user"):
258
306
  case t.includes(
259
307
  "this readable stream reader has been released and cannot be used to cancel its previous owner stream"
260
308
  ):
261
- this.dispatch("serial:need-permission", {});
309
+ this.dispatch("serial:need-permission", {}), c.$dispatchChange(this);
262
310
  break;
263
311
  case t.includes("the port is already open."):
264
312
  case t.includes("failed to open serial port"):
@@ -281,7 +329,7 @@ class z extends S {
281
329
  case t.includes("the port is already closed."):
282
330
  break;
283
331
  case t.includes("the device has been lost"):
284
- this.dispatch("serial:lost", {});
332
+ this.dispatch("serial:lost", {}), c.$dispatchChange(this);
285
333
  break;
286
334
  case t.includes("navigator.serial is undefined"):
287
335
  this.dispatch("serial:unsupported", {});
@@ -295,13 +343,13 @@ class z extends S {
295
343
  async serialConnect() {
296
344
  try {
297
345
  this.dispatch("serial:connecting", {});
298
- const e = await l(this, a, E).call(this);
346
+ const e = await l(this, r, E).call(this);
299
347
  if (e.length > 0)
300
348
  await this.serialPortsSaved(e);
301
349
  else {
302
- const s = this.serialFilters;
350
+ const a = this.serialFilters;
303
351
  this.__internal__.serial.port = await navigator.serial.requestPort({
304
- filters: s
352
+ filters: a
305
353
  });
306
354
  }
307
355
  const t = this.__internal__.serial.port;
@@ -309,22 +357,22 @@ class z extends S {
309
357
  throw new Error("No port selected by the user");
310
358
  await t.open(this.serialConfigPort);
311
359
  const n = this;
312
- t.onconnect = (s) => {
313
- n.dispatch("serial:connected", s), n.__internal__.serial.queue.length > 0 && n.dispatch("internal:queue", {});
360
+ t.onconnect = (a) => {
361
+ console.log(a), n.dispatch("serial:connected", a), c.$dispatchChange(this), n.__internal__.serial.queue.length > 0 && n.dispatch("internal:queue", {});
314
362
  }, t.ondisconnect = async () => {
315
363
  await n.disconnect();
316
- }, await x(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
364
+ }, await S(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
317
365
  await n.timeout(n.__internal__.serial.bytes_connection ?? [], "connection:start");
318
- }, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this, a, g).call(this, this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
366
+ }, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this, r, y).call(this, this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
319
367
  action: "connect",
320
368
  bytes: this.__internal__.serial.bytes_connection
321
- }), this.__internal__.auto_response && l(this, a, c).call(this, ["DD", "DD"], null), await l(this, a, k).call(this);
369
+ }), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null), await l(this, r, D).call(this);
322
370
  } catch (e) {
323
371
  this.serialErrors(e);
324
372
  }
325
373
  }
326
374
  async serialForget() {
327
- return await l(this, a, D).call(this);
375
+ return await l(this, r, L).call(this);
328
376
  }
329
377
  decToHex(e) {
330
378
  return typeof e == "string" && (e = parseInt(e, 10)), e.toString(16);
@@ -337,8 +385,8 @@ class z extends S {
337
385
  }
338
386
  add0x(e) {
339
387
  const t = [];
340
- return e.forEach((n, s) => {
341
- t[s] = "0x" + n;
388
+ return e.forEach((n, a) => {
389
+ t[a] = "0x" + n;
342
390
  }), t;
343
391
  }
344
392
  bytesToHex(e) {
@@ -381,7 +429,7 @@ class z extends S {
381
429
  });
382
430
  }
383
431
  softReload() {
384
- l(this, a, M).call(this), this.dispatch("serial:soft-reload", {});
432
+ l(this, r, M).call(this), this.dispatch("serial:soft-reload", {});
385
433
  }
386
434
  async sendConnect() {
387
435
  if (!this.__internal__.serial.bytes_connection)
@@ -409,7 +457,7 @@ class z extends S {
409
457
  parseStringToBytes(e = "", t = `
410
458
  `) {
411
459
  const n = this.parseStringToTextEncoder(e, t);
412
- return Array.from(n).map((s) => s.toString(16));
460
+ return Array.from(n).map((a) => a.toString(16));
413
461
  }
414
462
  parseUint8ToHex(e) {
415
463
  return Array.from(e).map((t) => t.toString(16));
@@ -420,95 +468,103 @@ class z extends S {
420
468
  stringArrayToUint8Array(e) {
421
469
  const t = [];
422
470
  return e.forEach((n) => {
423
- const s = n.replace("0x", "");
424
- t.push(parseInt(s, 16));
471
+ const a = n.replace("0x", "");
472
+ t.push(parseInt(a, 16));
425
473
  }), new Uint8Array(t);
426
474
  }
427
475
  parseUint8ArrayToString(e) {
428
476
  const t = this.stringArrayToUint8Array(e);
429
477
  e = this.parseUint8ToHex(t);
430
- const n = e.map((s) => parseInt(s, 16));
478
+ const n = e.map((a) => parseInt(a, 16));
431
479
  return String.fromCharCode(...n).replace(/[\n\r]+/g, "");
432
480
  }
433
481
  hexToAscii(e) {
434
482
  const t = e.toString();
435
483
  let n = "";
436
- for (let s = 0; s < t.length; s += 2)
437
- n += String.fromCharCode(parseInt(t.substring(s, 2), 16));
484
+ for (let a = 0; a < t.length; a += 2)
485
+ n += String.fromCharCode(parseInt(t.substring(a, 2), 16));
438
486
  return n;
439
487
  }
440
488
  asciiToHex(e) {
441
489
  const t = [];
442
- for (let n = 0, s = e.length; n < s; n++) {
443
- const u = Number(e.charCodeAt(n)).toString(16);
444
- t.push(u);
490
+ for (let n = 0, a = e.length; n < a; n++) {
491
+ const h = Number(e.charCodeAt(n)).toString(16);
492
+ t.push(h);
445
493
  }
446
494
  return t.join("");
447
495
  }
496
+ $checkAndDispatchConnection() {
497
+ return this.isConnected;
498
+ }
448
499
  }
449
- a = new WeakSet(), C = function(e) {
450
- return !!(e.readable && e.writable);
451
- }, g = async function(e) {
500
+ r = new WeakSet(), p = function(e) {
501
+ return !!(e && e.readable && e.writable);
502
+ }, f = function(e = null) {
503
+ this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), c.$dispatchChange(this);
504
+ }, y = async function(e) {
452
505
  const t = this.__internal__.serial.port;
453
- if (!t || !t.writable)
454
- throw new Error("The port is closed or is not writable");
455
- const n = this.stringArrayToUint8Array(e), s = t.writable.getWriter();
456
- await s.write(n), s.releaseLock();
457
- }, c = function(e = [], t = null) {
506
+ if (!t || t && (!t.readable || !t.writable))
507
+ throw l(this, r, f).call(this, { error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
508
+ const n = this.stringArrayToUint8Array(e);
509
+ if (t.writable === null) return;
510
+ const a = t.writable.getWriter();
511
+ await a.write(n), a.releaseLock();
512
+ }, u = function(e = [], t = null) {
458
513
  if (e && e.length > 0) {
459
- this.__internal__.serial.connected || this.dispatch("serial:connected"), this.__internal__.serial.connected = !0, 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);
460
- const n = [];
461
- for (const s in e)
462
- n.push(e[s].toString().padStart(2, "0").toLowerCase());
514
+ const n = this.__internal__.serial.connected;
515
+ this.__internal__.serial.connected = l(this, r, p).call(this, this.__internal__.serial.port), !n && this.__internal__.serial.connected && (this.dispatch("serial:connected"), c.$dispatchChange(this)), 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);
516
+ const a = [];
517
+ for (const h in e)
518
+ a.push(e[h].toString().padStart(2, "0").toLowerCase());
463
519
  if (this.__internal__.serial.response.as === "hex")
464
- this.serialMessage(n);
520
+ this.serialMessage(a);
465
521
  else if (this.__internal__.serial.response.as === "uint8")
466
- this.serialMessage(this.parseHexToUint8(this.add0x(n)));
522
+ this.serialMessage(this.parseHexToUint8(this.add0x(a)));
467
523
  else if (this.__internal__.serial.response.as === "string")
468
- this.serialMessage(this.parseUint8ArrayToString(this.add0x(n)));
524
+ this.serialMessage(this.parseUint8ArrayToString(this.add0x(a)));
469
525
  else {
470
- const s = this.stringToArrayBuffer(
471
- this.parseUint8ArrayToString(this.add0x(n))
526
+ const h = this.stringToArrayBuffer(
527
+ this.parseUint8ArrayToString(this.add0x(a))
472
528
  );
473
- this.serialMessage(s);
529
+ this.serialMessage(h);
474
530
  }
475
531
  } else
476
532
  this.serialCorruptMessage(e, t);
477
533
  this.__internal__.serial.queue.length !== 0 && this.dispatch("internal:queue", {});
478
534
  }, E = async function() {
479
535
  const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
480
- return e.length === 0 ? t : t.filter((s) => {
481
- const u = s.getInfo();
482
- return e.some((y) => u.usbProductId === y.usbProductId && u.usbVendorId === y.usbVendorId);
483
- }).filter((s) => !l(this, a, C).call(this, s));
484
- }, A = function(e) {
536
+ return e.length === 0 ? t : t.filter((a) => {
537
+ const h = a.getInfo();
538
+ return e.some((w) => h.usbProductId === w.usbProductId && h.usbVendorId === w.usbVendorId);
539
+ }).filter((a) => !l(this, r, p).call(this, a));
540
+ }, T = function(e) {
485
541
  if (e) {
486
542
  const t = this.__internal__.serial.response.buffer, n = new Uint8Array(t.length + e.byteLength);
487
543
  n.set(t, 0), n.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = n;
488
544
  }
489
- }, T = async function() {
545
+ }, U = async function() {
490
546
  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(() => {
491
547
  const e = [];
492
548
  for (const t in this.__internal__.serial.response.buffer)
493
549
  e.push(this.__internal__.serial.response.buffer[t].toString(16));
494
- this.__internal__.serial.response.buffer && l(this, a, c).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
550
+ this.__internal__.serial.response.buffer && l(this, r, u).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
495
551
  }, 400);
496
- }, U = async function() {
552
+ }, k = async function() {
497
553
  if (this.__internal__.serial.response.length !== null) {
498
554
  if (this.__internal__.serial.response.length === this.__internal__.serial.response.buffer.length) {
499
555
  const e = [];
500
556
  for (const t in this.__internal__.serial.response.buffer)
501
557
  e.push(this.__internal__.serial.response.buffer[t].toString(16));
502
- l(this, a, c).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
558
+ l(this, r, u).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
503
559
  } else if (this.__internal__.serial.response.length < this.__internal__.serial.response.buffer.length) {
504
560
  let e = new Uint8Array(0);
505
561
  for (let n = 0; n < this.__internal__.serial.response.length; n++)
506
562
  e[n] = this.__internal__.serial.response.buffer[n];
507
563
  if (e.length === this.__internal__.serial.response.length) {
508
564
  const n = [];
509
- for (const s in e)
510
- n.push(e[s].toString(16));
511
- l(this, a, c).call(this, n), this.__internal__.serial.response.buffer = new Uint8Array(0);
565
+ for (const a in e)
566
+ n.push(e[a].toString(16));
567
+ l(this, r, u).call(this, n), this.__internal__.serial.response.buffer = new Uint8Array(0);
512
568
  return;
513
569
  }
514
570
  e = new Uint8Array(0);
@@ -518,14 +574,14 @@ a = new WeakSet(), C = function(e) {
518
574
  e[n - this.__internal__.serial.response.length] = this.__internal__.serial.response.buffer[n];
519
575
  if (e.length === this.__internal__.serial.response.length) {
520
576
  const n = [];
521
- for (const s in e)
522
- n.push(e[s].toString(16));
523
- l(this, a, c).call(this, n), this.__internal__.serial.response.buffer = new Uint8Array(0);
577
+ for (const a in e)
578
+ n.push(e[a].toString(16));
579
+ l(this, r, u).call(this, n), this.__internal__.serial.response.buffer = new Uint8Array(0);
524
580
  }
525
581
  }
526
582
  }
527
583
  }
528
- }, k = async function() {
584
+ }, D = async function() {
529
585
  const e = this.__internal__.serial.port;
530
586
  if (!e || !e.readable) throw new Error("Port is not readable");
531
587
  for (; e.readable && this.__internal__.serial.keep_reading; ) {
@@ -534,12 +590,12 @@ a = new WeakSet(), C = function(e) {
534
590
  try {
535
591
  let n = !0;
536
592
  for (; n; ) {
537
- const { value: s, done: u } = await t.read();
538
- if (u) {
593
+ const { value: a, done: h } = await t.read();
594
+ if (h) {
539
595
  t.releaseLock(), this.__internal__.serial.keep_reading = !1, n = !1;
540
596
  break;
541
597
  }
542
- l(this, a, A).call(this, s), this.__internal__.serial.response.length === null ? await l(this, a, T).call(this) : await l(this, a, U).call(this);
598
+ l(this, r, T).call(this, a), this.__internal__.serial.response.length === null ? await l(this, r, U).call(this) : await l(this, r, k).call(this);
543
599
  }
544
600
  } catch (n) {
545
601
  this.serialErrors(n);
@@ -548,9 +604,9 @@ a = new WeakSet(), C = function(e) {
548
604
  }
549
605
  }
550
606
  this.__internal__.serial.keep_reading = !0, this.__internal__.serial.port && await this.__internal__.serial.port.close();
551
- }, D = async function() {
607
+ }, L = async function() {
552
608
  return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
553
- }, I = function() {
609
+ }, P = function() {
554
610
  [
555
611
  "serial:connected",
556
612
  "serial:connecting",
@@ -569,21 +625,21 @@ a = new WeakSet(), C = function(e) {
569
625
  ].forEach((t) => {
570
626
  this.serialRegisterAvailableListener(t);
571
627
  });
572
- }, L = function() {
628
+ }, I = function() {
573
629
  const e = this;
574
630
  this.on("internal:queue", async () => {
575
631
  var t;
576
- await l(t = e, a, q).call(t);
577
- }), l(this, a, P).call(this);
578
- }, P = function() {
632
+ await l(t = e, r, $).call(t);
633
+ }), l(this, r, q).call(this);
634
+ }, q = function() {
579
635
  const e = this;
580
636
  navigator.serial.addEventListener("connect", async () => {
581
637
  e.isDisconnected && await e.serialConnect().catch(() => {
582
638
  });
583
639
  });
584
- }, q = async function() {
585
- if (!this.__internal__.serial.connected) {
586
- await this.serialConnect();
640
+ }, $ = async function() {
641
+ if (!l(this, r, p).call(this, this.__internal__.serial.port)) {
642
+ l(this, r, f).call(this, { error: "Port is closed, not readable or writable." }), await this.serialConnect();
587
643
  return;
588
644
  }
589
645
  if (this.__internal__.timeout.until_response || this.__internal__.serial.queue.length === 0) return;
@@ -591,10 +647,10 @@ a = new WeakSet(), C = function(e) {
591
647
  let t = this.__internal__.time.response_general;
592
648
  e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
593
649
  await this.timeout(e.bytes, e.action);
594
- }, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this, a, g).call(this, e.bytes), this.dispatch("serial:sent", {
650
+ }, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this, r, y).call(this, e.bytes), this.dispatch("serial:sent", {
595
651
  action: e.action,
596
652
  bytes: e.bytes
597
- }), this.__internal__.auto_response && l(this, a, c).call(this, ["DD", "DD"], null);
653
+ }), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null);
598
654
  const n = [...this.__internal__.serial.queue];
599
655
  this.__internal__.serial.queue = n.splice(1);
600
656
  }, R = function(e = 1) {
@@ -607,43 +663,8 @@ a = new WeakSet(), C = function(e) {
607
663
  no_code: 0
608
664
  };
609
665
  };
610
- const o = class o extends S {
611
- static typeError(i) {
612
- const e = new Error();
613
- throw e.message = `Type ${i} is not supported`, e.name = "DeviceTypeError", e;
614
- }
615
- static registerType(i) {
616
- typeof o.devices[i] > "u" && (o.devices[i] = {});
617
- }
618
- static add(i) {
619
- const e = i.typeDevice;
620
- typeof o.devices[e] > "u" && (o.devices[e] = {});
621
- const t = i.uuid;
622
- if (typeof o.devices[e] > "u" && o.typeError(e), this.instance.dispatch("change", o.devices), o.devices[e][t])
623
- throw new Error(`Device with id ${t} already exists`);
624
- return o.devices[e][t] = i, this.instance.dispatch("change", o.devices), Object.keys(o.devices[e]).indexOf(t);
625
- }
626
- static get(i, e) {
627
- return typeof o.devices[i] > "u" && (o.devices[i] = {}), typeof o.devices[i] > "u" && o.typeError(i), o.devices[i][e];
628
- }
629
- static getAll(i = null) {
630
- return i === null ? o.devices : (typeof o.devices[i] > "u" && o.typeError(i), o.devices[i]);
631
- }
632
- static getList() {
633
- return Object.values(o.devices).map((e) => Object.values(e)).flat();
634
- }
635
- static getByNumber(i, e) {
636
- return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
637
- }
638
- static getCustom(i, e = 1) {
639
- return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
640
- }
641
- };
642
- h(o, "instance"), h(o, "devices", {});
643
- let d = o;
644
- d.instance || (d.instance = new d());
645
666
  export {
646
- z as Core,
647
- d as Devices,
648
- S as Dispatcher
667
+ G as Core,
668
+ c as Devices,
669
+ A as Dispatcher
649
670
  };
@@ -1,4 +1,4 @@
1
- (function(_,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(_=typeof globalThis<"u"?globalThis:_||self,s(_.WebSerialCore={}))})(this,function(_){"use strict";var $=Object.defineProperty;var C=_=>{throw TypeError(_)};var V=(_,s,u)=>s in _?$(_,s,{enumerable:!0,configurable:!0,writable:!0,value:u}):_[s]=u;var f=(_,s,u)=>V(_,typeof s!="symbol"?s+"":s,u),Q=(_,s,u)=>s.has(_)||C("Cannot "+u);var T=(_,s,u)=>s.has(_)?C("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(_):s.set(_,u);var c=(_,s,u)=>(Q(_,s,"access private method"),u);var a,E,m,h,A,U,D,k,I,L,P,q,M,R,N,O;const s=[];for(let o=0;o<256;++o)s.push((o+256).toString(16).slice(1));function u(o,i=0){return(s[o[i+0]]+s[o[i+1]]+s[o[i+2]]+s[o[i+3]]+"-"+s[o[i+4]]+s[o[i+5]]+"-"+s[o[i+6]]+s[o[i+7]]+"-"+s[o[i+8]]+s[o[i+9]]+"-"+s[o[i+10]]+s[o[i+11]]+s[o[i+12]]+s[o[i+13]]+s[o[i+14]]+s[o[i+15]]).toLowerCase()}let g;const H=new Uint8Array(16);function j(){if(!g){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");g=crypto.getRandomValues.bind(crypto)}return g(H)}const w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function B(o,i,e){var n;if(w.randomUUID&&!o)return w.randomUUID();o=o||{};const t=o.random??((n=o.rng)==null?void 0:n.call(o))??j();if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=t[6]&15|64,t[8]=t[8]&63|128,u(t)}class v extends CustomEvent{constructor(i,e){super(i,e)}}class y extends EventTarget{constructor(){super(...arguments);f(this,"__listeners__",{debug:!1});f(this,"__debug__",!1)}dispatch(e,t=null){const n=new v(e,{detail:t});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new v("debug",{detail:{type:e,data:t}}))}dispatchAsync(e,t=null,n=100){const r=this;setTimeout(()=>{r.dispatch(e,t)},n)}on(e,t){typeof this.__listeners__[e]<"u"&&!this.__listeners__[e]&&(this.__listeners__[e]=!0),this.addEventListener(e,t)}off(e,t){this.removeEventListener(e,t)}serialRegisterAvailableListener(e){this.__listeners__[e]||(this.__listeners__[e]=!1)}get availableListeners(){return Object.keys(this.__listeners__).sort().map(t=>({type:t,listening:this.__listeners__[t]}))}}function x(o=100){return new Promise(i=>setTimeout(()=>i(),o))}function F(){return"serial"in navigator}const b={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class W extends y{constructor({filters:e=null,config_port:t=b,no_device:n=1,device_listen_on_channel:r=1}={filters:null,config_port:b,no_device:1,device_listen_on_channel:1}){super();T(this,a);f(this,"__internal__",{auto_response:!1,device_number:1,aux_port_connector:0,last_error:{message:null,action:null,code:null,no_code:0},serial:{connected:!1,port:null,last_action:null,response:{length:null,buffer:new Uint8Array([]),as:"hex"},reader:null,input_done:null,output_done:null,input_stream:null,output_stream:null,keep_reading:!0,time_until_send_bytes:void 0,delay_first_connection:200,bytes_connection:null,filters:[],config_port:b,queue:[]},device:{type:"unknown",id:B(),listen_on_port:null},time:{response_connection:500,response_general:2e3},timeout:{until_response:0},interval:{reconnection:0}});if(!("serial"in navigator))throw new Error("Web Serial not supported");e&&(this.serialFilters=e),t&&(this.serialConfigPort=t),n&&c(this,a,N).call(this,n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),c(this,a,P).call(this),c(this,a,q).call(this)}set listenOnChannel(e){if(typeof e=="string"&&(e=parseInt(e)),isNaN(e)||e<1||e>255)throw new Error("Invalid port number");this.__internal__.device.listen_on_port=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)}get lastAction(){return this.__internal__.serial.last_action}get listenOnChannel(){return this.__internal__.device.listen_on_port??1}set serialFilters(e){this.__internal__.serial.filters=e}get serialFilters(){return this.__internal__.serial.filters}set serialConfigPort(e){this.__internal__.serial.config_port=e}get serialConfigPort(){return this.__internal__.serial.config_port}get isConnected(){return this.__internal__.serial.connected}get isDisconnected(){return!this.__internal__.serial.connected}get deviceNumber(){return this.__internal__.device_number}get uuid(){return this.__internal__.device.id}get typeDevice(){return this.__internal__.device.type}get queue(){return this.__internal__.serial.queue}async timeout(e,t){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",{})):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:e,action:t})}async disconnect(e=null){await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",e)}async connect(){return new Promise((e,t)=>{F()||t("Web Serial not supported"),setTimeout(async()=>{await x(499),await this.serialConnect(),this.isConnected?e(`${this.typeDevice} device ${this.deviceNumber} connected`):t(`${this.typeDevice} device ${this.deviceNumber} not connected`)},1)})}async serialDisconnect(){try{const e=this.__internal__.serial.reader,t=this.__internal__.serial.output_stream;e&&(await e.cancel().catch(r=>this.serialErrors(r)),await this.__internal__.serial.input_done),t&&(await t.getWriter().close(),await this.__internal__.serial.output_done),this.__internal__.serial.connected&&this.__internal__.serial&&this.__internal__.serial.port&&await this.__internal__.serial.port.close()}catch(e){this.serialErrors(e)}finally{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}}getResponseAsArrayBuffer(){this.__internal__.serial.response.as="arraybuffer"}getResponseAsArrayHex(){this.__internal__.serial.response.as="hex"}getResponseAsUint8Array(){this.__internal__.serial.response.as="uint8"}getResponseAsString(){this.__internal__.serial.response.as="string"}async serialPortsSaved(e){const t=this.serialFilters;if(this.__internal__.aux_port_connector<e.length){const n=this.__internal__.aux_port_connector;this.__internal__.serial.port=e[n]}else this.__internal__.aux_port_connector=0,this.__internal__.serial.port=await navigator.serial.requestPort({filters:t});if(!this.__internal__.serial.port)throw new Error("Select another port please")}serialErrors(e){const t=e.toString().toLowerCase();switch(!0){case t.includes("must be handling a user gesture to show a permission request"):case t.includes("the port is closed."):case t.includes("the port is closed or is not writable"):case t.includes("select another port please"):case t.includes("no port selected by the user"):case t.includes("this readable stream reader has been released and cannot be used to cancel its previous owner stream"):this.dispatch("serial:need-permission",{});break;case t.includes("the port is already open."):case t.includes("failed to open serial port"):this.serialDisconnect().then(async()=>{this.__internal__.aux_port_connector+=1,await this.serialConnect()});break;case t.includes("cannot read properties of undefined (reading 'writable')"):case t.includes("cannot read properties of null (reading 'writable')"):case t.includes("cannot read property 'writable' of null"):case t.includes("cannot read property 'writable' of undefined"):this.serialDisconnect().then(async()=>{await this.serialConnect()});break;case t.includes("'close' on 'serialport': a call to close() is already in progress."):break;case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):break;case t.includes("the port is already closed."):break;case t.includes("the device has been lost"):this.dispatch("serial:lost",{});break;case t.includes("navigator.serial is undefined"):this.dispatch("serial:unsupported",{});break;default:console.error(e);break}this.dispatch("serial:error",e)}async serialConnect(){try{this.dispatch("serial:connecting",{});const e=await c(this,a,A).call(this);if(e.length>0)await this.serialPortsSaved(e);else{const r=this.serialFilters;this.__internal__.serial.port=await navigator.serial.requestPort({filters:r})}const t=this.__internal__.serial.port;if(!t)throw new Error("No port selected by the user");await t.open(this.serialConfigPort);const n=this;t.onconnect=r=>{n.dispatch("serial:connected",r),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await n.disconnect()},await x(this.__internal__.serial.delay_first_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await n.timeout(n.__internal__.serial.bytes_connection??[],"connection:start")},this.__internal__.time.response_connection),this.__internal__.serial.last_action="connect",await c(this,a,m).call(this,this.__internal__.serial.bytes_connection??[]),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection}),this.__internal__.auto_response&&c(this,a,h).call(this,["DD","DD"],null),await c(this,a,I).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await c(this,a,L).call(this)}decToHex(e){return typeof e=="string"&&(e=parseInt(e,10)),e.toString(16)}hexToDec(e){return parseInt(e,16)}hexMaker(e="00",t=2){return e.toString().padStart(t,"0").toLowerCase()}add0x(e){const t=[];return e.forEach((n,r)=>{t[r]="0x"+n}),t}bytesToHex(e){return this.add0x(Array.from(e,t=>this.hexMaker(t)))}async appendToQueue(e,t){const n=this.bytesToHex(e);if(["connect","connection:start"].includes(t)){if(this.__internal__.serial.connected)return;await this.serialConnect();return}this.__internal__.serial.queue.push({bytes:n,action:t}),this.dispatch("internal:queue",{})}serialSetConnectionConstant(e=1){throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`)}serialMessage(e){throw console.log(e),new Error("Method not implemented 'serialMessage'")}serialCorruptMessage(e,t){throw console.log(e,t),new Error("Method not implemented 'serialCorruptMessage'")}clearSerialQueue(){this.__internal__.serial.queue=[]}sumHex(e){let t=0;return e.forEach(n=>{t+=parseInt(n,16)}),t.toString(16)}toString(){return JSON.stringify({__class:this.typeDevice,device_number:this.deviceNumber,uuid:this.uuid,connected:this.isConnected,connection:this.__internal__.serial.bytes_connection})}softReload(){c(this,a,O).call(this),this.dispatch("serial:soft-reload",{})}async sendConnect(){if(!this.__internal__.serial.bytes_connection)throw new Error("No connection bytes defined");await this.appendToQueue(this.__internal__.serial.bytes_connection,"connect")}async sendCustomCode({code:e=[]}={code:[]}){if(e===null||e.length===0)throw new Error("No data to send");await this.appendToQueue(e,"custom")}stringToArrayHex(e){return Array.from(e).map(t=>t.charCodeAt(0).toString(16))}stringToArrayBuffer(e,t=`
1
+ (function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.WebSerialCore={}))})(this,function(c){"use strict";var V=Object.defineProperty;var T=c=>{throw TypeError(c)};var Q=(c,a,h)=>a in c?V(c,a,{enumerable:!0,configurable:!0,writable:!0,value:h}):c[a]=h;var f=(c,a,h)=>Q(c,typeof a!="symbol"?a+"":a,h),z=(c,a,h)=>a.has(c)||T("Cannot "+h);var E=(c,a,h)=>a.has(c)?T("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(c):a.set(c,h);var _=(c,a,h)=>(z(c,a,"access private method"),h);var s,g,b,v,p,U,k,D,L,P,I,q,$,R,M,N,O;const a=[];for(let o=0;o<256;++o)a.push((o+256).toString(16).slice(1));function h(o,i=0){return(a[o[i+0]]+a[o[i+1]]+a[o[i+2]]+a[o[i+3]]+"-"+a[o[i+4]]+a[o[i+5]]+"-"+a[o[i+6]]+a[o[i+7]]+"-"+a[o[i+8]]+a[o[i+9]]+"-"+a[o[i+10]]+a[o[i+11]]+a[o[i+12]]+a[o[i+13]]+a[o[i+14]]+a[o[i+15]]).toLowerCase()}let y;const H=new Uint8Array(16);function j(){if(!y){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");y=crypto.getRandomValues.bind(crypto)}return y(H)}const C={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function B(o,i,e){var n;if(C.randomUUID&&!o)return C.randomUUID();o=o||{};const t=o.random??((n=o.rng)==null?void 0:n.call(o))??j();if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=t[6]&15|64,t[8]=t[8]&63|128,h(t)}class x extends CustomEvent{constructor(i,e){super(i,e)}}class w extends EventTarget{constructor(){super(...arguments);f(this,"__listeners__",{debug:!1});f(this,"__debug__",!1)}dispatch(e,t=null){const n=new x(e,{detail:t});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new x("debug",{detail:{type:e,data:t}}))}dispatchAsync(e,t=null,n=100){const r=this;setTimeout(()=>{r.dispatch(e,t)},n)}on(e,t){typeof this.__listeners__[e]<"u"&&!this.__listeners__[e]&&(this.__listeners__[e]=!0),this.addEventListener(e,t)}off(e,t){this.removeEventListener(e,t)}serialRegisterAvailableListener(e){this.__listeners__[e]||(this.__listeners__[e]=!1)}get availableListeners(){return Object.keys(this.__listeners__).sort().map(t=>({type:t,listening:this.__listeners__[t]}))}}const l=class l extends w{constructor(){super(),["change"].forEach(e=>{this.serialRegisterAvailableListener(e)})}static $dispatchChange(i=null){i&&i.$checkAndDispatchConnection(),l.instance.dispatch("change",{devices:l.devices,dispatcher:i})}static typeError(i){const e=new Error;throw e.message=`Type ${i} is not supported`,e.name="DeviceTypeError",e}static registerType(i){typeof l.devices[i]>"u"&&(l.devices[i]={})}static add(i){const e=i.typeDevice;typeof l.devices[e]>"u"&&(l.devices[e]={});const t=i.uuid;if(typeof l.devices[e]>"u"&&l.typeError(e),l.devices[e][t])throw new Error(`Device with id ${t} already exists`);return l.devices[e][t]=i,l.$dispatchChange(i),Object.keys(l.devices[e]).indexOf(t)}static get(i,e){return typeof l.devices[i]>"u"&&(l.devices[i]={}),typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i][e]}static getAll(i=null){return i===null?l.devices:(typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i])}static getList(){return Object.values(l.devices).map(e=>Object.values(e)).flat()}static getByNumber(i,e){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}static getCustom(i,e=1){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}};f(l,"instance"),f(l,"devices",{});let u=l;u.instance||(u.instance=new u);function S(o=100){return new Promise(i=>setTimeout(()=>i(),o))}function F(){return"serial"in navigator}const m={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class W extends w{constructor({filters:e=null,config_port:t=m,no_device:n=1,device_listen_on_channel:r=1}={filters:null,config_port:m,no_device:1,device_listen_on_channel:1}){super();E(this,s);f(this,"__internal__",{auto_response:!1,device_number:1,aux_port_connector:0,last_error:{message:null,action:null,code:null,no_code:0},serial:{connected:!1,port:null,last_action:null,response:{length:null,buffer:new Uint8Array([]),as:"hex"},reader:null,input_done:null,output_done:null,input_stream:null,output_stream:null,keep_reading:!0,time_until_send_bytes:void 0,delay_first_connection:200,bytes_connection:null,filters:[],config_port:m,queue:[],auto_response:["DD","DD"]},device:{type:"unknown",id:B(),listen_on_port:null},time:{response_connection:500,response_general:2e3},timeout:{until_response:0},interval:{reconnection:0}});if(!("serial"in navigator))throw new Error("Web Serial not supported");e&&(this.serialFilters=e),t&&(this.serialConfigPort=t),n&&_(this,s,N).call(this,n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),_(this,s,q).call(this),_(this,s,$).call(this)}set listenOnChannel(e){if(typeof e=="string"&&(e=parseInt(e)),isNaN(e)||e<1||e>255)throw new Error("Invalid port number");this.__internal__.device.listen_on_port=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)}get lastAction(){return this.__internal__.serial.last_action}get listenOnChannel(){return this.__internal__.device.listen_on_port??1}set serialFilters(e){this.__internal__.serial.filters=e}get serialFilters(){return this.__internal__.serial.filters}set serialConfigPort(e){this.__internal__.serial.config_port=e}get serialConfigPort(){return this.__internal__.serial.config_port}get isConnected(){const e=this.__internal__.serial.connected,t=_(this,s,g).call(this,this.__internal__.serial.port);return e&&!t&&_(this,s,b).call(this,{error:"Port is closed, not readable or writable."}),this.__internal__.serial.connected=t,this.__internal__.serial.connected}get isDisconnected(){const e=this.__internal__.serial.connected,t=_(this,s,g).call(this,this.__internal__.serial.port);return!e&&t&&(this.dispatch("serial:connected"),u.$dispatchChange(this)),this.__internal__.serial.connected=t,!this.__internal__.serial.connected}get deviceNumber(){return this.__internal__.device_number}get uuid(){return this.__internal__.device.id}get typeDevice(){return this.__internal__.device.type}get queue(){return this.__internal__.serial.queue}async timeout(e,t){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",{})):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:e,action:t})}async disconnect(e=null){await this.serialDisconnect(),_(this,s,b).call(this,e)}async connect(){return new Promise((e,t)=>{F()||t("Web Serial not supported"),setTimeout(async()=>{await S(499),await this.serialConnect(),this.isConnected?e(`${this.typeDevice} device ${this.deviceNumber} connected`):t(`${this.typeDevice} device ${this.deviceNumber} not connected`)},1)})}async serialDisconnect(){try{const e=this.__internal__.serial.reader,t=this.__internal__.serial.output_stream;e&&(await e.cancel().catch(r=>this.serialErrors(r)),await this.__internal__.serial.input_done),t&&(await t.getWriter().close(),await this.__internal__.serial.output_done),this.__internal__.serial.connected&&this.__internal__.serial&&this.__internal__.serial.port&&await this.__internal__.serial.port.close()}catch(e){this.serialErrors(e)}finally{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}}getResponseAsArrayBuffer(){this.__internal__.serial.response.as="arraybuffer"}getResponseAsArrayHex(){this.__internal__.serial.response.as="hex"}getResponseAsUint8Array(){this.__internal__.serial.response.as="uint8"}getResponseAsString(){this.__internal__.serial.response.as="string"}async serialPortsSaved(e){const t=this.serialFilters;if(this.__internal__.aux_port_connector<e.length){const n=this.__internal__.aux_port_connector;this.__internal__.serial.port=e[n]}else this.__internal__.aux_port_connector=0,this.__internal__.serial.port=await navigator.serial.requestPort({filters:t});if(!this.__internal__.serial.port)throw new Error("Select another port please")}serialErrors(e){const t=e.toString().toLowerCase();switch(!0){case t.includes("must be handling a user gesture to show a permission request"):case t.includes("the port is closed."):case t.includes("the port is closed or is not writable"):case t.includes("the port is closed or is not readable"):case t.includes("the port is closed or is not readable/writable"):case t.includes("select another port please"):case t.includes("no port selected by the user"):case t.includes("this readable stream reader has been released and cannot be used to cancel its previous owner stream"):this.dispatch("serial:need-permission",{}),u.$dispatchChange(this);break;case t.includes("the port is already open."):case t.includes("failed to open serial port"):this.serialDisconnect().then(async()=>{this.__internal__.aux_port_connector+=1,await this.serialConnect()});break;case t.includes("cannot read properties of undefined (reading 'writable')"):case t.includes("cannot read properties of null (reading 'writable')"):case t.includes("cannot read property 'writable' of null"):case t.includes("cannot read property 'writable' of undefined"):this.serialDisconnect().then(async()=>{await this.serialConnect()});break;case t.includes("'close' on 'serialport': a call to close() is already in progress."):break;case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):break;case t.includes("the port is already closed."):break;case t.includes("the device has been lost"):this.dispatch("serial:lost",{}),u.$dispatchChange(this);break;case t.includes("navigator.serial is undefined"):this.dispatch("serial:unsupported",{});break;default:console.error(e);break}this.dispatch("serial:error",e)}async serialConnect(){try{this.dispatch("serial:connecting",{});const e=await _(this,s,U).call(this);if(e.length>0)await this.serialPortsSaved(e);else{const r=this.serialFilters;this.__internal__.serial.port=await navigator.serial.requestPort({filters:r})}const t=this.__internal__.serial.port;if(!t)throw new Error("No port selected by the user");await t.open(this.serialConfigPort);const n=this;t.onconnect=r=>{console.log(r),n.dispatch("serial:connected",r),u.$dispatchChange(this),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await n.disconnect()},await S(this.__internal__.serial.delay_first_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await n.timeout(n.__internal__.serial.bytes_connection??[],"connection:start")},this.__internal__.time.response_connection),this.__internal__.serial.last_action="connect",await _(this,s,v).call(this,this.__internal__.serial.bytes_connection??[]),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection}),this.__internal__.auto_response&&_(this,s,p).call(this,this.__internal__.serial.auto_response,null),await _(this,s,P).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await _(this,s,I).call(this)}decToHex(e){return typeof e=="string"&&(e=parseInt(e,10)),e.toString(16)}hexToDec(e){return parseInt(e,16)}hexMaker(e="00",t=2){return e.toString().padStart(t,"0").toLowerCase()}add0x(e){const t=[];return e.forEach((n,r)=>{t[r]="0x"+n}),t}bytesToHex(e){return this.add0x(Array.from(e,t=>this.hexMaker(t)))}async appendToQueue(e,t){const n=this.bytesToHex(e);if(["connect","connection:start"].includes(t)){if(this.__internal__.serial.connected)return;await this.serialConnect();return}this.__internal__.serial.queue.push({bytes:n,action:t}),this.dispatch("internal:queue",{})}serialSetConnectionConstant(e=1){throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`)}serialMessage(e){throw console.log(e),new Error("Method not implemented 'serialMessage'")}serialCorruptMessage(e,t){throw console.log(e,t),new Error("Method not implemented 'serialCorruptMessage'")}clearSerialQueue(){this.__internal__.serial.queue=[]}sumHex(e){let t=0;return e.forEach(n=>{t+=parseInt(n,16)}),t.toString(16)}toString(){return JSON.stringify({__class:this.typeDevice,device_number:this.deviceNumber,uuid:this.uuid,connected:this.isConnected,connection:this.__internal__.serial.bytes_connection})}softReload(){_(this,s,O).call(this),this.dispatch("serial:soft-reload",{})}async sendConnect(){if(!this.__internal__.serial.bytes_connection)throw new Error("No connection bytes defined");await this.appendToQueue(this.__internal__.serial.bytes_connection,"connect")}async sendCustomCode({code:e=[]}={code:[]}){if(e===null||e.length===0)throw new Error("No data to send");await this.appendToQueue(e,"custom")}stringToArrayHex(e){return Array.from(e).map(t=>t.charCodeAt(0).toString(16))}stringToArrayBuffer(e,t=`
2
2
  `){return this.parseStringToTextEncoder(e,t).buffer}parseStringToTextEncoder(e="",t=`
3
3
  `){const n=new TextEncoder;return e+=t,n.encode(e)}parseStringToBytes(e="",t=`
4
- `){const n=this.parseStringToTextEncoder(e,t);return Array.from(n).map(r=>r.toString(16))}parseUint8ToHex(e){return Array.from(e).map(t=>t.toString(16))}parseHexToUint8(e){return new Uint8Array(e.map(t=>parseInt(t,16)))}stringArrayToUint8Array(e){const t=[];return e.forEach(n=>{const r=n.replace("0x","");t.push(parseInt(r,16))}),new Uint8Array(t)}parseUint8ArrayToString(e){const t=this.stringArrayToUint8Array(e);e=this.parseUint8ToHex(t);const n=e.map(r=>parseInt(r,16));return String.fromCharCode(...n).replace(/[\n\r]+/g,"")}hexToAscii(e){const t=e.toString();let n="";for(let r=0;r<t.length;r+=2)n+=String.fromCharCode(parseInt(t.substring(r,2),16));return n}asciiToHex(e){const t=[];for(let n=0,r=e.length;n<r;n++){const p=Number(e.charCodeAt(n)).toString(16);t.push(p)}return t.join("")}}a=new WeakSet,E=function(e){return!!(e.readable&&e.writable)},m=async function(e){const t=this.__internal__.serial.port;if(!t||!t.writable)throw new Error("The port is closed or is not writable");const n=this.stringArrayToUint8Array(e),r=t.writable.getWriter();await r.write(n),r.releaseLock()},h=function(e=[],t=null){if(e&&e.length>0){this.__internal__.serial.connected||this.dispatch("serial:connected"),this.__internal__.serial.connected=!0,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);const n=[];for(const r in e)n.push(e[r].toString().padStart(2,"0").toLowerCase());if(this.__internal__.serial.response.as==="hex")this.serialMessage(n);else if(this.__internal__.serial.response.as==="uint8")this.serialMessage(this.parseHexToUint8(this.add0x(n)));else if(this.__internal__.serial.response.as==="string")this.serialMessage(this.parseUint8ArrayToString(this.add0x(n)));else{const r=this.stringToArrayBuffer(this.parseUint8ArrayToString(this.add0x(n)));this.serialMessage(r)}}else this.serialCorruptMessage(e,t);this.__internal__.serial.queue.length!==0&&this.dispatch("internal:queue",{})},A=async function(){const e=this.serialFilters,t=await navigator.serial.getPorts({filters:e});return e.length===0?t:t.filter(r=>{const p=r.getInfo();return e.some(S=>p.usbProductId===S.usbProductId&&p.usbVendorId===S.usbVendorId)}).filter(r=>!c(this,a,E).call(this,r))},U=function(e){if(e){const t=this.__internal__.serial.response.buffer,n=new Uint8Array(t.length+e.byteLength);n.set(t,0),n.set(new Uint8Array(e),t.length),this.__internal__.serial.response.buffer=n}},D=async function(){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(()=>{const e=[];for(const t in this.__internal__.serial.response.buffer)e.push(this.__internal__.serial.response.buffer[t].toString(16));this.__internal__.serial.response.buffer&&c(this,a,h).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)},400)},k=async function(){if(this.__internal__.serial.response.length!==null){if(this.__internal__.serial.response.length===this.__internal__.serial.response.buffer.length){const e=[];for(const t in this.__internal__.serial.response.buffer)e.push(this.__internal__.serial.response.buffer[t].toString(16));c(this,a,h).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)}else if(this.__internal__.serial.response.length<this.__internal__.serial.response.buffer.length){let e=new Uint8Array(0);for(let n=0;n<this.__internal__.serial.response.length;n++)e[n]=this.__internal__.serial.response.buffer[n];if(e.length===this.__internal__.serial.response.length){const n=[];for(const r in e)n.push(e[r].toString(16));c(this,a,h).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0);return}e=new Uint8Array(0);const t=this.__internal__.serial.response.length*2;if(this.__internal__.serial.response.buffer.length===t){for(let n=14;n<t;n++)e[n-this.__internal__.serial.response.length]=this.__internal__.serial.response.buffer[n];if(e.length===this.__internal__.serial.response.length){const n=[];for(const r in e)n.push(e[r].toString(16));c(this,a,h).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0)}}}}},I=async function(){const e=this.__internal__.serial.port;if(!e||!e.readable)throw new Error("Port is not readable");for(;e.readable&&this.__internal__.serial.keep_reading;){const t=e.readable.getReader();this.__internal__.serial.reader=t;try{let n=!0;for(;n;){const{value:r,done:p}=await t.read();if(p){t.releaseLock(),this.__internal__.serial.keep_reading=!1,n=!1;break}c(this,a,U).call(this,r),this.__internal__.serial.response.length===null?await c(this,a,D).call(this):await c(this,a,k).call(this)}}catch(n){this.serialErrors(n)}finally{t.releaseLock()}}this.__internal__.serial.keep_reading=!0,this.__internal__.serial.port&&await this.__internal__.serial.port.close()},L=async function(){return typeof window>"u"?!1:"serial"in navigator&&"forget"in SerialPort.prototype&&this.__internal__.serial.port?(await this.__internal__.serial.port.forget(),!0):!1},P=function(){["serial:connected","serial:connecting","serial:reconnect","serial:timeout","serial:disconnected","serial:sent","serial:soft-reload","serial:message","unknown","serial:need-permission","serial:lost","serial:unsupported","serial:error","debug"].forEach(t=>{this.serialRegisterAvailableListener(t)})},q=function(){const e=this;this.on("internal:queue",async()=>{var t;await c(t=e,a,R).call(t)}),c(this,a,M).call(this)},M=function(){const e=this;navigator.serial.addEventListener("connect",async()=>{e.isDisconnected&&await e.serialConnect().catch(()=>{})})},R=async function(){if(!this.__internal__.serial.connected){await this.serialConnect();return}if(this.__internal__.timeout.until_response||this.__internal__.serial.queue.length===0)return;const e=this.__internal__.serial.queue[0];let t=this.__internal__.time.response_general;e.action==="connect"&&(t=this.__internal__.time.response_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await this.timeout(e.bytes,e.action)},t),this.__internal__.serial.last_action=e.action??"unknown",await c(this,a,m).call(this,e.bytes),this.dispatch("serial:sent",{action:e.action,bytes:e.bytes}),this.__internal__.auto_response&&c(this,a,h).call(this,["DD","DD"],null);const n=[...this.__internal__.serial.queue];this.__internal__.serial.queue=n.splice(1)},N=function(e=1){this.__internal__.device_number=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)},O=function(){this.__internal__.last_error={message:null,action:null,code:null,no_code:0}};const l=class l extends y{static typeError(i){const e=new Error;throw e.message=`Type ${i} is not supported`,e.name="DeviceTypeError",e}static registerType(i){typeof l.devices[i]>"u"&&(l.devices[i]={})}static add(i){const e=i.typeDevice;typeof l.devices[e]>"u"&&(l.devices[e]={});const t=i.uuid;if(typeof l.devices[e]>"u"&&l.typeError(e),this.instance.dispatch("change",l.devices),l.devices[e][t])throw new Error(`Device with id ${t} already exists`);return l.devices[e][t]=i,this.instance.dispatch("change",l.devices),Object.keys(l.devices[e]).indexOf(t)}static get(i,e){return typeof l.devices[i]>"u"&&(l.devices[i]={}),typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i][e]}static getAll(i=null){return i===null?l.devices:(typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i])}static getList(){return Object.values(l.devices).map(e=>Object.values(e)).flat()}static getByNumber(i,e){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}static getCustom(i,e=1){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}};f(l,"instance"),f(l,"devices",{});let d=l;d.instance||(d.instance=new d),_.Core=W,_.Devices=d,_.Dispatcher=y,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
4
+ `){const n=this.parseStringToTextEncoder(e,t);return Array.from(n).map(r=>r.toString(16))}parseUint8ToHex(e){return Array.from(e).map(t=>t.toString(16))}parseHexToUint8(e){return new Uint8Array(e.map(t=>parseInt(t,16)))}stringArrayToUint8Array(e){const t=[];return e.forEach(n=>{const r=n.replace("0x","");t.push(parseInt(r,16))}),new Uint8Array(t)}parseUint8ArrayToString(e){const t=this.stringArrayToUint8Array(e);e=this.parseUint8ToHex(t);const n=e.map(r=>parseInt(r,16));return String.fromCharCode(...n).replace(/[\n\r]+/g,"")}hexToAscii(e){const t=e.toString();let n="";for(let r=0;r<t.length;r+=2)n+=String.fromCharCode(parseInt(t.substring(r,2),16));return n}asciiToHex(e){const t=[];for(let n=0,r=e.length;n<r;n++){const d=Number(e.charCodeAt(n)).toString(16);t.push(d)}return t.join("")}$checkAndDispatchConnection(){return this.isConnected}}s=new WeakSet,g=function(e){return!!(e&&e.readable&&e.writable)},b=function(e=null){this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",e),u.$dispatchChange(this)},v=async function(e){const t=this.__internal__.serial.port;if(!t||t&&(!t.readable||!t.writable))throw _(this,s,b).call(this,{error:"Port is closed, not readable or writable."}),new Error("The port is closed or is not readable/writable");const n=this.stringArrayToUint8Array(e);if(t.writable===null)return;const r=t.writable.getWriter();await r.write(n),r.releaseLock()},p=function(e=[],t=null){if(e&&e.length>0){const n=this.__internal__.serial.connected;this.__internal__.serial.connected=_(this,s,g).call(this,this.__internal__.serial.port),!n&&this.__internal__.serial.connected&&(this.dispatch("serial:connected"),u.$dispatchChange(this)),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);const r=[];for(const d in e)r.push(e[d].toString().padStart(2,"0").toLowerCase());if(this.__internal__.serial.response.as==="hex")this.serialMessage(r);else if(this.__internal__.serial.response.as==="uint8")this.serialMessage(this.parseHexToUint8(this.add0x(r)));else if(this.__internal__.serial.response.as==="string")this.serialMessage(this.parseUint8ArrayToString(this.add0x(r)));else{const d=this.stringToArrayBuffer(this.parseUint8ArrayToString(this.add0x(r)));this.serialMessage(d)}}else this.serialCorruptMessage(e,t);this.__internal__.serial.queue.length!==0&&this.dispatch("internal:queue",{})},U=async function(){const e=this.serialFilters,t=await navigator.serial.getPorts({filters:e});return e.length===0?t:t.filter(r=>{const d=r.getInfo();return e.some(A=>d.usbProductId===A.usbProductId&&d.usbVendorId===A.usbVendorId)}).filter(r=>!_(this,s,g).call(this,r))},k=function(e){if(e){const t=this.__internal__.serial.response.buffer,n=new Uint8Array(t.length+e.byteLength);n.set(t,0),n.set(new Uint8Array(e),t.length),this.__internal__.serial.response.buffer=n}},D=async function(){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(()=>{const e=[];for(const t in this.__internal__.serial.response.buffer)e.push(this.__internal__.serial.response.buffer[t].toString(16));this.__internal__.serial.response.buffer&&_(this,s,p).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)},400)},L=async function(){if(this.__internal__.serial.response.length!==null){if(this.__internal__.serial.response.length===this.__internal__.serial.response.buffer.length){const e=[];for(const t in this.__internal__.serial.response.buffer)e.push(this.__internal__.serial.response.buffer[t].toString(16));_(this,s,p).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)}else if(this.__internal__.serial.response.length<this.__internal__.serial.response.buffer.length){let e=new Uint8Array(0);for(let n=0;n<this.__internal__.serial.response.length;n++)e[n]=this.__internal__.serial.response.buffer[n];if(e.length===this.__internal__.serial.response.length){const n=[];for(const r in e)n.push(e[r].toString(16));_(this,s,p).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0);return}e=new Uint8Array(0);const t=this.__internal__.serial.response.length*2;if(this.__internal__.serial.response.buffer.length===t){for(let n=14;n<t;n++)e[n-this.__internal__.serial.response.length]=this.__internal__.serial.response.buffer[n];if(e.length===this.__internal__.serial.response.length){const n=[];for(const r in e)n.push(e[r].toString(16));_(this,s,p).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0)}}}}},P=async function(){const e=this.__internal__.serial.port;if(!e||!e.readable)throw new Error("Port is not readable");for(;e.readable&&this.__internal__.serial.keep_reading;){const t=e.readable.getReader();this.__internal__.serial.reader=t;try{let n=!0;for(;n;){const{value:r,done:d}=await t.read();if(d){t.releaseLock(),this.__internal__.serial.keep_reading=!1,n=!1;break}_(this,s,k).call(this,r),this.__internal__.serial.response.length===null?await _(this,s,D).call(this):await _(this,s,L).call(this)}}catch(n){this.serialErrors(n)}finally{t.releaseLock()}}this.__internal__.serial.keep_reading=!0,this.__internal__.serial.port&&await this.__internal__.serial.port.close()},I=async function(){return typeof window>"u"?!1:"serial"in navigator&&"forget"in SerialPort.prototype&&this.__internal__.serial.port?(await this.__internal__.serial.port.forget(),!0):!1},q=function(){["serial:connected","serial:connecting","serial:reconnect","serial:timeout","serial:disconnected","serial:sent","serial:soft-reload","serial:message","unknown","serial:need-permission","serial:lost","serial:unsupported","serial:error","debug"].forEach(t=>{this.serialRegisterAvailableListener(t)})},$=function(){const e=this;this.on("internal:queue",async()=>{var t;await _(t=e,s,M).call(t)}),_(this,s,R).call(this)},R=function(){const e=this;navigator.serial.addEventListener("connect",async()=>{e.isDisconnected&&await e.serialConnect().catch(()=>{})})},M=async function(){if(!_(this,s,g).call(this,this.__internal__.serial.port)){_(this,s,b).call(this,{error:"Port is closed, not readable or writable."}),await this.serialConnect();return}if(this.__internal__.timeout.until_response||this.__internal__.serial.queue.length===0)return;const e=this.__internal__.serial.queue[0];let t=this.__internal__.time.response_general;e.action==="connect"&&(t=this.__internal__.time.response_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await this.timeout(e.bytes,e.action)},t),this.__internal__.serial.last_action=e.action??"unknown",await _(this,s,v).call(this,e.bytes),this.dispatch("serial:sent",{action:e.action,bytes:e.bytes}),this.__internal__.auto_response&&_(this,s,p).call(this,this.__internal__.serial.auto_response,null);const n=[...this.__internal__.serial.queue];this.__internal__.serial.queue=n.splice(1)},N=function(e=1){this.__internal__.device_number=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)},O=function(){this.__internal__.last_error={message:null,action:null,code:null,no_code:0}},c.Core=W,c.Devices=u,c.Dispatcher=w,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "webserial-core",
3
3
  "description": "Webserial Core to easy connections with serial devices",
4
- "version": "1.0.1",
4
+ "version": "1.0.3",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "danidoble",
@@ -39,9 +39,9 @@
39
39
  "format": "prettier --write ./lib/**/*.ts"
40
40
  },
41
41
  "devDependencies": {
42
- "@eslint/js": "^9.21.0",
42
+ "@eslint/js": "^9.22.0",
43
43
  "@types/w3c-web-serial": "^1.0.8",
44
- "eslint": "^9.21.0",
44
+ "eslint": "^9.22.0",
45
45
  "globals": "^15.15.0",
46
46
  "prettier": "3.4.2",
47
47
  "puppeteer": "^24.4.0",
@@ -49,7 +49,7 @@
49
49
  "typescript": "~5.7.3",
50
50
  "typescript-eslint": "^8.26.0",
51
51
  "uuid": "^11.1.0",
52
- "vite": "^6.2.0"
52
+ "vite": "^6.2.1"
53
53
  },
54
54
  "publishConfig": {
55
55
  "access": "public"