tasmota-esp-web-tools 12.1.0 → 12.1.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/install-dialog.js +18 -11
- package/dist/web/install-button.js +1 -1
- package/dist/web/{install-dialog-7l9oLExq.js → install-dialog-HRJeEoXW.js} +15 -10
- package/js/modules/install-button.js +1 -1
- package/js/modules/{install-dialog-7l9oLExq.js → install-dialog-HRJeEoXW.js} +15 -10
- package/package.json +1 -1
package/dist/install-dialog.js
CHANGED
|
@@ -1159,9 +1159,6 @@ export class EwtInstallDialog extends LitElement {
|
|
|
1159
1159
|
name="password"
|
|
1160
1160
|
type="password"
|
|
1161
1161
|
></ew-filled-text-field>
|
|
1162
|
-
<ew-text-button slot="actions" @click=${this._doProvision}
|
|
1163
|
-
>Connect</ew-text-button
|
|
1164
|
-
>
|
|
1165
1162
|
<ew-text-button
|
|
1166
1163
|
slot="actions"
|
|
1167
1164
|
@click=${async () => {
|
|
@@ -1185,6 +1182,9 @@ export class EwtInstallDialog extends LitElement {
|
|
|
1185
1182
|
? "Skip"
|
|
1186
1183
|
: "Back"}</ew-text-button
|
|
1187
1184
|
>
|
|
1185
|
+
<ew-text-button slot="actions" @click=${this._doProvision}
|
|
1186
|
+
>Connect</ew-text-button
|
|
1187
|
+
>
|
|
1188
1188
|
`;
|
|
1189
1189
|
}
|
|
1190
1190
|
return [heading, content, hideActions];
|
|
@@ -1203,17 +1203,17 @@ export class EwtInstallDialog extends LitElement {
|
|
|
1203
1203
|
<ew-text-button
|
|
1204
1204
|
slot="actions"
|
|
1205
1205
|
@click=${() => {
|
|
1206
|
-
|
|
1207
|
-
this._startInstall(checkbox.checked);
|
|
1206
|
+
this._state = "DASHBOARD";
|
|
1208
1207
|
}}
|
|
1209
|
-
>
|
|
1208
|
+
>Back</ew-text-button
|
|
1210
1209
|
>
|
|
1211
1210
|
<ew-text-button
|
|
1212
1211
|
slot="actions"
|
|
1213
1212
|
@click=${() => {
|
|
1214
|
-
|
|
1213
|
+
const checkbox = this.shadowRoot.querySelector("ew-checkbox");
|
|
1214
|
+
this._startInstall(checkbox.checked);
|
|
1215
1215
|
}}
|
|
1216
|
-
>
|
|
1216
|
+
>Next</ew-text-button
|
|
1217
1217
|
>
|
|
1218
1218
|
`;
|
|
1219
1219
|
return [heading, content];
|
|
@@ -1229,6 +1229,13 @@ export class EwtInstallDialog extends LitElement {
|
|
|
1229
1229
|
content = html `
|
|
1230
1230
|
Do you want to reset your device and erase all user data from your
|
|
1231
1231
|
device?
|
|
1232
|
+
<ew-text-button
|
|
1233
|
+
slot="actions"
|
|
1234
|
+
@click=${() => {
|
|
1235
|
+
this._state = "DASHBOARD";
|
|
1236
|
+
}}
|
|
1237
|
+
>Back</ew-text-button
|
|
1238
|
+
>
|
|
1232
1239
|
<ew-text-button
|
|
1233
1240
|
class="danger"
|
|
1234
1241
|
slot="actions"
|
|
@@ -1250,9 +1257,6 @@ export class EwtInstallDialog extends LitElement {
|
|
|
1250
1257
|
${this._installErase
|
|
1251
1258
|
? html `<br /><br />All data on the device will be erased.`
|
|
1252
1259
|
: ""}
|
|
1253
|
-
<ew-text-button slot="actions" @click=${this._confirmInstall}
|
|
1254
|
-
>Install</ew-text-button
|
|
1255
|
-
>
|
|
1256
1260
|
<ew-text-button
|
|
1257
1261
|
slot="actions"
|
|
1258
1262
|
@click=${() => {
|
|
@@ -1260,6 +1264,9 @@ export class EwtInstallDialog extends LitElement {
|
|
|
1260
1264
|
}}
|
|
1261
1265
|
>Back</ew-text-button
|
|
1262
1266
|
>
|
|
1267
|
+
<ew-text-button slot="actions" @click=${this._confirmInstall}
|
|
1268
|
+
>Install</ew-text-button
|
|
1269
|
+
>
|
|
1263
1270
|
`;
|
|
1264
1271
|
}
|
|
1265
1272
|
else if (!this._installState ||
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const t=t=>{let e=[192];for(const i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e.push(192),e},e=t=>{const e=[];for(let i=0;i<t.length;i++){const s=t.charCodeAt(i);s<=255&&e.push(s)}return e},i=t=>"["+t.map(t=>s(t)).join(", ")+"]",s=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},a=t=>new Promise(e=>setTimeout(e,t)),r={18:"256KB",19:"512KB",20:"1MB",21:"2MB",22:"4MB",23:"8MB",24:"16MB",25:"32MB",26:"64MB",27:"128MB",28:"256MB",32:"64MB",33:"128MB",34:"256MB",50:"256KB",51:"512KB",52:"1MB",53:"2MB",54:"4MB",55:"8MB",56:"16MB",57:"32MB",58:"64MB"},n=4096,o=115200,h=1610647552,l=1343410176,d=1343312316,c=1<<27,u=1343312312,g=1343312892,f=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),_=33382,p=50,w=12882,m=12883,b=12994,y=12995,S=12997,v=12998,R=207969,B=12914,U=12916,I=12917,C=12928,x=12849,k={5:{name:"ESP32-C3",family:y},9:{name:"ESP32-S3",family:m},12:{name:"ESP32-C2",family:b},13:{name:"ESP32-C6",family:v},16:{name:"ESP32-H2",family:B},18:{name:"ESP32-P4",family:C},20:{name:"ESP32-C61",family:R},23:{name:"ESP32-C5",family:S},25:{name:"ESP32-H21",family:I},28:{name:"ESP32-H4",family:U},32:{name:"ESP32-S31",family:x}},F={4293968129:{name:"ESP8266",family:_},15736195:{name:"ESP32",family:p},1990:{name:"ESP32-S2",family:w}},T=3e3,D=15e4,E=100,O=3e4,M=(t,e)=>{const i=Math.floor(t*(e/486));return i<T?T:i},z=t=>{switch(t){case p:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case w:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case m:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case _:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case b:return{regBase:1610620928,baseFuse:h,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case y:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case S:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case v:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case R:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case B:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case U:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case I:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case C:return{regBase:1342754816,baseFuse:l,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case x:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class $ extends Error{constructor(t){super(t),this.name="SlipReadError"}}const A=async(t,i)=>{let s;if(t==U||t==I||t==x)return null;if(t==p)s=await import("./esp32-BRKoi17y.js");else if(t==w)s=await import("./esp32s2-iX3WoDbg.js");else if(t==m)s=await import("./esp32s3-DGwDVIgz.js");else if(t==_)s=await import("./esp8266-CUwxJpGa.js");else if(t==b)s=await import("./esp32c2-Btgr_lwh.js");else if(t==y)s=await import("./esp32c3-CHKfoI8W.js");else if(t==S)s=await import("./esp32c5-BDW4KtLo.js");else if(t==v)s=await import("./esp32c6-il8tTxAG.js");else if(t==R)s=await import("./esp32c61-thKzxBGf.js");else if(t==B)s=await import("./esp32h2-CxoUHv_P.js");else{if(t!=C)return null;s=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")}return{...s,text:e(atob(s.text)),data:e(atob(s.data))}};function P(t){let e=t.length;for(;--e>=0;)t[e]=0}const W=256,L=286,N=30,H=15,V=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Z=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),G=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),J=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),j=new Array(576);P(j);const q=new Array(60);P(q);const Y=new Array(512);P(Y);const K=new Array(256);P(K);const X=new Array(29);P(X);const Q=new Array(N);function tt(t,e,i,s,a){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=a,this.has_stree=t&&t.length}let et,it,st;function at(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}P(Q);const rt=t=>t<256?Y[t]:Y[256+(t>>>7)],nt=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},ot=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,nt(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},ht=(t,e,i)=>{ot(t,i[2*e],i[2*e+1])},lt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},dt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=H;a++)n=n+i[a-1]<<1,s[a]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=lt(s[e]++,e))}},ct=t=>{let e;for(e=0;e<L;e++)t.dyn_ltree[2*e]=0;for(e=0;e<N;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},ut=t=>{t.bi_valid>8?nt(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},gt=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},ft=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&>(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!gt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},_t=(t,e,i)=>{let s,a,r,n,o=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+o++],s+=(255&t.pending_buf[t.sym_buf+o++])<<8,a=t.pending_buf[t.sym_buf+o++],0===s?ht(t,a,e):(r=K[a],ht(t,r+W+1,e),n=V[r],0!==n&&(a-=X[r],ot(t,a,n)),s--,r=rt(s),ht(t,r,i),n=Z[r],0!==n&&(s-=Q[r],ot(t,s,n)))}while(o<t.sym_next);ht(t,256,e)},pt=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=e.stat_desc.has_stree,r=e.stat_desc.elems;let n,o,h,l=-1;for(t.heap_len=0,t.heap_max=573,n=0;n<r;n++)0!==i[2*n]?(t.heap[++t.heap_len]=l=n,t.depth[n]=0):i[2*n+1]=0;for(;t.heap_len<2;)h=t.heap[++t.heap_len]=l<2?++l:0,i[2*h]=1,t.depth[h]=0,t.opt_len--,a&&(t.static_len-=s[2*h+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)ft(t,i,n);h=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ft(t,i,1),o=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=o,i[2*h]=i[2*n]+i[2*o],t.depth[h]=(t.depth[n]>=t.depth[o]?t.depth[n]:t.depth[o])+1,i[2*n+1]=i[2*o+1]=h,t.heap[1]=h++,ft(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,s=e.max_code,a=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,h=e.stat_desc.max_length;let l,d,c,u,g,f,_=0;for(u=0;u<=H;u++)t.bl_count[u]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)d=t.heap[l],u=i[2*i[2*d+1]+1]+1,u>h&&(u=h,_++),i[2*d+1]=u,d>s||(t.bl_count[u]++,g=0,d>=o&&(g=n[d-o]),f=i[2*d],t.opt_len+=f*(u+g),r&&(t.static_len+=f*(a[2*d+1]+g)));if(0!==_){do{for(u=h-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[h]--,_-=2}while(_>0);for(u=h;0!==u;u--)for(d=t.bl_count[u];0!==d;)c=t.heap[--l],c>s||(i[2*c+1]!==u&&(t.opt_len+=(u-i[2*c+1])*i[2*c],i[2*c+1]=u),d--)}})(t,e),dt(i,l,t.bl_count)},wt=(t,e,i)=>{let s,a,r=-1,n=e[1],o=0,h=7,l=4;for(0===n&&(h=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++o<h&&a===n||(o<l?t.bl_tree[2*a]+=o:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,r=a,0===n?(h=138,l=3):a===n?(h=6,l=3):(h=7,l=4))},mt=(t,e,i)=>{let s,a,r=-1,n=e[1],o=0,h=7,l=4;for(0===n&&(h=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++o<h&&a===n)){if(o<l)do{ht(t,a,t.bl_tree)}while(0!==--o);else 0!==a?(a!==r&&(ht(t,a,t.bl_tree),o--),ht(t,16,t.bl_tree),ot(t,o-3,2)):o<=10?(ht(t,17,t.bl_tree),ot(t,o-3,3)):(ht(t,18,t.bl_tree),ot(t,o-11,7));o=0,r=a,0===n?(h=138,l=3):a===n?(h=6,l=3):(h=7,l=4)}};let bt=!1;const yt=(t,e,i,s)=>{ot(t,0+(s?1:0),3),ut(t),nt(t,i),nt(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var St=(t,e,i,s)=>{let a,r,n=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<W;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),pt(t,t.l_desc),pt(t,t.d_desc),n=(t=>{let e;for(wt(t,t.dyn_ltree,t.l_desc.max_code),wt(t,t.dyn_dtree,t.d_desc.max_code),pt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*J[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=a&&(a=r)):a=r=i+5,i+4<=a&&-1!==e?yt(t,e,i,s):4===t.strategy||r===a?(ot(t,2+(s?1:0),3),_t(t,j,q)):(ot(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(ot(t,e-257,5),ot(t,i-1,5),ot(t,s-4,4),a=0;a<s;a++)ot(t,t.bl_tree[2*J[a]+1],3);mt(t,t.dyn_ltree,e-1),mt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),_t(t,t.dyn_ltree,t.dyn_dtree)),ct(t),s&&ut(t)},vt={_tr_init:t=>{bt||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(X[s]=i,t=0;t<1<<V[s];t++)K[i++]=s;for(K[i-1]=s,a=0,s=0;s<16;s++)for(Q[s]=a,t=0;t<1<<Z[s];t++)Y[a++]=s;for(a>>=7;s<N;s++)for(Q[s]=a<<7,t=0;t<1<<Z[s]-7;t++)Y[256+a++]=s;for(e=0;e<=H;e++)r[e]=0;for(t=0;t<=143;)j[2*t+1]=8,t++,r[8]++;for(;t<=255;)j[2*t+1]=9,t++,r[9]++;for(;t<=279;)j[2*t+1]=7,t++,r[7]++;for(;t<=287;)j[2*t+1]=8,t++,r[8]++;for(dt(j,287,r),t=0;t<N;t++)q[2*t+1]=5,q[2*t]=lt(t,5);et=new tt(j,V,257,L,H),it=new tt(q,Z,0,N,H),st=new tt(new Array(0),G,0,19,7)})(),bt=!0),t.l_desc=new at(t.dyn_ltree,et),t.d_desc=new at(t.dyn_dtree,it),t.bl_desc=new at(t.bl_tree,st),t.bi_buf=0,t.bi_valid=0,ct(t)},_tr_stored_block:yt,_tr_flush_block:St,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(K[i]+W+1)]++,t.dyn_dtree[2*rt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{ot(t,2,3),ht(t,256,j),(t=>{16===t.bi_valid?(nt(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var Rt=(t,e,i,s)=>{let a=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{a=a+e[s++]|0,r=r+a|0}while(--n);a%=65521,r%=65521}return a|r<<16};const Bt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var Ut=(t,e,i,s)=>{const a=Bt,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},It={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Ct={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:xt,_tr_stored_block:kt,_tr_flush_block:Ft,_tr_tally:Tt,_tr_align:Dt}=vt,{Z_NO_FLUSH:Et,Z_PARTIAL_FLUSH:Ot,Z_FULL_FLUSH:Mt,Z_FINISH:zt,Z_BLOCK:$t,Z_OK:At,Z_STREAM_END:Pt,Z_STREAM_ERROR:Wt,Z_DATA_ERROR:Lt,Z_BUF_ERROR:Nt,Z_DEFAULT_COMPRESSION:Ht,Z_FILTERED:Vt,Z_HUFFMAN_ONLY:Zt,Z_RLE:Gt,Z_FIXED:Jt,Z_DEFAULT_STRATEGY:jt,Z_UNKNOWN:qt,Z_DEFLATED:Yt}=Ct,Kt=258,Xt=262,Qt=42,te=113,ee=666,ie=(t,e)=>(t.msg=It[e],e),se=t=>2*t-(t>4?9:0),ae=t=>{let e=t.length;for(;--e>=0;)t[e]=0},re=t=>{let e,i,s,a=t.w_size;e=t.hash_size,s=e;do{i=t.head[--s],t.head[s]=i>=a?i-a:0}while(--e);e=a,s=e;do{i=t.prev[--s],t.prev[s]=i>=a?i-a:0}while(--e)};let ne=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const oe=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},he=(t,e)=>{Ft(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,oe(t.strm)},le=(t,e)=>{t.pending_buf[t.pending++]=e},de=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ce=(t,e,i,s)=>{let a=t.avail_in;return a>s&&(a=s),0===a?0:(t.avail_in-=a,e.set(t.input.subarray(t.next_in,t.next_in+a),i),1===t.state.wrap?t.adler=Rt(t.adler,e,a,i):2===t.state.wrap&&(t.adler=Ut(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},ue=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,o=t.nice_match;const h=t.strstart>t.w_size-Xt?t.strstart-(t.w_size-Xt):0,l=t.window,d=t.w_mask,c=t.prev,u=t.strstart+Kt;let g=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(a>>=2),o>t.lookahead&&(o=t.lookahead);do{if(i=e,l[i+n]===f&&l[i+n-1]===g&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do{}while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<u);if(s=Kt-(u-r),r=u-Kt,s>n){if(t.match_start=e,n=s,s>=o)break;g=l[r+n-1],f=l[r+n]}}}while((e=c[e&d])>h&&0!==--a);return n<=t.lookahead?n:t.lookahead},ge=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Xt)&&(t.window.set(t.window.subarray(e,e+e-s),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),re(t),s+=e),0===t.strm.avail_in)break;if(i=ce(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=ne(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=ne(t,t.ins_h,t.window[a+3-1]),t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Xt&&0!==t.strm.avail_in)},fe=(t,e)=>{let i,s,a,r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n=0,o=t.strm.avail_in;do{if(i=65535,a=t.bi_valid+42>>3,t.strm.avail_out<a)break;if(a=t.strm.avail_out-a,s=t.strstart-t.block_start,i>s+t.strm.avail_in&&(i=s+t.strm.avail_in),i>a&&(i=a),i<r&&(0===i&&e!==zt||e===Et||i!==s+t.strm.avail_in))break;n=e===zt&&i===s+t.strm.avail_in?1:0,kt(t,0,0,n),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,oe(t.strm),s&&(s>i&&(s=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+s),t.strm.next_out),t.strm.next_out+=s,t.strm.avail_out-=s,t.strm.total_out+=s,t.block_start+=s,i-=s),i&&(ce(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(0===n);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==Et&&e!==zt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(a=t.window_size-t.strstart,t.strm.avail_in>a&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(ce(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=r||(s||e===zt)&&e!==Et&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===zt&&0===t.strm.avail_in&&i===s?1:0,kt(t,t.block_start,i,n),t.block_start+=i,oe(t.strm)),n?3:1)},_e=(t,e)=>{let i,s;for(;;){if(t.lookahead<Xt){if(ge(t),t.lookahead<Xt&&e===Et)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Xt&&(t.match_length=ue(t,i)),t.match_length>=3)if(s=Tt(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ne(t,t.ins_h,t.window[t.strstart+1]);else s=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2},pe=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<Xt){if(ge(t),t.lookahead<Xt&&e===Et)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Xt&&(t.match_length=ue(t,i),t.match_length<=5&&(t.strategy===Vt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){a=t.strstart+t.lookahead-3,s=Tt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=a&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,s&&(he(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Tt(t,0,t.window[t.strstart-1]),s&&he(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(s=Tt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2};function we(t,e,i,s,a){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=a}const me=[new we(0,0,0,0,fe),new we(4,4,8,4,_e),new we(4,5,16,8,_e),new we(4,6,32,32,_e),new we(4,4,16,16,pe),new we(8,16,32,32,pe),new we(8,16,128,128,pe),new we(8,32,128,256,pe),new we(32,128,258,1024,pe),new we(32,258,258,4096,pe)];function be(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Yt,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),ae(this.dyn_ltree),ae(this.dyn_dtree),ae(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),ae(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ae(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const ye=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Qt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==te&&e.status!==ee?1:0},Se=t=>{if(ye(t))return ie(t,Wt);t.total_in=t.total_out=0,t.data_type=qt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Qt:te,t.adler=2===e.wrap?0:1,e.last_flush=-2,xt(e),At},ve=t=>{const e=Se(t);var i;return e===At&&((i=t.state).window_size=2*i.w_size,ae(i.head),i.max_lazy_match=me[i.level].max_lazy,i.good_match=me[i.level].good_length,i.nice_match=me[i.level].nice_length,i.max_chain_length=me[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},Re=(t,e,i,s,a,r)=>{if(!t)return Wt;let n=1;if(e===Ht&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==Yt||s<8||s>15||e<0||e>9||r<0||r>Jt||8===s&&1!==n)return ie(t,Wt);8===s&&(s=9);const o=new be;return t.state=o,o.strm=t,o.status=Qt,o.wrap=n,o.gzhead=null,o.w_bits=s,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=a+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<a+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=r,o.method=i,ve(t)};var Be={deflateInit:(t,e)=>Re(t,e,Yt,15,8,jt),deflateInit2:Re,deflateReset:ve,deflateResetKeep:Se,deflateSetHeader:(t,e)=>ye(t)||2!==t.state.wrap?Wt:(t.state.gzhead=e,At),deflate:(t,e)=>{if(ye(t)||e>$t||e<0)return t?ie(t,Wt):Wt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===ee&&e!==zt)return ie(t,0===t.avail_out?Nt:Wt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(oe(t),0===t.avail_out)return i.last_flush=-1,At}else if(0===t.avail_in&&se(e)<=se(s)&&e!==zt)return ie(t,Nt);if(i.status===ee&&0!==t.avail_in)return ie(t,Nt);if(i.status===Qt&&0===i.wrap&&(i.status=te),i.status===Qt){let e=Yt+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=Zt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=s<<6,0!==i.strstart&&(e|=32),e+=31-e%31,de(i,e),0!==i.strstart&&(de(i,t.adler>>>16),de(i,65535&t.adler)),t.adler=1,i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At}if(57===i.status)if(t.adler=0,le(i,31),le(i,139),le(i,8),i.gzhead)le(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),le(i,255&i.gzhead.time),le(i,i.gzhead.time>>8&255),le(i,i.gzhead.time>>16&255),le(i,i.gzhead.time>>24&255),le(i,9===i.level?2:i.strategy>=Zt||i.level<2?4:0),le(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(le(i,255&i.gzhead.extra.length),le(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=Ut(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(le(i,0),le(i,0),le(i,0),le(i,0),le(i,0),le(i,9===i.level?2:i.strategy>=Zt||i.level<2?4:0),le(i,3),i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At;if(69===i.status){if(i.gzhead.extra){let e=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,oe(t),0!==i.pending)return i.last_flush=-1,At;e=0,s-=a}let a=new Uint8Array(i.gzhead.extra);i.pending_buf.set(a.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>e&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),oe(t),0!==i.pending)return i.last_flush=-1,At;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,le(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),oe(t),0!==i.pending)return i.last_flush=-1,At;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,le(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(oe(t),0!==i.pending))return i.last_flush=-1,At;le(i,255&t.adler),le(i,t.adler>>8&255),t.adler=0}if(i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At}if(0!==t.avail_in||0!==i.lookahead||e!==Et&&i.status!==ee){let s=0===i.level?fe(i,e):i.strategy===Zt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(ge(t),0===t.lookahead)){if(e===Et)return 1;break}if(t.match_length=0,i=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Gt?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=Kt){if(ge(t),t.lookahead<=Kt&&e===Et)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=n[a],s===n[++a]&&s===n[++a]&&s===n[++a])){r=t.strstart+Kt;do{}while(s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&a<r);t.match_length=Kt-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Tt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2})(i,e):me[i.level].func(i,e);if(3!==s&&4!==s||(i.status=ee),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),At;if(2===s&&(e===Ot?Dt(i):e!==$t&&(kt(i,0,0,!1),e===Mt&&(ae(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),oe(t),0===t.avail_out))return i.last_flush=-1,At}return e!==zt?At:i.wrap<=0?Pt:(2===i.wrap?(le(i,255&t.adler),le(i,t.adler>>8&255),le(i,t.adler>>16&255),le(i,t.adler>>24&255),le(i,255&t.total_in),le(i,t.total_in>>8&255),le(i,t.total_in>>16&255),le(i,t.total_in>>24&255)):(de(i,t.adler>>>16),de(i,65535&t.adler)),oe(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?At:Pt)},deflateEnd:t=>{if(ye(t))return Wt;const e=t.state.status;return t.state=null,e===te?ie(t,Lt):At},deflateSetDictionary:(t,e)=>{let i=e.length;if(ye(t))return Wt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==Qt||s.lookahead)return Wt;if(1===a&&(t.adler=Rt(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(ae(s.head),s.strstart=0,s.block_start=0,s.insert=0);let t=new Uint8Array(s.w_size);t.set(e.subarray(i-s.w_size,i),0),e=t,i=s.w_size}const r=t.avail_in,n=t.next_in,o=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,ge(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=ne(s,s.ins_h,s.window[t+3-1]),s.prev[t&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=t,t++}while(--e);s.strstart=t,s.lookahead=2,ge(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,t.next_in=n,t.input=o,t.avail_in=r,s.wrap=a,At},deflateInfo:"pako deflate (from Nodeca project)"};const Ue=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ie=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)Ue(i,e)&&(t[e]=i[e])}}return t},Ce=t=>{let e=0;for(let i=0,s=t.length;i<s;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,s=0,a=t.length;e<a;e++){let a=t[e];i.set(a,s),s+=a.length}return i};let xe=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){xe=!1}const ke=new Uint8Array(256);for(let t=0;t<256;t++)ke[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;ke[254]=ke[254]=1;var Fe=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,o=0;for(a=0;a<n;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(o),r=0,a=0;r<o;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),i<128?e[r++]=i:i<2048?(e[r++]=192|i>>>6,e[r++]=128|63&i):i<65536?(e[r++]=224|i>>>12,e[r++]=128|i>>>6&63,e[r++]=128|63&i):(e[r++]=240|i>>>18,e[r++]=128|i>>>12&63,e[r++]=128|i>>>6&63,e[r++]=128|63&i);return e};var Te=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const De=Object.prototype.toString,{Z_NO_FLUSH:Ee,Z_SYNC_FLUSH:Oe,Z_FULL_FLUSH:Me,Z_FINISH:ze,Z_OK:$e,Z_STREAM_END:Ae,Z_DEFAULT_COMPRESSION:Pe,Z_DEFAULT_STRATEGY:We,Z_DEFLATED:Le}=Ct;function Ne(t){this.options=Ie({level:Pe,method:Le,chunkSize:16384,windowBits:15,memLevel:8,strategy:We},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Te,this.strm.avail_out=0;let i=Be.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==$e)throw new Error(It[i]);if(e.header&&Be.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Fe(e.dictionary):"[object ArrayBuffer]"===De.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=Be.deflateSetDictionary(this.strm,t),i!==$e)throw new Error(It[i]);this._dict_set=!0}}Ne.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?ze:Ee,"string"==typeof t?i.input=Fe(t):"[object ArrayBuffer]"===De.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),(r===Oe||r===Me)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=Be.deflate(i,r),a===Ae)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=Be.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===$e;if(0!==i.avail_out){if(r>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},Ne.prototype.onData=function(t){this.chunks.push(t)},Ne.prototype.onEnd=function(t){t===$e&&(this.result=Ce(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var He={deflate:function(t,e){const i=new Ne(e);if(i.push(t,!0),i.err)throw i.msg||It[i.err];return i.result}};const{deflate:Ve}=He;var Ze=Ve;const Ge={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},Je=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(r(t[s],e[i]),i++);function r(t,e){if(!(t in Ge))throw"Unhandled character '"+t+"' in pack format";const i=Ge[t].bytes,r=new DataView(new ArrayBuffer(i));Ge[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},je=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:r(e);function r(t){if(!(t in Ge))throw"Unhandled character '"+t+"' in unpack format";const r=Ge[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const o=Ge[t].u.bind(n);s.push(o(0,a)),i+=r}return s};class qe extends EventTarget{get isUsbJtagOrOtg(){return this._parent?this._parent._isUsbJtagOrOtg:this._isUsbJtagOrOtg}constructor(t,e,i){super(),this.port=t,this.logger=e,this._parent=i,this.__chipName=null,this.__chipRevision=null,this.__chipVariant=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null,this.currentBaudRate=o,this.SLIP_END=192,this.SLIP_ESC=219,this.SLIP_ESC_END=220,this.SLIP_ESC_ESC=221,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.__commandLock=Promise.resolve([0,[]]),this.__isReconfiguring=!1,this.__abandonCurrentOperation=!1,this._suppressDisconnect=!1,this.__consoleMode=!1,this._isUsbJtagOrOtg=void 0,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.state_RTS=!1,this.__writeChain=Promise.resolve()}get chipFamily(){return this._parent?this._parent.chipFamily:this.__chipFamily}set chipFamily(t){this._parent?this._parent.chipFamily=t:this.__chipFamily=t}get chipName(){return this._parent?this._parent.chipName:this.__chipName}set chipName(t){this._parent?this._parent.chipName=t:this.__chipName=t}get chipRevision(){return this._parent?this._parent.chipRevision:this.__chipRevision}set chipRevision(t){this._parent?this._parent.chipRevision=t:this.__chipRevision=t}get chipVariant(){return this._parent?this._parent.chipVariant:this.__chipVariant}set chipVariant(t){this._parent?this._parent.chipVariant=t:this.__chipVariant=t}get _consoleMode(){return this._parent?this._parent._consoleMode:this.__consoleMode}set _consoleMode(t){this._parent?this._parent._consoleMode=t:this.__consoleMode=t}setConsoleMode(t){this._consoleMode=t}get _inputBuffer(){if(this._parent)return this._parent._inputBuffer;if(void 0===this.__inputBuffer)throw new Error("_inputBuffer accessed before initialization");return this.__inputBuffer}get _inputBufferReadIndex(){return this._parent?this._parent._inputBufferReadIndex:this.__inputBufferReadIndex||0}set _inputBufferReadIndex(t){this._parent?this._parent._inputBufferReadIndex=t:this.__inputBufferReadIndex=t}get _inputBufferAvailable(){return this._inputBuffer.length-this._inputBufferReadIndex}_readByte(){if(!(this._inputBufferReadIndex>=this._inputBuffer.length))return this._inputBuffer[this._inputBufferReadIndex++]}_clearInputBuffer(){this._inputBuffer.length=0,this._inputBufferReadIndex=0}_compactInputBuffer(){this._inputBufferReadIndex>1e3&&this._inputBufferReadIndex>this._inputBuffer.length/2&&(this._inputBuffer.splice(0,this._inputBufferReadIndex),this._inputBufferReadIndex=0)}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}get _commandLock(){return this._parent?this._parent._commandLock:this.__commandLock}set _commandLock(t){this._parent?this._parent._commandLock=t:this.__commandLock=t}get _isReconfiguring(){return this._parent?this._parent._isReconfiguring:this.__isReconfiguring}set _isReconfiguring(t){this._parent?this._parent._isReconfiguring=t:this.__isReconfiguring=t}get _abandonCurrentOperation(){return this._parent?this._parent._abandonCurrentOperation:this.__abandonCurrentOperation}set _abandonCurrentOperation(t){this._parent?this._parent._abandonCurrentOperation=t:this.__abandonCurrentOperation=t}get _adaptiveBlockMultiplier(){return this._parent?this._parent._adaptiveBlockMultiplier:this.__adaptiveBlockMultiplier}set _adaptiveBlockMultiplier(t){this._parent?this._parent._adaptiveBlockMultiplier=t:this.__adaptiveBlockMultiplier=t}get _adaptiveMaxInFlightMultiplier(){return this._parent?this._parent._adaptiveMaxInFlightMultiplier:this.__adaptiveMaxInFlightMultiplier}set _adaptiveMaxInFlightMultiplier(t){this._parent?this._parent._adaptiveMaxInFlightMultiplier=t:this.__adaptiveMaxInFlightMultiplier=t}get _consecutiveSuccessfulChunks(){return this._parent?this._parent._consecutiveSuccessfulChunks:this.__consecutiveSuccessfulChunks}set _consecutiveSuccessfulChunks(t){this._parent?this._parent._consecutiveSuccessfulChunks=t:this.__consecutiveSuccessfulChunks=t}get _lastAdaptiveAdjustment(){return this._parent?this._parent._lastAdaptiveAdjustment:this.__lastAdaptiveAdjustment}set _lastAdaptiveAdjustment(t){this._parent?this._parent._lastAdaptiveAdjustment=t:this.__lastAdaptiveAdjustment=t}get _isCDCDevice(){return this._parent?this._parent._isCDCDevice:this.__isCDCDevice}set _isCDCDevice(t){this._parent?this._parent._isCDCDevice=t:this.__isCDCDevice=t}detectUSBSerialChip(t,e){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},18:{name:"ESP32-P4 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0;const t=this.port.getInfo();if(t.usbVendorId&&t.usbProductId){const e=this.detectUSBSerialChip(t.usbVendorId,t.usbProductId);this.logger.log(`USB-Serial: ${e.name} (VID: 0x${t.usbVendorId.toString(16)}, PID: 0x${t.usbProductId.toString(16)})`),e.maxBaudrate&&(this._maxUSBSerialBaudrate=e.maxBaudrate,this.logger.log(`Max baudrate: ${e.maxBaudrate}`)),12346===t.usbVendorId&&2===t.usbProductId&&(this._isESP32S2NativeUSB=!0),(12346===t.usbVendorId||6790===t.usbVendorId&&21971===t.usbProductId)&&(this._isCDCDevice=!0)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip(),this.chipFamily===C&&301===this.chipRevision&&await this.powerOnFlash();try{this._isUsbJtagOrOtg=await this.detectUsbConnectionType(),this.logger.debug("USB connection type: "+(this._isUsbJtagOrOtg?"USB-JTAG/OTG":"External Serial Chip"))}catch(t){this.logger.debug(`Could not detect USB connection type: ${t}`)}const t=z(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=k[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===C?(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)):this.chipFamily===y&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-C3 revision: ${this.chipRevision}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._clearInputBuffer(),await a(E);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=F[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${s(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===C?(this.chipRevision=await this.getChipRevision(),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)):this.chipFamily===y&&(this.chipRevision=await this.getChipRevision()),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily===C){const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}return this.chipFamily===y?await this.getChipRevisionC3():0}async powerOnFlash(){if(this.chipFamily!==C)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await a(10);const t=await this.readRegister(d);await this.writeRegister(d,t|c);const e=await this.readRegister(u);await this.writeRegister(u,128|e);const i=await this.readRegister(g);await this.writeRegister(g,3|i),await a(.05);const s=await this.readRegister(d);await this.writeRegister(d,-134217729&s);const r=await this.readRegister(u);await this.writeRegister(u,-2139095041&r);const n=await this.readRegister(u);await this.writeRegister(u,128|n);const o=await this.readRegister(u);await this.writeRegister(u,-129&o),await a(2),this.logger.debug("Flash powered on successfully")}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:je("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?je("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?je("<I",t.slice(16,20))[0]:0}}async getMacAddress(){if(!this._initializationSucceeded)throw new Error("getMacAddress() requires initialize() to have completed successfully");return this.macAddr().map(t=>t.toString(16).padStart(2,"0").toUpperCase()).join(":")}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{}finally{if(this._isReconfiguring=!1,this._reader){try{this._reader.releaseLock(),this.logger.debug("Reader released in readLoop cleanup")}catch(t){this.logger.debug(`Reader release error in readLoop: ${t}`)}this._reader=void 0}}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this._suppressDisconnect||this.dispatchEvent(new Event("disconnect")),this._suppressDisconnect=!1,this.logger.debug("Finished read loop")}sleep(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async setDTRandRTS(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async runSignalSequence(t){const e=!0===this.port.isWebUSB;for(const i of t)void 0!==i.dtr&&void 0!==i.rts?e?await this.setDTRandRTSWebUSB(i.dtr,i.rts):await this.setDTRandRTS(i.dtr,i.rts):(void 0!==i.dtr&&(e?await this.setDTRWebUSB(i.dtr):await this.setDTR(i.dtr)),void 0!==i.rts&&(e?await this.setRTSWebUSB(i.rts):await this.setRTS(i.rts))),i.delayMs&&await a(i.delayMs)}async hardResetUSBJTAGSerial(){await this.runSignalSequence([{rts:!1},{dtr:!1,delayMs:100},{dtr:!0,rts:!1,delayMs:100},{rts:!0},{dtr:!1,rts:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:200}])}async hardResetClassic(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:50},{dtr:!1,delayMs:200}])}async hardResetToFirmware(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:100},{rts:!1,delayMs:50},{delayMs:200}])}async hardResetUnixTight(){await this.runSignalSequence([{dtr:!0,rts:!0},{dtr:!1,rts:!1},{dtr:!1,rts:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:50},{dtr:!1,rts:!1},{dtr:!1,delayMs:200}])}async setRTSWebUSB(t){this.state_RTS=t,await this.port.setSignals({requestToSend:t,dataTerminalReady:this.state_DTR})}async setDTRWebUSB(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:this.state_RTS})}async setDTRandRTSWebUSB(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.runSignalSequence([{rts:!1,dtr:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:100},{rts:!0,dtr:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:200}])}async hardResetClassicLongDelayWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:500},{dtr:!0,rts:!1,delayMs:200},{dtr:!1,delayMs:500}])}async hardResetClassicShortDelayWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:50},{dtr:!0,rts:!1,delayMs:25},{dtr:!1,delayMs:100}])}async hardResetInvertedWebUSB(){await this.runSignalSequence([{dtr:!0,rts:!1,delayMs:100},{dtr:!1,rts:!0,delayMs:50},{dtr:!0,delayMs:200}])}async hardResetInvertedDTRWebUSB(){await this.runSignalSequence([{dtr:!0,rts:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:50},{dtr:!0,delayMs:200}])}async hardResetInvertedRTSWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!1,delayMs:100},{dtr:!0,rts:!0,delayMs:50},{dtr:!1,delayMs:200}])}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,s=[],r=this,n=!e&&!i;if(this.isWebUSB()){const a=4292===t.usbVendorId,o=6790===t.usbVendorId,h=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(h?(s.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async()=>await r.hardResetUSBJTAGSerial()}),s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async()=>await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async()=>await r.hardResetClassic()})):(s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async()=>await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"USB-JTAG/Serial (WebUSB)",fn:async()=>await r.hardResetUSBJTAGSerial()}),s.push({name:"Inverted DTR Classic (WebUSB)",fn:async()=>await r.hardResetInvertedDTRWebUSB()}))),n&&(o?(s.push({name:"UnixTight (WebUSB) - CH34x",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CH34x",fn:async()=>await r.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedDTRWebUSB()})):a?(s.push({name:"UnixTight (WebUSB) - CP2102",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CP2102",fn:async()=>await r.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedDTRWebUSB()})):(s.push({name:"UnixTight (WebUSB)",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassic()}}),s.push({name:"Inverted Both (WebUSB)",fn:async function(){return await r.hardResetInvertedWebUSB()}}),s.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),s.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),a||h||(6790!==t.usbVendorId&&s.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassic()}}),s.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTight()}}),s.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await r.hardResetClassicLongDelayWebUSB()}}),s.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await r.hardResetClassicShortDelayWebUSB()}}),e||i||s.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerial()}}))}else(e||i)&&s.push({name:"USB-JTAG/Serial",fn:async function(){return await r.hardResetUSBJTAGSerial()}}),s.push({name:"UnixTight",fn:async function(){return await r.hardResetUnixTight()}}),e||i||s.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await r.hardResetUSBJTAGSerial()}});let o=null;for(const t of s)try{if(!this.connected||!this.port.writable){this.logger.debug(`Port disconnected, skipping ${t.name} reset`);continue}if(this._abandonCurrentOperation=!1,await t.fn(),n){if(await this.syncWithTimeout(2e3))return void this.logger.log(`Connected USB Serial successfully with ${t.name} reset.`);throw new Error("Sync timeout or abandoned")}{const e=this.sync(),i=new Promise((t,e)=>setTimeout(()=>e(new Error("Sync timeout")),1e3));try{return await Promise.race([e,i]),void this.logger.log(`Connected CDC/JTAG successfully with ${t.name} reset.`)}catch(t){throw new Error("Sync timeout or abandoned")}}}catch(t){if(o=t,this._abandonCurrentOperation=!0,await a(100),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._clearInputBuffer(),await this.drainInputBuffer(200),await this.flushSerialBuffers()}throw this._abandonCurrentOperation=!1,new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${null==o?void 0:o.message}`)}async watchdogReset(){await this.rtcWdtResetChipSpecific()}async getChipRevisionC3(){if(this.chipFamily!==y)return 0;const t=await this.readRegister(1610647632)>>18&7;return(await this.readRegister(1610647640)>>23&7)<<3|t}async rtcWdtResetChipSpecific(){let t,e,i,s;if(this.logger.debug("Hard resetting with watchdog timer..."),this.chipFamily===w)t=1061191852,e=1061191828,i=1061191832,s=1356348065;else if(this.chipFamily===m)t=1610645680,e=1610645656,i=1610645660,s=1356348065;else if(this.chipFamily===y)t=1610645672,e=1610645648,i=1610645652,s=1356348065;else if(this.chipFamily===S||this.chipFamily===v)t=1611340824,e=1611340800,i=1611340804,s=1356348065;else{if(this.chipFamily!==C)throw new Error(`rtcWdtResetChipSpecific() is not supported for ${this.chipFamily}`);t=1343315992,e=1343315968,i=1343315972,s=1356348065}await this.writeRegister(t,s,void 0,0),await this.writeRegister(i,2e3,void 0,0);await this.writeRegister(e,-805306110,void 0,0),await this.writeRegister(t,0,void 0,0),await this.sleep(500)}async tryUsbWdtReset(t){return await this.detectUsbConnectionType()?(await this.rtcWdtResetChipSpecific(),this.logger.debug(`${t}: RTC WDT reset (USB-JTAG/Serial or USB-OTG detected)`),!0):(await this.hardResetClassic(),this.logger.debug("Classic reset."),!1)}async hardReset(t=!1){if(this._consoleMode)return t?void this.logger.debug("Skipping bootloader reset - device is in console mode"):(this.logger.debug("Performing hardware reset (console mode)..."),await this.hardResetToFirmware(),void this.logger.debug("Hardware reset complete"));if(t)4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.debug("USB-JTAG/Serial reset.")):(await this.hardResetClassic(),this.logger.debug("Classic reset."));else{if(this.logger.debug("*** Performing WDT reset strategy ***"),this.chipFamily===w){if(await this.tryUsbWdtReset("ESP32-S2"))return}else if(this.chipFamily===C){if(await this.tryUsbWdtReset("ESP32-P4"))return}else if(this.chipFamily===S){if(await this.tryUsbWdtReset("ESP32-C5"))return}else if(this.chipFamily===v){if(await this.tryUsbWdtReset("ESP32-C6"))return}this.isWebUSB()?(await this.setRTSWebUSB(!0),await this.sleep(200),await this.setRTSWebUSB(!1),await this.sleep(200),this.logger.debug("Hard reset (WebUSB).")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.debug("Hard reset."))}await new Promise(t=>setTimeout(t,1e3))}macAddr(){const t=new Array(6).fill(0),e=this._efuses[0],i=this._efuses[1],s=this._efuses[2],a=this._efuses[3];let r;if(this.chipFamily==_){if(0!=a)r=[a>>16&255,a>>8&255,255&a];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");r=[172,208,116]}else r=[24,254,52];t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==p)t[0]=s>>8&255,t[1]=255&s,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=v&&this.chipFamily!=R&&this.chipFamily!=B&&this.chipFamily!=U&&this.chipFamily!=I&&this.chipFamily!=C&&this.chipFamily!=x)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=e>>24&255,t[3]=e>>16&255,t[4]=e>>8&255,t[5]=255&e}return t}async readRegister(t){this.debug&&this.logger.debug("Reading from Register "+s(t,8));const e=Je("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){const r=async()=>{a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,a);if(null===n)throw new Error("Didn't get enough status bytes");let o=n,h=0;if(this.IS_STUB||this.chipFamily==_?h=2:[p,w,m,b,y,S,v,R,B,U,I,C,x].includes(this.chipFamily)||20===t?h=4:[2,4].includes(o.length)?h=o.length:(h=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${s(t)}, data.length: ${o.length})`)),o.length<h)throw new Error("Didn't get enough status bytes");const l=o.slice(-h,o.length);if(o=o.slice(0,-h),this.debug&&(this.logger.debug("status",l),this.logger.debug("value",r),this.logger.debug("data",o)),1==l[0])throw 5==l[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+s(t))):new Error("Command failure error code "+s(l[1]));return[r,o]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...Je("<BBHI",0,e,i.length,s),...i]);this.debug&&this.logger.debug(`Writing ${a.length} byte${1==a.length?"":"s"}:`,a),await this.writeToStream(a)}async readPacket(t){let e=null,r=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new $("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){if(Date.now()-n>t){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}const a=this._readByte();if(null===e){if(a!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(a)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid head of packet ("+s(a)+")");e=[]}else if(r)if(r=!1,a==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(a!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(a)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid SLIP escape (0xdb, "+s(a)+")");e.push(this.SLIP_ESC)}else if(a==this.SLIP_ESC)r=!0;else{if(a==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(a)}}else await a(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new $("Operation abandoned (reset strategy timeout)");const o=Date.now();for(n=[];Date.now()-o<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await a(1)}if(0==n.length){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+i(n));for(const t of n)if(null===e){if(t!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid head of packet ("+s(t)+")");e=[]}else if(r)if(r=!1,t==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(t!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid SLIP escape (0xdb, "+s(t)+")");e.push(this.SLIP_ESC)}else if(t==this.SLIP_ESC)r=!0;else{if(t==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}}}async getResponse(t,e=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(e);if(i.length<8)continue;const[a,r,,n]=je("<BBHI",i.slice(0,8));if(1!=a)continue;const o=i.slice(8);if(null==t||r==t)return[n,o];if(0!=o[0]&&5==o[1])throw await this.drainInputBuffer(200),new Error(`Invalid (unsupported) command ${s(t)}`)}throw new Error("Response doesn't match request")}checksum(t,e=239){for(const i of t)e^=i;return e}async getC5CrystalFreqRomExpect(){return(2130706432&await this.readRegister(1611227408))>>>24}async getC5CrystalFreqDetected(){const t=1048575&await this.readRegister(1610612756),e=o*t/1e6;return e>45?48:e>33?40:26}async setBaudrateC5Rom(t){const e=await this.getC5CrystalFreqRomExpect(),i=await this.getC5CrystalFreqDetected();this.logger.log(`ROM expects crystal freq: ${e} MHz, detected ${i} MHz.`);let s=t;48===i&&40===e?s=Math.trunc(40*t/48):40===i&&48===e&&(s=Math.trunc(48*t/40)),this.logger.log(`Changing baud rate to ${s}...`);try{const t=Je("<II",s,0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${s}: No response from set baud rate command.`)}this.logger.log("Changed.")}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==S)try{const e=Je("<II",t,this.IS_STUB?o:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}else await this.setBaudrateC5Rom(t);this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(E),this._parent?this._parent.currentBaudRate=t:this.currentBaudRate=t;const i=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;i&&t>i&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${i})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;this._isReconfiguring=!0;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this.isWebUSB()){const e=this.port.getInfo(),i=6790===e.usbVendorId&&21971===e.usbProductId;if(!i&&"function"==typeof this.port.setBaudRate)return await this.port.setBaudRate(t),void await a(100)}if(this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconfigure: ${t}`)}this._writer=void 0}await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(t){}finally{this._isReconfiguring=!1}}async syncWithTimeout(t){const e=Date.now();for(let i=0;i<5;i++){if(Date.now()-e>t)return!1;if(this._abandonCurrentOperation)return!1;this._clearInputBuffer();try{if(await this._sync())return await a(E),!0}catch(t){if(this._abandonCurrentOperation)return!1}await a(E)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await a(E),!0;await a(E)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,f);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,E);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){this.debug&&this.logger.debug(`Sync attempt ${t+1} failed: ${e}`)}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,a=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],a=e[2],r=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(r)}`)}const r=t.byteLength;let n,o=0,h=T;a?(n=Ze(new Uint8Array(t),{level:9}).buffer,o=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${o}`),h=await this.flashDeflBegin(r,o,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],d=0,c=0,u=0;const g=Date.now(),f=this.getFlashWriteSize(),_=a?o:r;for(;_-u>0;)this.debug&&this.logger.log(`Writing at ${s(i+d*f,8)} `),_-u>=f?l=Array.from(new Uint8Array(n,u,f)):(l=Array.from(new Uint8Array(n,u,_-u)),a||(l=l.concat(new Array(f-l.length).fill(255)))),a?await this.flashDeflBlock(l,d,h):await this.flashBlock(l,d),d+=1,c+=a?Math.round(l.length*r/o):l.length,u+=f,e(Math.min(c,r),r);this.logger.log("Took "+(Date.now()-g)+"ms to write "+_+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),a?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[p,w,m,b,y,S,v,R,B,U,I,C,x].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=_||this.IS_STUB?t:this.getEraseSize(e,t);const o=this.IS_STUB?T:M(O,t),h=Date.now();let l=Je("<IIII",a,n,r,e);return this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=v&&this.chipFamily!=R&&this.chipFamily!=B&&this.chipFamily!=U&&this.chipFamily!=I&&this.chipFamily!=C&&this.chipFamily!=x||(l=l.concat(Je("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+n+", block size "+s(r,4)+", offset "+s(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,l,0,o),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-h)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(t=0,e=0,i=0){const s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),r=Math.floor((t+s-1)/s);let n=0,o=0;this.IS_STUB?(n=t,o=M(O,n)):(n=r*s,o=T);const h=Je("<IIII",n,a,s,i);return await this.checkCommand(16,h,0,o),o}async flashFinish(){const t=Je("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=Je("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return z(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(t,e,i=4294967295,s=0,a=0){let r=Je("<IIII",t,e,i,s);a>0&&(r=r.concat(Je("<IIII",z(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const s=t.regBase+t.mosiDlenOffs,a=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(s,e-1),i>0&&await this.writeRegister(a,i-1)}else{const s=t.regBase+t.usr1Offs,a=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(s,a)}}async waitDone(t,e){for(let i=0;i<10;i++){if(0==(await this.readRegister(t)&e))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(t,e,i=0){const a=z(this.getChipFamily()),r=a.regBase,n=r,o=r+a.usrOffs,h=r+a.usr2Offs,l=r+a.w0Offs,d=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(e.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const c=8*e.length,u=await this.readRegister(o),g=await this.readRegister(h);let f=1<<31;if(i>0&&(f|=268435456),c>0&&(f|=134217728),await this.setDataLengths(a,c,i),await this.writeRegister(o,f),await this.writeRegister(h,7<<28|t),0==c)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=je("I".repeat(Math.floor(e.length/4)),e);let a=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${s(t)} to register offset ${s(a)}`),await this.writeRegister(a,t),a+=4}await this.writeRegister(n,d),await this.waitDone(n,d);const _=await this.readRegister(l);return await this.writeRegister(o,u),await this.writeRegister(h,g),_}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${s(t)}`),this.logger.log(`Flash Manufacturer: ${e.toString(16)}`),this.logger.log(`Flash Device: ${(t>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=r[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=n,s=Math.floor((e+i-1)/i);let a=16-Math.floor(t/i)%16;return s<a&&(a=s),s<2*a?Math.floor((s+1)/2*i):(s-a)*i}async memBegin(t,e,i,s){return await this.checkCommand(5,Je("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?T:500,i=Je("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){this.logger.debug(`Loading stub for ${this.chipName}, revision: ${this.chipRevision}`);const e=await A(this.chipFamily,this.chipRevision);if(null===e)return this.logger.log(`Stub flasher is not yet supported on ${this.chipName}, using ROM loader`),this;const i=2048;this.logger.log("Uploading stub...");for(const t of["text","data"]){const s=e[t],a=e[`${t}_start`],r=s.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,a);for(const t of Array(n).keys()){const e=t*i;let a=e+i;a>r&&(a=r),await this.memBlock(s.slice(e,a),t)}}await this.memFinish(e.entry);const s=await this.readPacket(500),a=String.fromCharCode(...s);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");const r=new Ye(this.port,this.logger,this);return t||await r.detectFlashSize(),r}get _reader(){return this._parent?this._parent._reader:this.__reader}set _reader(t){this._parent?this._parent._reader=t:this.__reader=t}get _writer(){return this._parent?this._parent._writer:this.__writer}set _writer(t){this._parent?this._parent._writer=t:this.__writer=t}get _writeChain(){return this._parent?this._parent._writeChain:this.__writeChain}set _writeChain(t){this._parent?this._parent._writeChain=t:this.__writeChain=t}async writeToStream(t){if(this.port.writable){if(this._isReconfiguring)throw new Error("Cannot write during port reconfiguration");this._writeChain=this._writeChain.then(async()=>{if(!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.error(`Failed to get writer: ${t}`),t}await this._writer.write(new Uint8Array(t))},async()=>{if(this.logger.debug("Previous write failed, attempting recovery for current write"),!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.debug(`Failed to get writer in recovery: ${t}`),new Error("Cannot acquire writer lock")}await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch{}this._writer=void 0}throw t}),await this._writeChain}else this.logger.debug("Port writable stream not available, skipping write")}async getUsbMode(){var t,e;const i=this._parent?this._parent.chipFamily:this.chipFamily,s=this._parent?null!==(t=this._parent.chipRevision)&&void 0!==t?t:0:null!==(e=this.chipRevision)&&void 0!==e?e:0;let a=null,r=null,n=null;switch(i){case w:a=1073741076,n=2;break;case m:a=1070526796,r=4,n=3;break;case y:a=(s<101?1070461028:1070461024)+24,r=3;break;case S:a=1082520852,r=3;break;case v:a=1082652032,r=3;break;case R:a=s<=200?1082455532:1082455524,r=s<=200?3:4;break;case B:a=1082457852,r=3;break;case U:a=1082652032,r=3;break;case C:a=s<300?1341390536:1341914824,r=6,n=5}if(null===a)return{mode:"uart",uartNo:0};const o=255&await this.readRegister(a);return null!==n&&o===n?(this.logger.debug(`USB mode: USB-OTG (uartNo=${o})`),{mode:"usb-otg",uartNo:o}):null!==r&&o===r?(this.logger.debug(`USB mode: USB-JTAG/Serial (uartNo=${o})`),{mode:"usb-jtag-serial",uartNo:o}):(this.logger.debug(`USB mode: UART (uartNo=${o})`),{mode:"uart",uartNo:o})}async disconnect(){if(this._parent)await this._parent.disconnect();else if(this.port.writable){try{await this._writeChain}catch(t){}if(this._writer){try{await this._writer.close(),this._writer.releaseLock()}catch(t){}this._writer=void 0}else try{const t=this.port.writable.getWriter();await t.close(),t.releaseLock()}catch(t){}await new Promise(t=>{if(!this._reader)return void t(void 0);const e=setTimeout(()=>{this.logger.debug("Disconnect timeout - forcing resolution"),t(void 0)},1e3);this.addEventListener("disconnect",()=>{clearTimeout(e),t(void 0)},{once:!0});try{this._reader.cancel()}catch(i){clearTimeout(e),t(void 0)}}),this.connected=!1;try{await this.port.close(),this.logger.debug("Port closed successfully")}catch(t){this.logger.debug(`Port close error: ${t}`)}}}async releaseReaderWriter(){if(this._parent)await this._parent.releaseReaderWriter();else{try{await this._writeChain}catch(t){}if(this._writer){try{this._writer.releaseLock(),this.logger.debug("Writer released")}catch(t){this.logger.debug(`Writer release error: ${t}`)}this._writer=void 0}if(this._reader){const t=this._reader;try{this._suppressDisconnect=!0,await t.cancel(),this.logger.debug("Reader cancelled")}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}finally{try{t.releaseLock()}catch(t){this.logger.debug(`Reader release error: ${t}`)}}this._reader===t&&(this._reader=void 0)}}}async resetToFirmware(){return await this._resetToFirmwareIfNeeded()}async detectUsbConnectionType(){const t=this.port.getInfo(),e=t.usbProductId;if(!(12346===t.usbVendorId))return this.logger.debug("Not Espressif VID - external serial chip"),!1;const i=[2,18,4097].includes(e||0);return this.logger.debug(`USB-JTAG/OTG detection: ${i?"YES":"NO"} (PID=0x${null==e?void 0:e.toString(16)})`),i}async enterConsoleMode(){if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - port selection needed"),!0;let t;try{t=await this.detectUsbConnectionType(),this.logger.debug("USB connection type detected: "+(t?"USB-JTAG/OTG":"External Serial Chip")),this._isUsbJtagOrOtg=t}catch(e){if(void 0===this.isUsbJtagOrOtg)throw new Error(`Cannot enter console mode: USB connection type unknown and detection failed: ${e}`);this._consoleMode=!1,this.logger.debug(`USB detection failed, using cached value: ${this.isUsbJtagOrOtg}`),t=this.isUsbJtagOrOtg}if(t){return await this._resetToFirmwareIfNeeded()}try{await this.releaseReaderWriter(),await this.sleep(100)}catch(t){this.logger.debug(`Failed to release locks: ${t}`)}try{await this.hardReset(!1),this.logger.log("Device reset to firmware mode")}catch(t){this.logger.debug(`Could not reset device: ${t}`)}if(this.isWebUSB())try{await this.port.recreateStreams(),this.logger.debug("WebUSB streams recreated for console mode")}catch(t){this._consoleMode=!1,this.logger.debug(`Failed to recreate WebUSB streams: ${t}`)}return this._consoleMode=!0,!1}async _clearForceDownloadBootIfNeeded(){try{let t,e,i;if(this.chipFamily===w)t=1061191976,e=1,i="ESP32-S2";else if(this.chipFamily===m)t=1610645804,e=1,i="ESP32-S3";else{if(this.chipFamily!==C)return!1;t=1343291400,e=4,i="ESP32-P4"}const s=await this.readRegister(t);this.logger.debug(`${i} force download boot register: 0x${s.toString(16)} (mask: 0x${e.toString(16)})`);return 0!==(s&e)?(this.logger.debug(`${i} force download boot flag is SET - clearing it`),await this.writeRegister(t,0,e,0),this.logger.debug(`${i} force download boot flag cleared`),!0):(this.logger.debug(`${i} force download boot flag is already CLEAR - no action needed`),!1)}catch(t){return this.logger.debug(`Error checking/clearing force download flag: ${t}`),!1}}async _resetToFirmwareIfNeeded(){try{if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - assuming device is already in firmware mode"),!1;const t=await this.detectUsbConnectionType();if(t){if(this.IS_STUB){if(this.logger.debug("On stub - need to get back to ROM to check flag"),this.currentBaudRate!==o){this.logger.debug(`Changing baudrate from ${this.currentBaudRate} to 115200 for ROM`);try{await this.reconfigurePort(o),this.currentBaudRate=o}catch(t){this.logger.debug(`Baudrate change failed: ${t}`)}}this.logger.debug("Resetting to bootloader (ROM)...");try{await this.hardReset(!0),await a(200),await this.sync(),this.logger.debug("Now on ROM after reset"),this.IS_STUB=!1}catch(t){return this.logger.debug(`Reset to ROM failed: ${t}`),this.logger.debug("Assuming device is already in firmware mode"),await this.releaseReaderWriter(),!1}}else this.logger.debug("Already on ROM - checking force download flag");await this._clearForceDownloadBootIfNeeded()?this.logger.debug("Force download flag was cleared - device will boot to firmware after reset"):this.logger.debug("Force download flag already clear - device will boot to firmware after reset"),await this.hardReset(!1);return this.chipFamily===w&&t||this.chipFamily===C&&t?(await this.releaseReaderWriter(),this.logger.log(`${this.chipName} USB-OTG: Port will change after WDT reset`),this.logger.log("Please select the new port for console mode"),this.dispatchEvent(new CustomEvent("usb-otg-port-change",{detail:{chipName:this.chipName,message:`${this.chipName} USB port changed after reset. Please select the new port.`,reason:"wdt-reset-to-firmware"}})),!0):(await this.releaseReaderWriter(),!1)}}catch(t){this.logger.debug(`Could not reset device to firmware mode: ${t}`)}return!1}async reconnect(){if(this._parent)await this._parent.reconnect();else try{this.logger.log("Reconnecting serial port...");const t=this.currentBaudRate;this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.debug("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:o}),this.connected=!0,this.currentBaudRate=o}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1;const e=this.chipFamily,i=this.chipName,s=this.chipRevision,a=this.chipVariant,r=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=e,this.chipName=i,this.chipRevision=s,this.chipVariant=a,this.flashSize=r,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");this.chipFamily===C&&301===this.chipRevision&&await this.powerOnFlash();const n=await this.runStub(!0);if(this.logger.debug("Stub loaded"),t!==o&&(await n.setBaudrate(t),!this.port.writable||!this.port.readable))throw new Error(`Port not ready after baudrate change (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this.IS_STUB=!0,this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async reconnectToBootloader(){if(this._parent)await this._parent.reconnectToBootloader();else try{this.logger.log("Reconnecting to bootloader mode..."),this._consoleMode=!1,this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.debug("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:o}),this.connected=!0,this.currentBaudRate=o}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1,this.__chipFamily=void 0,this.chipName="Unknown Chip",this.chipRevision=null,this.chipVariant=null,this.IS_STUB=!1,this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await a(100),await this.connectWithResetStrategies(),await this.detectChip(),this.logger.log(`Reconnected to bootloader: ${this.chipName}`)}catch(t){throw this._isReconfiguring=!1,t}}async exitConsoleMode(){if(this._parent)return await this._parent.exitConsoleMode();this._consoleMode=!1;const t=this.chipFamily===w||this.chipFamily===C;let e=this._isUsbJtagOrOtg;if(t&&void 0===e)try{e=await this.detectUsbConnectionType()}catch(t){this.logger.debug(`USB detection failed, assuming USB-JTAG/OTG for ${this.chipName}: ${t}`),e=!0}if(t&&e){this.logger.log(`${this.chipName} USB: Resetting to bootloader mode`);try{await this.hardResetClassic(),this.logger.debug("Reset to bootloader initiated")}catch(t){this.logger.debug(`Reset error: ${t}`)}return await a(500),this.logger.log(`${this.chipName}: Port changed. Please select the bootloader port.`),this.dispatchEvent(new CustomEvent("usb-otg-port-change",{detail:{chipName:this.chipName,message:`${this.chipName}: Port changed. Please select the bootloader port.`,reason:"exit-console-to-bootloader"}})),!0}return await this.reconnectToBootloader(),!1}isConsoleResetSupported(){if(this._parent)return this._parent.isConsoleResetSupported();return!(this.chipFamily===w&&(!0===this._isUsbJtagOrOtg||void 0===this._isUsbJtagOrOtg))}async resetInConsoleMode(){if(this._parent)return await this._parent.resetInConsoleMode();if(this.isConsoleResetSupported())try{this.logger.debug("Resetting device in console mode"),await this.hardResetToFirmware(),this.logger.debug("Device reset complete")}catch(t){throw this.logger.error(`Reset failed: ${t}`),t}else this.logger.debug("Console reset not supported for ESP32-S2 USB-JTAG/CDC")}async drainInputBuffer(t=200){await a(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBufferAvailable>0){void 0!==this._readByte()&&e++}else await a(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0)}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),await a(E),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s,r){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");let n;await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`),this.isWebUSB()&&(this._isCDCDevice?(this._adaptiveBlockMultiplier=8,this._adaptiveMaxInFlightMultiplier=8,this._consecutiveSuccessfulChunks=0,this.logger.debug(`CDC device - Initialized: blockMultiplier=${this._adaptiveBlockMultiplier}, maxInFlightMultiplier=${this._adaptiveMaxInFlightMultiplier}`)):(this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0,this.logger.debug("Non-CDC device - Fixed values: blockSize=31, maxInFlight=31"))),void 0!==(null==r?void 0:r.chunkSize)?(n=r.chunkSize,this.logger.log(`Using custom chunk size: 0x${n.toString(16)} bytes`)):n=this.isWebUSB()?16384:262144;let o=new Uint8Array(0),h=e,l=i;for(;l>0;){const e=Math.min(n,l);let d=!1,c=0;const u=5;let g=!1;for(;!d&&c<=u;){let i=new Uint8Array(0),s=0;try{let n,l;if(0===c&&this.logger.debug(`Reading chunk at 0x${h.toString(16)}, size: 0x${e.toString(16)}`),void 0!==(null==r?void 0:r.blockSize)&&void 0!==(null==r?void 0:r.maxInFlight))n=r.blockSize,l=r.maxInFlight,0===c&&this.logger.debug(`Using custom parameters: blockSize=${n}, maxInFlight=${l}`);else if(this.isWebUSB()){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2);n=e*this._adaptiveBlockMultiplier,l=e*this._adaptiveMaxInFlightMultiplier}else{const t=63;n=65*t,l=130*t}const u=Je("<IIII",h,e,n,l),[g]=await this.checkCommand(210,u);if(0!=g)throw new Error("Failed to read memory: "+g);for(;i.length<e;){let r;try{r=await this.readPacket(100)}catch(t){if(t instanceof $){this.logger.debug(`SLIP read error at ${i.length} bytes: ${t.message}`);try{const t=[this.SLIP_END,this.SLIP_END];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await a(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(r&&r.length>0){const a=new Uint8Array(r),n=new Uint8Array(i.length+a.length);n.set(i),n.set(a,i.length),i=n;if(i.length>=e||i.length>=s+l){const e=Je("<I",i.length),a=t(e);await this.writeToStream(a),s=i.length}}}const f=new Uint8Array(o.length+i.length);if(f.set(o),f.set(i,o.length),o=f,d=!0,this.isWebUSB()&&this._isCDCDevice&&0===c&&(this._consecutiveSuccessfulChunks++,this._consecutiveSuccessfulChunks>=2)){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=8,s=8;let a=!1;if(this._adaptiveBlockMultiplier<i?(this._adaptiveBlockMultiplier=Math.min(2*this._adaptiveBlockMultiplier,i),a=!0):this._adaptiveMaxInFlightMultiplier<s&&(this._adaptiveMaxInFlightMultiplier=Math.min(2*this._adaptiveMaxInFlightMultiplier,s),a=!0),a){const t=e*this._adaptiveBlockMultiplier,i=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Speed increased: blockSize=${t}, maxInFlight=${i}`),this._lastAdaptiveAdjustment=Date.now()}this._consecutiveSuccessfulChunks=0}}catch(t){if(c++,this.isWebUSB()&&this._isCDCDevice&&1===c)if(this._adaptiveBlockMultiplier>1||this._adaptiveMaxInFlightMultiplier>1){this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0;const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=e*this._adaptiveBlockMultiplier,s=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Error at higher speed - reduced to minimum: blockSize=${i}, maxInFlight=${s}`)}else this.logger.debug("Error at minimum speed (blockSize=31, maxInFlight=31) - not a speed issue");if(!(t instanceof $))throw t;if(c<=u){this.logger.debug(`${t.message} at 0x${h.toString(16)}. Draining buffer and retrying (attempt ${c}/${u})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await a(E)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(g)throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${u} retries and recovery attempt`);g=!0,this.logger.log(`All retries exhausted at 0x${h.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),c=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${u} retries and recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),o.length,i),h+=e,l-=e,this.logger.debug(`Total progress: 0x${o.length.toString(16)} from 0x${i.toString(16)} bytes`)}return o}}class Ye extends qe{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await A(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,o=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(o,8)}`),this.logger.debug(`Stub data: ${s(r.data_start,8)}, len: ${r.data.length}, text: ${s(r.text_start,8)}, len: ${r.text.length}`);for(const[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&o>t)throw new Error("Software loader is resident at "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(n,8)+"-"+s(o,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,D)}async eraseRegion(t,e){if(t<0)throw new Error(`Invalid offset: ${t} (must be non-negative)`);if(e<0)throw new Error(`Invalid size: ${e} (must be non-negative)`);if(0===e)return void this.logger.log("eraseRegion: size is 0, skipping erase");if(t%n!==0)throw new Error(`Offset ${t} (0x${t.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);if(e%n!==0)throw new Error(`Size ${e} (0x${e.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);const i=4294967295;if(t>i)throw new Error(`Offset ${t} exceeds maximum value 4294967295`);if(e>i)throw new Error(`Size ${e} exceeds maximum value 4294967295`);if(t+e>i)throw new Error(`Region end (offset + size = ${t+e}) exceeds maximum addressable range 4294967295`);const s=M(O,e),a=Je("<II",t,e);await this.checkCommand(209,a,0,s)}}const Ke=async t=>{if(import("./install-dialog-7l9oLExq.js"),(()=>{const t=navigator.userAgent||"";return/Android/i.test(t)})()&&"usb"in navigator)try{await(async()=>{if(!globalThis.requestSerialPort)return new Promise((t,e)=>{const i=document.createElement("script");i.type="module",i.src="https://unpkg.com/tasmota-webserial-esptool/js/webusb-serial.js",i.onload=()=>{globalThis.requestSerialPort?t():e(new Error("WebUSB serial script loaded but requestSerialPort not found"))},i.onerror=()=>e(new Error("Failed to load WebUSB serial script")),document.head.appendChild(i)})})()}catch(t){return void alert(`Failed to load WebUSB support: ${t.message}`)}let e;try{e=await(async t=>{let e;const i=globalThis.requestSerialPort;if("function"==typeof i)e=await i();else{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser. Please use Chrome, Edge, or Opera on desktop, or Chrome on Android. Note: The page must be served over HTTPS or localhost.");e=await navigator.serial.requestPort()}return e.readable&&e.writable||await e.open({baudRate:o}),new qe(e,t)})({log:()=>{},debug:()=>{},error:t=>console.error(t)})}catch(e){return"NotFoundError"===e.name?void import("./index-DUmRg0Cu.js").then(e=>e.openNoPortPickedDialog(()=>Ke(t))):void alert(`Connection failed: ${e.message}`)}if(!e)return void alert("Failed to connect to device");const i=document.createElement("ewt-install-dialog");i.esploader=e,i.manifestPath=t.manifest||t.getAttribute("manifest"),i.overrides=t.overrides,i.firmwareFile=t.firmwareFile;const s=t.getAttribute("baud-rate");if(s){const t=parseInt(s,10);isNaN(t)||(i.baudRate=t)}else void 0!==t.baudRate&&(i.baudRate=t.baudRate);i.addEventListener("closed",async()=>{try{await e.disconnect()}catch(t){}},{once:!0}),document.body.appendChild(i)},Xe="https://cors-proxy.espressif.tools",Qe=async(t,e)=>{if((t=>{try{const e=new URL(t),i=window.location.origin;return e.origin!==i&&"file:"!==e.protocol}catch{return!1}})(t=t.trim())){if(t.includes("github.com")&&t.includes("/releases/download/")){const i=`${Xe}/?url=${encodeURIComponent(t)}`,{headers:s,credentials:a,...r}=null!=e?e:{};return fetch(i,r)}try{return await fetch(t,e)}catch(i){try{const i=`${Xe}/?url=${encodeURIComponent(t)}`,{headers:s,credentials:a,...r}=null!=e?e:{};return await fetch(i,r)}catch(t){throw i}}}return fetch(t,e)};window.espWebToolsCorsProxyFetch=Qe;class ti extends HTMLElement{attributeChangedCallback(t,e,i){if("baud-rate"===t&&i!==e)if(i){const t=parseInt(i,10);this.baudRate=Number.isNaN(t)?void 0:t}else this.baudRate=void 0}connectedCallback(){if(this.renderRoot)return;if(this.renderRoot=this.attachShadow({mode:"open"}),!ti.isSupported||!ti.isAllowed)return this.toggleAttribute("install-unsupported",!0),void(this.renderRoot.innerHTML=ti.isAllowed?"<slot name='unsupported'>Your browser does not support installing things on ESP devices. Use Google Chrome or Microsoft Edge (Desktop) or Chrome on Android with USB OTG.</slot>":"<slot name='not-allowed'>You can only install ESP devices on HTTPS websites or on the localhost.</slot>");this.toggleAttribute("install-supported",!0);const t=document.createElement("slot");t.addEventListener("click",async t=>{t.preventDefault(),Ke(this)}),t.name="activate";const e=document.createElement("button");if(e.innerText="Connect",t.append(e),"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype){const t=new CSSStyleSheet;t.replaceSync(ti.style),this.renderRoot.adoptedStyleSheets=[t]}else{const t=document.createElement("style");t.innerText=ti.style,this.renderRoot.append(t)}this.renderRoot.append(t)}}ti.isSupported="serial"in navigator||"usb"in navigator,ti.isAllowed=window.isSecureContext,ti.observedAttributes=["baud-rate"],ti.style='\n button {\n position: relative;\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n padding: 10px 24px;\n color: var(--esp-tools-button-text-color, #fff);\n background-color: var(--esp-tools-button-color, #03a9f4);\n border: none;\n border-radius: var(--esp-tools-button-border-radius, 9999px);\n }\n button::before {\n content: " ";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n opacity: 0.2;\n border-radius: var(--esp-tools-button-border-radius, 9999px);\n }\n button:hover::before {\n background-color: rgba(255,255,255,.8);\n }\n button:focus {\n outline: none;\n }\n button:focus::before {\n background-color: white;\n }\n button:active::before {\n background-color: grey;\n }\n :host([active]) button {\n color: rgba(0, 0, 0, 0.38);\n background-color: rgba(0, 0, 0, 0.12);\n box-shadow: none;\n cursor: unset;\n pointer-events: none;\n }\n improv-wifi-launch-button {\n display: block;\n margin-top: 16px;\n }\n .hidden {\n display: none;\n }',customElements.define("esp-web-install-button",ti);export{_ as C,C as a,B as b,R as c,v as d,S as e,y as f,b as g,m as h,w as i,p as j,Qe as k};
|
|
1
|
+
const t=t=>{let e=[192];for(const i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e.push(192),e},e=t=>{const e=[];for(let i=0;i<t.length;i++){const s=t.charCodeAt(i);s<=255&&e.push(s)}return e},i=t=>"["+t.map(t=>s(t)).join(", ")+"]",s=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},a=t=>new Promise(e=>setTimeout(e,t)),r={18:"256KB",19:"512KB",20:"1MB",21:"2MB",22:"4MB",23:"8MB",24:"16MB",25:"32MB",26:"64MB",27:"128MB",28:"256MB",32:"64MB",33:"128MB",34:"256MB",50:"256KB",51:"512KB",52:"1MB",53:"2MB",54:"4MB",55:"8MB",56:"16MB",57:"32MB",58:"64MB"},n=4096,o=115200,h=1610647552,l=1343410176,d=1343312316,c=1<<27,u=1343312312,g=1343312892,f=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),_=33382,p=50,w=12882,m=12883,b=12994,y=12995,S=12997,v=12998,R=207969,B=12914,U=12916,I=12917,C=12928,x=12849,k={5:{name:"ESP32-C3",family:y},9:{name:"ESP32-S3",family:m},12:{name:"ESP32-C2",family:b},13:{name:"ESP32-C6",family:v},16:{name:"ESP32-H2",family:B},18:{name:"ESP32-P4",family:C},20:{name:"ESP32-C61",family:R},23:{name:"ESP32-C5",family:S},25:{name:"ESP32-H21",family:I},28:{name:"ESP32-H4",family:U},32:{name:"ESP32-S31",family:x}},F={4293968129:{name:"ESP8266",family:_},15736195:{name:"ESP32",family:p},1990:{name:"ESP32-S2",family:w}},T=3e3,D=15e4,E=100,O=3e4,M=(t,e)=>{const i=Math.floor(t*(e/486));return i<T?T:i},z=t=>{switch(t){case p:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case w:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case m:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case _:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case b:return{regBase:1610620928,baseFuse:h,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case y:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case S:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case v:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case R:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case B:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case U:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case I:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case C:return{regBase:1342754816,baseFuse:l,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case x:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class $ extends Error{constructor(t){super(t),this.name="SlipReadError"}}const A=async(t,i)=>{let s;if(t==U||t==I||t==x)return null;if(t==p)s=await import("./esp32-BRKoi17y.js");else if(t==w)s=await import("./esp32s2-iX3WoDbg.js");else if(t==m)s=await import("./esp32s3-DGwDVIgz.js");else if(t==_)s=await import("./esp8266-CUwxJpGa.js");else if(t==b)s=await import("./esp32c2-Btgr_lwh.js");else if(t==y)s=await import("./esp32c3-CHKfoI8W.js");else if(t==S)s=await import("./esp32c5-BDW4KtLo.js");else if(t==v)s=await import("./esp32c6-il8tTxAG.js");else if(t==R)s=await import("./esp32c61-thKzxBGf.js");else if(t==B)s=await import("./esp32h2-CxoUHv_P.js");else{if(t!=C)return null;s=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")}return{...s,text:e(atob(s.text)),data:e(atob(s.data))}};function P(t){let e=t.length;for(;--e>=0;)t[e]=0}const W=256,L=286,N=30,H=15,V=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Z=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),G=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),J=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),j=new Array(576);P(j);const q=new Array(60);P(q);const Y=new Array(512);P(Y);const K=new Array(256);P(K);const X=new Array(29);P(X);const Q=new Array(N);function tt(t,e,i,s,a){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=a,this.has_stree=t&&t.length}let et,it,st;function at(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}P(Q);const rt=t=>t<256?Y[t]:Y[256+(t>>>7)],nt=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},ot=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,nt(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},ht=(t,e,i)=>{ot(t,i[2*e],i[2*e+1])},lt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},dt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=H;a++)n=n+i[a-1]<<1,s[a]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=lt(s[e]++,e))}},ct=t=>{let e;for(e=0;e<L;e++)t.dyn_ltree[2*e]=0;for(e=0;e<N;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},ut=t=>{t.bi_valid>8?nt(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},gt=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},ft=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&>(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!gt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},_t=(t,e,i)=>{let s,a,r,n,o=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+o++],s+=(255&t.pending_buf[t.sym_buf+o++])<<8,a=t.pending_buf[t.sym_buf+o++],0===s?ht(t,a,e):(r=K[a],ht(t,r+W+1,e),n=V[r],0!==n&&(a-=X[r],ot(t,a,n)),s--,r=rt(s),ht(t,r,i),n=Z[r],0!==n&&(s-=Q[r],ot(t,s,n)))}while(o<t.sym_next);ht(t,256,e)},pt=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=e.stat_desc.has_stree,r=e.stat_desc.elems;let n,o,h,l=-1;for(t.heap_len=0,t.heap_max=573,n=0;n<r;n++)0!==i[2*n]?(t.heap[++t.heap_len]=l=n,t.depth[n]=0):i[2*n+1]=0;for(;t.heap_len<2;)h=t.heap[++t.heap_len]=l<2?++l:0,i[2*h]=1,t.depth[h]=0,t.opt_len--,a&&(t.static_len-=s[2*h+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)ft(t,i,n);h=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ft(t,i,1),o=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=o,i[2*h]=i[2*n]+i[2*o],t.depth[h]=(t.depth[n]>=t.depth[o]?t.depth[n]:t.depth[o])+1,i[2*n+1]=i[2*o+1]=h,t.heap[1]=h++,ft(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,s=e.max_code,a=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,h=e.stat_desc.max_length;let l,d,c,u,g,f,_=0;for(u=0;u<=H;u++)t.bl_count[u]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)d=t.heap[l],u=i[2*i[2*d+1]+1]+1,u>h&&(u=h,_++),i[2*d+1]=u,d>s||(t.bl_count[u]++,g=0,d>=o&&(g=n[d-o]),f=i[2*d],t.opt_len+=f*(u+g),r&&(t.static_len+=f*(a[2*d+1]+g)));if(0!==_){do{for(u=h-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[h]--,_-=2}while(_>0);for(u=h;0!==u;u--)for(d=t.bl_count[u];0!==d;)c=t.heap[--l],c>s||(i[2*c+1]!==u&&(t.opt_len+=(u-i[2*c+1])*i[2*c],i[2*c+1]=u),d--)}})(t,e),dt(i,l,t.bl_count)},wt=(t,e,i)=>{let s,a,r=-1,n=e[1],o=0,h=7,l=4;for(0===n&&(h=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++o<h&&a===n||(o<l?t.bl_tree[2*a]+=o:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,r=a,0===n?(h=138,l=3):a===n?(h=6,l=3):(h=7,l=4))},mt=(t,e,i)=>{let s,a,r=-1,n=e[1],o=0,h=7,l=4;for(0===n&&(h=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++o<h&&a===n)){if(o<l)do{ht(t,a,t.bl_tree)}while(0!==--o);else 0!==a?(a!==r&&(ht(t,a,t.bl_tree),o--),ht(t,16,t.bl_tree),ot(t,o-3,2)):o<=10?(ht(t,17,t.bl_tree),ot(t,o-3,3)):(ht(t,18,t.bl_tree),ot(t,o-11,7));o=0,r=a,0===n?(h=138,l=3):a===n?(h=6,l=3):(h=7,l=4)}};let bt=!1;const yt=(t,e,i,s)=>{ot(t,0+(s?1:0),3),ut(t),nt(t,i),nt(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var St=(t,e,i,s)=>{let a,r,n=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<W;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),pt(t,t.l_desc),pt(t,t.d_desc),n=(t=>{let e;for(wt(t,t.dyn_ltree,t.l_desc.max_code),wt(t,t.dyn_dtree,t.d_desc.max_code),pt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*J[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=a&&(a=r)):a=r=i+5,i+4<=a&&-1!==e?yt(t,e,i,s):4===t.strategy||r===a?(ot(t,2+(s?1:0),3),_t(t,j,q)):(ot(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(ot(t,e-257,5),ot(t,i-1,5),ot(t,s-4,4),a=0;a<s;a++)ot(t,t.bl_tree[2*J[a]+1],3);mt(t,t.dyn_ltree,e-1),mt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),_t(t,t.dyn_ltree,t.dyn_dtree)),ct(t),s&&ut(t)},vt={_tr_init:t=>{bt||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(X[s]=i,t=0;t<1<<V[s];t++)K[i++]=s;for(K[i-1]=s,a=0,s=0;s<16;s++)for(Q[s]=a,t=0;t<1<<Z[s];t++)Y[a++]=s;for(a>>=7;s<N;s++)for(Q[s]=a<<7,t=0;t<1<<Z[s]-7;t++)Y[256+a++]=s;for(e=0;e<=H;e++)r[e]=0;for(t=0;t<=143;)j[2*t+1]=8,t++,r[8]++;for(;t<=255;)j[2*t+1]=9,t++,r[9]++;for(;t<=279;)j[2*t+1]=7,t++,r[7]++;for(;t<=287;)j[2*t+1]=8,t++,r[8]++;for(dt(j,287,r),t=0;t<N;t++)q[2*t+1]=5,q[2*t]=lt(t,5);et=new tt(j,V,257,L,H),it=new tt(q,Z,0,N,H),st=new tt(new Array(0),G,0,19,7)})(),bt=!0),t.l_desc=new at(t.dyn_ltree,et),t.d_desc=new at(t.dyn_dtree,it),t.bl_desc=new at(t.bl_tree,st),t.bi_buf=0,t.bi_valid=0,ct(t)},_tr_stored_block:yt,_tr_flush_block:St,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(K[i]+W+1)]++,t.dyn_dtree[2*rt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{ot(t,2,3),ht(t,256,j),(t=>{16===t.bi_valid?(nt(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var Rt=(t,e,i,s)=>{let a=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{a=a+e[s++]|0,r=r+a|0}while(--n);a%=65521,r%=65521}return a|r<<16};const Bt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var Ut=(t,e,i,s)=>{const a=Bt,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},It={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Ct={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:xt,_tr_stored_block:kt,_tr_flush_block:Ft,_tr_tally:Tt,_tr_align:Dt}=vt,{Z_NO_FLUSH:Et,Z_PARTIAL_FLUSH:Ot,Z_FULL_FLUSH:Mt,Z_FINISH:zt,Z_BLOCK:$t,Z_OK:At,Z_STREAM_END:Pt,Z_STREAM_ERROR:Wt,Z_DATA_ERROR:Lt,Z_BUF_ERROR:Nt,Z_DEFAULT_COMPRESSION:Ht,Z_FILTERED:Vt,Z_HUFFMAN_ONLY:Zt,Z_RLE:Gt,Z_FIXED:Jt,Z_DEFAULT_STRATEGY:jt,Z_UNKNOWN:qt,Z_DEFLATED:Yt}=Ct,Kt=258,Xt=262,Qt=42,te=113,ee=666,ie=(t,e)=>(t.msg=It[e],e),se=t=>2*t-(t>4?9:0),ae=t=>{let e=t.length;for(;--e>=0;)t[e]=0},re=t=>{let e,i,s,a=t.w_size;e=t.hash_size,s=e;do{i=t.head[--s],t.head[s]=i>=a?i-a:0}while(--e);e=a,s=e;do{i=t.prev[--s],t.prev[s]=i>=a?i-a:0}while(--e)};let ne=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const oe=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},he=(t,e)=>{Ft(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,oe(t.strm)},le=(t,e)=>{t.pending_buf[t.pending++]=e},de=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ce=(t,e,i,s)=>{let a=t.avail_in;return a>s&&(a=s),0===a?0:(t.avail_in-=a,e.set(t.input.subarray(t.next_in,t.next_in+a),i),1===t.state.wrap?t.adler=Rt(t.adler,e,a,i):2===t.state.wrap&&(t.adler=Ut(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},ue=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,o=t.nice_match;const h=t.strstart>t.w_size-Xt?t.strstart-(t.w_size-Xt):0,l=t.window,d=t.w_mask,c=t.prev,u=t.strstart+Kt;let g=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(a>>=2),o>t.lookahead&&(o=t.lookahead);do{if(i=e,l[i+n]===f&&l[i+n-1]===g&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do{}while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<u);if(s=Kt-(u-r),r=u-Kt,s>n){if(t.match_start=e,n=s,s>=o)break;g=l[r+n-1],f=l[r+n]}}}while((e=c[e&d])>h&&0!==--a);return n<=t.lookahead?n:t.lookahead},ge=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Xt)&&(t.window.set(t.window.subarray(e,e+e-s),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),re(t),s+=e),0===t.strm.avail_in)break;if(i=ce(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=ne(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=ne(t,t.ins_h,t.window[a+3-1]),t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Xt&&0!==t.strm.avail_in)},fe=(t,e)=>{let i,s,a,r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n=0,o=t.strm.avail_in;do{if(i=65535,a=t.bi_valid+42>>3,t.strm.avail_out<a)break;if(a=t.strm.avail_out-a,s=t.strstart-t.block_start,i>s+t.strm.avail_in&&(i=s+t.strm.avail_in),i>a&&(i=a),i<r&&(0===i&&e!==zt||e===Et||i!==s+t.strm.avail_in))break;n=e===zt&&i===s+t.strm.avail_in?1:0,kt(t,0,0,n),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,oe(t.strm),s&&(s>i&&(s=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+s),t.strm.next_out),t.strm.next_out+=s,t.strm.avail_out-=s,t.strm.total_out+=s,t.block_start+=s,i-=s),i&&(ce(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(0===n);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==Et&&e!==zt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(a=t.window_size-t.strstart,t.strm.avail_in>a&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(ce(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=r||(s||e===zt)&&e!==Et&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===zt&&0===t.strm.avail_in&&i===s?1:0,kt(t,t.block_start,i,n),t.block_start+=i,oe(t.strm)),n?3:1)},_e=(t,e)=>{let i,s;for(;;){if(t.lookahead<Xt){if(ge(t),t.lookahead<Xt&&e===Et)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Xt&&(t.match_length=ue(t,i)),t.match_length>=3)if(s=Tt(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ne(t,t.ins_h,t.window[t.strstart+1]);else s=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2},pe=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<Xt){if(ge(t),t.lookahead<Xt&&e===Et)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Xt&&(t.match_length=ue(t,i),t.match_length<=5&&(t.strategy===Vt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){a=t.strstart+t.lookahead-3,s=Tt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=a&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,s&&(he(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Tt(t,0,t.window[t.strstart-1]),s&&he(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(s=Tt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2};function we(t,e,i,s,a){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=a}const me=[new we(0,0,0,0,fe),new we(4,4,8,4,_e),new we(4,5,16,8,_e),new we(4,6,32,32,_e),new we(4,4,16,16,pe),new we(8,16,32,32,pe),new we(8,16,128,128,pe),new we(8,32,128,256,pe),new we(32,128,258,1024,pe),new we(32,258,258,4096,pe)];function be(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Yt,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),ae(this.dyn_ltree),ae(this.dyn_dtree),ae(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),ae(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ae(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const ye=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Qt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==te&&e.status!==ee?1:0},Se=t=>{if(ye(t))return ie(t,Wt);t.total_in=t.total_out=0,t.data_type=qt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Qt:te,t.adler=2===e.wrap?0:1,e.last_flush=-2,xt(e),At},ve=t=>{const e=Se(t);var i;return e===At&&((i=t.state).window_size=2*i.w_size,ae(i.head),i.max_lazy_match=me[i.level].max_lazy,i.good_match=me[i.level].good_length,i.nice_match=me[i.level].nice_length,i.max_chain_length=me[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},Re=(t,e,i,s,a,r)=>{if(!t)return Wt;let n=1;if(e===Ht&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==Yt||s<8||s>15||e<0||e>9||r<0||r>Jt||8===s&&1!==n)return ie(t,Wt);8===s&&(s=9);const o=new be;return t.state=o,o.strm=t,o.status=Qt,o.wrap=n,o.gzhead=null,o.w_bits=s,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=a+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<a+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=r,o.method=i,ve(t)};var Be={deflateInit:(t,e)=>Re(t,e,Yt,15,8,jt),deflateInit2:Re,deflateReset:ve,deflateResetKeep:Se,deflateSetHeader:(t,e)=>ye(t)||2!==t.state.wrap?Wt:(t.state.gzhead=e,At),deflate:(t,e)=>{if(ye(t)||e>$t||e<0)return t?ie(t,Wt):Wt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===ee&&e!==zt)return ie(t,0===t.avail_out?Nt:Wt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(oe(t),0===t.avail_out)return i.last_flush=-1,At}else if(0===t.avail_in&&se(e)<=se(s)&&e!==zt)return ie(t,Nt);if(i.status===ee&&0!==t.avail_in)return ie(t,Nt);if(i.status===Qt&&0===i.wrap&&(i.status=te),i.status===Qt){let e=Yt+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=Zt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=s<<6,0!==i.strstart&&(e|=32),e+=31-e%31,de(i,e),0!==i.strstart&&(de(i,t.adler>>>16),de(i,65535&t.adler)),t.adler=1,i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At}if(57===i.status)if(t.adler=0,le(i,31),le(i,139),le(i,8),i.gzhead)le(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),le(i,255&i.gzhead.time),le(i,i.gzhead.time>>8&255),le(i,i.gzhead.time>>16&255),le(i,i.gzhead.time>>24&255),le(i,9===i.level?2:i.strategy>=Zt||i.level<2?4:0),le(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(le(i,255&i.gzhead.extra.length),le(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=Ut(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(le(i,0),le(i,0),le(i,0),le(i,0),le(i,0),le(i,9===i.level?2:i.strategy>=Zt||i.level<2?4:0),le(i,3),i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At;if(69===i.status){if(i.gzhead.extra){let e=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,oe(t),0!==i.pending)return i.last_flush=-1,At;e=0,s-=a}let a=new Uint8Array(i.gzhead.extra);i.pending_buf.set(a.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>e&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),oe(t),0!==i.pending)return i.last_flush=-1,At;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,le(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),oe(t),0!==i.pending)return i.last_flush=-1,At;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,le(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(oe(t),0!==i.pending))return i.last_flush=-1,At;le(i,255&t.adler),le(i,t.adler>>8&255),t.adler=0}if(i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At}if(0!==t.avail_in||0!==i.lookahead||e!==Et&&i.status!==ee){let s=0===i.level?fe(i,e):i.strategy===Zt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(ge(t),0===t.lookahead)){if(e===Et)return 1;break}if(t.match_length=0,i=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Gt?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=Kt){if(ge(t),t.lookahead<=Kt&&e===Et)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=n[a],s===n[++a]&&s===n[++a]&&s===n[++a])){r=t.strstart+Kt;do{}while(s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&a<r);t.match_length=Kt-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Tt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2})(i,e):me[i.level].func(i,e);if(3!==s&&4!==s||(i.status=ee),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),At;if(2===s&&(e===Ot?Dt(i):e!==$t&&(kt(i,0,0,!1),e===Mt&&(ae(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),oe(t),0===t.avail_out))return i.last_flush=-1,At}return e!==zt?At:i.wrap<=0?Pt:(2===i.wrap?(le(i,255&t.adler),le(i,t.adler>>8&255),le(i,t.adler>>16&255),le(i,t.adler>>24&255),le(i,255&t.total_in),le(i,t.total_in>>8&255),le(i,t.total_in>>16&255),le(i,t.total_in>>24&255)):(de(i,t.adler>>>16),de(i,65535&t.adler)),oe(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?At:Pt)},deflateEnd:t=>{if(ye(t))return Wt;const e=t.state.status;return t.state=null,e===te?ie(t,Lt):At},deflateSetDictionary:(t,e)=>{let i=e.length;if(ye(t))return Wt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==Qt||s.lookahead)return Wt;if(1===a&&(t.adler=Rt(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(ae(s.head),s.strstart=0,s.block_start=0,s.insert=0);let t=new Uint8Array(s.w_size);t.set(e.subarray(i-s.w_size,i),0),e=t,i=s.w_size}const r=t.avail_in,n=t.next_in,o=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,ge(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=ne(s,s.ins_h,s.window[t+3-1]),s.prev[t&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=t,t++}while(--e);s.strstart=t,s.lookahead=2,ge(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,t.next_in=n,t.input=o,t.avail_in=r,s.wrap=a,At},deflateInfo:"pako deflate (from Nodeca project)"};const Ue=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ie=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)Ue(i,e)&&(t[e]=i[e])}}return t},Ce=t=>{let e=0;for(let i=0,s=t.length;i<s;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,s=0,a=t.length;e<a;e++){let a=t[e];i.set(a,s),s+=a.length}return i};let xe=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){xe=!1}const ke=new Uint8Array(256);for(let t=0;t<256;t++)ke[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;ke[254]=ke[254]=1;var Fe=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,o=0;for(a=0;a<n;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(o),r=0,a=0;r<o;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),i<128?e[r++]=i:i<2048?(e[r++]=192|i>>>6,e[r++]=128|63&i):i<65536?(e[r++]=224|i>>>12,e[r++]=128|i>>>6&63,e[r++]=128|63&i):(e[r++]=240|i>>>18,e[r++]=128|i>>>12&63,e[r++]=128|i>>>6&63,e[r++]=128|63&i);return e};var Te=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const De=Object.prototype.toString,{Z_NO_FLUSH:Ee,Z_SYNC_FLUSH:Oe,Z_FULL_FLUSH:Me,Z_FINISH:ze,Z_OK:$e,Z_STREAM_END:Ae,Z_DEFAULT_COMPRESSION:Pe,Z_DEFAULT_STRATEGY:We,Z_DEFLATED:Le}=Ct;function Ne(t){this.options=Ie({level:Pe,method:Le,chunkSize:16384,windowBits:15,memLevel:8,strategy:We},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Te,this.strm.avail_out=0;let i=Be.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==$e)throw new Error(It[i]);if(e.header&&Be.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Fe(e.dictionary):"[object ArrayBuffer]"===De.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=Be.deflateSetDictionary(this.strm,t),i!==$e)throw new Error(It[i]);this._dict_set=!0}}Ne.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?ze:Ee,"string"==typeof t?i.input=Fe(t):"[object ArrayBuffer]"===De.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),(r===Oe||r===Me)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=Be.deflate(i,r),a===Ae)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=Be.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===$e;if(0!==i.avail_out){if(r>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},Ne.prototype.onData=function(t){this.chunks.push(t)},Ne.prototype.onEnd=function(t){t===$e&&(this.result=Ce(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var He={deflate:function(t,e){const i=new Ne(e);if(i.push(t,!0),i.err)throw i.msg||It[i.err];return i.result}};const{deflate:Ve}=He;var Ze=Ve;const Ge={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},Je=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(r(t[s],e[i]),i++);function r(t,e){if(!(t in Ge))throw"Unhandled character '"+t+"' in pack format";const i=Ge[t].bytes,r=new DataView(new ArrayBuffer(i));Ge[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},je=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:r(e);function r(t){if(!(t in Ge))throw"Unhandled character '"+t+"' in unpack format";const r=Ge[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const o=Ge[t].u.bind(n);s.push(o(0,a)),i+=r}return s};class qe extends EventTarget{get isUsbJtagOrOtg(){return this._parent?this._parent._isUsbJtagOrOtg:this._isUsbJtagOrOtg}constructor(t,e,i){super(),this.port=t,this.logger=e,this._parent=i,this.__chipName=null,this.__chipRevision=null,this.__chipVariant=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null,this.currentBaudRate=o,this.SLIP_END=192,this.SLIP_ESC=219,this.SLIP_ESC_END=220,this.SLIP_ESC_ESC=221,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.__commandLock=Promise.resolve([0,[]]),this.__isReconfiguring=!1,this.__abandonCurrentOperation=!1,this._suppressDisconnect=!1,this.__consoleMode=!1,this._isUsbJtagOrOtg=void 0,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.state_RTS=!1,this.__writeChain=Promise.resolve()}get chipFamily(){return this._parent?this._parent.chipFamily:this.__chipFamily}set chipFamily(t){this._parent?this._parent.chipFamily=t:this.__chipFamily=t}get chipName(){return this._parent?this._parent.chipName:this.__chipName}set chipName(t){this._parent?this._parent.chipName=t:this.__chipName=t}get chipRevision(){return this._parent?this._parent.chipRevision:this.__chipRevision}set chipRevision(t){this._parent?this._parent.chipRevision=t:this.__chipRevision=t}get chipVariant(){return this._parent?this._parent.chipVariant:this.__chipVariant}set chipVariant(t){this._parent?this._parent.chipVariant=t:this.__chipVariant=t}get _consoleMode(){return this._parent?this._parent._consoleMode:this.__consoleMode}set _consoleMode(t){this._parent?this._parent._consoleMode=t:this.__consoleMode=t}setConsoleMode(t){this._consoleMode=t}get _inputBuffer(){if(this._parent)return this._parent._inputBuffer;if(void 0===this.__inputBuffer)throw new Error("_inputBuffer accessed before initialization");return this.__inputBuffer}get _inputBufferReadIndex(){return this._parent?this._parent._inputBufferReadIndex:this.__inputBufferReadIndex||0}set _inputBufferReadIndex(t){this._parent?this._parent._inputBufferReadIndex=t:this.__inputBufferReadIndex=t}get _inputBufferAvailable(){return this._inputBuffer.length-this._inputBufferReadIndex}_readByte(){if(!(this._inputBufferReadIndex>=this._inputBuffer.length))return this._inputBuffer[this._inputBufferReadIndex++]}_clearInputBuffer(){this._inputBuffer.length=0,this._inputBufferReadIndex=0}_compactInputBuffer(){this._inputBufferReadIndex>1e3&&this._inputBufferReadIndex>this._inputBuffer.length/2&&(this._inputBuffer.splice(0,this._inputBufferReadIndex),this._inputBufferReadIndex=0)}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}get _commandLock(){return this._parent?this._parent._commandLock:this.__commandLock}set _commandLock(t){this._parent?this._parent._commandLock=t:this.__commandLock=t}get _isReconfiguring(){return this._parent?this._parent._isReconfiguring:this.__isReconfiguring}set _isReconfiguring(t){this._parent?this._parent._isReconfiguring=t:this.__isReconfiguring=t}get _abandonCurrentOperation(){return this._parent?this._parent._abandonCurrentOperation:this.__abandonCurrentOperation}set _abandonCurrentOperation(t){this._parent?this._parent._abandonCurrentOperation=t:this.__abandonCurrentOperation=t}get _adaptiveBlockMultiplier(){return this._parent?this._parent._adaptiveBlockMultiplier:this.__adaptiveBlockMultiplier}set _adaptiveBlockMultiplier(t){this._parent?this._parent._adaptiveBlockMultiplier=t:this.__adaptiveBlockMultiplier=t}get _adaptiveMaxInFlightMultiplier(){return this._parent?this._parent._adaptiveMaxInFlightMultiplier:this.__adaptiveMaxInFlightMultiplier}set _adaptiveMaxInFlightMultiplier(t){this._parent?this._parent._adaptiveMaxInFlightMultiplier=t:this.__adaptiveMaxInFlightMultiplier=t}get _consecutiveSuccessfulChunks(){return this._parent?this._parent._consecutiveSuccessfulChunks:this.__consecutiveSuccessfulChunks}set _consecutiveSuccessfulChunks(t){this._parent?this._parent._consecutiveSuccessfulChunks=t:this.__consecutiveSuccessfulChunks=t}get _lastAdaptiveAdjustment(){return this._parent?this._parent._lastAdaptiveAdjustment:this.__lastAdaptiveAdjustment}set _lastAdaptiveAdjustment(t){this._parent?this._parent._lastAdaptiveAdjustment=t:this.__lastAdaptiveAdjustment=t}get _isCDCDevice(){return this._parent?this._parent._isCDCDevice:this.__isCDCDevice}set _isCDCDevice(t){this._parent?this._parent._isCDCDevice=t:this.__isCDCDevice=t}detectUSBSerialChip(t,e){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},18:{name:"ESP32-P4 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0;const t=this.port.getInfo();if(t.usbVendorId&&t.usbProductId){const e=this.detectUSBSerialChip(t.usbVendorId,t.usbProductId);this.logger.log(`USB-Serial: ${e.name} (VID: 0x${t.usbVendorId.toString(16)}, PID: 0x${t.usbProductId.toString(16)})`),e.maxBaudrate&&(this._maxUSBSerialBaudrate=e.maxBaudrate,this.logger.log(`Max baudrate: ${e.maxBaudrate}`)),12346===t.usbVendorId&&2===t.usbProductId&&(this._isESP32S2NativeUSB=!0),(12346===t.usbVendorId||6790===t.usbVendorId&&21971===t.usbProductId)&&(this._isCDCDevice=!0)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip(),this.chipFamily===C&&301===this.chipRevision&&await this.powerOnFlash();try{this._isUsbJtagOrOtg=await this.detectUsbConnectionType(),this.logger.debug("USB connection type: "+(this._isUsbJtagOrOtg?"USB-JTAG/OTG":"External Serial Chip"))}catch(t){this.logger.debug(`Could not detect USB connection type: ${t}`)}const t=z(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=k[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===C?(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)):this.chipFamily===y&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-C3 revision: ${this.chipRevision}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._clearInputBuffer(),await a(E);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=F[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${s(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===C?(this.chipRevision=await this.getChipRevision(),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)):this.chipFamily===y&&(this.chipRevision=await this.getChipRevision()),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily===C){const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}return this.chipFamily===y?await this.getChipRevisionC3():0}async powerOnFlash(){if(this.chipFamily!==C)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await a(10);const t=await this.readRegister(d);await this.writeRegister(d,t|c);const e=await this.readRegister(u);await this.writeRegister(u,128|e);const i=await this.readRegister(g);await this.writeRegister(g,3|i),await a(.05);const s=await this.readRegister(d);await this.writeRegister(d,-134217729&s);const r=await this.readRegister(u);await this.writeRegister(u,-2139095041&r);const n=await this.readRegister(u);await this.writeRegister(u,128|n);const o=await this.readRegister(u);await this.writeRegister(u,-129&o),await a(2),this.logger.debug("Flash powered on successfully")}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:je("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?je("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?je("<I",t.slice(16,20))[0]:0}}async getMacAddress(){if(!this._initializationSucceeded)throw new Error("getMacAddress() requires initialize() to have completed successfully");return this.macAddr().map(t=>t.toString(16).padStart(2,"0").toUpperCase()).join(":")}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{}finally{if(this._isReconfiguring=!1,this._reader){try{this._reader.releaseLock(),this.logger.debug("Reader released in readLoop cleanup")}catch(t){this.logger.debug(`Reader release error in readLoop: ${t}`)}this._reader=void 0}}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this._suppressDisconnect||this.dispatchEvent(new Event("disconnect")),this._suppressDisconnect=!1,this.logger.debug("Finished read loop")}sleep(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async setDTRandRTS(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async runSignalSequence(t){const e=!0===this.port.isWebUSB;for(const i of t)void 0!==i.dtr&&void 0!==i.rts?e?await this.setDTRandRTSWebUSB(i.dtr,i.rts):await this.setDTRandRTS(i.dtr,i.rts):(void 0!==i.dtr&&(e?await this.setDTRWebUSB(i.dtr):await this.setDTR(i.dtr)),void 0!==i.rts&&(e?await this.setRTSWebUSB(i.rts):await this.setRTS(i.rts))),i.delayMs&&await a(i.delayMs)}async hardResetUSBJTAGSerial(){await this.runSignalSequence([{rts:!1},{dtr:!1,delayMs:100},{dtr:!0,rts:!1,delayMs:100},{rts:!0},{dtr:!1,rts:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:200}])}async hardResetClassic(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:50},{dtr:!1,delayMs:200}])}async hardResetToFirmware(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:100},{rts:!1,delayMs:50},{delayMs:200}])}async hardResetUnixTight(){await this.runSignalSequence([{dtr:!0,rts:!0},{dtr:!1,rts:!1},{dtr:!1,rts:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:50},{dtr:!1,rts:!1},{dtr:!1,delayMs:200}])}async setRTSWebUSB(t){this.state_RTS=t,await this.port.setSignals({requestToSend:t,dataTerminalReady:this.state_DTR})}async setDTRWebUSB(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:this.state_RTS})}async setDTRandRTSWebUSB(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.runSignalSequence([{rts:!1,dtr:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:100},{rts:!0,dtr:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:200}])}async hardResetClassicLongDelayWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:500},{dtr:!0,rts:!1,delayMs:200},{dtr:!1,delayMs:500}])}async hardResetClassicShortDelayWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:50},{dtr:!0,rts:!1,delayMs:25},{dtr:!1,delayMs:100}])}async hardResetInvertedWebUSB(){await this.runSignalSequence([{dtr:!0,rts:!1,delayMs:100},{dtr:!1,rts:!0,delayMs:50},{dtr:!0,delayMs:200}])}async hardResetInvertedDTRWebUSB(){await this.runSignalSequence([{dtr:!0,rts:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:50},{dtr:!0,delayMs:200}])}async hardResetInvertedRTSWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!1,delayMs:100},{dtr:!0,rts:!0,delayMs:50},{dtr:!1,delayMs:200}])}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,s=[],r=this,n=!e&&!i;if(this.isWebUSB()){const a=4292===t.usbVendorId,o=6790===t.usbVendorId,h=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(h?(s.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async()=>await r.hardResetUSBJTAGSerial()}),s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async()=>await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async()=>await r.hardResetClassic()})):(s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async()=>await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"USB-JTAG/Serial (WebUSB)",fn:async()=>await r.hardResetUSBJTAGSerial()}),s.push({name:"Inverted DTR Classic (WebUSB)",fn:async()=>await r.hardResetInvertedDTRWebUSB()}))),n&&(o?(s.push({name:"UnixTight (WebUSB) - CH34x",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CH34x",fn:async()=>await r.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedDTRWebUSB()})):a?(s.push({name:"UnixTight (WebUSB) - CP2102",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CP2102",fn:async()=>await r.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedDTRWebUSB()})):(s.push({name:"UnixTight (WebUSB)",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassic()}}),s.push({name:"Inverted Both (WebUSB)",fn:async function(){return await r.hardResetInvertedWebUSB()}}),s.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),s.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),a||h||(6790!==t.usbVendorId&&s.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassic()}}),s.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTight()}}),s.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await r.hardResetClassicLongDelayWebUSB()}}),s.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await r.hardResetClassicShortDelayWebUSB()}}),e||i||s.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerial()}}))}else(e||i)&&s.push({name:"USB-JTAG/Serial",fn:async function(){return await r.hardResetUSBJTAGSerial()}}),s.push({name:"UnixTight",fn:async function(){return await r.hardResetUnixTight()}}),e||i||s.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await r.hardResetUSBJTAGSerial()}});let o=null;for(const t of s)try{if(!this.connected||!this.port.writable){this.logger.debug(`Port disconnected, skipping ${t.name} reset`);continue}if(this._abandonCurrentOperation=!1,await t.fn(),n){if(await this.syncWithTimeout(2e3))return void this.logger.log(`Connected USB Serial successfully with ${t.name} reset.`);throw new Error("Sync timeout or abandoned")}{const e=this.sync(),i=new Promise((t,e)=>setTimeout(()=>e(new Error("Sync timeout")),1e3));try{return await Promise.race([e,i]),void this.logger.log(`Connected CDC/JTAG successfully with ${t.name} reset.`)}catch(t){throw new Error("Sync timeout or abandoned")}}}catch(t){if(o=t,this._abandonCurrentOperation=!0,await a(100),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._clearInputBuffer(),await this.drainInputBuffer(200),await this.flushSerialBuffers()}throw this._abandonCurrentOperation=!1,new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${null==o?void 0:o.message}`)}async watchdogReset(){await this.rtcWdtResetChipSpecific()}async getChipRevisionC3(){if(this.chipFamily!==y)return 0;const t=await this.readRegister(1610647632)>>18&7;return(await this.readRegister(1610647640)>>23&7)<<3|t}async rtcWdtResetChipSpecific(){let t,e,i,s;if(this.logger.debug("Hard resetting with watchdog timer..."),this.chipFamily===w)t=1061191852,e=1061191828,i=1061191832,s=1356348065;else if(this.chipFamily===m)t=1610645680,e=1610645656,i=1610645660,s=1356348065;else if(this.chipFamily===y)t=1610645672,e=1610645648,i=1610645652,s=1356348065;else if(this.chipFamily===S||this.chipFamily===v)t=1611340824,e=1611340800,i=1611340804,s=1356348065;else{if(this.chipFamily!==C)throw new Error(`rtcWdtResetChipSpecific() is not supported for ${this.chipFamily}`);t=1343315992,e=1343315968,i=1343315972,s=1356348065}await this.writeRegister(t,s,void 0,0),await this.writeRegister(i,2e3,void 0,0);await this.writeRegister(e,-805306110,void 0,0),await this.writeRegister(t,0,void 0,0),await this.sleep(500)}async tryUsbWdtReset(t){return await this.detectUsbConnectionType()?(await this.rtcWdtResetChipSpecific(),this.logger.debug(`${t}: RTC WDT reset (USB-JTAG/Serial or USB-OTG detected)`),!0):(await this.hardResetClassic(),this.logger.debug("Classic reset."),!1)}async hardReset(t=!1){if(this._consoleMode)return t?void this.logger.debug("Skipping bootloader reset - device is in console mode"):(this.logger.debug("Performing hardware reset (console mode)..."),await this.hardResetToFirmware(),void this.logger.debug("Hardware reset complete"));if(t)4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.debug("USB-JTAG/Serial reset.")):(await this.hardResetClassic(),this.logger.debug("Classic reset."));else{if(this.logger.debug("*** Performing WDT reset strategy ***"),this.chipFamily===w){if(await this.tryUsbWdtReset("ESP32-S2"))return}else if(this.chipFamily===C){if(await this.tryUsbWdtReset("ESP32-P4"))return}else if(this.chipFamily===S){if(await this.tryUsbWdtReset("ESP32-C5"))return}else if(this.chipFamily===v){if(await this.tryUsbWdtReset("ESP32-C6"))return}this.isWebUSB()?(await this.setRTSWebUSB(!0),await this.sleep(200),await this.setRTSWebUSB(!1),await this.sleep(200),this.logger.debug("Hard reset (WebUSB).")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.debug("Hard reset."))}await new Promise(t=>setTimeout(t,1e3))}macAddr(){const t=new Array(6).fill(0),e=this._efuses[0],i=this._efuses[1],s=this._efuses[2],a=this._efuses[3];let r;if(this.chipFamily==_){if(0!=a)r=[a>>16&255,a>>8&255,255&a];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");r=[172,208,116]}else r=[24,254,52];t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==p)t[0]=s>>8&255,t[1]=255&s,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=v&&this.chipFamily!=R&&this.chipFamily!=B&&this.chipFamily!=U&&this.chipFamily!=I&&this.chipFamily!=C&&this.chipFamily!=x)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=e>>24&255,t[3]=e>>16&255,t[4]=e>>8&255,t[5]=255&e}return t}async readRegister(t){this.debug&&this.logger.debug("Reading from Register "+s(t,8));const e=Je("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){const r=async()=>{a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,a);if(null===n)throw new Error("Didn't get enough status bytes");let o=n,h=0;if(this.IS_STUB||this.chipFamily==_?h=2:[p,w,m,b,y,S,v,R,B,U,I,C,x].includes(this.chipFamily)||20===t?h=4:[2,4].includes(o.length)?h=o.length:(h=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${s(t)}, data.length: ${o.length})`)),o.length<h)throw new Error("Didn't get enough status bytes");const l=o.slice(-h,o.length);if(o=o.slice(0,-h),this.debug&&(this.logger.debug("status",l),this.logger.debug("value",r),this.logger.debug("data",o)),1==l[0])throw 5==l[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+s(t))):new Error("Command failure error code "+s(l[1]));return[r,o]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...Je("<BBHI",0,e,i.length,s),...i]);this.debug&&this.logger.debug(`Writing ${a.length} byte${1==a.length?"":"s"}:`,a),await this.writeToStream(a)}async readPacket(t){let e=null,r=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new $("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){if(Date.now()-n>t){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}const a=this._readByte();if(null===e){if(a!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(a)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid head of packet ("+s(a)+")");e=[]}else if(r)if(r=!1,a==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(a!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(a)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid SLIP escape (0xdb, "+s(a)+")");e.push(this.SLIP_ESC)}else if(a==this.SLIP_ESC)r=!0;else{if(a==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(a)}}else await a(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new $("Operation abandoned (reset strategy timeout)");const o=Date.now();for(n=[];Date.now()-o<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await a(1)}if(0==n.length){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+i(n));for(const t of n)if(null===e){if(t!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid head of packet ("+s(t)+")");e=[]}else if(r)if(r=!1,t==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(t!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid SLIP escape (0xdb, "+s(t)+")");e.push(this.SLIP_ESC)}else if(t==this.SLIP_ESC)r=!0;else{if(t==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}}}async getResponse(t,e=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(e);if(i.length<8)continue;const[a,r,,n]=je("<BBHI",i.slice(0,8));if(1!=a)continue;const o=i.slice(8);if(null==t||r==t)return[n,o];if(0!=o[0]&&5==o[1])throw await this.drainInputBuffer(200),new Error(`Invalid (unsupported) command ${s(t)}`)}throw new Error("Response doesn't match request")}checksum(t,e=239){for(const i of t)e^=i;return e}async getC5CrystalFreqRomExpect(){return(2130706432&await this.readRegister(1611227408))>>>24}async getC5CrystalFreqDetected(){const t=1048575&await this.readRegister(1610612756),e=o*t/1e6;return e>45?48:e>33?40:26}async setBaudrateC5Rom(t){const e=await this.getC5CrystalFreqRomExpect(),i=await this.getC5CrystalFreqDetected();this.logger.log(`ROM expects crystal freq: ${e} MHz, detected ${i} MHz.`);let s=t;48===i&&40===e?s=Math.trunc(40*t/48):40===i&&48===e&&(s=Math.trunc(48*t/40)),this.logger.log(`Changing baud rate to ${s}...`);try{const t=Je("<II",s,0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${s}: No response from set baud rate command.`)}this.logger.log("Changed.")}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==S)try{const e=Je("<II",t,this.IS_STUB?o:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}else await this.setBaudrateC5Rom(t);this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(E),this._parent?this._parent.currentBaudRate=t:this.currentBaudRate=t;const i=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;i&&t>i&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${i})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;this._isReconfiguring=!0;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this.isWebUSB()){const e=this.port.getInfo(),i=6790===e.usbVendorId&&21971===e.usbProductId;if(!i&&"function"==typeof this.port.setBaudRate)return await this.port.setBaudRate(t),void await a(100)}if(this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconfigure: ${t}`)}this._writer=void 0}await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(t){}finally{this._isReconfiguring=!1}}async syncWithTimeout(t){const e=Date.now();for(let i=0;i<5;i++){if(Date.now()-e>t)return!1;if(this._abandonCurrentOperation)return!1;this._clearInputBuffer();try{if(await this._sync())return await a(E),!0}catch(t){if(this._abandonCurrentOperation)return!1}await a(E)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await a(E),!0;await a(E)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,f);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,E);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){this.debug&&this.logger.debug(`Sync attempt ${t+1} failed: ${e}`)}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,a=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],a=e[2],r=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(r)}`)}const r=t.byteLength;let n,o=0,h=T;a?(n=Ze(new Uint8Array(t),{level:9}).buffer,o=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${o}`),h=await this.flashDeflBegin(r,o,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],d=0,c=0,u=0;const g=Date.now(),f=this.getFlashWriteSize(),_=a?o:r;for(;_-u>0;)this.debug&&this.logger.log(`Writing at ${s(i+d*f,8)} `),_-u>=f?l=Array.from(new Uint8Array(n,u,f)):(l=Array.from(new Uint8Array(n,u,_-u)),a||(l=l.concat(new Array(f-l.length).fill(255)))),a?await this.flashDeflBlock(l,d,h):await this.flashBlock(l,d),d+=1,c+=a?Math.round(l.length*r/o):l.length,u+=f,e(Math.min(c,r),r);this.logger.log("Took "+(Date.now()-g)+"ms to write "+_+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),a?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[p,w,m,b,y,S,v,R,B,U,I,C,x].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=_||this.IS_STUB?t:this.getEraseSize(e,t);const o=this.IS_STUB?T:M(O,t),h=Date.now();let l=Je("<IIII",a,n,r,e);return this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=v&&this.chipFamily!=R&&this.chipFamily!=B&&this.chipFamily!=U&&this.chipFamily!=I&&this.chipFamily!=C&&this.chipFamily!=x||(l=l.concat(Je("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+n+", block size "+s(r,4)+", offset "+s(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,l,0,o),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-h)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(t=0,e=0,i=0){const s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),r=Math.floor((t+s-1)/s);let n=0,o=0;this.IS_STUB?(n=t,o=M(O,n)):(n=r*s,o=T);const h=Je("<IIII",n,a,s,i);return await this.checkCommand(16,h,0,o),o}async flashFinish(){const t=Je("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=Je("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return z(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(t,e,i=4294967295,s=0,a=0){let r=Je("<IIII",t,e,i,s);a>0&&(r=r.concat(Je("<IIII",z(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const s=t.regBase+t.mosiDlenOffs,a=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(s,e-1),i>0&&await this.writeRegister(a,i-1)}else{const s=t.regBase+t.usr1Offs,a=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(s,a)}}async waitDone(t,e){for(let i=0;i<10;i++){if(0==(await this.readRegister(t)&e))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(t,e,i=0){const a=z(this.getChipFamily()),r=a.regBase,n=r,o=r+a.usrOffs,h=r+a.usr2Offs,l=r+a.w0Offs,d=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(e.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const c=8*e.length,u=await this.readRegister(o),g=await this.readRegister(h);let f=1<<31;if(i>0&&(f|=268435456),c>0&&(f|=134217728),await this.setDataLengths(a,c,i),await this.writeRegister(o,f),await this.writeRegister(h,7<<28|t),0==c)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=je("I".repeat(Math.floor(e.length/4)),e);let a=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${s(t)} to register offset ${s(a)}`),await this.writeRegister(a,t),a+=4}await this.writeRegister(n,d),await this.waitDone(n,d);const _=await this.readRegister(l);return await this.writeRegister(o,u),await this.writeRegister(h,g),_}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${s(t)}`),this.logger.log(`Flash Manufacturer: ${e.toString(16)}`),this.logger.log(`Flash Device: ${(t>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=r[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=n,s=Math.floor((e+i-1)/i);let a=16-Math.floor(t/i)%16;return s<a&&(a=s),s<2*a?Math.floor((s+1)/2*i):(s-a)*i}async memBegin(t,e,i,s){return await this.checkCommand(5,Je("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?T:500,i=Je("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){this.logger.debug(`Loading stub for ${this.chipName}, revision: ${this.chipRevision}`);const e=await A(this.chipFamily,this.chipRevision);if(null===e)return this.logger.log(`Stub flasher is not yet supported on ${this.chipName}, using ROM loader`),this;const i=2048;this.logger.log("Uploading stub...");for(const t of["text","data"]){const s=e[t],a=e[`${t}_start`],r=s.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,a);for(const t of Array(n).keys()){const e=t*i;let a=e+i;a>r&&(a=r),await this.memBlock(s.slice(e,a),t)}}await this.memFinish(e.entry);const s=await this.readPacket(500),a=String.fromCharCode(...s);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");const r=new Ye(this.port,this.logger,this);return t||await r.detectFlashSize(),r}get _reader(){return this._parent?this._parent._reader:this.__reader}set _reader(t){this._parent?this._parent._reader=t:this.__reader=t}get _writer(){return this._parent?this._parent._writer:this.__writer}set _writer(t){this._parent?this._parent._writer=t:this.__writer=t}get _writeChain(){return this._parent?this._parent._writeChain:this.__writeChain}set _writeChain(t){this._parent?this._parent._writeChain=t:this.__writeChain=t}async writeToStream(t){if(this.port.writable){if(this._isReconfiguring)throw new Error("Cannot write during port reconfiguration");this._writeChain=this._writeChain.then(async()=>{if(!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.error(`Failed to get writer: ${t}`),t}await this._writer.write(new Uint8Array(t))},async()=>{if(this.logger.debug("Previous write failed, attempting recovery for current write"),!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.debug(`Failed to get writer in recovery: ${t}`),new Error("Cannot acquire writer lock")}await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch{}this._writer=void 0}throw t}),await this._writeChain}else this.logger.debug("Port writable stream not available, skipping write")}async getUsbMode(){var t,e;const i=this._parent?this._parent.chipFamily:this.chipFamily,s=this._parent?null!==(t=this._parent.chipRevision)&&void 0!==t?t:0:null!==(e=this.chipRevision)&&void 0!==e?e:0;let a=null,r=null,n=null;switch(i){case w:a=1073741076,n=2;break;case m:a=1070526796,r=4,n=3;break;case y:a=(s<101?1070461028:1070461024)+24,r=3;break;case S:a=1082520852,r=3;break;case v:a=1082652032,r=3;break;case R:a=s<=200?1082455532:1082455524,r=s<=200?3:4;break;case B:a=1082457852,r=3;break;case U:a=1082652032,r=3;break;case C:a=s<300?1341390536:1341914824,r=6,n=5}if(null===a)return{mode:"uart",uartNo:0};const o=255&await this.readRegister(a);return null!==n&&o===n?(this.logger.debug(`USB mode: USB-OTG (uartNo=${o})`),{mode:"usb-otg",uartNo:o}):null!==r&&o===r?(this.logger.debug(`USB mode: USB-JTAG/Serial (uartNo=${o})`),{mode:"usb-jtag-serial",uartNo:o}):(this.logger.debug(`USB mode: UART (uartNo=${o})`),{mode:"uart",uartNo:o})}async disconnect(){if(this._parent)await this._parent.disconnect();else if(this.port.writable){try{await this._writeChain}catch(t){}if(this._writer){try{await this._writer.close(),this._writer.releaseLock()}catch(t){}this._writer=void 0}else try{const t=this.port.writable.getWriter();await t.close(),t.releaseLock()}catch(t){}await new Promise(t=>{if(!this._reader)return void t(void 0);const e=setTimeout(()=>{this.logger.debug("Disconnect timeout - forcing resolution"),t(void 0)},1e3);this.addEventListener("disconnect",()=>{clearTimeout(e),t(void 0)},{once:!0});try{this._reader.cancel()}catch(i){clearTimeout(e),t(void 0)}}),this.connected=!1;try{await this.port.close(),this.logger.debug("Port closed successfully")}catch(t){this.logger.debug(`Port close error: ${t}`)}}}async releaseReaderWriter(){if(this._parent)await this._parent.releaseReaderWriter();else{try{await this._writeChain}catch(t){}if(this._writer){try{this._writer.releaseLock(),this.logger.debug("Writer released")}catch(t){this.logger.debug(`Writer release error: ${t}`)}this._writer=void 0}if(this._reader){const t=this._reader;try{this._suppressDisconnect=!0,await t.cancel(),this.logger.debug("Reader cancelled")}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}finally{try{t.releaseLock()}catch(t){this.logger.debug(`Reader release error: ${t}`)}}this._reader===t&&(this._reader=void 0)}}}async resetToFirmware(){return await this._resetToFirmwareIfNeeded()}async detectUsbConnectionType(){const t=this.port.getInfo(),e=t.usbProductId;if(!(12346===t.usbVendorId))return this.logger.debug("Not Espressif VID - external serial chip"),!1;const i=[2,18,4097].includes(e||0);return this.logger.debug(`USB-JTAG/OTG detection: ${i?"YES":"NO"} (PID=0x${null==e?void 0:e.toString(16)})`),i}async enterConsoleMode(){if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - port selection needed"),!0;let t;try{t=await this.detectUsbConnectionType(),this.logger.debug("USB connection type detected: "+(t?"USB-JTAG/OTG":"External Serial Chip")),this._isUsbJtagOrOtg=t}catch(e){if(void 0===this.isUsbJtagOrOtg)throw new Error(`Cannot enter console mode: USB connection type unknown and detection failed: ${e}`);this._consoleMode=!1,this.logger.debug(`USB detection failed, using cached value: ${this.isUsbJtagOrOtg}`),t=this.isUsbJtagOrOtg}if(t){return await this._resetToFirmwareIfNeeded()}try{await this.releaseReaderWriter(),await this.sleep(100)}catch(t){this.logger.debug(`Failed to release locks: ${t}`)}try{await this.hardReset(!1),this.logger.log("Device reset to firmware mode")}catch(t){this.logger.debug(`Could not reset device: ${t}`)}if(this.isWebUSB())try{await this.port.recreateStreams(),this.logger.debug("WebUSB streams recreated for console mode")}catch(t){this._consoleMode=!1,this.logger.debug(`Failed to recreate WebUSB streams: ${t}`)}return this._consoleMode=!0,!1}async _clearForceDownloadBootIfNeeded(){try{let t,e,i;if(this.chipFamily===w)t=1061191976,e=1,i="ESP32-S2";else if(this.chipFamily===m)t=1610645804,e=1,i="ESP32-S3";else{if(this.chipFamily!==C)return!1;t=1343291400,e=4,i="ESP32-P4"}const s=await this.readRegister(t);this.logger.debug(`${i} force download boot register: 0x${s.toString(16)} (mask: 0x${e.toString(16)})`);return 0!==(s&e)?(this.logger.debug(`${i} force download boot flag is SET - clearing it`),await this.writeRegister(t,0,e,0),this.logger.debug(`${i} force download boot flag cleared`),!0):(this.logger.debug(`${i} force download boot flag is already CLEAR - no action needed`),!1)}catch(t){return this.logger.debug(`Error checking/clearing force download flag: ${t}`),!1}}async _resetToFirmwareIfNeeded(){try{if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - assuming device is already in firmware mode"),!1;const t=await this.detectUsbConnectionType();if(t){if(this.IS_STUB){if(this.logger.debug("On stub - need to get back to ROM to check flag"),this.currentBaudRate!==o){this.logger.debug(`Changing baudrate from ${this.currentBaudRate} to 115200 for ROM`);try{await this.reconfigurePort(o),this.currentBaudRate=o}catch(t){this.logger.debug(`Baudrate change failed: ${t}`)}}this.logger.debug("Resetting to bootloader (ROM)...");try{await this.hardReset(!0),await a(200),await this.sync(),this.logger.debug("Now on ROM after reset"),this.IS_STUB=!1}catch(t){return this.logger.debug(`Reset to ROM failed: ${t}`),this.logger.debug("Assuming device is already in firmware mode"),await this.releaseReaderWriter(),!1}}else this.logger.debug("Already on ROM - checking force download flag");await this._clearForceDownloadBootIfNeeded()?this.logger.debug("Force download flag was cleared - device will boot to firmware after reset"):this.logger.debug("Force download flag already clear - device will boot to firmware after reset"),await this.hardReset(!1);return this.chipFamily===w&&t||this.chipFamily===C&&t?(await this.releaseReaderWriter(),this.logger.log(`${this.chipName} USB-OTG: Port will change after WDT reset`),this.logger.log("Please select the new port for console mode"),this.dispatchEvent(new CustomEvent("usb-otg-port-change",{detail:{chipName:this.chipName,message:`${this.chipName} USB port changed after reset. Please select the new port.`,reason:"wdt-reset-to-firmware"}})),!0):(await this.releaseReaderWriter(),!1)}}catch(t){this.logger.debug(`Could not reset device to firmware mode: ${t}`)}return!1}async reconnect(){if(this._parent)await this._parent.reconnect();else try{this.logger.log("Reconnecting serial port...");const t=this.currentBaudRate;this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.debug("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:o}),this.connected=!0,this.currentBaudRate=o}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1;const e=this.chipFamily,i=this.chipName,s=this.chipRevision,a=this.chipVariant,r=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=e,this.chipName=i,this.chipRevision=s,this.chipVariant=a,this.flashSize=r,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");this.chipFamily===C&&301===this.chipRevision&&await this.powerOnFlash();const n=await this.runStub(!0);if(this.logger.debug("Stub loaded"),t!==o&&(await n.setBaudrate(t),!this.port.writable||!this.port.readable))throw new Error(`Port not ready after baudrate change (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this.IS_STUB=!0,this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async reconnectToBootloader(){if(this._parent)await this._parent.reconnectToBootloader();else try{this.logger.log("Reconnecting to bootloader mode..."),this._consoleMode=!1,this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.debug("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:o}),this.connected=!0,this.currentBaudRate=o}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1,this.__chipFamily=void 0,this.chipName="Unknown Chip",this.chipRevision=null,this.chipVariant=null,this.IS_STUB=!1,this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await a(100),await this.connectWithResetStrategies(),await this.detectChip(),this.logger.log(`Reconnected to bootloader: ${this.chipName}`)}catch(t){throw this._isReconfiguring=!1,t}}async exitConsoleMode(){if(this._parent)return await this._parent.exitConsoleMode();this._consoleMode=!1;const t=this.chipFamily===w||this.chipFamily===C;let e=this._isUsbJtagOrOtg;if(t&&void 0===e)try{e=await this.detectUsbConnectionType()}catch(t){this.logger.debug(`USB detection failed, assuming USB-JTAG/OTG for ${this.chipName}: ${t}`),e=!0}if(t&&e){this.logger.log(`${this.chipName} USB: Resetting to bootloader mode`);try{await this.hardResetClassic(),this.logger.debug("Reset to bootloader initiated")}catch(t){this.logger.debug(`Reset error: ${t}`)}return await a(500),this.logger.log(`${this.chipName}: Port changed. Please select the bootloader port.`),this.dispatchEvent(new CustomEvent("usb-otg-port-change",{detail:{chipName:this.chipName,message:`${this.chipName}: Port changed. Please select the bootloader port.`,reason:"exit-console-to-bootloader"}})),!0}return await this.reconnectToBootloader(),!1}isConsoleResetSupported(){if(this._parent)return this._parent.isConsoleResetSupported();return!(this.chipFamily===w&&(!0===this._isUsbJtagOrOtg||void 0===this._isUsbJtagOrOtg))}async resetInConsoleMode(){if(this._parent)return await this._parent.resetInConsoleMode();if(this.isConsoleResetSupported())try{this.logger.debug("Resetting device in console mode"),await this.hardResetToFirmware(),this.logger.debug("Device reset complete")}catch(t){throw this.logger.error(`Reset failed: ${t}`),t}else this.logger.debug("Console reset not supported for ESP32-S2 USB-JTAG/CDC")}async drainInputBuffer(t=200){await a(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBufferAvailable>0){void 0!==this._readByte()&&e++}else await a(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0)}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),await a(E),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s,r){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");let n;await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`),this.isWebUSB()&&(this._isCDCDevice?(this._adaptiveBlockMultiplier=8,this._adaptiveMaxInFlightMultiplier=8,this._consecutiveSuccessfulChunks=0,this.logger.debug(`CDC device - Initialized: blockMultiplier=${this._adaptiveBlockMultiplier}, maxInFlightMultiplier=${this._adaptiveMaxInFlightMultiplier}`)):(this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0,this.logger.debug("Non-CDC device - Fixed values: blockSize=31, maxInFlight=31"))),void 0!==(null==r?void 0:r.chunkSize)?(n=r.chunkSize,this.logger.log(`Using custom chunk size: 0x${n.toString(16)} bytes`)):n=this.isWebUSB()?16384:262144;let o=new Uint8Array(0),h=e,l=i;for(;l>0;){const e=Math.min(n,l);let d=!1,c=0;const u=5;let g=!1;for(;!d&&c<=u;){let i=new Uint8Array(0),s=0;try{let n,l;if(0===c&&this.logger.debug(`Reading chunk at 0x${h.toString(16)}, size: 0x${e.toString(16)}`),void 0!==(null==r?void 0:r.blockSize)&&void 0!==(null==r?void 0:r.maxInFlight))n=r.blockSize,l=r.maxInFlight,0===c&&this.logger.debug(`Using custom parameters: blockSize=${n}, maxInFlight=${l}`);else if(this.isWebUSB()){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2);n=e*this._adaptiveBlockMultiplier,l=e*this._adaptiveMaxInFlightMultiplier}else{const t=63;n=65*t,l=130*t}const u=Je("<IIII",h,e,n,l),[g]=await this.checkCommand(210,u);if(0!=g)throw new Error("Failed to read memory: "+g);for(;i.length<e;){let r;try{r=await this.readPacket(100)}catch(t){if(t instanceof $){this.logger.debug(`SLIP read error at ${i.length} bytes: ${t.message}`);try{const t=[this.SLIP_END,this.SLIP_END];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await a(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(r&&r.length>0){const a=new Uint8Array(r),n=new Uint8Array(i.length+a.length);n.set(i),n.set(a,i.length),i=n;if(i.length>=e||i.length>=s+l){const e=Je("<I",i.length),a=t(e);await this.writeToStream(a),s=i.length}}}const f=new Uint8Array(o.length+i.length);if(f.set(o),f.set(i,o.length),o=f,d=!0,this.isWebUSB()&&this._isCDCDevice&&0===c&&(this._consecutiveSuccessfulChunks++,this._consecutiveSuccessfulChunks>=2)){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=8,s=8;let a=!1;if(this._adaptiveBlockMultiplier<i?(this._adaptiveBlockMultiplier=Math.min(2*this._adaptiveBlockMultiplier,i),a=!0):this._adaptiveMaxInFlightMultiplier<s&&(this._adaptiveMaxInFlightMultiplier=Math.min(2*this._adaptiveMaxInFlightMultiplier,s),a=!0),a){const t=e*this._adaptiveBlockMultiplier,i=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Speed increased: blockSize=${t}, maxInFlight=${i}`),this._lastAdaptiveAdjustment=Date.now()}this._consecutiveSuccessfulChunks=0}}catch(t){if(c++,this.isWebUSB()&&this._isCDCDevice&&1===c)if(this._adaptiveBlockMultiplier>1||this._adaptiveMaxInFlightMultiplier>1){this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0;const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=e*this._adaptiveBlockMultiplier,s=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Error at higher speed - reduced to minimum: blockSize=${i}, maxInFlight=${s}`)}else this.logger.debug("Error at minimum speed (blockSize=31, maxInFlight=31) - not a speed issue");if(!(t instanceof $))throw t;if(c<=u){this.logger.debug(`${t.message} at 0x${h.toString(16)}. Draining buffer and retrying (attempt ${c}/${u})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await a(E)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(g)throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${u} retries and recovery attempt`);g=!0,this.logger.log(`All retries exhausted at 0x${h.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),c=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${u} retries and recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),o.length,i),h+=e,l-=e,this.logger.debug(`Total progress: 0x${o.length.toString(16)} from 0x${i.toString(16)} bytes`)}return o}}class Ye extends qe{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await A(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,o=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(o,8)}`),this.logger.debug(`Stub data: ${s(r.data_start,8)}, len: ${r.data.length}, text: ${s(r.text_start,8)}, len: ${r.text.length}`);for(const[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&o>t)throw new Error("Software loader is resident at "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(n,8)+"-"+s(o,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,D)}async eraseRegion(t,e){if(t<0)throw new Error(`Invalid offset: ${t} (must be non-negative)`);if(e<0)throw new Error(`Invalid size: ${e} (must be non-negative)`);if(0===e)return void this.logger.log("eraseRegion: size is 0, skipping erase");if(t%n!==0)throw new Error(`Offset ${t} (0x${t.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);if(e%n!==0)throw new Error(`Size ${e} (0x${e.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);const i=4294967295;if(t>i)throw new Error(`Offset ${t} exceeds maximum value 4294967295`);if(e>i)throw new Error(`Size ${e} exceeds maximum value 4294967295`);if(t+e>i)throw new Error(`Region end (offset + size = ${t+e}) exceeds maximum addressable range 4294967295`);const s=M(O,e),a=Je("<II",t,e);await this.checkCommand(209,a,0,s)}}const Ke=async t=>{if(import("./install-dialog-HRJeEoXW.js"),(()=>{const t=navigator.userAgent||"";return/Android/i.test(t)})()&&"usb"in navigator)try{await(async()=>{if(!globalThis.requestSerialPort)return new Promise((t,e)=>{const i=document.createElement("script");i.type="module",i.src="https://unpkg.com/tasmota-webserial-esptool/js/webusb-serial.js",i.onload=()=>{globalThis.requestSerialPort?t():e(new Error("WebUSB serial script loaded but requestSerialPort not found"))},i.onerror=()=>e(new Error("Failed to load WebUSB serial script")),document.head.appendChild(i)})})()}catch(t){return void alert(`Failed to load WebUSB support: ${t.message}`)}let e;try{e=await(async t=>{let e;const i=globalThis.requestSerialPort;if("function"==typeof i)e=await i();else{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser. Please use Chrome, Edge, or Opera on desktop, or Chrome on Android. Note: The page must be served over HTTPS or localhost.");e=await navigator.serial.requestPort()}return e.readable&&e.writable||await e.open({baudRate:o}),new qe(e,t)})({log:()=>{},debug:()=>{},error:t=>console.error(t)})}catch(e){return"NotFoundError"===e.name?void import("./index-DUmRg0Cu.js").then(e=>e.openNoPortPickedDialog(()=>Ke(t))):void alert(`Connection failed: ${e.message}`)}if(!e)return void alert("Failed to connect to device");const i=document.createElement("ewt-install-dialog");i.esploader=e,i.manifestPath=t.manifest||t.getAttribute("manifest"),i.overrides=t.overrides,i.firmwareFile=t.firmwareFile;const s=t.getAttribute("baud-rate");if(s){const t=parseInt(s,10);isNaN(t)||(i.baudRate=t)}else void 0!==t.baudRate&&(i.baudRate=t.baudRate);i.addEventListener("closed",async()=>{try{await e.disconnect()}catch(t){}},{once:!0}),document.body.appendChild(i)},Xe="https://cors-proxy.espressif.tools",Qe=async(t,e)=>{if((t=>{try{const e=new URL(t),i=window.location.origin;return e.origin!==i&&"file:"!==e.protocol}catch{return!1}})(t=t.trim())){if(t.includes("github.com")&&t.includes("/releases/download/")){const i=`${Xe}/?url=${encodeURIComponent(t)}`,{headers:s,credentials:a,...r}=null!=e?e:{};return fetch(i,r)}try{return await fetch(t,e)}catch(i){try{const i=`${Xe}/?url=${encodeURIComponent(t)}`,{headers:s,credentials:a,...r}=null!=e?e:{};return await fetch(i,r)}catch(t){throw i}}}return fetch(t,e)};window.espWebToolsCorsProxyFetch=Qe;class ti extends HTMLElement{attributeChangedCallback(t,e,i){if("baud-rate"===t&&i!==e)if(i){const t=parseInt(i,10);this.baudRate=Number.isNaN(t)?void 0:t}else this.baudRate=void 0}connectedCallback(){if(this.renderRoot)return;if(this.renderRoot=this.attachShadow({mode:"open"}),!ti.isSupported||!ti.isAllowed)return this.toggleAttribute("install-unsupported",!0),void(this.renderRoot.innerHTML=ti.isAllowed?"<slot name='unsupported'>Your browser does not support installing things on ESP devices. Use Google Chrome or Microsoft Edge (Desktop) or Chrome on Android with USB OTG.</slot>":"<slot name='not-allowed'>You can only install ESP devices on HTTPS websites or on the localhost.</slot>");this.toggleAttribute("install-supported",!0);const t=document.createElement("slot");t.addEventListener("click",async t=>{t.preventDefault(),Ke(this)}),t.name="activate";const e=document.createElement("button");if(e.innerText="Connect",t.append(e),"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype){const t=new CSSStyleSheet;t.replaceSync(ti.style),this.renderRoot.adoptedStyleSheets=[t]}else{const t=document.createElement("style");t.innerText=ti.style,this.renderRoot.append(t)}this.renderRoot.append(t)}}ti.isSupported="serial"in navigator||"usb"in navigator,ti.isAllowed=window.isSecureContext,ti.observedAttributes=["baud-rate"],ti.style='\n button {\n position: relative;\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n padding: 10px 24px;\n color: var(--esp-tools-button-text-color, #fff);\n background-color: var(--esp-tools-button-color, #03a9f4);\n border: none;\n border-radius: var(--esp-tools-button-border-radius, 9999px);\n }\n button::before {\n content: " ";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n opacity: 0.2;\n border-radius: var(--esp-tools-button-border-radius, 9999px);\n }\n button:hover::before {\n background-color: rgba(255,255,255,.8);\n }\n button:focus {\n outline: none;\n }\n button:focus::before {\n background-color: white;\n }\n button:active::before {\n background-color: grey;\n }\n :host([active]) button {\n color: rgba(0, 0, 0, 0.38);\n background-color: rgba(0, 0, 0, 0.12);\n box-shadow: none;\n cursor: unset;\n pointer-events: none;\n }\n improv-wifi-launch-button {\n display: block;\n margin-top: 16px;\n }\n .hidden {\n display: none;\n }',customElements.define("esp-web-install-button",ti);export{_ as C,C as a,B as b,R as c,v as d,S as e,y as f,b as g,m as h,w as i,p as j,Qe as k};
|
|
@@ -1142,14 +1142,14 @@ import{e,i as t,_ as i,n as r,m as o,a as s,b as a,r as l,c as n,d,f as c,g as h
|
|
|
1142
1142
|
name="password"
|
|
1143
1143
|
type="password"
|
|
1144
1144
|
></ew-filled-text-field>
|
|
1145
|
-
<ew-text-button slot="actions" @click=${this._doProvision}
|
|
1146
|
-
>Connect</ew-text-button
|
|
1147
|
-
>
|
|
1148
1145
|
<ew-text-button
|
|
1149
1146
|
slot="actions"
|
|
1150
1147
|
@click=${async()=>{if(this._client)try{await this._closeClientWithoutEvents(this._client),this.logger.log("Improv client closed")}catch(e){this.logger.log("Failed to close Improv client:",e)}await this._releaseReaderWriter(),this.logger.log("Returning to dashboard (device stays in firmware mode)"),this._state="DASHBOARD"}}
|
|
1151
1148
|
>${this._installState&&this._installErase?"Skip":"Back"}</ew-text-button
|
|
1152
1149
|
>
|
|
1150
|
+
<ew-text-button slot="actions" @click=${this._doProvision}
|
|
1151
|
+
>Connect</ew-text-button
|
|
1152
|
+
>
|
|
1153
1153
|
`}else{t=void 0;const r=!this._wasProvisioned&&(void 0!==this._client.nextUrl||"home_assistant_domain"in this._manifest);i=r,e=u`
|
|
1154
1154
|
<ewt-page-message
|
|
1155
1155
|
.icon=${Hi}
|
|
@@ -1206,17 +1206,22 @@ import{e,i as t,_ as i,n as r,m as o,a as s,b as a,r as l,c as n,d,f as c,g as h
|
|
|
1206
1206
|
</label>
|
|
1207
1207
|
<ew-text-button
|
|
1208
1208
|
slot="actions"
|
|
1209
|
-
@click=${()=>{
|
|
1210
|
-
>
|
|
1209
|
+
@click=${()=>{this._state="DASHBOARD"}}
|
|
1210
|
+
>Back</ew-text-button
|
|
1211
1211
|
>
|
|
1212
1212
|
<ew-text-button
|
|
1213
1213
|
slot="actions"
|
|
1214
|
-
@click=${()=>{this.
|
|
1215
|
-
>
|
|
1214
|
+
@click=${()=>{const e=this.shadowRoot.querySelector("ew-checkbox");this._startInstall(e.checked)}}
|
|
1215
|
+
>Next</ew-text-button
|
|
1216
1216
|
>
|
|
1217
1217
|
`]}_renderInstall(){let e,t,i=!1;const r=!this._installErase&&this._isSameFirmware;if(!this._installConfirmed&&this._isSameVersion)e="Erase User Data",t=u`
|
|
1218
1218
|
Do you want to reset your device and erase all user data from your
|
|
1219
1219
|
device?
|
|
1220
|
+
<ew-text-button
|
|
1221
|
+
slot="actions"
|
|
1222
|
+
@click=${()=>{this._state="DASHBOARD"}}
|
|
1223
|
+
>Back</ew-text-button
|
|
1224
|
+
>
|
|
1220
1225
|
<ew-text-button
|
|
1221
1226
|
class="danger"
|
|
1222
1227
|
slot="actions"
|
|
@@ -1254,14 +1259,14 @@ import{e,i as t,_ as i,n as r,m as o,a as s,b as a,r as l,c as n,d,f as c,g as h
|
|
|
1254
1259
|
Do you want to ${i}
|
|
1255
1260
|
${this._manifest.name} ${this._manifest.version}?
|
|
1256
1261
|
${this._installErase?u`<br /><br />All data on the device will be erased.`:""}
|
|
1257
|
-
<ew-text-button slot="actions" @click=${this._confirmInstall}
|
|
1258
|
-
>Install</ew-text-button
|
|
1259
|
-
>
|
|
1260
1262
|
<ew-text-button
|
|
1261
1263
|
slot="actions"
|
|
1262
1264
|
@click=${()=>{this._state="DASHBOARD"}}
|
|
1263
1265
|
>Back</ew-text-button
|
|
1264
1266
|
>
|
|
1267
|
+
<ew-text-button slot="actions" @click=${this._confirmInstall}
|
|
1268
|
+
>Install</ew-text-button
|
|
1269
|
+
>
|
|
1265
1270
|
`}return[e,t,i,!1]}_renderLogs(){let e;return e=u`
|
|
1266
1271
|
<ew-console
|
|
1267
1272
|
.port=${this._port}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const t=t=>{let e=[192];for(const i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e.push(192),e},e=t=>{const e=[];for(let i=0;i<t.length;i++){const s=t.charCodeAt(i);s<=255&&e.push(s)}return e},i=t=>"["+t.map(t=>s(t)).join(", ")+"]",s=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},a=t=>new Promise(e=>setTimeout(e,t)),r={18:"256KB",19:"512KB",20:"1MB",21:"2MB",22:"4MB",23:"8MB",24:"16MB",25:"32MB",26:"64MB",27:"128MB",28:"256MB",32:"64MB",33:"128MB",34:"256MB",50:"256KB",51:"512KB",52:"1MB",53:"2MB",54:"4MB",55:"8MB",56:"16MB",57:"32MB",58:"64MB"},n=4096,o=115200,h=1610647552,l=1343410176,d=1343312316,c=1<<27,u=1343312312,g=1343312892,f=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),_=33382,p=50,w=12882,m=12883,b=12994,y=12995,S=12997,v=12998,R=207969,B=12914,U=12916,I=12917,C=12928,x=12849,k={5:{name:"ESP32-C3",family:y},9:{name:"ESP32-S3",family:m},12:{name:"ESP32-C2",family:b},13:{name:"ESP32-C6",family:v},16:{name:"ESP32-H2",family:B},18:{name:"ESP32-P4",family:C},20:{name:"ESP32-C61",family:R},23:{name:"ESP32-C5",family:S},25:{name:"ESP32-H21",family:I},28:{name:"ESP32-H4",family:U},32:{name:"ESP32-S31",family:x}},F={4293968129:{name:"ESP8266",family:_},15736195:{name:"ESP32",family:p},1990:{name:"ESP32-S2",family:w}},T=3e3,D=15e4,E=100,O=3e4,M=(t,e)=>{const i=Math.floor(t*(e/486));return i<T?T:i},z=t=>{switch(t){case p:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case w:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case m:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case _:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case b:return{regBase:1610620928,baseFuse:h,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case y:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case S:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case v:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case R:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case B:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case U:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case I:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case C:return{regBase:1342754816,baseFuse:l,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case x:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class $ extends Error{constructor(t){super(t),this.name="SlipReadError"}}const A=async(t,i)=>{let s;if(t==U||t==I||t==x)return null;if(t==p)s=await import("./esp32-BRKoi17y.js");else if(t==w)s=await import("./esp32s2-iX3WoDbg.js");else if(t==m)s=await import("./esp32s3-DGwDVIgz.js");else if(t==_)s=await import("./esp8266-CUwxJpGa.js");else if(t==b)s=await import("./esp32c2-Btgr_lwh.js");else if(t==y)s=await import("./esp32c3-CHKfoI8W.js");else if(t==S)s=await import("./esp32c5-BDW4KtLo.js");else if(t==v)s=await import("./esp32c6-il8tTxAG.js");else if(t==R)s=await import("./esp32c61-thKzxBGf.js");else if(t==B)s=await import("./esp32h2-CxoUHv_P.js");else{if(t!=C)return null;s=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")}return{...s,text:e(atob(s.text)),data:e(atob(s.data))}};function P(t){let e=t.length;for(;--e>=0;)t[e]=0}const W=256,L=286,N=30,H=15,V=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Z=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),G=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),J=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),j=new Array(576);P(j);const q=new Array(60);P(q);const Y=new Array(512);P(Y);const K=new Array(256);P(K);const X=new Array(29);P(X);const Q=new Array(N);function tt(t,e,i,s,a){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=a,this.has_stree=t&&t.length}let et,it,st;function at(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}P(Q);const rt=t=>t<256?Y[t]:Y[256+(t>>>7)],nt=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},ot=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,nt(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},ht=(t,e,i)=>{ot(t,i[2*e],i[2*e+1])},lt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},dt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=H;a++)n=n+i[a-1]<<1,s[a]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=lt(s[e]++,e))}},ct=t=>{let e;for(e=0;e<L;e++)t.dyn_ltree[2*e]=0;for(e=0;e<N;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},ut=t=>{t.bi_valid>8?nt(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},gt=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},ft=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&>(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!gt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},_t=(t,e,i)=>{let s,a,r,n,o=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+o++],s+=(255&t.pending_buf[t.sym_buf+o++])<<8,a=t.pending_buf[t.sym_buf+o++],0===s?ht(t,a,e):(r=K[a],ht(t,r+W+1,e),n=V[r],0!==n&&(a-=X[r],ot(t,a,n)),s--,r=rt(s),ht(t,r,i),n=Z[r],0!==n&&(s-=Q[r],ot(t,s,n)))}while(o<t.sym_next);ht(t,256,e)},pt=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=e.stat_desc.has_stree,r=e.stat_desc.elems;let n,o,h,l=-1;for(t.heap_len=0,t.heap_max=573,n=0;n<r;n++)0!==i[2*n]?(t.heap[++t.heap_len]=l=n,t.depth[n]=0):i[2*n+1]=0;for(;t.heap_len<2;)h=t.heap[++t.heap_len]=l<2?++l:0,i[2*h]=1,t.depth[h]=0,t.opt_len--,a&&(t.static_len-=s[2*h+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)ft(t,i,n);h=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ft(t,i,1),o=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=o,i[2*h]=i[2*n]+i[2*o],t.depth[h]=(t.depth[n]>=t.depth[o]?t.depth[n]:t.depth[o])+1,i[2*n+1]=i[2*o+1]=h,t.heap[1]=h++,ft(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,s=e.max_code,a=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,h=e.stat_desc.max_length;let l,d,c,u,g,f,_=0;for(u=0;u<=H;u++)t.bl_count[u]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)d=t.heap[l],u=i[2*i[2*d+1]+1]+1,u>h&&(u=h,_++),i[2*d+1]=u,d>s||(t.bl_count[u]++,g=0,d>=o&&(g=n[d-o]),f=i[2*d],t.opt_len+=f*(u+g),r&&(t.static_len+=f*(a[2*d+1]+g)));if(0!==_){do{for(u=h-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[h]--,_-=2}while(_>0);for(u=h;0!==u;u--)for(d=t.bl_count[u];0!==d;)c=t.heap[--l],c>s||(i[2*c+1]!==u&&(t.opt_len+=(u-i[2*c+1])*i[2*c],i[2*c+1]=u),d--)}})(t,e),dt(i,l,t.bl_count)},wt=(t,e,i)=>{let s,a,r=-1,n=e[1],o=0,h=7,l=4;for(0===n&&(h=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++o<h&&a===n||(o<l?t.bl_tree[2*a]+=o:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,r=a,0===n?(h=138,l=3):a===n?(h=6,l=3):(h=7,l=4))},mt=(t,e,i)=>{let s,a,r=-1,n=e[1],o=0,h=7,l=4;for(0===n&&(h=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++o<h&&a===n)){if(o<l)do{ht(t,a,t.bl_tree)}while(0!==--o);else 0!==a?(a!==r&&(ht(t,a,t.bl_tree),o--),ht(t,16,t.bl_tree),ot(t,o-3,2)):o<=10?(ht(t,17,t.bl_tree),ot(t,o-3,3)):(ht(t,18,t.bl_tree),ot(t,o-11,7));o=0,r=a,0===n?(h=138,l=3):a===n?(h=6,l=3):(h=7,l=4)}};let bt=!1;const yt=(t,e,i,s)=>{ot(t,0+(s?1:0),3),ut(t),nt(t,i),nt(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var St=(t,e,i,s)=>{let a,r,n=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<W;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),pt(t,t.l_desc),pt(t,t.d_desc),n=(t=>{let e;for(wt(t,t.dyn_ltree,t.l_desc.max_code),wt(t,t.dyn_dtree,t.d_desc.max_code),pt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*J[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=a&&(a=r)):a=r=i+5,i+4<=a&&-1!==e?yt(t,e,i,s):4===t.strategy||r===a?(ot(t,2+(s?1:0),3),_t(t,j,q)):(ot(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(ot(t,e-257,5),ot(t,i-1,5),ot(t,s-4,4),a=0;a<s;a++)ot(t,t.bl_tree[2*J[a]+1],3);mt(t,t.dyn_ltree,e-1),mt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),_t(t,t.dyn_ltree,t.dyn_dtree)),ct(t),s&&ut(t)},vt={_tr_init:t=>{bt||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(X[s]=i,t=0;t<1<<V[s];t++)K[i++]=s;for(K[i-1]=s,a=0,s=0;s<16;s++)for(Q[s]=a,t=0;t<1<<Z[s];t++)Y[a++]=s;for(a>>=7;s<N;s++)for(Q[s]=a<<7,t=0;t<1<<Z[s]-7;t++)Y[256+a++]=s;for(e=0;e<=H;e++)r[e]=0;for(t=0;t<=143;)j[2*t+1]=8,t++,r[8]++;for(;t<=255;)j[2*t+1]=9,t++,r[9]++;for(;t<=279;)j[2*t+1]=7,t++,r[7]++;for(;t<=287;)j[2*t+1]=8,t++,r[8]++;for(dt(j,287,r),t=0;t<N;t++)q[2*t+1]=5,q[2*t]=lt(t,5);et=new tt(j,V,257,L,H),it=new tt(q,Z,0,N,H),st=new tt(new Array(0),G,0,19,7)})(),bt=!0),t.l_desc=new at(t.dyn_ltree,et),t.d_desc=new at(t.dyn_dtree,it),t.bl_desc=new at(t.bl_tree,st),t.bi_buf=0,t.bi_valid=0,ct(t)},_tr_stored_block:yt,_tr_flush_block:St,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(K[i]+W+1)]++,t.dyn_dtree[2*rt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{ot(t,2,3),ht(t,256,j),(t=>{16===t.bi_valid?(nt(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var Rt=(t,e,i,s)=>{let a=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{a=a+e[s++]|0,r=r+a|0}while(--n);a%=65521,r%=65521}return a|r<<16};const Bt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var Ut=(t,e,i,s)=>{const a=Bt,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},It={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Ct={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:xt,_tr_stored_block:kt,_tr_flush_block:Ft,_tr_tally:Tt,_tr_align:Dt}=vt,{Z_NO_FLUSH:Et,Z_PARTIAL_FLUSH:Ot,Z_FULL_FLUSH:Mt,Z_FINISH:zt,Z_BLOCK:$t,Z_OK:At,Z_STREAM_END:Pt,Z_STREAM_ERROR:Wt,Z_DATA_ERROR:Lt,Z_BUF_ERROR:Nt,Z_DEFAULT_COMPRESSION:Ht,Z_FILTERED:Vt,Z_HUFFMAN_ONLY:Zt,Z_RLE:Gt,Z_FIXED:Jt,Z_DEFAULT_STRATEGY:jt,Z_UNKNOWN:qt,Z_DEFLATED:Yt}=Ct,Kt=258,Xt=262,Qt=42,te=113,ee=666,ie=(t,e)=>(t.msg=It[e],e),se=t=>2*t-(t>4?9:0),ae=t=>{let e=t.length;for(;--e>=0;)t[e]=0},re=t=>{let e,i,s,a=t.w_size;e=t.hash_size,s=e;do{i=t.head[--s],t.head[s]=i>=a?i-a:0}while(--e);e=a,s=e;do{i=t.prev[--s],t.prev[s]=i>=a?i-a:0}while(--e)};let ne=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const oe=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},he=(t,e)=>{Ft(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,oe(t.strm)},le=(t,e)=>{t.pending_buf[t.pending++]=e},de=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ce=(t,e,i,s)=>{let a=t.avail_in;return a>s&&(a=s),0===a?0:(t.avail_in-=a,e.set(t.input.subarray(t.next_in,t.next_in+a),i),1===t.state.wrap?t.adler=Rt(t.adler,e,a,i):2===t.state.wrap&&(t.adler=Ut(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},ue=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,o=t.nice_match;const h=t.strstart>t.w_size-Xt?t.strstart-(t.w_size-Xt):0,l=t.window,d=t.w_mask,c=t.prev,u=t.strstart+Kt;let g=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(a>>=2),o>t.lookahead&&(o=t.lookahead);do{if(i=e,l[i+n]===f&&l[i+n-1]===g&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do{}while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<u);if(s=Kt-(u-r),r=u-Kt,s>n){if(t.match_start=e,n=s,s>=o)break;g=l[r+n-1],f=l[r+n]}}}while((e=c[e&d])>h&&0!==--a);return n<=t.lookahead?n:t.lookahead},ge=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Xt)&&(t.window.set(t.window.subarray(e,e+e-s),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),re(t),s+=e),0===t.strm.avail_in)break;if(i=ce(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=ne(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=ne(t,t.ins_h,t.window[a+3-1]),t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Xt&&0!==t.strm.avail_in)},fe=(t,e)=>{let i,s,a,r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n=0,o=t.strm.avail_in;do{if(i=65535,a=t.bi_valid+42>>3,t.strm.avail_out<a)break;if(a=t.strm.avail_out-a,s=t.strstart-t.block_start,i>s+t.strm.avail_in&&(i=s+t.strm.avail_in),i>a&&(i=a),i<r&&(0===i&&e!==zt||e===Et||i!==s+t.strm.avail_in))break;n=e===zt&&i===s+t.strm.avail_in?1:0,kt(t,0,0,n),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,oe(t.strm),s&&(s>i&&(s=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+s),t.strm.next_out),t.strm.next_out+=s,t.strm.avail_out-=s,t.strm.total_out+=s,t.block_start+=s,i-=s),i&&(ce(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(0===n);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==Et&&e!==zt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(a=t.window_size-t.strstart,t.strm.avail_in>a&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(ce(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=r||(s||e===zt)&&e!==Et&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===zt&&0===t.strm.avail_in&&i===s?1:0,kt(t,t.block_start,i,n),t.block_start+=i,oe(t.strm)),n?3:1)},_e=(t,e)=>{let i,s;for(;;){if(t.lookahead<Xt){if(ge(t),t.lookahead<Xt&&e===Et)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Xt&&(t.match_length=ue(t,i)),t.match_length>=3)if(s=Tt(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ne(t,t.ins_h,t.window[t.strstart+1]);else s=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2},pe=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<Xt){if(ge(t),t.lookahead<Xt&&e===Et)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Xt&&(t.match_length=ue(t,i),t.match_length<=5&&(t.strategy===Vt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){a=t.strstart+t.lookahead-3,s=Tt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=a&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,s&&(he(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Tt(t,0,t.window[t.strstart-1]),s&&he(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(s=Tt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2};function we(t,e,i,s,a){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=a}const me=[new we(0,0,0,0,fe),new we(4,4,8,4,_e),new we(4,5,16,8,_e),new we(4,6,32,32,_e),new we(4,4,16,16,pe),new we(8,16,32,32,pe),new we(8,16,128,128,pe),new we(8,32,128,256,pe),new we(32,128,258,1024,pe),new we(32,258,258,4096,pe)];function be(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Yt,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),ae(this.dyn_ltree),ae(this.dyn_dtree),ae(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),ae(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ae(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const ye=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Qt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==te&&e.status!==ee?1:0},Se=t=>{if(ye(t))return ie(t,Wt);t.total_in=t.total_out=0,t.data_type=qt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Qt:te,t.adler=2===e.wrap?0:1,e.last_flush=-2,xt(e),At},ve=t=>{const e=Se(t);var i;return e===At&&((i=t.state).window_size=2*i.w_size,ae(i.head),i.max_lazy_match=me[i.level].max_lazy,i.good_match=me[i.level].good_length,i.nice_match=me[i.level].nice_length,i.max_chain_length=me[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},Re=(t,e,i,s,a,r)=>{if(!t)return Wt;let n=1;if(e===Ht&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==Yt||s<8||s>15||e<0||e>9||r<0||r>Jt||8===s&&1!==n)return ie(t,Wt);8===s&&(s=9);const o=new be;return t.state=o,o.strm=t,o.status=Qt,o.wrap=n,o.gzhead=null,o.w_bits=s,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=a+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<a+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=r,o.method=i,ve(t)};var Be={deflateInit:(t,e)=>Re(t,e,Yt,15,8,jt),deflateInit2:Re,deflateReset:ve,deflateResetKeep:Se,deflateSetHeader:(t,e)=>ye(t)||2!==t.state.wrap?Wt:(t.state.gzhead=e,At),deflate:(t,e)=>{if(ye(t)||e>$t||e<0)return t?ie(t,Wt):Wt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===ee&&e!==zt)return ie(t,0===t.avail_out?Nt:Wt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(oe(t),0===t.avail_out)return i.last_flush=-1,At}else if(0===t.avail_in&&se(e)<=se(s)&&e!==zt)return ie(t,Nt);if(i.status===ee&&0!==t.avail_in)return ie(t,Nt);if(i.status===Qt&&0===i.wrap&&(i.status=te),i.status===Qt){let e=Yt+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=Zt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=s<<6,0!==i.strstart&&(e|=32),e+=31-e%31,de(i,e),0!==i.strstart&&(de(i,t.adler>>>16),de(i,65535&t.adler)),t.adler=1,i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At}if(57===i.status)if(t.adler=0,le(i,31),le(i,139),le(i,8),i.gzhead)le(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),le(i,255&i.gzhead.time),le(i,i.gzhead.time>>8&255),le(i,i.gzhead.time>>16&255),le(i,i.gzhead.time>>24&255),le(i,9===i.level?2:i.strategy>=Zt||i.level<2?4:0),le(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(le(i,255&i.gzhead.extra.length),le(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=Ut(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(le(i,0),le(i,0),le(i,0),le(i,0),le(i,0),le(i,9===i.level?2:i.strategy>=Zt||i.level<2?4:0),le(i,3),i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At;if(69===i.status){if(i.gzhead.extra){let e=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,oe(t),0!==i.pending)return i.last_flush=-1,At;e=0,s-=a}let a=new Uint8Array(i.gzhead.extra);i.pending_buf.set(a.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>e&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),oe(t),0!==i.pending)return i.last_flush=-1,At;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,le(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),oe(t),0!==i.pending)return i.last_flush=-1,At;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,le(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(oe(t),0!==i.pending))return i.last_flush=-1,At;le(i,255&t.adler),le(i,t.adler>>8&255),t.adler=0}if(i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At}if(0!==t.avail_in||0!==i.lookahead||e!==Et&&i.status!==ee){let s=0===i.level?fe(i,e):i.strategy===Zt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(ge(t),0===t.lookahead)){if(e===Et)return 1;break}if(t.match_length=0,i=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Gt?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=Kt){if(ge(t),t.lookahead<=Kt&&e===Et)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=n[a],s===n[++a]&&s===n[++a]&&s===n[++a])){r=t.strstart+Kt;do{}while(s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&a<r);t.match_length=Kt-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Tt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2})(i,e):me[i.level].func(i,e);if(3!==s&&4!==s||(i.status=ee),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),At;if(2===s&&(e===Ot?Dt(i):e!==$t&&(kt(i,0,0,!1),e===Mt&&(ae(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),oe(t),0===t.avail_out))return i.last_flush=-1,At}return e!==zt?At:i.wrap<=0?Pt:(2===i.wrap?(le(i,255&t.adler),le(i,t.adler>>8&255),le(i,t.adler>>16&255),le(i,t.adler>>24&255),le(i,255&t.total_in),le(i,t.total_in>>8&255),le(i,t.total_in>>16&255),le(i,t.total_in>>24&255)):(de(i,t.adler>>>16),de(i,65535&t.adler)),oe(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?At:Pt)},deflateEnd:t=>{if(ye(t))return Wt;const e=t.state.status;return t.state=null,e===te?ie(t,Lt):At},deflateSetDictionary:(t,e)=>{let i=e.length;if(ye(t))return Wt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==Qt||s.lookahead)return Wt;if(1===a&&(t.adler=Rt(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(ae(s.head),s.strstart=0,s.block_start=0,s.insert=0);let t=new Uint8Array(s.w_size);t.set(e.subarray(i-s.w_size,i),0),e=t,i=s.w_size}const r=t.avail_in,n=t.next_in,o=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,ge(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=ne(s,s.ins_h,s.window[t+3-1]),s.prev[t&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=t,t++}while(--e);s.strstart=t,s.lookahead=2,ge(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,t.next_in=n,t.input=o,t.avail_in=r,s.wrap=a,At},deflateInfo:"pako deflate (from Nodeca project)"};const Ue=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ie=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)Ue(i,e)&&(t[e]=i[e])}}return t},Ce=t=>{let e=0;for(let i=0,s=t.length;i<s;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,s=0,a=t.length;e<a;e++){let a=t[e];i.set(a,s),s+=a.length}return i};let xe=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){xe=!1}const ke=new Uint8Array(256);for(let t=0;t<256;t++)ke[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;ke[254]=ke[254]=1;var Fe=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,o=0;for(a=0;a<n;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(o),r=0,a=0;r<o;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),i<128?e[r++]=i:i<2048?(e[r++]=192|i>>>6,e[r++]=128|63&i):i<65536?(e[r++]=224|i>>>12,e[r++]=128|i>>>6&63,e[r++]=128|63&i):(e[r++]=240|i>>>18,e[r++]=128|i>>>12&63,e[r++]=128|i>>>6&63,e[r++]=128|63&i);return e};var Te=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const De=Object.prototype.toString,{Z_NO_FLUSH:Ee,Z_SYNC_FLUSH:Oe,Z_FULL_FLUSH:Me,Z_FINISH:ze,Z_OK:$e,Z_STREAM_END:Ae,Z_DEFAULT_COMPRESSION:Pe,Z_DEFAULT_STRATEGY:We,Z_DEFLATED:Le}=Ct;function Ne(t){this.options=Ie({level:Pe,method:Le,chunkSize:16384,windowBits:15,memLevel:8,strategy:We},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Te,this.strm.avail_out=0;let i=Be.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==$e)throw new Error(It[i]);if(e.header&&Be.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Fe(e.dictionary):"[object ArrayBuffer]"===De.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=Be.deflateSetDictionary(this.strm,t),i!==$e)throw new Error(It[i]);this._dict_set=!0}}Ne.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?ze:Ee,"string"==typeof t?i.input=Fe(t):"[object ArrayBuffer]"===De.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),(r===Oe||r===Me)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=Be.deflate(i,r),a===Ae)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=Be.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===$e;if(0!==i.avail_out){if(r>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},Ne.prototype.onData=function(t){this.chunks.push(t)},Ne.prototype.onEnd=function(t){t===$e&&(this.result=Ce(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var He={deflate:function(t,e){const i=new Ne(e);if(i.push(t,!0),i.err)throw i.msg||It[i.err];return i.result}};const{deflate:Ve}=He;var Ze=Ve;const Ge={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},Je=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(r(t[s],e[i]),i++);function r(t,e){if(!(t in Ge))throw"Unhandled character '"+t+"' in pack format";const i=Ge[t].bytes,r=new DataView(new ArrayBuffer(i));Ge[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},je=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:r(e);function r(t){if(!(t in Ge))throw"Unhandled character '"+t+"' in unpack format";const r=Ge[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const o=Ge[t].u.bind(n);s.push(o(0,a)),i+=r}return s};class qe extends EventTarget{get isUsbJtagOrOtg(){return this._parent?this._parent._isUsbJtagOrOtg:this._isUsbJtagOrOtg}constructor(t,e,i){super(),this.port=t,this.logger=e,this._parent=i,this.__chipName=null,this.__chipRevision=null,this.__chipVariant=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null,this.currentBaudRate=o,this.SLIP_END=192,this.SLIP_ESC=219,this.SLIP_ESC_END=220,this.SLIP_ESC_ESC=221,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.__commandLock=Promise.resolve([0,[]]),this.__isReconfiguring=!1,this.__abandonCurrentOperation=!1,this._suppressDisconnect=!1,this.__consoleMode=!1,this._isUsbJtagOrOtg=void 0,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.state_RTS=!1,this.__writeChain=Promise.resolve()}get chipFamily(){return this._parent?this._parent.chipFamily:this.__chipFamily}set chipFamily(t){this._parent?this._parent.chipFamily=t:this.__chipFamily=t}get chipName(){return this._parent?this._parent.chipName:this.__chipName}set chipName(t){this._parent?this._parent.chipName=t:this.__chipName=t}get chipRevision(){return this._parent?this._parent.chipRevision:this.__chipRevision}set chipRevision(t){this._parent?this._parent.chipRevision=t:this.__chipRevision=t}get chipVariant(){return this._parent?this._parent.chipVariant:this.__chipVariant}set chipVariant(t){this._parent?this._parent.chipVariant=t:this.__chipVariant=t}get _consoleMode(){return this._parent?this._parent._consoleMode:this.__consoleMode}set _consoleMode(t){this._parent?this._parent._consoleMode=t:this.__consoleMode=t}setConsoleMode(t){this._consoleMode=t}get _inputBuffer(){if(this._parent)return this._parent._inputBuffer;if(void 0===this.__inputBuffer)throw new Error("_inputBuffer accessed before initialization");return this.__inputBuffer}get _inputBufferReadIndex(){return this._parent?this._parent._inputBufferReadIndex:this.__inputBufferReadIndex||0}set _inputBufferReadIndex(t){this._parent?this._parent._inputBufferReadIndex=t:this.__inputBufferReadIndex=t}get _inputBufferAvailable(){return this._inputBuffer.length-this._inputBufferReadIndex}_readByte(){if(!(this._inputBufferReadIndex>=this._inputBuffer.length))return this._inputBuffer[this._inputBufferReadIndex++]}_clearInputBuffer(){this._inputBuffer.length=0,this._inputBufferReadIndex=0}_compactInputBuffer(){this._inputBufferReadIndex>1e3&&this._inputBufferReadIndex>this._inputBuffer.length/2&&(this._inputBuffer.splice(0,this._inputBufferReadIndex),this._inputBufferReadIndex=0)}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}get _commandLock(){return this._parent?this._parent._commandLock:this.__commandLock}set _commandLock(t){this._parent?this._parent._commandLock=t:this.__commandLock=t}get _isReconfiguring(){return this._parent?this._parent._isReconfiguring:this.__isReconfiguring}set _isReconfiguring(t){this._parent?this._parent._isReconfiguring=t:this.__isReconfiguring=t}get _abandonCurrentOperation(){return this._parent?this._parent._abandonCurrentOperation:this.__abandonCurrentOperation}set _abandonCurrentOperation(t){this._parent?this._parent._abandonCurrentOperation=t:this.__abandonCurrentOperation=t}get _adaptiveBlockMultiplier(){return this._parent?this._parent._adaptiveBlockMultiplier:this.__adaptiveBlockMultiplier}set _adaptiveBlockMultiplier(t){this._parent?this._parent._adaptiveBlockMultiplier=t:this.__adaptiveBlockMultiplier=t}get _adaptiveMaxInFlightMultiplier(){return this._parent?this._parent._adaptiveMaxInFlightMultiplier:this.__adaptiveMaxInFlightMultiplier}set _adaptiveMaxInFlightMultiplier(t){this._parent?this._parent._adaptiveMaxInFlightMultiplier=t:this.__adaptiveMaxInFlightMultiplier=t}get _consecutiveSuccessfulChunks(){return this._parent?this._parent._consecutiveSuccessfulChunks:this.__consecutiveSuccessfulChunks}set _consecutiveSuccessfulChunks(t){this._parent?this._parent._consecutiveSuccessfulChunks=t:this.__consecutiveSuccessfulChunks=t}get _lastAdaptiveAdjustment(){return this._parent?this._parent._lastAdaptiveAdjustment:this.__lastAdaptiveAdjustment}set _lastAdaptiveAdjustment(t){this._parent?this._parent._lastAdaptiveAdjustment=t:this.__lastAdaptiveAdjustment=t}get _isCDCDevice(){return this._parent?this._parent._isCDCDevice:this.__isCDCDevice}set _isCDCDevice(t){this._parent?this._parent._isCDCDevice=t:this.__isCDCDevice=t}detectUSBSerialChip(t,e){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},18:{name:"ESP32-P4 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0;const t=this.port.getInfo();if(t.usbVendorId&&t.usbProductId){const e=this.detectUSBSerialChip(t.usbVendorId,t.usbProductId);this.logger.log(`USB-Serial: ${e.name} (VID: 0x${t.usbVendorId.toString(16)}, PID: 0x${t.usbProductId.toString(16)})`),e.maxBaudrate&&(this._maxUSBSerialBaudrate=e.maxBaudrate,this.logger.log(`Max baudrate: ${e.maxBaudrate}`)),12346===t.usbVendorId&&2===t.usbProductId&&(this._isESP32S2NativeUSB=!0),(12346===t.usbVendorId||6790===t.usbVendorId&&21971===t.usbProductId)&&(this._isCDCDevice=!0)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip(),this.chipFamily===C&&301===this.chipRevision&&await this.powerOnFlash();try{this._isUsbJtagOrOtg=await this.detectUsbConnectionType(),this.logger.debug("USB connection type: "+(this._isUsbJtagOrOtg?"USB-JTAG/OTG":"External Serial Chip"))}catch(t){this.logger.debug(`Could not detect USB connection type: ${t}`)}const t=z(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=k[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===C?(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)):this.chipFamily===y&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-C3 revision: ${this.chipRevision}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._clearInputBuffer(),await a(E);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=F[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${s(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===C?(this.chipRevision=await this.getChipRevision(),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)):this.chipFamily===y&&(this.chipRevision=await this.getChipRevision()),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily===C){const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}return this.chipFamily===y?await this.getChipRevisionC3():0}async powerOnFlash(){if(this.chipFamily!==C)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await a(10);const t=await this.readRegister(d);await this.writeRegister(d,t|c);const e=await this.readRegister(u);await this.writeRegister(u,128|e);const i=await this.readRegister(g);await this.writeRegister(g,3|i),await a(.05);const s=await this.readRegister(d);await this.writeRegister(d,-134217729&s);const r=await this.readRegister(u);await this.writeRegister(u,-2139095041&r);const n=await this.readRegister(u);await this.writeRegister(u,128|n);const o=await this.readRegister(u);await this.writeRegister(u,-129&o),await a(2),this.logger.debug("Flash powered on successfully")}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:je("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?je("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?je("<I",t.slice(16,20))[0]:0}}async getMacAddress(){if(!this._initializationSucceeded)throw new Error("getMacAddress() requires initialize() to have completed successfully");return this.macAddr().map(t=>t.toString(16).padStart(2,"0").toUpperCase()).join(":")}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{}finally{if(this._isReconfiguring=!1,this._reader){try{this._reader.releaseLock(),this.logger.debug("Reader released in readLoop cleanup")}catch(t){this.logger.debug(`Reader release error in readLoop: ${t}`)}this._reader=void 0}}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this._suppressDisconnect||this.dispatchEvent(new Event("disconnect")),this._suppressDisconnect=!1,this.logger.debug("Finished read loop")}sleep(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async setDTRandRTS(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async runSignalSequence(t){const e=!0===this.port.isWebUSB;for(const i of t)void 0!==i.dtr&&void 0!==i.rts?e?await this.setDTRandRTSWebUSB(i.dtr,i.rts):await this.setDTRandRTS(i.dtr,i.rts):(void 0!==i.dtr&&(e?await this.setDTRWebUSB(i.dtr):await this.setDTR(i.dtr)),void 0!==i.rts&&(e?await this.setRTSWebUSB(i.rts):await this.setRTS(i.rts))),i.delayMs&&await a(i.delayMs)}async hardResetUSBJTAGSerial(){await this.runSignalSequence([{rts:!1},{dtr:!1,delayMs:100},{dtr:!0,rts:!1,delayMs:100},{rts:!0},{dtr:!1,rts:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:200}])}async hardResetClassic(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:50},{dtr:!1,delayMs:200}])}async hardResetToFirmware(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:100},{rts:!1,delayMs:50},{delayMs:200}])}async hardResetUnixTight(){await this.runSignalSequence([{dtr:!0,rts:!0},{dtr:!1,rts:!1},{dtr:!1,rts:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:50},{dtr:!1,rts:!1},{dtr:!1,delayMs:200}])}async setRTSWebUSB(t){this.state_RTS=t,await this.port.setSignals({requestToSend:t,dataTerminalReady:this.state_DTR})}async setDTRWebUSB(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:this.state_RTS})}async setDTRandRTSWebUSB(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.runSignalSequence([{rts:!1,dtr:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:100},{rts:!0,dtr:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:200}])}async hardResetClassicLongDelayWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:500},{dtr:!0,rts:!1,delayMs:200},{dtr:!1,delayMs:500}])}async hardResetClassicShortDelayWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:50},{dtr:!0,rts:!1,delayMs:25},{dtr:!1,delayMs:100}])}async hardResetInvertedWebUSB(){await this.runSignalSequence([{dtr:!0,rts:!1,delayMs:100},{dtr:!1,rts:!0,delayMs:50},{dtr:!0,delayMs:200}])}async hardResetInvertedDTRWebUSB(){await this.runSignalSequence([{dtr:!0,rts:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:50},{dtr:!0,delayMs:200}])}async hardResetInvertedRTSWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!1,delayMs:100},{dtr:!0,rts:!0,delayMs:50},{dtr:!1,delayMs:200}])}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,s=[],r=this,n=!e&&!i;if(this.isWebUSB()){const a=4292===t.usbVendorId,o=6790===t.usbVendorId,h=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(h?(s.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async()=>await r.hardResetUSBJTAGSerial()}),s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async()=>await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async()=>await r.hardResetClassic()})):(s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async()=>await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"USB-JTAG/Serial (WebUSB)",fn:async()=>await r.hardResetUSBJTAGSerial()}),s.push({name:"Inverted DTR Classic (WebUSB)",fn:async()=>await r.hardResetInvertedDTRWebUSB()}))),n&&(o?(s.push({name:"UnixTight (WebUSB) - CH34x",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CH34x",fn:async()=>await r.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedDTRWebUSB()})):a?(s.push({name:"UnixTight (WebUSB) - CP2102",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CP2102",fn:async()=>await r.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedDTRWebUSB()})):(s.push({name:"UnixTight (WebUSB)",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassic()}}),s.push({name:"Inverted Both (WebUSB)",fn:async function(){return await r.hardResetInvertedWebUSB()}}),s.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),s.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),a||h||(6790!==t.usbVendorId&&s.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassic()}}),s.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTight()}}),s.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await r.hardResetClassicLongDelayWebUSB()}}),s.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await r.hardResetClassicShortDelayWebUSB()}}),e||i||s.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerial()}}))}else(e||i)&&s.push({name:"USB-JTAG/Serial",fn:async function(){return await r.hardResetUSBJTAGSerial()}}),s.push({name:"UnixTight",fn:async function(){return await r.hardResetUnixTight()}}),e||i||s.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await r.hardResetUSBJTAGSerial()}});let o=null;for(const t of s)try{if(!this.connected||!this.port.writable){this.logger.debug(`Port disconnected, skipping ${t.name} reset`);continue}if(this._abandonCurrentOperation=!1,await t.fn(),n){if(await this.syncWithTimeout(2e3))return void this.logger.log(`Connected USB Serial successfully with ${t.name} reset.`);throw new Error("Sync timeout or abandoned")}{const e=this.sync(),i=new Promise((t,e)=>setTimeout(()=>e(new Error("Sync timeout")),1e3));try{return await Promise.race([e,i]),void this.logger.log(`Connected CDC/JTAG successfully with ${t.name} reset.`)}catch(t){throw new Error("Sync timeout or abandoned")}}}catch(t){if(o=t,this._abandonCurrentOperation=!0,await a(100),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._clearInputBuffer(),await this.drainInputBuffer(200),await this.flushSerialBuffers()}throw this._abandonCurrentOperation=!1,new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${null==o?void 0:o.message}`)}async watchdogReset(){await this.rtcWdtResetChipSpecific()}async getChipRevisionC3(){if(this.chipFamily!==y)return 0;const t=await this.readRegister(1610647632)>>18&7;return(await this.readRegister(1610647640)>>23&7)<<3|t}async rtcWdtResetChipSpecific(){let t,e,i,s;if(this.logger.debug("Hard resetting with watchdog timer..."),this.chipFamily===w)t=1061191852,e=1061191828,i=1061191832,s=1356348065;else if(this.chipFamily===m)t=1610645680,e=1610645656,i=1610645660,s=1356348065;else if(this.chipFamily===y)t=1610645672,e=1610645648,i=1610645652,s=1356348065;else if(this.chipFamily===S||this.chipFamily===v)t=1611340824,e=1611340800,i=1611340804,s=1356348065;else{if(this.chipFamily!==C)throw new Error(`rtcWdtResetChipSpecific() is not supported for ${this.chipFamily}`);t=1343315992,e=1343315968,i=1343315972,s=1356348065}await this.writeRegister(t,s,void 0,0),await this.writeRegister(i,2e3,void 0,0);await this.writeRegister(e,-805306110,void 0,0),await this.writeRegister(t,0,void 0,0),await this.sleep(500)}async tryUsbWdtReset(t){return await this.detectUsbConnectionType()?(await this.rtcWdtResetChipSpecific(),this.logger.debug(`${t}: RTC WDT reset (USB-JTAG/Serial or USB-OTG detected)`),!0):(await this.hardResetClassic(),this.logger.debug("Classic reset."),!1)}async hardReset(t=!1){if(this._consoleMode)return t?void this.logger.debug("Skipping bootloader reset - device is in console mode"):(this.logger.debug("Performing hardware reset (console mode)..."),await this.hardResetToFirmware(),void this.logger.debug("Hardware reset complete"));if(t)4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.debug("USB-JTAG/Serial reset.")):(await this.hardResetClassic(),this.logger.debug("Classic reset."));else{if(this.logger.debug("*** Performing WDT reset strategy ***"),this.chipFamily===w){if(await this.tryUsbWdtReset("ESP32-S2"))return}else if(this.chipFamily===C){if(await this.tryUsbWdtReset("ESP32-P4"))return}else if(this.chipFamily===S){if(await this.tryUsbWdtReset("ESP32-C5"))return}else if(this.chipFamily===v){if(await this.tryUsbWdtReset("ESP32-C6"))return}this.isWebUSB()?(await this.setRTSWebUSB(!0),await this.sleep(200),await this.setRTSWebUSB(!1),await this.sleep(200),this.logger.debug("Hard reset (WebUSB).")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.debug("Hard reset."))}await new Promise(t=>setTimeout(t,1e3))}macAddr(){const t=new Array(6).fill(0),e=this._efuses[0],i=this._efuses[1],s=this._efuses[2],a=this._efuses[3];let r;if(this.chipFamily==_){if(0!=a)r=[a>>16&255,a>>8&255,255&a];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");r=[172,208,116]}else r=[24,254,52];t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==p)t[0]=s>>8&255,t[1]=255&s,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=v&&this.chipFamily!=R&&this.chipFamily!=B&&this.chipFamily!=U&&this.chipFamily!=I&&this.chipFamily!=C&&this.chipFamily!=x)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=e>>24&255,t[3]=e>>16&255,t[4]=e>>8&255,t[5]=255&e}return t}async readRegister(t){this.debug&&this.logger.debug("Reading from Register "+s(t,8));const e=Je("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){const r=async()=>{a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,a);if(null===n)throw new Error("Didn't get enough status bytes");let o=n,h=0;if(this.IS_STUB||this.chipFamily==_?h=2:[p,w,m,b,y,S,v,R,B,U,I,C,x].includes(this.chipFamily)||20===t?h=4:[2,4].includes(o.length)?h=o.length:(h=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${s(t)}, data.length: ${o.length})`)),o.length<h)throw new Error("Didn't get enough status bytes");const l=o.slice(-h,o.length);if(o=o.slice(0,-h),this.debug&&(this.logger.debug("status",l),this.logger.debug("value",r),this.logger.debug("data",o)),1==l[0])throw 5==l[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+s(t))):new Error("Command failure error code "+s(l[1]));return[r,o]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...Je("<BBHI",0,e,i.length,s),...i]);this.debug&&this.logger.debug(`Writing ${a.length} byte${1==a.length?"":"s"}:`,a),await this.writeToStream(a)}async readPacket(t){let e=null,r=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new $("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){if(Date.now()-n>t){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}const a=this._readByte();if(null===e){if(a!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(a)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid head of packet ("+s(a)+")");e=[]}else if(r)if(r=!1,a==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(a!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(a)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid SLIP escape (0xdb, "+s(a)+")");e.push(this.SLIP_ESC)}else if(a==this.SLIP_ESC)r=!0;else{if(a==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(a)}}else await a(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new $("Operation abandoned (reset strategy timeout)");const o=Date.now();for(n=[];Date.now()-o<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await a(1)}if(0==n.length){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+i(n));for(const t of n)if(null===e){if(t!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid head of packet ("+s(t)+")");e=[]}else if(r)if(r=!1,t==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(t!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid SLIP escape (0xdb, "+s(t)+")");e.push(this.SLIP_ESC)}else if(t==this.SLIP_ESC)r=!0;else{if(t==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}}}async getResponse(t,e=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(e);if(i.length<8)continue;const[a,r,,n]=je("<BBHI",i.slice(0,8));if(1!=a)continue;const o=i.slice(8);if(null==t||r==t)return[n,o];if(0!=o[0]&&5==o[1])throw await this.drainInputBuffer(200),new Error(`Invalid (unsupported) command ${s(t)}`)}throw new Error("Response doesn't match request")}checksum(t,e=239){for(const i of t)e^=i;return e}async getC5CrystalFreqRomExpect(){return(2130706432&await this.readRegister(1611227408))>>>24}async getC5CrystalFreqDetected(){const t=1048575&await this.readRegister(1610612756),e=o*t/1e6;return e>45?48:e>33?40:26}async setBaudrateC5Rom(t){const e=await this.getC5CrystalFreqRomExpect(),i=await this.getC5CrystalFreqDetected();this.logger.log(`ROM expects crystal freq: ${e} MHz, detected ${i} MHz.`);let s=t;48===i&&40===e?s=Math.trunc(40*t/48):40===i&&48===e&&(s=Math.trunc(48*t/40)),this.logger.log(`Changing baud rate to ${s}...`);try{const t=Je("<II",s,0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${s}: No response from set baud rate command.`)}this.logger.log("Changed.")}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==S)try{const e=Je("<II",t,this.IS_STUB?o:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}else await this.setBaudrateC5Rom(t);this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(E),this._parent?this._parent.currentBaudRate=t:this.currentBaudRate=t;const i=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;i&&t>i&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${i})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;this._isReconfiguring=!0;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this.isWebUSB()){const e=this.port.getInfo(),i=6790===e.usbVendorId&&21971===e.usbProductId;if(!i&&"function"==typeof this.port.setBaudRate)return await this.port.setBaudRate(t),void await a(100)}if(this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconfigure: ${t}`)}this._writer=void 0}await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(t){}finally{this._isReconfiguring=!1}}async syncWithTimeout(t){const e=Date.now();for(let i=0;i<5;i++){if(Date.now()-e>t)return!1;if(this._abandonCurrentOperation)return!1;this._clearInputBuffer();try{if(await this._sync())return await a(E),!0}catch(t){if(this._abandonCurrentOperation)return!1}await a(E)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await a(E),!0;await a(E)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,f);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,E);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){this.debug&&this.logger.debug(`Sync attempt ${t+1} failed: ${e}`)}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,a=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],a=e[2],r=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(r)}`)}const r=t.byteLength;let n,o=0,h=T;a?(n=Ze(new Uint8Array(t),{level:9}).buffer,o=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${o}`),h=await this.flashDeflBegin(r,o,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],d=0,c=0,u=0;const g=Date.now(),f=this.getFlashWriteSize(),_=a?o:r;for(;_-u>0;)this.debug&&this.logger.log(`Writing at ${s(i+d*f,8)} `),_-u>=f?l=Array.from(new Uint8Array(n,u,f)):(l=Array.from(new Uint8Array(n,u,_-u)),a||(l=l.concat(new Array(f-l.length).fill(255)))),a?await this.flashDeflBlock(l,d,h):await this.flashBlock(l,d),d+=1,c+=a?Math.round(l.length*r/o):l.length,u+=f,e(Math.min(c,r),r);this.logger.log("Took "+(Date.now()-g)+"ms to write "+_+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),a?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[p,w,m,b,y,S,v,R,B,U,I,C,x].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=_||this.IS_STUB?t:this.getEraseSize(e,t);const o=this.IS_STUB?T:M(O,t),h=Date.now();let l=Je("<IIII",a,n,r,e);return this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=v&&this.chipFamily!=R&&this.chipFamily!=B&&this.chipFamily!=U&&this.chipFamily!=I&&this.chipFamily!=C&&this.chipFamily!=x||(l=l.concat(Je("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+n+", block size "+s(r,4)+", offset "+s(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,l,0,o),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-h)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(t=0,e=0,i=0){const s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),r=Math.floor((t+s-1)/s);let n=0,o=0;this.IS_STUB?(n=t,o=M(O,n)):(n=r*s,o=T);const h=Je("<IIII",n,a,s,i);return await this.checkCommand(16,h,0,o),o}async flashFinish(){const t=Je("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=Je("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return z(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(t,e,i=4294967295,s=0,a=0){let r=Je("<IIII",t,e,i,s);a>0&&(r=r.concat(Je("<IIII",z(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const s=t.regBase+t.mosiDlenOffs,a=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(s,e-1),i>0&&await this.writeRegister(a,i-1)}else{const s=t.regBase+t.usr1Offs,a=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(s,a)}}async waitDone(t,e){for(let i=0;i<10;i++){if(0==(await this.readRegister(t)&e))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(t,e,i=0){const a=z(this.getChipFamily()),r=a.regBase,n=r,o=r+a.usrOffs,h=r+a.usr2Offs,l=r+a.w0Offs,d=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(e.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const c=8*e.length,u=await this.readRegister(o),g=await this.readRegister(h);let f=1<<31;if(i>0&&(f|=268435456),c>0&&(f|=134217728),await this.setDataLengths(a,c,i),await this.writeRegister(o,f),await this.writeRegister(h,7<<28|t),0==c)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=je("I".repeat(Math.floor(e.length/4)),e);let a=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${s(t)} to register offset ${s(a)}`),await this.writeRegister(a,t),a+=4}await this.writeRegister(n,d),await this.waitDone(n,d);const _=await this.readRegister(l);return await this.writeRegister(o,u),await this.writeRegister(h,g),_}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${s(t)}`),this.logger.log(`Flash Manufacturer: ${e.toString(16)}`),this.logger.log(`Flash Device: ${(t>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=r[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=n,s=Math.floor((e+i-1)/i);let a=16-Math.floor(t/i)%16;return s<a&&(a=s),s<2*a?Math.floor((s+1)/2*i):(s-a)*i}async memBegin(t,e,i,s){return await this.checkCommand(5,Je("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?T:500,i=Je("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){this.logger.debug(`Loading stub for ${this.chipName}, revision: ${this.chipRevision}`);const e=await A(this.chipFamily,this.chipRevision);if(null===e)return this.logger.log(`Stub flasher is not yet supported on ${this.chipName}, using ROM loader`),this;const i=2048;this.logger.log("Uploading stub...");for(const t of["text","data"]){const s=e[t],a=e[`${t}_start`],r=s.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,a);for(const t of Array(n).keys()){const e=t*i;let a=e+i;a>r&&(a=r),await this.memBlock(s.slice(e,a),t)}}await this.memFinish(e.entry);const s=await this.readPacket(500),a=String.fromCharCode(...s);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");const r=new Ye(this.port,this.logger,this);return t||await r.detectFlashSize(),r}get _reader(){return this._parent?this._parent._reader:this.__reader}set _reader(t){this._parent?this._parent._reader=t:this.__reader=t}get _writer(){return this._parent?this._parent._writer:this.__writer}set _writer(t){this._parent?this._parent._writer=t:this.__writer=t}get _writeChain(){return this._parent?this._parent._writeChain:this.__writeChain}set _writeChain(t){this._parent?this._parent._writeChain=t:this.__writeChain=t}async writeToStream(t){if(this.port.writable){if(this._isReconfiguring)throw new Error("Cannot write during port reconfiguration");this._writeChain=this._writeChain.then(async()=>{if(!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.error(`Failed to get writer: ${t}`),t}await this._writer.write(new Uint8Array(t))},async()=>{if(this.logger.debug("Previous write failed, attempting recovery for current write"),!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.debug(`Failed to get writer in recovery: ${t}`),new Error("Cannot acquire writer lock")}await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch{}this._writer=void 0}throw t}),await this._writeChain}else this.logger.debug("Port writable stream not available, skipping write")}async getUsbMode(){var t,e;const i=this._parent?this._parent.chipFamily:this.chipFamily,s=this._parent?null!==(t=this._parent.chipRevision)&&void 0!==t?t:0:null!==(e=this.chipRevision)&&void 0!==e?e:0;let a=null,r=null,n=null;switch(i){case w:a=1073741076,n=2;break;case m:a=1070526796,r=4,n=3;break;case y:a=(s<101?1070461028:1070461024)+24,r=3;break;case S:a=1082520852,r=3;break;case v:a=1082652032,r=3;break;case R:a=s<=200?1082455532:1082455524,r=s<=200?3:4;break;case B:a=1082457852,r=3;break;case U:a=1082652032,r=3;break;case C:a=s<300?1341390536:1341914824,r=6,n=5}if(null===a)return{mode:"uart",uartNo:0};const o=255&await this.readRegister(a);return null!==n&&o===n?(this.logger.debug(`USB mode: USB-OTG (uartNo=${o})`),{mode:"usb-otg",uartNo:o}):null!==r&&o===r?(this.logger.debug(`USB mode: USB-JTAG/Serial (uartNo=${o})`),{mode:"usb-jtag-serial",uartNo:o}):(this.logger.debug(`USB mode: UART (uartNo=${o})`),{mode:"uart",uartNo:o})}async disconnect(){if(this._parent)await this._parent.disconnect();else if(this.port.writable){try{await this._writeChain}catch(t){}if(this._writer){try{await this._writer.close(),this._writer.releaseLock()}catch(t){}this._writer=void 0}else try{const t=this.port.writable.getWriter();await t.close(),t.releaseLock()}catch(t){}await new Promise(t=>{if(!this._reader)return void t(void 0);const e=setTimeout(()=>{this.logger.debug("Disconnect timeout - forcing resolution"),t(void 0)},1e3);this.addEventListener("disconnect",()=>{clearTimeout(e),t(void 0)},{once:!0});try{this._reader.cancel()}catch(i){clearTimeout(e),t(void 0)}}),this.connected=!1;try{await this.port.close(),this.logger.debug("Port closed successfully")}catch(t){this.logger.debug(`Port close error: ${t}`)}}}async releaseReaderWriter(){if(this._parent)await this._parent.releaseReaderWriter();else{try{await this._writeChain}catch(t){}if(this._writer){try{this._writer.releaseLock(),this.logger.debug("Writer released")}catch(t){this.logger.debug(`Writer release error: ${t}`)}this._writer=void 0}if(this._reader){const t=this._reader;try{this._suppressDisconnect=!0,await t.cancel(),this.logger.debug("Reader cancelled")}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}finally{try{t.releaseLock()}catch(t){this.logger.debug(`Reader release error: ${t}`)}}this._reader===t&&(this._reader=void 0)}}}async resetToFirmware(){return await this._resetToFirmwareIfNeeded()}async detectUsbConnectionType(){const t=this.port.getInfo(),e=t.usbProductId;if(!(12346===t.usbVendorId))return this.logger.debug("Not Espressif VID - external serial chip"),!1;const i=[2,18,4097].includes(e||0);return this.logger.debug(`USB-JTAG/OTG detection: ${i?"YES":"NO"} (PID=0x${null==e?void 0:e.toString(16)})`),i}async enterConsoleMode(){if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - port selection needed"),!0;let t;try{t=await this.detectUsbConnectionType(),this.logger.debug("USB connection type detected: "+(t?"USB-JTAG/OTG":"External Serial Chip")),this._isUsbJtagOrOtg=t}catch(e){if(void 0===this.isUsbJtagOrOtg)throw new Error(`Cannot enter console mode: USB connection type unknown and detection failed: ${e}`);this._consoleMode=!1,this.logger.debug(`USB detection failed, using cached value: ${this.isUsbJtagOrOtg}`),t=this.isUsbJtagOrOtg}if(t){return await this._resetToFirmwareIfNeeded()}try{await this.releaseReaderWriter(),await this.sleep(100)}catch(t){this.logger.debug(`Failed to release locks: ${t}`)}try{await this.hardReset(!1),this.logger.log("Device reset to firmware mode")}catch(t){this.logger.debug(`Could not reset device: ${t}`)}if(this.isWebUSB())try{await this.port.recreateStreams(),this.logger.debug("WebUSB streams recreated for console mode")}catch(t){this._consoleMode=!1,this.logger.debug(`Failed to recreate WebUSB streams: ${t}`)}return this._consoleMode=!0,!1}async _clearForceDownloadBootIfNeeded(){try{let t,e,i;if(this.chipFamily===w)t=1061191976,e=1,i="ESP32-S2";else if(this.chipFamily===m)t=1610645804,e=1,i="ESP32-S3";else{if(this.chipFamily!==C)return!1;t=1343291400,e=4,i="ESP32-P4"}const s=await this.readRegister(t);this.logger.debug(`${i} force download boot register: 0x${s.toString(16)} (mask: 0x${e.toString(16)})`);return 0!==(s&e)?(this.logger.debug(`${i} force download boot flag is SET - clearing it`),await this.writeRegister(t,0,e,0),this.logger.debug(`${i} force download boot flag cleared`),!0):(this.logger.debug(`${i} force download boot flag is already CLEAR - no action needed`),!1)}catch(t){return this.logger.debug(`Error checking/clearing force download flag: ${t}`),!1}}async _resetToFirmwareIfNeeded(){try{if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - assuming device is already in firmware mode"),!1;const t=await this.detectUsbConnectionType();if(t){if(this.IS_STUB){if(this.logger.debug("On stub - need to get back to ROM to check flag"),this.currentBaudRate!==o){this.logger.debug(`Changing baudrate from ${this.currentBaudRate} to 115200 for ROM`);try{await this.reconfigurePort(o),this.currentBaudRate=o}catch(t){this.logger.debug(`Baudrate change failed: ${t}`)}}this.logger.debug("Resetting to bootloader (ROM)...");try{await this.hardReset(!0),await a(200),await this.sync(),this.logger.debug("Now on ROM after reset"),this.IS_STUB=!1}catch(t){return this.logger.debug(`Reset to ROM failed: ${t}`),this.logger.debug("Assuming device is already in firmware mode"),await this.releaseReaderWriter(),!1}}else this.logger.debug("Already on ROM - checking force download flag");await this._clearForceDownloadBootIfNeeded()?this.logger.debug("Force download flag was cleared - device will boot to firmware after reset"):this.logger.debug("Force download flag already clear - device will boot to firmware after reset"),await this.hardReset(!1);return this.chipFamily===w&&t||this.chipFamily===C&&t?(await this.releaseReaderWriter(),this.logger.log(`${this.chipName} USB-OTG: Port will change after WDT reset`),this.logger.log("Please select the new port for console mode"),this.dispatchEvent(new CustomEvent("usb-otg-port-change",{detail:{chipName:this.chipName,message:`${this.chipName} USB port changed after reset. Please select the new port.`,reason:"wdt-reset-to-firmware"}})),!0):(await this.releaseReaderWriter(),!1)}}catch(t){this.logger.debug(`Could not reset device to firmware mode: ${t}`)}return!1}async reconnect(){if(this._parent)await this._parent.reconnect();else try{this.logger.log("Reconnecting serial port...");const t=this.currentBaudRate;this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.debug("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:o}),this.connected=!0,this.currentBaudRate=o}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1;const e=this.chipFamily,i=this.chipName,s=this.chipRevision,a=this.chipVariant,r=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=e,this.chipName=i,this.chipRevision=s,this.chipVariant=a,this.flashSize=r,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");this.chipFamily===C&&301===this.chipRevision&&await this.powerOnFlash();const n=await this.runStub(!0);if(this.logger.debug("Stub loaded"),t!==o&&(await n.setBaudrate(t),!this.port.writable||!this.port.readable))throw new Error(`Port not ready after baudrate change (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this.IS_STUB=!0,this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async reconnectToBootloader(){if(this._parent)await this._parent.reconnectToBootloader();else try{this.logger.log("Reconnecting to bootloader mode..."),this._consoleMode=!1,this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.debug("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:o}),this.connected=!0,this.currentBaudRate=o}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1,this.__chipFamily=void 0,this.chipName="Unknown Chip",this.chipRevision=null,this.chipVariant=null,this.IS_STUB=!1,this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await a(100),await this.connectWithResetStrategies(),await this.detectChip(),this.logger.log(`Reconnected to bootloader: ${this.chipName}`)}catch(t){throw this._isReconfiguring=!1,t}}async exitConsoleMode(){if(this._parent)return await this._parent.exitConsoleMode();this._consoleMode=!1;const t=this.chipFamily===w||this.chipFamily===C;let e=this._isUsbJtagOrOtg;if(t&&void 0===e)try{e=await this.detectUsbConnectionType()}catch(t){this.logger.debug(`USB detection failed, assuming USB-JTAG/OTG for ${this.chipName}: ${t}`),e=!0}if(t&&e){this.logger.log(`${this.chipName} USB: Resetting to bootloader mode`);try{await this.hardResetClassic(),this.logger.debug("Reset to bootloader initiated")}catch(t){this.logger.debug(`Reset error: ${t}`)}return await a(500),this.logger.log(`${this.chipName}: Port changed. Please select the bootloader port.`),this.dispatchEvent(new CustomEvent("usb-otg-port-change",{detail:{chipName:this.chipName,message:`${this.chipName}: Port changed. Please select the bootloader port.`,reason:"exit-console-to-bootloader"}})),!0}return await this.reconnectToBootloader(),!1}isConsoleResetSupported(){if(this._parent)return this._parent.isConsoleResetSupported();return!(this.chipFamily===w&&(!0===this._isUsbJtagOrOtg||void 0===this._isUsbJtagOrOtg))}async resetInConsoleMode(){if(this._parent)return await this._parent.resetInConsoleMode();if(this.isConsoleResetSupported())try{this.logger.debug("Resetting device in console mode"),await this.hardResetToFirmware(),this.logger.debug("Device reset complete")}catch(t){throw this.logger.error(`Reset failed: ${t}`),t}else this.logger.debug("Console reset not supported for ESP32-S2 USB-JTAG/CDC")}async drainInputBuffer(t=200){await a(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBufferAvailable>0){void 0!==this._readByte()&&e++}else await a(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0)}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),await a(E),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s,r){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");let n;await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`),this.isWebUSB()&&(this._isCDCDevice?(this._adaptiveBlockMultiplier=8,this._adaptiveMaxInFlightMultiplier=8,this._consecutiveSuccessfulChunks=0,this.logger.debug(`CDC device - Initialized: blockMultiplier=${this._adaptiveBlockMultiplier}, maxInFlightMultiplier=${this._adaptiveMaxInFlightMultiplier}`)):(this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0,this.logger.debug("Non-CDC device - Fixed values: blockSize=31, maxInFlight=31"))),void 0!==(null==r?void 0:r.chunkSize)?(n=r.chunkSize,this.logger.log(`Using custom chunk size: 0x${n.toString(16)} bytes`)):n=this.isWebUSB()?16384:262144;let o=new Uint8Array(0),h=e,l=i;for(;l>0;){const e=Math.min(n,l);let d=!1,c=0;const u=5;let g=!1;for(;!d&&c<=u;){let i=new Uint8Array(0),s=0;try{let n,l;if(0===c&&this.logger.debug(`Reading chunk at 0x${h.toString(16)}, size: 0x${e.toString(16)}`),void 0!==(null==r?void 0:r.blockSize)&&void 0!==(null==r?void 0:r.maxInFlight))n=r.blockSize,l=r.maxInFlight,0===c&&this.logger.debug(`Using custom parameters: blockSize=${n}, maxInFlight=${l}`);else if(this.isWebUSB()){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2);n=e*this._adaptiveBlockMultiplier,l=e*this._adaptiveMaxInFlightMultiplier}else{const t=63;n=65*t,l=130*t}const u=Je("<IIII",h,e,n,l),[g]=await this.checkCommand(210,u);if(0!=g)throw new Error("Failed to read memory: "+g);for(;i.length<e;){let r;try{r=await this.readPacket(100)}catch(t){if(t instanceof $){this.logger.debug(`SLIP read error at ${i.length} bytes: ${t.message}`);try{const t=[this.SLIP_END,this.SLIP_END];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await a(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(r&&r.length>0){const a=new Uint8Array(r),n=new Uint8Array(i.length+a.length);n.set(i),n.set(a,i.length),i=n;if(i.length>=e||i.length>=s+l){const e=Je("<I",i.length),a=t(e);await this.writeToStream(a),s=i.length}}}const f=new Uint8Array(o.length+i.length);if(f.set(o),f.set(i,o.length),o=f,d=!0,this.isWebUSB()&&this._isCDCDevice&&0===c&&(this._consecutiveSuccessfulChunks++,this._consecutiveSuccessfulChunks>=2)){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=8,s=8;let a=!1;if(this._adaptiveBlockMultiplier<i?(this._adaptiveBlockMultiplier=Math.min(2*this._adaptiveBlockMultiplier,i),a=!0):this._adaptiveMaxInFlightMultiplier<s&&(this._adaptiveMaxInFlightMultiplier=Math.min(2*this._adaptiveMaxInFlightMultiplier,s),a=!0),a){const t=e*this._adaptiveBlockMultiplier,i=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Speed increased: blockSize=${t}, maxInFlight=${i}`),this._lastAdaptiveAdjustment=Date.now()}this._consecutiveSuccessfulChunks=0}}catch(t){if(c++,this.isWebUSB()&&this._isCDCDevice&&1===c)if(this._adaptiveBlockMultiplier>1||this._adaptiveMaxInFlightMultiplier>1){this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0;const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=e*this._adaptiveBlockMultiplier,s=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Error at higher speed - reduced to minimum: blockSize=${i}, maxInFlight=${s}`)}else this.logger.debug("Error at minimum speed (blockSize=31, maxInFlight=31) - not a speed issue");if(!(t instanceof $))throw t;if(c<=u){this.logger.debug(`${t.message} at 0x${h.toString(16)}. Draining buffer and retrying (attempt ${c}/${u})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await a(E)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(g)throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${u} retries and recovery attempt`);g=!0,this.logger.log(`All retries exhausted at 0x${h.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),c=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${u} retries and recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),o.length,i),h+=e,l-=e,this.logger.debug(`Total progress: 0x${o.length.toString(16)} from 0x${i.toString(16)} bytes`)}return o}}class Ye extends qe{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await A(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,o=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(o,8)}`),this.logger.debug(`Stub data: ${s(r.data_start,8)}, len: ${r.data.length}, text: ${s(r.text_start,8)}, len: ${r.text.length}`);for(const[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&o>t)throw new Error("Software loader is resident at "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(n,8)+"-"+s(o,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,D)}async eraseRegion(t,e){if(t<0)throw new Error(`Invalid offset: ${t} (must be non-negative)`);if(e<0)throw new Error(`Invalid size: ${e} (must be non-negative)`);if(0===e)return void this.logger.log("eraseRegion: size is 0, skipping erase");if(t%n!==0)throw new Error(`Offset ${t} (0x${t.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);if(e%n!==0)throw new Error(`Size ${e} (0x${e.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);const i=4294967295;if(t>i)throw new Error(`Offset ${t} exceeds maximum value 4294967295`);if(e>i)throw new Error(`Size ${e} exceeds maximum value 4294967295`);if(t+e>i)throw new Error(`Region end (offset + size = ${t+e}) exceeds maximum addressable range 4294967295`);const s=M(O,e),a=Je("<II",t,e);await this.checkCommand(209,a,0,s)}}const Ke=async t=>{if(import("./install-dialog-7l9oLExq.js"),(()=>{const t=navigator.userAgent||"";return/Android/i.test(t)})()&&"usb"in navigator)try{await(async()=>{if(!globalThis.requestSerialPort)return new Promise((t,e)=>{const i=document.createElement("script");i.type="module",i.src="https://unpkg.com/tasmota-webserial-esptool/js/webusb-serial.js",i.onload=()=>{globalThis.requestSerialPort?t():e(new Error("WebUSB serial script loaded but requestSerialPort not found"))},i.onerror=()=>e(new Error("Failed to load WebUSB serial script")),document.head.appendChild(i)})})()}catch(t){return void alert(`Failed to load WebUSB support: ${t.message}`)}let e;try{e=await(async t=>{let e;const i=globalThis.requestSerialPort;if("function"==typeof i)e=await i();else{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser. Please use Chrome, Edge, or Opera on desktop, or Chrome on Android. Note: The page must be served over HTTPS or localhost.");e=await navigator.serial.requestPort()}return e.readable&&e.writable||await e.open({baudRate:o}),new qe(e,t)})({log:()=>{},debug:()=>{},error:t=>console.error(t)})}catch(e){return"NotFoundError"===e.name?void import("./index-DUmRg0Cu.js").then(e=>e.openNoPortPickedDialog(()=>Ke(t))):void alert(`Connection failed: ${e.message}`)}if(!e)return void alert("Failed to connect to device");const i=document.createElement("ewt-install-dialog");i.esploader=e,i.manifestPath=t.manifest||t.getAttribute("manifest"),i.overrides=t.overrides,i.firmwareFile=t.firmwareFile;const s=t.getAttribute("baud-rate");if(s){const t=parseInt(s,10);isNaN(t)||(i.baudRate=t)}else void 0!==t.baudRate&&(i.baudRate=t.baudRate);i.addEventListener("closed",async()=>{try{await e.disconnect()}catch(t){}},{once:!0}),document.body.appendChild(i)},Xe="https://cors-proxy.espressif.tools",Qe=async(t,e)=>{if((t=>{try{const e=new URL(t),i=window.location.origin;return e.origin!==i&&"file:"!==e.protocol}catch{return!1}})(t=t.trim())){if(t.includes("github.com")&&t.includes("/releases/download/")){const i=`${Xe}/?url=${encodeURIComponent(t)}`,{headers:s,credentials:a,...r}=null!=e?e:{};return fetch(i,r)}try{return await fetch(t,e)}catch(i){try{const i=`${Xe}/?url=${encodeURIComponent(t)}`,{headers:s,credentials:a,...r}=null!=e?e:{};return await fetch(i,r)}catch(t){throw i}}}return fetch(t,e)};window.espWebToolsCorsProxyFetch=Qe;class ti extends HTMLElement{attributeChangedCallback(t,e,i){if("baud-rate"===t&&i!==e)if(i){const t=parseInt(i,10);this.baudRate=Number.isNaN(t)?void 0:t}else this.baudRate=void 0}connectedCallback(){if(this.renderRoot)return;if(this.renderRoot=this.attachShadow({mode:"open"}),!ti.isSupported||!ti.isAllowed)return this.toggleAttribute("install-unsupported",!0),void(this.renderRoot.innerHTML=ti.isAllowed?"<slot name='unsupported'>Your browser does not support installing things on ESP devices. Use Google Chrome or Microsoft Edge (Desktop) or Chrome on Android with USB OTG.</slot>":"<slot name='not-allowed'>You can only install ESP devices on HTTPS websites or on the localhost.</slot>");this.toggleAttribute("install-supported",!0);const t=document.createElement("slot");t.addEventListener("click",async t=>{t.preventDefault(),Ke(this)}),t.name="activate";const e=document.createElement("button");if(e.innerText="Connect",t.append(e),"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype){const t=new CSSStyleSheet;t.replaceSync(ti.style),this.renderRoot.adoptedStyleSheets=[t]}else{const t=document.createElement("style");t.innerText=ti.style,this.renderRoot.append(t)}this.renderRoot.append(t)}}ti.isSupported="serial"in navigator||"usb"in navigator,ti.isAllowed=window.isSecureContext,ti.observedAttributes=["baud-rate"],ti.style='\n button {\n position: relative;\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n padding: 10px 24px;\n color: var(--esp-tools-button-text-color, #fff);\n background-color: var(--esp-tools-button-color, #03a9f4);\n border: none;\n border-radius: var(--esp-tools-button-border-radius, 9999px);\n }\n button::before {\n content: " ";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n opacity: 0.2;\n border-radius: var(--esp-tools-button-border-radius, 9999px);\n }\n button:hover::before {\n background-color: rgba(255,255,255,.8);\n }\n button:focus {\n outline: none;\n }\n button:focus::before {\n background-color: white;\n }\n button:active::before {\n background-color: grey;\n }\n :host([active]) button {\n color: rgba(0, 0, 0, 0.38);\n background-color: rgba(0, 0, 0, 0.12);\n box-shadow: none;\n cursor: unset;\n pointer-events: none;\n }\n improv-wifi-launch-button {\n display: block;\n margin-top: 16px;\n }\n .hidden {\n display: none;\n }',customElements.define("esp-web-install-button",ti);export{_ as C,C as a,B as b,R as c,v as d,S as e,y as f,b as g,m as h,w as i,p as j,Qe as k};
|
|
1
|
+
const t=t=>{let e=[192];for(const i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e.push(192),e},e=t=>{const e=[];for(let i=0;i<t.length;i++){const s=t.charCodeAt(i);s<=255&&e.push(s)}return e},i=t=>"["+t.map(t=>s(t)).join(", ")+"]",s=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},a=t=>new Promise(e=>setTimeout(e,t)),r={18:"256KB",19:"512KB",20:"1MB",21:"2MB",22:"4MB",23:"8MB",24:"16MB",25:"32MB",26:"64MB",27:"128MB",28:"256MB",32:"64MB",33:"128MB",34:"256MB",50:"256KB",51:"512KB",52:"1MB",53:"2MB",54:"4MB",55:"8MB",56:"16MB",57:"32MB",58:"64MB"},n=4096,o=115200,h=1610647552,l=1343410176,d=1343312316,c=1<<27,u=1343312312,g=1343312892,f=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),_=33382,p=50,w=12882,m=12883,b=12994,y=12995,S=12997,v=12998,R=207969,B=12914,U=12916,I=12917,C=12928,x=12849,k={5:{name:"ESP32-C3",family:y},9:{name:"ESP32-S3",family:m},12:{name:"ESP32-C2",family:b},13:{name:"ESP32-C6",family:v},16:{name:"ESP32-H2",family:B},18:{name:"ESP32-P4",family:C},20:{name:"ESP32-C61",family:R},23:{name:"ESP32-C5",family:S},25:{name:"ESP32-H21",family:I},28:{name:"ESP32-H4",family:U},32:{name:"ESP32-S31",family:x}},F={4293968129:{name:"ESP8266",family:_},15736195:{name:"ESP32",family:p},1990:{name:"ESP32-S2",family:w}},T=3e3,D=15e4,E=100,O=3e4,M=(t,e)=>{const i=Math.floor(t*(e/486));return i<T?T:i},z=t=>{switch(t){case p:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case w:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case m:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case _:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case b:return{regBase:1610620928,baseFuse:h,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case y:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case S:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case v:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case R:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case B:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case U:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case I:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case C:return{regBase:1342754816,baseFuse:l,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case x:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class $ extends Error{constructor(t){super(t),this.name="SlipReadError"}}const A=async(t,i)=>{let s;if(t==U||t==I||t==x)return null;if(t==p)s=await import("./esp32-BRKoi17y.js");else if(t==w)s=await import("./esp32s2-iX3WoDbg.js");else if(t==m)s=await import("./esp32s3-DGwDVIgz.js");else if(t==_)s=await import("./esp8266-CUwxJpGa.js");else if(t==b)s=await import("./esp32c2-Btgr_lwh.js");else if(t==y)s=await import("./esp32c3-CHKfoI8W.js");else if(t==S)s=await import("./esp32c5-BDW4KtLo.js");else if(t==v)s=await import("./esp32c6-il8tTxAG.js");else if(t==R)s=await import("./esp32c61-thKzxBGf.js");else if(t==B)s=await import("./esp32h2-CxoUHv_P.js");else{if(t!=C)return null;s=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")}return{...s,text:e(atob(s.text)),data:e(atob(s.data))}};function P(t){let e=t.length;for(;--e>=0;)t[e]=0}const W=256,L=286,N=30,H=15,V=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Z=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),G=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),J=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),j=new Array(576);P(j);const q=new Array(60);P(q);const Y=new Array(512);P(Y);const K=new Array(256);P(K);const X=new Array(29);P(X);const Q=new Array(N);function tt(t,e,i,s,a){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=a,this.has_stree=t&&t.length}let et,it,st;function at(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}P(Q);const rt=t=>t<256?Y[t]:Y[256+(t>>>7)],nt=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},ot=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,nt(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},ht=(t,e,i)=>{ot(t,i[2*e],i[2*e+1])},lt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},dt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=H;a++)n=n+i[a-1]<<1,s[a]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=lt(s[e]++,e))}},ct=t=>{let e;for(e=0;e<L;e++)t.dyn_ltree[2*e]=0;for(e=0;e<N;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},ut=t=>{t.bi_valid>8?nt(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},gt=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},ft=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&>(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!gt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},_t=(t,e,i)=>{let s,a,r,n,o=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+o++],s+=(255&t.pending_buf[t.sym_buf+o++])<<8,a=t.pending_buf[t.sym_buf+o++],0===s?ht(t,a,e):(r=K[a],ht(t,r+W+1,e),n=V[r],0!==n&&(a-=X[r],ot(t,a,n)),s--,r=rt(s),ht(t,r,i),n=Z[r],0!==n&&(s-=Q[r],ot(t,s,n)))}while(o<t.sym_next);ht(t,256,e)},pt=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=e.stat_desc.has_stree,r=e.stat_desc.elems;let n,o,h,l=-1;for(t.heap_len=0,t.heap_max=573,n=0;n<r;n++)0!==i[2*n]?(t.heap[++t.heap_len]=l=n,t.depth[n]=0):i[2*n+1]=0;for(;t.heap_len<2;)h=t.heap[++t.heap_len]=l<2?++l:0,i[2*h]=1,t.depth[h]=0,t.opt_len--,a&&(t.static_len-=s[2*h+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)ft(t,i,n);h=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ft(t,i,1),o=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=o,i[2*h]=i[2*n]+i[2*o],t.depth[h]=(t.depth[n]>=t.depth[o]?t.depth[n]:t.depth[o])+1,i[2*n+1]=i[2*o+1]=h,t.heap[1]=h++,ft(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,s=e.max_code,a=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,h=e.stat_desc.max_length;let l,d,c,u,g,f,_=0;for(u=0;u<=H;u++)t.bl_count[u]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)d=t.heap[l],u=i[2*i[2*d+1]+1]+1,u>h&&(u=h,_++),i[2*d+1]=u,d>s||(t.bl_count[u]++,g=0,d>=o&&(g=n[d-o]),f=i[2*d],t.opt_len+=f*(u+g),r&&(t.static_len+=f*(a[2*d+1]+g)));if(0!==_){do{for(u=h-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[h]--,_-=2}while(_>0);for(u=h;0!==u;u--)for(d=t.bl_count[u];0!==d;)c=t.heap[--l],c>s||(i[2*c+1]!==u&&(t.opt_len+=(u-i[2*c+1])*i[2*c],i[2*c+1]=u),d--)}})(t,e),dt(i,l,t.bl_count)},wt=(t,e,i)=>{let s,a,r=-1,n=e[1],o=0,h=7,l=4;for(0===n&&(h=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++o<h&&a===n||(o<l?t.bl_tree[2*a]+=o:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,r=a,0===n?(h=138,l=3):a===n?(h=6,l=3):(h=7,l=4))},mt=(t,e,i)=>{let s,a,r=-1,n=e[1],o=0,h=7,l=4;for(0===n&&(h=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++o<h&&a===n)){if(o<l)do{ht(t,a,t.bl_tree)}while(0!==--o);else 0!==a?(a!==r&&(ht(t,a,t.bl_tree),o--),ht(t,16,t.bl_tree),ot(t,o-3,2)):o<=10?(ht(t,17,t.bl_tree),ot(t,o-3,3)):(ht(t,18,t.bl_tree),ot(t,o-11,7));o=0,r=a,0===n?(h=138,l=3):a===n?(h=6,l=3):(h=7,l=4)}};let bt=!1;const yt=(t,e,i,s)=>{ot(t,0+(s?1:0),3),ut(t),nt(t,i),nt(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var St=(t,e,i,s)=>{let a,r,n=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<W;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),pt(t,t.l_desc),pt(t,t.d_desc),n=(t=>{let e;for(wt(t,t.dyn_ltree,t.l_desc.max_code),wt(t,t.dyn_dtree,t.d_desc.max_code),pt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*J[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=a&&(a=r)):a=r=i+5,i+4<=a&&-1!==e?yt(t,e,i,s):4===t.strategy||r===a?(ot(t,2+(s?1:0),3),_t(t,j,q)):(ot(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(ot(t,e-257,5),ot(t,i-1,5),ot(t,s-4,4),a=0;a<s;a++)ot(t,t.bl_tree[2*J[a]+1],3);mt(t,t.dyn_ltree,e-1),mt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),_t(t,t.dyn_ltree,t.dyn_dtree)),ct(t),s&&ut(t)},vt={_tr_init:t=>{bt||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(X[s]=i,t=0;t<1<<V[s];t++)K[i++]=s;for(K[i-1]=s,a=0,s=0;s<16;s++)for(Q[s]=a,t=0;t<1<<Z[s];t++)Y[a++]=s;for(a>>=7;s<N;s++)for(Q[s]=a<<7,t=0;t<1<<Z[s]-7;t++)Y[256+a++]=s;for(e=0;e<=H;e++)r[e]=0;for(t=0;t<=143;)j[2*t+1]=8,t++,r[8]++;for(;t<=255;)j[2*t+1]=9,t++,r[9]++;for(;t<=279;)j[2*t+1]=7,t++,r[7]++;for(;t<=287;)j[2*t+1]=8,t++,r[8]++;for(dt(j,287,r),t=0;t<N;t++)q[2*t+1]=5,q[2*t]=lt(t,5);et=new tt(j,V,257,L,H),it=new tt(q,Z,0,N,H),st=new tt(new Array(0),G,0,19,7)})(),bt=!0),t.l_desc=new at(t.dyn_ltree,et),t.d_desc=new at(t.dyn_dtree,it),t.bl_desc=new at(t.bl_tree,st),t.bi_buf=0,t.bi_valid=0,ct(t)},_tr_stored_block:yt,_tr_flush_block:St,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(K[i]+W+1)]++,t.dyn_dtree[2*rt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{ot(t,2,3),ht(t,256,j),(t=>{16===t.bi_valid?(nt(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var Rt=(t,e,i,s)=>{let a=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{a=a+e[s++]|0,r=r+a|0}while(--n);a%=65521,r%=65521}return a|r<<16};const Bt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var Ut=(t,e,i,s)=>{const a=Bt,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},It={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Ct={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:xt,_tr_stored_block:kt,_tr_flush_block:Ft,_tr_tally:Tt,_tr_align:Dt}=vt,{Z_NO_FLUSH:Et,Z_PARTIAL_FLUSH:Ot,Z_FULL_FLUSH:Mt,Z_FINISH:zt,Z_BLOCK:$t,Z_OK:At,Z_STREAM_END:Pt,Z_STREAM_ERROR:Wt,Z_DATA_ERROR:Lt,Z_BUF_ERROR:Nt,Z_DEFAULT_COMPRESSION:Ht,Z_FILTERED:Vt,Z_HUFFMAN_ONLY:Zt,Z_RLE:Gt,Z_FIXED:Jt,Z_DEFAULT_STRATEGY:jt,Z_UNKNOWN:qt,Z_DEFLATED:Yt}=Ct,Kt=258,Xt=262,Qt=42,te=113,ee=666,ie=(t,e)=>(t.msg=It[e],e),se=t=>2*t-(t>4?9:0),ae=t=>{let e=t.length;for(;--e>=0;)t[e]=0},re=t=>{let e,i,s,a=t.w_size;e=t.hash_size,s=e;do{i=t.head[--s],t.head[s]=i>=a?i-a:0}while(--e);e=a,s=e;do{i=t.prev[--s],t.prev[s]=i>=a?i-a:0}while(--e)};let ne=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const oe=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},he=(t,e)=>{Ft(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,oe(t.strm)},le=(t,e)=>{t.pending_buf[t.pending++]=e},de=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ce=(t,e,i,s)=>{let a=t.avail_in;return a>s&&(a=s),0===a?0:(t.avail_in-=a,e.set(t.input.subarray(t.next_in,t.next_in+a),i),1===t.state.wrap?t.adler=Rt(t.adler,e,a,i):2===t.state.wrap&&(t.adler=Ut(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},ue=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,o=t.nice_match;const h=t.strstart>t.w_size-Xt?t.strstart-(t.w_size-Xt):0,l=t.window,d=t.w_mask,c=t.prev,u=t.strstart+Kt;let g=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(a>>=2),o>t.lookahead&&(o=t.lookahead);do{if(i=e,l[i+n]===f&&l[i+n-1]===g&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do{}while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<u);if(s=Kt-(u-r),r=u-Kt,s>n){if(t.match_start=e,n=s,s>=o)break;g=l[r+n-1],f=l[r+n]}}}while((e=c[e&d])>h&&0!==--a);return n<=t.lookahead?n:t.lookahead},ge=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Xt)&&(t.window.set(t.window.subarray(e,e+e-s),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),re(t),s+=e),0===t.strm.avail_in)break;if(i=ce(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=ne(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=ne(t,t.ins_h,t.window[a+3-1]),t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Xt&&0!==t.strm.avail_in)},fe=(t,e)=>{let i,s,a,r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n=0,o=t.strm.avail_in;do{if(i=65535,a=t.bi_valid+42>>3,t.strm.avail_out<a)break;if(a=t.strm.avail_out-a,s=t.strstart-t.block_start,i>s+t.strm.avail_in&&(i=s+t.strm.avail_in),i>a&&(i=a),i<r&&(0===i&&e!==zt||e===Et||i!==s+t.strm.avail_in))break;n=e===zt&&i===s+t.strm.avail_in?1:0,kt(t,0,0,n),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,oe(t.strm),s&&(s>i&&(s=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+s),t.strm.next_out),t.strm.next_out+=s,t.strm.avail_out-=s,t.strm.total_out+=s,t.block_start+=s,i-=s),i&&(ce(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(0===n);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==Et&&e!==zt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(a=t.window_size-t.strstart,t.strm.avail_in>a&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(ce(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=r||(s||e===zt)&&e!==Et&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===zt&&0===t.strm.avail_in&&i===s?1:0,kt(t,t.block_start,i,n),t.block_start+=i,oe(t.strm)),n?3:1)},_e=(t,e)=>{let i,s;for(;;){if(t.lookahead<Xt){if(ge(t),t.lookahead<Xt&&e===Et)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Xt&&(t.match_length=ue(t,i)),t.match_length>=3)if(s=Tt(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ne(t,t.ins_h,t.window[t.strstart+1]);else s=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2},pe=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<Xt){if(ge(t),t.lookahead<Xt&&e===Et)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Xt&&(t.match_length=ue(t,i),t.match_length<=5&&(t.strategy===Vt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){a=t.strstart+t.lookahead-3,s=Tt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=a&&(t.ins_h=ne(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,s&&(he(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Tt(t,0,t.window[t.strstart-1]),s&&he(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(s=Tt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2};function we(t,e,i,s,a){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=a}const me=[new we(0,0,0,0,fe),new we(4,4,8,4,_e),new we(4,5,16,8,_e),new we(4,6,32,32,_e),new we(4,4,16,16,pe),new we(8,16,32,32,pe),new we(8,16,128,128,pe),new we(8,32,128,256,pe),new we(32,128,258,1024,pe),new we(32,258,258,4096,pe)];function be(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Yt,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),ae(this.dyn_ltree),ae(this.dyn_dtree),ae(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),ae(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ae(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const ye=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Qt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==te&&e.status!==ee?1:0},Se=t=>{if(ye(t))return ie(t,Wt);t.total_in=t.total_out=0,t.data_type=qt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Qt:te,t.adler=2===e.wrap?0:1,e.last_flush=-2,xt(e),At},ve=t=>{const e=Se(t);var i;return e===At&&((i=t.state).window_size=2*i.w_size,ae(i.head),i.max_lazy_match=me[i.level].max_lazy,i.good_match=me[i.level].good_length,i.nice_match=me[i.level].nice_length,i.max_chain_length=me[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},Re=(t,e,i,s,a,r)=>{if(!t)return Wt;let n=1;if(e===Ht&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==Yt||s<8||s>15||e<0||e>9||r<0||r>Jt||8===s&&1!==n)return ie(t,Wt);8===s&&(s=9);const o=new be;return t.state=o,o.strm=t,o.status=Qt,o.wrap=n,o.gzhead=null,o.w_bits=s,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=a+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<a+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=r,o.method=i,ve(t)};var Be={deflateInit:(t,e)=>Re(t,e,Yt,15,8,jt),deflateInit2:Re,deflateReset:ve,deflateResetKeep:Se,deflateSetHeader:(t,e)=>ye(t)||2!==t.state.wrap?Wt:(t.state.gzhead=e,At),deflate:(t,e)=>{if(ye(t)||e>$t||e<0)return t?ie(t,Wt):Wt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===ee&&e!==zt)return ie(t,0===t.avail_out?Nt:Wt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(oe(t),0===t.avail_out)return i.last_flush=-1,At}else if(0===t.avail_in&&se(e)<=se(s)&&e!==zt)return ie(t,Nt);if(i.status===ee&&0!==t.avail_in)return ie(t,Nt);if(i.status===Qt&&0===i.wrap&&(i.status=te),i.status===Qt){let e=Yt+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=Zt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=s<<6,0!==i.strstart&&(e|=32),e+=31-e%31,de(i,e),0!==i.strstart&&(de(i,t.adler>>>16),de(i,65535&t.adler)),t.adler=1,i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At}if(57===i.status)if(t.adler=0,le(i,31),le(i,139),le(i,8),i.gzhead)le(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),le(i,255&i.gzhead.time),le(i,i.gzhead.time>>8&255),le(i,i.gzhead.time>>16&255),le(i,i.gzhead.time>>24&255),le(i,9===i.level?2:i.strategy>=Zt||i.level<2?4:0),le(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(le(i,255&i.gzhead.extra.length),le(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=Ut(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(le(i,0),le(i,0),le(i,0),le(i,0),le(i,0),le(i,9===i.level?2:i.strategy>=Zt||i.level<2?4:0),le(i,3),i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At;if(69===i.status){if(i.gzhead.extra){let e=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,oe(t),0!==i.pending)return i.last_flush=-1,At;e=0,s-=a}let a=new Uint8Array(i.gzhead.extra);i.pending_buf.set(a.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>e&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),oe(t),0!==i.pending)return i.last_flush=-1,At;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,le(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s)),oe(t),0!==i.pending)return i.last_flush=-1,At;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,le(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=Ut(t.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(oe(t),0!==i.pending))return i.last_flush=-1,At;le(i,255&t.adler),le(i,t.adler>>8&255),t.adler=0}if(i.status=te,oe(t),0!==i.pending)return i.last_flush=-1,At}if(0!==t.avail_in||0!==i.lookahead||e!==Et&&i.status!==ee){let s=0===i.level?fe(i,e):i.strategy===Zt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(ge(t),0===t.lookahead)){if(e===Et)return 1;break}if(t.match_length=0,i=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Gt?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=Kt){if(ge(t),t.lookahead<=Kt&&e===Et)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=n[a],s===n[++a]&&s===n[++a]&&s===n[++a])){r=t.strstart+Kt;do{}while(s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&a<r);t.match_length=Kt-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Tt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Tt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(he(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===zt?(he(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(he(t,!1),0===t.strm.avail_out)?1:2})(i,e):me[i.level].func(i,e);if(3!==s&&4!==s||(i.status=ee),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),At;if(2===s&&(e===Ot?Dt(i):e!==$t&&(kt(i,0,0,!1),e===Mt&&(ae(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),oe(t),0===t.avail_out))return i.last_flush=-1,At}return e!==zt?At:i.wrap<=0?Pt:(2===i.wrap?(le(i,255&t.adler),le(i,t.adler>>8&255),le(i,t.adler>>16&255),le(i,t.adler>>24&255),le(i,255&t.total_in),le(i,t.total_in>>8&255),le(i,t.total_in>>16&255),le(i,t.total_in>>24&255)):(de(i,t.adler>>>16),de(i,65535&t.adler)),oe(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?At:Pt)},deflateEnd:t=>{if(ye(t))return Wt;const e=t.state.status;return t.state=null,e===te?ie(t,Lt):At},deflateSetDictionary:(t,e)=>{let i=e.length;if(ye(t))return Wt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==Qt||s.lookahead)return Wt;if(1===a&&(t.adler=Rt(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(ae(s.head),s.strstart=0,s.block_start=0,s.insert=0);let t=new Uint8Array(s.w_size);t.set(e.subarray(i-s.w_size,i),0),e=t,i=s.w_size}const r=t.avail_in,n=t.next_in,o=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,ge(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=ne(s,s.ins_h,s.window[t+3-1]),s.prev[t&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=t,t++}while(--e);s.strstart=t,s.lookahead=2,ge(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,t.next_in=n,t.input=o,t.avail_in=r,s.wrap=a,At},deflateInfo:"pako deflate (from Nodeca project)"};const Ue=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ie=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)Ue(i,e)&&(t[e]=i[e])}}return t},Ce=t=>{let e=0;for(let i=0,s=t.length;i<s;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,s=0,a=t.length;e<a;e++){let a=t[e];i.set(a,s),s+=a.length}return i};let xe=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){xe=!1}const ke=new Uint8Array(256);for(let t=0;t<256;t++)ke[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;ke[254]=ke[254]=1;var Fe=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,o=0;for(a=0;a<n;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(o),r=0,a=0;r<o;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),i<128?e[r++]=i:i<2048?(e[r++]=192|i>>>6,e[r++]=128|63&i):i<65536?(e[r++]=224|i>>>12,e[r++]=128|i>>>6&63,e[r++]=128|63&i):(e[r++]=240|i>>>18,e[r++]=128|i>>>12&63,e[r++]=128|i>>>6&63,e[r++]=128|63&i);return e};var Te=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const De=Object.prototype.toString,{Z_NO_FLUSH:Ee,Z_SYNC_FLUSH:Oe,Z_FULL_FLUSH:Me,Z_FINISH:ze,Z_OK:$e,Z_STREAM_END:Ae,Z_DEFAULT_COMPRESSION:Pe,Z_DEFAULT_STRATEGY:We,Z_DEFLATED:Le}=Ct;function Ne(t){this.options=Ie({level:Pe,method:Le,chunkSize:16384,windowBits:15,memLevel:8,strategy:We},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Te,this.strm.avail_out=0;let i=Be.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==$e)throw new Error(It[i]);if(e.header&&Be.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Fe(e.dictionary):"[object ArrayBuffer]"===De.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=Be.deflateSetDictionary(this.strm,t),i!==$e)throw new Error(It[i]);this._dict_set=!0}}Ne.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?ze:Ee,"string"==typeof t?i.input=Fe(t):"[object ArrayBuffer]"===De.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),(r===Oe||r===Me)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=Be.deflate(i,r),a===Ae)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=Be.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===$e;if(0!==i.avail_out){if(r>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},Ne.prototype.onData=function(t){this.chunks.push(t)},Ne.prototype.onEnd=function(t){t===$e&&(this.result=Ce(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var He={deflate:function(t,e){const i=new Ne(e);if(i.push(t,!0),i.err)throw i.msg||It[i.err];return i.result}};const{deflate:Ve}=He;var Ze=Ve;const Ge={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},Je=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(r(t[s],e[i]),i++);function r(t,e){if(!(t in Ge))throw"Unhandled character '"+t+"' in pack format";const i=Ge[t].bytes,r=new DataView(new ArrayBuffer(i));Ge[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},je=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:r(e);function r(t){if(!(t in Ge))throw"Unhandled character '"+t+"' in unpack format";const r=Ge[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const o=Ge[t].u.bind(n);s.push(o(0,a)),i+=r}return s};class qe extends EventTarget{get isUsbJtagOrOtg(){return this._parent?this._parent._isUsbJtagOrOtg:this._isUsbJtagOrOtg}constructor(t,e,i){super(),this.port=t,this.logger=e,this._parent=i,this.__chipName=null,this.__chipRevision=null,this.__chipVariant=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null,this.currentBaudRate=o,this.SLIP_END=192,this.SLIP_ESC=219,this.SLIP_ESC_END=220,this.SLIP_ESC_ESC=221,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.__commandLock=Promise.resolve([0,[]]),this.__isReconfiguring=!1,this.__abandonCurrentOperation=!1,this._suppressDisconnect=!1,this.__consoleMode=!1,this._isUsbJtagOrOtg=void 0,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.state_RTS=!1,this.__writeChain=Promise.resolve()}get chipFamily(){return this._parent?this._parent.chipFamily:this.__chipFamily}set chipFamily(t){this._parent?this._parent.chipFamily=t:this.__chipFamily=t}get chipName(){return this._parent?this._parent.chipName:this.__chipName}set chipName(t){this._parent?this._parent.chipName=t:this.__chipName=t}get chipRevision(){return this._parent?this._parent.chipRevision:this.__chipRevision}set chipRevision(t){this._parent?this._parent.chipRevision=t:this.__chipRevision=t}get chipVariant(){return this._parent?this._parent.chipVariant:this.__chipVariant}set chipVariant(t){this._parent?this._parent.chipVariant=t:this.__chipVariant=t}get _consoleMode(){return this._parent?this._parent._consoleMode:this.__consoleMode}set _consoleMode(t){this._parent?this._parent._consoleMode=t:this.__consoleMode=t}setConsoleMode(t){this._consoleMode=t}get _inputBuffer(){if(this._parent)return this._parent._inputBuffer;if(void 0===this.__inputBuffer)throw new Error("_inputBuffer accessed before initialization");return this.__inputBuffer}get _inputBufferReadIndex(){return this._parent?this._parent._inputBufferReadIndex:this.__inputBufferReadIndex||0}set _inputBufferReadIndex(t){this._parent?this._parent._inputBufferReadIndex=t:this.__inputBufferReadIndex=t}get _inputBufferAvailable(){return this._inputBuffer.length-this._inputBufferReadIndex}_readByte(){if(!(this._inputBufferReadIndex>=this._inputBuffer.length))return this._inputBuffer[this._inputBufferReadIndex++]}_clearInputBuffer(){this._inputBuffer.length=0,this._inputBufferReadIndex=0}_compactInputBuffer(){this._inputBufferReadIndex>1e3&&this._inputBufferReadIndex>this._inputBuffer.length/2&&(this._inputBuffer.splice(0,this._inputBufferReadIndex),this._inputBufferReadIndex=0)}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}get _commandLock(){return this._parent?this._parent._commandLock:this.__commandLock}set _commandLock(t){this._parent?this._parent._commandLock=t:this.__commandLock=t}get _isReconfiguring(){return this._parent?this._parent._isReconfiguring:this.__isReconfiguring}set _isReconfiguring(t){this._parent?this._parent._isReconfiguring=t:this.__isReconfiguring=t}get _abandonCurrentOperation(){return this._parent?this._parent._abandonCurrentOperation:this.__abandonCurrentOperation}set _abandonCurrentOperation(t){this._parent?this._parent._abandonCurrentOperation=t:this.__abandonCurrentOperation=t}get _adaptiveBlockMultiplier(){return this._parent?this._parent._adaptiveBlockMultiplier:this.__adaptiveBlockMultiplier}set _adaptiveBlockMultiplier(t){this._parent?this._parent._adaptiveBlockMultiplier=t:this.__adaptiveBlockMultiplier=t}get _adaptiveMaxInFlightMultiplier(){return this._parent?this._parent._adaptiveMaxInFlightMultiplier:this.__adaptiveMaxInFlightMultiplier}set _adaptiveMaxInFlightMultiplier(t){this._parent?this._parent._adaptiveMaxInFlightMultiplier=t:this.__adaptiveMaxInFlightMultiplier=t}get _consecutiveSuccessfulChunks(){return this._parent?this._parent._consecutiveSuccessfulChunks:this.__consecutiveSuccessfulChunks}set _consecutiveSuccessfulChunks(t){this._parent?this._parent._consecutiveSuccessfulChunks=t:this.__consecutiveSuccessfulChunks=t}get _lastAdaptiveAdjustment(){return this._parent?this._parent._lastAdaptiveAdjustment:this.__lastAdaptiveAdjustment}set _lastAdaptiveAdjustment(t){this._parent?this._parent._lastAdaptiveAdjustment=t:this.__lastAdaptiveAdjustment=t}get _isCDCDevice(){return this._parent?this._parent._isCDCDevice:this.__isCDCDevice}set _isCDCDevice(t){this._parent?this._parent._isCDCDevice=t:this.__isCDCDevice=t}detectUSBSerialChip(t,e){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},18:{name:"ESP32-P4 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0;const t=this.port.getInfo();if(t.usbVendorId&&t.usbProductId){const e=this.detectUSBSerialChip(t.usbVendorId,t.usbProductId);this.logger.log(`USB-Serial: ${e.name} (VID: 0x${t.usbVendorId.toString(16)}, PID: 0x${t.usbProductId.toString(16)})`),e.maxBaudrate&&(this._maxUSBSerialBaudrate=e.maxBaudrate,this.logger.log(`Max baudrate: ${e.maxBaudrate}`)),12346===t.usbVendorId&&2===t.usbProductId&&(this._isESP32S2NativeUSB=!0),(12346===t.usbVendorId||6790===t.usbVendorId&&21971===t.usbProductId)&&(this._isCDCDevice=!0)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip(),this.chipFamily===C&&301===this.chipRevision&&await this.powerOnFlash();try{this._isUsbJtagOrOtg=await this.detectUsbConnectionType(),this.logger.debug("USB connection type: "+(this._isUsbJtagOrOtg?"USB-JTAG/OTG":"External Serial Chip"))}catch(t){this.logger.debug(`Could not detect USB connection type: ${t}`)}const t=z(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=k[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===C?(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)):this.chipFamily===y&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-C3 revision: ${this.chipRevision}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._clearInputBuffer(),await a(E);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=F[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${s(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===C?(this.chipRevision=await this.getChipRevision(),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)):this.chipFamily===y&&(this.chipRevision=await this.getChipRevision()),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily===C){const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}return this.chipFamily===y?await this.getChipRevisionC3():0}async powerOnFlash(){if(this.chipFamily!==C)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await a(10);const t=await this.readRegister(d);await this.writeRegister(d,t|c);const e=await this.readRegister(u);await this.writeRegister(u,128|e);const i=await this.readRegister(g);await this.writeRegister(g,3|i),await a(.05);const s=await this.readRegister(d);await this.writeRegister(d,-134217729&s);const r=await this.readRegister(u);await this.writeRegister(u,-2139095041&r);const n=await this.readRegister(u);await this.writeRegister(u,128|n);const o=await this.readRegister(u);await this.writeRegister(u,-129&o),await a(2),this.logger.debug("Flash powered on successfully")}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:je("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?je("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?je("<I",t.slice(16,20))[0]:0}}async getMacAddress(){if(!this._initializationSucceeded)throw new Error("getMacAddress() requires initialize() to have completed successfully");return this.macAddr().map(t=>t.toString(16).padStart(2,"0").toUpperCase()).join(":")}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{}finally{if(this._isReconfiguring=!1,this._reader){try{this._reader.releaseLock(),this.logger.debug("Reader released in readLoop cleanup")}catch(t){this.logger.debug(`Reader release error in readLoop: ${t}`)}this._reader=void 0}}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this._suppressDisconnect||this.dispatchEvent(new Event("disconnect")),this._suppressDisconnect=!1,this.logger.debug("Finished read loop")}sleep(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async setDTRandRTS(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async runSignalSequence(t){const e=!0===this.port.isWebUSB;for(const i of t)void 0!==i.dtr&&void 0!==i.rts?e?await this.setDTRandRTSWebUSB(i.dtr,i.rts):await this.setDTRandRTS(i.dtr,i.rts):(void 0!==i.dtr&&(e?await this.setDTRWebUSB(i.dtr):await this.setDTR(i.dtr)),void 0!==i.rts&&(e?await this.setRTSWebUSB(i.rts):await this.setRTS(i.rts))),i.delayMs&&await a(i.delayMs)}async hardResetUSBJTAGSerial(){await this.runSignalSequence([{rts:!1},{dtr:!1,delayMs:100},{dtr:!0,rts:!1,delayMs:100},{rts:!0},{dtr:!1,rts:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:200}])}async hardResetClassic(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:50},{dtr:!1,delayMs:200}])}async hardResetToFirmware(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:100},{rts:!1,delayMs:50},{delayMs:200}])}async hardResetUnixTight(){await this.runSignalSequence([{dtr:!0,rts:!0},{dtr:!1,rts:!1},{dtr:!1,rts:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:50},{dtr:!1,rts:!1},{dtr:!1,delayMs:200}])}async setRTSWebUSB(t){this.state_RTS=t,await this.port.setSignals({requestToSend:t,dataTerminalReady:this.state_DTR})}async setDTRWebUSB(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:this.state_RTS})}async setDTRandRTSWebUSB(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.runSignalSequence([{rts:!1,dtr:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:100},{rts:!0,dtr:!0,delayMs:100},{dtr:!0,rts:!1,delayMs:200}])}async hardResetClassicLongDelayWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:500},{dtr:!0,rts:!1,delayMs:200},{dtr:!1,delayMs:500}])}async hardResetClassicShortDelayWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!0,delayMs:50},{dtr:!0,rts:!1,delayMs:25},{dtr:!1,delayMs:100}])}async hardResetInvertedWebUSB(){await this.runSignalSequence([{dtr:!0,rts:!1,delayMs:100},{dtr:!1,rts:!0,delayMs:50},{dtr:!0,delayMs:200}])}async hardResetInvertedDTRWebUSB(){await this.runSignalSequence([{dtr:!0,rts:!0,delayMs:100},{dtr:!1,rts:!1,delayMs:50},{dtr:!0,delayMs:200}])}async hardResetInvertedRTSWebUSB(){await this.runSignalSequence([{dtr:!1,rts:!1,delayMs:100},{dtr:!0,rts:!0,delayMs:50},{dtr:!1,delayMs:200}])}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,s=[],r=this,n=!e&&!i;if(this.isWebUSB()){const a=4292===t.usbVendorId,o=6790===t.usbVendorId,h=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(h?(s.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async()=>await r.hardResetUSBJTAGSerial()}),s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async()=>await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async()=>await r.hardResetClassic()})):(s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async()=>await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"USB-JTAG/Serial (WebUSB)",fn:async()=>await r.hardResetUSBJTAGSerial()}),s.push({name:"Inverted DTR Classic (WebUSB)",fn:async()=>await r.hardResetInvertedDTRWebUSB()}))),n&&(o?(s.push({name:"UnixTight (WebUSB) - CH34x",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CH34x",fn:async()=>await r.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async()=>await r.hardResetInvertedDTRWebUSB()})):a?(s.push({name:"UnixTight (WebUSB) - CP2102",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CP2102",fn:async()=>await r.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async()=>await r.hardResetInvertedDTRWebUSB()})):(s.push({name:"UnixTight (WebUSB)",fn:async()=>await r.hardResetUnixTight()}),s.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassic()}}),s.push({name:"Inverted Both (WebUSB)",fn:async function(){return await r.hardResetInvertedWebUSB()}}),s.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),s.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),a||h||(6790!==t.usbVendorId&&s.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassic()}}),s.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTight()}}),s.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await r.hardResetClassicLongDelayWebUSB()}}),s.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await r.hardResetClassicShortDelayWebUSB()}}),e||i||s.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerial()}}))}else(e||i)&&s.push({name:"USB-JTAG/Serial",fn:async function(){return await r.hardResetUSBJTAGSerial()}}),s.push({name:"UnixTight",fn:async function(){return await r.hardResetUnixTight()}}),e||i||s.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await r.hardResetUSBJTAGSerial()}});let o=null;for(const t of s)try{if(!this.connected||!this.port.writable){this.logger.debug(`Port disconnected, skipping ${t.name} reset`);continue}if(this._abandonCurrentOperation=!1,await t.fn(),n){if(await this.syncWithTimeout(2e3))return void this.logger.log(`Connected USB Serial successfully with ${t.name} reset.`);throw new Error("Sync timeout or abandoned")}{const e=this.sync(),i=new Promise((t,e)=>setTimeout(()=>e(new Error("Sync timeout")),1e3));try{return await Promise.race([e,i]),void this.logger.log(`Connected CDC/JTAG successfully with ${t.name} reset.`)}catch(t){throw new Error("Sync timeout or abandoned")}}}catch(t){if(o=t,this._abandonCurrentOperation=!0,await a(100),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._clearInputBuffer(),await this.drainInputBuffer(200),await this.flushSerialBuffers()}throw this._abandonCurrentOperation=!1,new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${null==o?void 0:o.message}`)}async watchdogReset(){await this.rtcWdtResetChipSpecific()}async getChipRevisionC3(){if(this.chipFamily!==y)return 0;const t=await this.readRegister(1610647632)>>18&7;return(await this.readRegister(1610647640)>>23&7)<<3|t}async rtcWdtResetChipSpecific(){let t,e,i,s;if(this.logger.debug("Hard resetting with watchdog timer..."),this.chipFamily===w)t=1061191852,e=1061191828,i=1061191832,s=1356348065;else if(this.chipFamily===m)t=1610645680,e=1610645656,i=1610645660,s=1356348065;else if(this.chipFamily===y)t=1610645672,e=1610645648,i=1610645652,s=1356348065;else if(this.chipFamily===S||this.chipFamily===v)t=1611340824,e=1611340800,i=1611340804,s=1356348065;else{if(this.chipFamily!==C)throw new Error(`rtcWdtResetChipSpecific() is not supported for ${this.chipFamily}`);t=1343315992,e=1343315968,i=1343315972,s=1356348065}await this.writeRegister(t,s,void 0,0),await this.writeRegister(i,2e3,void 0,0);await this.writeRegister(e,-805306110,void 0,0),await this.writeRegister(t,0,void 0,0),await this.sleep(500)}async tryUsbWdtReset(t){return await this.detectUsbConnectionType()?(await this.rtcWdtResetChipSpecific(),this.logger.debug(`${t}: RTC WDT reset (USB-JTAG/Serial or USB-OTG detected)`),!0):(await this.hardResetClassic(),this.logger.debug("Classic reset."),!1)}async hardReset(t=!1){if(this._consoleMode)return t?void this.logger.debug("Skipping bootloader reset - device is in console mode"):(this.logger.debug("Performing hardware reset (console mode)..."),await this.hardResetToFirmware(),void this.logger.debug("Hardware reset complete"));if(t)4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.debug("USB-JTAG/Serial reset.")):(await this.hardResetClassic(),this.logger.debug("Classic reset."));else{if(this.logger.debug("*** Performing WDT reset strategy ***"),this.chipFamily===w){if(await this.tryUsbWdtReset("ESP32-S2"))return}else if(this.chipFamily===C){if(await this.tryUsbWdtReset("ESP32-P4"))return}else if(this.chipFamily===S){if(await this.tryUsbWdtReset("ESP32-C5"))return}else if(this.chipFamily===v){if(await this.tryUsbWdtReset("ESP32-C6"))return}this.isWebUSB()?(await this.setRTSWebUSB(!0),await this.sleep(200),await this.setRTSWebUSB(!1),await this.sleep(200),this.logger.debug("Hard reset (WebUSB).")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.debug("Hard reset."))}await new Promise(t=>setTimeout(t,1e3))}macAddr(){const t=new Array(6).fill(0),e=this._efuses[0],i=this._efuses[1],s=this._efuses[2],a=this._efuses[3];let r;if(this.chipFamily==_){if(0!=a)r=[a>>16&255,a>>8&255,255&a];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");r=[172,208,116]}else r=[24,254,52];t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==p)t[0]=s>>8&255,t[1]=255&s,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=v&&this.chipFamily!=R&&this.chipFamily!=B&&this.chipFamily!=U&&this.chipFamily!=I&&this.chipFamily!=C&&this.chipFamily!=x)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=e>>24&255,t[3]=e>>16&255,t[4]=e>>8&255,t[5]=255&e}return t}async readRegister(t){this.debug&&this.logger.debug("Reading from Register "+s(t,8));const e=Je("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){const r=async()=>{a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,a);if(null===n)throw new Error("Didn't get enough status bytes");let o=n,h=0;if(this.IS_STUB||this.chipFamily==_?h=2:[p,w,m,b,y,S,v,R,B,U,I,C,x].includes(this.chipFamily)||20===t?h=4:[2,4].includes(o.length)?h=o.length:(h=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${s(t)}, data.length: ${o.length})`)),o.length<h)throw new Error("Didn't get enough status bytes");const l=o.slice(-h,o.length);if(o=o.slice(0,-h),this.debug&&(this.logger.debug("status",l),this.logger.debug("value",r),this.logger.debug("data",o)),1==l[0])throw 5==l[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+s(t))):new Error("Command failure error code "+s(l[1]));return[r,o]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...Je("<BBHI",0,e,i.length,s),...i]);this.debug&&this.logger.debug(`Writing ${a.length} byte${1==a.length?"":"s"}:`,a),await this.writeToStream(a)}async readPacket(t){let e=null,r=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new $("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){if(Date.now()-n>t){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}const a=this._readByte();if(null===e){if(a!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(a)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid head of packet ("+s(a)+")");e=[]}else if(r)if(r=!1,a==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(a!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(a)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid SLIP escape (0xdb, "+s(a)+")");e.push(this.SLIP_ESC)}else if(a==this.SLIP_ESC)r=!0;else{if(a==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(a)}}else await a(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new $("Operation abandoned (reset strategy timeout)");const o=Date.now();for(n=[];Date.now()-o<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await a(1)}if(0==n.length){throw new $("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+i(n));for(const t of n)if(null===e){if(t!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid head of packet ("+s(t)+")");e=[]}else if(r)if(r=!1,t==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(t!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new $("Invalid SLIP escape (0xdb, "+s(t)+")");e.push(this.SLIP_ESC)}else if(t==this.SLIP_ESC)r=!0;else{if(t==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}}}async getResponse(t,e=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(e);if(i.length<8)continue;const[a,r,,n]=je("<BBHI",i.slice(0,8));if(1!=a)continue;const o=i.slice(8);if(null==t||r==t)return[n,o];if(0!=o[0]&&5==o[1])throw await this.drainInputBuffer(200),new Error(`Invalid (unsupported) command ${s(t)}`)}throw new Error("Response doesn't match request")}checksum(t,e=239){for(const i of t)e^=i;return e}async getC5CrystalFreqRomExpect(){return(2130706432&await this.readRegister(1611227408))>>>24}async getC5CrystalFreqDetected(){const t=1048575&await this.readRegister(1610612756),e=o*t/1e6;return e>45?48:e>33?40:26}async setBaudrateC5Rom(t){const e=await this.getC5CrystalFreqRomExpect(),i=await this.getC5CrystalFreqDetected();this.logger.log(`ROM expects crystal freq: ${e} MHz, detected ${i} MHz.`);let s=t;48===i&&40===e?s=Math.trunc(40*t/48):40===i&&48===e&&(s=Math.trunc(48*t/40)),this.logger.log(`Changing baud rate to ${s}...`);try{const t=Je("<II",s,0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${s}: No response from set baud rate command.`)}this.logger.log("Changed.")}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==S)try{const e=Je("<II",t,this.IS_STUB?o:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}else await this.setBaudrateC5Rom(t);this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(E),this._parent?this._parent.currentBaudRate=t:this.currentBaudRate=t;const i=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;i&&t>i&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${i})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;this._isReconfiguring=!0;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this.isWebUSB()){const e=this.port.getInfo(),i=6790===e.usbVendorId&&21971===e.usbProductId;if(!i&&"function"==typeof this.port.setBaudRate)return await this.port.setBaudRate(t),void await a(100)}if(this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconfigure: ${t}`)}this._writer=void 0}await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(t){}finally{this._isReconfiguring=!1}}async syncWithTimeout(t){const e=Date.now();for(let i=0;i<5;i++){if(Date.now()-e>t)return!1;if(this._abandonCurrentOperation)return!1;this._clearInputBuffer();try{if(await this._sync())return await a(E),!0}catch(t){if(this._abandonCurrentOperation)return!1}await a(E)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await a(E),!0;await a(E)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,f);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,E);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){this.debug&&this.logger.debug(`Sync attempt ${t+1} failed: ${e}`)}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,a=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],a=e[2],r=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(r)}`)}const r=t.byteLength;let n,o=0,h=T;a?(n=Ze(new Uint8Array(t),{level:9}).buffer,o=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${o}`),h=await this.flashDeflBegin(r,o,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],d=0,c=0,u=0;const g=Date.now(),f=this.getFlashWriteSize(),_=a?o:r;for(;_-u>0;)this.debug&&this.logger.log(`Writing at ${s(i+d*f,8)} `),_-u>=f?l=Array.from(new Uint8Array(n,u,f)):(l=Array.from(new Uint8Array(n,u,_-u)),a||(l=l.concat(new Array(f-l.length).fill(255)))),a?await this.flashDeflBlock(l,d,h):await this.flashBlock(l,d),d+=1,c+=a?Math.round(l.length*r/o):l.length,u+=f,e(Math.min(c,r),r);this.logger.log("Took "+(Date.now()-g)+"ms to write "+_+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),a?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[p,w,m,b,y,S,v,R,B,U,I,C,x].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=_||this.IS_STUB?t:this.getEraseSize(e,t);const o=this.IS_STUB?T:M(O,t),h=Date.now();let l=Je("<IIII",a,n,r,e);return this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=v&&this.chipFamily!=R&&this.chipFamily!=B&&this.chipFamily!=U&&this.chipFamily!=I&&this.chipFamily!=C&&this.chipFamily!=x||(l=l.concat(Je("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+n+", block size "+s(r,4)+", offset "+s(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,l,0,o),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-h)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(t=0,e=0,i=0){const s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),r=Math.floor((t+s-1)/s);let n=0,o=0;this.IS_STUB?(n=t,o=M(O,n)):(n=r*s,o=T);const h=Je("<IIII",n,a,s,i);return await this.checkCommand(16,h,0,o),o}async flashFinish(){const t=Je("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=Je("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return z(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(t,e,i=4294967295,s=0,a=0){let r=Je("<IIII",t,e,i,s);a>0&&(r=r.concat(Je("<IIII",z(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const s=t.regBase+t.mosiDlenOffs,a=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(s,e-1),i>0&&await this.writeRegister(a,i-1)}else{const s=t.regBase+t.usr1Offs,a=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(s,a)}}async waitDone(t,e){for(let i=0;i<10;i++){if(0==(await this.readRegister(t)&e))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(t,e,i=0){const a=z(this.getChipFamily()),r=a.regBase,n=r,o=r+a.usrOffs,h=r+a.usr2Offs,l=r+a.w0Offs,d=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(e.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const c=8*e.length,u=await this.readRegister(o),g=await this.readRegister(h);let f=1<<31;if(i>0&&(f|=268435456),c>0&&(f|=134217728),await this.setDataLengths(a,c,i),await this.writeRegister(o,f),await this.writeRegister(h,7<<28|t),0==c)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=je("I".repeat(Math.floor(e.length/4)),e);let a=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${s(t)} to register offset ${s(a)}`),await this.writeRegister(a,t),a+=4}await this.writeRegister(n,d),await this.waitDone(n,d);const _=await this.readRegister(l);return await this.writeRegister(o,u),await this.writeRegister(h,g),_}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${s(t)}`),this.logger.log(`Flash Manufacturer: ${e.toString(16)}`),this.logger.log(`Flash Device: ${(t>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=r[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=n,s=Math.floor((e+i-1)/i);let a=16-Math.floor(t/i)%16;return s<a&&(a=s),s<2*a?Math.floor((s+1)/2*i):(s-a)*i}async memBegin(t,e,i,s){return await this.checkCommand(5,Je("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,Je("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?T:500,i=Je("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){this.logger.debug(`Loading stub for ${this.chipName}, revision: ${this.chipRevision}`);const e=await A(this.chipFamily,this.chipRevision);if(null===e)return this.logger.log(`Stub flasher is not yet supported on ${this.chipName}, using ROM loader`),this;const i=2048;this.logger.log("Uploading stub...");for(const t of["text","data"]){const s=e[t],a=e[`${t}_start`],r=s.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,a);for(const t of Array(n).keys()){const e=t*i;let a=e+i;a>r&&(a=r),await this.memBlock(s.slice(e,a),t)}}await this.memFinish(e.entry);const s=await this.readPacket(500),a=String.fromCharCode(...s);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");const r=new Ye(this.port,this.logger,this);return t||await r.detectFlashSize(),r}get _reader(){return this._parent?this._parent._reader:this.__reader}set _reader(t){this._parent?this._parent._reader=t:this.__reader=t}get _writer(){return this._parent?this._parent._writer:this.__writer}set _writer(t){this._parent?this._parent._writer=t:this.__writer=t}get _writeChain(){return this._parent?this._parent._writeChain:this.__writeChain}set _writeChain(t){this._parent?this._parent._writeChain=t:this.__writeChain=t}async writeToStream(t){if(this.port.writable){if(this._isReconfiguring)throw new Error("Cannot write during port reconfiguration");this._writeChain=this._writeChain.then(async()=>{if(!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.error(`Failed to get writer: ${t}`),t}await this._writer.write(new Uint8Array(t))},async()=>{if(this.logger.debug("Previous write failed, attempting recovery for current write"),!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.debug(`Failed to get writer in recovery: ${t}`),new Error("Cannot acquire writer lock")}await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch{}this._writer=void 0}throw t}),await this._writeChain}else this.logger.debug("Port writable stream not available, skipping write")}async getUsbMode(){var t,e;const i=this._parent?this._parent.chipFamily:this.chipFamily,s=this._parent?null!==(t=this._parent.chipRevision)&&void 0!==t?t:0:null!==(e=this.chipRevision)&&void 0!==e?e:0;let a=null,r=null,n=null;switch(i){case w:a=1073741076,n=2;break;case m:a=1070526796,r=4,n=3;break;case y:a=(s<101?1070461028:1070461024)+24,r=3;break;case S:a=1082520852,r=3;break;case v:a=1082652032,r=3;break;case R:a=s<=200?1082455532:1082455524,r=s<=200?3:4;break;case B:a=1082457852,r=3;break;case U:a=1082652032,r=3;break;case C:a=s<300?1341390536:1341914824,r=6,n=5}if(null===a)return{mode:"uart",uartNo:0};const o=255&await this.readRegister(a);return null!==n&&o===n?(this.logger.debug(`USB mode: USB-OTG (uartNo=${o})`),{mode:"usb-otg",uartNo:o}):null!==r&&o===r?(this.logger.debug(`USB mode: USB-JTAG/Serial (uartNo=${o})`),{mode:"usb-jtag-serial",uartNo:o}):(this.logger.debug(`USB mode: UART (uartNo=${o})`),{mode:"uart",uartNo:o})}async disconnect(){if(this._parent)await this._parent.disconnect();else if(this.port.writable){try{await this._writeChain}catch(t){}if(this._writer){try{await this._writer.close(),this._writer.releaseLock()}catch(t){}this._writer=void 0}else try{const t=this.port.writable.getWriter();await t.close(),t.releaseLock()}catch(t){}await new Promise(t=>{if(!this._reader)return void t(void 0);const e=setTimeout(()=>{this.logger.debug("Disconnect timeout - forcing resolution"),t(void 0)},1e3);this.addEventListener("disconnect",()=>{clearTimeout(e),t(void 0)},{once:!0});try{this._reader.cancel()}catch(i){clearTimeout(e),t(void 0)}}),this.connected=!1;try{await this.port.close(),this.logger.debug("Port closed successfully")}catch(t){this.logger.debug(`Port close error: ${t}`)}}}async releaseReaderWriter(){if(this._parent)await this._parent.releaseReaderWriter();else{try{await this._writeChain}catch(t){}if(this._writer){try{this._writer.releaseLock(),this.logger.debug("Writer released")}catch(t){this.logger.debug(`Writer release error: ${t}`)}this._writer=void 0}if(this._reader){const t=this._reader;try{this._suppressDisconnect=!0,await t.cancel(),this.logger.debug("Reader cancelled")}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}finally{try{t.releaseLock()}catch(t){this.logger.debug(`Reader release error: ${t}`)}}this._reader===t&&(this._reader=void 0)}}}async resetToFirmware(){return await this._resetToFirmwareIfNeeded()}async detectUsbConnectionType(){const t=this.port.getInfo(),e=t.usbProductId;if(!(12346===t.usbVendorId))return this.logger.debug("Not Espressif VID - external serial chip"),!1;const i=[2,18,4097].includes(e||0);return this.logger.debug(`USB-JTAG/OTG detection: ${i?"YES":"NO"} (PID=0x${null==e?void 0:e.toString(16)})`),i}async enterConsoleMode(){if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - port selection needed"),!0;let t;try{t=await this.detectUsbConnectionType(),this.logger.debug("USB connection type detected: "+(t?"USB-JTAG/OTG":"External Serial Chip")),this._isUsbJtagOrOtg=t}catch(e){if(void 0===this.isUsbJtagOrOtg)throw new Error(`Cannot enter console mode: USB connection type unknown and detection failed: ${e}`);this._consoleMode=!1,this.logger.debug(`USB detection failed, using cached value: ${this.isUsbJtagOrOtg}`),t=this.isUsbJtagOrOtg}if(t){return await this._resetToFirmwareIfNeeded()}try{await this.releaseReaderWriter(),await this.sleep(100)}catch(t){this.logger.debug(`Failed to release locks: ${t}`)}try{await this.hardReset(!1),this.logger.log("Device reset to firmware mode")}catch(t){this.logger.debug(`Could not reset device: ${t}`)}if(this.isWebUSB())try{await this.port.recreateStreams(),this.logger.debug("WebUSB streams recreated for console mode")}catch(t){this._consoleMode=!1,this.logger.debug(`Failed to recreate WebUSB streams: ${t}`)}return this._consoleMode=!0,!1}async _clearForceDownloadBootIfNeeded(){try{let t,e,i;if(this.chipFamily===w)t=1061191976,e=1,i="ESP32-S2";else if(this.chipFamily===m)t=1610645804,e=1,i="ESP32-S3";else{if(this.chipFamily!==C)return!1;t=1343291400,e=4,i="ESP32-P4"}const s=await this.readRegister(t);this.logger.debug(`${i} force download boot register: 0x${s.toString(16)} (mask: 0x${e.toString(16)})`);return 0!==(s&e)?(this.logger.debug(`${i} force download boot flag is SET - clearing it`),await this.writeRegister(t,0,e,0),this.logger.debug(`${i} force download boot flag cleared`),!0):(this.logger.debug(`${i} force download boot flag is already CLEAR - no action needed`),!1)}catch(t){return this.logger.debug(`Error checking/clearing force download flag: ${t}`),!1}}async _resetToFirmwareIfNeeded(){try{if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - assuming device is already in firmware mode"),!1;const t=await this.detectUsbConnectionType();if(t){if(this.IS_STUB){if(this.logger.debug("On stub - need to get back to ROM to check flag"),this.currentBaudRate!==o){this.logger.debug(`Changing baudrate from ${this.currentBaudRate} to 115200 for ROM`);try{await this.reconfigurePort(o),this.currentBaudRate=o}catch(t){this.logger.debug(`Baudrate change failed: ${t}`)}}this.logger.debug("Resetting to bootloader (ROM)...");try{await this.hardReset(!0),await a(200),await this.sync(),this.logger.debug("Now on ROM after reset"),this.IS_STUB=!1}catch(t){return this.logger.debug(`Reset to ROM failed: ${t}`),this.logger.debug("Assuming device is already in firmware mode"),await this.releaseReaderWriter(),!1}}else this.logger.debug("Already on ROM - checking force download flag");await this._clearForceDownloadBootIfNeeded()?this.logger.debug("Force download flag was cleared - device will boot to firmware after reset"):this.logger.debug("Force download flag already clear - device will boot to firmware after reset"),await this.hardReset(!1);return this.chipFamily===w&&t||this.chipFamily===C&&t?(await this.releaseReaderWriter(),this.logger.log(`${this.chipName} USB-OTG: Port will change after WDT reset`),this.logger.log("Please select the new port for console mode"),this.dispatchEvent(new CustomEvent("usb-otg-port-change",{detail:{chipName:this.chipName,message:`${this.chipName} USB port changed after reset. Please select the new port.`,reason:"wdt-reset-to-firmware"}})),!0):(await this.releaseReaderWriter(),!1)}}catch(t){this.logger.debug(`Could not reset device to firmware mode: ${t}`)}return!1}async reconnect(){if(this._parent)await this._parent.reconnect();else try{this.logger.log("Reconnecting serial port...");const t=this.currentBaudRate;this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.debug("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:o}),this.connected=!0,this.currentBaudRate=o}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1;const e=this.chipFamily,i=this.chipName,s=this.chipRevision,a=this.chipVariant,r=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=e,this.chipName=i,this.chipRevision=s,this.chipVariant=a,this.flashSize=r,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");this.chipFamily===C&&301===this.chipRevision&&await this.powerOnFlash();const n=await this.runStub(!0);if(this.logger.debug("Stub loaded"),t!==o&&(await n.setBaudrate(t),!this.port.writable||!this.port.readable))throw new Error(`Port not ready after baudrate change (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this.IS_STUB=!0,this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async reconnectToBootloader(){if(this._parent)await this._parent.reconnectToBootloader();else try{this.logger.log("Reconnecting to bootloader mode..."),this._consoleMode=!1,this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.debug("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:o}),this.connected=!0,this.currentBaudRate=o}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1,this.__chipFamily=void 0,this.chipName="Unknown Chip",this.chipRevision=null,this.chipVariant=null,this.IS_STUB=!1,this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await a(100),await this.connectWithResetStrategies(),await this.detectChip(),this.logger.log(`Reconnected to bootloader: ${this.chipName}`)}catch(t){throw this._isReconfiguring=!1,t}}async exitConsoleMode(){if(this._parent)return await this._parent.exitConsoleMode();this._consoleMode=!1;const t=this.chipFamily===w||this.chipFamily===C;let e=this._isUsbJtagOrOtg;if(t&&void 0===e)try{e=await this.detectUsbConnectionType()}catch(t){this.logger.debug(`USB detection failed, assuming USB-JTAG/OTG for ${this.chipName}: ${t}`),e=!0}if(t&&e){this.logger.log(`${this.chipName} USB: Resetting to bootloader mode`);try{await this.hardResetClassic(),this.logger.debug("Reset to bootloader initiated")}catch(t){this.logger.debug(`Reset error: ${t}`)}return await a(500),this.logger.log(`${this.chipName}: Port changed. Please select the bootloader port.`),this.dispatchEvent(new CustomEvent("usb-otg-port-change",{detail:{chipName:this.chipName,message:`${this.chipName}: Port changed. Please select the bootloader port.`,reason:"exit-console-to-bootloader"}})),!0}return await this.reconnectToBootloader(),!1}isConsoleResetSupported(){if(this._parent)return this._parent.isConsoleResetSupported();return!(this.chipFamily===w&&(!0===this._isUsbJtagOrOtg||void 0===this._isUsbJtagOrOtg))}async resetInConsoleMode(){if(this._parent)return await this._parent.resetInConsoleMode();if(this.isConsoleResetSupported())try{this.logger.debug("Resetting device in console mode"),await this.hardResetToFirmware(),this.logger.debug("Device reset complete")}catch(t){throw this.logger.error(`Reset failed: ${t}`),t}else this.logger.debug("Console reset not supported for ESP32-S2 USB-JTAG/CDC")}async drainInputBuffer(t=200){await a(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBufferAvailable>0){void 0!==this._readByte()&&e++}else await a(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0)}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),await a(E),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s,r){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");let n;await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`),this.isWebUSB()&&(this._isCDCDevice?(this._adaptiveBlockMultiplier=8,this._adaptiveMaxInFlightMultiplier=8,this._consecutiveSuccessfulChunks=0,this.logger.debug(`CDC device - Initialized: blockMultiplier=${this._adaptiveBlockMultiplier}, maxInFlightMultiplier=${this._adaptiveMaxInFlightMultiplier}`)):(this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0,this.logger.debug("Non-CDC device - Fixed values: blockSize=31, maxInFlight=31"))),void 0!==(null==r?void 0:r.chunkSize)?(n=r.chunkSize,this.logger.log(`Using custom chunk size: 0x${n.toString(16)} bytes`)):n=this.isWebUSB()?16384:262144;let o=new Uint8Array(0),h=e,l=i;for(;l>0;){const e=Math.min(n,l);let d=!1,c=0;const u=5;let g=!1;for(;!d&&c<=u;){let i=new Uint8Array(0),s=0;try{let n,l;if(0===c&&this.logger.debug(`Reading chunk at 0x${h.toString(16)}, size: 0x${e.toString(16)}`),void 0!==(null==r?void 0:r.blockSize)&&void 0!==(null==r?void 0:r.maxInFlight))n=r.blockSize,l=r.maxInFlight,0===c&&this.logger.debug(`Using custom parameters: blockSize=${n}, maxInFlight=${l}`);else if(this.isWebUSB()){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2);n=e*this._adaptiveBlockMultiplier,l=e*this._adaptiveMaxInFlightMultiplier}else{const t=63;n=65*t,l=130*t}const u=Je("<IIII",h,e,n,l),[g]=await this.checkCommand(210,u);if(0!=g)throw new Error("Failed to read memory: "+g);for(;i.length<e;){let r;try{r=await this.readPacket(100)}catch(t){if(t instanceof $){this.logger.debug(`SLIP read error at ${i.length} bytes: ${t.message}`);try{const t=[this.SLIP_END,this.SLIP_END];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await a(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(r&&r.length>0){const a=new Uint8Array(r),n=new Uint8Array(i.length+a.length);n.set(i),n.set(a,i.length),i=n;if(i.length>=e||i.length>=s+l){const e=Je("<I",i.length),a=t(e);await this.writeToStream(a),s=i.length}}}const f=new Uint8Array(o.length+i.length);if(f.set(o),f.set(i,o.length),o=f,d=!0,this.isWebUSB()&&this._isCDCDevice&&0===c&&(this._consecutiveSuccessfulChunks++,this._consecutiveSuccessfulChunks>=2)){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=8,s=8;let a=!1;if(this._adaptiveBlockMultiplier<i?(this._adaptiveBlockMultiplier=Math.min(2*this._adaptiveBlockMultiplier,i),a=!0):this._adaptiveMaxInFlightMultiplier<s&&(this._adaptiveMaxInFlightMultiplier=Math.min(2*this._adaptiveMaxInFlightMultiplier,s),a=!0),a){const t=e*this._adaptiveBlockMultiplier,i=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Speed increased: blockSize=${t}, maxInFlight=${i}`),this._lastAdaptiveAdjustment=Date.now()}this._consecutiveSuccessfulChunks=0}}catch(t){if(c++,this.isWebUSB()&&this._isCDCDevice&&1===c)if(this._adaptiveBlockMultiplier>1||this._adaptiveMaxInFlightMultiplier>1){this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0;const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=e*this._adaptiveBlockMultiplier,s=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Error at higher speed - reduced to minimum: blockSize=${i}, maxInFlight=${s}`)}else this.logger.debug("Error at minimum speed (blockSize=31, maxInFlight=31) - not a speed issue");if(!(t instanceof $))throw t;if(c<=u){this.logger.debug(`${t.message} at 0x${h.toString(16)}. Draining buffer and retrying (attempt ${c}/${u})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await a(E)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(g)throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${u} retries and recovery attempt`);g=!0,this.logger.log(`All retries exhausted at 0x${h.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),c=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${u} retries and recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),o.length,i),h+=e,l-=e,this.logger.debug(`Total progress: 0x${o.length.toString(16)} from 0x${i.toString(16)} bytes`)}return o}}class Ye extends qe{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await A(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,o=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(o,8)}`),this.logger.debug(`Stub data: ${s(r.data_start,8)}, len: ${r.data.length}, text: ${s(r.text_start,8)}, len: ${r.text.length}`);for(const[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&o>t)throw new Error("Software loader is resident at "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(n,8)+"-"+s(o,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,D)}async eraseRegion(t,e){if(t<0)throw new Error(`Invalid offset: ${t} (must be non-negative)`);if(e<0)throw new Error(`Invalid size: ${e} (must be non-negative)`);if(0===e)return void this.logger.log("eraseRegion: size is 0, skipping erase");if(t%n!==0)throw new Error(`Offset ${t} (0x${t.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);if(e%n!==0)throw new Error(`Size ${e} (0x${e.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);const i=4294967295;if(t>i)throw new Error(`Offset ${t} exceeds maximum value 4294967295`);if(e>i)throw new Error(`Size ${e} exceeds maximum value 4294967295`);if(t+e>i)throw new Error(`Region end (offset + size = ${t+e}) exceeds maximum addressable range 4294967295`);const s=M(O,e),a=Je("<II",t,e);await this.checkCommand(209,a,0,s)}}const Ke=async t=>{if(import("./install-dialog-HRJeEoXW.js"),(()=>{const t=navigator.userAgent||"";return/Android/i.test(t)})()&&"usb"in navigator)try{await(async()=>{if(!globalThis.requestSerialPort)return new Promise((t,e)=>{const i=document.createElement("script");i.type="module",i.src="https://unpkg.com/tasmota-webserial-esptool/js/webusb-serial.js",i.onload=()=>{globalThis.requestSerialPort?t():e(new Error("WebUSB serial script loaded but requestSerialPort not found"))},i.onerror=()=>e(new Error("Failed to load WebUSB serial script")),document.head.appendChild(i)})})()}catch(t){return void alert(`Failed to load WebUSB support: ${t.message}`)}let e;try{e=await(async t=>{let e;const i=globalThis.requestSerialPort;if("function"==typeof i)e=await i();else{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser. Please use Chrome, Edge, or Opera on desktop, or Chrome on Android. Note: The page must be served over HTTPS or localhost.");e=await navigator.serial.requestPort()}return e.readable&&e.writable||await e.open({baudRate:o}),new qe(e,t)})({log:()=>{},debug:()=>{},error:t=>console.error(t)})}catch(e){return"NotFoundError"===e.name?void import("./index-DUmRg0Cu.js").then(e=>e.openNoPortPickedDialog(()=>Ke(t))):void alert(`Connection failed: ${e.message}`)}if(!e)return void alert("Failed to connect to device");const i=document.createElement("ewt-install-dialog");i.esploader=e,i.manifestPath=t.manifest||t.getAttribute("manifest"),i.overrides=t.overrides,i.firmwareFile=t.firmwareFile;const s=t.getAttribute("baud-rate");if(s){const t=parseInt(s,10);isNaN(t)||(i.baudRate=t)}else void 0!==t.baudRate&&(i.baudRate=t.baudRate);i.addEventListener("closed",async()=>{try{await e.disconnect()}catch(t){}},{once:!0}),document.body.appendChild(i)},Xe="https://cors-proxy.espressif.tools",Qe=async(t,e)=>{if((t=>{try{const e=new URL(t),i=window.location.origin;return e.origin!==i&&"file:"!==e.protocol}catch{return!1}})(t=t.trim())){if(t.includes("github.com")&&t.includes("/releases/download/")){const i=`${Xe}/?url=${encodeURIComponent(t)}`,{headers:s,credentials:a,...r}=null!=e?e:{};return fetch(i,r)}try{return await fetch(t,e)}catch(i){try{const i=`${Xe}/?url=${encodeURIComponent(t)}`,{headers:s,credentials:a,...r}=null!=e?e:{};return await fetch(i,r)}catch(t){throw i}}}return fetch(t,e)};window.espWebToolsCorsProxyFetch=Qe;class ti extends HTMLElement{attributeChangedCallback(t,e,i){if("baud-rate"===t&&i!==e)if(i){const t=parseInt(i,10);this.baudRate=Number.isNaN(t)?void 0:t}else this.baudRate=void 0}connectedCallback(){if(this.renderRoot)return;if(this.renderRoot=this.attachShadow({mode:"open"}),!ti.isSupported||!ti.isAllowed)return this.toggleAttribute("install-unsupported",!0),void(this.renderRoot.innerHTML=ti.isAllowed?"<slot name='unsupported'>Your browser does not support installing things on ESP devices. Use Google Chrome or Microsoft Edge (Desktop) or Chrome on Android with USB OTG.</slot>":"<slot name='not-allowed'>You can only install ESP devices on HTTPS websites or on the localhost.</slot>");this.toggleAttribute("install-supported",!0);const t=document.createElement("slot");t.addEventListener("click",async t=>{t.preventDefault(),Ke(this)}),t.name="activate";const e=document.createElement("button");if(e.innerText="Connect",t.append(e),"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype){const t=new CSSStyleSheet;t.replaceSync(ti.style),this.renderRoot.adoptedStyleSheets=[t]}else{const t=document.createElement("style");t.innerText=ti.style,this.renderRoot.append(t)}this.renderRoot.append(t)}}ti.isSupported="serial"in navigator||"usb"in navigator,ti.isAllowed=window.isSecureContext,ti.observedAttributes=["baud-rate"],ti.style='\n button {\n position: relative;\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n padding: 10px 24px;\n color: var(--esp-tools-button-text-color, #fff);\n background-color: var(--esp-tools-button-color, #03a9f4);\n border: none;\n border-radius: var(--esp-tools-button-border-radius, 9999px);\n }\n button::before {\n content: " ";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n opacity: 0.2;\n border-radius: var(--esp-tools-button-border-radius, 9999px);\n }\n button:hover::before {\n background-color: rgba(255,255,255,.8);\n }\n button:focus {\n outline: none;\n }\n button:focus::before {\n background-color: white;\n }\n button:active::before {\n background-color: grey;\n }\n :host([active]) button {\n color: rgba(0, 0, 0, 0.38);\n background-color: rgba(0, 0, 0, 0.12);\n box-shadow: none;\n cursor: unset;\n pointer-events: none;\n }\n improv-wifi-launch-button {\n display: block;\n margin-top: 16px;\n }\n .hidden {\n display: none;\n }',customElements.define("esp-web-install-button",ti);export{_ as C,C as a,B as b,R as c,v as d,S as e,y as f,b as g,m as h,w as i,p as j,Qe as k};
|
|
@@ -1142,14 +1142,14 @@ import{e,i as t,_ as i,n as r,m as o,a as s,b as a,r as l,c as n,d,f as c,g as h
|
|
|
1142
1142
|
name="password"
|
|
1143
1143
|
type="password"
|
|
1144
1144
|
></ew-filled-text-field>
|
|
1145
|
-
<ew-text-button slot="actions" @click=${this._doProvision}
|
|
1146
|
-
>Connect</ew-text-button
|
|
1147
|
-
>
|
|
1148
1145
|
<ew-text-button
|
|
1149
1146
|
slot="actions"
|
|
1150
1147
|
@click=${async()=>{if(this._client)try{await this._closeClientWithoutEvents(this._client),this.logger.log("Improv client closed")}catch(e){this.logger.log("Failed to close Improv client:",e)}await this._releaseReaderWriter(),this.logger.log("Returning to dashboard (device stays in firmware mode)"),this._state="DASHBOARD"}}
|
|
1151
1148
|
>${this._installState&&this._installErase?"Skip":"Back"}</ew-text-button
|
|
1152
1149
|
>
|
|
1150
|
+
<ew-text-button slot="actions" @click=${this._doProvision}
|
|
1151
|
+
>Connect</ew-text-button
|
|
1152
|
+
>
|
|
1153
1153
|
`}else{t=void 0;const r=!this._wasProvisioned&&(void 0!==this._client.nextUrl||"home_assistant_domain"in this._manifest);i=r,e=u`
|
|
1154
1154
|
<ewt-page-message
|
|
1155
1155
|
.icon=${Hi}
|
|
@@ -1206,17 +1206,22 @@ import{e,i as t,_ as i,n as r,m as o,a as s,b as a,r as l,c as n,d,f as c,g as h
|
|
|
1206
1206
|
</label>
|
|
1207
1207
|
<ew-text-button
|
|
1208
1208
|
slot="actions"
|
|
1209
|
-
@click=${()=>{
|
|
1210
|
-
>
|
|
1209
|
+
@click=${()=>{this._state="DASHBOARD"}}
|
|
1210
|
+
>Back</ew-text-button
|
|
1211
1211
|
>
|
|
1212
1212
|
<ew-text-button
|
|
1213
1213
|
slot="actions"
|
|
1214
|
-
@click=${()=>{this.
|
|
1215
|
-
>
|
|
1214
|
+
@click=${()=>{const e=this.shadowRoot.querySelector("ew-checkbox");this._startInstall(e.checked)}}
|
|
1215
|
+
>Next</ew-text-button
|
|
1216
1216
|
>
|
|
1217
1217
|
`]}_renderInstall(){let e,t,i=!1;const r=!this._installErase&&this._isSameFirmware;if(!this._installConfirmed&&this._isSameVersion)e="Erase User Data",t=u`
|
|
1218
1218
|
Do you want to reset your device and erase all user data from your
|
|
1219
1219
|
device?
|
|
1220
|
+
<ew-text-button
|
|
1221
|
+
slot="actions"
|
|
1222
|
+
@click=${()=>{this._state="DASHBOARD"}}
|
|
1223
|
+
>Back</ew-text-button
|
|
1224
|
+
>
|
|
1220
1225
|
<ew-text-button
|
|
1221
1226
|
class="danger"
|
|
1222
1227
|
slot="actions"
|
|
@@ -1254,14 +1259,14 @@ import{e,i as t,_ as i,n as r,m as o,a as s,b as a,r as l,c as n,d,f as c,g as h
|
|
|
1254
1259
|
Do you want to ${i}
|
|
1255
1260
|
${this._manifest.name} ${this._manifest.version}?
|
|
1256
1261
|
${this._installErase?u`<br /><br />All data on the device will be erased.`:""}
|
|
1257
|
-
<ew-text-button slot="actions" @click=${this._confirmInstall}
|
|
1258
|
-
>Install</ew-text-button
|
|
1259
|
-
>
|
|
1260
1262
|
<ew-text-button
|
|
1261
1263
|
slot="actions"
|
|
1262
1264
|
@click=${()=>{this._state="DASHBOARD"}}
|
|
1263
1265
|
>Back</ew-text-button
|
|
1264
1266
|
>
|
|
1267
|
+
<ew-text-button slot="actions" @click=${this._confirmInstall}
|
|
1268
|
+
>Install</ew-text-button
|
|
1269
|
+
>
|
|
1265
1270
|
`}return[e,t,i,!1]}_renderLogs(){let e;return e=u`
|
|
1266
1271
|
<ew-console
|
|
1267
1272
|
.port=${this._port}
|