esp32tool 1.3.7 → 1.3.8

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/web/index.js CHANGED
@@ -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=>t.map(t=>t.toString(16).toUpperCase().padStart(2,"0")).join(":"),r=t=>new Promise(e=>setTimeout(e,t)),n={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"},h=4096,o=115200,l=1073061888,c=1061265408,d=1610641408,u=1610647552,g=1611352064,f=1611335680,_=1611352064,p=1611335680,b=1343410176,w=1343312316,m=1<<27,S=1343312312,y=1343312892,B=544296960,R=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),I=33382,v=50,U=12882,C=12883,E=12994,k=12995,D=12997,x=12998,O=207969,T=12914,M=12916,A=12917,F=12928,L=12849,P={5:{name:"ESP32-C3",family:k},9:{name:"ESP32-S3",family:C},12:{name:"ESP32-C2",family:E},13:{name:"ESP32-C6",family:x},16:{name:"ESP32-H2",family:T},18:{name:"ESP32-P4",family:F},20:{name:"ESP32-C61",family:O},23:{name:"ESP32-C5",family:D},25:{name:"ESP32-H21",family:A},28:{name:"ESP32-H4",family:M},32:{name:"ESP32-S31",family:L}},z={4293968129:{name:"ESP8266",family:I},15736195:{name:"ESP32",family:v},1990:{name:"ESP32-S2",family:U}},W=2,N=3,$=4,j=5,G=6,H=7,J=8,Q=9,V=10,Z=208,X=209,K=210,q=11,Y=13,tt=15,et=19,it=20,st=239,at=16,rt=17,nt=18,ht=5,ot=2048,lt=6144,ct=3e3,dt=15e4,ut=3e5,gt=100,ft=3e4,_t=500,pt=100,bt=(t,e)=>{const i=Math.floor(t*(e/486));return i<ct?ct:i},wt=t=>{switch(t){case v:return{regBase:1072963584,baseFuse:l,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case U:return{regBase:1061167104,baseFuse:c,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case C:return{regBase:1610620928,usrOffs:24,baseFuse:d,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case I:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case E:return{regBase:1610620928,baseFuse:u,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case k:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case D:return{regBase:1610625024,baseFuse:g,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case x:return{regBase:1610625024,baseFuse:f,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case O:return{regBase:1610625024,baseFuse:_,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case T:return{regBase:1610625024,baseFuse:p,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case M:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case A:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case F:return{regBase:1342754816,baseFuse:b,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case L:return{regBase:542113792,baseFuse:B,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 mt extends Error{constructor(t){super(t),this.name="SlipReadError"}}const St=async(t,i)=>{let s;if(t==M||t==A||t==L)return null;if(t==v)s=await import("./esp32-BRKoi17y.js");else if(t==U)s=await import("./esp32s2-iX3WoDbg.js");else if(t==C)s=await import("./esp32s3-DGwDVIgz.js");else if(t==I)s=await import("./esp8266-CUwxJpGa.js");else if(t==E)s=await import("./esp32c2-Btgr_lwh.js");else if(t==k)s=await import("./esp32c3-CHKfoI8W.js");else if(t==D)s=await import("./esp32c5-BDW4KtLo.js");else if(t==x)s=await import("./esp32c6-il8tTxAG.js");else if(t==O)s=await import("./esp32c61-thKzxBGf.js");else if(t==T)s=await import("./esp32h2-CxoUHv_P.js");else{if(t!=F)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))}},yt={239:"Winbond",200:"GigaDevice",157:"ISSI",194:"Macronix/MXIC",32:"XMC / Micron",28:"EON",133:"Puya",104:"BOYA",161:"Fudan Microelectronics (FM)",1:"Spansion/Cypress",94:"Zbit",55:"AMIC",224:"Berg Micro"},Bt={66073:"S25FL256S (256Mbit)",81941:"S25FL016K (16Mbit)",81942:"S25FL032K (32Mbit)",90135:"S25FL064L (64Mbit)",90136:"S25FL128L (128Mbit)",1847315:"EN25Q40 (4Mbit)",1847316:"EN25Q80A (8Mbit)",1847317:"EN25Q16 (16Mbit)",1847318:"EN25Q32B (32Mbit)",1847319:"EN25Q64 (64Mbit)",1847320:"EN25Q128 (128Mbit)",1863701:"EN25QH16 (16Mbit)",1863702:"EN25QH32 (32Mbit)",1863703:"EN25QH64 (64Mbit)",1863704:"EN25QH128 (128Mbit)",2113557:"XM25QH16C (16Mbit)",2113558:"XM25QH32B (32Mbit)",2113559:"XM25QH64C (64Mbit)",2113560:"XM25QH128C (128Mbit)",2113561:"XM25QH256C (256Mbit)",2113817:"XM25QU256C (256Mbit)",2125847:"XM25QH64A (64Mbit)",2125848:"XM25QH128A (128Mbit)",2144790:"N25Q032A (32Mbit)",2144791:"N25Q064A (64Mbit)",2144792:"N25Q128A (128Mbit)",2145045:"N25Q016A (16Mbit)",3612693:"A25L016 (16Mbit)",3612694:"A25L032 (32Mbit)",3620886:"A25LQ032 (32Mbit)",6176789:"ZB25VQ16 (16Mbit)",6176790:"ZB25VQ32 (32Mbit)",6176791:"ZB25VQ64 (64Mbit)",6176792:"ZB25VQ128 (128Mbit)",6832149:"BY25Q16 (16Mbit)",6832150:"BY25Q32 (32Mbit)",6832151:"BY25Q64 (64Mbit)",6832152:"BY25Q128 (128Mbit)",8740885:"P25Q16H (16Mbit)",8740886:"P25Q32H (32Mbit)",8740887:"P25Q64H (64Mbit)",8740888:"P25Q128H (128Mbit)",10313749:"IS25LP016 (16Mbit)",10313750:"IS25LP032 (32Mbit)",10313751:"IS25LP064 (64Mbit)",10313752:"IS25LP128 (128Mbit)",10313753:"IS25LP256 (256Mbit)",10317845:"IS25WP016 (16Mbit)",10317846:"IS25WP032 (32Mbit)",10317847:"IS25WP064 (64Mbit)",10317848:"IS25WP128 (128Mbit)",10317849:"IS25WP256 (256Mbit)",10567700:"FM25Q08 (8Mbit)",10567701:"FM25Q16 (16Mbit)",10567702:"FM25Q32 (32Mbit)",10567703:"FM25Q64 (64Mbit)",10567704:"FM25Q128 (128Mbit)",12722192:"MX25L512E (512Kbit)",12722193:"MX25L1005C (1Mbit)",12722194:"MX25L2005C (2Mbit)",12722195:"MX25L4005 (4Mbit)",12722196:"MX25L8005 (8Mbit)",12722197:"MX25L1605D (16Mbit)",12722198:"MX25L3205D (32Mbit)",12722199:"MX25L6405D (64Mbit)",12722200:"MX25L12805D (128Mbit)",12722201:"MX25L25635E (256Mbit)",12722202:"MX25L51245G (512Mbit)",12738070:"MX25L3233F (32Mbit)",13123601:"GD25Q10 (1Mbit)",13123602:"GD25Q20 (2Mbit)",13123603:"GD25Q40 (4Mbit)",13123604:"GD25Q80 (8Mbit)",13123605:"GD25Q16 (16Mbit)",13123606:"GD25Q32 (32Mbit)",13123607:"GD25Q64 (64Mbit)",13123608:"GD25Q127C (128Mbit)",13123609:"GD25Q256 (256Mbit)",13123616:"GD25Q512 (512Mbit)",13131801:"GD25LQ256D (256Mbit)",14696469:"BG25Q16A (16Mbit)",14696470:"BG25Q32 (32Mbit)",14696471:"BG25Q64 (64Mbit)",14696472:"BG25Q128 (128Mbit)",15679508:"W25Q80 (8Mbit)",15679509:"W25Q16 (16Mbit)",15679510:"W25Q32 (32Mbit)",15679511:"W25Q64 (64Mbit)",15679512:"W25Q128 (128Mbit)",15679513:"W25Q256 (256Mbit)",15679520:"W25Q512JV (512Mbit)",15683602:"W25Q20BW (2Mbit)",15683603:"W25Q40BW (4Mbit)",15687697:"W25Q10EW (1Mbit)",15687698:"W25Q20EW (2Mbit)",15687699:"W25Q40EW (4Mbit)"};function Rt(t){let e=t.length;for(;--e>=0;)t[e]=0}const It=256,vt=286,Ut=30,Ct=15,Et=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]),kt=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]),Dt=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),xt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ot=new Array(576);Rt(Ot);const Tt=new Array(60);Rt(Tt);const Mt=new Array(512);Rt(Mt);const At=new Array(256);Rt(At);const Ft=new Array(29);Rt(Ft);const Lt=new Array(Ut);function Pt(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 zt,Wt,Nt;function $t(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}Rt(Lt);const jt=t=>t<256?Mt[t]:Mt[256+(t>>>7)],Gt=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},Ht=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,Gt(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)},Jt=(t,e,i)=>{Ht(t,i[2*e],i[2*e+1])},Qt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},Vt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=Ct;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]=Qt(s[e]++,e))}},Zt=t=>{let e;for(e=0;e<vt;e++)t.dyn_ltree[2*e]=0;for(e=0;e<Ut;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},Xt=t=>{t.bi_valid>8?Gt(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},Kt=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},qt=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&&Kt(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!Kt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},Yt=(t,e,i)=>{let s,a,r,n,h=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+h++],s+=(255&t.pending_buf[t.sym_buf+h++])<<8,a=t.pending_buf[t.sym_buf+h++],0===s?Jt(t,a,e):(r=At[a],Jt(t,r+It+1,e),n=Et[r],0!==n&&(a-=Ft[r],Ht(t,a,n)),s--,r=jt(s),Jt(t,r,i),n=kt[r],0!==n&&(s-=Lt[r],Ht(t,s,n)))}while(h<t.sym_next);Jt(t,256,e)},te=(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,h,o,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;)o=t.heap[++t.heap_len]=l<2?++l:0,i[2*o]=1,t.depth[o]=0,t.opt_len--,a&&(t.static_len-=s[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)qt(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],qt(t,i,1),h=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=h,i[2*o]=i[2*n]+i[2*h],t.depth[o]=(t.depth[n]>=t.depth[h]?t.depth[n]:t.depth[h])+1,i[2*n+1]=i[2*h+1]=o,t.heap[1]=o++,qt(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,h=e.stat_desc.extra_base,o=e.stat_desc.max_length;let l,c,d,u,g,f,_=0;for(u=0;u<=Ct;u++)t.bl_count[u]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)c=t.heap[l],u=i[2*i[2*c+1]+1]+1,u>o&&(u=o,_++),i[2*c+1]=u,c>s||(t.bl_count[u]++,g=0,c>=h&&(g=n[c-h]),f=i[2*c],t.opt_len+=f*(u+g),r&&(t.static_len+=f*(a[2*c+1]+g)));if(0!==_){do{for(u=o-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[o]--,_-=2}while(_>0);for(u=o;0!==u;u--)for(c=t.bl_count[u];0!==c;)d=t.heap[--l],d>s||(i[2*d+1]!==u&&(t.opt_len+=(u-i[2*d+1])*i[2*d],i[2*d+1]=u),c--)}})(t,e),Vt(i,l,t.bl_count)},ee=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++h<o&&a===n||(h<l?t.bl_tree[2*a]+=h:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4))},ie=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++h<o&&a===n)){if(h<l)do{Jt(t,a,t.bl_tree)}while(0!==--h);else 0!==a?(a!==r&&(Jt(t,a,t.bl_tree),h--),Jt(t,16,t.bl_tree),Ht(t,h-3,2)):h<=10?(Jt(t,17,t.bl_tree),Ht(t,h-3,3)):(Jt(t,18,t.bl_tree),Ht(t,h-11,7));h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4)}};let se=!1;const ae=(t,e,i,s)=>{Ht(t,0+(s?1:0),3),Xt(t),Gt(t,i),Gt(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var re=(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<It;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),te(t,t.l_desc),te(t,t.d_desc),n=(t=>{let e;for(ee(t,t.dyn_ltree,t.l_desc.max_code),ee(t,t.dyn_dtree,t.d_desc.max_code),te(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*xt[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?ae(t,e,i,s):4===t.strategy||r===a?(Ht(t,2+(s?1:0),3),Yt(t,Ot,Tt)):(Ht(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(Ht(t,e-257,5),Ht(t,i-1,5),Ht(t,s-4,4),a=0;a<s;a++)Ht(t,t.bl_tree[2*xt[a]+1],3);ie(t,t.dyn_ltree,e-1),ie(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),Yt(t,t.dyn_ltree,t.dyn_dtree)),Zt(t),s&&Xt(t)},ne={_tr_init:t=>{se||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(Ft[s]=i,t=0;t<1<<Et[s];t++)At[i++]=s;for(At[i-1]=s,a=0,s=0;s<16;s++)for(Lt[s]=a,t=0;t<1<<kt[s];t++)Mt[a++]=s;for(a>>=7;s<Ut;s++)for(Lt[s]=a<<7,t=0;t<1<<kt[s]-7;t++)Mt[256+a++]=s;for(e=0;e<=Ct;e++)r[e]=0;for(t=0;t<=143;)Ot[2*t+1]=8,t++,r[8]++;for(;t<=255;)Ot[2*t+1]=9,t++,r[9]++;for(;t<=279;)Ot[2*t+1]=7,t++,r[7]++;for(;t<=287;)Ot[2*t+1]=8,t++,r[8]++;for(Vt(Ot,287,r),t=0;t<Ut;t++)Tt[2*t+1]=5,Tt[2*t]=Qt(t,5);zt=new Pt(Ot,Et,257,vt,Ct),Wt=new Pt(Tt,kt,0,Ut,Ct),Nt=new Pt(new Array(0),Dt,0,19,7)})(),se=!0),t.l_desc=new $t(t.dyn_ltree,zt),t.d_desc=new $t(t.dyn_dtree,Wt),t.bl_desc=new $t(t.bl_tree,Nt),t.bi_buf=0,t.bi_valid=0,Zt(t)},_tr_stored_block:ae,_tr_flush_block:re,_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*(At[i]+It+1)]++,t.dyn_dtree[2*jt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{Ht(t,2,3),Jt(t,256,Ot),(t=>{16===t.bi_valid?(Gt(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 he=(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 oe=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 le=(t,e,i,s)=>{const a=oe,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},ce={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"},de={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:ue,_tr_stored_block:ge,_tr_flush_block:fe,_tr_tally:_e,_tr_align:pe}=ne,{Z_NO_FLUSH:be,Z_PARTIAL_FLUSH:we,Z_FULL_FLUSH:me,Z_FINISH:Se,Z_BLOCK:ye,Z_OK:Be,Z_STREAM_END:Re,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:ve,Z_BUF_ERROR:Ue,Z_DEFAULT_COMPRESSION:Ce,Z_FILTERED:Ee,Z_HUFFMAN_ONLY:ke,Z_RLE:De,Z_FIXED:xe,Z_DEFAULT_STRATEGY:Oe,Z_UNKNOWN:Te,Z_DEFLATED:Me}=de,Ae=258,Fe=262,Le=42,Pe=113,ze=666,We=(t,e)=>(t.msg=ce[e],e),Ne=t=>2*t-(t>4?9:0),$e=t=>{let e=t.length;for(;--e>=0;)t[e]=0},je=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 Ge=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const He=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))},Je=(t,e)=>{fe(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,He(t.strm)},Qe=(t,e)=>{t.pending_buf[t.pending++]=e},Ve=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},Ze=(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=he(t.adler,e,a,i):2===t.state.wrap&&(t.adler=le(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},Xe=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-Fe?t.strstart-(t.w_size-Fe):0,l=t.window,c=t.w_mask,d=t.prev,u=t.strstart+Ae;let g=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(a>>=2),h>t.lookahead&&(h=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=Ae-(u-r),r=u-Ae,s>n){if(t.match_start=e,n=s,s>=h)break;g=l[r+n-1],f=l[r+n]}}}while((e=d[e&c])>o&&0!==--a);return n<=t.lookahead?n:t.lookahead},Ke=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Fe)&&(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),je(t),s+=e),0===t.strm.avail_in)break;if(i=Ze(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=Ge(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=Ge(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<Fe&&0!==t.strm.avail_in)},qe=(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,h=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!==Se||e===be||i!==s+t.strm.avail_in))break;n=e===Se&&i===s+t.strm.avail_in?1:0,ge(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,He(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&&(Ze(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 h-=t.strm.avail_in,h&&(h>=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<=h&&(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-h,t.strm.next_in),t.strstart),t.strstart+=h,t.insert+=h>t.w_size-t.insert?t.w_size-t.insert:h),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==be&&e!==Se&&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&&(Ze(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===Se)&&e!==be&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===Se&&0===t.strm.avail_in&&i===s?1:0,ge(t,t.block_start,i,n),t.block_start+=i,He(t.strm)),n?3:1)},Ye=(t,e)=>{let i,s;for(;;){if(t.lookahead<Fe){if(Ke(t),t.lookahead<Fe&&e===be)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Ge(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-Fe&&(t.match_length=Xe(t,i)),t.match_length>=3)if(s=_e(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=Ge(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=Ge(t,t.ins_h,t.window[t.strstart+1]);else s=_e(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(Je(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===Se?(Je(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(Je(t,!1),0===t.strm.avail_out)?1:2},ti=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<Fe){if(Ke(t),t.lookahead<Fe&&e===be)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Ge(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-Fe&&(t.match_length=Xe(t,i),t.match_length<=5&&(t.strategy===Ee||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=_e(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=Ge(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&&(Je(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=_e(t,0,t.window[t.strstart-1]),s&&Je(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=_e(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===Se?(Je(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(Je(t,!1),0===t.strm.avail_out)?1:2};function ei(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 ii=[new ei(0,0,0,0,qe),new ei(4,4,8,4,Ye),new ei(4,5,16,8,Ye),new ei(4,6,32,32,Ye),new ei(4,4,16,16,ti),new ei(8,16,32,32,ti),new ei(8,16,128,128,ti),new ei(8,32,128,256,ti),new ei(32,128,258,1024,ti),new ei(32,258,258,4096,ti)];function si(){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=Me,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),$e(this.dyn_ltree),$e(this.dyn_dtree),$e(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),$e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),$e(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 ai=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Le&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==Pe&&e.status!==ze?1:0},ri=t=>{if(ai(t))return We(t,Ie);t.total_in=t.total_out=0,t.data_type=Te;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?Le:Pe,t.adler=2===e.wrap?0:1,e.last_flush=-2,ue(e),Be},ni=t=>{const e=ri(t);var i;return e===Be&&((i=t.state).window_size=2*i.w_size,$e(i.head),i.max_lazy_match=ii[i.level].max_lazy,i.good_match=ii[i.level].good_length,i.nice_match=ii[i.level].nice_length,i.max_chain_length=ii[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},hi=(t,e,i,s,a,r)=>{if(!t)return Ie;let n=1;if(e===Ce&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==Me||s<8||s>15||e<0||e>9||r<0||r>xe||8===s&&1!==n)return We(t,Ie);8===s&&(s=9);const h=new si;return t.state=h,h.strm=t,h.status=Le,h.wrap=n,h.gzhead=null,h.w_bits=s,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=a+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+3-1)/3),h.window=new Uint8Array(2*h.w_size),h.head=new Uint16Array(h.hash_size),h.prev=new Uint16Array(h.w_size),h.lit_bufsize=1<<a+6,h.pending_buf_size=4*h.lit_bufsize,h.pending_buf=new Uint8Array(h.pending_buf_size),h.sym_buf=h.lit_bufsize,h.sym_end=3*(h.lit_bufsize-1),h.level=e,h.strategy=r,h.method=i,ni(t)};var oi={deflateInit:(t,e)=>hi(t,e,Me,15,8,Oe),deflateInit2:hi,deflateReset:ni,deflateResetKeep:ri,deflateSetHeader:(t,e)=>ai(t)||2!==t.state.wrap?Ie:(t.state.gzhead=e,Be),deflate:(t,e)=>{if(ai(t)||e>ye||e<0)return t?We(t,Ie):Ie;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===ze&&e!==Se)return We(t,0===t.avail_out?Ue:Ie);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(He(t),0===t.avail_out)return i.last_flush=-1,Be}else if(0===t.avail_in&&Ne(e)<=Ne(s)&&e!==Se)return We(t,Ue);if(i.status===ze&&0!==t.avail_in)return We(t,Ue);if(i.status===Le&&0===i.wrap&&(i.status=Pe),i.status===Le){let e=Me+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=ke||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,Ve(i,e),0!==i.strstart&&(Ve(i,t.adler>>>16),Ve(i,65535&t.adler)),t.adler=1,i.status=Pe,He(t),0!==i.pending)return i.last_flush=-1,Be}if(57===i.status)if(t.adler=0,Qe(i,31),Qe(i,139),Qe(i,8),i.gzhead)Qe(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)),Qe(i,255&i.gzhead.time),Qe(i,i.gzhead.time>>8&255),Qe(i,i.gzhead.time>>16&255),Qe(i,i.gzhead.time>>24&255),Qe(i,9===i.level?2:i.strategy>=ke||i.level<2?4:0),Qe(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Qe(i,255&i.gzhead.extra.length),Qe(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=le(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Qe(i,0),Qe(i,0),Qe(i,0),Qe(i,0),Qe(i,0),Qe(i,9===i.level?2:i.strategy>=ke||i.level<2?4:0),Qe(i,3),i.status=Pe,He(t),0!==i.pending)return i.last_flush=-1,Be;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=le(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,He(t),0!==i.pending)return i.last_flush=-1,Be;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=le(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=le(t.adler,i.pending_buf,i.pending-s,s)),He(t),0!==i.pending)return i.last_flush=-1,Be;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,Qe(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=le(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=le(t.adler,i.pending_buf,i.pending-s,s)),He(t),0!==i.pending)return i.last_flush=-1,Be;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,Qe(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=le(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&&(He(t),0!==i.pending))return i.last_flush=-1,Be;Qe(i,255&t.adler),Qe(i,t.adler>>8&255),t.adler=0}if(i.status=Pe,He(t),0!==i.pending)return i.last_flush=-1,Be}if(0!==t.avail_in||0!==i.lookahead||e!==be&&i.status!==ze){let s=0===i.level?qe(i,e):i.strategy===ke?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(Ke(t),0===t.lookahead)){if(e===be)return 1;break}if(t.match_length=0,i=_e(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(Je(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Se?(Je(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(Je(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===De?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=Ae){if(Ke(t),t.lookahead<=Ae&&e===be)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+Ae;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=Ae-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=_e(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=_e(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(Je(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Se?(Je(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(Je(t,!1),0===t.strm.avail_out)?1:2})(i,e):ii[i.level].func(i,e);if(3!==s&&4!==s||(i.status=ze),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),Be;if(2===s&&(e===we?pe(i):e!==ye&&(ge(i,0,0,!1),e===me&&($e(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),He(t),0===t.avail_out))return i.last_flush=-1,Be}return e!==Se?Be:i.wrap<=0?Re:(2===i.wrap?(Qe(i,255&t.adler),Qe(i,t.adler>>8&255),Qe(i,t.adler>>16&255),Qe(i,t.adler>>24&255),Qe(i,255&t.total_in),Qe(i,t.total_in>>8&255),Qe(i,t.total_in>>16&255),Qe(i,t.total_in>>24&255)):(Ve(i,t.adler>>>16),Ve(i,65535&t.adler)),He(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Be:Re)},deflateEnd:t=>{if(ai(t))return Ie;const e=t.state.status;return t.state=null,e===Pe?We(t,ve):Be},deflateSetDictionary:(t,e)=>{let i=e.length;if(ai(t))return Ie;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==Le||s.lookahead)return Ie;if(1===a&&(t.adler=he(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&($e(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,h=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,Ke(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=Ge(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,Ke(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=h,t.avail_in=r,s.wrap=a,Be},deflateInfo:"pako deflate (from Nodeca project)"};const li=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ci=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)li(i,e)&&(t[e]=i[e])}}return t},di=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 ui=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){ui=!1}const gi=new Uint8Array(256);for(let t=0;t<256;t++)gi[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;gi[254]=gi[254]=1;var fi=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,h=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++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,a=0;r<h;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 _i=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 pi=Object.prototype.toString,{Z_NO_FLUSH:bi,Z_SYNC_FLUSH:wi,Z_FULL_FLUSH:mi,Z_FINISH:Si,Z_OK:yi,Z_STREAM_END:Bi,Z_DEFAULT_COMPRESSION:Ri,Z_DEFAULT_STRATEGY:Ii,Z_DEFLATED:vi}=de;function Ui(t){this.options=ci({level:Ri,method:vi,chunkSize:16384,windowBits:15,memLevel:8,strategy:Ii},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 _i,this.strm.avail_out=0;let i=oi.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==yi)throw new Error(ce[i]);if(e.header&&oi.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?fi(e.dictionary):"[object ArrayBuffer]"===pi.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=oi.deflateSetDictionary(this.strm,t),i!==yi)throw new Error(ce[i]);this._dict_set=!0}}Ui.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?Si:bi,"string"==typeof t?i.input=fi(t):"[object ArrayBuffer]"===pi.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===wi||r===mi)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=oi.deflate(i,r),a===Bi)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=oi.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===yi;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},Ui.prototype.onData=function(t){this.chunks.push(t)},Ui.prototype.onEnd=function(t){t===yi&&(this.result=di(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Ci={deflate:function(t,e){const i=new Ui(e);if(i.push(t,!0),i.err)throw i.msg||ce[i.err];return i.result}};const{deflate:Ei}=Ci;var ki=Ei;const Di={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}},xi=(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 Di))throw"Unhandled character '"+t+"' in pack format";const i=Di[t].bytes,r=new DataView(new ArrayBuffer(i));Di[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},Oi=(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 Di))throw"Unhandled character '"+t+"' in unpack format";const r=Di[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=Di[t].u.bind(n);s.push(h(0,a)),i+=r}return s};class Ti 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===F&&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=wt(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);const i=null!==this.chipRevision&&void 0!==this.chipRevision?` (revision ${this.chipRevision})`:"";this.logger.log(`Connected to ${this.chipName}${i}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=P[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===F&&this.chipRevision>=300?this.chipVariant="rev300":this.chipFamily===F&&(this.chipVariant="rev0"),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 r(gt);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=z[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.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===F&&(this.chipVariant=this.chipRevision>=300?"rev300":"rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){var t;let e=0,i=0;switch(this.chipFamily){case v:{const s=await this.readRegister(1073061900),a=await this.readRegister(1073061908);e=a>>24&3;const r=s>>15&1,n=a>>20&1;i=null!==(t={0:0,1:1,3:2,7:3}[(await this.readRegister(1073111164)>>31&1)<<2|n<<1|r])&&void 0!==t?t:0;break}case U:{const t=await this.readRegister(1061265488);e=((t>>20&1)<<3)+(await this.readRegister(1061265492)>>4&7),i=t>>18&3;break}case C:{const t=await this.readRegister(1610641488),s=await this.readRegister(1610641496);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case E:{const t=await this.readRegister(1610647620);e=t>>16&15,i=t>>20&3;break}case k:{const t=await this.readRegister(1610647632),s=await this.readRegister(1610647640);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case D:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case x:{const t=await this.readRegister(1611335760);e=t>>18&15,i=t>>22&3;break}case O:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case T:{const t=await this.readRegister(1611335760);e=t>>18&7,i=t>>21&3;break}case M:case A:break;case F:{const t=await this.readRegister(1343410252);e=15&t,i=(t>>23&1)<<2|t>>4&3;break}case L:{const t=await this.readRegister(544297036);e=15&t,i=t>>4&3;break}}return 100*i+e}async powerOnFlash(){if(this.chipFamily!==F)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await r(10);const t=await this.readRegister(w);await this.writeRegister(w,t|m);const e=await this.readRegister(S);await this.writeRegister(S,128|e);const i=await this.readRegister(y);await this.writeRegister(y,3|i),await r(.05);const s=await this.readRegister(w);await this.writeRegister(w,-134217729&s);const a=await this.readRegister(S);await this.writeRegister(S,-2139095041&a);const n=await this.readRegister(S);await this.writeRegister(S,128|n);const h=await this.readRegister(S);await this.writeRegister(S,-129&h),await r(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:Oi("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?Oi("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?Oi("<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 hardResetUSBJTAGSerial(){await this.setRTS(!1),await this.setDTR(!1),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(100),await this.setRTS(!0),await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!1),await this.setRTS(!1),await this.sleep(200)}async hardResetClassic(){await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(50),await this.setDTR(!1),await this.sleep(200)}async hardResetToFirmware(){await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),await this.sleep(50),await this.sleep(200)}async hardResetToFirmwareWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setRTSWebUSB(!1),await this.sleep(50),await this.sleep(200)}async hardResetUnixTight(){await this.setDTRandRTS(!0,!0),await this.setDTRandRTS(!1,!1),await this.setDTRandRTS(!1,!0),await this.sleep(100),await this.setDTRandRTS(!0,!1),await this.sleep(50),await this.setDTRandRTS(!1,!1),await this.setDTR(!1),await this.sleep(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 hardResetUSBJTAGSerialWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetClassicWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetUnixTightWebUSB(){await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRandRTSWebUSB(!0,!0),await this.setDTRandRTSWebUSB(!1,!0),await this.sleep(100),await this.setDTRandRTSWebUSB(!0,!1),await this.sleep(50),await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetClassicLongDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(500),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200),await this.setDTRWebUSB(!1),await this.sleep(500)}async hardResetClassicShortDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(25),await this.setDTRWebUSB(!1),await this.sleep(100)}async hardResetInvertedWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedDTRWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedRTSWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,s=[],a=this,n=!e&&!i;if(this.isWebUSB()){const r=4292===t.usbVendorId,h=6790===t.usbVendorId,o=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(o?(s.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async()=>await a.hardResetUSBJTAGSerialWebUSB()}),s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async()=>await a.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async()=>await a.hardResetUnixTightWebUSB()}),s.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async()=>await a.hardResetClassicWebUSB()})):(s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async()=>await a.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"USB-JTAG/Serial (WebUSB)",fn:async()=>await a.hardResetUSBJTAGSerialWebUSB()}),s.push({name:"Inverted DTR Classic (WebUSB)",fn:async()=>await a.hardResetInvertedDTRWebUSB()}))),n&&(h?(s.push({name:"UnixTight (WebUSB) - CH34x",fn:async()=>await a.hardResetUnixTightWebUSB()}),s.push({name:"Classic (WebUSB) - CH34x",fn:async()=>await a.hardResetClassicWebUSB()}),s.push({name:"Inverted Both (WebUSB) - CH34x",fn:async()=>await a.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async()=>await a.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async()=>await a.hardResetInvertedDTRWebUSB()})):r?(s.push({name:"UnixTight (WebUSB) - CP2102",fn:async()=>await a.hardResetUnixTightWebUSB()}),s.push({name:"Classic (WebUSB) - CP2102",fn:async()=>await a.hardResetClassicWebUSB()}),s.push({name:"Inverted Both (WebUSB) - CP2102",fn:async()=>await a.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async()=>await a.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async()=>await a.hardResetInvertedDTRWebUSB()})):(s.push({name:"UnixTight (WebUSB)",fn:async()=>await a.hardResetUnixTightWebUSB()}),s.push({name:"Classic (WebUSB)",fn:async function(){return await a.hardResetClassicWebUSB()}}),s.push({name:"Inverted Both (WebUSB)",fn:async function(){return await a.hardResetInvertedWebUSB()}}),s.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await a.hardResetInvertedRTSWebUSB()}}),s.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await a.hardResetInvertedDTRWebUSB()}}))),r||o||(6790!==t.usbVendorId&&s.push({name:"Classic (WebUSB)",fn:async function(){return await a.hardResetClassicWebUSB()}}),s.push({name:"UnixTight (WebUSB)",fn:async function(){return await a.hardResetUnixTightWebUSB()}}),s.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await a.hardResetClassicLongDelayWebUSB()}}),s.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await a.hardResetClassicShortDelayWebUSB()}}),e||i||s.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await a.hardResetUSBJTAGSerialWebUSB()}}))}else(e||i)&&s.push({name:"USB-JTAG/Serial",fn:async function(){return await a.hardResetUSBJTAGSerial()}}),s.push({name:"UnixTight",fn:async function(){return await a.hardResetUnixTight()}}),e||i||s.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await a.hardResetUSBJTAGSerial()}});let h=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.debug(`Connected CDC/JTAG successfully with ${t.name} reset.`)}catch(t){throw new Error("Sync timeout or abandoned")}}}catch(t){if(h=t,this._abandonCurrentOperation=!0,await r(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==h?void 0:h.message}`)}async watchdogReset(){await this.rtcWdtResetChipSpecific()}async rtcWdtResetChipSpecific(){let t,e,i,s;if(this.logger.debug("Hard resetting with watchdog timer..."),this.chipFamily===U)t=1061191852,e=1061191828,i=1061191832,s=1356348065;else if(this.chipFamily===C)t=1610645680,e=1610645656,i=1610645660,s=1356348065;else if(this.chipFamily===k)t=1610645672,e=1610645648,i=1610645652,s=1356348065;else if(this.chipFamily===D||this.chipFamily===x)t=1611340824,e=1611340800,i=1611340804,s=1356348065;else{if(this.chipFamily!==F)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):(this.isWebUSB()?(await this.hardResetClassicWebUSB(),this.logger.debug("Classic reset (WebUSB/Android).")):(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)..."),this.isWebUSB()?await this.hardResetToFirmwareWebUSB():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.")):this.isWebUSB()?(await this.hardResetClassicWebUSB(),this.logger.debug("Classic reset (WebUSB/Android).")):(await this.hardResetClassic(),this.logger.debug("Classic reset."));else{if(this.logger.debug("*** Performing WDT reset strategy ***"),this.chipFamily===U){if(await this.tryUsbWdtReset("ESP32-S2"))return}else if(this.chipFamily===F){if(await this.tryUsbWdtReset("ESP32-P4"))return}else if(this.chipFamily===D){if(await this.tryUsbWdtReset("ESP32-C5"))return}else if(this.chipFamily===x){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==I){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==v)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!=U&&this.chipFamily!=C&&this.chipFamily!=E&&this.chipFamily!=k&&this.chipFamily!=D&&this.chipFamily!=x&&this.chipFamily!=O&&this.chipFamily!=T&&this.chipFamily!=M&&this.chipFamily!=A&&this.chipFamily!=F&&this.chipFamily!=L)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=xi("<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,ut),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 h=n,o=0;if(this.IS_STUB||this.chipFamily==I?o=2:[v,U,C,E,k,D,x,O,T,M,A,F,L].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)?o=h.length:(o=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${s(t)}, data.length: ${h.length})`)),h.length<o)throw new Error("Didn't get enough status bytes");const l=h.slice(-o,h.length);if(h=h.slice(0,-o),this.debug&&(this.logger.debug("status",l),this.logger.debug("value",r),this.logger.debug("data",h)),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,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...xi("<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,a=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new mt("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new mt("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){if(Date.now()-n>t){throw new mt("Timed out waiting for packet "+(null===e?"header":"content"))}const r=this._readByte();if(null===e){if(r!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(r)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new mt("Invalid head of packet ("+s(r)+")");e=[]}else if(a)if(a=!1,r==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(r!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(r)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new mt("Invalid SLIP escape (0xdb, "+s(r)+")");e.push(this.SLIP_ESC)}else if(r==this.SLIP_ESC)a=!0;else{if(r==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(r)}}else await r(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new mt("Operation abandoned (reset strategy timeout)");const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await r(1)}if(0==n.length){throw new mt("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 mt("Invalid head of packet ("+s(t)+")");e=[]}else if(a)if(a=!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 mt("Invalid SLIP escape (0xdb, "+s(t)+")");e.push(this.SLIP_ESC)}else if(t==this.SLIP_ESC)a=!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]=Oi("<BBHI",i.slice(0,8));if(1!=a)continue;const h=i.slice(8);if(null==t||r==t)return[n,h];if(0!=h[0]&&5==h[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 setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==D)try{const e=xi("<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 r(gt),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.debug(`Changed baud rate to ${t}`)}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=xi("<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 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 r(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 r(gt),!0}catch(t){if(this._abandonCurrentOperation)return!1}await r(gt)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await r(gt),!0;await r(gt)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,R);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,gt);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,h=0,o=ct;a?(n=ki(new Uint8Array(t),{level:9}).buffer,h=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${h}`),o=await this.flashDeflBegin(r,h,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],c=0,d=0,u=0;const g=Date.now(),f=this.getFlashWriteSize(),_=a?h:r;for(;_-u>0;)this.debug&&this.logger.log(`Writing at ${s(i+c*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,c,o):await this.flashBlock(l,c),c+=1,d+=a?Math.round(l.length*r/h):l.length,u+=f,e(Math.min(d,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,xi("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,xi("<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&&[v,U,C,E,k,D,x,O,T,M,A,F,L].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=I||this.IS_STUB?t:this.getEraseSize(e,t);const h=this.IS_STUB?ct:bt(ft,t),o=Date.now();let l=xi("<IIII",a,n,r,e);return this.chipFamily!=v&&this.chipFamily!=U&&this.chipFamily!=C&&this.chipFamily!=E&&this.chipFamily!=k&&this.chipFamily!=D&&this.chipFamily!=x&&this.chipFamily!=O&&this.chipFamily!=T&&this.chipFamily!=M&&this.chipFamily!=A&&this.chipFamily!=F&&this.chipFamily!=L||(l=l.concat(xi("<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,h),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-o)+"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,h=0;this.IS_STUB?(n=t,h=bt(ft,n)):(n=r*s,h=ct);const o=xi("<IIII",n,a,s,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=xi("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=xi("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return wt(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=xi("<IIII",t,e,i,s);a>0&&(r=r.concat(xi("<IIII",wt(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=wt(this.getChipFamily()),r=a.regBase,n=r,h=r+a.usrOffs,o=r+a.usr2Offs,l=r+a.w0Offs,c=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 d=8*e.length,u=await this.readRegister(h),g=await this.readRegister(o);let f=1<<31;if(i>0&&(f|=268435456),d>0&&(f|=134217728),await this.setDataLengths(a,d,i),await this.writeRegister(h,f),await this.writeRegister(o,7<<28|t),0==d)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=Oi("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,c),await this.waitDone(n,c);const _=await this.readRegister(l);return await this.writeRegister(h,u),await this.writeRegister(o,g),_}async detectFlashSize(){this.logger.debug("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255,s=(t>>8&255)<<8|i,a=yt[e],r=Bt[e<<16|s];this.logger.log(`Flash Manufacturer: ${a||"Unknown"} (0x${e.toString(16)})`),this.logger.log(`Flash Device: ${r||`Unknown (0x${s.toString(16)})`}`),this.flashSize=n[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=h,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,xi("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,xi("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?ct:500,i=xi("<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 St(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.debug("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.debug("Stub is now running...");const r=new Mi(this.port,this.logger,this);return t||await r.detectFlashSize(),r}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 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===U)t=1061191976,e=1,i="ESP32-S2";else if(this.chipFamily===C)t=1610645804,e=1,i="ESP32-S3";else{if(this.chipFamily!==F)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 r(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===U&&t||this.chipFamily===F&&t?(await this.releaseReaderWriter(),this.logger.debug(`${this.chipName} USB-OTG: Port will change after WDT reset`),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===F&&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 r(100),await this.connectWithResetStrategies(),await this.detectChip(),this.logger.debug(`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===U||this.chipFamily===F;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.debug(`${this.chipName} USB: Resetting to bootloader mode`);try{this.isWebUSB()?await this.hardResetClassicWebUSB():await this.hardResetClassic(),this.logger.debug("Reset to bootloader initiated")}catch(t){this.logger.debug(`Reset error: ${t}`)}return await r(500),this.logger.debug(`${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===U&&(!0===this._isUsbJtagOrOtg||void 0===this._isUsbJtagOrOtg))}async resetInConsoleMode(){if(this._parent)return await this._parent.resetInConsoleMode();if(!this.isConsoleResetSupported())return void this.logger.debug("Console reset not supported for ESP32-S2 USB-JTAG/CDC");const t=!0===this.port.isWebUSB;try{this.logger.debug("Resetting device in console mode"),t?await this.hardResetToFirmwareWebUSB():await this.hardResetToFirmware(),this.logger.debug("Device reset complete")}catch(t){throw this.logger.error(`Reset failed: ${t}`),t}}async drainInputBuffer(t=200){await r(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 r(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 r(gt),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s,a){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==a?void 0:a.chunkSize)?(n=a.chunkSize,this.logger.log(`Using custom chunk size: 0x${n.toString(16)} bytes`)):n=this.isWebUSB()?16384:262144;let h=new Uint8Array(0),o=e,l=i;for(;l>0;){const e=Math.min(n,l);let c=!1,d=0;const u=5;let g=!1;for(;!c&&d<=u;){let i=new Uint8Array(0),s=0;try{let n,l;if(0===d&&this.logger.debug(`Reading chunk at 0x${o.toString(16)}, size: 0x${e.toString(16)}`),void 0!==(null==a?void 0:a.blockSize)&&void 0!==(null==a?void 0:a.maxInFlight))n=a.blockSize,l=a.maxInFlight,0===d&&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=xi("<IIII",o,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 a;try{a=await this.readPacket(100)}catch(t){if(t instanceof mt){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 r(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(a&&a.length>0){const r=new Uint8Array(a),n=new Uint8Array(i.length+r.length);n.set(i),n.set(r,i.length),i=n;if(i.length>=e||i.length>=s+l){const e=xi("<I",i.length),a=t(e);await this.writeToStream(a),s=i.length}}}const f=new Uint8Array(h.length+i.length);if(f.set(h),f.set(i,h.length),h=f,c=!0,this.isWebUSB()&&this._isCDCDevice&&0===d&&(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(d++,this.isWebUSB()&&this._isCDCDevice&&1===d)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 mt))throw t;if(d<=u){this.logger.debug(`${t.message} at 0x${o.toString(16)}. Draining buffer and retrying (attempt ${d}/${u})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await r(gt)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(g)throw new Error(`Failed to read chunk at 0x${o.toString(16)} after ${u} retries and recovery attempt`);g=!0,this.logger.log(`All retries exhausted at 0x${o.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),d=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${o.toString(16)} after ${u} retries and recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),h.length,i),o+=e,l-=e,this.logger.debug(`Total progress: 0x${h.length.toString(16)} from 0x${i.toString(16)} bytes`)}return h}}class Mi extends Ti{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await St(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,h=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(h,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&&h>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(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,dt)}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%h!==0)throw new Error(`Offset ${t} (0x${t.toString(16)}) is not aligned to flash sector size 4096 (0x${h.toString(16)})`);if(e%h!==0)throw new Error(`Size ${e} (0x${e.toString(16)}) is not aligned to flash sector size 4096 (0x${h.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=bt(ft,e),a=xi("<II",t,e);await this.checkCommand(209,a,0,s)}}const Ai=4096,Fi=[4096,2048,1024,512],Li=4096,Pi=[4096,2048,1024,512],zi=8192,Wi=[8192,4096],Ni=256,$i=256,ji=8192;function Gi(t){if(t.length<4096)return!1;let e=0;const i=256,s=Math.min(32,Math.floor(t.length/i));for(let a=0;a<s;a++){const s=a*i;if(s+i>t.length)break;const r=t.slice(s,s+i),n=r[0]|r[1]<<8;for(let t=0;t<r.length-10;t++)if(1===r[t]&&47===r[t+1]){let i=0;for(let e=t+1;e<Math.min(t+20,r.length);e++)if(r[e]>=32&&r[e]<127)i++;else if(0===r[e])break;if(i>=4){e+=5;break}}if(32768&n){const t=32767&n;t>0&&t<4096&&(e+=2)}}return e>=10}function Hi(t,e,i){const s=Wi;for(const a of s)for(let s=0;s<2;s++){const r=s*a,n=r+8;if(n+8>t.length)continue;if("littlefs"===String.fromCharCode(t[n],t[n+1],t[n+2],t[n+3],t[n+4],t[n+5],t[n+6],t[n+7])){const s=r+16,n=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;if(0!==n&&n>>>0!=4294967295){const s=r+24;if(s+4<=t.length){const r=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;if(r>0&&r<1e5){const t=r*a;if(t>0&&e+t<=i)return{start:e,end:e+t,size:t,page:256,block:a}}}return Ji(e,i,a)}}}if(Gi(t))return Ji(e,i,ji);if(t.length>=4){if(538182953===(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)){let s=!0;if(t.length>=16){let e=!0;for(let i=4;i<16;i++)if(255!==t[i]){e=!1;break}e&&(s=!1)}if(s)return Ji(e,i,ji)}}const a=[0,4096];for(const s of a){if(t.length<s+512)continue;if(43605===(t[s+510]|t[s+511]<<8)){const a=t[s+11]|t[s+12]<<8;if(![512,1024,2048,4096].includes(a))continue;let r=t[s+19]|t[s+20]<<8;if(0===r&&(r=t[s+32]|t[s+33]<<8|t[s+34]<<16|t[s+35]<<24),a>0&&r>0&&r<1e8){const t=r*a,n=e+s;if(t>0&&n+t<=i)return{start:n,end:n+t,size:t,page:a,block:a}}}}return null}function Ji(t,e,i){const s=e/1048576;if(s>=16){if(1048576===t)return{start:1048576,end:16752640,size:15704064,page:256,block:i};if(2097152===t)return{start:2097152,end:16752640,size:14655488,page:256,block:i}}if(s>=8){if(1048576===t)return{start:1048576,end:8364032,size:7315456,page:256,block:i};if(2097152===t)return{start:2097152,end:8364032,size:6266880,page:256,block:i}}if(s>=4){if(1048576===t)return{start:1048576,end:4169728,size:3121152,page:256,block:i};if(2097152===t)return{start:2097152,end:4169728,size:2072576,page:256,block:i};if(3145728===t)return{start:3145728,end:4169728,size:1024e3,page:256,block:i}}if(s>=2){if(1048576===t)return{start:1048576,end:2072576,size:1024e3,page:256,block:i};if(1572864===t)return{start:1572864,end:2072576,size:499712,page:256,block:i};if(1835008===t)return{start:1835008,end:2076672,size:241664,page:256,block:i};if(1966080===t)return{start:1966080,end:2076672,size:110592,page:256,block:i};if(2031616===t)return{start:2031616,end:2076672,size:45056,page:256,block:i}}if(s>=1){if(503808===t)return{start:503808,end:1028096,size:524288,page:256,block:i};if(765952===t)return{start:765952,end:1028096,size:262144,page:256,block:i};if(831488===t)return{start:831488,end:1028096,size:196608,page:256,block:i};if(864256===t)return{start:864256,end:1028096,size:163840,page:256,block:i};if(880640===t)return{start:880640,end:1028096,size:147456,page:256,block:i};if(897024===t)return{start:897024,end:1028096,size:131072,page:256,block:i};if(962560===t)return{start:962560,end:1028096,size:65536,page:256,block:i}}if(s>=.5){if(372736===t)return{start:372736,end:503808,size:131072,page:256,block:i};if(438272===t)return{start:438272,end:503808,size:65536,page:256,block:i};if(471040===t)return{start:471040,end:503808,size:32768,page:256,block:i}}return{start:t,end:e,size:e-t,page:256,block:i}}function Qi(t){return t>=16?[{start:1048576,end:16752640,size:15704064,page:256,block:8192},{start:2097152,end:16752640,size:14655488,page:256,block:8192}]:t>=8?[{start:1048576,end:8364032,size:7315456,page:256,block:8192},{start:2097152,end:8364032,size:6266880,page:256,block:8192}]:t>=4?[{start:2097152,end:4169728,size:2072576,page:256,block:8192},{start:1048576,end:4169728,size:3121152,page:256,block:8192},{start:3145728,end:4169728,size:1024e3,page:256,block:8192}]:t>=2?[{start:1048576,end:2072576,size:1024e3,page:256,block:8192},{start:1572864,end:2072576,size:499712,page:256,block:8192},{start:1835008,end:2076672,size:241664,page:256,block:8192},{start:1966080,end:2076672,size:110592,page:256,block:8192},{start:2031616,end:2076672,size:45056,page:256,block:8192}]:t>=1?[{start:897024,end:1028096,size:131072,page:256,block:8192},{start:503808,end:1028096,size:524288,page:256,block:8192},{start:765952,end:1028096,size:262144,page:256,block:8192},{start:831488,end:1028096,size:196608,page:256,block:8192},{start:864256,end:1028096,size:163840,page:256,block:8192},{start:880640,end:1028096,size:147456,page:256,block:8192},{start:962560,end:1028096,size:65536,page:256,block:8192}]:t>=.5?[{start:372736,end:503808,size:131072,page:256,block:8192},{start:438272,end:503808,size:65536,page:256,block:8192},{start:471040,end:503808,size:32768,page:256,block:8192}]:[]}var Vi;function Zi(t){return 1!==t.type?Vi.UNKNOWN:129===t.subtype?Vi.FATFS:Vi.UNKNOWN}function Xi(t,e){if(t.length<512)return Vi.UNKNOWN;const i=(null==e?void 0:e.toUpperCase().includes("ESP8266"))?Wi:Fi;for(const e of i)for(let i=0;i<2;i++){const s=i*e;if(s+20>t.length)continue;const a=s+8;if(a+8<=t.length){if("littlefs"===String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3],t[a+4],t[a+5],t[a+6],t[a+7])){const e=s+16,i=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24;if(0!==i&&i>>>0!=4294967295)return Vi.LITTLEFS}}}const s=[0,4096];for(const e of s){if(t.length<e+512)continue;if(43605===(t[e+510]|t[e+511]<<8)){const i=t.length>=e+62?String.fromCharCode(t[e+54],t[e+55],t[e+56],t[e+57],t[e+58]):"",s=t.length>=e+90?String.fromCharCode(t[e+82],t[e+83],t[e+84],t[e+85],t[e+86]):"";if(i.startsWith("FAT")||s.startsWith("FAT"))return Vi.FATFS}}if(t.length>=4){if(538182953===(t[0]|t[1]<<8|t[2]<<16|t[3]<<24))return Vi.SPIFFS}return Gi(t)?Vi.SPIFFS:Vi.UNKNOWN}function Ki(t,e){const i=null==e?void 0:e.toUpperCase().includes("ESP8266");switch(t){case Vi.FATFS:return 4096;case Vi.LITTLEFS:default:return i?zi:4096}}function qi(t,e){const i=null==e?void 0:e.toUpperCase().includes("ESP8266");switch(t){case Vi.FATFS:return Pi;case Vi.LITTLEFS:return i?Wi:Fi;default:return i?Wi:[4096,2048,1024,512]}}!function(t){t.UNKNOWN="unknown",t.LITTLEFS="littlefs",t.FATFS="fatfs",t.SPIFFS="spiffs"}(Vi||(Vi={}));const Yi={0:"app",1:"data"},ts={0:"factory",16:"ota_0",17:"ota_1",18:"ota_2",19:"ota_3",20:"ota_4",21:"ota_5",22:"ota_6",23:"ota_7",24:"ota_8",25:"ota_9",26:"ota_10",27:"ota_11",28:"ota_12",29:"ota_13",30:"ota_14",31:"ota_15",32:"test"},es={0:"ota",1:"phy",2:"nvs",3:"coredump",4:"nvs_keys",5:"efuse",128:"esphttpd",129:"fat",130:"spiffs",131:"littlefs"};function is(t){if(t.length<32)return null;if(20650!==(65535&(t[0]|t[1]<<8)))return null;const e=t[2],i=t[3],s=t[4]|t[5]<<8|t[6]<<16|t[7]<<24,a=t[8]|t[9]<<8|t[10]<<16|t[11]<<24;let r="";for(let e=12;e<28&&0!==t[e];e++)r+=String.fromCharCode(t[e]);const n=t[28]|t[29]<<8|t[30]<<16|t[31]<<24,h=Yi[e]||`unknown(0x${e.toString(16)})`;let o="";return o=0===e?ts[i]||`unknown(0x${i.toString(16)})`:1===e?es[i]||`unknown(0x${i.toString(16)})`:`0x${i.toString(16)}`,{name:r,type:e,subtype:i,offset:s,size:a,flags:n,typeName:h,subtypeName:o}}function ss(t){const e=[];for(let i=0;i<t.length;i+=32){const s=is(t.slice(i,i+32));if(null===s)break;e.push(s)}return e}function as(){return 32768}function rs(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}class ns{constructor(t){var e,i,s,a,r,n,h,o,l,c,d,u;if(t.blockSize%t.pageSize!==0)throw new Error("block size should be a multiple of page size");this.pageSize=t.pageSize,this.blockSize=t.blockSize,this.objIdLen=null!==(e=t.objIdLen)&&void 0!==e?e:2,this.spanIxLen=null!==(i=t.spanIxLen)&&void 0!==i?i:2,this.packed=null===(s=t.packed)||void 0===s||s,this.aligned=null===(a=t.aligned)||void 0===a||a,this.objNameLen=null!==(r=t.objNameLen)&&void 0!==r?r:32,this.metaLen=null!==(n=t.metaLen)&&void 0!==n?n:4,this.pageIxLen=null!==(h=t.pageIxLen)&&void 0!==h?h:2,this.blockIxLen=null!==(o=t.blockIxLen)&&void 0!==o?o:2,this.endianness=null!==(l=t.endianness)&&void 0!==l?l:"little",this.useMagic=null===(c=t.useMagic)||void 0===c||c,this.useMagicLen=null===(d=t.useMagicLen)||void 0===d||d,this.alignedObjIxTables=null!==(u=t.alignedObjIxTables)&&void 0!==u&&u,this.PAGES_PER_BLOCK=Math.floor(this.blockSize/this.pageSize),this.OBJ_LU_PAGES_PER_BLOCK=Math.ceil(this.blockSize/this.pageSize*this.objIdLen/this.pageSize),this.OBJ_USABLE_PAGES_PER_BLOCK=this.PAGES_PER_BLOCK-this.OBJ_LU_PAGES_PER_BLOCK,this.OBJ_LU_PAGES_OBJ_IDS_LIM=Math.floor(this.pageSize/this.objIdLen),this.OBJ_DATA_PAGE_HEADER_LEN=this.objIdLen+this.spanIxLen+1;const g=4-(this.OBJ_DATA_PAGE_HEADER_LEN%4==0?4:this.OBJ_DATA_PAGE_HEADER_LEN%4);this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED=this.OBJ_DATA_PAGE_HEADER_LEN+g,this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD=g,this.OBJ_DATA_PAGE_CONTENT_LEN=this.pageSize-this.OBJ_DATA_PAGE_HEADER_LEN,this.OBJ_INDEX_PAGES_HEADER_LEN=this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED+4+1+this.objNameLen+this.metaLen,this.alignedObjIxTables?(this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED=this.OBJ_INDEX_PAGES_HEADER_LEN+2-1&-2,this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD=this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED-this.OBJ_INDEX_PAGES_HEADER_LEN):(this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED=this.OBJ_INDEX_PAGES_HEADER_LEN,this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD=0),this.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM=Math.floor((this.pageSize-this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED)/this.blockIxLen),this.OBJ_INDEX_PAGES_OBJ_IDS_LIM=Math.floor((this.pageSize-this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED)/this.blockIxLen)}}class hs extends Error{constructor(t="SPIFFS is full"){super(t),this.name="SpiffsFullError"}}class os{constructor(t,e){this.buildConfig=e,this.bix=t}pack(t,...e){const i=new ArrayBuffer(this.calcSize(t)),s=new DataView(i);let a=0;for(let i=0;i<t.length;i++){const r=t[i],n=e[i];switch(r){case"B":s.setUint8(a,n),a+=1;break;case"H":"little"===this.buildConfig.endianness?s.setUint16(a,n,!0):s.setUint16(a,n,!1),a+=2;break;case"I":"little"===this.buildConfig.endianness?s.setUint32(a,n,!0):s.setUint32(a,n,!1),a+=4}}return new Uint8Array(i)}unpack(t,e,i=0){const s=new DataView(e.buffer,e.byteOffset+i),a=[];let r=0;for(const e of t)switch(e){case"B":a.push(s.getUint8(r)),r+=1;break;case"H":a.push("little"===this.buildConfig.endianness?s.getUint16(r,!0):s.getUint16(r,!1)),r+=2;break;case"I":a.push("little"===this.buildConfig.endianness?s.getUint32(r,!0):s.getUint32(r,!1)),r+=4}return a}calcSize(t){let e=0;for(const i of t)switch(i){case"B":e+=1;break;case"H":e+=2;break;case"I":e+=4}return e}}class ls extends os{constructor(t,e){super(0,e),this.objId=t}getObjId(){return this.objId}}class cs extends os{constructor(t,e){super(t,e),this.objIdsLimit=this.buildConfig.OBJ_LU_PAGES_OBJ_IDS_LIM,this.objIds=[]}calcMagic(t){let e=538182953^this.buildConfig.pageSize;this.buildConfig.useMagicLen&&(e^=t-this.bix);return e&(1<<8*this.buildConfig.objIdLen)-1}registerPage(t){if(this.objIdsLimit<=0)throw new hs;const e=t instanceof ds?"index":"data";this.objIds.push([t.getObjId(),e]),this.objIdsLimit--}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);let e=0;for(const[i,s]of this.objIds){let a=i;"index"===s&&(a^=1<<8*this.buildConfig.objIdLen-1);const r=this.pack(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I",a);t.set(r,e),e+=r.length}return t}magicfy(t){const e=this.objIdsLimit,i=(1<<8*this.buildConfig.objIdLen)-1;if(e>=2)for(let s=0;s<e;s++){if(s===e-2){this.objIds.push([this.calcMagic(t),"data"]);break}this.objIds.push([i,"data"]),this.objIdsLimit--}}}class ds extends ls{constructor(t,e,i,s,a){super(t,a),this.spanIx=e,this.name=s,this.size=i,0===this.spanIx?this.pagesLim=this.buildConfig.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM:this.pagesLim=this.buildConfig.OBJ_INDEX_PAGES_OBJ_IDS_LIM,this.pages=[]}registerPage(t){if(this.pagesLim<=0)throw new hs;this.pages.push(t.offset),this.pagesLim--}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);const e=this.objId^1<<8*this.buildConfig.objIdLen-1,i=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B";let s=0;const a=this.pack(i,e,this.spanIx,248);if(t.set(a,s),s+=a.length,s+=this.buildConfig.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD,0===this.spanIx){const e=this.pack("IB",this.size,1);t.set(e,s),s+=e.length;const i=(new TextEncoder).encode(this.name),a=Math.min(i.length,this.buildConfig.objNameLen);t.set(i.slice(0,a),s);for(let e=a;e<this.buildConfig.objNameLen;e++)t[s+e]=0;s+=this.buildConfig.objNameLen+this.buildConfig.metaLen+this.buildConfig.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD}for(const e of this.pages){const i=Math.floor(e/this.buildConfig.pageSize),a=this.pack(1===this.buildConfig.pageIxLen?"B":2===this.buildConfig.pageIxLen?"H":"I",i);t.set(a,s),s+=a.length}return t}}class us extends ls{constructor(t,e,i,s,a){super(e,a),this.offset=t,this.spanIx=i,this.contents=s}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);const e=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B",i=this.pack(e,this.objId,this.spanIx,252);return t.set(i,0),t.set(this.contents,i.length),t}}class gs{constructor(t,e){this.buildConfig=e,this.offset=t*this.buildConfig.blockSize,this.remainingPages=this.buildConfig.OBJ_USABLE_PAGES_PER_BLOCK,this.pages=[],this.bix=t,this.luPages=[];for(let t=0;t<this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;t++){const t=new cs(this.bix,this.buildConfig);this.luPages.push(t)}this.pages.push(...this.luPages),this.luPageIter=this.luPages[Symbol.iterator](),this.luPage=this.luPageIter.next().value||null,this.curObjIndexSpanIx=0,this.curObjDataSpanIx=0,this.curObjId=0,this.curObjIdxPage=null}reset(){this.curObjIndexSpanIx=0,this.curObjDataSpanIx=0,this.curObjId=0,this.curObjIdxPage=null}registerPage(t){if(t instanceof us){if(!this.curObjIdxPage)throw new Error("No current object index page");this.curObjIdxPage.registerPage(t)}try{if(!this.luPage)throw new hs;this.luPage.registerPage(t)}catch(e){if(!(e instanceof hs))throw e;{const e=this.luPageIter.next();if(e.done)throw new Error("Invalid attempt to add page to a block when there is no more space in lookup");this.luPage=e.value,this.luPage.registerPage(t)}}this.pages.push(t)}beginObj(t,e,i,s=0,a=0){if(this.remainingPages<=0)throw new hs;this.reset(),this.curObjId=t,this.curObjIndexSpanIx=s,this.curObjDataSpanIx=a;const r=new ds(t,this.curObjIndexSpanIx,e,i,this.buildConfig);this.registerPage(r),this.curObjIdxPage=r,this.remainingPages--,this.curObjIndexSpanIx++}updateObj(t){if(this.remainingPages<=0)throw new hs;const e=new us(this.offset+this.pages.length*this.buildConfig.pageSize,this.curObjId,this.curObjDataSpanIx,t,this.buildConfig);this.registerPage(e),this.curObjDataSpanIx++,this.remainingPages--}endObj(){this.reset()}isFull(){return this.remainingPages<=0}toBinary(t){const e=new Uint8Array(this.buildConfig.blockSize);e.fill(255);let i=0;if(this.buildConfig.useMagic)for(let s=0;s<this.pages.length;s++){const a=this.pages[s];s===this.buildConfig.OBJ_LU_PAGES_PER_BLOCK-1&&a instanceof cs&&a.magicfy(t);const r=a.toBinary();e.set(r,i),i+=r.length}else for(const t of this.pages){const s=t.toBinary();e.set(s,i),i+=s.length}return e}get currentObjIndexSpanIx(){return this.curObjIndexSpanIx}get currentObjDataSpanIx(){return this.curObjDataSpanIx}get currentObjId(){return this.curObjId}get currentObjIdxPage(){return this.curObjIdxPage}set currentObjId(t){this.curObjId=t}set currentObjIdxPage(t){this.curObjIdxPage=t}set currentObjDataSpanIx(t){this.curObjDataSpanIx=t}set currentObjIndexSpanIx(t){this.curObjIndexSpanIx=t}}class fs{constructor(t,e){if(t%e.blockSize!==0)throw new Error("image size should be a multiple of block size");this.imgSize=t,this.buildConfig=e,this.blocks=[],this.blocksLim=Math.floor(this.imgSize/this.buildConfig.blockSize),this.remainingBlocks=this.blocksLim,this.curObjId=1}createBlock(){if(this.isFull())throw new hs("the image size has been exceeded");const t=new gs(this.blocks.length,this.buildConfig);return this.blocks.push(t),this.remainingBlocks--,t}isFull(){return this.remainingBlocks<=0}createFile(t,e){if(t.length>this.buildConfig.objNameLen)throw new Error(`object name '${t}' too long`);const i=t;let s=0;try{this.blocks[this.blocks.length-1].beginObj(this.curObjId,e.length,i)}catch{this.createBlock().beginObj(this.curObjId,e.length,i)}for(;s<e.length;){const t=Math.min(this.buildConfig.OBJ_DATA_PAGE_CONTENT_LEN,e.length-s),a=e.slice(s,s+t);try{const t=this.blocks[this.blocks.length-1];try{t.updateObj(a)}catch(s){if(s instanceof hs){if(t.isFull())throw s;t.beginObj(this.curObjId,e.length,i,t.currentObjIndexSpanIx,t.currentObjDataSpanIx);continue}throw s}}catch(t){if(t instanceof hs){const t=this.blocks[this.blocks.length-1],e=this.createBlock();e.currentObjId=t.currentObjId,e.currentObjIdxPage=t.currentObjIdxPage,e.currentObjDataSpanIx=t.currentObjDataSpanIx,e.currentObjIndexSpanIx=t.currentObjIndexSpanIx;continue}throw t}s+=t}this.blocks[this.blocks.length-1].endObj(),this.curObjId++}toBinary(){const t=[];for(const e of this.blocks)t.push(e.toBinary(this.blocksLim));let e=this.blocks.length,i=this.remainingBlocks;if(this.buildConfig.useMagic)for(;i>0;){const s=new gs(e,this.buildConfig);t.push(s.toBinary(this.blocksLim)),i--,e++}else{const e=this.imgSize-t.length*this.buildConfig.blockSize;if(e>0){const i=new Uint8Array(e);i.fill(255),t.push(i)}}const s=t.reduce((t,e)=>t+e.length,0),a=new Uint8Array(s);let r=0;for(const e of t)a.set(e,r),r+=e.length;return a}listFiles(){throw new Error("listFiles requires fromBinary to be called first")}readFile(){throw new Error("readFile requires fromBinary to be called first")}deleteFile(){throw new Error("deleteFile not yet implemented - requires filesystem recreation")}}class _s{constructor(t,e){this.imageData=t,this.buildConfig=e,this.filesMap=new Map}unpack(t,e,i=0){const s=new DataView(e.buffer,e.byteOffset+i),a=[];let r=0;for(const e of t)switch(e){case"B":a.push(s.getUint8(r)),r+=1;break;case"H":a.push("little"===this.buildConfig.endianness?s.getUint16(r,!0):s.getUint16(r,!1)),r+=2;break;case"I":a.push("little"===this.buildConfig.endianness?s.getUint32(r,!0):s.getUint32(r,!1)),r+=4}return a}parse(){const t=Math.floor(this.imageData.length/this.buildConfig.blockSize);for(let e=0;e<t;e++){const t=e*this.buildConfig.blockSize,i=this.imageData.slice(t,t+this.buildConfig.blockSize);this.parseBlock(i)}}parseBlock(t){for(let e=0;e<this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;e++){const i=e*this.buildConfig.pageSize,s=t.slice(i,i+this.buildConfig.pageSize);for(let t=0;t<s.length&&!(t+this.buildConfig.objIdLen>s.length);t+=this.buildConfig.objIdLen){const e=s.slice(t,t+this.buildConfig.objIdLen),[i]=this.unpack(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I",e);if(i===(1<<8*this.buildConfig.objIdLen)-1)continue;const a=!!(i&1<<8*this.buildConfig.objIdLen-1),r=i&~(1<<8*this.buildConfig.objIdLen-1);a&&!this.filesMap.has(r)&&this.filesMap.set(r,{name:null,size:0,dataPages:[]})}}for(let e=this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;e<this.buildConfig.PAGES_PER_BLOCK;e++){const i=e*this.buildConfig.pageSize,s=t.slice(i,i+this.buildConfig.pageSize);this.parsePage(s)}}parsePage(t){const e=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B",i=this.buildConfig.objIdLen+this.buildConfig.spanIxLen+1;if(t.length<i)return;const[s,a,r]=this.unpack(e,t);if(s===(1<<8*this.buildConfig.objIdLen)-1)return;const n=!!(s&1<<8*this.buildConfig.objIdLen-1),h=s&~(1<<8*this.buildConfig.objIdLen-1);if(n&&248===r)this.filesMap.has(h)||this.filesMap.set(h,{name:null,size:0,dataPages:[]}),0===a&&this.parseIndexPage(t,i,h);else if(!n&&252===r&&this.filesMap.has(h)){const e=i,s=t.slice(e,e+this.buildConfig.OBJ_DATA_PAGE_CONTENT_LEN);this.filesMap.get(h).dataPages.push([a,s])}}parseIndexPage(t,e,i){let s=e+this.buildConfig.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD;if(s+5<=t.length){const[e]=this.unpack("IB",t,s);s+=5;const a=s+this.buildConfig.objNameLen;if(a<=t.length){const r=t.slice(s,a),n=r.indexOf(0),h=-1!==n?r.slice(0,n):r,o=(new TextDecoder).decode(h),l=this.filesMap.get(i);l.name=o,l.size=e}}}listFiles(){const t=[];for(const[,e]of this.filesMap){if(null===e.name)continue;e.dataPages.sort((t,e)=>t[0]-e[0]);const i=[];let s=0;for(const[,t]of e.dataPages){const a=e.size-s;if(a<=0)break;const r=Math.min(t.length,a);i.push(t.slice(0,r)),s+=r}const a=new Uint8Array(s);let r=0;for(const t of i)a.set(t,r),r+=t.length;t.push({name:e.name,size:e.size,data:a})}return t}readFile(t){const e=this.listFiles().find(e=>e.name===t||e.name==="/"+t);return e?e.data:null}}const ps={pageSize:256,blockSize:4096,objNameLen:32,metaLen:4,useMagic:!0,useMagicLen:!0,alignedObjIxTables:!1},bs=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 Ti(e,t)},ws=async(t,e)=>{if(!t)throw new Error("Port is required");return t.readable&&t.writable||await t.open({baudRate:o}),new Ti(t,e)};export{dt as CHIP_ERASE_TIMEOUT,v as CHIP_FAMILY_ESP32,E as CHIP_FAMILY_ESP32C2,k as CHIP_FAMILY_ESP32C3,D as CHIP_FAMILY_ESP32C5,x as CHIP_FAMILY_ESP32C6,O as CHIP_FAMILY_ESP32C61,T as CHIP_FAMILY_ESP32H2,A as CHIP_FAMILY_ESP32H21,M as CHIP_FAMILY_ESP32H4,F as CHIP_FAMILY_ESP32P4,U as CHIP_FAMILY_ESP32S2,C as CHIP_FAMILY_ESP32S3,L as CHIP_FAMILY_ESP32S31,I as CHIP_FAMILY_ESP8266,ps as DEFAULT_SPIFFS_CONFIG,ct as DEFAULT_TIMEOUT,ft as ERASE_REGION_TIMEOUT_PER_MB,zi as ESP8266_LITTLEFS_BLOCK_SIZE,Wi as ESP8266_LITTLEFS_BLOCK_SIZE_CANDIDATES,Ni as ESP8266_LITTLEFS_PAGE_SIZE,ji as ESP8266_SPIFFS_BLOCK_SIZE,$i as ESP8266_SPIFFS_PAGE_SIZE,Ti as ESPLoader,tt as ESP_CHANGE_BAUDRATE,st as ESP_CHECKSUM_MAGIC,Z as ESP_ERASE_FLASH,X as ESP_ERASE_REGION,W as ESP_FLASH_BEGIN,N as ESP_FLASH_DATA,at as ESP_FLASH_DEFL_BEGIN,rt as ESP_FLASH_DEFL_DATA,nt as ESP_FLASH_DEFL_END,$ as ESP_FLASH_END,it as ESP_GET_SECURITY_INFO,j as ESP_MEM_BEGIN,H as ESP_MEM_DATA,G as ESP_MEM_END,lt as ESP_RAM_BLOCK,K as ESP_READ_FLASH,V as ESP_READ_REG,Y as ESP_SPI_ATTACH,et as ESP_SPI_FLASH_MD5,q as ESP_SPI_SET_PARAMS,J as ESP_SYNC,Q as ESP_WRITE_REG,Pi as FATFS_BLOCK_SIZE_CANDIDATES,Li as FATFS_DEFAULT_BLOCK_SIZE,pt as FLASH_READ_TIMEOUT,Vi as FilesystemType,Fi as LITTLEFS_BLOCK_SIZE_CANDIDATES,Ai as LITTLEFS_DEFAULT_BLOCK_SIZE,ut as MAX_TIMEOUT,_t as MEM_END_ROM_TIMEOUT,ht as ROM_INVALID_RECV_MSG,gt as SYNC_TIMEOUT,ns as SpiffsBuildConfig,fs as SpiffsFS,_s as SpiffsReader,ot as USB_RAM_BLOCK,bs as connect,ws as connectWithPort,Xi as detectFilesystemFromImage,Zi as detectFilesystemType,a as formatMacAddr,rs as formatSize,qi as getBlockSizeCandidates,Ki as getDefaultBlockSize,Qi as getESP8266FilesystemLayout,as as getPartitionTableOffset,i as hexFormatter,ss as parsePartitionTable,Hi as scanESP8266Filesystem,r as sleep,s as toHex};
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=>t.map(t=>t.toString(16).toUpperCase().padStart(2,"0")).join(":"),r=t=>new Promise(e=>setTimeout(e,t)),n={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"},o=4096,h=115200,l=1073061888,d=1061265408,c=1610641408,u=1610647552,g=1611352064,f=1611335680,_=1611352064,p=1611335680,b=1343410176,w=1343312316,m=1<<27,S=1343312312,y=1343312892,B=544296960,I=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),R=33382,v=50,C=12882,E=12883,k=12994,U=12995,D=12997,x=12998,O=207969,M=12914,A=12916,T=12917,F=12928,L=12849,z={5:{name:"ESP32-C3",family:U},9:{name:"ESP32-S3",family:E},12:{name:"ESP32-C2",family:k},13:{name:"ESP32-C6",family:x},16:{name:"ESP32-H2",family:M},18:{name:"ESP32-P4",family:F},20:{name:"ESP32-C61",family:O},23:{name:"ESP32-C5",family:D},25:{name:"ESP32-H21",family:T},28:{name:"ESP32-H4",family:A},32:{name:"ESP32-S31",family:L}},P={4293968129:{name:"ESP8266",family:R},15736195:{name:"ESP32",family:v},1990:{name:"ESP32-S2",family:C}},N=2,$=3,W=4,j=5,G=6,H=7,J=8,Q=9,V=10,Z=208,X=209,K=210,q=11,Y=13,tt=15,et=19,it=20,st=239,at=16,rt=17,nt=18,ot=5,ht=2048,lt=6144,dt=3e3,ct=15e4,ut=3e5,gt=100,ft=3e4,_t=500,pt=100,bt=(t,e)=>{const i=Math.floor(t*(e/486));return i<dt?dt:i},wt=t=>{switch(t){case v:return{regBase:1072963584,baseFuse:l,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case C:return{regBase:1061167104,baseFuse:d,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case E:return{regBase:1610620928,usrOffs:24,baseFuse:c,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case R:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case k:return{regBase:1610620928,baseFuse:u,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case U:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case D:return{regBase:1610625024,baseFuse:g,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case x:return{regBase:1610625024,baseFuse:f,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case O:return{regBase:1610625024,baseFuse:_,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case M:return{regBase:1610625024,baseFuse:p,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case A:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case T:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case F:return{regBase:1342754816,baseFuse:b,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case L:return{regBase:542113792,baseFuse:B,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 mt extends Error{constructor(t){super(t),this.name="SlipReadError"}}const St=async(t,i)=>{let s;if(t==A||t==T||t==L)return null;if(t==v)s=await import("./esp32-BRKoi17y.js");else if(t==C)s=await import("./esp32s2-iX3WoDbg.js");else if(t==E)s=await import("./esp32s3-DGwDVIgz.js");else if(t==R)s=await import("./esp8266-CUwxJpGa.js");else if(t==k)s=await import("./esp32c2-Btgr_lwh.js");else if(t==U)s=await import("./esp32c3-CHKfoI8W.js");else if(t==D)s=await import("./esp32c5-BDW4KtLo.js");else if(t==x)s=await import("./esp32c6-il8tTxAG.js");else if(t==O)s=await import("./esp32c61-thKzxBGf.js");else if(t==M)s=await import("./esp32h2-CxoUHv_P.js");else{if(t!=F)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))}},yt={239:"Winbond",200:"GigaDevice",157:"ISSI",194:"Macronix/MXIC",32:"XMC / Micron",28:"EON",133:"Puya",104:"BOYA",161:"Fudan Microelectronics (FM)",1:"Spansion/Cypress",94:"Zbit",55:"AMIC",224:"Berg Micro"},Bt={66073:"S25FL256S (256Mbit)",81941:"S25FL016K (16Mbit)",81942:"S25FL032K (32Mbit)",90135:"S25FL064L (64Mbit)",90136:"S25FL128L (128Mbit)",1847315:"EN25Q40 (4Mbit)",1847316:"EN25Q80A (8Mbit)",1847317:"EN25Q16 (16Mbit)",1847318:"EN25Q32B (32Mbit)",1847319:"EN25Q64 (64Mbit)",1847320:"EN25Q128 (128Mbit)",1863701:"EN25QH16 (16Mbit)",1863702:"EN25QH32 (32Mbit)",1863703:"EN25QH64 (64Mbit)",1863704:"EN25QH128 (128Mbit)",2113557:"XM25QH16C (16Mbit)",2113558:"XM25QH32B (32Mbit)",2113559:"XM25QH64C (64Mbit)",2113560:"XM25QH128C (128Mbit)",2113561:"XM25QH256C (256Mbit)",2113817:"XM25QU256C (256Mbit)",2125847:"XM25QH64A (64Mbit)",2125848:"XM25QH128A (128Mbit)",2144790:"N25Q032A (32Mbit)",2144791:"N25Q064A (64Mbit)",2144792:"N25Q128A (128Mbit)",2145045:"N25Q016A (16Mbit)",3612693:"A25L016 (16Mbit)",3612694:"A25L032 (32Mbit)",3620886:"A25LQ032 (32Mbit)",6176789:"ZB25VQ16 (16Mbit)",6176790:"ZB25VQ32 (32Mbit)",6176791:"ZB25VQ64 (64Mbit)",6176792:"ZB25VQ128 (128Mbit)",6832149:"BY25Q16 (16Mbit)",6832150:"BY25Q32 (32Mbit)",6832151:"BY25Q64 (64Mbit)",6832152:"BY25Q128 (128Mbit)",8740885:"P25Q16H (16Mbit)",8740886:"P25Q32H (32Mbit)",8740887:"P25Q64H (64Mbit)",8740888:"P25Q128H (128Mbit)",10313749:"IS25LP016 (16Mbit)",10313750:"IS25LP032 (32Mbit)",10313751:"IS25LP064 (64Mbit)",10313752:"IS25LP128 (128Mbit)",10313753:"IS25LP256 (256Mbit)",10317845:"IS25WP016 (16Mbit)",10317846:"IS25WP032 (32Mbit)",10317847:"IS25WP064 (64Mbit)",10317848:"IS25WP128 (128Mbit)",10317849:"IS25WP256 (256Mbit)",10567700:"FM25Q08 (8Mbit)",10567701:"FM25Q16 (16Mbit)",10567702:"FM25Q32 (32Mbit)",10567703:"FM25Q64 (64Mbit)",10567704:"FM25Q128 (128Mbit)",12722192:"MX25L512E (512Kbit)",12722193:"MX25L1005C (1Mbit)",12722194:"MX25L2005C (2Mbit)",12722195:"MX25L4005 (4Mbit)",12722196:"MX25L8005 (8Mbit)",12722197:"MX25L1605D (16Mbit)",12722198:"MX25L3205D (32Mbit)",12722199:"MX25L6405D (64Mbit)",12722200:"MX25L12805D (128Mbit)",12722201:"MX25L25635E (256Mbit)",12722202:"MX25L51245G (512Mbit)",12738070:"MX25L3233F (32Mbit)",13123601:"GD25Q10 (1Mbit)",13123602:"GD25Q20 (2Mbit)",13123603:"GD25Q40 (4Mbit)",13123604:"GD25Q80 (8Mbit)",13123605:"GD25Q16 (16Mbit)",13123606:"GD25Q32 (32Mbit)",13123607:"GD25Q64 (64Mbit)",13123608:"GD25Q127C (128Mbit)",13123609:"GD25Q256 (256Mbit)",13123616:"GD25Q512 (512Mbit)",13131801:"GD25LQ256D (256Mbit)",14696469:"BG25Q16A (16Mbit)",14696470:"BG25Q32 (32Mbit)",14696471:"BG25Q64 (64Mbit)",14696472:"BG25Q128 (128Mbit)",15679508:"W25Q80 (8Mbit)",15679509:"W25Q16 (16Mbit)",15679510:"W25Q32 (32Mbit)",15679511:"W25Q64 (64Mbit)",15679512:"W25Q128 (128Mbit)",15679513:"W25Q256 (256Mbit)",15679520:"W25Q512JV (512Mbit)",15683602:"W25Q20BW (2Mbit)",15683603:"W25Q40BW (4Mbit)",15687697:"W25Q10EW (1Mbit)",15687698:"W25Q20EW (2Mbit)",15687699:"W25Q40EW (4Mbit)"};function It(t){let e=t.length;for(;--e>=0;)t[e]=0}const Rt=256,vt=286,Ct=30,Et=15,kt=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]),Ut=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]),Dt=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),xt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ot=new Array(576);It(Ot);const Mt=new Array(60);It(Mt);const At=new Array(512);It(At);const Tt=new Array(256);It(Tt);const Ft=new Array(29);It(Ft);const Lt=new Array(Ct);function zt(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 Pt,Nt,$t;function Wt(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}It(Lt);const jt=t=>t<256?At[t]:At[256+(t>>>7)],Gt=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},Ht=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,Gt(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)},Jt=(t,e,i)=>{Ht(t,i[2*e],i[2*e+1])},Qt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},Vt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=Et;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]=Qt(s[e]++,e))}},Zt=t=>{let e;for(e=0;e<vt;e++)t.dyn_ltree[2*e]=0;for(e=0;e<Ct;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},Xt=t=>{t.bi_valid>8?Gt(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},Kt=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},qt=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&&Kt(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!Kt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},Yt=(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?Jt(t,a,e):(r=Tt[a],Jt(t,r+Rt+1,e),n=kt[r],0!==n&&(a-=Ft[r],Ht(t,a,n)),s--,r=jt(s),Jt(t,r,i),n=Ut[r],0!==n&&(s-=Lt[r],Ht(t,s,n)))}while(o<t.sym_next);Jt(t,256,e)},te=(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--)qt(t,i,n);h=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],qt(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++,qt(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<=Et;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),Vt(i,l,t.bl_count)},ee=(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))},ie=(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{Jt(t,a,t.bl_tree)}while(0!==--o);else 0!==a?(a!==r&&(Jt(t,a,t.bl_tree),o--),Jt(t,16,t.bl_tree),Ht(t,o-3,2)):o<=10?(Jt(t,17,t.bl_tree),Ht(t,o-3,3)):(Jt(t,18,t.bl_tree),Ht(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 se=!1;const ae=(t,e,i,s)=>{Ht(t,0+(s?1:0),3),Xt(t),Gt(t,i),Gt(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var re=(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<Rt;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),te(t,t.l_desc),te(t,t.d_desc),n=(t=>{let e;for(ee(t,t.dyn_ltree,t.l_desc.max_code),ee(t,t.dyn_dtree,t.d_desc.max_code),te(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*xt[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?ae(t,e,i,s):4===t.strategy||r===a?(Ht(t,2+(s?1:0),3),Yt(t,Ot,Mt)):(Ht(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(Ht(t,e-257,5),Ht(t,i-1,5),Ht(t,s-4,4),a=0;a<s;a++)Ht(t,t.bl_tree[2*xt[a]+1],3);ie(t,t.dyn_ltree,e-1),ie(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),Yt(t,t.dyn_ltree,t.dyn_dtree)),Zt(t),s&&Xt(t)},ne={_tr_init:t=>{se||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(Ft[s]=i,t=0;t<1<<kt[s];t++)Tt[i++]=s;for(Tt[i-1]=s,a=0,s=0;s<16;s++)for(Lt[s]=a,t=0;t<1<<Ut[s];t++)At[a++]=s;for(a>>=7;s<Ct;s++)for(Lt[s]=a<<7,t=0;t<1<<Ut[s]-7;t++)At[256+a++]=s;for(e=0;e<=Et;e++)r[e]=0;for(t=0;t<=143;)Ot[2*t+1]=8,t++,r[8]++;for(;t<=255;)Ot[2*t+1]=9,t++,r[9]++;for(;t<=279;)Ot[2*t+1]=7,t++,r[7]++;for(;t<=287;)Ot[2*t+1]=8,t++,r[8]++;for(Vt(Ot,287,r),t=0;t<Ct;t++)Mt[2*t+1]=5,Mt[2*t]=Qt(t,5);Pt=new zt(Ot,kt,257,vt,Et),Nt=new zt(Mt,Ut,0,Ct,Et),$t=new zt(new Array(0),Dt,0,19,7)})(),se=!0),t.l_desc=new Wt(t.dyn_ltree,Pt),t.d_desc=new Wt(t.dyn_dtree,Nt),t.bl_desc=new Wt(t.bl_tree,$t),t.bi_buf=0,t.bi_valid=0,Zt(t)},_tr_stored_block:ae,_tr_flush_block:re,_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*(Tt[i]+Rt+1)]++,t.dyn_dtree[2*jt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{Ht(t,2,3),Jt(t,256,Ot),(t=>{16===t.bi_valid?(Gt(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 oe=(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 he=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 le=(t,e,i,s)=>{const a=he,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},de={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"},ce={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:ue,_tr_stored_block:ge,_tr_flush_block:fe,_tr_tally:_e,_tr_align:pe}=ne,{Z_NO_FLUSH:be,Z_PARTIAL_FLUSH:we,Z_FULL_FLUSH:me,Z_FINISH:Se,Z_BLOCK:ye,Z_OK:Be,Z_STREAM_END:Ie,Z_STREAM_ERROR:Re,Z_DATA_ERROR:ve,Z_BUF_ERROR:Ce,Z_DEFAULT_COMPRESSION:Ee,Z_FILTERED:ke,Z_HUFFMAN_ONLY:Ue,Z_RLE:De,Z_FIXED:xe,Z_DEFAULT_STRATEGY:Oe,Z_UNKNOWN:Me,Z_DEFLATED:Ae}=ce,Te=258,Fe=262,Le=42,ze=113,Pe=666,Ne=(t,e)=>(t.msg=de[e],e),$e=t=>2*t-(t>4?9:0),We=t=>{let e=t.length;for(;--e>=0;)t[e]=0},je=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 Ge=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const He=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))},Je=(t,e)=>{fe(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,He(t.strm)},Qe=(t,e)=>{t.pending_buf[t.pending++]=e},Ve=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},Ze=(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=oe(t.adler,e,a,i):2===t.state.wrap&&(t.adler=le(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},Xe=(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-Fe?t.strstart-(t.w_size-Fe):0,l=t.window,d=t.w_mask,c=t.prev,u=t.strstart+Te;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=Te-(u-r),r=u-Te,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},Ke=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Fe)&&(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),je(t),s+=e),0===t.strm.avail_in)break;if(i=Ze(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=Ge(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=Ge(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<Fe&&0!==t.strm.avail_in)},qe=(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!==Se||e===be||i!==s+t.strm.avail_in))break;n=e===Se&&i===s+t.strm.avail_in?1:0,ge(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,He(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&&(Ze(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!==be&&e!==Se&&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&&(Ze(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===Se)&&e!==be&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===Se&&0===t.strm.avail_in&&i===s?1:0,ge(t,t.block_start,i,n),t.block_start+=i,He(t.strm)),n?3:1)},Ye=(t,e)=>{let i,s;for(;;){if(t.lookahead<Fe){if(Ke(t),t.lookahead<Fe&&e===be)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Ge(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-Fe&&(t.match_length=Xe(t,i)),t.match_length>=3)if(s=_e(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=Ge(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=Ge(t,t.ins_h,t.window[t.strstart+1]);else s=_e(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(Je(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===Se?(Je(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(Je(t,!1),0===t.strm.avail_out)?1:2},ti=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<Fe){if(Ke(t),t.lookahead<Fe&&e===be)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Ge(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-Fe&&(t.match_length=Xe(t,i),t.match_length<=5&&(t.strategy===ke||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=_e(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=Ge(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&&(Je(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=_e(t,0,t.window[t.strstart-1]),s&&Je(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=_e(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===Se?(Je(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(Je(t,!1),0===t.strm.avail_out)?1:2};function ei(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 ii=[new ei(0,0,0,0,qe),new ei(4,4,8,4,Ye),new ei(4,5,16,8,Ye),new ei(4,6,32,32,Ye),new ei(4,4,16,16,ti),new ei(8,16,32,32,ti),new ei(8,16,128,128,ti),new ei(8,32,128,256,ti),new ei(32,128,258,1024,ti),new ei(32,258,258,4096,ti)];function si(){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=Ae,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),We(this.dyn_ltree),We(this.dyn_dtree),We(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),We(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),We(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 ai=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Le&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==ze&&e.status!==Pe?1:0},ri=t=>{if(ai(t))return Ne(t,Re);t.total_in=t.total_out=0,t.data_type=Me;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?Le:ze,t.adler=2===e.wrap?0:1,e.last_flush=-2,ue(e),Be},ni=t=>{const e=ri(t);var i;return e===Be&&((i=t.state).window_size=2*i.w_size,We(i.head),i.max_lazy_match=ii[i.level].max_lazy,i.good_match=ii[i.level].good_length,i.nice_match=ii[i.level].nice_length,i.max_chain_length=ii[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},oi=(t,e,i,s,a,r)=>{if(!t)return Re;let n=1;if(e===Ee&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==Ae||s<8||s>15||e<0||e>9||r<0||r>xe||8===s&&1!==n)return Ne(t,Re);8===s&&(s=9);const o=new si;return t.state=o,o.strm=t,o.status=Le,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,ni(t)};var hi={deflateInit:(t,e)=>oi(t,e,Ae,15,8,Oe),deflateInit2:oi,deflateReset:ni,deflateResetKeep:ri,deflateSetHeader:(t,e)=>ai(t)||2!==t.state.wrap?Re:(t.state.gzhead=e,Be),deflate:(t,e)=>{if(ai(t)||e>ye||e<0)return t?Ne(t,Re):Re;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===Pe&&e!==Se)return Ne(t,0===t.avail_out?Ce:Re);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(He(t),0===t.avail_out)return i.last_flush=-1,Be}else if(0===t.avail_in&&$e(e)<=$e(s)&&e!==Se)return Ne(t,Ce);if(i.status===Pe&&0!==t.avail_in)return Ne(t,Ce);if(i.status===Le&&0===i.wrap&&(i.status=ze),i.status===Le){let e=Ae+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=Ue||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,Ve(i,e),0!==i.strstart&&(Ve(i,t.adler>>>16),Ve(i,65535&t.adler)),t.adler=1,i.status=ze,He(t),0!==i.pending)return i.last_flush=-1,Be}if(57===i.status)if(t.adler=0,Qe(i,31),Qe(i,139),Qe(i,8),i.gzhead)Qe(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)),Qe(i,255&i.gzhead.time),Qe(i,i.gzhead.time>>8&255),Qe(i,i.gzhead.time>>16&255),Qe(i,i.gzhead.time>>24&255),Qe(i,9===i.level?2:i.strategy>=Ue||i.level<2?4:0),Qe(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Qe(i,255&i.gzhead.extra.length),Qe(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=le(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Qe(i,0),Qe(i,0),Qe(i,0),Qe(i,0),Qe(i,0),Qe(i,9===i.level?2:i.strategy>=Ue||i.level<2?4:0),Qe(i,3),i.status=ze,He(t),0!==i.pending)return i.last_flush=-1,Be;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=le(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,He(t),0!==i.pending)return i.last_flush=-1,Be;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=le(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=le(t.adler,i.pending_buf,i.pending-s,s)),He(t),0!==i.pending)return i.last_flush=-1,Be;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,Qe(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=le(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=le(t.adler,i.pending_buf,i.pending-s,s)),He(t),0!==i.pending)return i.last_flush=-1,Be;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,Qe(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=le(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&&(He(t),0!==i.pending))return i.last_flush=-1,Be;Qe(i,255&t.adler),Qe(i,t.adler>>8&255),t.adler=0}if(i.status=ze,He(t),0!==i.pending)return i.last_flush=-1,Be}if(0!==t.avail_in||0!==i.lookahead||e!==be&&i.status!==Pe){let s=0===i.level?qe(i,e):i.strategy===Ue?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(Ke(t),0===t.lookahead)){if(e===be)return 1;break}if(t.match_length=0,i=_e(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(Je(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Se?(Je(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(Je(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===De?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=Te){if(Ke(t),t.lookahead<=Te&&e===be)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+Te;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=Te-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=_e(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=_e(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(Je(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Se?(Je(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(Je(t,!1),0===t.strm.avail_out)?1:2})(i,e):ii[i.level].func(i,e);if(3!==s&&4!==s||(i.status=Pe),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),Be;if(2===s&&(e===we?pe(i):e!==ye&&(ge(i,0,0,!1),e===me&&(We(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),He(t),0===t.avail_out))return i.last_flush=-1,Be}return e!==Se?Be:i.wrap<=0?Ie:(2===i.wrap?(Qe(i,255&t.adler),Qe(i,t.adler>>8&255),Qe(i,t.adler>>16&255),Qe(i,t.adler>>24&255),Qe(i,255&t.total_in),Qe(i,t.total_in>>8&255),Qe(i,t.total_in>>16&255),Qe(i,t.total_in>>24&255)):(Ve(i,t.adler>>>16),Ve(i,65535&t.adler)),He(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Be:Ie)},deflateEnd:t=>{if(ai(t))return Re;const e=t.state.status;return t.state=null,e===ze?Ne(t,ve):Be},deflateSetDictionary:(t,e)=>{let i=e.length;if(ai(t))return Re;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==Le||s.lookahead)return Re;if(1===a&&(t.adler=oe(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(We(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,Ke(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=Ge(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,Ke(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,Be},deflateInfo:"pako deflate (from Nodeca project)"};const li=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var di=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)li(i,e)&&(t[e]=i[e])}}return t},ci=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 ui=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){ui=!1}const gi=new Uint8Array(256);for(let t=0;t<256;t++)gi[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;gi[254]=gi[254]=1;var fi=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 _i=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 pi=Object.prototype.toString,{Z_NO_FLUSH:bi,Z_SYNC_FLUSH:wi,Z_FULL_FLUSH:mi,Z_FINISH:Si,Z_OK:yi,Z_STREAM_END:Bi,Z_DEFAULT_COMPRESSION:Ii,Z_DEFAULT_STRATEGY:Ri,Z_DEFLATED:vi}=ce;function Ci(t){this.options=di({level:Ii,method:vi,chunkSize:16384,windowBits:15,memLevel:8,strategy:Ri},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 _i,this.strm.avail_out=0;let i=hi.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==yi)throw new Error(de[i]);if(e.header&&hi.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?fi(e.dictionary):"[object ArrayBuffer]"===pi.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=hi.deflateSetDictionary(this.strm,t),i!==yi)throw new Error(de[i]);this._dict_set=!0}}Ci.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?Si:bi,"string"==typeof t?i.input=fi(t):"[object ArrayBuffer]"===pi.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===wi||r===mi)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=hi.deflate(i,r),a===Bi)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=hi.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===yi;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},Ci.prototype.onData=function(t){this.chunks.push(t)},Ci.prototype.onEnd=function(t){t===yi&&(this.result=ci(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Ei={deflate:function(t,e){const i=new Ci(e);if(i.push(t,!0),i.err)throw i.msg||de[i.err];return i.result}};const{deflate:ki}=Ei;var Ui=ki;const Di={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}},xi=(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 Di))throw"Unhandled character '"+t+"' in pack format";const i=Di[t].bytes,r=new DataView(new ArrayBuffer(i));Di[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},Oi=(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 Di))throw"Unhandled character '"+t+"' in unpack format";const r=Di[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const o=Di[t].u.bind(n);s.push(o(0,a)),i+=r}return s};class Mi 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=h,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===F&&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}`)}try{const t=await this.getUsbMode();this.logger.debug(`USB mode (register): ${t.mode} (uartNo=${t.uartNo})`)}catch(t){this.logger.debug(`Could not detect USB mode: ${t}`)}const t=wt(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);const i=null!==this.chipRevision&&void 0!==this.chipRevision?` (revision ${this.chipRevision})`:"";this.logger.log(`Connected to ${this.chipName}${i}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=z[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===F&&this.chipRevision>=300?this.chipVariant="rev300":this.chipFamily===F&&(this.chipVariant="rev0"),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 r(gt);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=P[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.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===F&&(this.chipVariant=this.chipRevision>=300?"rev300":"rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){var t;let e=0,i=0;switch(this.chipFamily){case v:{const s=await this.readRegister(1073061900),a=await this.readRegister(1073061908);e=a>>24&3;const r=s>>15&1,n=a>>20&1;i=null!==(t={0:0,1:1,3:2,7:3}[(await this.readRegister(1073111164)>>31&1)<<2|n<<1|r])&&void 0!==t?t:0;break}case C:{const t=await this.readRegister(1061265488);e=((t>>20&1)<<3)+(await this.readRegister(1061265492)>>4&7),i=t>>18&3;break}case E:{const t=await this.readRegister(1610641488),s=await this.readRegister(1610641496);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case k:{const t=await this.readRegister(1610647620);e=t>>16&15,i=t>>20&3;break}case U:{const t=await this.readRegister(1610647632),s=await this.readRegister(1610647640);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case D:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case x:{const t=await this.readRegister(1611335760);e=t>>18&15,i=t>>22&3;break}case O:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case M:{const t=await this.readRegister(1611335760);e=t>>18&7,i=t>>21&3;break}case A:case T:break;case F:{const t=await this.readRegister(1343410252);e=15&t,i=(t>>23&1)<<2|t>>4&3;break}case L:{const t=await this.readRegister(544297036);e=15&t,i=t>>4&3;break}}return 100*i+e}async powerOnFlash(){if(this.chipFamily!==F)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await r(10);const t=await this.readRegister(w);await this.writeRegister(w,t|m);const e=await this.readRegister(S);await this.writeRegister(S,128|e);const i=await this.readRegister(y);await this.writeRegister(y,3|i),await r(.05);const s=await this.readRegister(w);await this.writeRegister(w,-134217729&s);const a=await this.readRegister(S);await this.writeRegister(S,-2139095041&a);const n=await this.readRegister(S);await this.writeRegister(S,128|n);const o=await this.readRegister(S);await this.writeRegister(S,-129&o),await r(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:Oi("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?Oi("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?Oi("<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")}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 r(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.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await r(50),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await r(25),await this.setDTRWebUSB(!1),await r(100)}async hardResetInvertedWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await r(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await r(50),await this.setDTRWebUSB(!0),await r(200)}async hardResetInvertedDTRWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await r(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await r(50),await this.setDTRWebUSB(!0),await r(200)}async hardResetInvertedRTSWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await r(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await r(50),await this.setDTRWebUSB(!1),await r(200)}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,s=[],a=this,n=!e&&!i;if(this.isWebUSB()){const r=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 a.hardResetUSBJTAGSerial()}),s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async()=>await a.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async()=>await a.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async()=>await a.hardResetClassic()})):(s.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async()=>await a.hardResetUSBJTAGSerialInvertedDTRWebUSB()}),s.push({name:"USB-JTAG/Serial (WebUSB)",fn:async()=>await a.hardResetUSBJTAGSerial()}),s.push({name:"Inverted DTR Classic (WebUSB)",fn:async()=>await a.hardResetInvertedDTRWebUSB()}))),n&&(o?(s.push({name:"UnixTight (WebUSB) - CH34x",fn:async()=>await a.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CH34x",fn:async()=>await a.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CH34x",fn:async()=>await a.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async()=>await a.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async()=>await a.hardResetInvertedDTRWebUSB()})):r?(s.push({name:"UnixTight (WebUSB) - CP2102",fn:async()=>await a.hardResetUnixTight()}),s.push({name:"Classic (WebUSB) - CP2102",fn:async()=>await a.hardResetClassic()}),s.push({name:"Inverted Both (WebUSB) - CP2102",fn:async()=>await a.hardResetInvertedWebUSB()}),s.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async()=>await a.hardResetInvertedRTSWebUSB()}),s.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async()=>await a.hardResetInvertedDTRWebUSB()})):(s.push({name:"UnixTight (WebUSB)",fn:async()=>await a.hardResetUnixTight()}),s.push({name:"Classic (WebUSB)",fn:async function(){return await a.hardResetClassic()}}),s.push({name:"Inverted Both (WebUSB)",fn:async function(){return await a.hardResetInvertedWebUSB()}}),s.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await a.hardResetInvertedRTSWebUSB()}}),s.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await a.hardResetInvertedDTRWebUSB()}}))),r||h||(6790!==t.usbVendorId&&s.push({name:"Classic (WebUSB)",fn:async function(){return await a.hardResetClassic()}}),s.push({name:"UnixTight (WebUSB)",fn:async function(){return await a.hardResetUnixTight()}}),s.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await a.hardResetClassicLongDelayWebUSB()}}),s.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await a.hardResetClassicShortDelayWebUSB()}}),e||i||s.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await a.hardResetUSBJTAGSerial()}}))}else(e||i)&&s.push({name:"USB-JTAG/Serial",fn:async function(){return await a.hardResetUSBJTAGSerial()}}),s.push({name:"UnixTight",fn:async function(){return await a.hardResetUnixTight()}}),e||i||s.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await a.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.debug(`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 r(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 rtcWdtResetChipSpecific(){let t,e,i,s;if(this.logger.debug("Hard resetting with watchdog timer..."),this.chipFamily===C)t=1061191852,e=1061191828,i=1061191832,s=1356348065;else if(this.chipFamily===E)t=1610645680,e=1610645656,i=1610645660,s=1356348065;else if(this.chipFamily===U)t=1610645672,e=1610645648,i=1610645652,s=1356348065;else if(this.chipFamily===D||this.chipFamily===x)t=1611340824,e=1611340800,i=1611340804,s=1356348065;else{if(this.chipFamily!==F)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 r(500)}async resetToFirmwareMode(t=!0){this.logger.debug("Resetting from bootloader to firmware mode...");try{if(await this.detectUsbConnectionType()){let e;this.logger.debug("USB-JTAG/OTG detected - checking WDT reset support");try{e=await this.getUsbMode(),this.logger.debug(`USB mode: ${e.mode} (uartNo=${e.uartNo})`)}catch(t){this.logger.debug(`Could not get USB mode: ${t}`),e={mode:"usb-jtag-serial",uartNo:0}}if(!(this.chipFamily===C||this.chipFamily===E||this.chipFamily===F))return this.logger.debug(`${this.chipName} does not support WDT reset - using classic reset instead`),await this.hardResetToFirmware(),this.logger.debug("Classic reset to firmware complete"),!1;if(this.logger.debug(`${this.chipName} supports WDT reset - using WDT reset strategy`),this.IS_STUB){this.logger.debug("On stub - returning to ROM before WDT reset"),this.currentBaudRate!==h&&(this.logger.debug(`Changing baudrate from ${this.currentBaudRate} to 115200`),await this.reconfigurePort(h),this.currentBaudRate=h,this.logger.debug("Baudrate changed to 115200"));const t=this._consoleMode;this._consoleMode=!1,await this.hardReset(!0),await r(200),this._consoleMode=t,await this.sync(),this.IS_STUB=!1,this.logger.debug("Now on ROM")}else this.currentBaudRate!==h&&(this.logger.debug(`Not on stub, but baudrate is ${this.currentBaudRate} - changing to 115200 for WDT reset`),await this.reconfigurePort(h),this.currentBaudRate=h,this.logger.debug("Baudrate changed to 115200"));if(t&&"usb-otg"===e.mode){await this._clearForceDownloadBootIfNeeded()&&this.logger.debug("Force download boot flag cleared")}await this.rtcWdtResetChipSpecific(),this.logger.debug("WDT reset performed - device will boot to firmware");return!!("usb-otg"===e.mode||"usb-jtag-serial"===e.mode)&&(this.logger.debug(`Port will change after WDT reset (${e.mode}) - port reselection needed`),!0)}return this.logger.debug("External serial chip detected - using classic reset"),await this.hardResetToFirmware(),this.logger.debug("Classic reset to firmware complete"),!1}catch(t){throw this.logger.error(`Failed to reset to firmware mode: ${t}`),t}}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.resetInConsoleMode(),void this.logger.debug("Hardware reset complete"));if(t)4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.debug("USB-JTAG/Serial reset to bootloader.")):(await this.hardResetClassic(),this.logger.debug("Classic reset to bootloader."));else{this.logger.debug("Resetting to firmware mode...");if(await this.detectUsbConnectionType()){let t;this.logger.debug("USB-JTAG/OTG detected - using WDT reset");try{t=await this.getUsbMode(),this.logger.debug(`USB mode: ${t.mode} (uartNo=${t.uartNo})`)}catch(e){this.logger.debug(`Could not get USB mode: ${e}`),t={mode:"usb-jtag-serial",uartNo:0}}if("usb-otg"===t.mode)try{await this._clearForceDownloadBootIfNeeded()&&this.logger.debug("Force download boot flag cleared")}catch(t){this.logger.debug(`Could not clear force download flag: ${t}`)}return await this.rtcWdtResetChipSpecific(),void this.logger.debug(`${this.chipName}: WDT reset to firmware complete`)}this.logger.debug("External serial chip detected - using classic reset"),this.isWebUSB()?(await this.setRTSWebUSB(!0),await r(200),await this.setRTSWebUSB(!1),await r(200),this.logger.debug("Hard reset to firmware (WebUSB).")):(await this.setRTS(!0),await r(100),await this.setRTS(!1),this.logger.debug("Hard reset to firmware."))}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==R){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==v)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!=C&&this.chipFamily!=E&&this.chipFamily!=k&&this.chipFamily!=U&&this.chipFamily!=D&&this.chipFamily!=x&&this.chipFamily!=O&&this.chipFamily!=M&&this.chipFamily!=A&&this.chipFamily!=T&&this.chipFamily!=F&&this.chipFamily!=L)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=xi("<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,ut),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==R?h=2:[v,C,E,k,U,D,x,O,M,A,T,F,L].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([...xi("<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,a=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new mt("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new mt("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){if(Date.now()-n>t){throw new mt("Timed out waiting for packet "+(null===e?"header":"content"))}const r=this._readByte();if(null===e){if(r!=this.SLIP_END)throw this.debug&&(this.logger.debug("Read invalid data: "+s(r)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new mt("Invalid head of packet ("+s(r)+")");e=[]}else if(a)if(a=!1,r==this.SLIP_ESC_END)e.push(this.SLIP_END);else{if(r!=this.SLIP_ESC_ESC)throw this.debug&&(this.logger.debug("Read invalid data: "+s(r)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new mt("Invalid SLIP escape (0xdb, "+s(r)+")");e.push(this.SLIP_ESC)}else if(r==this.SLIP_ESC)a=!0;else{if(r==this.SLIP_END)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(r)}}else await r(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new mt("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 r(1)}if(0==n.length){throw new mt("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 mt("Invalid head of packet ("+s(t)+")");e=[]}else if(a)if(a=!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 mt("Invalid SLIP escape (0xdb, "+s(t)+")");e.push(this.SLIP_ESC)}else if(t==this.SLIP_ESC)a=!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]=Oi("<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=h*t/1e6;return e>45?48:e>33?40:26}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==D)try{const e=xi("<II",t,this.IS_STUB?h: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 r(gt),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.debug(`Changed baud rate to ${t}`)}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=xi("<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 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 r(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 r(gt),!0}catch(t){if(this._abandonCurrentOperation)return!1}await r(gt)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await r(gt),!0;await r(gt)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,I);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,gt);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=dt;a?(n=Ui(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,xi("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,xi("<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&&[v,C,E,k,U,D,x,O,M,A,T,F,L].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=R||this.IS_STUB?t:this.getEraseSize(e,t);const o=this.IS_STUB?dt:bt(ft,t),h=Date.now();let l=xi("<IIII",a,n,r,e);return this.chipFamily!=v&&this.chipFamily!=C&&this.chipFamily!=E&&this.chipFamily!=k&&this.chipFamily!=U&&this.chipFamily!=D&&this.chipFamily!=x&&this.chipFamily!=O&&this.chipFamily!=M&&this.chipFamily!=A&&this.chipFamily!=T&&this.chipFamily!=F&&this.chipFamily!=L||(l=l.concat(xi("<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=bt(ft,n)):(n=r*s,o=dt);const h=xi("<IIII",n,a,s,i);return await this.checkCommand(16,h,0,o),o}async flashFinish(){const t=xi("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=xi("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return wt(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=xi("<IIII",t,e,i,s);a>0&&(r=r.concat(xi("<IIII",wt(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=wt(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=Oi("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.debug("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255,s=(t>>8&255)<<8|i,a=yt[e],r=Bt[e<<16|s];this.logger.log(`Flash Manufacturer: ${a||"Unknown"} (0x${e.toString(16)})`),this.logger.log(`Flash Device: ${r||`Unknown (0x${s.toString(16)})`}`),this.flashSize=n[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=o,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,xi("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,xi("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?dt:500,i=xi("<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 St(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.debug("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.debug("Stub is now running...");const r=new Ai(this.port,this.logger,this);return t||await r.detectFlashSize(),r}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 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)try{this._suppressDisconnect=!0,await this._reader.cancel(),this.logger.debug("Reader cancelled - waiting for readLoop to finish"),await r(50),this.logger.debug("ReadLoop cleanup should be complete")}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}}}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 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 C:a=1073741076,n=2;break;case E:a=1070526796,r=4,n=3;break;case U:a=(s<101?1070461028:1070461024)+24,r=3;break;case D:a=1082520852,r=3;break;case x:a=1082652032,r=3;break;case O:a=s<=200?1082455532:1082455524,r=s<=200?3:4;break;case M:a=1082457852,r=3;break;case A:a=1082652032,r=3;break;case F: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})}supportsNativeUsb(){const t=this._parent?this._parent.chipFamily:this.chipFamily;return[C,E,U,D,x,O,M,A,F].includes(t)}async _ensureStreamsReady(){if(this.isWebUSB())try{await this.port.recreateStreams(),this.logger.debug("WebUSB streams recreated");let t=30;for(;t>0&&!this.port.readable;)await r(100),t--;if(!this.port.readable)throw new Error("Readable stream not available after recreating streams");this.logger.debug("WebUSB streams are ready")}catch(t){throw this.logger.error(`Failed to recreate WebUSB streams: ${t}`),this._consoleMode=!1,t}else{let t=20;for(;t>0&&!this.port.readable;)await r(100),t--;if(!this.port.readable)throw this._consoleMode=!1,new Error("Readable stream not available after reset");this.logger.debug("Port streams are ready")}}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.logger.debug(`USB detection failed, using cached value: ${this.isUsbJtagOrOtg}`),t=this.isUsbJtagOrOtg}if(this._consoleMode=!0,t){return!!await this._resetToFirmwareIfNeeded()||(await this._ensureStreamsReady(),!1)}try{await this.releaseReaderWriter(),await r(100)}catch(t){this.logger.debug(`Failed to release locks: ${t}`)}try{await this.hardResetToFirmware(),this.logger.debug("Device reset to firmware mode")}catch(t){this.logger.debug(`Could not reset device: ${t}`)}return await this._ensureStreamsReady(),!1}async _clearForceDownloadBootIfNeeded(){try{let t,e,i;if(this.chipFamily===C)t=1061191976,e=1,i="ESP32-S2";else if(this.chipFamily===E)t=1610645804,e=1,i="ESP32-S3";else{if(this.chipFamily!==F)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(){const t=await this.detectUsbConnectionType();try{if(!this.port.writable||!this.port.readable)return this.logger.debug("Port is not open - assuming device is already in firmware mode"),!1;t?this.logger.debug("USB-JTAG/OTG: Keeping reader/writer active for WDT reset"):(await this.releaseReaderWriter(),this.logger.debug("External serial: Reader/writer released before reset"));return await this.resetToFirmwareMode(!0)?(this.logger.debug(`${this.chipName}: Port will change after WDT reset - user must reselect port`),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):(t&&(await this.releaseReaderWriter(),this.logger.debug("Reader/writer released after reset")),!1)}catch(e){return this.logger.error(`Reset to firmware mode failed: ${e}`),t?(this.logger.debug("Forcing port reselection due to USB-JTAG/OTG reset failure"),!0):(this.logger.debug("External serial reset failed, but port should still be usable"),!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:h}),this.connected=!0,this.currentBaudRate=h}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===F&&301===this.chipRevision&&await this.powerOnFlash();const n=await this.runStub(!0);if(this.logger.debug("Stub loaded"),t!==h&&(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:h}),this.connected=!0,this.currentBaudRate=h}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 r(100),await this.connectWithResetStrategies(),await this.detectChip(),this.logger.debug(`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===C||this.chipFamily===F;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.debug(`${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 r(500),this.logger.debug(`${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===C&&(!0===this._isUsbJtagOrOtg||void 0===this._isUsbJtagOrOtg))}async resetInConsoleMode(){if(this._parent)return await this._parent.resetInConsoleMode();if(!this.isConsoleResetSupported())return this.logger.debug("Simple Console reset not supported for ESP32-S2 USB-JTAG/CDC - using exitConsoleMode to enter bootloader"),await this.exitConsoleMode(),void this.logger.debug("S2 now in bootloader mode - caller must do syncAndWdtReset on new port, then reconnect console");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}}async syncAndWdtReset(t){this._parent?await this._parent.syncAndWdtReset(t):(this.port=t,this.connected=!1,this.IS_STUB=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.logger.debug("Opening bootloader port at 115200..."),await this.port.open({baudRate:h}),this.connected=!0,this.currentBaudRate=h,this.readLoop(),await r(100),this.logger.debug("Syncing with bootloader ROM..."),await this.sync(),this.logger.debug("Bootloader sync OK, no stub"),this.logger.debug("Firing WDT reset..."),await this.rtcWdtResetChipSpecific(),this.logger.debug("WDT reset fired - device will boot to firmware"))}async drainInputBuffer(t=200){await r(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 r(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 r(gt),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s,a){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==a?void 0:a.chunkSize)?(n=a.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==a?void 0:a.blockSize)&&void 0!==(null==a?void 0:a.maxInFlight))n=a.blockSize,l=a.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=xi("<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 a;try{a=await this.readPacket(100)}catch(t){if(t instanceof mt){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 r(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(a&&a.length>0){const r=new Uint8Array(a),n=new Uint8Array(i.length+r.length);n.set(i),n.set(r,i.length),i=n;if(i.length>=e||i.length>=s+l){const e=xi("<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 mt))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 r(gt)}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 Ai extends Mi{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await St(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,ct)}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%o!==0)throw new Error(`Offset ${t} (0x${t.toString(16)}) is not aligned to flash sector size 4096 (0x${o.toString(16)})`);if(e%o!==0)throw new Error(`Size ${e} (0x${e.toString(16)}) is not aligned to flash sector size 4096 (0x${o.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=bt(ft,e),a=xi("<II",t,e);await this.checkCommand(209,a,0,s)}}const Ti=4096,Fi=[4096,2048,1024,512],Li=4096,zi=[4096,2048,1024,512],Pi=8192,Ni=[8192,4096],$i=256,Wi=256,ji=8192;function Gi(t){if(t.length<4096)return!1;let e=0;const i=256,s=Math.min(32,Math.floor(t.length/i));for(let a=0;a<s;a++){const s=a*i;if(s+i>t.length)break;const r=t.slice(s,s+i),n=r[0]|r[1]<<8;for(let t=0;t<r.length-10;t++)if(1===r[t]&&47===r[t+1]){let i=0;for(let e=t+1;e<Math.min(t+20,r.length);e++)if(r[e]>=32&&r[e]<127)i++;else if(0===r[e])break;if(i>=4){e+=5;break}}if(32768&n){const t=32767&n;t>0&&t<4096&&(e+=2)}}return e>=10}function Hi(t,e,i){const s=Ni;for(const a of s)for(let s=0;s<2;s++){const r=s*a,n=r+8;if(n+8>t.length)continue;if("littlefs"===String.fromCharCode(t[n],t[n+1],t[n+2],t[n+3],t[n+4],t[n+5],t[n+6],t[n+7])){const s=r+16,n=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;if(0!==n&&n>>>0!=4294967295){const s=r+24;if(s+4<=t.length){const r=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;if(r>0&&r<1e5){const t=r*a;if(t>0&&e+t<=i)return{start:e,end:e+t,size:t,page:256,block:a}}}return Ji(e,i,a)}}}if(Gi(t))return Ji(e,i,ji);if(t.length>=4){if(538182953===(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)){let s=!0;if(t.length>=16){let e=!0;for(let i=4;i<16;i++)if(255!==t[i]){e=!1;break}e&&(s=!1)}if(s)return Ji(e,i,ji)}}const a=[0,4096];for(const s of a){if(t.length<s+512)continue;if(43605===(t[s+510]|t[s+511]<<8)){const a=t[s+11]|t[s+12]<<8;if(![512,1024,2048,4096].includes(a))continue;let r=t[s+19]|t[s+20]<<8;if(0===r&&(r=t[s+32]|t[s+33]<<8|t[s+34]<<16|t[s+35]<<24),a>0&&r>0&&r<1e8){const t=r*a,n=e+s;if(t>0&&n+t<=i)return{start:n,end:n+t,size:t,page:a,block:a}}}}return null}function Ji(t,e,i){const s=e/1048576;if(s>=16){if(1048576===t)return{start:1048576,end:16752640,size:15704064,page:256,block:i};if(2097152===t)return{start:2097152,end:16752640,size:14655488,page:256,block:i}}if(s>=8){if(1048576===t)return{start:1048576,end:8364032,size:7315456,page:256,block:i};if(2097152===t)return{start:2097152,end:8364032,size:6266880,page:256,block:i}}if(s>=4){if(1048576===t)return{start:1048576,end:4169728,size:3121152,page:256,block:i};if(2097152===t)return{start:2097152,end:4169728,size:2072576,page:256,block:i};if(3145728===t)return{start:3145728,end:4169728,size:1024e3,page:256,block:i}}if(s>=2){if(1048576===t)return{start:1048576,end:2072576,size:1024e3,page:256,block:i};if(1572864===t)return{start:1572864,end:2072576,size:499712,page:256,block:i};if(1835008===t)return{start:1835008,end:2076672,size:241664,page:256,block:i};if(1966080===t)return{start:1966080,end:2076672,size:110592,page:256,block:i};if(2031616===t)return{start:2031616,end:2076672,size:45056,page:256,block:i}}if(s>=1){if(503808===t)return{start:503808,end:1028096,size:524288,page:256,block:i};if(765952===t)return{start:765952,end:1028096,size:262144,page:256,block:i};if(831488===t)return{start:831488,end:1028096,size:196608,page:256,block:i};if(864256===t)return{start:864256,end:1028096,size:163840,page:256,block:i};if(880640===t)return{start:880640,end:1028096,size:147456,page:256,block:i};if(897024===t)return{start:897024,end:1028096,size:131072,page:256,block:i};if(962560===t)return{start:962560,end:1028096,size:65536,page:256,block:i}}if(s>=.5){if(372736===t)return{start:372736,end:503808,size:131072,page:256,block:i};if(438272===t)return{start:438272,end:503808,size:65536,page:256,block:i};if(471040===t)return{start:471040,end:503808,size:32768,page:256,block:i}}return{start:t,end:e,size:e-t,page:256,block:i}}function Qi(t){return t>=16?[{start:1048576,end:16752640,size:15704064,page:256,block:8192},{start:2097152,end:16752640,size:14655488,page:256,block:8192}]:t>=8?[{start:1048576,end:8364032,size:7315456,page:256,block:8192},{start:2097152,end:8364032,size:6266880,page:256,block:8192}]:t>=4?[{start:2097152,end:4169728,size:2072576,page:256,block:8192},{start:1048576,end:4169728,size:3121152,page:256,block:8192},{start:3145728,end:4169728,size:1024e3,page:256,block:8192}]:t>=2?[{start:1048576,end:2072576,size:1024e3,page:256,block:8192},{start:1572864,end:2072576,size:499712,page:256,block:8192},{start:1835008,end:2076672,size:241664,page:256,block:8192},{start:1966080,end:2076672,size:110592,page:256,block:8192},{start:2031616,end:2076672,size:45056,page:256,block:8192}]:t>=1?[{start:897024,end:1028096,size:131072,page:256,block:8192},{start:503808,end:1028096,size:524288,page:256,block:8192},{start:765952,end:1028096,size:262144,page:256,block:8192},{start:831488,end:1028096,size:196608,page:256,block:8192},{start:864256,end:1028096,size:163840,page:256,block:8192},{start:880640,end:1028096,size:147456,page:256,block:8192},{start:962560,end:1028096,size:65536,page:256,block:8192}]:t>=.5?[{start:372736,end:503808,size:131072,page:256,block:8192},{start:438272,end:503808,size:65536,page:256,block:8192},{start:471040,end:503808,size:32768,page:256,block:8192}]:[]}var Vi;function Zi(t){return 1!==t.type?Vi.UNKNOWN:129===t.subtype?Vi.FATFS:Vi.UNKNOWN}function Xi(t,e){if(t.length<512)return Vi.UNKNOWN;const i=(null==e?void 0:e.toUpperCase().includes("ESP8266"))?Ni:Fi;for(const e of i)for(let i=0;i<2;i++){const s=i*e;if(s+20>t.length)continue;const a=s+8;if(a+8<=t.length){if("littlefs"===String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3],t[a+4],t[a+5],t[a+6],t[a+7])){const e=s+16,i=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24;if(0!==i&&i>>>0!=4294967295)return Vi.LITTLEFS}}}const s=[0,4096];for(const e of s){if(t.length<e+512)continue;if(43605===(t[e+510]|t[e+511]<<8)){const i=t.length>=e+62?String.fromCharCode(t[e+54],t[e+55],t[e+56],t[e+57],t[e+58]):"",s=t.length>=e+90?String.fromCharCode(t[e+82],t[e+83],t[e+84],t[e+85],t[e+86]):"";if(i.startsWith("FAT")||s.startsWith("FAT"))return Vi.FATFS}}if(t.length>=4){if(538182953===(t[0]|t[1]<<8|t[2]<<16|t[3]<<24))return Vi.SPIFFS}return Gi(t)?Vi.SPIFFS:Vi.UNKNOWN}function Ki(t,e){const i=null==e?void 0:e.toUpperCase().includes("ESP8266");switch(t){case Vi.FATFS:return 4096;case Vi.LITTLEFS:default:return i?Pi:4096}}function qi(t,e){const i=null==e?void 0:e.toUpperCase().includes("ESP8266");switch(t){case Vi.FATFS:return zi;case Vi.LITTLEFS:return i?Ni:Fi;default:return i?Ni:[4096,2048,1024,512]}}!function(t){t.UNKNOWN="unknown",t.LITTLEFS="littlefs",t.FATFS="fatfs",t.SPIFFS="spiffs"}(Vi||(Vi={}));const Yi={0:"app",1:"data"},ts={0:"factory",16:"ota_0",17:"ota_1",18:"ota_2",19:"ota_3",20:"ota_4",21:"ota_5",22:"ota_6",23:"ota_7",24:"ota_8",25:"ota_9",26:"ota_10",27:"ota_11",28:"ota_12",29:"ota_13",30:"ota_14",31:"ota_15",32:"test"},es={0:"ota",1:"phy",2:"nvs",3:"coredump",4:"nvs_keys",5:"efuse",128:"esphttpd",129:"fat",130:"spiffs",131:"littlefs"};function is(t){if(t.length<32)return null;if(20650!==(65535&(t[0]|t[1]<<8)))return null;const e=t[2],i=t[3],s=t[4]|t[5]<<8|t[6]<<16|t[7]<<24,a=t[8]|t[9]<<8|t[10]<<16|t[11]<<24;let r="";for(let e=12;e<28&&0!==t[e];e++)r+=String.fromCharCode(t[e]);const n=t[28]|t[29]<<8|t[30]<<16|t[31]<<24,o=Yi[e]||`unknown(0x${e.toString(16)})`;let h="";return h=0===e?ts[i]||`unknown(0x${i.toString(16)})`:1===e?es[i]||`unknown(0x${i.toString(16)})`:`0x${i.toString(16)}`,{name:r,type:e,subtype:i,offset:s,size:a,flags:n,typeName:o,subtypeName:h}}function ss(t){const e=[];for(let i=0;i<t.length;i+=32){const s=is(t.slice(i,i+32));if(null===s)break;e.push(s)}return e}function as(){return 32768}function rs(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}class ns{constructor(t){var e,i,s,a,r,n,o,h,l,d,c,u;if(t.blockSize%t.pageSize!==0)throw new Error("block size should be a multiple of page size");this.pageSize=t.pageSize,this.blockSize=t.blockSize,this.objIdLen=null!==(e=t.objIdLen)&&void 0!==e?e:2,this.spanIxLen=null!==(i=t.spanIxLen)&&void 0!==i?i:2,this.packed=null===(s=t.packed)||void 0===s||s,this.aligned=null===(a=t.aligned)||void 0===a||a,this.objNameLen=null!==(r=t.objNameLen)&&void 0!==r?r:32,this.metaLen=null!==(n=t.metaLen)&&void 0!==n?n:4,this.pageIxLen=null!==(o=t.pageIxLen)&&void 0!==o?o:2,this.blockIxLen=null!==(h=t.blockIxLen)&&void 0!==h?h:2,this.endianness=null!==(l=t.endianness)&&void 0!==l?l:"little",this.useMagic=null===(d=t.useMagic)||void 0===d||d,this.useMagicLen=null===(c=t.useMagicLen)||void 0===c||c,this.alignedObjIxTables=null!==(u=t.alignedObjIxTables)&&void 0!==u&&u,this.PAGES_PER_BLOCK=Math.floor(this.blockSize/this.pageSize),this.OBJ_LU_PAGES_PER_BLOCK=Math.ceil(this.blockSize/this.pageSize*this.objIdLen/this.pageSize),this.OBJ_USABLE_PAGES_PER_BLOCK=this.PAGES_PER_BLOCK-this.OBJ_LU_PAGES_PER_BLOCK,this.OBJ_LU_PAGES_OBJ_IDS_LIM=Math.floor(this.pageSize/this.objIdLen),this.OBJ_DATA_PAGE_HEADER_LEN=this.objIdLen+this.spanIxLen+1;const g=4-(this.OBJ_DATA_PAGE_HEADER_LEN%4==0?4:this.OBJ_DATA_PAGE_HEADER_LEN%4);this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED=this.OBJ_DATA_PAGE_HEADER_LEN+g,this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD=g,this.OBJ_DATA_PAGE_CONTENT_LEN=this.pageSize-this.OBJ_DATA_PAGE_HEADER_LEN,this.OBJ_INDEX_PAGES_HEADER_LEN=this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED+4+1+this.objNameLen+this.metaLen,this.alignedObjIxTables?(this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED=this.OBJ_INDEX_PAGES_HEADER_LEN+2-1&-2,this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD=this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED-this.OBJ_INDEX_PAGES_HEADER_LEN):(this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED=this.OBJ_INDEX_PAGES_HEADER_LEN,this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD=0),this.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM=Math.floor((this.pageSize-this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED)/this.blockIxLen),this.OBJ_INDEX_PAGES_OBJ_IDS_LIM=Math.floor((this.pageSize-this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED)/this.blockIxLen)}}class os extends Error{constructor(t="SPIFFS is full"){super(t),this.name="SpiffsFullError"}}class hs{constructor(t,e){this.buildConfig=e,this.bix=t}pack(t,...e){const i=new ArrayBuffer(this.calcSize(t)),s=new DataView(i);let a=0;for(let i=0;i<t.length;i++){const r=t[i],n=e[i];switch(r){case"B":s.setUint8(a,n),a+=1;break;case"H":"little"===this.buildConfig.endianness?s.setUint16(a,n,!0):s.setUint16(a,n,!1),a+=2;break;case"I":"little"===this.buildConfig.endianness?s.setUint32(a,n,!0):s.setUint32(a,n,!1),a+=4}}return new Uint8Array(i)}unpack(t,e,i=0){const s=new DataView(e.buffer,e.byteOffset+i),a=[];let r=0;for(const e of t)switch(e){case"B":a.push(s.getUint8(r)),r+=1;break;case"H":a.push("little"===this.buildConfig.endianness?s.getUint16(r,!0):s.getUint16(r,!1)),r+=2;break;case"I":a.push("little"===this.buildConfig.endianness?s.getUint32(r,!0):s.getUint32(r,!1)),r+=4}return a}calcSize(t){let e=0;for(const i of t)switch(i){case"B":e+=1;break;case"H":e+=2;break;case"I":e+=4}return e}}class ls extends hs{constructor(t,e){super(0,e),this.objId=t}getObjId(){return this.objId}}class ds extends hs{constructor(t,e){super(t,e),this.objIdsLimit=this.buildConfig.OBJ_LU_PAGES_OBJ_IDS_LIM,this.objIds=[]}calcMagic(t){let e=538182953^this.buildConfig.pageSize;this.buildConfig.useMagicLen&&(e^=t-this.bix);return e&(1<<8*this.buildConfig.objIdLen)-1}registerPage(t){if(this.objIdsLimit<=0)throw new os;const e=t instanceof cs?"index":"data";this.objIds.push([t.getObjId(),e]),this.objIdsLimit--}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);let e=0;for(const[i,s]of this.objIds){let a=i;"index"===s&&(a^=1<<8*this.buildConfig.objIdLen-1);const r=this.pack(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I",a);t.set(r,e),e+=r.length}return t}magicfy(t){const e=this.objIdsLimit,i=(1<<8*this.buildConfig.objIdLen)-1;if(e>=2)for(let s=0;s<e;s++){if(s===e-2){this.objIds.push([this.calcMagic(t),"data"]);break}this.objIds.push([i,"data"]),this.objIdsLimit--}}}class cs extends ls{constructor(t,e,i,s,a){super(t,a),this.spanIx=e,this.name=s,this.size=i,0===this.spanIx?this.pagesLim=this.buildConfig.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM:this.pagesLim=this.buildConfig.OBJ_INDEX_PAGES_OBJ_IDS_LIM,this.pages=[]}registerPage(t){if(this.pagesLim<=0)throw new os;this.pages.push(t.offset),this.pagesLim--}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);const e=this.objId^1<<8*this.buildConfig.objIdLen-1,i=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B";let s=0;const a=this.pack(i,e,this.spanIx,248);if(t.set(a,s),s+=a.length,s+=this.buildConfig.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD,0===this.spanIx){const e=this.pack("IB",this.size,1);t.set(e,s),s+=e.length;const i=(new TextEncoder).encode(this.name),a=Math.min(i.length,this.buildConfig.objNameLen);t.set(i.slice(0,a),s);for(let e=a;e<this.buildConfig.objNameLen;e++)t[s+e]=0;s+=this.buildConfig.objNameLen+this.buildConfig.metaLen+this.buildConfig.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD}for(const e of this.pages){const i=Math.floor(e/this.buildConfig.pageSize),a=this.pack(1===this.buildConfig.pageIxLen?"B":2===this.buildConfig.pageIxLen?"H":"I",i);t.set(a,s),s+=a.length}return t}}class us extends ls{constructor(t,e,i,s,a){super(e,a),this.offset=t,this.spanIx=i,this.contents=s}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);const e=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B",i=this.pack(e,this.objId,this.spanIx,252);return t.set(i,0),t.set(this.contents,i.length),t}}class gs{constructor(t,e){this.buildConfig=e,this.offset=t*this.buildConfig.blockSize,this.remainingPages=this.buildConfig.OBJ_USABLE_PAGES_PER_BLOCK,this.pages=[],this.bix=t,this.luPages=[];for(let t=0;t<this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;t++){const t=new ds(this.bix,this.buildConfig);this.luPages.push(t)}this.pages.push(...this.luPages),this.luPageIter=this.luPages[Symbol.iterator](),this.luPage=this.luPageIter.next().value||null,this.curObjIndexSpanIx=0,this.curObjDataSpanIx=0,this.curObjId=0,this.curObjIdxPage=null}reset(){this.curObjIndexSpanIx=0,this.curObjDataSpanIx=0,this.curObjId=0,this.curObjIdxPage=null}registerPage(t){if(t instanceof us){if(!this.curObjIdxPage)throw new Error("No current object index page");this.curObjIdxPage.registerPage(t)}try{if(!this.luPage)throw new os;this.luPage.registerPage(t)}catch(e){if(!(e instanceof os))throw e;{const e=this.luPageIter.next();if(e.done)throw new Error("Invalid attempt to add page to a block when there is no more space in lookup");this.luPage=e.value,this.luPage.registerPage(t)}}this.pages.push(t)}beginObj(t,e,i,s=0,a=0){if(this.remainingPages<=0)throw new os;this.reset(),this.curObjId=t,this.curObjIndexSpanIx=s,this.curObjDataSpanIx=a;const r=new cs(t,this.curObjIndexSpanIx,e,i,this.buildConfig);this.registerPage(r),this.curObjIdxPage=r,this.remainingPages--,this.curObjIndexSpanIx++}updateObj(t){if(this.remainingPages<=0)throw new os;const e=new us(this.offset+this.pages.length*this.buildConfig.pageSize,this.curObjId,this.curObjDataSpanIx,t,this.buildConfig);this.registerPage(e),this.curObjDataSpanIx++,this.remainingPages--}endObj(){this.reset()}isFull(){return this.remainingPages<=0}toBinary(t){const e=new Uint8Array(this.buildConfig.blockSize);e.fill(255);let i=0;if(this.buildConfig.useMagic)for(let s=0;s<this.pages.length;s++){const a=this.pages[s];s===this.buildConfig.OBJ_LU_PAGES_PER_BLOCK-1&&a instanceof ds&&a.magicfy(t);const r=a.toBinary();e.set(r,i),i+=r.length}else for(const t of this.pages){const s=t.toBinary();e.set(s,i),i+=s.length}return e}get currentObjIndexSpanIx(){return this.curObjIndexSpanIx}get currentObjDataSpanIx(){return this.curObjDataSpanIx}get currentObjId(){return this.curObjId}get currentObjIdxPage(){return this.curObjIdxPage}set currentObjId(t){this.curObjId=t}set currentObjIdxPage(t){this.curObjIdxPage=t}set currentObjDataSpanIx(t){this.curObjDataSpanIx=t}set currentObjIndexSpanIx(t){this.curObjIndexSpanIx=t}}class fs{constructor(t,e){if(t%e.blockSize!==0)throw new Error("image size should be a multiple of block size");this.imgSize=t,this.buildConfig=e,this.blocks=[],this.blocksLim=Math.floor(this.imgSize/this.buildConfig.blockSize),this.remainingBlocks=this.blocksLim,this.curObjId=1}createBlock(){if(this.isFull())throw new os("the image size has been exceeded");const t=new gs(this.blocks.length,this.buildConfig);return this.blocks.push(t),this.remainingBlocks--,t}isFull(){return this.remainingBlocks<=0}createFile(t,e){if(t.length>this.buildConfig.objNameLen)throw new Error(`object name '${t}' too long`);const i=t;let s=0;try{this.blocks[this.blocks.length-1].beginObj(this.curObjId,e.length,i)}catch{this.createBlock().beginObj(this.curObjId,e.length,i)}for(;s<e.length;){const t=Math.min(this.buildConfig.OBJ_DATA_PAGE_CONTENT_LEN,e.length-s),a=e.slice(s,s+t);try{const t=this.blocks[this.blocks.length-1];try{t.updateObj(a)}catch(s){if(s instanceof os){if(t.isFull())throw s;t.beginObj(this.curObjId,e.length,i,t.currentObjIndexSpanIx,t.currentObjDataSpanIx);continue}throw s}}catch(t){if(t instanceof os){const t=this.blocks[this.blocks.length-1],e=this.createBlock();e.currentObjId=t.currentObjId,e.currentObjIdxPage=t.currentObjIdxPage,e.currentObjDataSpanIx=t.currentObjDataSpanIx,e.currentObjIndexSpanIx=t.currentObjIndexSpanIx;continue}throw t}s+=t}this.blocks[this.blocks.length-1].endObj(),this.curObjId++}toBinary(){const t=[];for(const e of this.blocks)t.push(e.toBinary(this.blocksLim));let e=this.blocks.length,i=this.remainingBlocks;if(this.buildConfig.useMagic)for(;i>0;){const s=new gs(e,this.buildConfig);t.push(s.toBinary(this.blocksLim)),i--,e++}else{const e=this.imgSize-t.length*this.buildConfig.blockSize;if(e>0){const i=new Uint8Array(e);i.fill(255),t.push(i)}}const s=t.reduce((t,e)=>t+e.length,0),a=new Uint8Array(s);let r=0;for(const e of t)a.set(e,r),r+=e.length;return a}listFiles(){throw new Error("listFiles requires fromBinary to be called first")}readFile(){throw new Error("readFile requires fromBinary to be called first")}deleteFile(){throw new Error("deleteFile not yet implemented - requires filesystem recreation")}}class _s{constructor(t,e){this.imageData=t,this.buildConfig=e,this.filesMap=new Map}unpack(t,e,i=0){const s=new DataView(e.buffer,e.byteOffset+i),a=[];let r=0;for(const e of t)switch(e){case"B":a.push(s.getUint8(r)),r+=1;break;case"H":a.push("little"===this.buildConfig.endianness?s.getUint16(r,!0):s.getUint16(r,!1)),r+=2;break;case"I":a.push("little"===this.buildConfig.endianness?s.getUint32(r,!0):s.getUint32(r,!1)),r+=4}return a}parse(){const t=Math.floor(this.imageData.length/this.buildConfig.blockSize);for(let e=0;e<t;e++){const t=e*this.buildConfig.blockSize,i=this.imageData.slice(t,t+this.buildConfig.blockSize);this.parseBlock(i)}}parseBlock(t){for(let e=0;e<this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;e++){const i=e*this.buildConfig.pageSize,s=t.slice(i,i+this.buildConfig.pageSize);for(let t=0;t<s.length&&!(t+this.buildConfig.objIdLen>s.length);t+=this.buildConfig.objIdLen){const e=s.slice(t,t+this.buildConfig.objIdLen),[i]=this.unpack(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I",e);if(i===(1<<8*this.buildConfig.objIdLen)-1)continue;const a=!!(i&1<<8*this.buildConfig.objIdLen-1),r=i&~(1<<8*this.buildConfig.objIdLen-1);a&&!this.filesMap.has(r)&&this.filesMap.set(r,{name:null,size:0,dataPages:[]})}}for(let e=this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;e<this.buildConfig.PAGES_PER_BLOCK;e++){const i=e*this.buildConfig.pageSize,s=t.slice(i,i+this.buildConfig.pageSize);this.parsePage(s)}}parsePage(t){const e=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B",i=this.buildConfig.objIdLen+this.buildConfig.spanIxLen+1;if(t.length<i)return;const[s,a,r]=this.unpack(e,t);if(s===(1<<8*this.buildConfig.objIdLen)-1)return;const n=!!(s&1<<8*this.buildConfig.objIdLen-1),o=s&~(1<<8*this.buildConfig.objIdLen-1);if(n&&248===r)this.filesMap.has(o)||this.filesMap.set(o,{name:null,size:0,dataPages:[]}),0===a&&this.parseIndexPage(t,i,o);else if(!n&&252===r&&this.filesMap.has(o)){const e=i,s=t.slice(e,e+this.buildConfig.OBJ_DATA_PAGE_CONTENT_LEN);this.filesMap.get(o).dataPages.push([a,s])}}parseIndexPage(t,e,i){let s=e+this.buildConfig.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD;if(s+5<=t.length){const[e]=this.unpack("IB",t,s);s+=5;const a=s+this.buildConfig.objNameLen;if(a<=t.length){const r=t.slice(s,a),n=r.indexOf(0),o=-1!==n?r.slice(0,n):r,h=(new TextDecoder).decode(o),l=this.filesMap.get(i);l.name=h,l.size=e}}}listFiles(){const t=[];for(const[,e]of this.filesMap){if(null===e.name)continue;e.dataPages.sort((t,e)=>t[0]-e[0]);const i=[];let s=0;for(const[,t]of e.dataPages){const a=e.size-s;if(a<=0)break;const r=Math.min(t.length,a);i.push(t.slice(0,r)),s+=r}const a=new Uint8Array(s);let r=0;for(const t of i)a.set(t,r),r+=t.length;t.push({name:e.name,size:e.size,data:a})}return t}readFile(t){const e=this.listFiles().find(e=>e.name===t||e.name==="/"+t);return e?e.data:null}}const ps={pageSize:256,blockSize:4096,objNameLen:32,metaLen:4,useMagic:!0,useMagicLen:!0,alignedObjIxTables:!1},bs=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:h}),new Mi(e,t)},ws=async(t,e)=>{if(!t)throw new Error("Port is required");return t.readable&&t.writable||await t.open({baudRate:h}),new Mi(t,e)};export{ct as CHIP_ERASE_TIMEOUT,v as CHIP_FAMILY_ESP32,k as CHIP_FAMILY_ESP32C2,U as CHIP_FAMILY_ESP32C3,D as CHIP_FAMILY_ESP32C5,x as CHIP_FAMILY_ESP32C6,O as CHIP_FAMILY_ESP32C61,M as CHIP_FAMILY_ESP32H2,T as CHIP_FAMILY_ESP32H21,A as CHIP_FAMILY_ESP32H4,F as CHIP_FAMILY_ESP32P4,C as CHIP_FAMILY_ESP32S2,E as CHIP_FAMILY_ESP32S3,L as CHIP_FAMILY_ESP32S31,R as CHIP_FAMILY_ESP8266,ps as DEFAULT_SPIFFS_CONFIG,dt as DEFAULT_TIMEOUT,ft as ERASE_REGION_TIMEOUT_PER_MB,Pi as ESP8266_LITTLEFS_BLOCK_SIZE,Ni as ESP8266_LITTLEFS_BLOCK_SIZE_CANDIDATES,$i as ESP8266_LITTLEFS_PAGE_SIZE,ji as ESP8266_SPIFFS_BLOCK_SIZE,Wi as ESP8266_SPIFFS_PAGE_SIZE,Mi as ESPLoader,tt as ESP_CHANGE_BAUDRATE,st as ESP_CHECKSUM_MAGIC,Z as ESP_ERASE_FLASH,X as ESP_ERASE_REGION,N as ESP_FLASH_BEGIN,$ as ESP_FLASH_DATA,at as ESP_FLASH_DEFL_BEGIN,rt as ESP_FLASH_DEFL_DATA,nt as ESP_FLASH_DEFL_END,W as ESP_FLASH_END,it as ESP_GET_SECURITY_INFO,j as ESP_MEM_BEGIN,H as ESP_MEM_DATA,G as ESP_MEM_END,lt as ESP_RAM_BLOCK,K as ESP_READ_FLASH,V as ESP_READ_REG,Y as ESP_SPI_ATTACH,et as ESP_SPI_FLASH_MD5,q as ESP_SPI_SET_PARAMS,J as ESP_SYNC,Q as ESP_WRITE_REG,zi as FATFS_BLOCK_SIZE_CANDIDATES,Li as FATFS_DEFAULT_BLOCK_SIZE,pt as FLASH_READ_TIMEOUT,Vi as FilesystemType,Fi as LITTLEFS_BLOCK_SIZE_CANDIDATES,Ti as LITTLEFS_DEFAULT_BLOCK_SIZE,ut as MAX_TIMEOUT,_t as MEM_END_ROM_TIMEOUT,ot as ROM_INVALID_RECV_MSG,gt as SYNC_TIMEOUT,ns as SpiffsBuildConfig,fs as SpiffsFS,_s as SpiffsReader,ht as USB_RAM_BLOCK,bs as connect,ws as connectWithPort,Xi as detectFilesystemFromImage,Zi as detectFilesystemType,a as formatMacAddr,rs as formatSize,qi as getBlockSizeCandidates,Ki as getDefaultBlockSize,Qi as getESP8266FilesystemLayout,as as getPartitionTableOffset,i as hexFormatter,ss as parsePartitionTable,Hi as scanESP8266Filesystem,r as sleep,s as toHex};
Binary file
Binary file