webserial-core 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Core.d.ts ADDED
@@ -0,0 +1,183 @@
1
+ import { Dispatcher } from "./Dispatcher.ts";
2
+ interface LastError {
3
+ message: string | null;
4
+ action: string | null;
5
+ code: number | Array<Uint8Array> | Array<string> | null;
6
+ no_code: number;
7
+ }
8
+ interface DeviceData {
9
+ type: string;
10
+ id: string;
11
+ listen_on_port: number | null;
12
+ }
13
+ type SerialResponseAs = "hex" | "uint8" | "string" | "arraybuffer";
14
+ interface SerialResponse {
15
+ length: number | null;
16
+ buffer: Uint8Array;
17
+ as: SerialResponseAs;
18
+ replacer: RegExp | string;
19
+ limiter: null | string | RegExp;
20
+ }
21
+ interface QueueData {
22
+ bytes: string[];
23
+ action: string;
24
+ }
25
+ type SerialData = {
26
+ connected: boolean;
27
+ port: SerialPort | null;
28
+ last_action: string | null;
29
+ response: SerialResponse;
30
+ reader: ReadableStreamDefaultReader<Uint8Array> | null;
31
+ input_done: Promise<void> | null;
32
+ output_done: Promise<void> | null;
33
+ input_stream: ReadableStream<Uint8Array> | null;
34
+ output_stream: WritableStream<Uint8Array> | null;
35
+ keep_reading: boolean;
36
+ time_until_send_bytes: number | undefined | ReturnType<typeof setTimeout>;
37
+ delay_first_connection: number;
38
+ bytes_connection: Array<string> | null;
39
+ filters: SerialPortFilter[];
40
+ config_port: SerialOptions;
41
+ queue: QueueData[];
42
+ auto_response: any;
43
+ };
44
+ interface TimeResponse {
45
+ response_connection: number;
46
+ response_general: number;
47
+ }
48
+ interface Timeout {
49
+ until_response: number | ReturnType<typeof setTimeout>;
50
+ }
51
+ interface InternalIntervals {
52
+ reconnection: number;
53
+ }
54
+ export type Internal = {
55
+ auto_response: boolean;
56
+ device_number: number;
57
+ aux_port_connector: number;
58
+ last_error: LastError;
59
+ serial: SerialData;
60
+ device: DeviceData;
61
+ time: TimeResponse;
62
+ timeout: Timeout;
63
+ interval: InternalIntervals;
64
+ };
65
+ interface CoreConstructorParams {
66
+ filters?: SerialPortFilter[] | null;
67
+ config_port?: SerialOptions;
68
+ no_device?: number;
69
+ device_listen_on_channel?: number | string;
70
+ }
71
+ interface CustomCode {
72
+ code: Array<string>;
73
+ }
74
+ interface ICore {
75
+ lastAction: string | null;
76
+ set listenOnChannel(channel: string | number);
77
+ set serialFilters(filters: SerialPortFilter[]);
78
+ get serialFilters(): SerialPortFilter[];
79
+ set serialConfigPort(config_port: SerialOptions);
80
+ get serialConfigPort(): SerialOptions;
81
+ get isConnected(): boolean;
82
+ get isDisconnected(): boolean;
83
+ get deviceNumber(): number;
84
+ get uuid(): string;
85
+ get typeDevice(): string;
86
+ get queue(): QueueData[];
87
+ timeout(bytes: string[], event: string): Promise<void>;
88
+ disconnect(detail?: null): Promise<void>;
89
+ connect(): Promise<string>;
90
+ serialDisconnect(): Promise<void>;
91
+ serialPortsSaved(ports: SerialPort[]): Promise<void>;
92
+ serialErrors(error: unknown | Error | DOMException): void;
93
+ serialConnect(): Promise<void>;
94
+ serialForget(): Promise<boolean>;
95
+ decToHex(dec: number | string): string;
96
+ hexToDec(hex: string): number;
97
+ hexMaker(val?: string, min?: number): string;
98
+ add0x(bytes: string[]): string[];
99
+ bytesToHex(bytes: string[]): string[];
100
+ appendToQueue(arr: string[], action: string): Promise<void>;
101
+ serialSetConnectionConstant(listen_on_port?: number): never[] | string[];
102
+ serialMessage(hex: string[]): void;
103
+ serialCorruptMessage(code: string[], data: never | null): void;
104
+ clearSerialQueue(): void;
105
+ sumHex(arr: string[]): string;
106
+ softReload(): void;
107
+ sendConnect(): Promise<void>;
108
+ sendCustomCode({ code }: {
109
+ code: CustomCode;
110
+ }): Promise<void>;
111
+ stringToArrayHex(string: string): string[];
112
+ stringToArrayBuffer(string: string, end: string): ArrayBufferLike;
113
+ parseStringToBytes(string: string, end: string): string[];
114
+ parseUint8ToHex(array: Uint8Array): string[];
115
+ parseHexToUint8(array: string[]): Uint8Array;
116
+ stringArrayToUint8Array(strings: string[]): Uint8Array;
117
+ parseUint8ArrayToString(array: string[]): string;
118
+ parseStringToTextEncoder(string: string, end: string): Uint8Array;
119
+ hexToAscii(hex: string | number): string;
120
+ asciiToHex(asciiString: string): string;
121
+ getResponseAsArrayBuffer(): void;
122
+ getResponseAsArrayHex(): void;
123
+ getResponseAsUint8Array(): void;
124
+ getResponseAsString(): void;
125
+ }
126
+ export declare class Core extends Dispatcher implements ICore {
127
+ #private;
128
+ protected __internal__: Internal;
129
+ constructor({ filters, config_port, no_device, device_listen_on_channel, }?: CoreConstructorParams);
130
+ set listenOnChannel(channel: string | number);
131
+ get lastAction(): string | null;
132
+ get listenOnChannel(): number;
133
+ set serialFilters(filters: SerialPortFilter[]);
134
+ get serialFilters(): SerialPortFilter[];
135
+ set serialConfigPort(config_port: SerialOptions);
136
+ get serialConfigPort(): SerialOptions;
137
+ get isConnected(): boolean;
138
+ get isDisconnected(): boolean;
139
+ get deviceNumber(): number;
140
+ get uuid(): string;
141
+ get typeDevice(): string;
142
+ get queue(): QueueData[];
143
+ timeout(bytes: string[], event: string): Promise<void>;
144
+ disconnect(detail?: null): Promise<void>;
145
+ connect(): Promise<string>;
146
+ serialDisconnect(): Promise<void>;
147
+ getResponseAsArrayBuffer(): void;
148
+ getResponseAsArrayHex(): void;
149
+ getResponseAsUint8Array(): void;
150
+ getResponseAsString(): void;
151
+ serialPortsSaved(ports: SerialPort[]): Promise<void>;
152
+ serialErrors(error: any): void;
153
+ serialConnect(): Promise<void>;
154
+ serialForget(): Promise<boolean>;
155
+ decToHex(dec: number | string): string;
156
+ hexToDec(hex: string): number;
157
+ hexMaker(val?: string, min?: number): string;
158
+ add0x(bytes: string[]): string[];
159
+ bytesToHex(bytes: string[]): string[];
160
+ appendToQueue(arr: string[], action: string): Promise<void>;
161
+ serialSetConnectionConstant(listen_on_port?: number): never[] | string[];
162
+ serialMessage(hex: string[] | Uint8Array<ArrayBufferLike> | string | ArrayBuffer): void;
163
+ serialCorruptMessage(code: string[], data: never | null): void;
164
+ clearSerialQueue(): void;
165
+ sumHex(arr: string[]): string;
166
+ toString(): string;
167
+ softReload(): void;
168
+ sendConnect(): Promise<void>;
169
+ sendCustomCode({ code }?: CustomCode): Promise<void>;
170
+ stringToArrayHex(string: string): string[];
171
+ stringToArrayBuffer(string: string, end?: string): ArrayBufferLike;
172
+ parseStringToTextEncoder(string?: string, end?: string): Uint8Array;
173
+ parseStringToBytes(string?: string, end?: string): string[];
174
+ parseUint8ToHex(array: Uint8Array): string[];
175
+ parseHexToUint8(array: string[]): Uint8Array;
176
+ stringArrayToUint8Array(strings: string[]): Uint8Array;
177
+ parseUint8ArrayToString(array: string[]): string;
178
+ hexToAscii(hex: string | number): string;
179
+ asciiToHex(asciiString: string): string;
180
+ $checkAndDispatchConnection(): boolean;
181
+ }
182
+ export {};
183
+ //# sourceMappingURL=Core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Core.d.ts","sourceRoot":"","sources":["../lib/Core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAI7C,UAAU,SAAS;IACjB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IACxD,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,UAAU;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,KAAK,gBAAgB,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,GAAG,aAAa,CAAC;AAEnE,UAAU,cAAc;IACtB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,MAAM,EAAE,U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;IAI5C,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,UAAU;IAI5C,uBAAuB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,UAAU;IAUtD,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM;IAUhD,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM;IASxC,UAAU,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM;IASvC,2BAA2B,IAAI,OAAO;CAGvC"}
@@ -0,0 +1,24 @@
1
+ import { Core } from "./Core.ts";
2
+ import { Dispatcher } from "./Dispatcher.ts";
3
+ interface IDevice {
4
+ [key: string]: Core;
5
+ }
6
+ interface IDevices {
7
+ [key: string]: IDevice;
8
+ }
9
+ export declare class Devices extends Dispatcher {
10
+ static instance: Devices;
11
+ static devices: IDevices;
12
+ constructor();
13
+ static $dispatchChange(device?: Core | null): void;
14
+ static typeError(type: string): void;
15
+ static registerType(type: string): void;
16
+ static add(device: Core): number;
17
+ static get(type: string, id: string): Core;
18
+ static getAll(type?: string | null): IDevice | IDevices;
19
+ static getList(): Core[];
20
+ static getByNumber(type: string, device_number: number): Core | null;
21
+ static getCustom(type: string, device_number?: number): Core | null;
22
+ }
23
+ export {};
24
+ //# sourceMappingURL=Devices.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Devices.d.ts","sourceRoot":"","sources":["../lib/Devices.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,UAAU,OAAO;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB;AAED,UAAU,QAAQ;IAChB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,qBAAa,OAAQ,SAAQ,UAAU;IACrC,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC;IACzB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAM;;IAY9B,MAAM,CAAC,eAAe,CAAC,MAAM,GAAE,IAAI,GAAG,IAAW,GAAG,IAAI;IAOxD,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAOpC,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAMvC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,MAAM;IAoBhC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,IAAI;IAU1C,MAAM,CAAC,MAAM,CAAC,IAAI,GAAE,MAAM,GAAG,IAAW,GAAG,OAAO,GAAG,QAAQ;IAO7D,MAAM,CAAC,OAAO,IAAI,IAAI,EAAE;IAWxB,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAOpE,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,GAAE,MAAU,GAAG,IAAI,GAAG,IAAI;CAMvE"}
@@ -0,0 +1,30 @@
1
+ type AvailableListener = {
2
+ type: string;
3
+ listening: boolean;
4
+ };
5
+ type AvailableListeners = AvailableListener[];
6
+ type DataType = string | number | boolean | object | null;
7
+ interface IDispatcher {
8
+ dispatch(type: string, data?: DataType): void;
9
+ dispatchAsync(type: string, data?: DataType, ms?: number): void;
10
+ on(type: string, callback: EventListener): void;
11
+ off(type: string, callback: EventListener): void;
12
+ serialRegisterAvailableListener(type: string): void;
13
+ availableListeners: AvailableListeners;
14
+ }
15
+ interface Listeners {
16
+ [key: string]: boolean;
17
+ debug: boolean;
18
+ }
19
+ export declare class Dispatcher extends EventTarget implements IDispatcher {
20
+ __listeners__: Listeners;
21
+ __debug__: boolean;
22
+ dispatch(type: string, data?: DataType): void;
23
+ dispatchAsync(type: string, data?: null, ms?: number): void;
24
+ on(type: string, callback: EventListenerOrEventListenerObject): void;
25
+ off(type: string, callback: EventListenerOrEventListenerObject): void;
26
+ serialRegisterAvailableListener(type: string): void;
27
+ get availableListeners(): AvailableListeners;
28
+ }
29
+ export {};
30
+ //# sourceMappingURL=Dispatcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Dispatcher.d.ts","sourceRoot":"","sources":["../lib/Dispatcher.ts"],"names":[],"mappings":"AAEA,KAAK,iBAAiB,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAAC;AAC9D,KAAK,kBAAkB,GAAG,iBAAiB,EAAE,CAAC;AAE9C,KAAK,QAAQ,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,IAAI,CAAC;AAE1D,UAAU,WAAW;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC;IAE9C,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,QAAQ,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAEhE,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,GAAG,IAAI,CAAC;IAEhD,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,GAAG,IAAI,CAAC;IAEjD,+BAA+B,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAEpD,kBAAkB,EAAE,kBAAkB,CAAC;CACxC;AAED,UAAU,SAAS;IACjB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IAEvB,KAAK,EAAE,OAAO,CAAC;CAChB;AAED,qBAAa,UAAW,SAAQ,WAAY,YAAW,WAAW;IAChE,aAAa,EAAE,SAAS,CAEtB;IACF,SAAS,EAAE,OAAO,CAAS;IAE3B,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,QAAe;IAQ5C,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,OAAO,EAAE,EAAE,SAAM;IAQjD,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,kCAAkC;IAQ7D,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,kCAAkC;IAI9D,+BAA+B,CAAC,IAAI,EAAE,MAAM;IAM5C,IAAI,kBAAkB,IAAI,kBAAkB,CAQ3C;CACF"}
@@ -0,0 +1,4 @@
1
+ export declare class SerialEvent extends CustomEvent<SerialEvent> implements CustomEvent {
2
+ constructor(type: string, options: CustomEventInit);
3
+ }
4
+ //# sourceMappingURL=SerialEvent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SerialEvent.d.ts","sourceRoot":"","sources":["../lib/SerialEvent.ts"],"names":[],"mappings":"AAAA,qBAAa,WAAY,SAAQ,WAAW,CAAC,WAAW,CAAE,YAAW,WAAW;gBAClE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe;CAGnD"}
package/dist/main.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @license webserial-core
3
+ * webserial-core
4
+ *
5
+ * Created by (c) Danidoble.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */
10
+ export { Core } from "./Core";
11
+ export { Devices } from "./Devices";
12
+ export { Dispatcher } from "./Dispatcher";
13
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../lib/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,3 @@
1
+ export declare function wait(ms?: number): Promise<void>;
2
+ export declare function supportWebSerial(): boolean;
3
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../lib/utils.ts"],"names":[],"mappings":"AAEA,wBAAgB,IAAI,CAAC,EAAE,GAAE,MAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAIpD;AAED,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C"}
@@ -1,44 +1,17 @@
1
- var N = Object.defineProperty;
2
- var m = (s) => {
3
- throw TypeError(s);
1
+ var M = Object.defineProperty;
2
+ var w = (l) => {
3
+ throw TypeError(l);
4
4
  };
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
- const _ = [];
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
- }
15
- let g;
16
- const B = new Uint8Array(16);
17
- function F() {
18
- if (!g) {
19
- if (typeof crypto > "u" || !crypto.getRandomValues)
20
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
21
- g = crypto.getRandomValues.bind(crypto);
22
- }
23
- return g(B);
24
- }
25
- const V = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), C = { randomUUID: V };
26
- function W(s, i, e) {
27
- var n;
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
- if (t.length < 16)
33
- throw new Error("Random bytes length must be >= 16");
34
- return t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128, j(t);
35
- }
36
- class x extends CustomEvent {
37
- constructor(i, e) {
38
- super(i, e);
5
+ var N = (l, n, e) => n in l ? M(l, n, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[n] = e;
6
+ var d = (l, n, e) => N(l, typeof n != "symbol" ? n + "" : n, e), O = (l, n, e) => n.has(l) || w("Cannot " + e);
7
+ var m = (l, n, e) => n.has(l) ? w("Cannot add the same private member more than once") : n instanceof WeakSet ? n.add(l) : n.set(l, e);
8
+ var o = (l, n, e) => (O(l, n, "access private method"), e);
9
+ class v extends CustomEvent {
10
+ constructor(n, e) {
11
+ super(n, e);
39
12
  }
40
13
  }
41
- class A extends EventTarget {
14
+ class x extends EventTarget {
42
15
  constructor() {
43
16
  super(...arguments);
44
17
  d(this, "__listeners__", {
@@ -47,14 +20,14 @@ class A extends EventTarget {
47
20
  d(this, "__debug__", !1);
48
21
  }
49
22
  dispatch(e, t = null) {
50
- const n = new x(e, { detail: t });
51
- this.dispatchEvent(n), this.__debug__ && this.dispatchEvent(new x("debug", { detail: { type: e, data: t } }));
23
+ const i = new v(e, { detail: t });
24
+ this.dispatchEvent(i), this.__debug__ && this.dispatchEvent(new v("debug", { detail: { type: e, data: t } }));
52
25
  }
53
- dispatchAsync(e, t = null, n = 100) {
54
- const a = this;
26
+ dispatchAsync(e, t = null, i = 100) {
27
+ const r = this;
55
28
  setTimeout(() => {
56
- a.dispatch(e, t);
57
- }, n);
29
+ r.dispatch(e, t);
30
+ }, i);
58
31
  }
59
32
  on(e, t) {
60
33
  typeof this.__listeners__[e] < "u" && !this.__listeners__[e] && (this.__listeners__[e] = !0), this.addEventListener(e, t);
@@ -72,58 +45,58 @@ class A extends EventTarget {
72
45
  }));
73
46
  }
74
47
  }
75
- const o = class o extends A {
48
+ const a = class a extends x {
76
49
  constructor() {
77
50
  super(), ["change"].forEach((e) => {
78
51
  this.serialRegisterAvailableListener(e);
79
52
  });
80
53
  }
81
- static $dispatchChange(i = null) {
82
- i && i.$checkAndDispatchConnection(), o.instance.dispatch("change", { devices: o.devices, dispatcher: i });
54
+ static $dispatchChange(n = null) {
55
+ n && n.$checkAndDispatchConnection(), a.instance.dispatch("change", { devices: a.devices, dispatcher: n });
83
56
  }
84
- static typeError(i) {
57
+ static typeError(n) {
85
58
  const e = new Error();
86
- throw e.message = `Type ${i} is not supported`, e.name = "DeviceTypeError", e;
59
+ throw e.message = `Type ${n} is not supported`, e.name = "DeviceTypeError", e;
87
60
  }
88
- static registerType(i) {
89
- typeof o.devices[i] > "u" && (o.devices[i] = {});
61
+ static registerType(n) {
62
+ typeof a.devices[n] > "u" && (a.devices[n] = {});
90
63
  }
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])
64
+ static add(n) {
65
+ const e = n.typeDevice;
66
+ typeof a.devices[e] > "u" && (a.devices[e] = {});
67
+ const t = n.uuid;
68
+ if (typeof a.devices[e] > "u" && a.typeError(e), a.devices[e][t])
96
69
  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);
70
+ return a.devices[e][t] = n, a.$dispatchChange(n), Object.keys(a.devices[e]).indexOf(t);
98
71
  }
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];
72
+ static get(n, e) {
73
+ return typeof a.devices[n] > "u" && (a.devices[n] = {}), typeof a.devices[n] > "u" && a.typeError(n), a.devices[n][e];
101
74
  }
102
- static getAll(i = null) {
103
- return i === null ? o.devices : (typeof o.devices[i] > "u" && o.typeError(i), o.devices[i]);
75
+ static getAll(n = null) {
76
+ return n === null ? a.devices : (typeof a.devices[n] > "u" && a.typeError(n), a.devices[n]);
104
77
  }
105
78
  static getList() {
106
- return Object.values(o.devices).map((e) => Object.values(e)).flat();
79
+ return Object.values(a.devices).map((e) => Object.values(e)).flat();
107
80
  }
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;
81
+ static getByNumber(n, e) {
82
+ return typeof a.devices[n] > "u" && a.typeError(n), Object.values(a.devices[n]).find((i) => i.deviceNumber === e) ?? null;
110
83
  }
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;
84
+ static getCustom(n, e = 1) {
85
+ return typeof a.devices[n] > "u" && a.typeError(n), Object.values(a.devices[n]).find((i) => i.deviceNumber === e) ?? null;
113
86
  }
114
87
  };
115
- d(o, "instance"), d(o, "devices", {});
116
- let c = o;
117
- c.instance || (c.instance = new c());
118
- function S(s = 100) {
88
+ d(a, "instance"), d(a, "devices", {});
89
+ let _ = a;
90
+ _.instance || (_.instance = new _());
91
+ function C(l = 100) {
119
92
  return new Promise(
120
- (i) => setTimeout(() => i(), s)
93
+ (n) => setTimeout(() => n(), l)
121
94
  );
122
95
  }
123
- function Q() {
96
+ function H() {
124
97
  return "serial" in navigator;
125
98
  }
126
- const b = {
99
+ const g = {
127
100
  baudRate: 9600,
128
101
  dataBits: 8,
129
102
  stopBits: 1,
@@ -131,21 +104,21 @@ const b = {
131
104
  bufferSize: 32768,
132
105
  flowControl: "none"
133
106
  };
134
- var r, p, f, y, u, E, T, U, k, D, L, P, I, $, q, R, M;
135
- class G extends A {
107
+ var s, p, f, b, h, S, A, E, T, k, U, L, P, D, $, q, I;
108
+ class B extends x {
136
109
  constructor({
137
110
  filters: e = null,
138
- config_port: t = b,
139
- no_device: n = 1,
140
- device_listen_on_channel: a = 1
111
+ config_port: t = g,
112
+ no_device: i = 1,
113
+ device_listen_on_channel: r = 1
141
114
  } = {
142
115
  filters: null,
143
- config_port: b,
116
+ config_port: g,
144
117
  no_device: 1,
145
118
  device_listen_on_channel: 1
146
119
  }) {
147
120
  super();
148
- v(this, r);
121
+ m(this, s);
149
122
  d(this, "__internal__", {
150
123
  auto_response: !1,
151
124
  device_number: 1,
@@ -163,7 +136,9 @@ class G extends A {
163
136
  response: {
164
137
  length: null,
165
138
  buffer: new Uint8Array([]),
166
- as: "hex"
139
+ as: "hex",
140
+ replacer: /[\n\r]+/g,
141
+ limiter: null
167
142
  },
168
143
  reader: null,
169
144
  input_done: null,
@@ -175,13 +150,13 @@ class G extends A {
175
150
  delay_first_connection: 200,
176
151
  bytes_connection: null,
177
152
  filters: [],
178
- config_port: b,
153
+ config_port: g,
179
154
  queue: [],
180
155
  auto_response: ["DD", "DD"]
181
156
  },
182
157
  device: {
183
158
  type: "unknown",
184
- id: W(),
159
+ id: window.crypto.randomUUID(),
185
160
  listen_on_port: null
186
161
  },
187
162
  time: {
@@ -197,7 +172,7 @@ class G extends A {
197
172
  });
198
173
  if (!("serial" in navigator))
199
174
  throw new Error("Web Serial not supported");
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);
175
+ e && (this.serialFilters = e), t && (this.serialConfigPort = t), i && o(this, s, q).call(this, i), r && ["number", "string"].includes(typeof r) && (this.listenOnChannel = r), o(this, s, L).call(this), o(this, s, P).call(this);
201
176
  }
202
177
  set listenOnChannel(e) {
203
178
  if (typeof e == "string" && (e = parseInt(e)), isNaN(e) || e < 1 || e > 255)
@@ -223,12 +198,12 @@ class G extends A {
223
198
  return this.__internal__.serial.config_port;
224
199
  }
225
200
  get isConnected() {
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;
201
+ const e = this.__internal__.serial.connected, t = o(this, s, p).call(this, this.__internal__.serial.port);
202
+ return e && !t && o(this, s, f).call(this, { error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
228
203
  }
229
204
  get isDisconnected() {
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;
205
+ const e = this.__internal__.serial.connected, t = o(this, s, p).call(this, this.__internal__.serial.port);
206
+ return !e && t && (this.dispatch("serial:connected"), _.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
232
207
  }
233
208
  get deviceNumber() {
234
209
  return this.__internal__.device_number;
@@ -243,30 +218,30 @@ class G extends A {
243
218
  return this.__internal__.serial.queue;
244
219
  }
245
220
  async timeout(e, t) {
246
- 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", {}), c.$dispatchChange(this)) : t === "connection:start" && (await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector += 1, c.$dispatchChange(this), await this.serialConnect()), this.dispatch("serial:timeout", {
221
+ 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", {}), _.$dispatchChange(this)) : t === "connection:start" && (await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector += 1, _.$dispatchChange(this), await this.serialConnect()), this.dispatch("serial:timeout", {
247
222
  ...this.__internal__.last_error,
248
223
  bytes: e,
249
224
  action: t
250
225
  });
251
226
  }
252
227
  async disconnect(e = null) {
253
- await this.serialDisconnect(), l(this, r, f).call(this, e);
228
+ await this.serialDisconnect(), o(this, s, f).call(this, e);
254
229
  }
255
230
  async connect() {
256
231
  return new Promise((e, t) => {
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`);
232
+ H() || t("Web Serial not supported"), setTimeout(async () => {
233
+ await C(499), await this.serialConnect(), this.isConnected ? e(`${this.typeDevice} device ${this.deviceNumber} connected`) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`);
259
234
  }, 1);
260
235
  });
261
236
  }
262
237
  async serialDisconnect() {
263
238
  try {
264
239
  const e = this.__internal__.serial.reader, t = this.__internal__.serial.output_stream;
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();
240
+ 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();
266
241
  } catch (e) {
267
242
  this.serialErrors(e);
268
243
  } finally {
269
- 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, c.$dispatchChange(this);
244
+ 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, _.$dispatchChange(this);
270
245
  }
271
246
  }
272
247
  getResponseAsArrayBuffer() {
@@ -284,8 +259,8 @@ class G extends A {
284
259
  async serialPortsSaved(e) {
285
260
  const t = this.serialFilters;
286
261
  if (this.__internal__.aux_port_connector < e.length) {
287
- const n = this.__internal__.aux_port_connector;
288
- this.__internal__.serial.port = e[n];
262
+ const i = this.__internal__.aux_port_connector;
263
+ this.__internal__.serial.port = e[i];
289
264
  } else
290
265
  this.__internal__.aux_port_connector = 0, this.__internal__.serial.port = await navigator.serial.requestPort({
291
266
  filters: t
@@ -306,7 +281,7 @@ class G extends A {
306
281
  case t.includes(
307
282
  "this readable stream reader has been released and cannot be used to cancel its previous owner stream"
308
283
  ):
309
- this.dispatch("serial:need-permission", {}), c.$dispatchChange(this);
284
+ this.dispatch("serial:need-permission", {}), _.$dispatchChange(this);
310
285
  break;
311
286
  case t.includes("the port is already open."):
312
287
  case t.includes("failed to open serial port"):
@@ -329,7 +304,7 @@ class G extends A {
329
304
  case t.includes("the port is already closed."):
330
305
  break;
331
306
  case t.includes("the device has been lost"):
332
- this.dispatch("serial:lost", {}), c.$dispatchChange(this);
307
+ this.dispatch("serial:lost", {}), _.$dispatchChange(this);
333
308
  break;
334
309
  case t.includes("navigator.serial is undefined"):
335
310
  this.dispatch("serial:unsupported", {});
@@ -343,36 +318,36 @@ class G extends A {
343
318
  async serialConnect() {
344
319
  try {
345
320
  this.dispatch("serial:connecting", {});
346
- const e = await l(this, r, E).call(this);
321
+ const e = await o(this, s, S).call(this);
347
322
  if (e.length > 0)
348
323
  await this.serialPortsSaved(e);
349
324
  else {
350
- const a = this.serialFilters;
325
+ const r = this.serialFilters;
351
326
  this.__internal__.serial.port = await navigator.serial.requestPort({
352
- filters: a
327
+ filters: r
353
328
  });
354
329
  }
355
330
  const t = this.__internal__.serial.port;
356
331
  if (!t)
357
332
  throw new Error("No port selected by the user");
358
333
  await t.open(this.serialConfigPort);
359
- const n = this;
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", {});
334
+ const i = this;
335
+ t.onconnect = (r) => {
336
+ console.log(r), i.dispatch("serial:connected", r), _.$dispatchChange(this), i.__internal__.serial.queue.length > 0 && i.dispatch("internal:queue", {});
362
337
  }, t.ondisconnect = async () => {
363
- await n.disconnect();
364
- }, await S(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
365
- await n.timeout(n.__internal__.serial.bytes_connection ?? [], "connection:start");
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", {
338
+ await i.disconnect();
339
+ }, await C(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
340
+ await i.timeout(i.__internal__.serial.bytes_connection ?? [], "connection:start");
341
+ }, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await o(this, s, b).call(this, this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
367
342
  action: "connect",
368
343
  bytes: this.__internal__.serial.bytes_connection
369
- }), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null), await l(this, r, D).call(this);
344
+ }), this.__internal__.auto_response && o(this, s, h).call(this, this.__internal__.serial.auto_response, null), await o(this, s, k).call(this);
370
345
  } catch (e) {
371
346
  this.serialErrors(e);
372
347
  }
373
348
  }
374
349
  async serialForget() {
375
- return await l(this, r, L).call(this);
350
+ return await o(this, s, U).call(this);
376
351
  }
377
352
  decToHex(e) {
378
353
  return typeof e == "string" && (e = parseInt(e, 10)), e.toString(16);
@@ -385,21 +360,21 @@ class G extends A {
385
360
  }
386
361
  add0x(e) {
387
362
  const t = [];
388
- return e.forEach((n, a) => {
389
- t[a] = "0x" + n;
363
+ return e.forEach((i, r) => {
364
+ t[r] = "0x" + i;
390
365
  }), t;
391
366
  }
392
367
  bytesToHex(e) {
393
368
  return this.add0x(Array.from(e, (t) => this.hexMaker(t)));
394
369
  }
395
370
  async appendToQueue(e, t) {
396
- const n = this.bytesToHex(e);
371
+ const i = this.bytesToHex(e);
397
372
  if (["connect", "connection:start"].includes(t)) {
398
373
  if (this.__internal__.serial.connected) return;
399
374
  await this.serialConnect();
400
375
  return;
401
376
  }
402
- this.__internal__.serial.queue.push({ bytes: n, action: t }), this.dispatch("internal:queue", {});
377
+ this.__internal__.serial.queue.push({ bytes: i, action: t }), this.dispatch("internal:queue", {});
403
378
  }
404
379
  serialSetConnectionConstant(e = 1) {
405
380
  throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`);
@@ -415,8 +390,8 @@ class G extends A {
415
390
  }
416
391
  sumHex(e) {
417
392
  let t = 0;
418
- return e.forEach((n) => {
419
- t += parseInt(n, 16);
393
+ return e.forEach((i) => {
394
+ t += parseInt(i, 16);
420
395
  }), t.toString(16);
421
396
  }
422
397
  toString() {
@@ -429,7 +404,7 @@ class G extends A {
429
404
  });
430
405
  }
431
406
  softReload() {
432
- l(this, r, M).call(this), this.dispatch("serial:soft-reload", {});
407
+ o(this, s, I).call(this), this.dispatch("serial:soft-reload", {});
433
408
  }
434
409
  async sendConnect() {
435
410
  if (!this.__internal__.serial.bytes_connection)
@@ -451,13 +426,13 @@ class G extends A {
451
426
  }
452
427
  parseStringToTextEncoder(e = "", t = `
453
428
  `) {
454
- const n = new TextEncoder();
455
- return e += t, n.encode(e);
429
+ const i = new TextEncoder();
430
+ return e += t, i.encode(e);
456
431
  }
457
432
  parseStringToBytes(e = "", t = `
458
433
  `) {
459
- const n = this.parseStringToTextEncoder(e, t);
460
- return Array.from(n).map((a) => a.toString(16));
434
+ const i = this.parseStringToTextEncoder(e, t);
435
+ return Array.from(i).map((r) => r.toString(16));
461
436
  }
462
437
  parseUint8ToHex(e) {
463
438
  return Array.from(e).map((t) => t.toString(16));
@@ -467,29 +442,29 @@ class G extends A {
467
442
  }
468
443
  stringArrayToUint8Array(e) {
469
444
  const t = [];
470
- return e.forEach((n) => {
471
- const a = n.replace("0x", "");
472
- t.push(parseInt(a, 16));
445
+ return e.forEach((i) => {
446
+ const r = i.replace("0x", "");
447
+ t.push(parseInt(r, 16));
473
448
  }), new Uint8Array(t);
474
449
  }
475
450
  parseUint8ArrayToString(e) {
476
451
  const t = this.stringArrayToUint8Array(e);
477
452
  e = this.parseUint8ToHex(t);
478
- const n = e.map((a) => parseInt(a, 16));
479
- return String.fromCharCode(...n).replace(/[\n\r]+/g, "");
453
+ const i = e.map((r) => parseInt(r, 16));
454
+ return this.__internal__.serial.response.replacer ? String.fromCharCode(...i).replace(this.__internal__.serial.response.replacer, "") : String.fromCharCode(...i);
480
455
  }
481
456
  hexToAscii(e) {
482
457
  const t = e.toString();
483
- let n = "";
484
- for (let a = 0; a < t.length; a += 2)
485
- n += String.fromCharCode(parseInt(t.substring(a, 2), 16));
486
- return n;
458
+ let i = "";
459
+ for (let r = 0; r < t.length; r += 2)
460
+ i += String.fromCharCode(parseInt(t.substring(r, 2), 16));
461
+ return i;
487
462
  }
488
463
  asciiToHex(e) {
489
464
  const t = [];
490
- for (let n = 0, a = e.length; n < a; n++) {
491
- const h = Number(e.charCodeAt(n)).toString(16);
492
- t.push(h);
465
+ for (let i = 0, r = e.length; i < r; i++) {
466
+ const c = Number(e.charCodeAt(i)).toString(16);
467
+ t.push(c);
493
468
  }
494
469
  return t.join("");
495
470
  }
@@ -497,116 +472,121 @@ class G extends A {
497
472
  return this.isConnected;
498
473
  }
499
474
  }
500
- r = new WeakSet(), p = function(e) {
475
+ s = new WeakSet(), p = function(e) {
501
476
  return !!(e && e.readable && e.writable);
502
477
  }, 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) {
478
+ this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), _.$dispatchChange(this);
479
+ }, b = async function(e) {
505
480
  const t = this.__internal__.serial.port;
506
481
  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);
482
+ throw o(this, s, f).call(this, { error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
483
+ const i = this.stringArrayToUint8Array(e);
509
484
  if (t.writable === null) return;
510
- const a = t.writable.getWriter();
511
- await a.write(n), a.releaseLock();
512
- }, u = function(e = [], t = null) {
485
+ const r = t.writable.getWriter();
486
+ await r.write(i), r.releaseLock();
487
+ }, h = function(e = [], t = null) {
513
488
  if (e && e.length > 0) {
514
- const n = this.__internal__.serial.connected;
515
- this.__internal__.serial.connected = l(this, r, p).call(this, this.__internal__.serial.port), c.$dispatchChange(this), !n && this.__internal__.serial.connected && this.dispatch("serial:connected"), 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());
489
+ const i = this.__internal__.serial.connected;
490
+ this.__internal__.serial.connected = o(this, s, p).call(this, this.__internal__.serial.port), _.$dispatchChange(this), !i && this.__internal__.serial.connected && this.dispatch("serial:connected"), 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);
491
+ const r = [];
492
+ for (const c in e)
493
+ r.push(e[c].toString().padStart(2, "0").toLowerCase());
519
494
  if (this.__internal__.serial.response.as === "hex")
520
- this.serialMessage(a);
495
+ this.serialMessage(r);
521
496
  else if (this.__internal__.serial.response.as === "uint8")
522
- this.serialMessage(this.parseHexToUint8(this.add0x(a)));
497
+ this.serialMessage(this.parseHexToUint8(this.add0x(r)));
523
498
  else if (this.__internal__.serial.response.as === "string")
524
- this.serialMessage(this.parseUint8ArrayToString(this.add0x(a)));
499
+ if (this.__internal__.serial.response.limiter !== null) {
500
+ const u = this.parseUint8ArrayToString(this.add0x(r)).split(this.__internal__.serial.response.limiter);
501
+ for (const y in u)
502
+ u[y] && this.serialMessage(u[y]);
503
+ } else
504
+ this.serialMessage(this.parseUint8ArrayToString(this.add0x(r)));
525
505
  else {
526
- const h = this.stringToArrayBuffer(
527
- this.parseUint8ArrayToString(this.add0x(a))
506
+ const c = this.stringToArrayBuffer(
507
+ this.parseUint8ArrayToString(this.add0x(r))
528
508
  );
529
- this.serialMessage(h);
509
+ this.serialMessage(c);
530
510
  }
531
511
  } else
532
512
  this.serialCorruptMessage(e, t);
533
513
  this.__internal__.serial.queue.length !== 0 && this.dispatch("internal:queue", {});
534
- }, E = async function() {
514
+ }, S = async function() {
535
515
  const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: 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) {
516
+ return e.length === 0 ? t : t.filter((r) => {
517
+ const c = r.getInfo();
518
+ return e.some((u) => c.usbProductId === u.usbProductId && c.usbVendorId === u.usbVendorId);
519
+ }).filter((r) => !o(this, s, p).call(this, r));
520
+ }, A = function(e) {
541
521
  if (e) {
542
- const t = this.__internal__.serial.response.buffer, n = new Uint8Array(t.length + e.byteLength);
543
- n.set(t, 0), n.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = n;
522
+ const t = this.__internal__.serial.response.buffer, i = new Uint8Array(t.length + e.byteLength);
523
+ i.set(t, 0), i.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = i;
544
524
  }
545
- }, U = async function() {
525
+ }, E = async function() {
546
526
  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(() => {
547
527
  const e = [];
548
528
  for (const t in this.__internal__.serial.response.buffer)
549
529
  e.push(this.__internal__.serial.response.buffer[t].toString(16));
550
- this.__internal__.serial.response.buffer && l(this, r, u).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
530
+ this.__internal__.serial.response.buffer && o(this, s, h).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
551
531
  }, 400);
552
- }, k = async function() {
532
+ }, T = async function() {
553
533
  if (this.__internal__.serial.response.length !== null) {
554
534
  if (this.__internal__.serial.response.length === this.__internal__.serial.response.buffer.length) {
555
535
  const e = [];
556
536
  for (const t in this.__internal__.serial.response.buffer)
557
537
  e.push(this.__internal__.serial.response.buffer[t].toString(16));
558
- l(this, r, u).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
538
+ o(this, s, h).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
559
539
  } else if (this.__internal__.serial.response.length < this.__internal__.serial.response.buffer.length) {
560
540
  let e = new Uint8Array(0);
561
- for (let n = 0; n < this.__internal__.serial.response.length; n++)
562
- e[n] = this.__internal__.serial.response.buffer[n];
541
+ for (let i = 0; i < this.__internal__.serial.response.length; i++)
542
+ e[i] = this.__internal__.serial.response.buffer[i];
563
543
  if (e.length === this.__internal__.serial.response.length) {
564
- const n = [];
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);
544
+ const i = [];
545
+ for (const r in e)
546
+ i.push(e[r].toString(16));
547
+ o(this, s, h).call(this, i), this.__internal__.serial.response.buffer = new Uint8Array(0);
568
548
  return;
569
549
  }
570
550
  e = new Uint8Array(0);
571
551
  const t = this.__internal__.serial.response.length * 2;
572
552
  if (this.__internal__.serial.response.buffer.length === t) {
573
- for (let n = 14; n < t; n++)
574
- e[n - this.__internal__.serial.response.length] = this.__internal__.serial.response.buffer[n];
553
+ for (let i = 14; i < t; i++)
554
+ e[i - this.__internal__.serial.response.length] = this.__internal__.serial.response.buffer[i];
575
555
  if (e.length === this.__internal__.serial.response.length) {
576
- const n = [];
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);
556
+ const i = [];
557
+ for (const r in e)
558
+ i.push(e[r].toString(16));
559
+ o(this, s, h).call(this, i), this.__internal__.serial.response.buffer = new Uint8Array(0);
580
560
  }
581
561
  }
582
562
  }
583
563
  }
584
- }, D = async function() {
564
+ }, k = async function() {
585
565
  const e = this.__internal__.serial.port;
586
566
  if (!e || !e.readable) throw new Error("Port is not readable");
587
567
  for (; e.readable && this.__internal__.serial.keep_reading; ) {
588
568
  const t = e.readable.getReader();
589
569
  this.__internal__.serial.reader = t;
590
570
  try {
591
- let n = !0;
592
- for (; n; ) {
593
- const { value: a, done: h } = await t.read();
594
- if (h) {
595
- t.releaseLock(), this.__internal__.serial.keep_reading = !1, n = !1;
571
+ let i = !0;
572
+ for (; i; ) {
573
+ const { value: r, done: c } = await t.read();
574
+ if (c) {
575
+ t.releaseLock(), this.__internal__.serial.keep_reading = !1, i = !1;
596
576
  break;
597
577
  }
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);
578
+ o(this, s, A).call(this, r), this.__internal__.serial.response.length === null ? await o(this, s, E).call(this) : await o(this, s, T).call(this);
599
579
  }
600
- } catch (n) {
601
- this.serialErrors(n);
580
+ } catch (i) {
581
+ this.serialErrors(i);
602
582
  } finally {
603
583
  t.releaseLock();
604
584
  }
605
585
  }
606
586
  this.__internal__.serial.keep_reading = !0, this.__internal__.serial.port && await this.__internal__.serial.port.close();
607
- }, L = async function() {
587
+ }, U = async function() {
608
588
  return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
609
- }, P = function() {
589
+ }, L = function() {
610
590
  [
611
591
  "serial:connected",
612
592
  "serial:connecting",
@@ -625,21 +605,21 @@ r = new WeakSet(), p = function(e) {
625
605
  ].forEach((t) => {
626
606
  this.serialRegisterAvailableListener(t);
627
607
  });
628
- }, I = function() {
608
+ }, P = function() {
629
609
  const e = this;
630
610
  this.on("internal:queue", async () => {
631
611
  var t;
632
- await l(t = e, r, q).call(t);
633
- }), l(this, r, $).call(this);
634
- }, $ = function() {
612
+ await o(t = e, s, $).call(t);
613
+ }), o(this, s, D).call(this);
614
+ }, D = function() {
635
615
  const e = this;
636
616
  navigator.serial.addEventListener("connect", async () => {
637
617
  e.isDisconnected && await e.serialConnect().catch(() => {
638
618
  });
639
619
  });
640
- }, q = 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();
620
+ }, $ = async function() {
621
+ if (!o(this, s, p).call(this, this.__internal__.serial.port)) {
622
+ o(this, s, f).call(this, { error: "Port is closed, not readable or writable." }), await this.serialConnect();
643
623
  return;
644
624
  }
645
625
  if (this.__internal__.timeout.until_response || this.__internal__.serial.queue.length === 0) return;
@@ -647,15 +627,15 @@ r = new WeakSet(), p = function(e) {
647
627
  let t = this.__internal__.time.response_general;
648
628
  e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
649
629
  await this.timeout(e.bytes, e.action);
650
- }, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this, r, y).call(this, e.bytes), this.dispatch("serial:sent", {
630
+ }, t), this.__internal__.serial.last_action = e.action ?? "unknown", await o(this, s, b).call(this, e.bytes), this.dispatch("serial:sent", {
651
631
  action: e.action,
652
632
  bytes: e.bytes
653
- }), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null);
654
- const n = [...this.__internal__.serial.queue];
655
- this.__internal__.serial.queue = n.splice(1);
656
- }, R = function(e = 1) {
633
+ }), this.__internal__.auto_response && o(this, s, h).call(this, this.__internal__.serial.auto_response, null);
634
+ const i = [...this.__internal__.serial.queue];
635
+ this.__internal__.serial.queue = i.splice(1);
636
+ }, q = function(e = 1) {
657
637
  this.__internal__.device_number = e, this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e);
658
- }, M = function() {
638
+ }, I = function() {
659
639
  this.__internal__.last_error = {
660
640
  message: null,
661
641
  action: null,
@@ -664,7 +644,7 @@ r = new WeakSet(), p = function(e) {
664
644
  };
665
645
  };
666
646
  export {
667
- G as Core,
668
- c as Devices,
669
- A as Dispatcher
647
+ B as Core,
648
+ _ as Devices,
649
+ x as Dispatcher
670
650
  };
@@ -1,4 +1,4 @@
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,u)=>a in c?V(c,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):c[a]=u;var f=(c,a,u)=>Q(c,typeof a!="symbol"?a+"":a,u),z=(c,a,u)=>a.has(c)||T("Cannot "+u);var E=(c,a,u)=>a.has(c)?T("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(c):a.set(c,u);var _=(c,a,u)=>(z(c,a,"access private method"),u);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 u(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,u(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 h=l;h.instance||(h.instance=new h);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,$).call(this),_(this,s,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(){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"),h.$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",{}),h.$dispatchChange(this)):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,h.$dispatchChange(this),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,h.$dispatchChange(this)}}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",{}),h.$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",{}),h.$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),h.$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=`
1
+ (function(l,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):(l=typeof globalThis<"u"?globalThis:l||self,_(l.WebSerialCore={}))})(this,function(l){"use strict";var H=Object.defineProperty;var x=l=>{throw TypeError(l)};var R=(l,_,h)=>_ in l?H(l,_,{enumerable:!0,configurable:!0,writable:!0,value:h}):l[_]=h;var f=(l,_,h)=>R(l,typeof _!="symbol"?_+"":_,h),j=(l,_,h)=>_.has(l)||x("Cannot "+h);var S=(l,_,h)=>_.has(l)?x("Cannot add the same private member more than once"):_ instanceof WeakSet?_.add(l):_.set(l,h);var o=(l,_,h)=>(j(l,_,"access private method"),h);var n,g,b,m,d,A,T,E,k,U,P,L,D,$,q,I,M;class _ extends CustomEvent{constructor(r,e){super(r,e)}}class h extends EventTarget{constructor(){super(...arguments);f(this,"__listeners__",{debug:!1});f(this,"__debug__",!1)}dispatch(e,t=null){const i=new _(e,{detail:t});this.dispatchEvent(i),this.__debug__&&this.dispatchEvent(new _("debug",{detail:{type:e,data:t}}))}dispatchAsync(e,t=null,i=100){const s=this;setTimeout(()=>{s.dispatch(e,t)},i)}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 a=class a extends h{constructor(){super(),["change"].forEach(e=>{this.serialRegisterAvailableListener(e)})}static $dispatchChange(r=null){r&&r.$checkAndDispatchConnection(),a.instance.dispatch("change",{devices:a.devices,dispatcher:r})}static typeError(r){const e=new Error;throw e.message=`Type ${r} is not supported`,e.name="DeviceTypeError",e}static registerType(r){typeof a.devices[r]>"u"&&(a.devices[r]={})}static add(r){const e=r.typeDevice;typeof a.devices[e]>"u"&&(a.devices[e]={});const t=r.uuid;if(typeof a.devices[e]>"u"&&a.typeError(e),a.devices[e][t])throw new Error(`Device with id ${t} already exists`);return a.devices[e][t]=r,a.$dispatchChange(r),Object.keys(a.devices[e]).indexOf(t)}static get(r,e){return typeof a.devices[r]>"u"&&(a.devices[r]={}),typeof a.devices[r]>"u"&&a.typeError(r),a.devices[r][e]}static getAll(r=null){return r===null?a.devices:(typeof a.devices[r]>"u"&&a.typeError(r),a.devices[r])}static getList(){return Object.values(a.devices).map(e=>Object.values(e)).flat()}static getByNumber(r,e){return typeof a.devices[r]>"u"&&a.typeError(r),Object.values(a.devices[r]).find(i=>i.deviceNumber===e)??null}static getCustom(r,e=1){return typeof a.devices[r]>"u"&&a.typeError(r),Object.values(a.devices[r]).find(i=>i.deviceNumber===e)??null}};f(a,"instance"),f(a,"devices",{});let c=a;c.instance||(c.instance=new c);function v(y=100){return new Promise(r=>setTimeout(()=>r(),y))}function N(){return"serial"in navigator}const w={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class O extends h{constructor({filters:e=null,config_port:t=w,no_device:i=1,device_listen_on_channel:s=1}={filters:null,config_port:w,no_device:1,device_listen_on_channel:1}){super();S(this,n);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",replacer:/[\n\r]+/g,limiter:null},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:w,queue:[],auto_response:["DD","DD"]},device:{type:"unknown",id:window.crypto.randomUUID(),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),i&&o(this,n,I).call(this,i),s&&["number","string"].includes(typeof s)&&(this.listenOnChannel=s),o(this,n,L).call(this),o(this,n,D).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=o(this,n,g).call(this,this.__internal__.serial.port);return e&&!t&&o(this,n,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=o(this,n,g).call(this,this.__internal__.serial.port);return!e&&t&&(this.dispatch("serial:connected"),c.$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",{}),c.$dispatchChange(this)):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,c.$dispatchChange(this),await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:e,action:t})}async disconnect(e=null){await this.serialDisconnect(),o(this,n,b).call(this,e)}async connect(){return new Promise((e,t)=>{N()||t("Web Serial not supported"),setTimeout(async()=>{await v(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(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()}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,c.$dispatchChange(this)}}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 i=this.__internal__.aux_port_connector;this.__internal__.serial.port=e[i]}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",{}),c.$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",{}),c.$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 o(this,n,A).call(this);if(e.length>0)await this.serialPortsSaved(e);else{const s=this.serialFilters;this.__internal__.serial.port=await navigator.serial.requestPort({filters:s})}const t=this.__internal__.serial.port;if(!t)throw new Error("No port selected by the user");await t.open(this.serialConfigPort);const i=this;t.onconnect=s=>{console.log(s),i.dispatch("serial:connected",s),c.$dispatchChange(this),i.__internal__.serial.queue.length>0&&i.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await i.disconnect()},await v(this.__internal__.serial.delay_first_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await i.timeout(i.__internal__.serial.bytes_connection??[],"connection:start")},this.__internal__.time.response_connection),this.__internal__.serial.last_action="connect",await o(this,n,m).call(this,this.__internal__.serial.bytes_connection??[]),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection}),this.__internal__.auto_response&&o(this,n,d).call(this,this.__internal__.serial.auto_response,null),await o(this,n,U).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await o(this,n,P).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((i,s)=>{t[s]="0x"+i}),t}bytesToHex(e){return this.add0x(Array.from(e,t=>this.hexMaker(t)))}async appendToQueue(e,t){const i=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:i,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(i=>{t+=parseInt(i,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(){o(this,n,M).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
- `){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 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),h.$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),h.$dispatchChange(this),!n&&this.__internal__.serial.connected&&this.dispatch("serial:connected"),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},$=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 _(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=h,c.Dispatcher=w,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
3
+ `){const i=new TextEncoder;return e+=t,i.encode(e)}parseStringToBytes(e="",t=`
4
+ `){const i=this.parseStringToTextEncoder(e,t);return Array.from(i).map(s=>s.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(i=>{const s=i.replace("0x","");t.push(parseInt(s,16))}),new Uint8Array(t)}parseUint8ArrayToString(e){const t=this.stringArrayToUint8Array(e);e=this.parseUint8ToHex(t);const i=e.map(s=>parseInt(s,16));return this.__internal__.serial.response.replacer?String.fromCharCode(...i).replace(this.__internal__.serial.response.replacer,""):String.fromCharCode(...i)}hexToAscii(e){const t=e.toString();let i="";for(let s=0;s<t.length;s+=2)i+=String.fromCharCode(parseInt(t.substring(s,2),16));return i}asciiToHex(e){const t=[];for(let i=0,s=e.length;i<s;i++){const u=Number(e.charCodeAt(i)).toString(16);t.push(u)}return t.join("")}$checkAndDispatchConnection(){return this.isConnected}}n=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),c.$dispatchChange(this)},m=async function(e){const t=this.__internal__.serial.port;if(!t||t&&(!t.readable||!t.writable))throw o(this,n,b).call(this,{error:"Port is closed, not readable or writable."}),new Error("The port is closed or is not readable/writable");const i=this.stringArrayToUint8Array(e);if(t.writable===null)return;const s=t.writable.getWriter();await s.write(i),s.releaseLock()},d=function(e=[],t=null){if(e&&e.length>0){const i=this.__internal__.serial.connected;this.__internal__.serial.connected=o(this,n,g).call(this,this.__internal__.serial.port),c.$dispatchChange(this),!i&&this.__internal__.serial.connected&&this.dispatch("serial:connected"),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 s=[];for(const u in e)s.push(e[u].toString().padStart(2,"0").toLowerCase());if(this.__internal__.serial.response.as==="hex")this.serialMessage(s);else if(this.__internal__.serial.response.as==="uint8")this.serialMessage(this.parseHexToUint8(this.add0x(s)));else if(this.__internal__.serial.response.as==="string")if(this.__internal__.serial.response.limiter!==null){const p=this.parseUint8ArrayToString(this.add0x(s)).split(this.__internal__.serial.response.limiter);for(const C in p)p[C]&&this.serialMessage(p[C])}else this.serialMessage(this.parseUint8ArrayToString(this.add0x(s)));else{const u=this.stringToArrayBuffer(this.parseUint8ArrayToString(this.add0x(s)));this.serialMessage(u)}}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(s=>{const u=s.getInfo();return e.some(p=>u.usbProductId===p.usbProductId&&u.usbVendorId===p.usbVendorId)}).filter(s=>!o(this,n,g).call(this,s))},T=function(e){if(e){const t=this.__internal__.serial.response.buffer,i=new Uint8Array(t.length+e.byteLength);i.set(t,0),i.set(new Uint8Array(e),t.length),this.__internal__.serial.response.buffer=i}},E=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&&o(this,n,d).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));o(this,n,d).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 i=0;i<this.__internal__.serial.response.length;i++)e[i]=this.__internal__.serial.response.buffer[i];if(e.length===this.__internal__.serial.response.length){const i=[];for(const s in e)i.push(e[s].toString(16));o(this,n,d).call(this,i),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 i=14;i<t;i++)e[i-this.__internal__.serial.response.length]=this.__internal__.serial.response.buffer[i];if(e.length===this.__internal__.serial.response.length){const i=[];for(const s in e)i.push(e[s].toString(16));o(this,n,d).call(this,i),this.__internal__.serial.response.buffer=new Uint8Array(0)}}}}},U=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 i=!0;for(;i;){const{value:s,done:u}=await t.read();if(u){t.releaseLock(),this.__internal__.serial.keep_reading=!1,i=!1;break}o(this,n,T).call(this,s),this.__internal__.serial.response.length===null?await o(this,n,E).call(this):await o(this,n,k).call(this)}}catch(i){this.serialErrors(i)}finally{t.releaseLock()}}this.__internal__.serial.keep_reading=!0,this.__internal__.serial.port&&await this.__internal__.serial.port.close()},P=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},L=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)})},D=function(){const e=this;this.on("internal:queue",async()=>{var t;await o(t=e,n,q).call(t)}),o(this,n,$).call(this)},$=function(){const e=this;navigator.serial.addEventListener("connect",async()=>{e.isDisconnected&&await e.serialConnect().catch(()=>{})})},q=async function(){if(!o(this,n,g).call(this,this.__internal__.serial.port)){o(this,n,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 o(this,n,m).call(this,e.bytes),this.dispatch("serial:sent",{action:e.action,bytes:e.bytes}),this.__internal__.auto_response&&o(this,n,d).call(this,this.__internal__.serial.auto_response,null);const i=[...this.__internal__.serial.queue];this.__internal__.serial.queue=i.splice(1)},I=function(e=1){this.__internal__.device_number=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)},M=function(){this.__internal__.last_error={message:null,action:null,code:null,no_code:0}},l.Core=O,l.Devices=c,l.Dispatcher=h,Object.defineProperty(l,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.4",
4
+ "version": "1.0.6",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "danidoble",
@@ -17,7 +17,11 @@
17
17
  "webserial",
18
18
  "serial",
19
19
  "core",
20
- "web"
20
+ "web",
21
+ "iot",
22
+ "device",
23
+ "communication",
24
+ "usb"
21
25
  ],
22
26
  "files": [
23
27
  "dist",
@@ -25,8 +29,10 @@
25
29
  ],
26
30
  "main": "./dist/webserial-core.umd.cjs",
27
31
  "module": "./dist/webserial-core.js",
32
+ "types": "./dist/main.d.ts",
28
33
  "exports": {
29
34
  ".": {
35
+ "types": "./dist/main.d.ts",
30
36
  "import": "./dist/webserial-core.js",
31
37
  "require": "./dist/webserial-core.umd.cjs"
32
38
  }
@@ -39,17 +45,14 @@
39
45
  "format": "prettier --write ./lib/**/*.ts"
40
46
  },
41
47
  "devDependencies": {
42
- "@eslint/js": "^9.22.0",
48
+ "@eslint/js": "^9.26.0",
43
49
  "@types/w3c-web-serial": "^1.0.8",
44
- "eslint": "^9.22.0",
50
+ "eslint": "^9.26.0",
45
51
  "globals": "^15.15.0",
46
52
  "prettier": "3.4.2",
47
- "puppeteer": "^24.4.0",
48
- "semantic-release": "^24.2.3",
49
53
  "typescript": "~5.7.3",
50
- "typescript-eslint": "^8.26.0",
51
- "uuid": "^11.1.0",
52
- "vite": "^6.2.1"
54
+ "typescript-eslint": "^8.32.0",
55
+ "vite": "^6.3.5"
53
56
  },
54
57
  "publishConfig": {
55
58
  "access": "public"