@danidoble/webserial 4.3.5 → 4.4.0-beta.1
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/boardroid.cjs +1 -1
- package/dist/boardroid.js +4 -4
- package/dist/hopper.cjs +2 -2
- package/dist/hopper.js +25 -23
- package/dist/jofemar.cjs +1 -1
- package/dist/jofemar.js +5 -4
- package/dist/{kernel-DAtdBEi3.js → kernel-505KqpPU.js} +1 -1
- package/dist/{kernel-D8A562gb.cjs → kernel-Dq3Fv1y8.cjs} +1 -1
- package/dist/kernel.cjs +2 -2
- package/dist/kernel.js +3 -3
- package/dist/locker.cjs +1 -1
- package/dist/locker.js +6 -6
- package/dist/pinpad.cjs +8 -8
- package/dist/pinpad.js +7 -5
- package/dist/pinpax.cjs +3 -3
- package/dist/pinpax.js +33 -32
- package/dist/relay.cjs +1 -1
- package/dist/relay.js +16 -14
- package/dist/webserial-core-B7vfLzGH.cjs +4 -0
- package/dist/webserial-core-C0ZbaNYy.js +3315 -0
- package/dist/webserial.cjs +2 -2
- package/dist/webserial.js +17 -16
- package/package.json +5 -5
- package/dist/webserial-core-BjytHor1.js +0 -812
- package/dist/webserial-core-N14HUamr.cjs +0 -4
package/dist/pinpad.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { K as Ze, a as Ye, i as K, b as Qt, w as Zt } from "./kernel-
|
|
2
|
-
import {
|
|
1
|
+
import { K as Ze, a as Ye, i as K, b as Qt, w as Zt } from "./kernel-505KqpPU.js";
|
|
2
|
+
import { a as Yt } from "./webserial-core-C0ZbaNYy.js";
|
|
3
3
|
var ti = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
4
4
|
function H(n) {
|
|
5
5
|
return ti.charAt(n);
|
|
@@ -3841,7 +3841,8 @@ class vr extends Ze {
|
|
|
3841
3841
|
device_listen_on_channel: r = 1,
|
|
3842
3842
|
username: s = null,
|
|
3843
3843
|
password: a = null,
|
|
3844
|
-
environment: o = "production"
|
|
3844
|
+
environment: o = "production",
|
|
3845
|
+
socket: c = !1
|
|
3845
3846
|
} = {
|
|
3846
3847
|
filters: null,
|
|
3847
3848
|
config_port: {
|
|
@@ -3856,9 +3857,10 @@ class vr extends Ze {
|
|
|
3856
3857
|
device_listen_on_channel: 1,
|
|
3857
3858
|
username: null,
|
|
3858
3859
|
password: null,
|
|
3859
|
-
environment: "production"
|
|
3860
|
+
environment: "production",
|
|
3861
|
+
socket: !1
|
|
3860
3862
|
}) {
|
|
3861
|
-
if (super({ filters: t, config_port: e, no_device: i, device_listen_on_channel: r }), this.__internal__.device.type = "pinpad", !Ye())
|
|
3863
|
+
if (super({ filters: t, config_port: e, no_device: i, device_listen_on_channel: r, socket: c }), this.__internal__.device.type = "pinpad", !Ye())
|
|
3862
3864
|
throw new Error("Crypto not supported in this browser");
|
|
3863
3865
|
if (Yt.getCustom(this.typeDevice, i))
|
|
3864
3866
|
throw new Error(`Device ${this.typeDevice} ${i} already exists`);
|
package/dist/pinpax.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
`,this.#t(),c.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("./kernel-Dq3Fv1y8.cjs"),a=require("./relay-DGFymXOw.cjs"),c=require("./webserial-core-B7vfLzGH.cjs");class h extends u.Kernel{__pinpax__={server:"DEV",bussinessId:null,encriptionKey:null,apiKey:null,asyncResponses:{voucher:null,sale:null},waiting:{voucher:!1,sale:!1}};constructor({filters:s=null,config_port:e={baudRate:115200,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"},no_device:t=1,device_listen_on_channel:i=1,socket:n=!1}={filters:null,config_port:{baudRate:115200,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"},no_device:1,device_listen_on_channel:1,socket:!1}){if(super({filters:s,config_port:e,no_device:t,device_listen_on_channel:i,socket:n}),this.__internal__.device.type="pinpax",c.a.getCustom(this.typeDevice,t))throw new Error(`Device ${this.typeDevice} ${t} already exists`);this.__internal__.time.response_connection=4e3,this.__internal__.time.response_general=3e3,this.__internal__.serial.delay_first_connection=1e3,this.__internal__.serial.response.replacer="",this.__internal__.serial.response.limiter=`\r
|
|
2
|
+
`,this.#t(),c.a.add(this),this.getResponseAsString()}#t(){const s=["buttons-status","init-app","connectMessage","voucher","info","keep-alive","reset-app","get-config","payment","error","refund","login"];for(const e of s)this.serialRegisterAvailableListener(e)}set bussinessId(s){this.__pinpax__.bussinessId=s}get bussinessId(){return this.__pinpax__.bussinessId}set encriptionKey(s){this.__pinpax__.encriptionKey=s}get encriptionKey(){return this.__pinpax__.encriptionKey}set apiKey(s){this.__pinpax__.apiKey=s}get apiKey(){return this.__pinpax__.apiKey}set server(s){this.__pinpax__.server=s}get server(){return this.__pinpax__.server}serialMessage(s){let e=null;try{e=JSON.parse(s),e.request||(e.request=this.lastAction),e.name||(e.name=this.lastAction)}catch(t){console.error("Error parsing response",t,s),this.dispatch("serial:message",s);return}switch(e.response){case"INITAPP":this.dispatch("init-app",{name:"INITAPP",request:this.lastAction,status:"started"}),this.#n().then(()=>{});break;case"CONNECT":this.dispatch("connectMessage",{name:"CONNECT",request:this.lastAction,status:"connected"}),this.#r().then(()=>{});break;case"LOGIN":e.name||(e.name="LOGIN"),this.dispatch("login",e);break;case"LASTVOUCHER":e.name||(e.name="LASTVOUCHER"),this.dispatch("voucher",e),this.__pinpax__.waiting.voucher&&(this.__pinpax__.asyncResponses.voucher=e,this.__pinpax__.waiting.voucher=!1);break;case"DEVICEINFO":e.name||(e.name="DEVICEINFO"),this.dispatch("info",e);break;case"KEEPALIVE":this.dispatch("keep-alive",{name:"KEEPALIVE",request:this.lastAction,status:"alive"});break;case"RESETAPP":this.dispatch("reset-app",{name:"RESETAPP",request:this.lastAction,status:"accepted"});break;case"GETCONFIG":e.name||(e.name="GETCONFIG"),this.dispatch("get-config",e);break;case"HIDEBUTTONS":this.dispatch("buttons-status",{name:"HIDEBUTTONS",request:this.lastAction,hidden:!0});break;case"SHOWBUTTONS":this.dispatch("buttons-status",{name:"SHOWBUTTONS",request:this.lastAction,hidden:!1});break;case"PAYMENT_PROCESS":e.name||(e.name="PAYMENT_PROCESS"),this.dispatch("payment",{name:"PAYMENT_PROCESS",request:this.lastAction,status:"starting",amount:e.amount,reference:e.referecence});break;case"INSERT_CARD":this.dispatch("payment",{name:"INSERT_CARD",request:this.lastAction,status:"insert card"});break;case"CARD_DATA":e.name||(e.name="CARD_DATA"),this.dispatch("payment",{name:"CARD_DATA",request:this.lastAction,status:"card data",amount:e.amount,cardHolderName:e.cardHolderName,ccMark:e.ccMark,ccType:e.ccType,currency:e.currency,maskedPan:e.maskedPan,readingType:e.readingType});break;case"MERCHANT":e.name||(e.name="MERCHANT"),this.dispatch("payment",{request:this.lastAction,status:"merchant",afiliation:e.afiliation,alias:e.alias,amountCashBackCommission:e.amountCashBackCommission,currency:e.currency,description:e.description,hasCashBack:e.hasCashBack,limitCashBackAmount:e.limitCashBackAmount,merchant:e.merchant,months:e.months,name:e.name});break;case"TRANSACTION_RESULT":e.name||(e.name="TRANSACTION_RESULT"),this.#o({status:"result",approved:e.approved,acquirer:e.acquirer,address:e.address,amount:e.amount,amountCashback:e.amountCashback,appIDLabel:e.appIDLabel,appId:e.appId,arqc:e.arqc,auth:e.auth,ccBin:e.ccBin,ccExpirationDate:e.ccExpirationDate,ccName:e.ccName,ccNumber:e.ccNumber,ccType:e.ccType,comissionCashback:e.comissionCashback,currency:e.currency,date:e.date,errorCode:e.errorCode,errorDescription:e.errorDescription,folio:e.folio,id:e.id,merchantName:e.merchantName,msiLabel:e.msiLabel,operation:e.operation,pin:e.pin,qps:e.qps,reference:e.reference,response:e.response,source:e.source,sourceLabel:e.sourceLabel,time:e.time});break;case"ERROR":e.name||(e.name="ERROR"),this.__pinpax__.waiting.sale&&(this.__pinpax__.asyncResponses.sale={status:"error",approved:!1,response:e}),this.dispatch("error",{name:"ERROR",request:this.lastAction,status:"error",response:e}),this.dispatch("payment",{name:"ERROR",request:this.lastAction,status:"error",response:e});break;case"REFUND":this.dispatch("refund",{name:"ERROR",request:this.lastAction,status:"refund",response:e});break}this.dispatch("serial:message",e)}serialSetConnectionConstant(s=1){return a.s.connection(s)}softReload(){super.softReload(),this.__pinpax__.waiting.sale=!1,this.__pinpax__.waiting.voucher=!1,this.__pinpax__.asyncResponses.sale=null,this.__pinpax__.asyncResponses.voucher=null}async sendCustomCode(s={}){if(typeof s!="object")throw new Error("Invalid object");if(s.constructor!==Object)throw new Error("Invalid object");if(Object.keys(s).length===0)throw new Error("Empty object");if(s.action===void 0||s.action===null)throw new Error("Invalid object add action");const e=JSON.stringify(s),t=this.parseStringToBytes(e,`\r
|
|
3
3
|
`);await this.appendToQueue(this.stringArrayToUint8Array(t),"custom")}async connectMessage(){await this.appendToQueue(a.s.connect(),"connect:message")}async#e(){if(this.isDisconnected)throw new Error("Device is disconnected");if(this.queue.length===0)return!0;const s=this;return new Promise(e=>{let t=setInterval(()=>{s.queue.length===0&&(clearInterval(t),e(!0))},500)})}async#s({type:s="production"}={}){const e=a.s.readQR({type:s});return await this.appendToQueue(e,"read-qr")}async#a(){await this.appendToQueue(a.s.forceHide(),"force-hide")}async#i(){await this.appendToQueue(a.s.forceShow(),"force-show")}async#n(){await this.connectMessage()}async#r(){await this.hideButtons()}#o(s){this.dispatch("payment",s),this.__pinpax__.waiting.sale&&(this.__pinpax__.asyncResponses.sale=s)}async makeSale({amount:s=0,reference:e=null}={}){if(this.isDisconnected)throw new Error("Device is disconnected");if(this.__pinpax__.waiting.sale)throw new Error("Already waiting for sale response");const t=a.s.makeSale({amount:s,reference:e});this.__pinpax__.waiting.sale=!0,this.__pinpax__.asyncResponses.sale=null,this.queue.length>0&&await this.#e();const i=this;return await this.appendToQueue(t,"make-sale"),new Promise(n=>{const r=setInterval(()=>{if(i.__pinpax__.asyncResponses.sale){const o=i.__pinpax__.asyncResponses.sale;i.__pinpax__.asyncResponses.sale=null,i.__pinpax__.waiting.sale=!1,clearInterval(r),n(o.approved)}},100)})}async getVoucher({folio:s=null}={}){if(this.isDisconnected)throw new Error("Device is disconnected");if(this.__pinpax__.waiting.voucher)throw new Error("Already waiting for voucher");if(!s)throw new Error("Folio is required");this.__pinpax__.waiting.voucher=!0,this.__pinpax__.asyncResponses.voucher=null;const e=a.s.getVoucher({folio:s});this.queue.length>0&&await this.#e(),await this.appendToQueue(e,"get-voucher");const t=this;return new Promise((i,n)=>{const r=setTimeout(()=>{t.__pinpax__.waiting.voucher=!1,n("Timeout")},1e4),o=setInterval(()=>{if(t.__pinpax__.asyncResponses.voucher){const p=t.__pinpax__.asyncResponses.voucher;t.__pinpax__.asyncResponses.voucher=null,t.__pinpax__.waiting.voucher=!1,clearInterval(o),clearTimeout(r),i(p.voucher)}},100)})}async info(){await this.appendToQueue(a.s.info(),"info")}async keepAlive(){await this.appendToQueue(a.s.keepAlive(),"keep-alive")}async restartApp(){await this.appendToQueue(a.s.restartApp(),"reset-app")}async getConfig(){return await this.appendToQueue(a.s.getConfig(),"get-config")}async hideButtons(){return await this.appendToQueue(a.s.hideButtons(),"hide-buttons"),await this.#a()}async showButtons(){return await this.appendToQueue(a.s.showButtons(),"show-buttons"),await this.#i()}async demo(){return console.warn("RUNNING DEMO APP, BE CAREFUL"),await this.appendToQueue(a.s.demo(),"demo")}async refund({amount:s=0,folio:e=null,auth:t=null}={}){return await this.appendToQueue(a.s.refund({amount:s,folio:e,auth:t}),"refund")}async readProductionQR(){return await this.#s({type:"production"})}async readQualityAssuranceQR(){return this.#s({type:"QA"})}async exit(){return await this.appendToQueue(a.s.exit(),"exit-app")}async init(){await this.appendToQueue(a.s.init(),"init-app")}async login(){if(!this.apiKey||!this.bussinessId||!this.encriptionKey||!this.server)throw new Error("Invalid data to login check apiKey, bussinessId, encriptionKey, server");const s=JSON.stringify({action:"LOGIN_MIT",server:this.__pinpax__.server,bussiness_id:this.__pinpax__.bussinessId,encription_key:this.__pinpax__.encriptionKey,api_key:this.__pinpax__.apiKey}),e=this.parseStringToBytes(s,`\r
|
|
4
|
-
`);await this.appendToQueue(e,"login")}}exports.PinPax=
|
|
4
|
+
`);await this.appendToQueue(e,"login")}}exports.PinPax=h;
|
package/dist/pinpax.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { K as h } from "./kernel-
|
|
1
|
+
import { K as h } from "./kernel-505KqpPU.js";
|
|
2
2
|
import { s as a } from "./relay-CsdB0FSa.js";
|
|
3
|
-
import {
|
|
4
|
-
class
|
|
3
|
+
import { a as c } from "./webserial-core-C0ZbaNYy.js";
|
|
4
|
+
class m extends h {
|
|
5
5
|
__pinpax__ = {
|
|
6
6
|
server: "DEV",
|
|
7
7
|
bussinessId: null,
|
|
@@ -27,7 +27,8 @@ class y extends h {
|
|
|
27
27
|
flowControl: "none"
|
|
28
28
|
},
|
|
29
29
|
no_device: t = 1,
|
|
30
|
-
device_listen_on_channel: i = 1
|
|
30
|
+
device_listen_on_channel: i = 1,
|
|
31
|
+
socket: n = !1
|
|
31
32
|
} = {
|
|
32
33
|
filters: null,
|
|
33
34
|
config_port: {
|
|
@@ -39,9 +40,10 @@ class y extends h {
|
|
|
39
40
|
flowControl: "none"
|
|
40
41
|
},
|
|
41
42
|
no_device: 1,
|
|
42
|
-
device_listen_on_channel: 1
|
|
43
|
+
device_listen_on_channel: 1,
|
|
44
|
+
socket: !1
|
|
43
45
|
}) {
|
|
44
|
-
if (super({ filters: s, config_port: e, no_device: t, device_listen_on_channel: i }), this.__internal__.device.type = "pinpax", c.getCustom(this.typeDevice, t))
|
|
46
|
+
if (super({ filters: s, config_port: e, no_device: t, device_listen_on_channel: i, socket: n }), this.__internal__.device.type = "pinpax", c.getCustom(this.typeDevice, t))
|
|
45
47
|
throw new Error(`Device ${this.typeDevice} ${t} already exists`);
|
|
46
48
|
this.__internal__.time.response_connection = 4e3, this.__internal__.time.response_general = 3e3, this.__internal__.serial.delay_first_connection = 1e3, this.__internal__.serial.response.replacer = "", this.__internal__.serial.response.limiter = `\r
|
|
47
49
|
`, this.#t(), c.add(this), this.getResponseAsString();
|
|
@@ -91,56 +93,60 @@ class y extends h {
|
|
|
91
93
|
serialMessage(s) {
|
|
92
94
|
let e = null;
|
|
93
95
|
try {
|
|
94
|
-
e = JSON.parse(s);
|
|
96
|
+
e = JSON.parse(s), e.request || (e.request = this.lastAction), e.name || (e.name = this.lastAction);
|
|
95
97
|
} catch (t) {
|
|
96
98
|
console.error("Error parsing response", t, s), this.dispatch("serial:message", s);
|
|
97
99
|
return;
|
|
98
100
|
}
|
|
99
101
|
switch (e.response) {
|
|
100
102
|
case "INITAPP":
|
|
101
|
-
this.dispatch("init-app", { status: "started" }), this.#n().then(() => {
|
|
103
|
+
this.dispatch("init-app", { name: "INITAPP", request: this.lastAction, status: "started" }), this.#n().then(() => {
|
|
102
104
|
});
|
|
103
105
|
break;
|
|
104
106
|
case "CONNECT":
|
|
105
|
-
this.dispatch("connectMessage", { status: "connected" }), this.#r().then(() => {
|
|
107
|
+
this.dispatch("connectMessage", { name: "CONNECT", request: this.lastAction, status: "connected" }), this.#r().then(() => {
|
|
106
108
|
});
|
|
107
109
|
break;
|
|
108
110
|
case "LOGIN":
|
|
109
|
-
this.dispatch("login", e);
|
|
111
|
+
e.name || (e.name = "LOGIN"), this.dispatch("login", e);
|
|
110
112
|
break;
|
|
111
113
|
case "LASTVOUCHER":
|
|
112
|
-
this.dispatch("voucher", e), this.__pinpax__.waiting.voucher && (this.__pinpax__.asyncResponses.voucher = e, this.__pinpax__.waiting.voucher = !1);
|
|
114
|
+
e.name || (e.name = "LASTVOUCHER"), this.dispatch("voucher", e), this.__pinpax__.waiting.voucher && (this.__pinpax__.asyncResponses.voucher = e, this.__pinpax__.waiting.voucher = !1);
|
|
113
115
|
break;
|
|
114
116
|
case "DEVICEINFO":
|
|
115
|
-
this.dispatch("info", e);
|
|
117
|
+
e.name || (e.name = "DEVICEINFO"), this.dispatch("info", e);
|
|
116
118
|
break;
|
|
117
119
|
case "KEEPALIVE":
|
|
118
|
-
this.dispatch("keep-alive", { status: "alive" });
|
|
120
|
+
this.dispatch("keep-alive", { name: "KEEPALIVE", request: this.lastAction, status: "alive" });
|
|
119
121
|
break;
|
|
120
122
|
case "RESETAPP":
|
|
121
|
-
this.dispatch("reset-app", { status: "accepted" });
|
|
123
|
+
this.dispatch("reset-app", { name: "RESETAPP", request: this.lastAction, status: "accepted" });
|
|
122
124
|
break;
|
|
123
125
|
case "GETCONFIG":
|
|
124
|
-
this.dispatch("get-config", e);
|
|
126
|
+
e.name || (e.name = "GETCONFIG"), this.dispatch("get-config", e);
|
|
125
127
|
break;
|
|
126
128
|
case "HIDEBUTTONS":
|
|
127
|
-
this.dispatch("buttons-status", { hidden: !0 });
|
|
129
|
+
this.dispatch("buttons-status", { name: "HIDEBUTTONS", request: this.lastAction, hidden: !0 });
|
|
128
130
|
break;
|
|
129
131
|
case "SHOWBUTTONS":
|
|
130
|
-
this.dispatch("buttons-status", { hidden: !1 });
|
|
132
|
+
this.dispatch("buttons-status", { name: "SHOWBUTTONS", request: this.lastAction, hidden: !1 });
|
|
131
133
|
break;
|
|
132
134
|
case "PAYMENT_PROCESS":
|
|
133
|
-
this.dispatch("payment", {
|
|
135
|
+
e.name || (e.name = "PAYMENT_PROCESS"), this.dispatch("payment", {
|
|
136
|
+
name: "PAYMENT_PROCESS",
|
|
137
|
+
request: this.lastAction,
|
|
134
138
|
status: "starting",
|
|
135
139
|
amount: e.amount,
|
|
136
140
|
reference: e.referecence
|
|
137
141
|
});
|
|
138
142
|
break;
|
|
139
143
|
case "INSERT_CARD":
|
|
140
|
-
this.dispatch("payment", { status: "insert card" });
|
|
144
|
+
this.dispatch("payment", { name: "INSERT_CARD", request: this.lastAction, status: "insert card" });
|
|
141
145
|
break;
|
|
142
146
|
case "CARD_DATA":
|
|
143
|
-
this.dispatch("payment", {
|
|
147
|
+
e.name || (e.name = "CARD_DATA"), this.dispatch("payment", {
|
|
148
|
+
name: "CARD_DATA",
|
|
149
|
+
request: this.lastAction,
|
|
144
150
|
status: "card data",
|
|
145
151
|
amount: e.amount,
|
|
146
152
|
cardHolderName: e.cardHolderName,
|
|
@@ -152,7 +158,8 @@ class y extends h {
|
|
|
152
158
|
});
|
|
153
159
|
break;
|
|
154
160
|
case "MERCHANT":
|
|
155
|
-
this.dispatch("payment", {
|
|
161
|
+
e.name || (e.name = "MERCHANT"), this.dispatch("payment", {
|
|
162
|
+
request: this.lastAction,
|
|
156
163
|
status: "merchant",
|
|
157
164
|
afiliation: e.afiliation,
|
|
158
165
|
alias: e.alias,
|
|
@@ -167,7 +174,7 @@ class y extends h {
|
|
|
167
174
|
});
|
|
168
175
|
break;
|
|
169
176
|
case "TRANSACTION_RESULT":
|
|
170
|
-
this.#o({
|
|
177
|
+
e.name || (e.name = "TRANSACTION_RESULT"), this.#o({
|
|
171
178
|
status: "result",
|
|
172
179
|
approved: e.approved,
|
|
173
180
|
acquirer: e.acquirer,
|
|
@@ -203,20 +210,14 @@ class y extends h {
|
|
|
203
210
|
});
|
|
204
211
|
break;
|
|
205
212
|
case "ERROR":
|
|
206
|
-
this.__pinpax__.waiting.sale && (this.__pinpax__.asyncResponses.sale = {
|
|
213
|
+
e.name || (e.name = "ERROR"), this.__pinpax__.waiting.sale && (this.__pinpax__.asyncResponses.sale = {
|
|
207
214
|
status: "error",
|
|
208
215
|
approved: !1,
|
|
209
216
|
response: e
|
|
210
|
-
}), this.dispatch("error", {
|
|
211
|
-
status: "error",
|
|
212
|
-
response: e
|
|
213
|
-
}), this.dispatch("payment", {
|
|
214
|
-
status: "error",
|
|
215
|
-
response: e
|
|
216
|
-
});
|
|
217
|
+
}), this.dispatch("error", { name: "ERROR", request: this.lastAction, status: "error", response: e }), this.dispatch("payment", { name: "ERROR", request: this.lastAction, status: "error", response: e });
|
|
217
218
|
break;
|
|
218
219
|
case "REFUND":
|
|
219
|
-
this.dispatch("refund", { status: "refund", response: e });
|
|
220
|
+
this.dispatch("refund", { name: "ERROR", request: this.lastAction, status: "refund", response: e });
|
|
220
221
|
break;
|
|
221
222
|
}
|
|
222
223
|
this.dispatch("serial:message", e);
|
|
@@ -360,5 +361,5 @@ class y extends h {
|
|
|
360
361
|
}
|
|
361
362
|
}
|
|
362
363
|
export {
|
|
363
|
-
|
|
364
|
+
m as PinPax
|
|
364
365
|
};
|
package/dist/relay.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./kernel-Dq3Fv1y8.cjs"),i=require("./relay-DGFymXOw.cjs"),r=require("./webserial-core-B7vfLzGH.cjs");class o extends s.Kernel{constructor({filters:t=null,config_port:e=null,no_device:n=1,socket:a=!1}={}){if(super({filters:t,config_port:e,no_device:n,socket:a}),this.__internal__.device.type="relay",this.__internal__.auto_response=!0,this.__internal__.serial.auto_response=[2,6,221,221,240,207,3],r.a.getCustom(this.typeDevice,n))throw new Error(`Device ${this.typeDevice} ${n} already exists`);r.a.add(this)}serialMessage(t){const e={code:t,name:null,description:null,request:null,no_code:0};switch(t[1].toString()){case"dd":case"06":e.name="Connection with the serial device completed.",e.description="Your connection with the serial device was successfully completed.",e.request="connect",e.no_code=100;break;case"de":break;default:e.name="Unrecognized response",e.description="The response of application was received, but dont identify with any of current parameters",e.request="undefined",e.no_code=400;break}this.dispatch("serial:message",e)}serialRelaySumHex(t){let e=0;return t.forEach((n,a)=>{a!==3&&(e+=n)}),e}serialSetConnectionConstant(t=1){return i.e.connection(t)}async turnOn(){const t=i.e.activate();await this.appendToQueue(t,"relay:turn-on")}async turnOff(){const t=i.e.deactivate();await this.appendToQueue(t,"relay:turn-off")}async toggle({inverse:t=!1,ms:e=300}={}){if(!t){await this.turnOn(),await s.wait(e),await this.turnOff();return}await this.turnOff(),await s.wait(e),await this.turnOn()}}exports.Relay=o;
|
package/dist/relay.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { K as o, w as i } from "./kernel-
|
|
2
|
-
import { e as
|
|
3
|
-
import {
|
|
4
|
-
class
|
|
5
|
-
constructor({ filters: t = null, config_port: e = null, no_device: n = 1 } = {}) {
|
|
6
|
-
if (super({ filters: t, config_port: e, no_device: n }), this.__internal__.device.type = "relay", this.__internal__.auto_response = !0,
|
|
7
|
-
throw new Error(`Device ${this.typeDevice} ${
|
|
8
|
-
|
|
1
|
+
import { K as o, w as i } from "./kernel-505KqpPU.js";
|
|
2
|
+
import { e as s } from "./relay-CsdB0FSa.js";
|
|
3
|
+
import { a as r } from "./webserial-core-C0ZbaNYy.js";
|
|
4
|
+
class f extends o {
|
|
5
|
+
constructor({ filters: t = null, config_port: e = null, no_device: a = 1, socket: n = !1 } = {}) {
|
|
6
|
+
if (super({ filters: t, config_port: e, no_device: a, socket: n }), this.__internal__.device.type = "relay", this.__internal__.auto_response = !0, this.__internal__.serial.auto_response = [2, 6, 221, 221, 240, 207, 3], r.getCustom(this.typeDevice, a))
|
|
7
|
+
throw new Error(`Device ${this.typeDevice} ${a} already exists`);
|
|
8
|
+
r.add(this);
|
|
9
9
|
}
|
|
10
10
|
serialMessage(t) {
|
|
11
11
|
const e = {
|
|
@@ -17,6 +17,8 @@ class p extends o {
|
|
|
17
17
|
};
|
|
18
18
|
switch (t[1].toString()) {
|
|
19
19
|
case "dd":
|
|
20
|
+
// old status
|
|
21
|
+
case "06":
|
|
20
22
|
e.name = "Connection with the serial device completed.", e.description = "Your connection with the serial device was successfully completed.", e.request = "connect", e.no_code = 100;
|
|
21
23
|
break;
|
|
22
24
|
case "de":
|
|
@@ -29,19 +31,19 @@ class p extends o {
|
|
|
29
31
|
}
|
|
30
32
|
serialRelaySumHex(t) {
|
|
31
33
|
let e = 0;
|
|
32
|
-
return t.forEach((
|
|
33
|
-
|
|
34
|
+
return t.forEach((a, n) => {
|
|
35
|
+
n !== 3 && (e += a);
|
|
34
36
|
}), e;
|
|
35
37
|
}
|
|
36
38
|
serialSetConnectionConstant(t = 1) {
|
|
37
|
-
return
|
|
39
|
+
return s.connection(t);
|
|
38
40
|
}
|
|
39
41
|
async turnOn() {
|
|
40
|
-
const t =
|
|
42
|
+
const t = s.activate();
|
|
41
43
|
await this.appendToQueue(t, "relay:turn-on");
|
|
42
44
|
}
|
|
43
45
|
async turnOff() {
|
|
44
|
-
const t =
|
|
46
|
+
const t = s.deactivate();
|
|
45
47
|
await this.appendToQueue(t, "relay:turn-off");
|
|
46
48
|
}
|
|
47
49
|
async toggle({ inverse: t = !1, ms: e = 300 } = {}) {
|
|
@@ -53,5 +55,5 @@ class p extends o {
|
|
|
53
55
|
}
|
|
54
56
|
}
|
|
55
57
|
export {
|
|
56
|
-
|
|
58
|
+
f as Relay
|
|
57
59
|
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";class Y extends CustomEvent{constructor(t,e){super(t,e)}}class et extends EventTarget{__listeners__={debug:!1};__debug__=!1;__listenersCallbacks__=[];dispatch(t,e=null){const n=new Y(t,{detail:e});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new Y("debug",{detail:{type:t,data:e}}))}dispatchAsync(t,e=null,n=100){const r=this;setTimeout(()=>{r.dispatch(t,e)},n)}on(t,e){typeof this.__listeners__[t]<"u"&&!this.__listeners__[t]&&(this.__listeners__[t]=!0),this.__listenersCallbacks__.push({key:t,callback:e}),this.addEventListener(t,e)}off(t,e){this.__listenersCallbacks__=this.__listenersCallbacks__.filter(n=>!(n.key===t&&n.callback===e)),this.removeEventListener(t,e)}serialRegisterAvailableListener(t){this.__listeners__[t]||(this.__listeners__[t]=!1)}get availableListeners(){return Object.keys(this.__listeners__).sort().map(t=>({type:t,listening:this.__listeners__[t]}))}removeAllListeners(){for(const t of this.__listenersCallbacks__)["internal:queue"].includes(t.key)||(this.__listenersCallbacks__=this.__listenersCallbacks__.filter(e=>!(e.key===t.key&&e.callback===t.callback)),this.removeEventListener(t.key,t.callback));for(const t of Object.keys(this.__listeners__))this.__listeners__[t]=!1}}class a extends et{static instance;static devices={};constructor(){super(),["change"].forEach(t=>{this.serialRegisterAvailableListener(t)})}static $dispatchChange(t=null){t&&t.$checkAndDispatchConnection(),a.instance.dispatch("change",{devices:a.devices,dispatcher:t})}static typeError(t){const e=new Error;throw e.message=`Type ${t} is not supported`,e.name="DeviceTypeError",e}static registerType(t){typeof a.devices[t]>"u"&&(a.devices={...a.devices,[t]:{}})}static add(t){const e=t.typeDevice;typeof a.devices[e]>"u"&&a.registerType(e);const n=t.uuid;if(typeof a.devices[e]>"u"&&a.typeError(e),a.devices[e][n])throw new Error(`Device with id ${n} already exists`);return a.devices[e][n]=t,a.$dispatchChange(t),Object.keys(a.devices[e]).indexOf(n)}static get(t,e){return typeof a.devices[t]>"u"&&a.registerType(t),typeof a.devices[t]>"u"&&a.typeError(t),a.devices[t][e]}static getAll(t=null){return t===null?a.devices:(typeof a.devices[t]>"u"&&a.typeError(t),a.devices[t])}static getList(){return Object.values(a.devices).map(t=>Object.values(t)).flat()}static getByNumber(t,e){return typeof a.devices[t]>"u"&&a.typeError(t),Object.values(a.devices[t]).find(n=>n.deviceNumber===e)??null}static getCustom(t,e=1){return typeof a.devices[t]>"u"&&a.typeError(t),Object.values(a.devices[t]).find(n=>n.deviceNumber===e)??null}static async connectToAll(){const t=a.getList();for(const e of t)e.isConnected||await e.connect().catch(console.warn);return Promise.resolve(a.areAllConnected())}static async disconnectAll(){const t=a.getList();for(const e of t)e.isDisconnected||await e.disconnect().catch(console.warn);return Promise.resolve(a.areAllDisconnected())}static async areAllConnected(){const t=a.getList();for(const e of t)if(!e.isConnected)return Promise.resolve(!1);return Promise.resolve(!0)}static async areAllDisconnected(){const t=a.getList();for(const e of t)if(!e.isDisconnected)return Promise.resolve(!1);return Promise.resolve(!0)}static async getAllConnected(){const t=a.getList();return Promise.resolve(t.filter(e=>e.isConnected))}static async getAllDisconnected(){const t=a.getList();return Promise.resolve(t.filter(e=>e.isDisconnected))}}a.instance||(a.instance=new a);function J(s=100){return new Promise(t=>setTimeout(()=>t(),s))}const m=Object.create(null);m.open="0";m.close="1";m.ping="2";m.pong="3";m.message="4";m.upgrade="5";m.noop="6";const x=Object.create(null);Object.keys(m).forEach(s=>{x[m[s]]=s});const q={type:"error",data:"parser error"},st=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",nt=typeof ArrayBuffer=="function",rt=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,V=({type:s,data:t},e,n)=>st&&t instanceof Blob?e?n(t):Q(t,n):nt&&(t instanceof ArrayBuffer||rt(t))?e?n(t):Q(new Blob([t]),n):n(m[s]+(t||"")),Q=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function X(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let P;function ft(s,t){if(st&&s.data instanceof Blob)return s.data.arrayBuffer().then(X).then(t);if(nt&&(s.data instanceof ArrayBuffer||rt(s.data)))return t(X(s.data));V(s,!1,e=>{P||(P=new TextEncoder),t(P.encode(e))})}const G="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",E=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<G.length;s++)E[G.charCodeAt(s)]=s;const yt=s=>{let t=s.length*.75,e=s.length,n,r=0,i,o,h,c;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);const p=new ArrayBuffer(t),u=new Uint8Array(p);for(n=0;n<e;n+=4)i=E[s.charCodeAt(n)],o=E[s.charCodeAt(n+1)],h=E[s.charCodeAt(n+2)],c=E[s.charCodeAt(n+3)],u[r++]=i<<2|o>>4,u[r++]=(o&15)<<4|h>>2,u[r++]=(h&3)<<6|c&63;return p},gt=typeof ArrayBuffer=="function",H=(s,t)=>{if(typeof s!="string")return{type:"message",data:it(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:mt(s.substring(1),t)}:x[e]?s.length>1?{type:x[e],data:s.substring(1)}:{type:x[e]}:q},mt=(s,t)=>{if(gt){const e=yt(s);return it(e,t)}else return{base64:!0,data:s}},it=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},ot="",bt=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,o)=>{V(i,!1,h=>{n[o]=h,++r===e&&t(n.join(ot))})})},wt=(s,t)=>{const e=s.split(ot),n=[];for(let r=0;r<e.length;r++){const i=H(e[r],t);if(n.push(i),i.type==="error")break}return n};function vt(){return new TransformStream({transform(s,t){ft(s,e=>{const n=e.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let N;function T(s){return s.reduce((t,e)=>t+e.length,0)}function A(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let r=0;r<t;r++)e[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),e}function kt(s,t){N||(N=new TextDecoder);const e=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,h){for(e.push(o);;){if(n===0){if(T(e)<1)break;const c=A(e,1);i=(c[0]&128)===128,r=c[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(T(e)<2)break;const c=A(e,2);r=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),n=3}else if(n===2){if(T(e)<8)break;const c=A(e,8),p=new DataView(c.buffer,c.byteOffset,c.length),u=p.getUint32(0);if(u>Math.pow(2,21)-1){h.enqueue(q);break}r=u*Math.pow(2,32)+p.getUint32(4),n=3}else{if(T(e)<r)break;const c=A(e,r);h.enqueue(H(i?c:N.decode(c),t)),n=0}if(r===0||r>s){h.enqueue(q);break}}}})}const at=4;function _(s){if(s)return Et(s)}function Et(s){for(var t in _.prototype)s[t]=_.prototype[t];return s}_.prototype.on=_.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};_.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};_.prototype.off=_.prototype.removeListener=_.prototype.removeAllListeners=_.prototype.removeEventListener=function(s,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+s];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<e.length;r++)if(n=e[r],n===t||n.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+s],this};_.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+s],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(e){e=e.slice(0);for(var n=0,r=e.length;n<r;++n)e[n].apply(this,t)}return this};_.prototype.emitReserved=_.prototype.emit;_.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};_.prototype.hasListeners=function(s){return!!this.listeners(s).length};const O=typeof Promise=="function"&&typeof Promise.resolve=="function"?s=>Promise.resolve().then(s):(s,t)=>t(s,0),d=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Ct="arraybuffer";function ct(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const Tt=d.setTimeout,At=d.clearTimeout;function L(s,t){t.useNativeTimers?(s.setTimeoutFn=Tt.bind(d),s.clearTimeoutFn=At.bind(d)):(s.setTimeoutFn=d.setTimeout.bind(d),s.clearTimeoutFn=d.clearTimeout.bind(d))}const xt=1.33;function St(s){return typeof s=="string"?Rt(s):Math.ceil((s.byteLength||s.size)*xt)}function Rt(s){let t=0,e=0;for(let n=0,r=s.length;n<r;n++)t=s.charCodeAt(n),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(n++,e+=4);return e}function lt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Bt(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function Ot(s){let t={},e=s.split("&");for(let n=0,r=e.length;n<r;n++){let i=e[n].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class Lt extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class W extends _{constructor(t){super(),this.writable=!1,L(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new Lt(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=H(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const e=Bt(t);return e.length?"?"+e:""}}class Pt extends W{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||e()})),this.writable||(n++,this.once("drain",function(){--n||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};wt(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,bt(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=lt()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let ht=!1;try{ht=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Nt=ht;function It(){}class Dt extends Pt{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let n=location.port;n||(n=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,n)=>{this.onError("xhr poll error",e,n)}),this.pollXhr=t}}class g extends _{constructor(t,e,n){super(),this.createRequest=t,L(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const e=ct(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=g.requestsCount++,g.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=It,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete g.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}g.requestsCount=0;g.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Z);else if(typeof addEventListener=="function"){const s="onpagehide"in d?"pagehide":"unload";addEventListener(s,Z,!1)}}function Z(){for(let s in g.requests)g.requests.hasOwnProperty(s)&&g.requests[s].abort()}const qt=function(){const s=ut({xdomain:!1});return s&&s.responseType!==null}();class Ut extends Dt{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=qt&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new g(ut,this.uri(),t)}}function ut(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Nt))return new XMLHttpRequest}catch{}if(!t)try{return new d[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const _t=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class jt extends W{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=_t?{}:ct(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;V(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&O(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=lt()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const I=d.WebSocket||d.MozWebSocket;class Mt extends jt{createSocket(t,e,n){return _t?new I(t,e,n):e?new I(t,e):new I(t)}doWrite(t,e){this.ws.send(e)}}class Ft extends W{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=kt(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=vt();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:h,value:c})=>{h||(this.onPacket(c),i())}).catch(h=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;this._writer.write(n).then(()=>{r&&O(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const $t={websocket:Mt,webtransport:Ft,polling:Ut},Vt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Ht=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function U(s){if(s.length>8e3)throw"URI too long";const t=s,e=s.indexOf("["),n=s.indexOf("]");e!=-1&&n!=-1&&(s=s.substring(0,e)+s.substring(e,n).replace(/:/g,";")+s.substring(n,s.length));let r=Vt.exec(s||""),i={},o=14;for(;o--;)i[Ht[o]]=r[o]||"";return e!=-1&&n!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Wt(i,i.path),i.queryKey=zt(i,i.query),i}function Wt(s,t){const e=/\/{2,9}/g,n=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function zt(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(e[r]=i)}),e}const j=typeof addEventListener=="function"&&typeof removeEventListener=="function",S=[];j&&addEventListener("offline",()=>{S.forEach(s=>s())},!1);class b extends _{constructor(t,e){if(super(),this.binaryType=Ct,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const n=U(t);e.hostname=n.host,e.secure=n.protocol==="https"||n.protocol==="wss",e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=U(e.host).host);L(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ot(this.opts.query)),j&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},S.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=at,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&b.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",b.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=St(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,O(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if(typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(b.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),j&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=S.indexOf(this._offlineEventListener);n!==-1&&S.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}b.protocol=at;class Kt extends b{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;b.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",y=>{if(!n)if(y.type==="pong"&&y.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;b.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(u(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const v=new Error("probe error");v.transport=e.name,this.emitReserved("upgradeError",v)}}))};function i(){n||(n=!0,u(),e.close(),e=null)}const o=y=>{const v=new Error("probe error: "+y);v.transport=e.name,i(),this.emitReserved("upgradeError",v)};function h(){o("transport closed")}function c(){o("socket closed")}function p(y){e&&y.name!==e.name&&i()}const u=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",h),this.off("close",c),this.off("upgrading",p)};e.once("open",r),e.once("error",o),e.once("close",h),this.once("close",c),this.once("upgrading",p),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let Yt=class extends Kt{constructor(s,t={}){const e=typeof s=="object"?s:t;(!e.transports||e.transports&&typeof e.transports[0]=="string")&&(e.transports=(e.transports||["polling","websocket","webtransport"]).map(n=>$t[n]).filter(n=>!!n)),super(s,e)}};function Jt(s,t="",e){let n=s;e=e||typeof location<"u"&&location,s==null&&(s=e.protocol+"//"+e.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=e.protocol+s:s=e.host+s),/^(https?|wss?):\/\//.test(s)||(typeof e<"u"?s=e.protocol+"//"+s:s="https://"+s),n=U(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const r=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+r+":"+n.port+t,n.href=n.protocol+"://"+r+(e&&e.port===n.port?"":":"+n.port),n}const Qt=typeof ArrayBuffer=="function",Xt=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,pt=Object.prototype.toString,Gt=typeof Blob=="function"||typeof Blob<"u"&&pt.call(Blob)==="[object BlobConstructor]",Zt=typeof File=="function"||typeof File<"u"&&pt.call(File)==="[object FileConstructor]";function z(s){return Qt&&(s instanceof ArrayBuffer||Xt(s))||Gt&&s instanceof Blob||Zt&&s instanceof File}function R(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(R(s[e]))return!0;return!1}if(z(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return R(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&R(s[e]))return!0;return!1}function te(s){const t=[],e=s.data,n=s;return n.data=M(e,t),n.attachments=t.length,{packet:n,buffers:t}}function M(s,t){if(!s)return s;if(z(s)){const e={_placeholder:!0,num:t.length};return t.push(s),e}else if(Array.isArray(s)){const e=new Array(s.length);for(let n=0;n<s.length;n++)e[n]=M(s[n],t);return e}else if(typeof s=="object"&&!(s instanceof Date)){const e={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(e[n]=M(s[n],t));return e}return s}function ee(s,t){return s.data=F(s.data,t),delete s.attachments,s}function F(s,t){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<t.length)return t[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=F(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=F(s[e],t));return s}const se=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ne=5;var l;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(l||(l={}));class re{constructor(t){this.replacer=t}encode(t){return(t.type===l.EVENT||t.type===l.ACK)&&R(t)?this.encodeAsBinary({type:t.type===l.EVENT?l.BINARY_EVENT:l.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===l.BINARY_EVENT||t.type===l.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=te(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}function tt(s){return Object.prototype.toString.call(s)==="[object Object]"}class K extends _{constructor(t){super(),this.reviver=t}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===l.BINARY_EVENT;n||e.type===l.BINARY_ACK?(e.type=n?l.EVENT:l.ACK,this.reconstructor=new ie(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(z(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(l[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===l.BINARY_EVENT||n.type===l.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");n.attachments=Number(o)}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(i,e)}else n.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(K.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case l.CONNECT:return tt(e);case l.DISCONNECT:return e===void 0;case l.CONNECT_ERROR:return typeof e=="string"||tt(e);case l.EVENT:case l.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&se.indexOf(e[0])===-1);case l.ACK:case l.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ie{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=ee(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const oe=Object.freeze(Object.defineProperty({__proto__:null,Decoder:K,Encoder:re,get PacketType(){return l},protocol:ne},Symbol.toStringTag,{value:"Module"}));function f(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const ae=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});let dt=class extends _{constructor(s,t,e){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=s,this.nsp=t,e&&e.auth&&(this.auth=e.auth),this._opts=Object.assign({},e),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const s=this.io;this.subs=[f(s,"open",this.onopen.bind(this)),f(s,"packet",this.onpacket.bind(this)),f(s,"error",this.onerror.bind(this)),f(s,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...s){return s.unshift("message"),this.emit.apply(this,s),this}emit(s,...t){var e,n,r;if(ae.hasOwnProperty(s))throw new Error('"'+s.toString()+'" is a reserved event name');if(t.unshift(s),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:l.EVENT,data:t};if(i.options={},i.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const c=this.ids++,p=t.pop();this._registerAckCallback(c,p),i.id=c}const o=(n=(e=this.io.engine)===null||e===void 0?void 0:e.transport)===null||n===void 0?void 0:n.writable,h=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!o||(h?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(s,t){var e;const n=(e=this.flags.timeout)!==null&&e!==void 0?e:this._opts.ackTimeout;if(n===void 0){this.acks[s]=t;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[s];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===s&&this.sendBuffer.splice(o,1);t.call(this,new Error("operation has timed out"))},n),i=(...o)=>{this.io.clearTimeoutFn(r),t.apply(this,o)};i.withError=!0,this.acks[s]=i}emitWithAck(s,...t){return new Promise((e,n)=>{const r=(i,o)=>i?n(i):e(o);r.withError=!0,t.push(r),this.emit(s,...t)})}_addToQueue(s){let t;typeof s[s.length-1]=="function"&&(t=s.pop());const e={id:this._queueSeq++,tryCount:0,pending:!1,args:s,flags:Object.assign({fromQueue:!0},this.flags)};s.push((n,...r)=>e!==this._queue[0]?void 0:(n!==null?e.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(n)):(this._queue.shift(),t&&t(null,...r)),e.pending=!1,this._drainQueue())),this._queue.push(e),this._drainQueue()}_drainQueue(s=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!s||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(s){s.nsp=this.nsp,this.io._packet(s)}onopen(){typeof this.auth=="function"?this.auth(s=>{this._sendConnectPacket(s)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(s){this.packet({type:l.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},s):s})}onerror(s){this.connected||this.emitReserved("connect_error",s)}onclose(s,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",s,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(s=>{if(!this.sendBuffer.some(t=>String(t.id)===s)){const t=this.acks[s];delete this.acks[s],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(s){if(s.nsp===this.nsp)switch(s.type){case l.CONNECT:s.data&&s.data.sid?this.onconnect(s.data.sid,s.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case l.EVENT:case l.BINARY_EVENT:this.onevent(s);break;case l.ACK:case l.BINARY_ACK:this.onack(s);break;case l.DISCONNECT:this.ondisconnect();break;case l.CONNECT_ERROR:this.destroy();const t=new Error(s.data.message);t.data=s.data.data,this.emitReserved("connect_error",t);break}}onevent(s){const t=s.data||[];s.id!=null&&t.push(this.ack(s.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(s){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const e of t)e.apply(this,s)}super.emit.apply(this,s),this._pid&&s.length&&typeof s[s.length-1]=="string"&&(this._lastOffset=s[s.length-1])}ack(s){const t=this;let e=!1;return function(...n){e||(e=!0,t.packet({type:l.ACK,id:s,data:n}))}}onack(s){const t=this.acks[s.id];typeof t=="function"&&(delete this.acks[s.id],t.withError&&s.data.unshift(null),t.apply(this,s.data))}onconnect(s,t){this.id=s,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(s=>this.emitEvent(s)),this.receiveBuffer=[],this.sendBuffer.forEach(s=>{this.notifyOutgoingListeners(s),this.packet(s)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(s=>s()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:l.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(s){return this.flags.compress=s,this}get volatile(){return this.flags.volatile=!0,this}timeout(s){return this.flags.timeout=s,this}onAny(s){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(s),this}prependAny(s){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(s),this}offAny(s){if(!this._anyListeners)return this;if(s){const t=this._anyListeners;for(let e=0;e<t.length;e++)if(s===t[e])return t.splice(e,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(s){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(s),this}prependAnyOutgoing(s){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(s),this}offAnyOutgoing(s){if(!this._anyOutgoingListeners)return this;if(s){const t=this._anyOutgoingListeners;for(let e=0;e<t.length;e++)if(s===t[e])return t.splice(e,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(s){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const e of t)e.apply(this,s.data)}}};function w(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}w.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*s);s=(Math.floor(t*10)&1)==0?s-e:s+e}return Math.min(s,this.max)|0};w.prototype.reset=function(){this.attempts=0};w.prototype.setMin=function(s){this.ms=s};w.prototype.setMax=function(s){this.max=s};w.prototype.setJitter=function(s){this.jitter=s};class $ extends _{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,L(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((n=e.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new w({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||oe;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Yt(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=f(e,"open",function(){n.onopen(),t&&t()}),i=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),t?t(h):this.maybeReconnectOnOpen()},o=f(e,"error",i);if(this._timeout!==!1){const h=this._timeout,c=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},h);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(f(t,"ping",this.onping.bind(this)),f(t,"data",this.ondata.bind(this)),f(t,"error",this.onerror.bind(this)),f(t,"close",this.onclose.bind(this)),f(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){O(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new dt(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const n of e)if(this.nsps[n].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const k={};function B(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Jt(s,t.path||"/socket.io"),n=e.source,r=e.id,i=e.path,o=k[r]&&i in k[r].nsps,h=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let c;return h?c=new $(n,t):(k[r]||(k[r]=new $(n,t)),c=k[r]),e.query&&!t.query&&(t.query=e.queryKey),c.socket(e.path,t)}Object.assign(B,{Manager:$,Socket:dt,io:B,connect:B});class ce{#e="http://localhost:3000";#s={transports:["websocket"]};#t;#i=!1;#o={};set uri(t){const e=new URL(t);if(!["http:","https:","ws:","wss:"].includes(e.protocol))throw new Error("URI must start with http://, https://, ws://, or wss://");this.#e=t}get uri(){return this.#e}set options(t){if(typeof t!="object")throw new Error("Options must be an object");this.#s=t}get options(){return this.#s}constructor(){this.#o.onResponse=this.onResponse.bind(this)}disconnect(){this.#t&&(this.#t.off("response",this.#o.onResponse),this.#t.disconnect(),this.#t=null),this.#i=!1}prepare(){this.#i||(this.#t=B(this.#e,this.#s),this.#i=!0,this.#t.on("response",this.#o.onResponse))}connectDevice(t){this.#t.emit("connectDevice",{config:t})}disconnectDevice(t){this.#t.emit("disconnectDevice",{config:t})}disconnectAllDevices(){this.#t.emit("disconnectAll")}write(t){this.#t.emit("cmd",t)}onResponse(t){let e=a.get(t.name,t.uuid);e||(e=a.getByNumber(t.name,t.deviceNumber)),e&&e.socketResponse(t)}}const C=new ce,D={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class le extends et{__internal__={bypassSerialBytesConnection:!1,auto_response:!1,device_number:1,aux_port_connector:0,last_error:{message:null,action:null,code:null,no_code:0},serial:{socket:!1,portInfo:{path:null,vendorId:null,productId:null,parser:{name:"inter-byte-timeout",interval:50}},aux_connecting:"idle",connecting:!1,connected:!1,port:null,last_action:null,response:{length:null,buffer:new Uint8Array([]),as:"uint8",replacer:/[\n\r]+/g,limiter:null,prefixLimiter:!1,sufixLimiter:!0,delimited:!1},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:D,queue:[],auto_response:null,free_timeout_ms:50,useRTSCTS:!1},device:{type:"unknown",id:window.crypto.randomUUID(),listen_on_port:null},time:{response_connection:500,response_engines:2e3,response_general:2e3},timeout:{until_response:0},interval:{reconnection:0}};#e=null;constructor({filters:t=null,config_port:e=D,no_device:n=1,device_listen_on_channel:r=1,bypassSerialBytesConnection:i=!1,socket:o=!1}={filters:null,config_port:D,no_device:1,device_listen_on_channel:1,bypassSerialBytesConnection:!1,socket:!1}){if(super(),!("serial"in navigator))throw new Error("Web Serial not supported");t&&(this.serialFilters=t),e&&(this.serialConfigPort=e),i&&(this.__internal__.bypassSerialBytesConnection=i),n&&this.#w(n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),this.__internal__.serial.socket=o,this.#y(),this.#g()}set listenOnChannel(t){if(typeof t=="string"&&(t=parseInt(t)),isNaN(t)||t<1||t>255)throw new Error("Invalid port number");this.__internal__.device.listen_on_port=t,!this.__internal__.bypassSerialBytesConnection&&(this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(t))}get lastAction(){return this.__internal__.serial.last_action}get listenOnChannel(){return this.__internal__.device.listen_on_port??1}set serialFilters(t){if(this.isConnected)throw new Error("Cannot change serial filters while connected");this.__internal__.serial.filters=t}get serialFilters(){return this.__internal__.serial.filters}set serialConfigPort(t){if(this.isConnected)throw new Error("Cannot change serial filters while connected");this.__internal__.serial.config_port=t}get serialConfigPort(){return this.__internal__.serial.config_port}get useRTSCTS(){return this.__internal__.serial.useRTSCTS}set useRTSCTS(t){this.__internal__.serial.useRTSCTS=t}get isConnected(){const t=this.__internal__.serial.connected,e=this.#s(this.__internal__.serial.port);return t&&!e&&this.#t({error:"Port is closed, not readable or writable."}),this.__internal__.serial.connected=e,this.__internal__.serial.connected}get isConnecting(){return this.__internal__.serial.connecting}get isDisconnected(){const t=this.__internal__.serial.connected,e=this.#s(this.__internal__.serial.port);return!t&&e&&(this.dispatch("serial:connected"),this.#r(!1),a.$dispatchChange(this)),this.__internal__.serial.connected=e,!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}get responseDelimited(){return this.__internal__.serial.response.delimited}set responseDelimited(t){if(typeof t!="boolean")throw new Error("responseDelimited must be a boolean");this.__internal__.serial.response.delimited=t}get responsePrefixLimited(){return this.__internal__.serial.response.prefixLimiter}set responsePrefixLimited(t){if(typeof t!="boolean")throw new Error("responsePrefixLimited must be a boolean");this.__internal__.serial.response.prefixLimiter=t}get responseSufixLimited(){return this.__internal__.serial.response.sufixLimiter}set responseSufixLimited(t){if(typeof t!="boolean")throw new Error("responseSufixLimited must be a boolean");this.__internal__.serial.response.sufixLimiter=t}get responseLimiter(){return this.__internal__.serial.response.limiter}set responseLimiter(t){if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("responseLimiter must be a string or a RegExp");this.__internal__.serial.response.limiter=t}get fixedBytesMessage(){return this.__internal__.serial.response.length}set fixedBytesMessage(t){if(t!==null&&(typeof t!="number"||t<1))throw new Error("Invalid length for fixed bytes message");this.__internal__.serial.response.length=t}get timeoutBeforeResponseBytes(){return this.__internal__.serial.free_timeout_ms||50}set timeoutBeforeResponseBytes(t){if(t!==void 0&&(typeof t!="number"||t<1))throw new Error("Invalid timeout for response bytes");this.__internal__.serial.free_timeout_ms=t??50}get bypassSerialBytesConnection(){return this.__internal__.bypassSerialBytesConnection}set bypassSerialBytesConnection(t){if(typeof t!="boolean")throw new Error("bypassSerialBytesConnection must be a boolean");this.__internal__.bypassSerialBytesConnection=t}get useSocket(){return this.__internal__.serial.socket}get connectionBytes(){const t=this.__internal__.serial.bytes_connection;return t instanceof Uint8Array?t:typeof t=="string"?this.stringArrayToUint8Array(this.parseStringToBytes(t,"")):Array.isArray(t)&&typeof t[0]=="string"?this.stringArrayToUint8Array(t):Array.isArray(t)&&typeof t[0]=="number"?new Uint8Array(t):new Uint8Array([])}set portPath(t){if(this.isConnected)throw new Error("Cannot change port path while connected");if(typeof t!="string"&&t!==null)throw new TypeError("vendorId must be string or null");this.__internal__.serial.portInfo.path=t}get portPath(){return this.__internal__.serial.portInfo.path}set portVendorId(t){if(this.isConnected)throw new Error("Cannot change port vendorId while connected");if(typeof t=="number"&&typeof t!="string"&&t!==null)throw new TypeError("vendorId must be a number, string or null");this.__internal__.serial.portInfo.vendorId=t}get portVendorId(){return this.__internal__.serial.portInfo.vendorId}set portProductId(t){if(this.isConnected)throw new Error("Cannot change port productId while connected");if(typeof t=="number"&&typeof t!="string"&&t!==null)throw new TypeError("productId must be a number, string or null");this.__internal__.serial.portInfo.productId=t}get portProductId(){return this.__internal__.serial.portInfo.productId}set socketPortParser(t){if(["byte-length","inter-byte-timeout"].includes(t))throw new TypeError("socketPortParser must be a string, either 'byte-length' or 'inter-byte-timeout'");this.__internal__.serial.portInfo.parser.name=t}get socketPortParser(){return this.__internal__.serial.portInfo.parser.name}set socketPortParserInterval(t){if(typeof t!="number"||t<1)throw new TypeError("Interval must be a positive number");this.__internal__.serial.portInfo.parser.interval=t}get socketPortParserInterval(){return this.__internal__.serial.portInfo.parser.interval||50}set socketPortParserLength(t){if(typeof t!="number"||t<1)throw new TypeError("Length must be a positive number or null");this.__internal__.serial.portInfo.parser.length=t}get socketPortParserLength(){return this.__internal__.serial.portInfo.parser.length||14}get parserForSocket(){return this.socketPortParser==="byte-length"?{name:this.socketPortParser,length:this.socketPortParserLength}:{name:this.socketPortParser,interval:this.socketPortParserInterval}}get configDeviceSocket(){return{uuid:this.uuid,name:this.typeDevice,deviceNumber:this.deviceNumber,connectionBytes:Array.from(this.connectionBytes),config:{baudRate:this.__internal__.serial.config_port.baudRate,dataBits:this.__internal__.serial.config_port.dataBits,stopBits:this.__internal__.serial.config_port.stopBits,parity:this.__internal__.serial.config_port.parity,bufferSize:this.__internal__.serial.config_port.bufferSize,flowControl:this.__internal__.serial.config_port.flowControl},info:{vendorId:this.portVendorId,productId:this.portProductId,portName:this.portPath},response:{automatic:this.__internal__.auto_response,autoResponse:this.__internal__.serial.auto_response,parser:this.parserForSocket,timeout:{general:this.__internal__.time.response_general,engines:this.__internal__.time.response_engines,connection:this.__internal__.time.response_connection}}}}#s(t){return this.useSocket?this.__internal__.serial.connected:!!(t&&t.readable&&t.writable)}async timeout(t,e){this.__internal__.last_error.message="Operation response timed out.",this.__internal__.last_error.action=e,this.__internal__.last_error.code=t,this.__internal__.timeout.until_response&&(clearTimeout(this.__internal__.timeout.until_response),this.__internal__.timeout.until_response=0),e==="connect"?(this.__internal__.serial.connected=!1,this.dispatch("serial:reconnect",{}),a.$dispatchChange(this)):e==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,a.$dispatchChange(this),await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:t,action:e})}async disconnect(t=null){await this.serialDisconnect(),this.#t(t)}#t(t=null){this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",t),a.$dispatchChange(this)}#i(t){this.__internal__.serial.aux_connecting=t.detail.active?"connecting":"finished"}socketResponse(t){const e=this.__internal__.serial.connected;if(t.type==="disconnect"||t.type==="error"&&t.data==="DISCONNECTED"?this.__internal__.serial.connected=!1:t.type==="success"&&(this.__internal__.serial.connected=!0),a.$dispatchChange(this),!e&&this.__internal__.serial.connected&&(this.dispatch("serial:connected"),this.#r(!1)),t.type==="success")this.#n(new Uint8Array(t.data));else if(t.type==="error"){const n=new Error("The port is closed or is not readable/writable");this.serialErrors(n)}else t.type==="timeout"&&this.timeout(t.data.bytes??[],this.lastAction||"unknown");this.__internal__.serial.last_action=null}async connect(){return this.isConnected?!0:(this.__internal__.serial.aux_connecting="idle",new Promise((t,e)=>{this.#e||(this.#e=this.#i.bind(this)),this.on("internal:connecting",this.#e);const n=setInterval(()=>{this.__internal__.serial.aux_connecting==="finished"?(clearInterval(n),this.__internal__.serial.aux_connecting="idle",this.#e!==null&&this.off("internal:connecting",this.#e),this.isConnected?t(!0):e(`${this.typeDevice} device ${this.deviceNumber} not connected`)):this.__internal__.serial.aux_connecting==="connecting"&&(this.__internal__.serial.aux_connecting="idle",this.dispatch("internal:connecting",{active:!0}),this.dispatch("serial:connecting",{active:!0}))},100);this.serialConnect()}))}async serialDisconnect(){try{if(this.useSocket)C.disconnectDevice(this.configDeviceSocket);else{const t=this.__internal__.serial.reader,e=this.__internal__.serial.output_stream;t&&(await t.cancel().catch(n=>this.serialErrors(n)),await this.__internal__.serial.input_done),e&&(await e.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(t){this.serialErrors(t)}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,a.$dispatchChange(this)}}async#o(t){if(this.isDisconnected)throw this.#t({error:"Port is closed, not readable or writable."}),new Error("The port is closed or is not readable/writable");const e=this.validateBytes(t);C.write({config:this.configDeviceSocket,bytes:Array.from(e)})}async#a(t){if(this.useSocket){await this.#o(t);return}const e=this.__internal__.serial.port;if(!e||e&&(!e.readable||!e.writable))throw this.#t({error:"Port is closed, not readable or writable."}),new Error("The port is closed or is not readable/writable");const n=this.validateBytes(t);if(this.useRTSCTS&&await this.#c(e,5e3),e.writable===null)return;const r=e.writable.getWriter();await r.write(n),r.releaseLock()}async#c(t,e=5e3){const n=Date.now();for(;;){if(Date.now()-n>e)throw new Error("Timeout waiting for clearToSend signal");const{clearToSend:r}=await t.getSignals();if(r)return;await J(100)}}#n(t=new Uint8Array([]),e=!1){if(t&&t.length>0){const n=this.__internal__.serial.connected;if(this.__internal__.serial.connected=this.#s(this.__internal__.serial.port),a.$dispatchChange(this),!n&&this.__internal__.serial.connected&&(this.dispatch("serial:connected"),this.#r(!1)),this.__internal__.interval.reconnection&&(clearInterval(this.__internal__.interval.reconnection),this.__internal__.interval.reconnection=0),this.__internal__.timeout.until_response&&(clearTimeout(this.__internal__.timeout.until_response),this.__internal__.timeout.until_response=0),this.__internal__.serial.response.as==="hex")e?this.serialCorruptMessage(this.parseUint8ToHex(t)):this.serialMessage(this.parseUint8ToHex(t));else if(this.__internal__.serial.response.as==="uint8")e?this.serialCorruptMessage(t):this.serialMessage(t);else if(this.__internal__.serial.response.as==="string"){const r=this.parseUint8ArrayToString(t);if(this.__internal__.serial.response.limiter!==null){const i=r.split(this.__internal__.serial.response.limiter);for(const o in i)i[o]&&(e?this.serialCorruptMessage(i[o]):this.serialMessage(i[o]))}else e?this.serialCorruptMessage(r):this.serialMessage(r)}else{const r=this.stringToArrayBuffer(this.parseUint8ArrayToString(t));e?this.serialCorruptMessage(r):this.serialMessage(r)}}this.__internal__.serial.queue.length!==0&&this.dispatch("internal:queue",{})}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#l(){const t=this.serialFilters,e=await navigator.serial.getPorts({filters:t});return t.length===0?e:e.filter(n=>{const r=n.getInfo();return t.some(i=>r.usbProductId===i.usbProductId&&r.usbVendorId===i.usbVendorId)}).filter(n=>!this.#s(n))}async serialPortsSaved(t){const e=this.serialFilters;if(this.__internal__.aux_port_connector<t.length){const n=this.__internal__.aux_port_connector;this.__internal__.serial.port=t[n]}else this.__internal__.aux_port_connector=0,this.__internal__.serial.port=await navigator.serial.requestPort({filters:e});if(!this.__internal__.serial.port)throw new Error("Select another port please")}serialErrors(t){const e=t.toString().toLowerCase();switch(!0){case e.includes("must be handling a user gesture to show a permission request"):case e.includes("the port is closed."):case e.includes("the port is closed or is not writable"):case e.includes("the port is closed or is not readable"):case e.includes("the port is closed or is not readable/writable"):case e.includes("select another port please"):case e.includes("no port selected by the user"):case e.includes("this readable stream reader has been released and cannot be used to cancel its previous owner stream"):this.dispatch("serial:need-permission",{}),a.$dispatchChange(this);break;case e.includes("the port is already open."):case e.includes("failed to open serial port"):this.serialDisconnect().then(async()=>{this.__internal__.aux_port_connector+=1,await this.serialConnect()});break;case e.includes("cannot read properties of undefined (reading 'writable')"):case e.includes("cannot read properties of null (reading 'writable')"):case e.includes("cannot read property 'writable' of null"):case e.includes("cannot read property 'writable' of undefined"):this.serialDisconnect().then(async()=>{await this.serialConnect()});break;case e.includes("'close' on 'serialport': a call to close() is already in progress."):break;case e.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):break;case e.includes("the port is already closed."):break;case e.includes("the device has been lost"):this.dispatch("serial:lost",{}),a.$dispatchChange(this);break;case e.includes("navigator.serial is undefined"):this.dispatch("serial:unsupported",{});break;default:console.error(t);break}this.dispatch("serial:error",t)}#h(t){if(t){const e=this.__internal__.serial.response.buffer,n=new Uint8Array(e.length+t.byteLength);n.set(e,0),n.set(new Uint8Array(t),e.length),this.__internal__.serial.response.buffer=n}}async#u(){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(()=>{this.__internal__.serial.response.buffer&&this.#n(this.__internal__.serial.response.buffer),this.__internal__.serial.response.buffer=new Uint8Array(0)},this.__internal__.serial.free_timeout_ms||50)}async#_(){const t=this.__internal__.serial.response.length;let e=this.__internal__.serial.response.buffer;if(this.__internal__.serial.time_until_send_bytes&&(clearTimeout(this.__internal__.serial.time_until_send_bytes),this.__internal__.serial.time_until_send_bytes=0),!(t===null||!e||e.length===0)){for(;e.length>=t;){const n=e.slice(0,t);this.#n(n),e=e.slice(t)}this.__internal__.serial.response.buffer=e,e.length>0&&(this.__internal__.serial.time_until_send_bytes=setTimeout(()=>{this.#n(this.__internal__.serial.response.buffer,!0)},this.__internal__.serial.free_timeout_ms||50))}}async#p(){const{limiter:t,prefixLimiter:e=!1,sufixLimiter:n=!0}=this.__internal__.serial.response;if(!t)throw new Error("No limiter defined for delimited serial response");const r=this.__internal__.serial.response.buffer;if(!t||!r||r.length===0)return;this.__internal__.serial.time_until_send_bytes&&(clearTimeout(this.__internal__.serial.time_until_send_bytes),this.__internal__.serial.time_until_send_bytes=0);let i=new TextDecoder().decode(r);const o=[];if(typeof t=="string"){let c;if(e&&n)c=new RegExp(`${t}([^${t}]+)${t}`,"g");else if(e)c=new RegExp(`${t}([^${t}]*)`,"g");else if(n)c=new RegExp(`([^${t}]+)${t}`,"g");else return;let p,u=0;for(;(p=c.exec(i))!==null;)o.push(new TextEncoder().encode(p[1])),u=c.lastIndex;i=i.slice(u)}else if(t instanceof RegExp){let c,p=0;if(e&&n){const u=new RegExp(`${t.source}(.*?)${t.source}`,"g");for(;(c=u.exec(i))!==null;)o.push(new TextEncoder().encode(c[1])),p=u.lastIndex}else if(n)for(;(c=t.exec(i))!==null;){const u=c.index,y=i.slice(p,u);o.push(new TextEncoder().encode(y)),p=t.lastIndex}else if(e){const u=i.split(t);u.shift();for(const y of u)o.push(new TextEncoder().encode(y));i=""}i=i.slice(p)}for(const c of o)this.#n(c);const h=new TextEncoder().encode(i);this.__internal__.serial.response.buffer=h,h.length>0&&(this.__internal__.serial.time_until_send_bytes=setTimeout(()=>{this.#n(this.__internal__.serial.response.buffer,!0),this.__internal__.serial.response.buffer=new Uint8Array(0)},this.__internal__.serial.free_timeout_ms??50))}async#d(){const t=this.__internal__.serial.port;if(!t||!t.readable)throw new Error("Port is not readable");const e=t.readable.getReader();this.__internal__.serial.reader=e;try{for(;this.__internal__.serial.keep_reading;){const{value:n,done:r}=await e.read();if(r)break;this.#h(n),this.__internal__.serial.response.delimited?await this.#p():this.__internal__.serial.response.length===null?await this.#u():await this.#_()}}catch(n){this.serialErrors(n)}finally{e.releaseLock(),this.__internal__.serial.keep_reading=!0,this.__internal__.serial.port&&await this.__internal__.serial.port.close()}}#r(t){t!==this.__internal__.serial.connecting&&(this.__internal__.serial.connecting=t,this.dispatch("serial:connecting",{active:t}),this.dispatch("internal:connecting",{active:t}))}async serialConnect(){try{if(this.#r(!0),this.useSocket)C.prepare(),this.__internal__.serial.last_action="connect",this.__internal__.timeout.until_response=setTimeout(async()=>{await this.timeout(this.__internal__.serial.bytes_connection??[],"connection:start")},this.__internal__.time.response_connection),C.connectDevice(this.configDeviceSocket),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection});else{const t=await this.#l();if(t.length>0)await this.serialPortsSaved(t);else{const r=this.serialFilters;this.__internal__.serial.port=await navigator.serial.requestPort({filters:r})}const e=this.__internal__.serial.port;if(!e)throw new Error("No port selected by the user");await e.open(this.serialConfigPort);const n=this;e.onconnect=r=>{n.dispatch("serial:connected",r),n.#r(!1),a.$dispatchChange(this),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},e.ondisconnect=async()=>{await n.disconnect()},await J(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.#a(this.__internal__.serial.bytes_connection??[]),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection}),this.__internal__.auto_response&&this.#n(this.__internal__.serial.auto_response),await this.#d()}}catch(t){this.#r(!1),this.serialErrors(t)}}async#f(){return typeof window>"u"?!1:"serial"in navigator&&"forget"in SerialPort.prototype&&this.__internal__.serial.port?(await this.__internal__.serial.port.forget(),!0):!1}async serialForget(){return await this.#f()}decToHex(t){return typeof t=="string"&&(t=parseInt(t,10)),t.toString(16)}hexToDec(t){return parseInt(t,16)}hexMaker(t="00",e=2){return t.toString().padStart(e,"0").toLowerCase()}add0x(t){const e=[];return t.forEach((n,r)=>{e[r]="0x"+n}),e}bytesToHex(t){return this.add0x(Array.from(t,e=>this.hexMaker(e)))}#y(){["serial:connected","serial:connecting","serial:reconnect","serial:timeout","serial:disconnected","serial:sent","serial:soft-reload","serial:message","serial:corrupt-message","unknown","serial:need-permission","serial:lost","serial:unsupported","serial:error","debug"].forEach(t=>{this.serialRegisterAvailableListener(t)})}#g(){const t=this;this.on("internal:queue",async()=>{await t.#b()}),this.#m()}#m(){const t=this;navigator.serial.addEventListener("connect",async()=>{t.isDisconnected&&await t.serialConnect().catch(()=>{})})}async#b(){if(!this.#s(this.__internal__.serial.port)){this.#t({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 t=this.__internal__.serial.queue[0];let e=this.__internal__.time.response_general;if(t.action==="connect"&&(e=this.__internal__.time.response_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await this.timeout(t.bytes,t.action)},e),this.__internal__.serial.last_action=t.action??"unknown",await this.#a(t.bytes),this.dispatch("serial:sent",{action:t.action,bytes:t.bytes}),this.__internal__.auto_response){let r=new Uint8Array(0);try{r=this.validateBytes(this.__internal__.serial.auto_response)}catch(i){this.serialErrors(i)}this.#n(r)}const n=[...this.__internal__.serial.queue];this.__internal__.serial.queue=n.splice(1)}validateBytes(t){let e=new Uint8Array(0);if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=this.parseStringToTextEncoder(t);else if(Array.isArray(t)&&typeof t[0]=="string")e=this.stringArrayToUint8Array(t);else if(Array.isArray(t)&&typeof t[0]=="number")e=new Uint8Array(t);else throw new Error("Invalid data type");return e}async appendToQueue(t,e){const n=this.validateBytes(t);if(["connect","connection:start"].includes(e)){if(this.__internal__.serial.connected)return;await this.serialConnect();return}this.__internal__.serial.queue.push({bytes:n,action:e}),this.dispatch("internal:queue",{})}#w(t=1){this.__internal__.device_number=t,!this.__internal__.bypassSerialBytesConnection&&(this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(t))}serialSetConnectionConstant(t=1){if(this.__internal__.bypassSerialBytesConnection)return this.__internal__.serial.bytes_connection;throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${t}`)}serialMessage(t){throw console.log(t),this.dispatch("serial:message",{code:t}),new Error("Method not implemented 'serialMessage'")}serialCorruptMessage(t){throw console.log(t),this.dispatch("serial:corrupt-message",{code:t}),new Error("Method not implemented 'serialCorruptMessage'")}#v(){this.__internal__.last_error={message:null,action:null,code:null,no_code:0}}clearSerialQueue(){this.__internal__.serial.queue=[]}sumHex(t){let e=0;return t.forEach(n=>{e+=parseInt(n,16)}),e.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.#v(),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:t=[]}={code:[]}){if(!t)throw new Error("No data to send");this.__internal__.bypassSerialBytesConnection&&(this.__internal__.serial.bytes_connection=this.validateBytes(t)),await this.appendToQueue(t,"custom")}stringToArrayHex(t){return Array.from(t).map(e=>e.charCodeAt(0).toString(16))}stringToArrayBuffer(t,e=`
|
|
2
|
+
`){return this.parseStringToTextEncoder(t,e).buffer}parseStringToTextEncoder(t="",e=`
|
|
3
|
+
`){const n=new TextEncoder;return t+=e,n.encode(t)}parseStringToBytes(t="",e=`
|
|
4
|
+
`){const n=this.parseStringToTextEncoder(t,e);return Array.from(n).map(r=>r.toString(16))}parseUint8ToHex(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0").toLowerCase())}parseHexToUint8(t){return new Uint8Array(t.map(e=>parseInt(e,16)))}stringArrayToUint8Array(t){const e=[];return typeof t=="string"?this.parseStringToTextEncoder(t).buffer:(t.forEach(n=>{const r=n.replace("0x","");e.push(parseInt(r,16))}),new Uint8Array(e))}parseUint8ArrayToString(t){let e=new Uint8Array(0);t instanceof Uint8Array?e=t:e=this.stringArrayToUint8Array(t),t=this.parseUint8ToHex(e);const n=t.map(r=>parseInt(r,16));return this.__internal__.serial.response.replacer?String.fromCharCode(...n).replace(this.__internal__.serial.response.replacer,""):String.fromCharCode(...n)}hexToAscii(t){const e=t.toString();let n="";for(let r=0;r<e.length;r+=2)n+=String.fromCharCode(parseInt(e.substring(r,2),16));return n}asciiToHex(t){const e=[];for(let n=0,r=t.length;n<r;n++){const i=Number(t.charCodeAt(n)).toString(16);e.push(i)}return e.join("")}$checkAndDispatchConnection(){return this.isConnected}}exports.A=C;exports.a=a;exports.ut=le;
|